Skip to content

Commit c20c446

Browse files
committed
Use the MySQL-on-SQLite PDO API
Load and instantiate WP_MySQL_On_SQLite automatically when it is available while retaining the flag-controlled fallbacks for older plugin layouts. Adapt query results, documentation, and fixtures to the PDO API.
1 parent 94894fc commit c20c446

10 files changed

Lines changed: 118 additions & 67 deletions

File tree

‎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: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,13 @@ public function theSqliteDatabaseContainsSomeSampleData() {
107107
$this->connectToDatabase();
108108
$this->db->exec(
109109
"
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');
110+
INSERT OR REPLACE INTO wp_posts (
111+
ID, post_title, post_content, post_excerpt, to_ping, pinged,
112+
post_content_filtered, post_type, post_status
113+
)
114+
VALUES (
115+
1, 'Sample Post', 'This is a sample post content.', '', '', '', '', 'post', 'publish'
116+
);
112117
"
113118
);
114119

@@ -274,25 +279,20 @@ public function theSqlStringEscapeBytesShouldBePreserved() {
274279
* @Given /^the SQLite database contains a test table with alphanumeric string hash values$/
275280
*/
276281
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-
'
282+
$this->create_file(
283+
'test_export_alphanumeric_string_setup.sql',
284+
"
285+
DROP TABLE IF EXISTS test_export_alphanumeric_string;
283286
CREATE TABLE test_export_alphanumeric_string (
284287
id INTEGER PRIMARY KEY,
285288
hash_value TEXT
286-
)
287-
'
288-
);
289-
290-
// Insert test data with values that might be mistaken for scientific notation
291-
$this->db->exec(
289+
);
290+
INSERT INTO test_export_alphanumeric_string (id, hash_value) VALUES (1, '123e99');
292291
"
293-
INSERT INTO test_export_alphanumeric_string (id, hash_value) VALUES
294-
(1, '123e99')
295-
"
292+
);
293+
$this->wpcli_tests_invoke_proc(
294+
$this->proc( 'wp sqlite import test_export_alphanumeric_string_setup.sql' ),
295+
'run'
296296
);
297297
}
298298
}

‎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: 36 additions & 15 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
*
@@ -158,6 +176,13 @@ protected function write_insert_statements( $handle, $table_name ) {
158176
* @throws Exception
159177
*/
160178
protected function get_create_statement( $table_name ) {
179+
if ( $this->driver instanceof PDO ) {
180+
$table_name = '`' . str_replace( '`', '``', $table_name ) . '`';
181+
$create = $this->driver->query( 'SHOW CREATE TABLE ' . $table_name );
182+
$sql = $create->fetchColumn( 1 );
183+
return rtrim( $sql, ';' ) . ";\n";
184+
}
185+
161186
$table_name = $this->driver instanceof WP_SQLite_Driver
162187
? $this->driver->get_connection()->quote_identifier( $table_name )
163188
: $table_name;
@@ -176,12 +201,11 @@ protected function get_create_statement( $table_name ) {
176201
* @return \Generator
177202
*/
178203
protected function get_insert_statements( $table_name ) {
179-
$pdo = $this->get_pdo();
180-
$stmt = $pdo->prepare( 'SELECT * FROM ' . $table_name );
181-
$stmt->execute();
204+
$quoted_table_name = '`' . str_replace( '`', '``', $table_name ) . '`';
205+
$stmt = $this->get_sqlite_pdo()->query( 'SELECT * FROM ' . $quoted_table_name );
182206
// phpcs:ignore
183207
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 ) );
208+
yield sprintf( 'INSERT INTO `%1s` VALUES (%2s);', $table_name, $this->escape_values( $row ) );
185209
}
186210
}
187211

@@ -228,13 +252,11 @@ protected function get_include_tables() {
228252
/**
229253
* Escape values for insert statement
230254
*
231-
* @param PDO $pdo
232255
* @param $values
233256
*
234257
* @return string
235258
*/
236-
protected function escape_values( PDO $pdo, $values ) {
237-
// Get a mysql PDO instance
259+
protected function escape_values( $values ) {
238260
$escaped_values = [];
239261
foreach ( $values as $value ) {
240262
if ( is_null( $value ) ) {
@@ -292,18 +314,17 @@ protected function get_dump_comment( $comment ) {
292314
* @return bool
293315
*/
294316
protected function table_has_records( $table_name ) {
295-
$pdo = $this->get_pdo();
296-
$stmt = $pdo->prepare( 'SELECT COUNT(*) FROM ' . $table_name );
297-
$stmt->execute();
317+
$table_name = '`' . str_replace( '`', '``', $table_name ) . '`';
318+
$stmt = $this->get_sqlite_pdo()->query( 'SELECT COUNT(*) FROM ' . $table_name );
298319
return $stmt->fetchColumn() > 0;
299320
}
300321

301322
/**
302-
* Get the PDO instance.
323+
* Get the underlying SQLite PDO instance.
303324
*
304325
* @return PDO
305326
*/
306-
protected function get_pdo() {
327+
protected function get_sqlite_pdo() {
307328
if ( $this->driver instanceof WP_SQLite_Translator ) {
308329
return $this->driver->get_pdo();
309330
}

‎src/Import.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@
44
use Exception;
55
use Generator;
66
use WP_CLI;
7+
use WP_MySQL_On_SQLite;
8+
use WP_SQLite_Driver;
79
use WP_SQLite_Translator;
810

911
class Import {
1012
/**
1113
* The SQLite driver instance.
1214
*
13-
* @var WP_SQLite_Driver|WP_SQLite_Translator
15+
* @var WP_MySQL_On_SQLite|WP_SQLite_Driver|WP_SQLite_Translator
1416
*/
1517
protected $driver;
1618

‎src/SQLiteDatabaseIntegrationLoader.php‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,18 +81,25 @@ public static function load_plugin() {
8181
define( 'SQLITE_DB_DROPIN_VERSION', $sqlite_plugin_version ); // phpcs:ignore
8282
}
8383

84-
$new_driver_enabled = defined( 'WP_SQLITE_AST_DRIVER' ) && WP_SQLITE_AST_DRIVER;
85-
$old_structure = file_exists( $plugin_directory . '/php-polyfills.php' );
84+
$old_structure = file_exists( $plugin_directory . '/php-polyfills.php' );
8685

8786
if ( $old_structure ) {
8887
require_once $plugin_directory . '/php-polyfills.php';
8988
}
9089
require_once $plugin_directory . '/constants.php';
9190

91+
$mysql_on_sqlite_class_file = $plugin_directory . '/wp-includes/database/sqlite/class-wp-mysql-on-sqlite.php';
92+
$mysql_on_sqlite_loader_file = $plugin_directory . '/wp-includes/database/load.php';
93+
if ( file_exists( $mysql_on_sqlite_class_file ) && file_exists( $mysql_on_sqlite_loader_file ) ) {
94+
require_once $mysql_on_sqlite_loader_file;
95+
return;
96+
}
97+
98+
$new_driver_enabled = defined( 'WP_SQLITE_AST_DRIVER' ) && WP_SQLITE_AST_DRIVER;
9299
if ( $new_driver_enabled && file_exists( $plugin_directory . '/wp-pdo-mysql-on-sqlite.php' ) ) {
93100
require_once $plugin_directory . '/wp-pdo-mysql-on-sqlite.php';
94-
} elseif ( $new_driver_enabled && file_exists( $plugin_directory . '/wp-includes/database/load.php' ) ) {
95-
require_once $plugin_directory . '/wp-includes/database/load.php';
101+
} elseif ( $new_driver_enabled && file_exists( $mysql_on_sqlite_loader_file ) ) {
102+
require_once $mysql_on_sqlite_loader_file;
96103
} elseif ( $new_driver_enabled ) {
97104
require_once $plugin_directory . '/version.php';
98105
require_once $plugin_directory . '/wp-includes/parser/class-wp-parser-grammar.php';

‎src/SQLiteDriverFactory.php‎

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Automattic\WP_CLI\SQLite;
44

5+
use PDO;
6+
use WP_MySQL_On_SQLite;
57
use WP_SQLite_Connection;
68
use WP_SQLite_Driver;
79
use WP_SQLite_Translator;
@@ -10,25 +12,32 @@ class SQLiteDriverFactory {
1012
/**
1113
* Create an instance of the SQLite driver.
1214
*
13-
* @return WP_SQLite_Driver|WP_SQLite_Translator
15+
* @return WP_MySQL_On_SQLite|WP_SQLite_Driver|WP_SQLite_Translator
1416
*/
1517
public static function create_driver() {
16-
$new_driver_enabled = defined( 'WP_SQLITE_AST_DRIVER' ) && WP_SQLITE_AST_DRIVER;
18+
$db_name = defined( 'DB_NAME' ) && '' !== DB_NAME ? DB_NAME : 'database_name_here';
1719

18-
if ( $new_driver_enabled ) {
19-
$connection = new WP_SQLite_Connection(
20-
array(
21-
'path' => FQDB,
22-
)
20+
if ( class_exists( WP_MySQL_On_SQLite::class ) ) {
21+
$database_dsn = sprintf(
22+
'mysql-on-sqlite:path=%s;dbname=%s',
23+
str_replace( ';', ';;', FQDB ),
24+
str_replace( ';', ';;', $db_name )
2325
);
24-
if ( defined( 'DB_NAME' ) && '' !== DB_NAME ) {
25-
$db_name = DB_NAME;
26-
} else {
27-
$db_name = 'database_name_here';
28-
}
29-
return new WP_SQLite_Driver( $connection, $db_name );
26+
$driver = new WP_MySQL_On_SQLite( $database_dsn );
27+
$driver->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true );
28+
return $driver;
29+
}
30+
31+
$new_driver_enabled = defined( 'WP_SQLITE_AST_DRIVER' ) && WP_SQLITE_AST_DRIVER;
32+
if ( ! $new_driver_enabled ) {
33+
return new WP_SQLite_Translator();
3034
}
3135

32-
return new WP_SQLite_Translator();
36+
$connection = new WP_SQLite_Connection(
37+
array(
38+
'path' => FQDB,
39+
)
40+
);
41+
return new WP_SQLite_Driver( $connection, $db_name );
3342
}
3443
}

‎src/SQLite_Command.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class SQLite_Command extends WP_CLI_Command {
1717
* : The name of the SQL file to import. If '-', then reads from STDIN. If omitted, it will look for '{dbname}.sql'.
1818
*
1919
* [--enable-ast-driver]
20-
* : Enables new AST driver for full MySQL compatibility.
20+
* : Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
2121
*
2222
* ## EXAMPLES
2323
* # Import the database from a file
@@ -65,7 +65,7 @@ public function import( $args, $assoc_args ) {
6565
* : Output filename for the exported database.
6666
*
6767
* [--enable-ast-driver]
68-
* : Enables new AST driver for full MySQL compatibility.
68+
* : Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
6969
*
7070
* ## EXAMPLES
7171
* # Export the database to a file
@@ -138,7 +138,7 @@ public function export( $args, $assoc_args ) {
138138
* ---
139139
*
140140
* [--enable-ast-driver]
141-
* : Enables new AST driver for full MySQL compatibility.
141+
* : Enables the AST driver for older integration plugin releases. The current driver API is selected automatically.
142142
*
143143
* ## EXAMPLES
144144
*

0 commit comments

Comments
 (0)