3 * @copyright Copyright (C) 2010-2022, the Friendica project
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 = ['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();
72 $this->_transactionDepth = 0;
74 $this->exec("SAVEPOINT LEVEL{$this->_transactionDepth}");
77 $this->_transactionDepth++;
81 * Commit current transaction
85 public function commit(): bool
87 // We don't want to "really" commit something, so skip the most outer hierarchy
88 if ($this->_transactionDepth <= 1 && $this->hasSavepoint()) {
89 $this->_transactionDepth = $this->_transactionDepth <= 0 ? 0 : 1;
93 $this->_transactionDepth--;
95 return $this->exec("RELEASE SAVEPOINT LEVEL{$this->_transactionDepth}");
99 * Rollback current transaction,
101 * @throws PDOException if there is no transaction started
102 * @return bool Whether rollback was successful
104 public function rollback(): bool
106 $this->_transactionDepth--;
108 if ($this->_transactionDepth <= 0 || !$this->hasSavepoint()) {
109 $this->_transactionDepth = 0;
111 return parent::rollBack();
112 } catch (PDOException $e) {
113 // this shouldn't happen, but it does ...
116 return $this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->_transactionDepth}");