-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTransactionPDO.php
73 lines (61 loc) · 1.7 KB
/
TransactionPDO.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* License: GNU General Public License v3.
* http://www.gnu.org/licenses/gpl-3.0-standalone.html
*/
class TransactionPDO extends PDO {
// Database drivers that support SAVEPOINTs.
protected static $savepointTransactions = array("pgsql", "mysql");
// The current transaction level.
protected $transLevel = 0;
protected function nestable() {
return in_array($this->getAttribute(PDO::ATTR_DRIVER_NAME),
self::$savepointTransactions);
}
function transaction($call) {
if($this->beginTransaction()) {
try {
$ret = call_user_func($call);
} catch(Exception $e) {
$this->rollBack();
throw $e;
}
if($ret) {
if(!$this->commit()) throw new Exception("Transaction was not committed.");
} else {
$this->rollBack();
}
return $ret;
} else {
throw new Exception("Transaction was not started.");
}
}
public function beginTransaction() {
if(!$this->nestable() || $this->transLevel == 0) {
$ret = parent::beginTransaction();
$this->transLevel++;
return $ret;
} else {
$this->exec("SAVEPOINT LEVEL{$this->transLevel}");
$this->transLevel++;
return true;
}
}
public function commit() {
$this->transLevel--;
if(!$this->nestable() || $this->transLevel == 0) {
return parent::commit();
} else {
$this->exec("RELEASE SAVEPOINT LEVEL{$this->transLevel}");
return true;
}
}
public function rollBack() {
$this->transLevel--;
if(!$this->nestable() || $this->transLevel == 0) {
return parent::rollBack();
} else {
$this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->transLevel}");
return true;
}
}
}