Skip to content

Commit a77ddba

Browse files
committed
feat(sqlite): harden export escaping and verify imports
Add \" to Export::escape_string for full MySQL backslash escaping and document the one-statement-per-line guarantee. Wrap Import in a transaction with rollback, add --refuse-overwrite and --verify-old-host, and delete a newly created database file (with -wal/-shm/-journal sidecars) when the import fails. Cover the new behaviors with Behat scenarios for export escaping, single-line INSERTs, refuse-overwrite, verification failure, and corrupt serialized data.
1 parent 3c4358b commit a77ddba

8 files changed

Lines changed: 573 additions & 12 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,21 @@ $ wp sqlite import <file>
2020
<file>
2121
The path to the MySQL compatible dump file to import. When passing `-` as the file argument, the SQL commands are read from standard input.
2222

23+
[--refuse-overwrite]
24+
Refuse to import when the SQLite database already contains user tables. By default the import merges into the existing database.
25+
26+
[--verify-old-host=<host>]
27+
After loading, fail when any stored value still contains <host>, or when any PHP-serialized value no longer unserializes. The check runs inside the import transaction, so a failure rolls everything back. A failed import into a new database file also deletes that file and its `-wal`, `-shm`, and `-journal` sidecars.
28+
2329
[--enable-ast-driver]
2430
Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
2531

2632
### wp sqlite export
2733

2834
Exports an SQLite database to a MySQL compatible file.
2935

36+
Each `INSERT` statement is written on a single line: embedded newlines and other special bytes are backslash-escaped (including double quotes), so dumps are safe for line-oriented downstream rewriters as well as for quote-aware parsers.
37+
3038
```
3139
$ wp sqlite export [<file>] [--tables=<tables>] [--exclude-tables] [--porcelain]
3240
```

‎features/bootstrap/SQLiteFeatureContext.php‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,18 @@ public function theSqliteDatabaseShouldContainATableNamed( $table_name ) {
3333
}
3434
}
3535

36+
/**
37+
* @Then /^the SQLite database should not contain a table named "([^"]*)"$/
38+
*/
39+
public function theSqliteDatabaseShouldNotContainATableNamed( $table_name ) {
40+
$this->connectToDatabase();
41+
$stmt = $this->db->prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name=?" );
42+
$stmt->execute( [ $table_name ] );
43+
$row = $stmt->fetch();
44+
if ( $row ) {
45+
throw new Exception( "Table '$table_name' was found in the database but should not exist." );
46+
}
47+
}
3648
/**
3749
* @Then /^the "([^"]*)" should contain a row with name "([^"]*)"$/
3850
* @Then /^the "([^"]*)" should contain a row with name:$/
@@ -71,8 +83,15 @@ public function theFileShouldExist( $filename ) {
7183

7284
private function connectToDatabase() {
7385
if ( ! $this->db ) {
74-
$result = $this->proc( 'wp eval \'echo defined( "DB_PATH" ) ? DB_PATH : FQDB;\'' )->run_check();
86+
// Prefer the configured path without booting WordPress: the
87+
// target may be a fresh import without WP tables installed.
88+
$result = $this->proc( 'wp config get DB_PATH' )->run();
7589
$db_file = trim( $result->stdout );
90+
if ( '' === $db_file || 0 === strpos( $db_file, 'Error:' ) ) {
91+
// Fall back to a full boot so the drop-in resolves FQDB.
92+
$result = $this->proc( 'wp eval \'echo defined( "FQDB" ) ? FQDB : ""; \'' )->run_check();
93+
$db_file = trim( $result->stdout );
94+
}
7695
if ( ! is_file( $db_file ) ) {
7796
throw new Exception( 'The WordPress SQLite database does not exist.' );
7897
}
@@ -345,4 +364,73 @@ public function iExportTheTableWithACommentInjectionName() {
345364
'run'
346365
);
347366
}
367+
368+
/**
369+
* @Given /^the SQLite database contains an option with a double quote$/
370+
*/
371+
public function theSqliteDatabaseContainsAnOptionWithADoubleQuote() {
372+
$this->connectToDatabase();
373+
374+
$this->db->exec( "DELETE FROM wp_options WHERE option_name = 'double-quote-option'" );
375+
376+
$stmt = $this->db->prepare(
377+
'
378+
INSERT INTO wp_options (option_name, option_value, autoload)
379+
VALUES (:option_name, :option_value, :autoload)
380+
'
381+
);
382+
$stmt->execute(
383+
array(
384+
':option_name' => 'double-quote-option',
385+
':option_value' => 'say "hello" backslash\\ end',
386+
':autoload' => 'yes',
387+
)
388+
);
389+
}
390+
391+
/**
392+
* @Then /^the double quote option should be escaped and preserved$/
393+
*/
394+
public function theDoubleQuoteOptionShouldBeEscapedAndPreserved() {
395+
$this->connectToDatabase();
396+
397+
$stmt = $this->db->prepare( "SELECT option_value FROM wp_options WHERE option_name = 'double-quote-option'" );
398+
$stmt->execute();
399+
$value = $stmt->fetchColumn();
400+
401+
$expected = 'say "hello" backslash\\ end';
402+
if ( $expected !== $value ) {
403+
throw new Exception(
404+
sprintf(
405+
'Double quote option was not preserved. Expected %s, got %s.',
406+
var_export( $expected, true ),
407+
var_export( $value, true )
408+
)
409+
);
410+
}
411+
}
412+
413+
/**
414+
* @Then /^every INSERT in the file "([^"]*)" should be on a single line$/
415+
*/
416+
public function everyInsertInTheFileShouldBeOnASingleLine( $filename ) {
417+
$full_path = $this->variables['RUN_DIR'] . '/' . $filename;
418+
$lines = file( $full_path, FILE_IGNORE_NEW_LINES );
419+
if ( false === $lines ) {
420+
throw new Exception( "Could not read file: $full_path" );
421+
}
422+
$insert_count = 0;
423+
foreach ( $lines as $line ) {
424+
if ( 0 !== strpos( ltrim( $line ), 'INSERT INTO' ) ) {
425+
continue;
426+
}
427+
++$insert_count;
428+
if ( ';' !== substr( rtrim( $line ), -1 ) ) {
429+
throw new Exception( "INSERT statement spans multiple lines: $line" );
430+
}
431+
}
432+
if ( 0 === $insert_count ) {
433+
throw new Exception( "No INSERT statements found in file: $full_path" );
434+
}
435+
}
348436
}

‎features/sqlite-export.feature‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ Feature: WP-CLI SQLite Export Command
169169
And the file "test_export_serialized_settings.sql" should exist
170170
And the file "test_export_serialized_settings.sql" should contain:
171171
"""
172-
breadcrumb-separator";s:4:"\00bb
172+
breadcrumb-separator\";s:4:\"\00bb
173173
"""
174174
And the file "test_export_serialized_settings.sql" should contain:
175175
"""
@@ -201,3 +201,30 @@ Feature: WP-CLI SQLite Export Command
201201
Success: Imported from 'test_export_escape_bytes.sql'.
202202
"""
203203
And the SQL string escape bytes should be preserved
204+
205+
@require-sqlite
206+
Scenario: Export should escape double quotes with a backslash
207+
Given the SQLite database contains an option with a double quote
208+
When I run `wp sqlite export test_export_dquote.sql --tables=wp_options`
209+
Then STDOUT should contain:
210+
"""
211+
Success: Export complete. File written to test_export_dquote.sql
212+
"""
213+
And the file "test_export_dquote.sql" should exist
214+
And the file "test_export_dquote.sql" should contain:
215+
"""
216+
'double-quote-option','say \"hello\" backslash\\ end','yes'
217+
"""
218+
When I run `wp sqlite --enable-ast-driver import test_export_dquote.sql`
219+
Then STDOUT should contain:
220+
"""
221+
Success: Imported from 'test_export_dquote.sql'.
222+
"""
223+
And the double quote option should be escaped and preserved
224+
225+
@require-sqlite
226+
Scenario: Export keeps every INSERT on a single line
227+
Given the SQLite database contains an option with SQL string escape bytes
228+
When I run `wp sqlite export test_export_single_line.sql --tables=wp_options`
229+
Then the file "test_export_single_line.sql" should exist
230+
And every INSERT in the file "test_export_single_line.sql" should be on a single line

‎features/sqlite-import.feature‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,102 @@ Feature: WP-CLI SQLite Import Command
211211
"""
212212
And the SQLite database should contain a table named "wp_zz_parent"
213213
And the SQLite database should contain a table named "wp_aa_child"
214+
215+
@require-sqlite
216+
Scenario: Refuse to overwrite an existing database
217+
Given a SQL dump file named "test_import.sql" with content:
218+
"""
219+
CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);
220+
INSERT INTO test_table (name) VALUES ('Test Name');
221+
"""
222+
When I run `wp sqlite import test_import.sql`
223+
Then STDOUT should contain:
224+
"""
225+
Success: Imported from 'test_import.sql'.
226+
"""
227+
When I try `wp sqlite import test_import.sql --refuse-overwrite`
228+
Then the return code should be 1
229+
And STDERR should contain:
230+
"""
231+
already contains tables
232+
"""
233+
And the SQLite database should contain a table named "test_table"
234+
235+
@require-sqlite
236+
Scenario: Allow refuse-overwrite into a fresh database file
237+
Given a SQL dump file named "test_import.sql" with content:
238+
"""
239+
CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);
240+
INSERT INTO test_table (name) VALUES ('Test Name');
241+
"""
242+
When I run `wp config set DB_PATH '{RUN_DIR}/fresh.sqlite'`
243+
And I run `wp sqlite import test_import.sql --refuse-overwrite`
244+
Then STDOUT should contain:
245+
"""
246+
Success: Imported from 'test_import.sql'.
247+
"""
248+
And the SQLite database should contain a table named "test_table"
249+
250+
@require-sqlite
251+
Scenario: Failed import into a new database removes the new file
252+
Given a SQL dump file named "test_import_bad.sql" with content:
253+
"""
254+
CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);
255+
INSERT INTO missing_table (name) VALUES ('Test Name');
256+
"""
257+
When I run `wp config set DB_PATH '{RUN_DIR}/atomic.sqlite'`
258+
And I try `wp sqlite import test_import_bad.sql`
259+
Then the return code should be 1
260+
And STDERR should contain:
261+
"""
262+
Could not execute statement
263+
"""
264+
And the atomic.sqlite file should not exist
265+
And the atomic.sqlite-wal file should not exist
266+
And the atomic.sqlite-shm file should not exist
267+
And the atomic.sqlite-journal file should not exist
268+
269+
@require-sqlite
270+
Scenario: Fail verification when the old host remains
271+
Given a SQL dump file named "test_import.sql" with content:
272+
"""
273+
CREATE TABLE verify_host (id INTEGER PRIMARY KEY, name TEXT);
274+
INSERT INTO verify_host (name) VALUES ('https://oldhost.invalid/page');
275+
"""
276+
When I try `wp sqlite import test_import.sql --verify-old-host=oldhost.invalid`
277+
Then the return code should be 1
278+
And STDERR should contain:
279+
"""
280+
still contain 'oldhost.invalid'
281+
"""
282+
And the SQLite database should not contain a table named "verify_host"
283+
284+
@require-sqlite
285+
Scenario: Pass verification when the old host is gone
286+
Given a SQL dump file named "test_import.sql" with content:
287+
"""
288+
CREATE TABLE verify_host (id INTEGER PRIMARY KEY, name TEXT);
289+
INSERT INTO verify_host (name) VALUES ('https://newhost.invalid/page');
290+
"""
291+
When I run `wp sqlite import test_import.sql --verify-old-host=oldhost.invalid`
292+
Then STDOUT should contain:
293+
"""
294+
Success: Imported from 'test_import.sql'.
295+
"""
296+
And the SQLite database should contain a table named "verify_host"
297+
And the "verify_host" should contain a row with name "https://newhost.invalid/page"
298+
299+
@require-sqlite
300+
Scenario: Fail verification on corrupt serialized data
301+
Given a SQL dump file named "test_import.sql" with content:
302+
"""
303+
CREATE TABLE verify_serialized (id INTEGER PRIMARY KEY, name TEXT);
304+
INSERT INTO verify_serialized (name) VALUES ('a:1:{s:3:"foo";s:4:"broken}');
305+
"""
306+
When I try `wp sqlite import test_import.sql --verify-old-host=never-present.invalid`
307+
Then the return code should be 1
308+
And STDERR should contain:
309+
"""
310+
invalid serialized data
311+
"""
312+
And the SQLite database should not contain a table named "verify_serialized"

‎src/Export.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,11 @@ protected function get_create_statement( $table_name ) {
191191
/**
192192
* Get the INSERT statements for a table.
193193
*
194+
* Each yielded statement is a single line: embedded newlines and other
195+
* special bytes are backslash-escaped by escape_string(), and the caller
196+
* terminates every statement with PHP_EOL. Line-oriented downstream
197+
* rewriters may therefore process the dump one statement per line.
198+
*
194199
* @param string $table_name
195200
*
196201
* @return \Generator
@@ -269,6 +274,11 @@ protected function escape_values( $values ) {
269274
/**
270275
* Escapes a string for use in an insert statement.
271276
*
277+
* Uses full MySQL backslash escaping, including double quotes, so that
278+
* each INSERT statement stays on a single line and remains safe for
279+
* line-oriented downstream rewriters (e.g. go-search-replace) as well
280+
* as for the quote-aware Import::parse_statements().
281+
*
272282
* @param $value
273283
*
274284
* @return string
@@ -281,6 +291,7 @@ protected function escape_string( $value ) {
281291
"\n" => '\n',
282292
"\r" => '\r',
283293
"\x1a" => '\Z',
294+
'"' => '\\"',
284295
'\\' => '\\\\',
285296
"'" => "\\'",
286297
)

0 commit comments

Comments
 (0)