Skip to content

Commit 182bf2c

Browse files
authored
Use the new MySQL-on-SQLite driver API (#33)
1 parent 94894fc commit 182bf2c

11 files changed

Lines changed: 208 additions & 75 deletions

‎AGENTS.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Imports a MySQL dump file into the SQLite database. Parses SQL statements using
1111
**Parameters:**
1212

1313
- `<file>` (required), Path to the SQL dump file. Use `-` to read from STDIN.
14-
- `[--enable-ast-driver]` Use the new AST-based `WP_SQLite_Driver` instead of the legacy `WP_SQLite_Translator` for full MySQL compatibility.
14+
- `[--enable-ast-driver]` Enable the AST driver on older integration plugin releases. The current `WP_MySQL_On_SQLite` API is selected automatically when available.
1515

1616
### `wp sqlite export [<file>]`
1717

@@ -23,7 +23,7 @@ Exports the SQLite database to a MySQL-compatible SQL dump file. Generates `DROP
2323
- `[--tables=<tables>]` Comma-separated list of tables to include. If omitted, all tables are exported.
2424
- `[--exclude_tables=<tables>]` Comma-separated list of tables to skip.
2525
- `[--porcelain]` Output only the filename (for scripting).
26-
- `[--enable-ast-driver]` Use the new AST-based driver.
26+
- `[--enable-ast-driver]` Enable the AST driver on older integration plugin releases.
2727

2828
### `wp sqlite tables`
2929

@@ -32,13 +32,13 @@ Lists all user tables in the SQLite database, excluding internal/system tables.
3232
**Parameters:**
3333

3434
- `[--format=<format>]` Output format: `list` (default, one table per line), `csv`, or `json`.
35-
- `[--enable-ast-driver]` Use the new AST-based driver.
35+
- `[--enable-ast-driver]` Enable the AST driver on older integration plugin releases.
3636

3737
## Tech Stack
3838

3939
- PHP >=7.4, WP-CLI package (`wp-cli/wp-cli ^2.5`)
4040
- WordPress SQLite Database Integration plugin, translation layer between MySQL queries and SQLite
41-
- Two driver modes: legacy `WP_SQLite_Translator` and new AST-based `WP_SQLite_Driver` (via `--enable-ast-driver`)
41+
- The PDO-based `WP_MySQL_On_SQLite` API is selected automatically when available; `WP_SQLite_Translator` and `WP_SQLite_Driver` remain as compatibility fallbacks for older integration plugin releases
4242

4343
## Directory Structure
4444

@@ -105,13 +105,13 @@ Runs lint, phpcs, phpunit, and behat sequentially.
105105
- `command.php` is the entry point, it registers `wp sqlite` as a WP-CLI command pointing to `SQLite_Command`
106106
- `SQLite_Command` delegates to `Import`, `Export`, and `Tables` classes
107107
- `SQLiteDatabaseIntegrationLoader::load_plugin()` bootstraps the WordPress SQLite Database Integration plugin, which MUST be loaded before any database operations
108-
- `SQLiteDriverFactory::create_driver()` creates the appropriate driver based on whether the AST driver is enabled
108+
- `SQLiteDriverFactory::create_driver()` creates the PDO-based `WP_MySQL_On_SQLite` driver when the class is available, with compatibility fallbacks for older integration plugin versions and the legacy translator
109109
- The import parser (`Import::parse_statements()`) is a streaming SQL parser using PHP generators, it handles quotes, comments, escape sequences, and multi-line statements character by character
110110

111111
## Common Pitfalls
112112

113113
- **MUST load the SQLite plugin first:** All database operations require `SQLiteDatabaseIntegrationLoader::load_plugin()` to be called before creating a driver. The driver depends on classes from the WordPress SQLite Database Integration plugin.
114-
- **Two driver APIs:** The legacy `WP_SQLite_Translator` and new `WP_SQLite_Driver` (AST) have different class names. Use `SQLiteDriverFactory::create_driver()` to get the correct one, do not instantiate drivers directly.
114+
- **Multiple driver APIs:** Always use `SQLiteDriverFactory::create_driver()`. It selects the PDO-based `WP_MySQL_On_SQLite` API when available and preserves compatibility with older AST drivers and the legacy translator.
115115
- **SQL parser edge cases:** The `Import::parse_statements()` method handles escape sequences, nested quotes, and multi-line comments manually. Changes to this parser MUST be tested with the existing Behat scenarios in `features/sqlite-import.feature`.
116116
- **Encoding handling:** Import attempts UTF-8 conversion as a fallback when queries fail. This is intentional error recovery, not a bug.
117117
- **`@when after_wp_config_load`:** All command methods use this WP-CLI hook annotation. New commands MUST include it to ensure WordPress config is loaded before execution.

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ $ wp sqlite import <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

2323
[--enable-ast-driver]
24-
Enables new AST driver for full MySQL compatibility.
24+
Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
2525

2626
### wp sqlite export
2727

@@ -46,7 +46,7 @@ $ wp sqlite export [<file>] [--tables=<tables>] [--exclude-tables] [--porcelain]
4646
Output filename for the exported database.
4747

4848
[--enable-ast-driver]
49-
Enables new AST driver for full MySQL compatibility.
49+
Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
5050

5151
### wp sqlite tables
5252

@@ -68,7 +68,7 @@ $ wp sqlite tables [--format=<list|csv>]
6868
---
6969

7070
[--enable-ast-driver]
71-
Enables new AST driver for full MySQL compatibility.
71+
Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
7272

7373
**EXAMPLES**
7474

‎features/bootstrap/SQLiteFeatureContext.php‎

Lines changed: 62 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
class SQLiteFeatureContext extends WPCLIFeatureContext implements Context {
1212

1313
private $db;
14+
private $comment_injection_table_name;
1415

1516
/**
1617
* @Given /^a SQL dump file named "([^"]*)" with content:$/
@@ -107,8 +108,13 @@ public function theSqliteDatabaseContainsSomeSampleData() {
107108
$this->connectToDatabase();
108109
$this->db->exec(
109110
"
110-
INSERT OR REPLACE INTO wp_posts (ID, post_title, post_content, post_type, post_status)
111-
VALUES (1, 'Sample Post', 'This is a sample post content.', 'post', 'publish');
111+
INSERT OR REPLACE INTO wp_posts (
112+
ID, post_title, post_content, post_excerpt, to_ping, pinged,
113+
post_content_filtered, post_type, post_status
114+
)
115+
VALUES (
116+
1, 'Sample Post', 'This is a sample post content.', '', '', '', '', 'post', 'publish'
117+
);
112118
"
113119
);
114120

@@ -274,25 +280,66 @@ public function theSqlStringEscapeBytesShouldBePreserved() {
274280
* @Given /^the SQLite database contains a test table with alphanumeric string hash values$/
275281
*/
276282
public function theSqliteDatabaseContainsATestTableWithAlphanumericStringHashValues() {
277-
$this->connectToDatabase();
278-
279-
// Create a test table with hash values that look like scientific notation
280-
$this->db->exec( 'DROP TABLE IF EXISTS test_export_alphanumeric_string' );
281-
$this->db->exec(
282-
'
283+
$this->create_file(
284+
'test_export_alphanumeric_string_setup.sql',
285+
"
286+
DROP TABLE IF EXISTS test_export_alphanumeric_string;
283287
CREATE TABLE test_export_alphanumeric_string (
284288
id INTEGER PRIMARY KEY,
285289
hash_value TEXT
286-
)
287-
'
290+
);
291+
INSERT INTO test_export_alphanumeric_string (id, hash_value) VALUES (1, '123e99');
292+
"
293+
);
294+
$this->wpcli_tests_invoke_proc(
295+
$this->proc( 'wp sqlite import test_export_alphanumeric_string_setup.sql' ),
296+
'run'
288297
);
298+
}
289299

290-
// Insert test data with values that might be mistaken for scientific notation
291-
$this->db->exec(
300+
/**
301+
* @Given /^the SQLite database contains a table with a backtick in its name$/
302+
*/
303+
public function theSqliteDatabaseContainsATableWithABacktickInItsName() {
304+
$this->create_file(
305+
'test_export_identifier_setup.sql',
292306
"
293-
INSERT INTO test_export_alphanumeric_string (id, hash_value) VALUES
294-
(1, '123e99')
295-
"
307+
DROP TABLE IF EXISTS `test``table`;
308+
CREATE TABLE `test``table` (id INTEGER PRIMARY KEY, value TEXT);
309+
INSERT INTO `test``table` (id, value) VALUES (1, 'Test value');
310+
"
311+
);
312+
$this->wpcli_tests_invoke_proc(
313+
$this->proc( 'wp sqlite import test_export_identifier_setup.sql' ),
314+
'run'
315+
);
316+
}
317+
318+
/**
319+
* @Given /^the SQLite database contains a table with a comment injection name$/
320+
*/
321+
public function theSqliteDatabaseContainsATableWithACommentInjectionName() {
322+
$this->connectToDatabase();
323+
324+
$this->comment_injection_table_name = "safe`\nDROP TABLE IF EXISTS wp_users; --\rtable";
325+
$quoted_table_name = '"' . str_replace( '"', '""', $this->comment_injection_table_name ) . '"';
326+
327+
$this->db->exec( "CREATE TABLE $quoted_table_name (id INTEGER PRIMARY KEY, value TEXT)" );
328+
$this->db->exec( "INSERT INTO $quoted_table_name (id, value) VALUES (1, 'Test value')" );
329+
}
330+
331+
/**
332+
* @When /^I export the table with a comment injection name$/
333+
*/
334+
public function iExportTheTableWithACommentInjectionName() {
335+
$this->wpcli_tests_invoke_proc(
336+
$this->proc(
337+
sprintf(
338+
'wp sqlite --enable-ast-driver export test_export_comment.sql --tables=%s',
339+
escapeshellarg( $this->comment_injection_table_name )
340+
)
341+
),
342+
'run'
296343
);
297344
}
298345
}

‎features/sqlite-export.feature‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,30 @@ Feature: WP-CLI SQLite Export Command
134134
INSERT INTO `test_export_alphanumeric_string` VALUES (1,123e99);
135135
"""
136136

137+
@require-sqlite
138+
Scenario: Export should quote table names containing backticks
139+
Given the SQLite database contains a table with a backtick in its name
140+
When I run `wp sqlite --enable-ast-driver export test_export_identifier.sql`
141+
Then the file "test_export_identifier.sql" should contain:
142+
"""
143+
DROP TABLE IF EXISTS `test``table`;
144+
"""
145+
And the file "test_export_identifier.sql" should contain:
146+
"""
147+
INSERT INTO `test``table` VALUES (1,'Test value');
148+
"""
149+
150+
@require-sqlite
151+
Scenario: Export should keep multiline table names inside comments
152+
Given the SQLite database contains a table with a comment injection name
153+
When I export the table with a comment injection name
154+
And I run `wp sqlite --enable-ast-driver import test_export_comment.sql`
155+
Then STDOUT should contain:
156+
"""
157+
Success: Imported from 'test_export_comment.sql'.
158+
"""
159+
And the SQLite database should contain a table named "wp_users"
160+
137161
@require-sqlite
138162
Scenario: Export should preserve serialized settings containing a NUL byte
139163
Given the SQLite database contains a serialized settings option with a NUL byte separator

‎phpstan/stubs.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ public function query( string $sql ) {}
2626
public function get_connection(): WP_SQLite_Connection {}
2727
}
2828

29+
// phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO -- Stub for the plugin's PDO subclass.
30+
class WP_MySQL_On_SQLite extends PDO {
31+
public function get_connection(): WP_SQLite_Connection {}
32+
}
33+
2934
class WP_SQLite_Translator {
3035
public function __construct() {}
3136
public function query( string $sql ) {}

‎src/Export.php‎

Lines changed: 53 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@
44
use Exception;
55
use PDO;
66
use WP_CLI;
7+
use WP_MySQL_On_SQLite;
78
use WP_SQLite_Driver;
89
use WP_SQLite_Translator;
910

1011
class Export {
1112
/**
1213
* The SQLite driver instance.
1314
*
14-
* @var WP_SQLite_Driver|WP_SQLite_Translator
15+
* @var WP_MySQL_On_SQLite|WP_SQLite_Driver|WP_SQLite_Translator
1516
*/
1617
protected $driver;
1718

@@ -85,8 +86,7 @@ protected function close_output_stream( $handle ) {
8586
protected function write_sql_statements( $handle ) {
8687
$include_tables = $this->get_include_tables();
8788
$exclude_tables = $this->get_exclude_tables();
88-
foreach ( $this->driver->query( 'SHOW TABLES' ) as $row ) {
89-
$table_name = array_values( (array) $row )[0];
89+
foreach ( $this->get_table_names() as $table_name ) {
9090

9191
// Skip tables that are not in the include_tables list if the list is defined
9292
if ( ! empty( $include_tables ) && ! in_array( $table_name, $include_tables, true ) ) {
@@ -111,6 +111,24 @@ protected function write_sql_statements( $handle ) {
111111
fwrite( $handle, sprintf( '-- Dump completed on %s', gmdate( 'c' ) ) );
112112
}
113113

114+
/**
115+
* Get the database table names.
116+
*
117+
* @return string[]
118+
*/
119+
protected function get_table_names() {
120+
$result = $this->driver->query( 'SHOW TABLES' );
121+
if ( $this->driver instanceof PDO ) {
122+
return $result->fetchAll( PDO::FETCH_COLUMN );
123+
}
124+
125+
$tables = array();
126+
foreach ( $result as $row ) {
127+
$tables[] = array_values( (array) $row )[0];
128+
}
129+
return $tables;
130+
}
131+
114132
/**
115133
* Write the create statement for a table to the output stream.
116134
*
@@ -120,9 +138,10 @@ protected function write_sql_statements( $handle ) {
120138
* @throws Exception
121139
*/
122140
protected function write_create_table_statement( $handle, $table_name ) {
123-
$comment = $this->get_dump_comment( sprintf( 'Table structure for table `%s`', $table_name ) );
141+
$quoted_table_name = $this->quote_identifier( $table_name );
142+
$comment = $this->get_dump_comment( sprintf( 'Table structure for table %s', $quoted_table_name ) );
124143
fwrite( $handle, $comment . PHP_EOL . PHP_EOL );
125-
fwrite( $handle, sprintf( 'DROP TABLE IF EXISTS `%s`;', $table_name ) . PHP_EOL );
144+
fwrite( $handle, sprintf( 'DROP TABLE IF EXISTS %s;', $quoted_table_name ) . PHP_EOL );
126145
fwrite( $handle, $this->get_create_statement( $table_name ) . PHP_EOL );
127146
}
128147

@@ -140,7 +159,7 @@ protected function write_insert_statements( $handle, $table_name ) {
140159
return;
141160
}
142161

143-
$comment = $this->get_dump_comment( sprintf( 'Dumping data for table `%s`', $table_name ) );
162+
$comment = $this->get_dump_comment( sprintf( 'Dumping data for table %s', $this->quote_identifier( $table_name ) ) );
144163
fwrite( $handle, $comment . PHP_EOL . PHP_EOL );
145164
foreach ( $this->get_insert_statements( $table_name ) as $insert_statement ) {
146165
fwrite( $handle, $insert_statement . PHP_EOL );
@@ -158,13 +177,14 @@ protected function write_insert_statements( $handle, $table_name ) {
158177
* @throws Exception
159178
*/
160179
protected function get_create_statement( $table_name ) {
161-
$table_name = $this->driver instanceof WP_SQLite_Driver
162-
? $this->driver->get_connection()->quote_identifier( $table_name )
163-
: $table_name;
180+
$create = $this->driver->query( 'SHOW CREATE TABLE ' . $this->quote_identifier( $table_name ) );
181+
if ( $this->driver instanceof PDO ) {
182+
$sql = $create->fetchColumn( 1 );
183+
return rtrim( $sql, ';' ) . ";\n";
184+
}
164185

165-
$create = $this->driver->query( 'SHOW CREATE TABLE ' . $table_name );
166-
$sql = $create[0]->{'Create Table'};
167-
$sql = rtrim( $sql, ';' ); // The old SQLite driver appends a semicolon.
186+
$sql = $create[0]->{'Create Table'};
187+
$sql = rtrim( $sql, ';' ); // The old SQLite driver appends a semicolon.
168188
return $sql . ";\n";
169189
}
170190

@@ -176,12 +196,11 @@ protected function get_create_statement( $table_name ) {
176196
* @return \Generator
177197
*/
178198
protected function get_insert_statements( $table_name ) {
179-
$pdo = $this->get_pdo();
180-
$stmt = $pdo->prepare( 'SELECT * FROM ' . $table_name );
181-
$stmt->execute();
199+
$quoted_table_name = $this->quote_identifier( $table_name );
200+
$stmt = $this->get_sqlite_pdo()->query( 'SELECT * FROM ' . $quoted_table_name );
182201
// phpcs:ignore
183202
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT ) ) {
184-
yield sprintf( 'INSERT INTO `%1s` VALUES (%2s);', $table_name, $this->escape_values( $pdo, $row ) );
203+
yield sprintf( 'INSERT INTO %1s VALUES (%2s);', $quoted_table_name, $this->escape_values( $row ) );
185204
}
186205
}
187206

@@ -228,13 +247,11 @@ protected function get_include_tables() {
228247
/**
229248
* Escape values for insert statement
230249
*
231-
* @param PDO $pdo
232250
* @param $values
233251
*
234252
* @return string
235253
*/
236-
protected function escape_values( PDO $pdo, $values ) {
237-
// Get a mysql PDO instance
254+
protected function escape_values( $values ) {
238255
$escaped_values = [];
239256
foreach ( $values as $value ) {
240257
if ( is_null( $value ) ) {
@@ -278,9 +295,11 @@ protected function escape_string( $value ) {
278295
* @return string
279296
*/
280297
protected function get_dump_comment( $comment ) {
298+
$comment = str_replace( array( "\r\n", "\r" ), "\n", $comment );
299+
281300
return implode(
282301
"\n",
283-
array( '--', sprintf( '-- %s', $comment ), '--' )
302+
array( '--', sprintf( '-- %s', str_replace( "\n", "\n-- ", $comment ) ), '--' )
284303
);
285304
}
286305

@@ -292,18 +311,27 @@ protected function get_dump_comment( $comment ) {
292311
* @return bool
293312
*/
294313
protected function table_has_records( $table_name ) {
295-
$pdo = $this->get_pdo();
296-
$stmt = $pdo->prepare( 'SELECT COUNT(*) FROM ' . $table_name );
297-
$stmt->execute();
314+
$table_name = $this->quote_identifier( $table_name );
315+
$stmt = $this->get_sqlite_pdo()->query( 'SELECT COUNT(*) FROM ' . $table_name );
298316
return $stmt->fetchColumn() > 0;
299317
}
300318

301319
/**
302-
* Get the PDO instance.
320+
* Quote a MySQL identifier.
321+
*
322+
* @param string $identifier Identifier to quote.
323+
* @return string
324+
*/
325+
protected function quote_identifier( $identifier ) {
326+
return '`' . str_replace( '`', '``', $identifier ) . '`';
327+
}
328+
329+
/**
330+
* Get the underlying SQLite PDO instance.
303331
*
304332
* @return PDO
305333
*/
306-
protected function get_pdo() {
334+
protected function get_sqlite_pdo() {
307335
if ( $this->driver instanceof WP_SQLite_Translator ) {
308336
return $this->driver->get_pdo();
309337
}

0 commit comments

Comments
 (0)