From f3dfbc0946f6d7606829279c1005d8e457f2ca4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Jake=C5=A1?= Date: Tue, 18 Aug 2026 15:47:00 +0200 Subject: [PATCH] Fix fresh multisite database setup (#492) ## Summary This fixes fresh multisite installation when the SQLite database is still empty. The change: - Treats a missing blogs table as an empty list of existing sites during information schema reconstruction. - Continues to surface unrelated SQLite errors. - Covers empty, partially initialized, existing, and invalid multisite databases. Closes #490. ## Why When `MULTISITE` was defined before installation, database startup queried `wp_blogs` before WordPress had created it. The connection failed, so WordPress never had the opportunity to install the network tables. **Validation:** The reported workflow was reproduced end to end with a fresh SQLite database and WordPress 7.0.1. `wp core multisite-install` completed successfully, and the resulting network and main site were verified. --- ...qlite-information-schema-reconstructor.php | 90 ++++++++----- ...Information_Schema_Reconstructor_Tests.php | 126 +++++++++++++++--- packages/mysql-on-sqlite/tests/bootstrap.php | 25 +++- 3 files changed, 186 insertions(+), 55 deletions(-) diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php index 759e636ad..a8500d60d 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php @@ -64,40 +64,41 @@ public function ensure_correct_information_schema(): void { $sqlite_tables = $this->get_sqlite_table_names(); $information_schema_tables = $this->get_information_schema_table_names(); + $tables_missing_from_information_schema = array_diff( $sqlite_tables, $information_schema_tables ); + $tables_missing_from_sqlite = array_diff( $information_schema_tables, $sqlite_tables ); + // In WordPress, use "wp_get_db_schema()" to reconstruct WordPress tables. - $wp_tables = $this->get_wp_create_table_statements(); + $wp_tables = count( $tables_missing_from_information_schema ) > 0 + ? $this->get_wp_create_table_statements() + : array(); // Reconstruct information schema records for tables that don't have them. - foreach ( $sqlite_tables as $table ) { - if ( ! in_array( $table, $information_schema_tables, true ) ) { - if ( isset( $wp_tables[ $table ] ) ) { - // WordPress core table (as returned by "wp_get_db_schema()"). - $ast = $wp_tables[ $table ]; - } else { - // Other table (a WordPress plugin or unrelated to WordPress). - $sql = $this->generate_create_table_statement( $table ); - $ast = $this->driver->create_parser( $sql )->parse(); - if ( null === $ast ) { - throw new WP_MySQL_On_SQLite_Exception( $this->driver, 'Failed to parse the MySQL query.' ); - } + foreach ( $tables_missing_from_information_schema as $table ) { + if ( isset( $wp_tables[ $table ] ) ) { + // WordPress core table (as returned by "wp_get_db_schema()"). + $ast = $wp_tables[ $table ]; + } else { + // Other table (a WordPress plugin or unrelated to WordPress). + $sql = $this->generate_create_table_statement( $table ); + $ast = $this->driver->create_parser( $sql )->parse(); + if ( null === $ast ) { + throw new WP_MySQL_On_SQLite_Exception( $this->driver, 'Failed to parse the MySQL query.' ); } + } - /* - * First, let's make sure we clean up all related data. This fixes - * partial data corruption, such as when a table record is missing, - * but some related column, index, or constraint records are stored. - */ - $this->record_drop_table( $table ); + /* + * First, let's make sure we clean up all related data. This fixes + * partial data corruption, such as when a table record is missing, + * but some related column, index, or constraint records are stored. + */ + $this->record_drop_table( $table ); - $this->schema_builder->record_create_table( $ast ); - } + $this->schema_builder->record_create_table( $ast ); } // Remove information schema records for tables that don't exist. - foreach ( $information_schema_tables as $table ) { - if ( ! in_array( $table, $sqlite_tables, true ) ) { - $this->record_drop_table( $table ); - } + foreach ( $tables_missing_from_sqlite as $table ) { + $this->record_drop_table( $table ); } } @@ -202,31 +203,46 @@ private function get_wp_create_table_statements(): array { * the "$table_prefix" global so we can get correct table names. */ global $table_prefix; - $wpdb->set_prefix( $table_prefix ); + $set_prefix_result = $wpdb->set_prefix( $table_prefix ); + if ( $set_prefix_result instanceof WP_Error ) { + throw new Exception( $set_prefix_result->get_error_message() ); + } // Get schema for global tables. $schema = wp_get_db_schema( 'global' ); - // For multisite installs, add schema definitions for all sites. + // For multisite installs, get all blog IDs. + $blog_ids = array(); if ( is_multisite() ) { /* * We need to use a database query over the "get_sites()" function, - * as WPDB may not yet initialized. Moreover, we need to get the IDs + * as WPDB may not yet be initialized. Moreover, we need to get the IDs * of all existing blogs, independent of any filters and actions that * could possibly alter the results of a "get_sites()" call. */ - $blog_ids = $this->driver->execute_sqlite_query( - sprintf( - 'SELECT blog_id FROM %s', - $this->connection->quote_identifier( $wpdb->blogs ) - ) - )->fetchAll( PDO::FETCH_COLUMN ); + try { + $blog_ids = $this->driver->execute_sqlite_query( + sprintf( + 'SELECT blog_id FROM %s', + $this->connection->quote_identifier( $wpdb->blogs ) + ) + )->fetchAll( PDO::FETCH_COLUMN ); + } catch ( PDOException $e ) { + if ( ! str_contains( $e->getMessage(), 'no such table' ) ) { + throw $e; + } + } + } + + // Get schema for blog tables. + if ( 0 === count( $blog_ids ) ) { + // Single site or no blog IDs: Add schema for the main site. + $schema .= wp_get_db_schema( 'blog' ); + } else { + // Multisite: Add schema definitions for all sites. foreach ( $blog_ids as $blog_id ) { $schema .= wp_get_db_schema( 'blog', (int) $blog_id ); } - } else { - // For single site installs, add schema for the main site. - $schema .= wp_get_db_schema( 'blog' ); } // Parse the schema. diff --git a/packages/mysql-on-sqlite/tests/WP_SQLite_Information_Schema_Reconstructor_Tests.php b/packages/mysql-on-sqlite/tests/WP_SQLite_Information_Schema_Reconstructor_Tests.php index b02c8d793..5e98d5119 100644 --- a/packages/mysql-on-sqlite/tests/WP_SQLite_Information_Schema_Reconstructor_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_SQLite_Information_Schema_Reconstructor_Tests.php @@ -27,11 +27,13 @@ public static function setUpBeforeClass(): void { } if ( ! function_exists( 'is_multisite' ) ) { function is_multisite() { - return false; + return $GLOBALS['wp_sqlite_is_multisite']; } } if ( ! function_exists( 'wp_get_db_schema' ) ) { - function wp_get_db_schema() { + function wp_get_db_schema( $scope = 'all', $blog_id = null ) { + $GLOBALS['wp_sqlite_db_schema_calls'][] = array( $scope, $blog_id ); + // Output from "wp_get_db_schema" as of WordPress 6.8.0. // See: https://github.com/WordPress/wordpress-develop/blob/6.8.0/src/wp-admin/includes/schema.php#L36 return "CREATE TABLE wp_users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(255) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(255) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename), KEY user_email (user_email) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_usermeta ( umeta_id bigint(20) unsigned NOT NULL auto_increment, user_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (umeta_id), KEY user_id (user_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_termmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY term_id (term_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_terms ( term_id bigint(20) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', slug varchar(200) NOT NULL default '', term_group bigint(10) NOT NULL default 0, PRIMARY KEY (term_id), KEY slug (slug(191)), KEY name (name(191)) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_term_taxonomy ( term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default 0, taxonomy varchar(32) NOT NULL default '', description longtext NOT NULL, parent bigint(20) unsigned NOT NULL default 0, count bigint(20) NOT NULL default 0, PRIMARY KEY (term_taxonomy_id), UNIQUE KEY term_id_taxonomy (term_id,taxonomy), KEY taxonomy (taxonomy) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_term_relationships ( object_id bigint(20) unsigned NOT NULL default 0, term_taxonomy_id bigint(20) unsigned NOT NULL default 0, term_order int(11) NOT NULL default 0, PRIMARY KEY (object_id,term_taxonomy_id), KEY term_taxonomy_id (term_taxonomy_id) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_commentmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, comment_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY comment_id (comment_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID bigint(20) unsigned NOT NULL default '0', comment_author tinytext NOT NULL, comment_author_email varchar(100) NOT NULL default '', comment_author_url varchar(200) NOT NULL default '', comment_author_IP varchar(100) NOT NULL default '', comment_date datetime NOT NULL default '0000-00-00 00:00:00', comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', comment_content text NOT NULL, comment_karma int(11) NOT NULL default '0', comment_approved varchar(20) NOT NULL default '1', comment_agent varchar(255) NOT NULL default '', comment_type varchar(20) NOT NULL default 'comment', comment_parent bigint(20) unsigned NOT NULL default '0', user_id bigint(20) unsigned NOT NULL default '0', PRIMARY KEY (comment_ID), KEY comment_post_ID (comment_post_ID), KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), KEY comment_date_gmt (comment_date_gmt), KEY comment_parent (comment_parent), KEY comment_author_email (comment_author_email(10)) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_links ( link_id bigint(20) unsigned NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', link_name varchar(255) NOT NULL default '', link_image varchar(255) NOT NULL default '', link_target varchar(25) NOT NULL default '', link_description varchar(255) NOT NULL default '', link_visible varchar(20) NOT NULL default 'Y', link_owner bigint(20) unsigned NOT NULL default '1', link_rating int(11) NOT NULL default '0', link_updated datetime NOT NULL default '0000-00-00 00:00:00', link_rel varchar(255) NOT NULL default '', link_notes mediumtext NOT NULL, link_rss varchar(255) NOT NULL default '', PRIMARY KEY (link_id), KEY link_visible (link_visible) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_options ( option_id bigint(20) unsigned NOT NULL auto_increment, option_name varchar(191) NOT NULL default '', option_value longtext NOT NULL, autoload varchar(20) NOT NULL default 'yes', PRIMARY KEY (option_id), UNIQUE KEY option_name (option_name), KEY autoload (autoload) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_postmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, post_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key(191)) ) DEFAULT CHARACTER SET utf8mb4; CREATE TABLE wp_posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) unsigned NOT NULL default '0', post_date datetime NOT NULL default '0000-00-00 00:00:00', post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content longtext NOT NULL, post_title text NOT NULL, post_excerpt text NOT NULL, post_status varchar(20) NOT NULL default 'publish', comment_status varchar(20) NOT NULL default 'open', ping_status varchar(20) NOT NULL default 'open', post_password varchar(255) NOT NULL default '', post_name varchar(200) NOT NULL default '', to_ping text NOT NULL, pinged text NOT NULL, post_modified datetime NOT NULL default '0000-00-00 00:00:00', post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content_filtered longtext NOT NULL, post_parent bigint(20) unsigned NOT NULL default '0', guid varchar(255) NOT NULL default '', menu_order int(11) NOT NULL default '0', post_type varchar(20) NOT NULL default 'post', post_mime_type varchar(100) NOT NULL default '', comment_count bigint(20) NOT NULL default '0', PRIMARY KEY (ID), KEY post_name (post_name(191)), KEY type_status_date (post_type,post_status,post_date,ID), KEY post_parent (post_parent), KEY post_author (post_author) ) DEFAULT CHARACTER SET utf8mb4;"; @@ -41,27 +43,95 @@ function wp_get_db_schema() { // Before each test, we create a new database public function setUp(): void { - $pdo_class = PHP_VERSION_ID >= 80400 ? Pdo\Sqlite::class : PDO::class; - $this->sqlite = new $pdo_class( 'sqlite::memory:' ); - $this->engine = new WP_MySQL_On_SQLite( - 'mysql-on-sqlite:dbname=wp', - null, - null, - array( 'sqlite_pdo' => $this->sqlite ) - ); - $this->engine->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true ); + $GLOBALS['wp_sqlite_is_multisite'] = false; + $GLOBALS['table_prefix'] = 'wptests_'; - $builder = new WP_SQLite_Information_Schema_Builder( - WP_MySQL_On_SQLite::RESERVED_PREFIX, - $this->engine->get_connection() + $this->initializeDatabase(); + + $GLOBALS['wp_sqlite_db_schema_calls'] = array(); + } + + public function tearDown(): void { + $GLOBALS['wp_sqlite_is_multisite'] = false; + $GLOBALS['wp_sqlite_db_schema_calls'] = array(); + $GLOBALS['table_prefix'] = 'wptests_'; + $GLOBALS['wpdb']->blogs = 'wptests_blogs'; + } + + public function testInvalidWpTablePrefix(): void { + $GLOBALS['wp_sqlite_is_multisite'] = true; + $GLOBALS['table_prefix'] = 'invalid-prefix'; + $GLOBALS['wpdb']->blogs = null; + $this->engine->get_connection()->query( 'CREATE TABLE t ( id INTEGER )' ); + + $this->expectException( Exception::class ); + $this->expectExceptionMessage( 'Invalid database prefix' ); + + $this->reconstructor->ensure_correct_information_schema(); + } + + public function testEmptyMultisiteDatabase(): void { + $GLOBALS['wp_sqlite_is_multisite'] = true; + + $this->initializeDatabase(); + + $result = $this->assertQuery( 'SELECT * FROM information_schema.tables' ); + $this->assertSame( array(), $result ); + $this->assertSame( array(), $GLOBALS['wp_sqlite_db_schema_calls'] ); + } + + public function testSkipWpSchemaWhenNoTablesAreMissing(): void { + $this->engine->query( 'CREATE TABLE t ( id INTEGER )' ); + $GLOBALS['wp_sqlite_is_multisite'] = true; + + $this->reconstructor->ensure_correct_information_schema(); + + $this->assertSame( array(), $GLOBALS['wp_sqlite_db_schema_calls'] ); + } + + public function testReconstructTableInMultisiteWithoutBlogsTable(): void { + $GLOBALS['wp_sqlite_is_multisite'] = true; + $this->engine->get_connection()->query( 'CREATE TABLE t ( id INTEGER )' ); + + $this->reconstructor->ensure_correct_information_schema(); + + $result = $this->assertQuery( 'SELECT table_name FROM information_schema.tables WHERE table_name = "t"' ); + $this->assertCount( 1, $result ); + $this->assertSame( + array( + array( 'global', null ), + array( 'blog', null ), + ), + $GLOBALS['wp_sqlite_db_schema_calls'] ); + } - $this->reconstructor = new WP_SQLite_Information_Schema_Reconstructor( - $this->engine, - $builder + public function testReconstructTablesInExistingMultisite(): void { + $GLOBALS['wp_sqlite_is_multisite'] = true; + $this->engine->get_connection()->query( 'CREATE TABLE wptests_blogs ( blog_id INTEGER )' ); + $this->engine->get_connection()->query( 'INSERT INTO wptests_blogs ( blog_id ) VALUES ( 2 )' ); + + $this->reconstructor->ensure_correct_information_schema(); + + $this->assertSame( + array( + array( 'global', null ), + array( 'blog', 2 ), + ), + $GLOBALS['wp_sqlite_db_schema_calls'] ); } + public function testReconstructTablesInInvalidMultisite(): void { + $GLOBALS['wp_sqlite_is_multisite'] = true; + $this->engine->get_connection()->query( 'CREATE TABLE wptests_blogs ( id INTEGER )' ); + + $this->expectException( PDOException::class ); + $this->expectExceptionMessage( 'no such column: blog_id' ); + + $this->reconstructor->ensure_correct_information_schema(); + } + public function testReconstructTable(): void { $this->engine->get_connection()->query( ' @@ -464,4 +534,26 @@ private function assertQuery( $sql ) { $this->assertNotFalse( $retval ); return $retval; } + + private function initializeDatabase(): void { + $pdo_class = PHP_VERSION_ID >= 80400 ? Pdo\Sqlite::class : PDO::class; + $this->sqlite = new $pdo_class( 'sqlite::memory:' ); + $this->engine = new WP_MySQL_On_SQLite( + 'mysql-on-sqlite:dbname=wp', + null, + null, + array( 'sqlite_pdo' => $this->sqlite ) + ); + $this->engine->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true ); + + $builder = new WP_SQLite_Information_Schema_Builder( + WP_MySQL_On_SQLite::RESERVED_PREFIX, + $this->engine->get_connection() + ); + + $this->reconstructor = new WP_SQLite_Information_Schema_Reconstructor( + $this->engine, + $builder + ); + } } diff --git a/packages/mysql-on-sqlite/tests/bootstrap.php b/packages/mysql-on-sqlite/tests/bootstrap.php index 415b02238..49adca752 100644 --- a/packages/mysql-on-sqlite/tests/bootstrap.php +++ b/packages/mysql-on-sqlite/tests/bootstrap.php @@ -21,9 +21,32 @@ // Polyfill WPDB globals. $GLOBALS['table_prefix'] = 'wptests_'; $GLOBALS['wpdb'] = new class() { - public function set_prefix( string $prefix ): void {} + public $blogs; + + public function set_prefix( string $prefix ) { + if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) { + return new WP_Error( 'invalid_db_prefix', 'Invalid database prefix' ); + } + + $this->blogs = $prefix . 'blogs'; + return $prefix; + } }; +if ( ! class_exists( 'WP_Error' ) ) { + class WP_Error { + private $message; + + public function __construct( $code, $message ) { + $this->message = $message; + } + + public function get_error_message() { + return $this->message; + } + } +} + /** * Polyfills for WordPress functions */