Skip to content

Commit a5314e3

Browse files
authored
Roll back failed OPTIMIZE TABLE and REPAIR TABLE rebuilds (#567)
`OPTIMIZE TABLE` and `REPAIR TABLE` report rebuild errors as result rows. The surrounding transaction then commits the work completed before the error, leaving hidden tables or a partly rebuilt table. This change makes **each table administration operation atomic** with an internal savepoint. A failed rebuild restores the original schema and data, while successful rebuilds of other tables are preserved. Regression tests cover failures while copying rows, dropping the old table, and recreating indexes, including permanent and temporary tables, repeated failures, and mixed results. They also verify committed data when the command is issued inside a transaction. Fixes #549. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Failed table maintenance operations, including `OPTIMIZE` and `REPAIR`, now roll back changes for the affected table. This helps preserve its schema and data after an error, including when an operation fails while recreating indexes or dropping a table. * When a statement affects multiple tables, successful operations can be retained while failed operations are rolled back individually. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent db55ab1 commit a5314e3

2 files changed

Lines changed: 138 additions & 6 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4097,6 +4097,7 @@ private function execute_set_user_variable_statement(
40974097
private function execute_administration_statement( WP_Parser_Node $node ): void {
40984098
$first_token = $node->get_first_child_token();
40994099
$table_ref_list = $node->get_first_child_node( 'tableRefList' );
4100+
$savepoint_name = $this->get_internal_savepoint_name( 'table_administration' );
41004101
$results = array();
41014102
foreach ( $table_ref_list->get_child_nodes( 'tableRef' ) as $table_ref ) {
41024103
$database = $this->get_database_name( $table_ref );
@@ -4106,6 +4107,9 @@ private function execute_administration_statement( WP_Parser_Node $node ): void
41064107

41074108
$table_name = $this->unquote_sqlite_identifier( $this->translate( $table_ref ) );
41084109
$quoted_table_name = $this->quote_sqlite_identifier( $table_name );
4110+
4111+
// Each table must be atomic because failures are reported as result rows.
4112+
$this->execute_sqlite_query( sprintf( 'SAVEPOINT %s', $savepoint_name ) );
41094113
try {
41104114
switch ( $first_token->id ) {
41114115
case WP_MySQL_Lexer::ANALYZE_SYMBOL:
@@ -4143,6 +4147,7 @@ private function execute_administration_statement( WP_Parser_Node $node ): void
41434147
);
41444148
}
41454149
} catch ( PDOException $e ) {
4150+
$this->execute_sqlite_query( sprintf( 'ROLLBACK TO SAVEPOINT %s', $savepoint_name ) );
41464151
if ( '42S02' === $e->getCode() && isset( $e->errorInfo[2] ) ) {
41474152
$errors = array( $e->errorInfo[2] );
41484153
} elseif (
@@ -4155,6 +4160,7 @@ private function execute_administration_statement( WP_Parser_Node $node ): void
41554160
$errors = array( $e->getMessage() );
41564161
}
41574162
}
4163+
$this->execute_sqlite_query( sprintf( 'RELEASE SAVEPOINT %s', $savepoint_name ) );
41584164

41594165
$operation = strtolower( $first_token->get_value() );
41604166
foreach ( $errors as $error ) {

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

Lines changed: 132 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -474,31 +474,40 @@ public function testOptimizeTable() {
474474
);
475475
}
476476

477-
public function testOptimizeTableWithFailedRecreation() {
478-
$this->assertQuery( 'CREATE TABLE t (id INT, name TEXT)' );
477+
/**
478+
* @dataProvider data_rebuild_operations_and_table_types
479+
*/
480+
public function testAdministrationWithFailedRecreation( string $operation, bool $temporary ): void {
481+
$this->assertQuery( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . 'TABLE t (id INT, name TEXT)' );
482+
$this->assertQuery( "INSERT INTO t VALUES (1, 'a'), (2, 'b')" );
479483

480484
// Make recreating the table fail, as its information schema names a column that doesn't exist.
481-
$this->sqlite->exec( "UPDATE _wp_sqlite_mysql_information_schema_columns SET column_name = 'title' WHERE table_name = 't' AND column_name = 'name'" );
485+
$columns_table = $temporary ? '_wp_sqlite_mysql_information_schema_tmp_columns' : '_wp_sqlite_mysql_information_schema_columns';
486+
$this->sqlite->exec( "UPDATE $columns_table SET column_name = 'title' WHERE table_name = 't' AND column_name = 'name'" );
487+
$schema = $this->getSqliteSchema();
488+
$data = $this->sqlite->query( 'SELECT rowid, * FROM t ORDER BY rowid' )->fetchAll( PDO::FETCH_ASSOC );
482489

483490
// The error from SQLite is reported, not a missing table.
484-
$result = $this->assertQuery( 'OPTIMIZE TABLE t' );
491+
$result = $this->assertQuery( "$operation TABLE t" );
485492
$this->assertEquals(
486493
array(
487494
(object) array(
488495
'Table' => 'wp.t',
489-
'Op' => 'optimize',
496+
'Op' => strtolower( $operation ),
490497
'Msg_type' => 'Error',
491498
'Msg_text' => 'SQLSTATE[HY000]: General error: 1 no such column: title',
492499
),
493500
(object) array(
494501
'Table' => 'wp.t',
495-
'Op' => 'optimize',
502+
'Op' => strtolower( $operation ),
496503
'Msg_type' => 'status',
497504
'Msg_text' => 'Operation failed',
498505
),
499506
),
500507
$result
501508
);
509+
$this->assertSame( $schema, $this->getSqliteSchema() );
510+
$this->assertSame( $data, $this->sqlite->query( 'SELECT rowid, * FROM t ORDER BY rowid' )->fetchAll( PDO::FETCH_ASSOC ) );
502511
}
503512

504513
public function testRepairTable() {
@@ -586,6 +595,114 @@ public function testRepairTable() {
586595
);
587596
}
588597

598+
/**
599+
* @dataProvider data_rebuild_operations_and_table_types
600+
*/
601+
public function testAdministrationRollsBackFailedDrop( string $operation, bool $temporary ): void {
602+
$this->assertQuery( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . 'TABLE t (id INT PRIMARY KEY, name TEXT)' );
603+
$this->assertQuery( "INSERT INTO t VALUES (1, 'a'), (2, 'b')" );
604+
$schema = $this->getSqliteSchema();
605+
$data = $this->sqlite->query( 'SELECT rowid, * FROM t ORDER BY rowid' )->fetchAll( PDO::FETCH_ASSOC );
606+
607+
// SQLite can't drop a table while another statement is still reading.
608+
$read = $this->sqlite->query( 'SELECT * FROM t' );
609+
$read->fetch();
610+
611+
// Repeated failures must not leave copies of the table behind.
612+
for ( $i = 0; $i < 2; ++$i ) {
613+
$result = $this->assertQuery( "$operation TABLE t" );
614+
$this->assertCount( 2, $result );
615+
$this->assertStringContainsString( 'database table is locked', $result[0]->Msg_text );
616+
$this->assertSame( 'Operation failed', $result[1]->Msg_text );
617+
$this->assertSame( $schema, $this->getSqliteSchema() );
618+
$this->assertSame( $data, $this->sqlite->query( 'SELECT rowid, * FROM t ORDER BY rowid' )->fetchAll( PDO::FETCH_ASSOC ) );
619+
}
620+
}
621+
622+
/**
623+
* @dataProvider data_rebuild_operations_and_table_types
624+
*/
625+
public function testAdministrationRollsBackFailedIndexRecreation( string $operation, bool $temporary ): void {
626+
$this->assertQuery(
627+
'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . 'TABLE t (id INT AUTO_INCREMENT PRIMARY KEY, name TEXT, UNIQUE KEY u (name), KEY k (id)) AUTO_INCREMENT = 100'
628+
);
629+
630+
// These values fit the existing binary index but conflict when its NOCASE definition is restored.
631+
$this->sqlite->exec( 'DROP INDEX t__u' );
632+
$this->sqlite->exec( 'CREATE UNIQUE INDEX t__u ON t (name COLLATE BINARY)' );
633+
$this->sqlite->exec( "INSERT INTO t VALUES (1, 'a'), (2, 'A')" );
634+
$schema = $this->getSqliteSchema();
635+
$data = $this->sqlite->query( 'SELECT rowid, * FROM t ORDER BY rowid' )->fetchAll( PDO::FETCH_ASSOC );
636+
$sequence_table = $temporary ? 'temp.sqlite_sequence' : 'main.sqlite_sequence';
637+
$sequence = $this->sqlite->query( "SELECT seq FROM $sequence_table WHERE name = 't'" )->fetchColumn();
638+
639+
$result = $this->assertQuery( "$operation TABLE t" );
640+
$this->assertCount( 2, $result );
641+
$this->assertStringContainsString( 'UNIQUE constraint failed', $result[0]->Msg_text );
642+
$this->assertSame( 'Operation failed', $result[1]->Msg_text );
643+
$this->assertSame( $schema, $this->getSqliteSchema() );
644+
$this->assertSame( $data, $this->sqlite->query( 'SELECT rowid, * FROM t ORDER BY rowid' )->fetchAll( PDO::FETCH_ASSOC ) );
645+
$this->assertSame( $sequence, $this->sqlite->query( "SELECT seq FROM $sequence_table WHERE name = 't'" )->fetchColumn() );
646+
}
647+
648+
/**
649+
* @dataProvider data_rebuild_operations_and_transactions
650+
*/
651+
public function testAdministrationKeepsSuccessfulRebuilds( string $operation, bool $in_transaction ): void {
652+
$this->assertQuery( 'CREATE TABLE good_before (id INT, KEY k (id))' );
653+
$this->assertQuery( 'CREATE TABLE bad (id INT)' );
654+
$this->assertQuery( 'CREATE TABLE good_after (id INT, KEY k (id))' );
655+
$this->assertQuery( 'INSERT INTO bad VALUES (NULL)' );
656+
$this->sqlite->exec( "UPDATE _wp_sqlite_mysql_information_schema_columns SET is_nullable = 'NO' WHERE table_name = 'bad'" );
657+
658+
// Rebuilding the good tables must restore their missing indexes.
659+
$this->sqlite->exec( 'DROP INDEX good_before__k' );
660+
$this->sqlite->exec( 'DROP INDEX good_after__k' );
661+
if ( $in_transaction ) {
662+
$this->assertQuery( 'START TRANSACTION' );
663+
$this->assertQuery( 'INSERT INTO good_before VALUES (1)' );
664+
}
665+
666+
$result = $this->assertQuery( "$operation TABLE good_before, bad, good_after" );
667+
$this->assertSame( array( 'wp.good_before', 'wp.bad', 'wp.bad', 'wp.good_after' ), array_column( $result, 'Table' ) );
668+
$this->assertSame( array( 'status', 'Error', 'status', 'status' ), array_column( $result, 'Msg_type' ) );
669+
$this->assertSame( 'OK', $result[0]->Msg_text );
670+
$this->assertStringContainsString( 'NOT NULL constraint failed', $result[1]->Msg_text );
671+
$this->assertSame( 'Operation failed', $result[2]->Msg_text );
672+
$this->assertSame( 'OK', $result[3]->Msg_text );
673+
$this->assertSame(
674+
array( 'good_after__k', 'good_before__k' ),
675+
$this->sqlite->query( "SELECT name FROM sqlite_master WHERE type = 'index' AND name IN ('good_before__k', 'good_after__k') ORDER BY name" )->fetchAll( PDO::FETCH_COLUMN )
676+
);
677+
$this->assertSame( array( null ), $this->sqlite->query( 'SELECT id FROM bad' )->fetchAll( PDO::FETCH_COLUMN ) );
678+
$this->assertSame( array(), $this->sqlite->query( "SELECT name FROM sqlite_master WHERE name GLOB '_wp_sqlite_tmp_*'" )->fetchAll( PDO::FETCH_COLUMN ) );
679+
680+
// MySQL commits before table administration, so only check the committed result.
681+
if ( $in_transaction ) {
682+
$this->assertQuery( 'COMMIT' );
683+
$this->assertEquals( array( (object) array( 'id' => '1' ) ), $this->assertQuery( 'SELECT id FROM good_before' ) );
684+
}
685+
$this->assertFalse( $this->engine->inTransaction() );
686+
}
687+
688+
public function data_rebuild_operations_and_table_types(): array {
689+
return array(
690+
'optimize permanent' => array( 'OPTIMIZE', false ),
691+
'optimize temporary' => array( 'OPTIMIZE', true ),
692+
'repair permanent' => array( 'REPAIR', false ),
693+
'repair temporary' => array( 'REPAIR', true ),
694+
);
695+
}
696+
697+
public function data_rebuild_operations_and_transactions(): array {
698+
return array(
699+
'optimize autocommit' => array( 'OPTIMIZE', false ),
700+
'optimize transaction' => array( 'OPTIMIZE', true ),
701+
'repair autocommit' => array( 'REPAIR', false ),
702+
'repair transaction' => array( 'REPAIR', true ),
703+
);
704+
}
705+
589706
public function testShowCollation(): void {
590707
// Simple.
591708
$this->assertQuery( 'SHOW COLLATION' );
@@ -2856,4 +2973,13 @@ public function testInformationSchemaAlterTableDropCheckConstraint(): void {
28562973
$result = $this->assertQuery( 'SELECT * FROM information_schema.check_constraints' );
28572974
$this->assertCount( 0, $result );
28582975
}
2976+
2977+
private function getSqliteSchema(): array {
2978+
return $this->sqlite->query(
2979+
"SELECT 'main' AS db, type, name, tbl_name, sql FROM sqlite_master
2980+
UNION ALL
2981+
SELECT 'temp' AS db, type, name, tbl_name, sql FROM sqlite_temp_master
2982+
ORDER BY db, type, name"
2983+
)->fetchAll( PDO::FETCH_ASSOC );
2984+
}
28592985
}

0 commit comments

Comments
 (0)