Skip to content

Commit c7d6963

Browse files
authored
Keep the user transaction active after a failed statement (#536)
1 parent 57eb90d commit c7d6963

3 files changed

Lines changed: 279 additions & 18 deletions

File tree

‎packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php‎

Lines changed: 65 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1210,16 +1210,18 @@ public function query( string $query, ?int $fetch_mode = null, ...$fetch_mode_ar
12101210
$this->error_info = array( '00000', null, null );
12111211
return $stmt;
12121212
} catch ( Throwable $e ) {
1213-
// MySQL error 1305 reports a missing savepoint without ending the transaction.
1214-
$preserves_transaction = $e instanceof WP_MySQL_On_SQLite_Exception
1215-
&& 1305 === ( $e->errorInfo[1] ?? null );
1216-
if ( ! $preserves_transaction ) {
1217-
try {
1218-
$this->rollback_user_transaction();
1219-
$this->table_lock_active = false;
1220-
} catch ( Throwable $rollback_exception ) {
1221-
// Ignore rollback errors.
1222-
}
1213+
/*
1214+
* Undo the failed statement. Like MySQL, keep an active user
1215+
* transaction open, so the caller can decide whether to commit
1216+
* or roll back the rest of it.
1217+
*/
1218+
try {
1219+
$this->rollback_wrapper_transaction();
1220+
} catch ( Throwable $rollback_exception ) {
1221+
// Ignore rollback errors.
1222+
}
1223+
if ( ! $this->inTransaction() ) {
1224+
$this->table_lock_active = false;
12231225
}
12241226
if ( $e instanceof WP_SQLite_Information_Schema_Exception ) {
12251227
$e = $this->convert_information_schema_exception( $e );
@@ -1396,7 +1398,12 @@ public function commit(): bool {
13961398
throw $this->new_driver_exception( 'There is no active transaction' );
13971399
}
13981400
$this->flush();
1399-
$this->commit_user_transaction();
1401+
1402+
// Unlike a COMMIT statement, PDO::commit() doesn't roll back on failure,
1403+
// so the caller can still call PDO::rollBack(), as with PDO MySQL.
1404+
$this->connection->query( 'COMMIT' );
1405+
$this->in_transaction = false;
1406+
$this->savepoint_names = array();
14001407
return true;
14011408
}
14021409

@@ -2095,6 +2102,33 @@ private function commit_wrapper_transaction(): void {
20952102
$this->in_transaction = $in_transaction;
20962103
}
20972104

2105+
/**
2106+
* Roll back a wrapper transaction.
2107+
*
2108+
* This undoes all changes of a failed statement. When the wrapper is
2109+
* a savepoint, the user transaction around it stays active.
2110+
*/
2111+
private function rollback_wrapper_transaction(): void {
2112+
if ( 'transaction' === $this->wrapper_transaction_type ) {
2113+
$this->rollback_user_transaction();
2114+
} elseif ( 'savepoint' === $this->wrapper_transaction_type ) {
2115+
$savepoint_name = $this->get_internal_savepoint_name( 'wrapper' );
2116+
try {
2117+
$this->connection->query( sprintf( 'ROLLBACK TO SAVEPOINT %s', $savepoint_name ) );
2118+
} catch ( PDOException $e ) {
2119+
/*
2120+
* Some SQLite errors roll back the whole transaction automatically,
2121+
* which also removes the savepoint. In that case, end the transaction.
2122+
*
2123+
* @see https://www.sqlite.org/lang_transaction.html#response_to_errors_within_a_transaction
2124+
*/
2125+
$this->rollback_user_transaction();
2126+
return;
2127+
}
2128+
$this->connection->query( sprintf( 'RELEASE SAVEPOINT %s', $savepoint_name ) );
2129+
}
2130+
}
2131+
20982132
/**
20992133
* Execute the "BEGIN" or "START TRANSACTION" MySQL statement in SQLite.
21002134
*/
@@ -2127,7 +2161,17 @@ private function commit_user_transaction(): void {
21272161
if ( ! $this->inTransaction() ) {
21282162
return;
21292163
}
2130-
$this->connection->query( 'COMMIT' );
2164+
try {
2165+
$this->connection->query( 'COMMIT' );
2166+
} catch ( PDOException $e ) {
2167+
// Like MySQL, roll back a transaction that fails to commit.
2168+
try {
2169+
$this->rollback_user_transaction();
2170+
} catch ( PDOException $rollback_exception ) {
2171+
// SQLite has already rolled back the transaction.
2172+
}
2173+
throw $e;
2174+
}
21312175
$this->in_transaction = false;
21322176
$this->savepoint_names = array();
21332177
}
@@ -2136,13 +2180,16 @@ private function commit_user_transaction(): void {
21362180
* Execute the "ROLLBACK" MySQL statement in SQLite.
21372181
*/
21382182
private function rollback_user_transaction(): void {
2139-
// MySQL doesn't throw an error if there is no active transaction.
2140-
if ( ! $this->inTransaction() ) {
2141-
return;
2183+
try {
2184+
// MySQL doesn't throw an error if there is no active transaction.
2185+
if ( $this->inTransaction() ) {
2186+
$this->connection->query( 'ROLLBACK' );
2187+
}
2188+
} finally {
2189+
// A ROLLBACK always ends the transaction, even when it fails.
2190+
$this->in_transaction = false;
2191+
$this->savepoint_names = array();
21422192
}
2143-
$this->connection->query( 'ROLLBACK' );
2144-
$this->in_transaction = false;
2145-
$this->savepoint_names = array();
21462193
}
21472194

21482195
/**

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_PDO_API_Tests.php‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,6 +1003,43 @@ public function test_rollback_method_as_first_transaction_on_connection(): void
10031003
$this->assertSame( 0, $this->driver->exec( 'CREATE TABLE t (id INT)' ) );
10041004
}
10051005

1006+
public function test_failed_query_keeps_transaction_active(): void {
1007+
$this->driver->exec( 'CREATE TABLE t (id INT PRIMARY KEY)' );
1008+
$this->driver->beginTransaction();
1009+
$this->driver->exec( 'INSERT INTO t VALUES (1)' );
1010+
try {
1011+
$this->driver->exec( 'INSERT INTO t VALUES (1)' );
1012+
$this->fail( 'An exception was expected, but none was thrown.' );
1013+
} catch ( PDOException $e ) {
1014+
$this->assertSame( '23000', $e->getCode() );
1015+
}
1016+
1017+
$this->assertTrue( $this->driver->inTransaction() );
1018+
$this->assertTrue( $this->driver->commit() );
1019+
$this->assertSame( array( '1' ), $this->driver->query( 'SELECT id FROM t' )->fetchAll( PDO::FETCH_COLUMN ) );
1020+
}
1021+
1022+
public function test_failed_commit_keeps_transaction_active(): void {
1023+
$this->driver->exec( 'CREATE TABLE p (id INT PRIMARY KEY)' );
1024+
$this->driver->exec( 'CREATE TABLE c (id INT PRIMARY KEY, p_id INT, FOREIGN KEY (p_id) REFERENCES p (id))' );
1025+
$this->driver->beginTransaction();
1026+
1027+
// Make the commit fail by deferring a foreign key check to it.
1028+
$this->driver->get_sqlite_pdo()->exec( 'PRAGMA defer_foreign_keys = ON' );
1029+
$this->driver->exec( 'INSERT INTO c VALUES (1, 1)' );
1030+
try {
1031+
$this->driver->commit();
1032+
$this->fail( 'An exception was expected, but none was thrown.' );
1033+
} catch ( PDOException $e ) {
1034+
$this->assertStringContainsString( 'FOREIGN KEY constraint failed', $e->getMessage() );
1035+
}
1036+
1037+
// Like PDO MySQL, the transaction is still active, so it can be rolled back.
1038+
$this->assertTrue( $this->driver->inTransaction() );
1039+
$this->assertTrue( $this->driver->rollBack() );
1040+
$this->assertSame( array(), $this->driver->query( 'SELECT id FROM c' )->fetchAll( PDO::FETCH_COLUMN ) );
1041+
}
1042+
10061043
public function test_rollback_no_active_transaction(): void {
10071044
$this->expectException( PDOException::class );
10081045
$this->expectExceptionMessage( 'There is no active transaction' );

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10407,6 +10407,183 @@ public function testTransactionSavepoints(): void {
1040710407
$this->assertSame( array(), (array) array_column( $result, 'id' ) );
1040810408
}
1040910409

10410+
public function testFailedStatementKeepsTransactionActive(): void {
10411+
$this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY)' );
10412+
$this->assertQuery( 'BEGIN' );
10413+
$this->assertQuery( 'INSERT INTO t VALUES (1)' );
10414+
10415+
// A failed write and a failed read keep the transaction active.
10416+
$this->assertQueryError(
10417+
'INSERT INTO t VALUES (1)',
10418+
'SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: t.id'
10419+
);
10420+
$this->assertTrue( $this->engine->inTransaction() );
10421+
$this->assertQueryError(
10422+
'SELECT * FROM missing_table',
10423+
"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'missing_table' doesn't exist"
10424+
);
10425+
$this->assertTrue( $this->engine->inTransaction() );
10426+
10427+
$this->assertQuery( 'INSERT INTO t VALUES (2)' );
10428+
$this->assertQuery( 'COMMIT' );
10429+
$result = $this->assertQuery( 'SELECT id FROM t ORDER BY id' );
10430+
$this->assertSame( array( '1', '2' ), array_column( $result, 'id' ) );
10431+
}
10432+
10433+
public function testFailedStatementIsRolledBackInTransaction(): void {
10434+
$this->assertQuery( 'CREATE TABLE t1 (id INT PRIMARY KEY)' );
10435+
$this->assertQuery( 'CREATE TABLE t2 (id INT PRIMARY KEY)' );
10436+
$this->assertQuery( 'CREATE TABLE t3 (id INT PRIMARY KEY, t2_id INT, FOREIGN KEY (t2_id) REFERENCES t2 (id))' );
10437+
$this->assertQuery( 'INSERT INTO t1 VALUES (1)' );
10438+
$this->assertQuery( 'INSERT INTO t2 VALUES (1)' );
10439+
$this->assertQuery( 'INSERT INTO t3 VALUES (1, 1)' );
10440+
$this->assertQuery( 'BEGIN' );
10441+
$this->assertQuery( 'INSERT INTO t1 VALUES (2)' );
10442+
10443+
/*
10444+
* A multi-table DELETE runs a DELETE query for each table. Deleting
10445+
* from t1 succeeds, and then deleting from t2 fails on the foreign key.
10446+
*/
10447+
$this->assertQueryError(
10448+
'DELETE t1, t2 FROM t1 JOIN t2 ON t2.id = t1.id',
10449+
'SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed'
10450+
);
10451+
$this->assertTrue( $this->engine->inTransaction() );
10452+
$this->assertQuery( 'COMMIT' );
10453+
10454+
// The changes of the failed statement are undone, and the rest is kept.
10455+
$result = $this->assertQuery( 'SELECT id FROM t1 ORDER BY id' );
10456+
$this->assertSame( array( '1', '2' ), array_column( $result, 'id' ) );
10457+
$result = $this->assertQuery( 'SELECT id FROM t2' );
10458+
$this->assertSame( array( '1' ), array_column( $result, 'id' ) );
10459+
}
10460+
10461+
public function testRollbackToSavepointAfterFailedStatement(): void {
10462+
$this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY)' );
10463+
$this->assertQuery( 'BEGIN' );
10464+
$this->assertQuery( 'INSERT INTO t VALUES (1)' );
10465+
$this->assertQuery( 'SAVEPOINT sp1' );
10466+
$this->assertQuery( 'INSERT INTO t VALUES (2)' );
10467+
$this->assertQueryError(
10468+
'INSERT INTO t VALUES (1)',
10469+
'SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: t.id'
10470+
);
10471+
10472+
// The savepoint still exists after the failed statement.
10473+
$this->assertQuery( 'ROLLBACK TO SAVEPOINT sp1' );
10474+
$this->assertQuery( 'COMMIT' );
10475+
$result = $this->assertQuery( 'SELECT id FROM t ORDER BY id' );
10476+
$this->assertSame( array( '1' ), array_column( $result, 'id' ) );
10477+
}
10478+
10479+
public function testFailedStatementKeepsTableLock(): void {
10480+
$this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY)' );
10481+
$this->assertQuery( 'LOCK TABLES t WRITE' );
10482+
$this->assertQuery( 'INSERT INTO t VALUES (1)' );
10483+
$this->assertQueryError(
10484+
'INSERT INTO t VALUES (1)',
10485+
'SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: t.id'
10486+
);
10487+
10488+
// UNLOCK TABLES keeps the rows written before the failed statement.
10489+
$this->assertQuery( 'UNLOCK TABLES' );
10490+
$this->assertFalse( $this->engine->inTransaction() );
10491+
$result = $this->assertQuery( 'SELECT id FROM t' );
10492+
$this->assertSame( array( '1' ), array_column( $result, 'id' ) );
10493+
}
10494+
10495+
/**
10496+
* @dataProvider dataFailedCommits
10497+
*/
10498+
public function testFailedCommitRollsBackTransaction( string $begin_query, string $commit_query ): void {
10499+
$this->assertQuery( 'CREATE TABLE p (id INT PRIMARY KEY)' );
10500+
$this->assertQuery( 'CREATE TABLE c (id INT PRIMARY KEY, p_id INT, FOREIGN KEY (p_id) REFERENCES p (id))' );
10501+
$this->assertQuery( $begin_query );
10502+
10503+
// Make the commit fail by deferring a foreign key check to it.
10504+
$this->sqlite->exec( 'PRAGMA defer_foreign_keys = ON' );
10505+
$this->assertQuery( 'INSERT INTO c VALUES (1, 1)' );
10506+
$this->assertQueryError(
10507+
$commit_query,
10508+
'SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed'
10509+
);
10510+
10511+
// Like MySQL, the failed commit rolls back the transaction.
10512+
$this->assertFalse( $this->engine->inTransaction() );
10513+
$result = $this->assertQuery( 'SELECT id FROM c' );
10514+
$this->assertSame( array(), array_column( $result, 'id' ) );
10515+
10516+
// The table lock is released, so UNLOCK TABLES doesn't commit a new transaction.
10517+
$this->assertQuery( 'BEGIN' );
10518+
$this->assertQuery( 'UNLOCK TABLES' );
10519+
$this->assertTrue( $this->engine->inTransaction() );
10520+
}
10521+
10522+
public static function dataFailedCommits(): array {
10523+
return array(
10524+
'COMMIT' => array( 'BEGIN', 'COMMIT' ),
10525+
'UNLOCK TABLES' => array( 'LOCK TABLES c WRITE', 'UNLOCK TABLES' ),
10526+
'implicit START TRANSACTION' => array( 'BEGIN', 'START TRANSACTION' ),
10527+
'implicit BEGIN' => array( 'BEGIN', 'BEGIN' ),
10528+
'implicit LOCK TABLES' => array( 'BEGIN', 'LOCK TABLES p WRITE' ),
10529+
);
10530+
}
10531+
10532+
public function testFailedStatementRolledBackBySqliteEndsTransaction(): void {
10533+
$this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY)' );
10534+
10535+
// Some SQLite errors roll back the whole transaction. Emulate them with a trigger.
10536+
$this->sqlite->exec(
10537+
"CREATE TRIGGER t_rollback BEFORE INSERT ON t WHEN NEW.id = 2 BEGIN SELECT RAISE(ROLLBACK, 'Rolled back'); END"
10538+
);
10539+
10540+
$this->assertQuery( 'BEGIN' );
10541+
$this->assertQuery( 'INSERT INTO t VALUES (1)' );
10542+
$this->assertQuery( 'SAVEPOINT sp1' );
10543+
$this->assertQueryError(
10544+
'INSERT INTO t VALUES (2)',
10545+
'SQLSTATE[23000]: Integrity constraint violation: 19 Rolled back'
10546+
);
10547+
10548+
// The transaction and its savepoints are gone.
10549+
$this->assertFalse( $this->engine->inTransaction() );
10550+
$this->assertQueryError(
10551+
'ROLLBACK TO SAVEPOINT sp1',
10552+
'SQLSTATE[42000]: Syntax error or access violation: 1305 SAVEPOINT sp1 does not exist'
10553+
);
10554+
10555+
// Without a transaction, the same error leaves the connection usable.
10556+
$this->assertQueryError(
10557+
'INSERT INTO t VALUES (2)',
10558+
'SQLSTATE[23000]: Integrity constraint violation: 19 Rolled back'
10559+
);
10560+
$this->assertFalse( $this->engine->inTransaction() );
10561+
$this->assertQuery( 'INSERT INTO t VALUES (3)' );
10562+
$result = $this->assertQuery( 'SELECT id FROM t' );
10563+
$this->assertSame( array( '3' ), array_column( $result, 'id' ) );
10564+
}
10565+
10566+
public function testFailedStatementRolledBackBySqliteReleasesTableLock(): void {
10567+
$this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY)' );
10568+
10569+
// Some SQLite errors roll back the whole transaction. Emulate them with a trigger.
10570+
$this->sqlite->exec(
10571+
"CREATE TRIGGER t_rollback BEFORE INSERT ON t WHEN NEW.id = 2 BEGIN SELECT RAISE(ROLLBACK, 'Rolled back'); END"
10572+
);
10573+
10574+
$this->assertQuery( 'LOCK TABLES t WRITE' );
10575+
$this->assertQueryError(
10576+
'INSERT INTO t VALUES (2)',
10577+
'SQLSTATE[23000]: Integrity constraint violation: 19 Rolled back'
10578+
);
10579+
$this->assertFalse( $this->engine->inTransaction() );
10580+
10581+
// The table lock is released, so UNLOCK TABLES doesn't commit a new transaction.
10582+
$this->assertQuery( 'BEGIN' );
10583+
$this->assertQuery( 'UNLOCK TABLES' );
10584+
$this->assertTrue( $this->engine->inTransaction() );
10585+
}
10586+
1041010587
public function testSavepointWithoutTransactionDoesNotStartTransaction(): void {
1041110588
$this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY, v INT)' );
1041210589
$this->assertQuery( 'INSERT INTO t (id, v) VALUES (1, 1)' );

0 commit comments

Comments
 (0)