3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
27 * Manage savepoints within a transaction
31 class SavepointPostgres
{
32 /** @var DatabasePostgres Establish a savepoint within a transaction */
34 /** @var LoggerInterface */
42 * @param DatabasePostgres $dbw
44 * @param LoggerInterface $logger
46 public function __construct( DatabasePostgres
$dbw, $id, LoggerInterface
$logger ) {
48 $this->logger
= $logger;
50 $this->didbegin
= false;
51 /* If we are not in a transaction, we need to be for savepoint trickery */
52 if ( !$dbw->trxLevel() ) {
53 $dbw->begin( __CLASS__
, DatabasePostgres
::TRANSACTION_INTERNAL
);
54 $this->didbegin
= true;
58 public function __destruct() {
59 if ( $this->didbegin
) {
60 $this->dbw
->rollback();
61 $this->didbegin
= false;
65 public function commit() {
66 if ( $this->didbegin
) {
67 $this->dbw
->commit( __CLASS__
, DatabasePostgres
::FLUSHING_INTERNAL
);
68 $this->didbegin
= false;
72 protected function query( $keyword, $msg_ok, $msg_failed ) {
73 if ( $this->dbw
->doQuery( $keyword . " " . $this->id
) !== false ) {
74 $this->logger
->debug( sprintf( $msg_ok, $this->id
) );
76 $this->logger
->debug( sprintf( $msg_failed, $this->id
) );
80 public function savepoint() {
81 $this->query( "SAVEPOINT",
82 "Transaction state: savepoint \"%s\" established.\n",
83 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
87 public function release() {
88 $this->query( "RELEASE",
89 "Transaction state: savepoint \"%s\" released.\n",
90 "Transaction state: release of savepoint \"%s\" FAILED.\n"
94 public function rollback() {
95 $this->query( "ROLLBACK TO",
96 "Transaction state: savepoint \"%s\" rolled back.\n",
97 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
101 public function __toString() {
102 return (string)$this->id
;