Skip to content

Commit 053f717

Browse files
committed
Fix character escaping to support escaped backslashes
1 parent 92c3558 commit 053f717

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

‎features/sqlite-import.feature‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,27 @@ Feature: WP-CLI SQLite Import Command
4343
Success: Imported from 'STDIN'.
4444
"""
4545
And the SQLite database should contain the imported data
46+
47+
@require-sqlite
48+
Scenario: Import a file with escape sequences
49+
Given a SQL dump file named "test_import.sql" with content:
50+
"""
51+
SET sql_mode='NO_BACKSLASH_ESCAPES';
52+
CREATE TABLE test_table (id INTEGER PRIMARY KEY AUTO_INCREMENT, name TEXT);
53+
INSERT INTO test_table (name) VALUES ('Test that escaping a backslash \\ works');
54+
INSERT INTO test_table (name) VALUES ('Test that escaping multiple backslashes \\\\\\ works');
55+
INSERT INTO test_table (name) VALUES ('Test that escaping a character \a works');
56+
INSERT INTO test_table (name) VALUES ('Test that escaping a backslash followed by a character \\a works');
57+
INSERT INTO test_table (name) VALUES ('Test that escaping a backslash and a character \\\a works');
58+
"""
59+
When I run `wp sqlite --enable-ast-driver import test_import.sql`
60+
Then STDOUT should contain:
61+
"""
62+
Success: Imported from 'test_import.sql'.
63+
"""
64+
And the SQLite database should contain a table named "test_table"
65+
And the "test_table" should contain a row with name "Test that escaping a backslash \\ works"
66+
And the "test_table" should contain a row with name "Test that escaping multiple backslashes \\\\\\ works"
67+
And the "test_table" should contain a row with name "Test that escaping a character \a works"
68+
And the "test_table" should contain a row with name "Test that escaping a backslash followed by a character \\a works"
69+
And the "test_table" should contain a row with name "Test that escaping a backslash and a character \\\a works"

‎src/Import.php‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,16 @@ public function parse_statements( $sql_file_path ) {
102102
for ( $i = 0; $i < $strlen; $i++ ) {
103103
$ch = $line[ $i ];
104104

105-
// Handle escaped characters
106-
if ( $i > 0 && '\\' === $line[ $i - 1 ] ) {
105+
// Count preceding backslashes.
106+
$slashes = 0;
107+
while ( $slashes < $i && '\\' === $line[ $i - $slashes - 1 ] ) {
108+
++$slashes;
109+
}
110+
111+
// Handle escaped characters.
112+
// A characters is escaped only when the number of preceding backslashes
113+
// is odd - "\" is an escape sequence, "\\" is an escaped backslash.
114+
if ( 1 === $slashes % 2 ) {
107115
$buffer .= $ch;
108116
continue;
109117
}

0 commit comments

Comments
 (0)