Skip to content

Commit 959505e

Browse files
committed
Fix schema inference for WordPress tables
1 parent c67f6c4 commit 959505e

2 files changed

Lines changed: 26 additions & 13 deletions

File tree

tests/WP_SQLite_Information_Schema_Reconstructor_Tests.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ public static function setUpBeforeClass(): void {
3030
$GLOBALS['table_prefix'] = 'wptests_';
3131
}
3232
if ( ! isset( $GLOBALS['wpdb'] ) ) {
33-
$GLOBALS['wpdb'] = new stdClass();
34-
$GLOBALS['wpdb']->suppress_errors = false;
35-
$GLOBALS['wpdb']->show_errors = true;
33+
$GLOBALS['wpdb'] = new class() {
34+
public function set_prefix( string $prefix ): void {}
35+
};
3636
}
3737

3838
// Mock symbols that are used for WordPress table reconstruction.

wp-includes/sqlite-ast/class-wp-sqlite-information-schema-reconstructor.php

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -145,20 +145,33 @@ private function get_wp_create_table_statements(): array {
145145
throw new Exception( 'The "wp_get_db_schema()" function was not defined.' );
146146
}
147147

148-
// Get schema for global tables and the main site.
149-
$schema = wp_get_db_schema();
148+
/*
149+
* At this point, WPDB may not yet be initialized, as we're configuring
150+
* the database connection. Let's only populate the table names using
151+
* the "$table_prefix" global so we can get correct table names.
152+
*/
153+
global $wpdb, $table_prefix;
154+
$wpdb->set_prefix( $table_prefix );
155+
156+
// Get schema for global tables.
157+
$schema = wp_get_db_schema( 'global' );
150158

151159
// For multisite installs, add schema definitions for all sites.
152160
if ( is_multisite() ) {
153-
$site_ids = get_sites(
154-
array(
155-
'fields' => 'ids',
156-
'number' => PHP_INT_MAX,
157-
)
158-
);
159-
foreach ( $site_ids as $site_id ) {
160-
$schema .= wp_get_db_schema( 'blog', $site_id );
161+
/*
162+
* We need to use a database query over the "get_sites()" function,
163+
* as WPDB may not yet initialized. Moreover, we need to get the IDs
164+
* of all existing blogs, independent of any filters and actions that
165+
* could possibly alter the results of a "get_sites()" call.
166+
*/
167+
$stmt = $this->driver->execute_sqlite_query( "SELECT blog_id FROM {$wpdb->blogs}" );
168+
$blog_ids = $stmt->fetchAll( PDO::FETCH_COLUMN );
169+
foreach ( $blog_ids as $blog_id ) {
170+
$schema .= wp_get_db_schema( 'blog', (int) $blog_id );
161171
}
172+
} else {
173+
// For single site installs, add schema for the main site.
174+
$schema .= wp_get_db_schema( 'blog' );
162175
}
163176

164177
// Parse the schema.

0 commit comments

Comments
 (0)