Skip to content

Commit 501b73f

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 b8eafab commit 501b73f

2 files changed

Lines changed: 234 additions & 25 deletions

File tree

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

Lines changed: 81 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
*/
@@ -34,6 +37,13 @@ class WP_SQLite_Storage {
3437
*/
3538
private $database_root;
3639

40+
/**
41+
* Database busy timeout during legacy migration, in milliseconds.
42+
*
43+
* @var int
44+
*/
45+
private $migration_timeout = 10000;
46+
3747
/**
3848
* Creates a SQLite storage manager.
3949
*
@@ -47,7 +57,7 @@ public function __construct( ?string $database_root = null ) {
4757
* Initializes the SQLite database storage.
4858
*
4959
* Uses an explicit file path or ":memory:" as provided. Otherwise, initializes
50-
* managed storage with a randomized path unless a legacy database already exists.
60+
* managed storage with a randomized path and migrates legacy storage as needed.
5161
*
5262
* @param string|null $database_path Optional explicit database path.
5363
* @return string Absolute path to the SQLite database file, or ":memory:".
@@ -74,14 +84,6 @@ public function initialize( ?string $database_path = null ): string {
7484
if ( @is_file( $database_path ) ) {
7585
return $database_path;
7686
}
77-
} else {
78-
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
79-
if ( ! @is_file( $legacy_path ) ) {
80-
$legacy_path .= '.php';
81-
}
82-
if ( @is_file( $legacy_path ) ) {
83-
return $legacy_path;
84-
}
8587
}
8688

8789
// Initialize or repair the managed database under a lock.
@@ -90,17 +92,20 @@ public function initialize( ?string $database_path = null ): string {
9092
try {
9193
// Publish a new database path.
9294
if ( ! @is_file( $db_path_file ) ) {
93-
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
94-
if ( ! @is_file( $legacy_path ) ) {
95-
$legacy_path .= '.php';
96-
}
97-
if ( @is_file( $legacy_path ) ) {
98-
return $legacy_path;
99-
}
10095
$this->publish_database_path();
10196
}
10297
$database_path = $this->read_database_path( $db_path_file );
10398

99+
// Migrate from legacy ".ht.sqlite" and ".ht.sqlite.php" paths.
100+
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
101+
if ( ! @is_file( $legacy_path ) ) {
102+
$legacy_path .= '.php';
103+
}
104+
if ( ! @is_file( $database_path ) && @is_file( $legacy_path ) ) {
105+
$this->migrate_legacy_database( $legacy_path, $database_path );
106+
return $database_path;
107+
}
108+
104109
// Initialize a new database.
105110
$this->ensure_database( $database_path );
106111
return $database_path;
@@ -128,6 +133,66 @@ private function ensure_database( string $database_path ) {
128133
}
129134
}
130135

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

‎tests/phpunit/WP_SQLite_Storage_Test.php‎

Lines changed: 153 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -228,21 +228,113 @@ public function test_does_not_expose_the_database_path_when_initialization_fails
228228
}
229229
}
230230

231-
public function test_preserves_the_current_database_filename() {
232-
$this->assert_legacy_database_is_preserved( '.ht.sqlite' );
231+
public function test_automatically_migrates_the_current_legacy_database() {
232+
$this->assert_legacy_database_is_migrated( '.ht.sqlite' );
233233
}
234234

235-
public function test_preserves_the_older_database_filename() {
236-
$this->assert_legacy_database_is_preserved( '.ht.sqlite.php' );
235+
public function test_automatically_migrates_the_older_legacy_database() {
236+
$this->assert_legacy_database_is_migrated( '.ht.sqlite.php' );
237237
}
238238

239-
private function assert_legacy_database_is_preserved( $filename ) {
239+
public function test_prefers_the_current_legacy_database() {
240240
$database_root = $this->create_temporary_directory_path();
241-
$this->create_directory( $database_root );
242-
touch( $database_root . '/' . $filename );
241+
$current_path = $database_root . '/.ht.sqlite';
242+
$older_path = $database_root . '/.ht.sqlite.php';
243+
$this->create_sqlite_database( $current_path );
244+
$this->create_sqlite_database( $older_path );
243245

244-
$this->assertSame( $database_root . '/' . $filename, $this->initialize_managed_storage( $database_root ) );
245-
$this->assertFileDoesNotExist( $database_root . '/db-path.php' );
246+
$database_path = $this->initialize_managed_storage( $database_root );
247+
248+
$this->assertFileDoesNotExist( $current_path );
249+
$this->assertFileExists( $older_path );
250+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
251+
}
252+
253+
public function test_waits_for_existing_wal_connections_before_migrating() {
254+
$database_root = $this->create_temporary_directory_path();
255+
$legacy_path = $database_root . '/.ht.sqlite';
256+
$connection = $this->create_sqlite_database( $legacy_path );
257+
$connection->query( 'PRAGMA journal_mode = WAL' );
258+
$connection = null;
259+
260+
list( $process, $pipes ) = $this->open_temporary_database_connection( $legacy_path );
261+
try {
262+
$database_path = $this->initialize_managed_storage( $database_root );
263+
} finally {
264+
$process_result = $this->close_temporary_database_connection( $process, $pipes );
265+
}
266+
267+
$this->assertSame( 0, $process_result['exit_code'] );
268+
$this->assertSame( '', $process_result['error'] );
269+
$this->assertFileDoesNotExist( $legacy_path );
270+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
271+
}
272+
273+
public function test_does_not_migrate_a_busy_legacy_database() {
274+
$database_root = $this->create_temporary_directory_path();
275+
$legacy_path = $database_root . '/.ht.sqlite';
276+
$connection = $this->create_sqlite_database( $legacy_path );
277+
$connection->beginTransaction();
278+
$connection->exec( "UPDATE storage_test SET value = 'pending'" );
279+
$storage = new WP_SQLite_Storage( $database_root );
280+
$set_migration_timeout = Closure::bind(
281+
function ( $migration_timeout ) {
282+
$this->migration_timeout = $migration_timeout;
283+
},
284+
$storage,
285+
WP_SQLite_Storage::class
286+
);
287+
$set_migration_timeout( 10 );
288+
289+
try {
290+
$storage->initialize();
291+
$this->fail( 'A busy SQLite database was migrated.' );
292+
} catch ( RuntimeException $exception ) {
293+
$this->assertStringContainsString( 'Failed to prepare the SQLite database for migration', $exception->getMessage() );
294+
$this->assertStringNotContainsString( $legacy_path, $exception->getMessage() );
295+
} finally {
296+
$connection->rollBack();
297+
}
298+
299+
$database_path = require $database_root . '/db-path.php';
300+
301+
$this->assertFileExists( $legacy_path );
302+
$this->assertFileDoesNotExist( $database_path );
303+
$this->assertSame( $database_path, $storage->initialize() );
304+
$this->assertFileDoesNotExist( $legacy_path );
305+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
306+
}
307+
308+
public function test_does_not_expose_database_paths_when_migration_fails() {
309+
$database_root = $this->create_temporary_directory_path();
310+
$legacy_path = $database_root . '/.ht.sqlite';
311+
$database_path = $database_root . '/.ht.secret/.ht.sqlite';
312+
$this->create_sqlite_database( $legacy_path );
313+
$this->create_directory( $database_path );
314+
file_put_contents( $database_root . '/db-path.php', "<?php\nreturn " . var_export( $database_path, true ) . ";\n" );
315+
316+
try {
317+
$this->initialize_managed_storage( $database_root );
318+
$this->fail( 'The database was migrated over a directory.' );
319+
} catch ( RuntimeException $exception ) {
320+
$this->assertSame( 'Failed to move the SQLite database file.', $exception->getMessage() );
321+
$this->assertStringNotContainsString( $database_path, $exception->getMessage() );
322+
}
323+
324+
$this->assertFileExists( $legacy_path );
325+
}
326+
327+
private function assert_legacy_database_is_migrated( $filename ) {
328+
$database_root = $this->create_temporary_directory_path();
329+
$legacy_path = $database_root . '/' . $filename;
330+
$this->create_wal_sqlite_database_copy( $legacy_path );
331+
332+
$database_path = $this->initialize_managed_storage( $database_root );
333+
$stored_database_path = require $database_root . '/db-path.php';
334+
335+
$this->assertSame( $database_path, $stored_database_path );
336+
$this->assertFileDoesNotExist( $legacy_path );
337+
$this->assertSame( 'preserved', $this->read_sqlite_value( $database_path ) );
246338
}
247339

248340
private function initialize_managed_storage( $database_root ) {
@@ -270,6 +362,58 @@ private function create_sqlite_database( $database_path ) {
270362
return $connection;
271363
}
272364

365+
private function create_wal_sqlite_database_copy( $database_path ) {
366+
$source_directory = $this->create_temporary_directory_path();
367+
$source_path = $source_directory . '/source.sqlite';
368+
$this->create_directory( $source_directory );
369+
$this->create_directory( dirname( $database_path ) );
370+
371+
$connection = new PDO( 'sqlite:' . $source_path );
372+
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
373+
$this->assertSame( 'wal', $connection->query( 'PRAGMA journal_mode = WAL' )->fetchColumn() );
374+
$connection->exec( 'PRAGMA wal_autocheckpoint = 0' );
375+
$connection->exec( 'CREATE TABLE storage_test (value TEXT NOT NULL)' );
376+
$connection->exec( "INSERT INTO storage_test VALUES ('preserved')" );
377+
378+
$this->assertTrue( copy( $source_path, $database_path ) );
379+
$this->assertTrue( copy( $source_path . '-wal', $database_path . '-wal' ) );
380+
$connection = null;
381+
}
382+
383+
private function open_temporary_database_connection( $database_path ) {
384+
$script = sprintf(
385+
'$connection = new PDO(%s); $connection->query("SELECT value FROM storage_test")->fetchColumn(); fwrite(STDOUT, "ready\n"); fflush(STDOUT); usleep(250000);',
386+
var_export( 'sqlite:' . $database_path, true )
387+
);
388+
$command = escapeshellarg( PHP_BINARY ) . ' -r ' . escapeshellarg( $script );
389+
$process = proc_open(
390+
$command,
391+
array(
392+
array( 'pipe', 'r' ),
393+
array( 'pipe', 'w' ),
394+
array( 'pipe', 'w' ),
395+
),
396+
$pipes
397+
);
398+
399+
$this->assertIsResource( $process );
400+
fclose( $pipes[0] );
401+
$this->assertSame( "ready\n", fgets( $pipes[1] ) );
402+
403+
return array( $process, $pipes );
404+
}
405+
406+
private function close_temporary_database_connection( $process, $pipes ) {
407+
fclose( $pipes[1] );
408+
$error = stream_get_contents( $pipes[2] );
409+
fclose( $pipes[2] );
410+
411+
return array(
412+
'exit_code' => proc_close( $process ),
413+
'error' => $error,
414+
);
415+
}
416+
273417
private function read_sqlite_value( $database_path ) {
274418
$connection = new PDO( 'sqlite:' . $database_path );
275419

0 commit comments

Comments
 (0)