Skip to content

Commit 1121fcc

Browse files
committed
Refactor and document key column definition inference
1 parent 6a3b370 commit 1121fcc

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

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

+29-15
Original file line numberDiff line numberDiff line change
@@ -277,8 +277,6 @@ private function get_column_definition( string $table_name, array $column_info )
277277
* @return string The MySQL key definition.
278278
*/
279279
private function get_key_definition( array $key, array $key_columns, array $data_types ): string {
280-
$key_length_limit = 100;
281-
282280
// Key definition.
283281
$definition = array();
284282
if ( $key['unique'] ) {
@@ -293,24 +291,40 @@ private function get_key_definition( array $key, array $key_columns, array $data
293291
// Key columns.
294292
$cols = array();
295293
foreach ( $key_columns as $column ) {
296-
// Get data type and length.
297-
$data_type = strtolower( $data_types[ $column['name'] ] );
298-
if ( 1 === preg_match( '/^(\w+)\s*\(\s*(\d+)\s*\)/', $data_type, $matches ) ) {
299-
$data_type = $matches[1]; // "varchar"
300-
$data_length = min( $matches[2], $key_length_limit ); // "255"
301-
}
302-
303-
// Apply max length if needed.
294+
/*
295+
* Extract type and length from column data type definition.
296+
*
297+
* This is required when the column data type is inferred from the
298+
* '_mysql_data_types_cache' table, which stores the data type in
299+
* the format "type(length)", such as "varchar(255)".
300+
*/
301+
$max_prefix_length = 100;
302+
$type = strtolower( $data_types[ $column['name'] ] );
303+
$parts = explode( '(', $type );
304+
$column_type = $parts[0];
305+
$column_length = isset( $parts[1] ) ? (int) $parts[1] : null;
306+
307+
/*
308+
* Add an index column prefix length, if needed.
309+
*
310+
* This is required for "text" and "blob" types for columns inferred
311+
* directly from the SQLite schema, and for the following types for
312+
* columns inferred from the '_mysql_data_types_cache' table:
313+
* char, varchar
314+
* text, tinytext, mediumtext, longtext
315+
* blob, tinyblob, mediumblob, longblob
316+
* varbinary
317+
*/
304318
if (
305-
str_contains( $data_type, 'char' )
306-
|| str_starts_with( $data_type, 'var' )
307-
|| str_ends_with( $data_type, 'text' )
308-
|| str_ends_with( $data_type, 'blob' )
319+
str_ends_with( $column_type, 'char' )
320+
|| str_ends_with( $column_type, 'text' )
321+
|| str_ends_with( $column_type, 'blob' )
322+
|| str_starts_with( $column_type, 'var' )
309323
) {
310324
$cols[] = sprintf(
311325
'%s(%d)',
312326
$this->quote_sqlite_identifier( $column['name'] ),
313-
$data_length ?? $key_length_limit
327+
min( $column_length ?? $max_prefix_length, $max_prefix_length )
314328
);
315329
} else {
316330
$cols[] = $this->quote_sqlite_identifier( $column['name'] );

0 commit comments

Comments
 (0)