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 +329 -201 2.2.21 → 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,85 +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 444
310 - // Migrate the database file from a legacy path, if it exists.
311 - if ( ! defined( 'DB_FILE' ) && ! file_exists( FQDB ) ) {
312 - $old_db_path = FQDBDIR . '.ht.sqlite.php';
313 -
314 - if ( file_exists( $old_db_path ) ) {
315 - if ( ! rename( $old_db_path, FQDB ) ) {
316 - wp_die( 'Failed to rename database file.', 'Error!' );
317 - }
318 -
319 - foreach ( array( '-wal', '-shm', '-journal' ) as $suffix ) {
320 - if ( file_exists( $old_db_path . $suffix ) ) {
321 - if ( ! rename( $old_db_path . $suffix, FQDB . $suffix ) ) {
322 - wp_die( 'Failed to rename database file.', 'Error!' );
323 - }
324 - }
325 - }
326 - }
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;
327 451 }
328 452
329 - if ( defined( 'WP_SQLITE_AST_DRIVER' ) && WP_SQLITE_AST_DRIVER ) {
330 - if ( null === $this->dbname || '' === $this->dbname ) {
331 - $this->bail(
332 - 'The database name was not set. The SQLite driver requires a database name to be set to emulate MySQL information schema tables.',
333 - 'db_connect_fail'
334 - );
335 - return false;
336 - }
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;
337 469
338 - $this->ensure_database_directory( FQDB );
339 -
340 - try {
341 - $connection = new WP_SQLite_Connection(
342 - array(
343 - 'pdo' => $pdo,
344 - 'path' => FQDB,
345 - 'journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
346 - )
347 - );
348 - $this->dbh = new WP_SQLite_Driver( $connection, $this->dbname );
349 - $GLOBALS['@pdo'] = $this->dbh->get_connection()->get_pdo();
350 - } catch ( Throwable $e ) {
351 - $this->last_error = $this->format_error_message( $e );
352 - }
353 - } else {
354 - $this->dbh = new WP_SQLite_Translator( $pdo );
355 - $this->last_error = $this->dbh->get_error_message();
356 - $GLOBALS['@pdo'] = $this->dbh->get_pdo();
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 );
357 479 }
358 480 if ( $this->last_error ) {
359 481 return false;
360 482 }
483 +
484 + $this->has_connected = true;
485 + $this->set_charset( $this->dbh );
486 +
361 487 $this->ready = true;
362 488 $this->set_sql_mode();
489 + return true;
363 490 }
364 491
365 492 /**
366 - * Method to dummy out wpdb::check_connection()
493 + * Checks that the database connection is available.
367 494 *
368 495 * @param bool $allow_bail Not used.
369 496 *
370 - * @return bool
497 + * @return bool True when the connection is available, false otherwise.
371 498 */
372 499 public function check_connection( $allow_bail = true ) {
373 - return true;
500 + if ( $this->dbh ) {
501 + return true;
502 + }
503 +
504 + return $this->db_connect( $allow_bail );
374 505 }
375 506
376 507 /**
377 508 * Prepares a SQL query for safe execution.
@@ -420,8 +551,9 @@
420 551 $this->hide_errors();
421 552 }
422 553
423 554 if ( ! $this->ready ) {
555 + $this->check_current_query = true;
424 556 return false;
425 557 }
426 558
427 559 $query = apply_filters( 'query', $query );
@@ -435,24 +567,32 @@
435 567
436 568 // Log how the function was called.
437 569 $this->func_call = "\$db->query(\"$query\")";
438 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 +
439 590 // Keep track of the last query for debug.
440 591 $this->last_query = $query;
441 592
442 - // Save the query count before running another query.
593 + // Save the query count after any charset discovery queries.
443 594 $last_query_count = count( $this->queries ?? array() );
444 -
445 - /*
446 - * @TODO: WPDB uses "$this->check_current_query" to check table/column
447 - * charset and strip all invalid characters from the query.
448 - * This is an involved process that we can bypass for SQLite,
449 - * if we simply strip all invalid UTF-8 characters from the query.
450 - *
451 - * To do so, mb_convert_encoding can be used with an optional
452 - * fallback to a htmlspecialchars method. E.g.:
453 - * https://github.com/nette/utils/blob/be534713c227aeef57ce1883fc17bc9f9e29eca2/src/Utils/Strings.php#L42
454 - */
455 595 $this->_do_query( $query );
456 596
457 597 if ( $this->last_error ) {
458 598 // Clear insert_id on a subsequent failed insert.
@@ -466,17 +606,13 @@
466 606
467 607 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
468 608 $return_val = true;
469 609 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
470 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
471 - $this->rows_affected = $this->dbh->get_last_return_value();
472 - } else {
473 - $this->rows_affected = $this->dbh->get_affected_rows();
474 - }
610 + $this->rows_affected = $this->result->rowCount();
475 611
476 612 // Take note of the insert_id.
477 613 if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
478 - $this->insert_id = $this->dbh->get_insert_id();
614 + $this->insert_id = (int) $this->dbh->lastInsertId();
479 615 }
480 616
481 617 // Return number of rows affected.
482 618 $return_val = $this->rows_affected;
@@ -482,11 +618,11 @@
482 618 $return_val = $this->rows_affected;
483 619 } else {
484 620 $num_rows = 0;
485 621
486 - if ( is_array( $this->result ) ) {
487 - $this->last_result = $this->result;
488 - $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 );
489 625 }
490 626
491 627 // Log and return the number of rows selected.
492 628 $this->num_rows = $num_rows;
@@ -515,13 +651,9 @@
515 651 $this->queries[ $i ]['result'] = (int) $return_val;
516 652 }
517 653
518 654 // Add SQLite query data.
519 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
520 - $this->queries[ $i ]['sqlite_queries'] = $this->dbh->get_last_sqlite_queries();
521 - } else {
522 - $this->queries[ $i ]['sqlite_queries'] = $this->dbh->executed_sqlite_queries;
523 - }
655 + $this->queries[ $i ]['sqlite_queries'] = $this->dbh->get_last_sqlite_queries();
524 656 }
525 657 return $return_val;
526 658 }
527 659
@@ -539,17 +671,13 @@
539 671 $this->timer_start();
540 672 }
541 673
542 674 try {
543 - $this->result = $this->dbh->query( $query );
675 + $this->result = $this->dbh->query( $query, PDO::FETCH_OBJ ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
544 676 } catch ( Throwable $e ) {
545 677 $this->last_error = $this->format_error_message( $e );
546 678 }
547 679
548 - if ( $this->dbh instanceof WP_SQLite_Translator ) {
549 - $this->last_error = $this->dbh->get_error_message();
550 - }
551 -
552 680 ++$this->num_queries;
553 681
554 682 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
555 683 $this->log_query(
@@ -572,122 +700,122 @@
572 700 protected function load_col_info() {
573 701 if ( $this->col_info ) {
574 702 return;
575 703 }
576 - if ( $this->dbh instanceof WP_SQLite_Driver ) {
577 - $this->col_info = array();
578 - foreach ( $this->dbh->get_last_column_meta() as $column ) {
579 - $this->col_info[] = (object) array(
580 - 'name' => $column['name'],
581 - 'orgname' => $column['mysqli:orgname'],
582 - 'table' => $column['table'],
583 - 'orgtable' => $column['mysqli:orgtable'],
584 - 'def' => '', // Unused, always ''.
585 - 'db' => $column['mysqli:db'],
586 - 'catalog' => 'def', // Unused, always 'def'.
587 - 'max_length' => 0, // As of PHP 8.1, this is always 0.
588 - 'length' => $column['len'],
589 - 'charsetnr' => $column['mysqli:charsetnr'],
590 - 'flags' => $column['mysqli:flags'],
591 - 'type' => $column['mysqli:type'],
592 - 'decimals' => $column['precision'],
593 - );
594 - }
595 - } else {
596 - $this->col_info = $this->dbh->get_columns();
704 + $this->col_info = array();
705 + if ( null === $this->result ) {
706 + return;
597 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 + }
598 726 }
599 727
600 728 /**
601 - * Method to return what the database can do.
729 + * Determines whether the database supports a given feature.
602 730 *
603 - * This overrides wpdb::has_cap() to avoid using MySQL functions.
604 - * 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.
605 733 *
606 734 * @see wpdb::has_cap()
607 735 *
608 - * @param string $db_cap The feature to check for. Accepts 'collation',
609 - * 'group_concat', 'subqueries', 'set_charset',
610 - * 'utf8mb4', or 'utf8mb4_520'.
611 - *
612 - * @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.
613 738 */
614 739 public function has_cap( $db_cap ) {
615 - return 'subqueries' === strtolower( $db_cap );
740 + if ( 'utf8mb4' === strtolower( $db_cap ) ) {
741 + return true;
742 + }
743 +
744 + return parent::has_cap( $db_cap );
616 745 }
617 746
618 747 /**
619 - * Method to return database version number.
748 + * Retrieves the emulated database server version number.
620 749 *
621 - * This overrides wpdb::db_version() to avoid using MySQL function.
622 - * It returns mysql version number, but it means nothing for SQLite.
623 - * 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().
624 753 *
625 754 * @see wpdb::db_version()
755 + *
756 + * @return string Version number on success, or an empty string while disconnected.
626 757 */
627 758 public function db_version() {
628 - return '8.0';
759 + return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() );
629 760 }
630 761
631 762 /**
632 - * Returns the version of the SQLite engine.
763 + * Returns the raw version string of the emulated MySQL server.
633 764 *
634 - * @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.
635 768 */
636 769 public function db_server_info() {
637 - 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
638 775 }
639 776
640 777 /**
641 - * Make sure the SQLite database directory exists and is writable.
642 - * Create .htaccess and index.php files to prevent direct access.
778 + * Resolves the charset and collation as wpdb::determine_charset() does.
643 779 *
644 - * @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 + * }
645 793 */
646 - private function ensure_database_directory( string $database_path ) {
647 - $dir = dirname( $database_path );
648 -
649 - // Set the umask to 0000 to apply permissions exactly as specified.
650 - // A non-zero umask affects new file and directory permissions.
651 - $umask = umask( 0 );
652 -
653 - // Ensure database directory.
654 - if ( ! is_dir( $dir ) ) {
655 - if ( ! @mkdir( $dir, 0700, true ) ) {
656 - wp_die( sprintf( 'Failed to create database directory: %s', $dir ), 'Error!' );
657 - }
794 + private function resolve_charset( $charset, $collate ) {
795 + if ( 'utf8' === $charset ) {
796 + $charset = 'utf8mb4';
658 797 }
659 - if ( ! is_writable( $dir ) ) {
660 - wp_die( sprintf( 'Database directory is not writable: %s', $dir ), 'Error!' );
661 - }
662 798
663 - // Ensure .htaccess file to prevent direct access.
664 - $path = $dir . DIRECTORY_SEPARATOR . '.htaccess';
665 - if ( ! is_file( $path ) ) {
666 - $result = file_put_contents( $path, 'DENY FROM ALL', LOCK_EX );
667 - if ( false === $result ) {
668 - 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 );
669 805 }
670 - chmod( $path, 0600 );
671 806 }
672 807
673 - // Ensure index.php file to prevent direct access.
674 - $path = $dir . DIRECTORY_SEPARATOR . 'index.php';
675 - if ( ! is_file( $path ) ) {
676 - $result = file_put_contents( $path, '<?php // Silence is gold. ?>', LOCK_EX );
677 - if ( false === $result ) {
678 - wp_die( sprintf( 'Failed to create file: %s', $path ), 'Error!' );
679 - }
680 - 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';
681 811 }
682 812
683 - // Restore the original umask value.
684 - umask( $umask );
813 + return compact( 'charset', 'collate' );
685 814 }
686 815
687 -
688 816 /**
689 - * Format SQLite driver error message.
817 + * Format MySQL-on-SQLite driver error message.
690 818 *
691 819 * @return string
692 820 */
693 821 private function format_error_message( Throwable $e ) {
@@ -693,10 +821,10 @@
693 821 private function format_error_message( Throwable $e ) {
694 822 $output = '<div style="clear:both">&nbsp;</div>' . PHP_EOL;
695 823
696 824 // Queries.
697 - if ( $e instanceof WP_SQLite_Driver_Exception ) {
698 - $driver = $e->getDriver();
825 + if ( $e instanceof WP_MySQL_On_SQLite_Exception ) {
826 + $driver = $e->get_driver();
699 827
700 828 $output .= '<div class="queries" style="clear:both;margin-bottom:2px;border:red dotted thin;">' . PHP_EOL;
701 829 $output .= '<p>MySQL query:</p>' . PHP_EOL;
702 830 $output .= '<p>' . $driver->get_last_mysql_query() . '</p>' . PHP_EOL;