query( 'DROP TABLE IF EXISTS `' . self::TABLE . '`' ); $wpdb->query( 'CREATE TABLE `' . self::TABLE . '` ( id BIGINT NOT NULL AUTO_INCREMENT, post_id BIGINT NOT NULL, ci_flag BIGINT(20) DEFAULT NULL, ci_price DECIMAL(18,6) DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY uk_entity (post_id) ) ENGINE=InnoDB' ); $wpdb->query( 'INSERT INTO `' . self::TABLE . '` (post_id, ci_flag, ci_price) VALUES (1, 1, 10), (2, 0, 20)' ); $GLOBALS['_wp_options'] = array(); $ref = new ReflectionProperty( WPDO_Schema_Manager::class, 'table_exists_cache' ); $ref->setAccessible( true ); $ref->setValue( null, array() ); WPDO_Entity_Registry::init(); WPDO_Entity_Registry::register_adapter( 'post', new WPDO_Adapter_Post() ); WPDO_Entity_Registry::register_group( 'post', 'ci_core', array( array( 'key' => 'ci_flag', 'type' => 'integer' ), array( 'key' => 'ci_price', 'type' => 'decimal' ), ), array( 'indexes' => array( 'flag_price' => array( 'ci_flag', 'ci_price' ) ) ) ); } protected function tearDown(): void { global $wpdb; $wpdb->query( 'DROP TABLE IF EXISTS `' . self::TABLE . '`' ); WPDO_Entity_Registry::init(); } /** @return array index name → ordered columns */ private function indexes(): array { global $wpdb; $out = array(); foreach ( (array) $wpdb->get_results( 'SHOW INDEX FROM `' . self::TABLE . '`', ARRAY_A ) as $row ) { $out[ $row['Key_name'] ][ (int) $row['Seq_in_index'] - 1 ] = $row['Column_name']; } return $out; } public function test_missing_composite_index_is_added_to_the_existing_table(): void { TMDO_Schema_Manager::ensure_group_indexes( 'post', 'ci_core' ); $this->assertSame( array( 'ci_flag', 'ci_price' ), $this->indexes()['cidx_flag_price'] ?? null ); global $wpdb; $this->assertSame( '2', $wpdb->get_var( 'SELECT COUNT(*) FROM `' . self::TABLE . '`' ), 'data untouched' ); } public function test_applied_definition_is_remembered_so_later_requests_skip_the_check(): void { TMDO_Schema_Manager::ensure_group_indexes( 'post', 'ci_core' ); global $wpdb; $wpdb->query( 'ALTER TABLE `' . self::TABLE . '` DROP INDEX `cidx_flag_price`' ); TMDO_Schema_Manager::ensure_group_indexes( 'post', 'ci_core' ); $this->assertArrayNotHasKey( 'cidx_flag_price', $this->indexes(), 'same definition → no SHOW INDEX / ALTER' ); $this->assertArrayHasKey( 'post/ci_core', get_option( TMDO_Schema_Manager::INDEXES_OPTION ) ); } public function test_group_without_indexes_is_left_alone(): void { WPDO_Entity_Registry::init(); WPDO_Entity_Registry::register_adapter( 'post', new WPDO_Adapter_Post() ); WPDO_Entity_Registry::register_group( 'post', 'ci_core', array( array( 'key' => 'ci_flag', 'type' => 'integer' ) ) ); TMDO_Schema_Manager::ensure_group_indexes( 'post', 'ci_core' ); $this->assertSame( array( 'PRIMARY', 'uk_entity' ), array_keys( $this->indexes() ) ); $this->assertFalse( get_option( TMDO_Schema_Manager::INDEXES_OPTION ) ); } }