get_index_columns using SHOW INDEX FROM query instead of information_schema (#36427)

* get_index_columns using SHOW INDEX FROM query instead of information_schema

* returning empty array for clarity

* ignore interpolated query

* adding changelog entry

* Adding unit tests for the updated DatabaseUtil::get_index_columns()

---------

Co-authored-by: Michael Pretty <prettyboymp@Michaels-MacBook-Pro.local>
This commit is contained in:
Michael Pretty 2023-06-20 14:34:59 -04:00 committed by GitHub
parent 87c69f38e6
commit 6771b48c20
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 72 additions and 9 deletions

View File

@ -0,0 +1,4 @@
Significance: minor
Type: fix
Convert DatabaseUtil::get_index_columns() to use SHOW INDEX FROM instead of INFORMATION_SCHEMA query

View File

@ -126,15 +126,14 @@ class DatabaseUtil {
$index_name = 'PRIMARY';
}
// phpcs:disable WordPress.DB.PreparedSQL
return $wpdb->get_col(
"
SELECT column_name FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_name='$table_name'
AND table_schema='" . DB_NAME . "'
AND index_name='$index_name'"
);
// phpcs:enable WordPress.DB.PreparedSQL
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$results = $wpdb->get_results( $wpdb->prepare( "SHOW INDEX FROM $table_name WHERE Key_name = %s", $index_name ) );
if ( empty( $results ) ) {
return array();
}
return array_column( $results, 'Column_name' );
}
/**

View File

@ -0,0 +1,60 @@
<?php
/**
* Tests for the DatabaseUtil utility.
*/
use Automattic\WooCommerce\Internal\Utilities\DatabaseUtil;
/**
* Tests relating to DatabaseUtil.
*/
class DatabaseUtilTest extends WC_Unit_Test_Case {
/**
* @var DatabaseUtil
*/
private $sut;
/**
* Set-up subject under test.
*/
public function set_up() {
$this->sut = wc_get_container()->get( DatabaseUtil::class );
parent::set_up();
}
/**
* @testdox Test that get_index_columns() will default to return the primary key index columns.
*/
public function test_get_index_columns_returns_primary_index_by_default() {
global $wpdb;
$this->assertEquals(
array( 'product_id' ),
$this->sut->get_index_columns( $wpdb->prefix . 'wc_product_meta_lookup' )
);
}
/**
* @testdox Test that get_index_columns() will return an array containing all columns of a multi-column index.
*/
public function test_get_index_columns_returns_multicolumn_index() {
global $wpdb;
$this->assertEquals(
array( 'min_price', 'max_price' ),
$this->sut->get_index_columns( $wpdb->prefix . 'wc_product_meta_lookup', 'min_max_price' )
);
}
/**
* @testdox Test that giving a non-existent index name to get_index_columns() will return an empty array.
*/
public function test_get_index_columns_returns_empty_for_invalid_index() {
global $wpdb;
$this->assertEmpty(
$this->sut->get_index_columns( $wpdb->prefix . 'wc_product_meta_lookup', 'invalid_index_name' )
);
}
}