Skip to content

Commit 36f4919

Browse files
committed
Migrate legacy SQLite database storage
Move fixed database files into randomized storage automatically before opening SQLite. Serialize concurrent requests, checkpoint WAL, refuse busy or ambiguous storage, and preserve legacy files when migration fails.
1 parent a091d31 commit 36f4919

2 files changed

Lines changed: 218 additions & 25 deletions

File tree

‎packages/plugin-sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-storage.php‎

Lines changed: 74 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
/**
44
* Manages the storage layout for the WordPress SQLite database.
55
*
6+
* Legacy database migration uses a PDO SQLite connection:
7+
* phpcs:disable WordPress.DB.RestrictedClasses.mysql__PDO
8+
*
69
* Filesystem warnings are suppressed to avoid exposing database paths:
710
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
811
*/
@@ -47,7 +50,7 @@ public function __construct( ?string $database_root = null ) {
4750
* Initializes the SQLite database storage.
4851
*
4952
* Uses an explicit file path or ":memory:" as provided. Otherwise, initializes
50-
* managed storage with a randomized path unless a legacy database already exists.
53+
* managed storage with a randomized path and migrates legacy storage as needed.
5154
*
5255
* @param string|null $database_path Optional explicit database path.
5356
* @return string Absolute path to the SQLite database file, or ":memory:".
@@ -76,32 +79,27 @@ public function initialize( ?string $database_path = null ): string {
7679
$this->ensure_database( $database_path );
7780
return $database_path;
7881
}
79-
} else {
80-
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
81-
if ( ! @is_file( $legacy_path ) ) {
82-
$legacy_path .= '.php';
83-
}
84-
if ( @is_file( $legacy_path ) ) {
85-
return $legacy_path;
86-
}
8782
}
8883

8984
// Initialize or repair the managed database under a lock.
9085
$lock = $this->acquire_lock();
9186
try {
9287
// Publish a new database path.
9388
if ( ! @is_file( $db_path_file ) ) {
94-
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
95-
if ( ! @is_file( $legacy_path ) ) {
96-
$legacy_path .= '.php';
97-
}
98-
if ( @is_file( $legacy_path ) ) {
99-
return $legacy_path;
100-
}
10189
$this->publish_database_path();
10290
}
10391
$database_path = $this->read_database_path( $db_path_file );
10492

93+
// Migrate from legacy ".ht.sqlite" and ".ht.sqlite.php" paths.
94+
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
95+
if ( ! @is_file( $legacy_path ) ) {
96+
$legacy_path .= '.php';
97+
}
98+
if ( ! @is_file( $database_path ) && @is_file( $legacy_path ) ) {
99+
$this->migrate_legacy_database( $legacy_path, $database_path );
100+
return $database_path;
101+
}
102+
105103
// Initialize a new database.
106104
$this->ensure_database( $database_path );
107105
return $database_path;
@@ -129,6 +127,66 @@ private function ensure_database( string $database_path ) {
129127
}
130128
}
131129

130+
/**
131+
* Moves the legacy database to the intended database path.
132+
*
133+
* @param string $legacy_path Absolute legacy database path.
134+
* @param string $database_path Absolute intended database path.
135+
*/
136+
private function migrate_legacy_database( string $legacy_path, string $database_path ) {
137+
// Disable WAL so only the main database file needs to be moved.
138+
try {
139+
$this->ensure_protected_directory( dirname( $database_path ) );
140+
141+
$connection = new PDO( 'sqlite:' . $legacy_path );
142+
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
143+
$connection->exec( 'PRAGMA busy_timeout = 10000' );
144+
145+
$deadline = microtime( true ) + 10; // Now + 10 seconds.
146+
do {
147+
try {
148+
$journal_mode = $connection->query( 'PRAGMA journal_mode = DELETE' )->fetchColumn();
149+
if ( 'delete' === strtolower( (string) $journal_mode ) ) {
150+
break;
151+
}
152+
} catch ( PDOException $exception ) {
153+
$error_info = $connection->errorInfo();
154+
$sqlite_error_code = isset( $error_info[1] ) ? (int) $error_info[1] : 0;
155+
$sqlite_busy = 5;
156+
if ( ( $sqlite_error_code & 0xff ) !== $sqlite_busy ) {
157+
throw $exception;
158+
}
159+
}
160+
161+
if ( microtime( true ) >= $deadline ) {
162+
throw new RuntimeException( 'Failed to disable WAL before migrating the SQLite database.' );
163+
}
164+
usleep( 100 * 1000 ); // Wait 100 milliseconds.
165+
} while ( true );
166+
167+
// Block other reads and writes before moving the database.
168+
$connection->exec( 'BEGIN EXCLUSIVE' );
169+
} catch ( Throwable $exception ) {
170+
throw new RuntimeException( 'Failed to prepare the SQLite database for migration.', 0, $exception );
171+
}
172+
173+
/*
174+
* Close the connection just before moving the database. SQLite considers
175+
* renaming an open database undefined, and Windows generally prevents it.
176+
* We cannot fully prevent race conditions, but this makes them unlikely.
177+
*
178+
* See: https://www.sqlite.org/howtocorrupt.html#unlink
179+
*/
180+
$connection = null;
181+
182+
// Move only the main database file. WAL was disabled and an exclusive
183+
// lock was acquired, so no valid sidecar files are expected.
184+
if ( ! @rename( $legacy_path, $database_path ) ) {
185+
throw new RuntimeException( 'Failed to move the SQLite database file.' );
186+
}
187+
@chmod( $database_path, 0600 );
188+
}
189+
132190
/**
133191
* Reads and validates the database path file.
134192
*

‎tests/phpunit/WP_SQLite_Storage_Test.php‎

Lines changed: 144 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -213,21 +213,104 @@ public function test_does_not_expose_the_database_path_when_initialization_fails
213213
}
214214
}
215215

216-
public function test_preserves_the_current_database_filename() {
217-
$this->assert_legacy_database_is_preserved( '.ht.sqlite' );
216+
public function test_automatically_migrates_the_current_legacy_database() {
217+
$this->assert_legacy_database_is_migrated( '.ht.sqlite' );
218218
}
219219

220-
public function test_preserves_the_older_database_filename() {
221-
$this->assert_legacy_database_is_preserved( '.ht.sqlite.php' );
220+
public function test_automatically_migrates_the_older_legacy_database() {
221+
$this->assert_legacy_database_is_migrated( '.ht.sqlite.php' );
222222
}
223223

224-
private function assert_legacy_database_is_preserved( $filename ) {
224+
public function test_prefers_the_current_legacy_database() {
225225
$database_root = $this->create_temporary_directory_path();
226-
$this->create_directory( $database_root );
227-
touch( $database_root . '/' . $filename );
226+
$current_path = $database_root . '/.ht.sqlite';
227+
$older_path = $database_root . '/.ht.sqlite.php';
228+
$this->create_sqlite_database( $current_path );
229+
$this->create_sqlite_database( $older_path );
228230

229-
$this->assertSame( $database_root . '/' . $filename, $this->initialize_managed_storage( $database_root ) );
230-
$this->assertFileDoesNotExist( $database_root . '/db-path.php' );
231+
$database_path = $this->initialize_managed_storage( $database_root );
232+
233+
$this->assertFileDoesNotExist( $current_path );
234+
$this->assertFileExists( $older_path );
235+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
236+
}
237+
238+
public function test_waits_for_existing_wal_connections_before_migrating() {
239+
$database_root = $this->create_temporary_directory_path();
240+
$legacy_path = $database_root . '/.ht.sqlite';
241+
$connection = $this->create_sqlite_database( $legacy_path );
242+
$connection->query( 'PRAGMA journal_mode = WAL' );
243+
$connection = null;
244+
245+
list( $process, $pipes ) = $this->open_temporary_database_connection( $legacy_path );
246+
try {
247+
$database_path = $this->initialize_managed_storage( $database_root );
248+
} finally {
249+
$process_result = $this->close_temporary_database_connection( $process, $pipes );
250+
}
251+
252+
$this->assertSame( 0, $process_result['exit_code'] );
253+
$this->assertSame( '', $process_result['error'] );
254+
$this->assertFileDoesNotExist( $legacy_path );
255+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
256+
}
257+
258+
public function test_does_not_migrate_a_busy_legacy_database() {
259+
$database_root = $this->create_temporary_directory_path();
260+
$legacy_path = $database_root . '/.ht.sqlite';
261+
$connection = $this->create_sqlite_database( $legacy_path );
262+
$connection->beginTransaction();
263+
$connection->exec( "UPDATE storage_test SET value = 'pending'" );
264+
265+
try {
266+
$this->initialize_managed_storage( $database_root );
267+
$this->fail( 'A busy SQLite database was migrated.' );
268+
} catch ( RuntimeException $exception ) {
269+
$this->assertStringContainsString( 'Failed to prepare the SQLite database for migration', $exception->getMessage() );
270+
$this->assertStringNotContainsString( $legacy_path, $exception->getMessage() );
271+
} finally {
272+
$connection->rollBack();
273+
}
274+
275+
$database_path = require $database_root . '/db-path.php';
276+
277+
$this->assertFileExists( $legacy_path );
278+
$this->assertFileDoesNotExist( $database_path );
279+
$this->assertSame( $database_path, $this->initialize_managed_storage( $database_root ) );
280+
$this->assertFileDoesNotExist( $legacy_path );
281+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
282+
}
283+
284+
public function test_does_not_expose_database_paths_when_migration_fails() {
285+
$database_root = $this->create_temporary_directory_path();
286+
$legacy_path = $database_root . '/.ht.sqlite';
287+
$database_path = $database_root . '/.ht.secret/.ht.sqlite';
288+
$this->create_sqlite_database( $legacy_path );
289+
$this->create_directory( $database_path );
290+
file_put_contents( $database_root . '/db-path.php', "<?php\nreturn " . var_export( $database_path, true ) . ";\n" );
291+
292+
try {
293+
$this->initialize_managed_storage( $database_root );
294+
$this->fail( 'The database was migrated over a directory.' );
295+
} catch ( RuntimeException $exception ) {
296+
$this->assertSame( 'Failed to move the SQLite database file.', $exception->getMessage() );
297+
$this->assertStringNotContainsString( $database_path, $exception->getMessage() );
298+
}
299+
300+
$this->assertFileExists( $legacy_path );
301+
}
302+
303+
private function assert_legacy_database_is_migrated( $filename ) {
304+
$database_root = $this->create_temporary_directory_path();
305+
$legacy_path = $database_root . '/' . $filename;
306+
$this->create_wal_sqlite_database_copy( $legacy_path );
307+
308+
$database_path = $this->initialize_managed_storage( $database_root );
309+
$stored_database_path = require $database_root . '/db-path.php';
310+
311+
$this->assertSame( $database_path, $stored_database_path );
312+
$this->assertFileDoesNotExist( $legacy_path );
313+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
231314
}
232315

233316
private function initialize_managed_storage( $database_root ) {
@@ -255,6 +338,58 @@ private function create_sqlite_database( $database_path ) {
255338
return $connection;
256339
}
257340

341+
private function create_wal_sqlite_database_copy( $database_path ) {
342+
$source_directory = $this->create_temporary_directory_path();
343+
$source_path = $source_directory . '/source.sqlite';
344+
$this->create_directory( $source_directory );
345+
$this->create_directory( dirname( $database_path ) );
346+
347+
$connection = new PDO( 'sqlite:' . $source_path );
348+
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
349+
$this->assertSame( 'wal', $connection->query( 'PRAGMA journal_mode = WAL' )->fetchColumn() );
350+
$connection->exec( 'PRAGMA wal_autocheckpoint = 0' );
351+
$connection->exec( 'CREATE TABLE storage_test (value TEXT NOT NULL)' );
352+
$connection->exec( "INSERT INTO storage_test VALUES ('preserved')" );
353+
354+
$this->assertTrue( copy( $source_path, $database_path ) );
355+
$this->assertTrue( copy( $source_path . '-wal', $database_path . '-wal' ) );
356+
$connection = null;
357+
}
358+
359+
private function open_temporary_database_connection( $database_path ) {
360+
$script = sprintf(
361+
'$connection = new PDO(%s); $connection->query("SELECT value FROM storage_test")->fetchColumn(); fwrite(STDOUT, "ready\n"); fflush(STDOUT); usleep(250000);',
362+
var_export( 'sqlite:' . $database_path, true )
363+
);
364+
$command = escapeshellarg( PHP_BINARY ) . ' -r ' . escapeshellarg( $script );
365+
$process = proc_open(
366+
$command,
367+
array(
368+
array( 'pipe', 'r' ),
369+
array( 'pipe', 'w' ),
370+
array( 'pipe', 'w' ),
371+
),
372+
$pipes
373+
);
374+
375+
$this->assertIsResource( $process );
376+
fclose( $pipes[0] );
377+
$this->assertSame( "ready\n", fgets( $pipes[1] ) );
378+
379+
return array( $process, $pipes );
380+
}
381+
382+
private function close_temporary_database_connection( $process, $pipes ) {
383+
fclose( $pipes[1] );
384+
$error = stream_get_contents( $pipes[2] );
385+
fclose( $pipes[2] );
386+
387+
return array(
388+
'exit_code' => proc_close( $process ),
389+
'error' => $error,
390+
);
391+
}
392+
258393
private function read_sqlite_value( $database_path ) {
259394
$connection = new PDO( 'sqlite:' . $database_path );
260395

0 commit comments

Comments
 (0)