diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php index 12b34be10..af5b73287 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php @@ -1802,6 +1802,11 @@ private function extract_referential_constraint_data( WP_Parser_Node $node, stri // Find which index includes referenced column names as a prefix. $unique_constraint_name = null; foreach ( $index_columns_map as $index_name => $index_columns ) { + // An index with fewer columns than the reference can't have them as a prefix. + if ( count( $index_columns ) < count( $reference_parts ) ) { + continue; + } + $is_prefix = true; foreach ( $reference_parts as $i => $reference_part ) { if ( $index_columns[ $i ] !== $this->get_value( $reference_part ) ) { diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Metadata_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Metadata_Tests.php index e8a8f4d33..7dfb79548 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Metadata_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Metadata_Tests.php @@ -1914,6 +1914,35 @@ public function testInformationSchemaForeignKeysWithMultipleColumns(): void { ); } + public function testInformationSchemaForeignKeysReferencingShorterUniqueKey(): void { + // The referenced table also has a unique key with fewer columns than the reference. + $this->assertQuery( + 'CREATE TABLE t1 ( + id INT, + name VARCHAR(255), + UNIQUE KEY u_id (id), + UNIQUE KEY u_id_name (id, name) + )' + ); + $this->assertQuery( + 'CREATE TABLE t2 ( + id INT, + name VARCHAR(255), + FOREIGN KEY (id, name) REFERENCES t1 (id, name) + )' + ); + + $result = $this->assertQuery( "SELECT unique_constraint_name FROM information_schema.referential_constraints WHERE table_name = 't2'" ); + $this->assertEquals( + array( + (object) array( + 'UNIQUE_CONSTRAINT_NAME' => 'u_id_name', + ), + ), + $result + ); + } + public function testInformationSchemaAlterTableAddForeignKeys(): void { $this->assertQuery( 'CREATE TABLE t1 (id INT PRIMARY KEY, name VARCHAR(255))' ); $this->assertQuery( 'CREATE TABLE t2 (id INT)' );