3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Test\Util\Database;
28 * This class extends native PDO one but allow nested transactions
29 * by using the SQL statements `SAVEPOINT', 'RELEASE SAVEPOINT' AND 'ROLLBACK SAVEPOINT'
31 class ExtendedPDO extends PDO
34 * @var array Database drivers that support SAVEPOINT * statements.
36 protected static $_supportedDrivers = array("pgsql", "mysql");
39 * @var int the current transaction depth
41 protected $_transactionDepth = 0;
46 public function getTransactionDepth()
48 return $this->_transactionDepth;
52 * Test if database driver support savepoints
56 protected function hasSavepoint()
58 return in_array($this->getAttribute(PDO::ATTR_DRIVER_NAME),
59 self::$_supportedDrivers);
68 public function beginTransaction()
70 if($this->_transactionDepth == 0 || !$this->hasSavepoint()) {
71 parent::beginTransaction();
73 $this->exec("SAVEPOINT LEVEL{$this->_transactionDepth}");
76 $this->_transactionDepth++;
80 * Commit current transaction
84 public function commit()
86 $this->_transactionDepth--;
88 if($this->_transactionDepth == 0 || !$this->hasSavepoint()) {
91 $this->exec("RELEASE SAVEPOINT LEVEL{$this->_transactionDepth}");
96 * Rollback current transaction,
98 * @throws PDOException if there is no transaction started
101 public function rollBack()
104 if ($this->_transactionDepth == 0) {
105 throw new PDOException('Rollback error : There is no transaction started');
108 $this->_transactionDepth--;
110 if($this->_transactionDepth == 0 || !$this->hasSavepoint()) {
113 $this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->_transactionDepth}");