PluginProbe
SQLite Database Integration / 3.1.0
SQLite Database Integration v3.1.0
3.1.0 3.0.2 3.0.1 trunk 2.1.13 2.1.14 2.1.15 2.1.16 2.2.0 2.2.1 2.2.10 2.2.11 2.2.12 2.2.13 2.2.14 2.2.15 2.2.16 2.2.17 2.2.18 2.2.19 2.2.2 2.2.20 2.2.21 2.2.22 2.2.23 All 33 releases
← All changes | wp-includes/sqlite/class-wp-sqlite-db.php +331 -197 2.2.13 → 3.1.0 View file →
@@ -1,10 +1,7 @@
1 1 <?php
2 2 /**
3 3 * Extend and replace the wpdb class.
4 - *
5 - * @package wp-sqlite-integration
6 - * @since 1.0.0
7 4 */
8 5
9 6 /**
10 7 * This class extends wpdb and replaces it.
@@ -15,9 +12,9 @@
15 12
16 13 /**
17 14 * Database Handle
18 15 *
19 - * @var WP_SQLite_Translator
16 + * @var WP_MySQL_On_SQLite
20 17 */
21 18 protected $dbh;
22 19
23 20 /**
@@ -51,13 +48,29 @@
51 48 * which creates a circular dependency.
52 49 */
53 50 $GLOBALS['wpdb'] = $this;
54 51
52 + // The SQLite driver may use the charset and collation while connecting.
53 + $this->init_charset();
54 +
55 55 parent::__construct( '', '', $dbname, '' );
56 - $this->charset = 'utf8mb4';
57 56 }
58 57
59 58 /**
59 + * Returns the active MySQL-on-SQLite driver.
60 + *
61 + * @return WP_MySQL_On_SQLite The active driver.
62 + * @throws RuntimeException When there is no active database connection.
63 + */
64 + public function get_driver(): WP_MySQL_On_SQLite {
65 + if ( ! $this->dbh ) {
66 + throw new RuntimeException( 'Cannot access the driver without an active database connection.' );
67 + }
68 +
69 + return $this->dbh;
70 + }
71 +
72 + /**
60 73 * Method to set character set for the database.
61 74 *
62 75 * This overrides wpdb::set_charset(), only to dummy out the MySQL function.
63 76 *
@@ -70,22 +83,64 @@
70 83 public function set_charset( $dbh, $charset = null, $collate = null ) {
71 84 }
72 85
73 86 /**
74 - * Method to get the character set for the database.
75 - * Hardcoded to utf8mb4 for now.
87 + * Retrieves the character set for the given column.
76 88 *
77 - * @param string $table The table name.
78 - * @param string $column The column name.
89 + * This overrides wpdb::get_col_charset() to enable the parent's implementation
90 + * for SQLite by temporarily setting the is_mysql flag.
79 91 *
80 - * @return string The character set.
92 + * @see wpdb::get_col_charset()
93 + *
94 + * @param string $table Table name.
95 + * @param string $column Column name.
96 + * @return string|false|WP_Error Column character set as a string. False if the column has
97 + * no character set. WP_Error object on failure.
81 98 */
82 99 public function get_col_charset( $table, $column ) {
83 - // Hardcoded for now.
84 - return 'utf8mb4';
100 + $original_is_mysql = $this->is_mysql ?? null;
101 +
102 + /*
103 + * The parent method returns early when `$this->is_mysql` is falsy.
104 + * Since SQLite doesn't set this flag, we enable it temporarily so
105 + * the parent can run its full logic — querying column metadata via
106 + * SHOW FULL COLUMNS (which the SQLite driver translates) and
107 + * populating the `$this->col_meta` cache.
108 + */
109 + try {
110 + $this->is_mysql = true;
111 + return parent::get_col_charset( $table, $column );
112 + } finally {
113 + $this->is_mysql = $original_is_mysql;
114 + }
85 115 }
86 116
87 117 /**
118 + * Retrieves the maximum string length allowed in a given column.
119 + *
120 + * This overrides wpdb::get_col_length() to enable the parent's implementation
121 + * for SQLite by temporarily setting the is_mysql flag.
122 + *
123 + * @see wpdb::get_col_length()
124 + *
125 + * @param string $table Table name.
126 + * @param string $column Column name.
127 + * @return array|false|WP_Error Column length information, false if the column has
128 + * no length. WP_Error object on failure.
129 + */
130 + public function get_col_length( $table, $column ) {
131 + $original_is_mysql = $this->is_mysql ?? null;
132 +
133 + // See get_col_charset() for an explanation of the is_mysql flag.
134 + try {
135 + $this->is_mysql = true;
136 + return parent::get_col_length( $table, $column );
137 + } finally {
138 + $this->is_mysql = $original_is_mysql;
139 + }
140 + }
141 +
142 + /**
88 143 * Changes the current SQL mode, and ensures its WordPress compatibility.
89 144 *
90 145 * If no modes are passed, it will ensure the current MySQL server modes are compatible.
91 146 *
@@ -93,14 +148,10 @@
93 148 *
94 149 * @param array $modes Optional. A list of SQL modes to set. Default empty array.
95 150 */
96 151 public function set_sql_mode( $modes = array() ) {
97 - if ( ! $this->dbh instanceof WP_SQLite_Driver ) {
98 - return;
99 - }
100 -
101 152 if ( empty( $modes ) ) {
102 - $result = $this->dbh->query( 'SELECT @@SESSION.sql_mode' );
153 + $result = $this->dbh->query( 'SELECT @@SESSION.sql_mode' )->fetchAll( PDO::FETCH_OBJ ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
103 154 if ( ! isset( $result[0] ) ) {
104 155 return;
105 156 }
106 157
@@ -133,17 +184,113 @@
133 184 }
134 185
135 186 /**
136 187 * Closes the current database connection.
137 - * Noop in SQLite.
138 188 *
139 - * @return bool True to indicate the connection was successfully closed.
189 + * This overrides wpdb::close() while closely mirroring its implementation.
190 + *
191 + * @see wpdb::close()
192 + *
193 + * @return bool True if the connection was successfully closed,
194 + * false if it wasn't, or if the connection doesn't exist.
140 195 */
141 196 public function close() {
197 + if ( ! $this->dbh ) {
198 + return false;
199 + }
200 +
201 + $connection = $this->dbh->get_connection();
202 + $pdo = $connection->get_pdo();
203 +
204 + try {
205 + if ( $this->dbh->inTransaction() ) {
206 + $this->dbh->rollBack();
207 + } elseif ( $pdo->inTransaction() ) {
208 + $pdo->rollBack();
209 + } else {
210 + /*
211 + * On PHP < 8.4, PDO cannot detect transactions started via SQL.
212 + * A savepoint ensures ROLLBACK succeeds with or without one.
213 + */
214 + $pdo->exec( 'SAVEPOINT wp_sqlite_db_close' );
215 + $pdo->exec( 'ROLLBACK' );
216 + }
217 + } catch ( Throwable $e ) {
218 + return false;
219 + }
220 +
221 + if (
222 + isset( $GLOBALS['@pdo'] )
223 + && $GLOBALS['@pdo'] === $pdo
224 + ) {
225 + unset( $GLOBALS['@pdo'] );
226 + }
227 +
228 + $connection->set_query_logger( null );
229 + $this->result = null;
230 + $this->dbh = null;
231 + $this->ready = false;
232 + $this->has_connected = false;
233 +
142 234 return true;
143 235 }
144 236
145 237 /**
238 + * Sets $this->charset and $this->collate.
239 + *
240 + * This overrides wpdb::init_charset(). SQLite stores all text as UTF-8, and
241 + * the emulated MySQL connection always uses utf8mb4 (see set_charset()), so
242 + * the charset is always utf8mb4, and only a UTF-8 DB_COLLATE applies.
243 + *
244 + * Unlike in wpdb, the result doesn't depend on the database connection.
245 + * This is important, as the SQLite driver may use the charset and collation
246 + * while connecting (see the constructor).
247 + *
248 + * @see wpdb::init_charset()
249 + */
250 + public function init_charset() {
251 + $collate = defined( 'DB_COLLATE' ) ? strtolower( (string) DB_COLLATE ) : '';
252 +
253 + // MySQL 8.0.30 and newer name the utf8 collations "utf8mb3_*".
254 + $collate = preg_replace( '/^utf8mb3_/', 'utf8_', $collate );
255 +
256 + // Collations of other charsets don't apply to the utf8mb4 connection.
257 + if ( ! preg_match( '/^utf8(mb4)?_/', $collate ) ) {
258 + $collate = '';
259 + }
260 +
261 + $charset_collate = $this->resolve_charset( 'utf8mb4', $collate );
262 +
263 + $this->charset = $charset_collate['charset'];
264 + $this->collate = $charset_collate['collate'];
265 + }
266 +
267 + /**
268 + * Determines the best charset and collation to use given a charset and collation.
269 + *
270 + * For example, when able, utf8mb4 should be used instead of utf8.
271 + *
272 + * This overrides wpdb::determine_charset() while closely mirroring its implementation.
273 + * The override is needed because the parent checks for a mysqli connection object.
274 + *
275 + * @param string $charset The character set to check.
276 + * @param string $collate The collation to check.
277 + * @return array {
278 + * The most appropriate character set and collation to use.
279 + *
280 + * @type string $charset Character set.
281 + * @type string $collate Collation.
282 + * }
283 + */
284 + public function determine_charset( $charset, $collate ) {
285 + if ( ! $this->dbh ) {
286 + return compact( 'charset', 'collate' );
287 + }
288 +
289 + return $this->resolve_charset( $charset, $collate );
290 + }
291 +
292 + /**
146 293 * Method to select the database connection.
147 294 *
148 295 * This overrides wpdb::select(), only to dummy out the MySQL function.
149 296 *
@@ -165,37 +312,23 @@
165 312 *
166 313 * @param string $data The string to escape.
167 314 *
168 315 * @return string escaped
316 + * @throws RuntimeException When the database connection is not initialized.
169 317 */
170 318 public function _real_escape( $data ) {
171 319 if ( ! is_scalar( $data ) ) {
172 320 return '';
173 321 }
174 - $escaped = addslashes( $data );
175 - return $this->add_placeholder_escape( $escaped );
176 - }
177 322
178 - /**
179 - * Method to dummy out wpdb::esc_like() function.
180 - *
181 - * WordPress 4.0.0 introduced esc_like() function that adds backslashes to %,
182 - * underscore and backslash, which is not interpreted as escape character
183 - * by SQLite. So we override it and dummy out this function.
184 - *
185 - * @param string $text The raw text to be escaped. The input typed by the user should have no
186 - * extra or deleted slashes.
187 - *
188 - * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
189 - * or real_escape next.
190 - */
191 - public function esc_like( $text ) {
192 - // The new driver adds "ESCAPE '\\'" to every LIKE expression by default.
193 - // We only need to overload this function to a no-op for the old driver.
194 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
195 - return parent::esc_like( $text );
323 + if ( ! $this->dbh ) {
324 + throw new RuntimeException( 'Cannot escape data without an active database connection.' );
196 325 }
197 - return $text;
326 +
327 + // Escape the string without bounding quotes to mirror mysqli_real_escape_string().
328 + $quoted = $this->dbh->quote( (string) $data );
329 + $escaped = substr( $quoted, 1, -1 );
330 + return $this->add_placeholder_escape( $escaped );
198 331 }
199 332
200 333 /**
201 334 * Prints SQL/DB error.
@@ -293,79 +426,83 @@
293 426 *
294 427 * @see wpdb::db_connect()
295 428 *
296 429 * @param bool $allow_bail Not used.
297 - * @return void
430 + * @return bool True on a successful connection, false on failure.
298 431 */
299 432 public function db_connect( $allow_bail = true ) {
300 433 if ( $this->dbh ) {
301 - return;
434 + return $this->ready;
302 435 }
303 - $this->init_charset();
304 436
305 - $pdo = null;
437 + $this->last_error = '';
306 438 if ( isset( $GLOBALS['@pdo'] ) ) {
307 - $pdo = $GLOBALS['@pdo'];
439 + trigger_error(
440 + 'PDO injection via $GLOBALS[\'@pdo\'] is no longer supported. The existing PDO will be ignored and a new connection will be created.',
441 + E_USER_WARNING
442 + );
308 443 }
309 - if ( defined( 'WP_SQLITE_AST_DRIVER' ) && WP_SQLITE_AST_DRIVER ) {
310 - if ( null === $this->dbname || '' === $this->dbname ) {
311 - $this->bail(
312 - 'The database name was not set. The SQLite driver requires a database name to be set to emulate MySQL information schema tables.',
313 - 'db_connect_fail'
314 - );
315 - return false;
316 - }
317 444
318 - require_once __DIR__ . '/../../wp-includes/parser/class-wp-parser-grammar.php';
319 - require_once __DIR__ . '/../../wp-includes/parser/class-wp-parser.php';
320 - require_once __DIR__ . '/../../wp-includes/parser/class-wp-parser-node.php';
321 - require_once __DIR__ . '/../../wp-includes/parser/class-wp-parser-token.php';
322 - require_once __DIR__ . '/../../wp-includes/mysql/class-wp-mysql-token.php';
323 - require_once __DIR__ . '/../../wp-includes/mysql/class-wp-mysql-lexer.php';
324 - require_once __DIR__ . '/../../wp-includes/mysql/class-wp-mysql-parser.php';
325 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-connection.php';
326 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-configurator.php';
327 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-driver.php';
328 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-driver-exception.php';
329 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-information-schema-builder.php';
330 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-information-schema-exception.php';
331 - require_once __DIR__ . '/../../wp-includes/sqlite-ast/class-wp-sqlite-information-schema-reconstructor.php';
332 - $this->ensure_database_directory( FQDB );
445 + if ( null === $this->dbname || '' === $this->dbname ) {
446 + $this->bail(
447 + 'The database name was not set. The SQLite driver requires a database name to be set to emulate MySQL information schema tables.',
448 + 'db_connect_fail'
449 + );
450 + return false;
451 + }
333 452
334 - try {
335 - $connection = new WP_SQLite_Connection(
336 - array(
337 - 'pdo' => $pdo,
338 - 'path' => FQDB,
339 - 'journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
340 - )
341 - );
342 - $this->dbh = new WP_SQLite_Driver( $connection, $this->dbname );
343 - $GLOBALS['@pdo'] = $this->dbh->get_connection()->get_pdo();
344 - } catch ( Throwable $e ) {
345 - $this->last_error = $this->format_error_message( $e );
346 - }
347 - } else {
348 - $this->dbh = new WP_SQLite_Translator( $pdo );
349 - $this->last_error = $this->dbh->get_error_message();
350 - $GLOBALS['@pdo'] = $this->dbh->get_pdo();
453 + try {
454 + $options = array(
455 + 'sqlite_journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
456 + );
457 + $dbh = new WP_MySQL_On_SQLite(
458 + sprintf(
459 + 'mysql-on-sqlite:path=%s;dbname=%s',
460 + str_replace( ';', ';;', DB_PATH ),
461 + str_replace( ';', ';;', $this->dbname )
462 + ),
463 + null,
464 + null,
465 + $options
466 + );
467 + $dbh->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
468 + $this->dbh = $dbh;
469 +
470 + /**
471 + * Exposes the underlying PDO SQLite connection for backward compatibility.
472 + *
473 + * @deprecated 3.0.0 Use WP_SQLite_DB::get_driver() with
474 + * WP_MySQL_On_SQLite::get_sqlite_pdo() instead.
475 + */
476 + $GLOBALS['@pdo'] = $dbh->get_sqlite_pdo();
477 + } catch ( Throwable $e ) {
478 + $this->last_error = $this->format_error_message( $e );
351 479 }
352 480 if ( $this->last_error ) {
353 481 return false;
354 482 }
483 +
484 + $this->has_connected = true;
485 + $this->set_charset( $this->dbh );
486 +
355 487 $this->ready = true;
356 488 $this->set_sql_mode();
489 + return true;
357 490 }
358 491
359 492 /**
360 - * Method to dummy out wpdb::check_connection()
493 + * Checks that the database connection is available.
361 494 *
362 495 * @param bool $allow_bail Not used.
363 496 *
364 - * @return bool
497 + * @return bool True when the connection is available, false otherwise.
365 498 */
366 499 public function check_connection( $allow_bail = true ) {
367 - return true;
500 + if ( $this->dbh ) {
501 + return true;
502 + }
503 +
504 + return $this->db_connect( $allow_bail );
368 505 }
369 506
370 507 /**
371 508 * Prepares a SQL query for safe execution.
@@ -414,8 +551,9 @@
414 551 $this->hide_errors();
415 552 }
416 553
417 554 if ( ! $this->ready ) {
555 + $this->check_current_query = true;
418 556 return false;
419 557 }
420 558
421 559 $query = apply_filters( 'query', $query );
@@ -429,24 +567,32 @@
429 567
430 568 // Log how the function was called.
431 569 $this->func_call = "\$db->query(\"$query\")";
432 570
571 + /*
572 + * Mirror wpdb's query text validation.
573 + * TODO: Add full charset enforcement to MySQL on SQLite, where column
574 + * types and SQL mode are known, so all callers are protected.
575 + */
576 + if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
577 + $stripped_query = $this->strip_invalid_text_from_query( $query );
578 + // Charset discovery can run queries, so clear their results.
579 + $this->flush();
580 + if ( $stripped_query !== $query ) {
581 + $this->insert_id = 0;
582 + $this->last_query = $query;
583 + wp_load_translations_early();
584 + $this->last_error = __( 'WordPress database error: Could not perform query because it contains invalid data.' );
585 + return false;
586 + }
587 + }
588 + $this->check_current_query = true;
589 +
433 590 // Keep track of the last query for debug.
434 591 $this->last_query = $query;
435 592
436 - // Save the query count before running another query.
593 + // Save the query count after any charset discovery queries.
437 594 $last_query_count = count( $this->queries ?? array() );
438 -
439 - /*
440 - * @TODO: WPDB uses "$this->check_current_query" to check table/column
441 - * charset and strip all invalid characters from the query.
442 - * This is an involved process that we can bypass for SQLite,
443 - * if we simply strip all invalid UTF-8 characters from the query.
444 - *
445 - * To do so, mb_convert_encoding can be used with an optional
446 - * fallback to a htmlspecialchars method. E.g.:
447 - * https://github.com/nette/utils/blob/be534713c227aeef57ce1883fc17bc9f9e29eca2/src/Utils/Strings.php#L42
448 - */
449 595 $this->_do_query( $query );
450 596
451 597 if ( $this->last_error ) {
452 598 // Clear insert_id on a subsequent failed insert.
@@ -460,17 +606,13 @@
460 606
461 607 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
462 608 $return_val = true;
463 609 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
464 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
465 - $this->rows_affected = $this->dbh->get_last_return_value();
466 - } else {
467 - $this->rows_affected = $this->dbh->get_affected_rows();
468 - }
610 + $this->rows_affected = $this->result->rowCount();
469 611
470 612 // Take note of the insert_id.
471 613 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
472 - $this->insert_id = $this->dbh->get_insert_id();
614 + $this->insert_id = (int) $this->dbh->lastInsertId();
473 615 }
474 616
475 617 // Return number of rows affected.
476 618 $return_val = $this->rows_affected;
@@ -476,11 +618,11 @@
476 618 $return_val = $this->rows_affected;
477 619 } else {
478 620 $num_rows = 0;
479 621
480 - if ( is_array( $this->result ) ) {
481 - $this->last_result = $this->result;
482 - $num_rows = count( $this->result );
622 + if ( $this->result->columnCount() > 0 ) {
623 + $this->last_result = $this->result->fetchAll();
624 + $num_rows = count( $this->last_result );
483 625 }
484 626
485 627 // Log and return the number of rows selected.
486 628 $this->num_rows = $num_rows;
@@ -509,13 +651,9 @@
509 651 $this->queries[ $i ]['result'] = (int) $return_val;
510 652 }
511 653
512 654 // Add SQLite query data.
513 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
514 - $this->queries[ $i ]['sqlite_queries'] = $this->dbh->get_last_sqlite_queries();
515 - } else {
516 - $this->queries[ $i ]['sqlite_queries'] = $this->dbh->executed_sqlite_queries;
517 - }
655 + $this->queries[ $i ]['sqlite_queries'] = $this->dbh->get_last_sqlite_queries();
518 656 }
519 657 return $return_val;
520 658 }
521 659
@@ -533,17 +671,13 @@
533 671 $this->timer_start();
534 672 }
535 673
536 674 try {
537 - $this->result = $this->dbh->query( $query );
675 + $this->result = $this->dbh->query( $query, PDO::FETCH_OBJ ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
538 676 } catch ( Throwable $e ) {
539 677 $this->last_error = $this->format_error_message( $e );
540 678 }
541 679
542 - if ( $this->dbh instanceof WP_SQLite_Translator ) {
543 - $this->last_error = $this->dbh->get_error_message();
544 - }
545 -
546 680 ++$this->num_queries;
547 681
548 682 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
549 683 $this->log_query(
@@ -566,122 +700,122 @@
566 700 protected function load_col_info() {
567 701 if ( $this->col_info ) {
568 702 return;
569 703 }
570 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
571 - $this->col_info = array();
572 - foreach ( $this->dbh->get_last_column_meta() as $column ) {
573 - $this->col_info[] = (object) array(
574 - 'name' => $column['name'],
575 - 'orgname' => $column['mysqli:orgname'],
576 - 'table' => $column['table'],
577 - 'orgtable' => $column['mysqli:orgtable'],
578 - 'def' => '', // Unused, always ''.
579 - 'db' => $column['mysqli:db'],
580 - 'catalog' => 'def', // Unused, always 'def'.
581 - 'max_length' => 0, // As of PHP 8.1, this is always 0.
582 - 'length' => $column['len'],
583 - 'charsetnr' => $column['mysqli:charsetnr'],
584 - 'flags' => $column['mysqli:flags'],
585 - 'type' => $column['mysqli:type'],
586 - 'decimals' => $column['precision'],
587 - );
588 - }
589 - } else {
590 - $this->col_info = $this->dbh->get_columns();
704 + $this->col_info = array();
705 + if ( null === $this->result ) {
706 + return;
591 707 }
708 + for ( $i = 0; $i < $this->result->columnCount(); $i++ ) {
709 + $column = $this->result->getColumnMeta( $i );
710 + $this->col_info[] = (object) array(
711 + 'name' => $column['name'],
712 + 'orgname' => $column['mysqli:orgname'],
713 + 'table' => $column['table'],
714 + 'orgtable' => $column['mysqli:orgtable'],
715 + 'def' => '', // Unused, always ''.
716 + 'db' => $column['mysqli:db'],
717 + 'catalog' => 'def', // Unused, always 'def'.
718 + 'max_length' => 0, // As of PHP 8.1, this is always 0.
719 + 'length' => $column['len'],
720 + 'charsetnr' => $column['mysqli:charsetnr'],
721 + 'flags' => $column['mysqli:flags'],
722 + 'type' => $column['mysqli:type'],
723 + 'decimals' => $column['precision'],
724 + );
725 + }
592 726 }
593 727
594 728 /**
595 - * Method to return what the database can do.
729 + * Determines whether the database supports a given feature.
596 730 *
597 - * This overrides wpdb::has_cap() to avoid using MySQL functions.
598 - * SQLite supports subqueries, but not support collation, group_concat and set_charset.
731 + * The utf8mb4 check is handled here because older WordPress versions inspect
732 + * the MySQL client library. All other capabilities use the parent logic.
599 733 *
600 734 * @see wpdb::has_cap()
601 735 *
602 - * @param string $db_cap The feature to check for. Accepts 'collation',
603 - * 'group_concat', 'subqueries', 'set_charset',
604 - * 'utf8mb4', or 'utf8mb4_520'.
605 - *
606 - * @return bool Whether the database feature is supported, false otherwise.
736 + * @param string $db_cap The feature to check for.
737 + * @return bool True when the database feature is supported, false otherwise.
607 738 */
608 739 public function has_cap( $db_cap ) {
609 - return 'subqueries' === strtolower( $db_cap );
740 + if ( 'utf8mb4' === strtolower( $db_cap ) ) {
741 + return true;
742 + }
743 +
744 + return parent::has_cap( $db_cap );
610 745 }
611 746
612 747 /**
613 - * Method to return database version number.
748 + * Retrieves the emulated database server version number.
614 749 *
615 - * This overrides wpdb::db_version() to avoid using MySQL function.
616 - * It returns mysql version number, but it means nothing for SQLite.
617 - * So it return the newest mysql version.
750 + * This mirrors wpdb::db_version(), but must also be defined here because
751 + * WordPress 5.4 and older fetch server information directly from the MySQL
752 + * extension instead of delegating to wpdb::db_server_info().
618 753 *
619 754 * @see wpdb::db_version()
755 + *
756 + * @return string Version number on success, or an empty string while disconnected.
620 757 */
621 758 public function db_version() {
622 - return '8.0';
759 + return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() );
623 760 }
624 761
625 762 /**
626 - * Returns the version of the SQLite engine.
763 + * Returns the raw version string of the emulated MySQL server.
627 764 *
628 - * @return string SQLite engine version as a string.
765 + * @see wpdb::db_server_info()
766 + *
767 + * @return string Emulated MySQL server version, or an empty string while disconnected.
629 768 */
630 769 public function db_server_info() {
631 - return $this->dbh->get_sqlite_version();
770 + if ( ! $this->dbh ) {
771 + return '';
772 + }
773 +
774 + return $this->dbh->getAttribute( PDO::ATTR_SERVER_VERSION ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
632 775 }
633 776
634 777 /**
635 - * Make sure the SQLite database directory exists and is writable.
636 - * Create .htaccess and index.php files to prevent direct access.
778 + * Resolves the charset and collation as wpdb::determine_charset() does.
637 779 *
638 - * @param string $database_path The path to the SQLite database file.
780 + * Unlike in wpdb, this doesn't need a database connection. The emulated
781 + * MySQL server (5.7 or newer) always supports utf8mb4_unicode_520_ci.
782 + *
783 + * @see wpdb::determine_charset()
784 + *
785 + * @param string $charset The character set to check.
786 + * @param string $collate The collation to check.
787 + * @return array {
788 + * The most appropriate character set and collation to use.
789 + *
790 + * @type string $charset Character set.
791 + * @type string $collate Collation.
792 + * }
639 793 */
640 - private function ensure_database_directory( string $database_path ) {
641 - $dir = dirname( $database_path );
642 -
643 - // Set the umask to 0000 to apply permissions exactly as specified.
644 - // A non-zero umask affects new file and directory permissions.
645 - $umask = umask( 0 );
646 -
647 - // Ensure database directory.
648 - if ( ! is_dir( $dir ) ) {
649 - if ( ! @mkdir( $dir, 0700, true ) ) {
650 - wp_die( sprintf( 'Failed to create database directory: %s', $dir ), 'Error!' );
651 - }
794 + private function resolve_charset( $charset, $collate ) {
795 + if ( 'utf8' === $charset ) {
796 + $charset = 'utf8mb4';
652 797 }
653 - if ( ! is_writable( $dir ) ) {
654 - wp_die( sprintf( 'Database directory is not writable: %s', $dir ), 'Error!' );
655 - }
656 798
657 - // Ensure .htaccess file to prevent direct access.
658 - $path = $dir . DIRECTORY_SEPARATOR . '.htaccess';
659 - if ( ! is_file( $path ) ) {
660 - $result = file_put_contents( $path, 'DENY FROM ALL', LOCK_EX );
661 - if ( false === $result ) {
662 - wp_die( sprintf( 'Failed to create file: %s', $path ), 'Error!' );
799 + if ( 'utf8mb4' === $charset ) {
800 + // _general_ is outdated, so we can upgrade it to _unicode_, instead.
801 + if ( ! $collate || 'utf8_general_ci' === $collate ) {
802 + $collate = 'utf8mb4_unicode_ci';
803 + } else {
804 + $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
663 805 }
664 - chmod( $path, 0600 );
665 806 }
666 807
667 - // Ensure index.php file to prevent direct access.
668 - $path = $dir . DIRECTORY_SEPARATOR . 'index.php';
669 - if ( ! is_file( $path ) ) {
670 - $result = file_put_contents( $path, '<?php // Silence is gold. ?>', LOCK_EX );
671 - if ( false === $result ) {
672 - wp_die( sprintf( 'Failed to create file: %s', $path ), 'Error!' );
673 - }
674 - chmod( $path, 0600 );
808 + // _unicode_520_ is a better collation, we should use that when it's available.
809 + if ( 'utf8mb4_unicode_ci' === $collate ) {
810 + $collate = 'utf8mb4_unicode_520_ci';
675 811 }
676 812
677 - // Restore the original umask value.
678 - umask( $umask );
813 + return compact( 'charset', 'collate' );
679 814 }
680 815
681 -
682 816 /**
683 - * Format SQLite driver error message.
817 + * Format MySQL-on-SQLite driver error message.
684 818 *
685 819 * @return string
686 820 */
687 821 private function format_error_message( Throwable $e ) {
@@ -687,10 +821,10 @@
687 821 private function format_error_message( Throwable $e ) {
688 822 $output = '<div style="clear:both">&nbsp;</div>' . PHP_EOL;
689 823
690 824 // Queries.
691 - if ( $e instanceof WP_SQLite_Driver_Exception ) {
692 - $driver = $e->getDriver();
825 + if ( $e instanceof WP_MySQL_On_SQLite_Exception ) {
826 + $driver = $e->get_driver();
693 827
694 828 $output .= '<div class="queries" style="clear:both;margin-bottom:2px;border:red dotted thin;">' . PHP_EOL;
695 829 $output .= '<p>MySQL query:</p>' . PHP_EOL;
696 830 $output .= '<p>' . $driver->get_last_mysql_query() . '</p>' . PHP_EOL;