Skip to content

Commit 874ffb4

Browse files
committed
Apply ALTER COLUMN default changes
Record SET DEFAULT and DROP DEFAULT using shared default handling, in order with the other ALTER TABLE actions. Preserve unrelated column metadata and reject missing columns. Reject NULL defaults on NOT NULL columns and keep accepted AUTO_INCREMENT defaults unset. Cover inserted values, schema metadata, temporary tables, quoted names, expressions, and rollback on failure. Fixes #553
1 parent e3926fc commit 874ffb4

5 files changed

Lines changed: 580 additions & 16 deletions

‎packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3012,6 +3012,10 @@ private function execute_alter_table_statement( WP_Parser_Node $node ): void {
30123012
array( $this->get_saved_db_name( $database ), $table_name )
30133013
)->fetchAll( PDO::FETCH_ASSOC );
30143014

3015+
if ( 0 === count( $column_names ) ) {
3016+
throw $this->new_table_not_found_exception( sprintf( '%s.%s', $database, $table_name ) );
3017+
}
3018+
30153019
// Track column renames and removals.
30163020
$column_map = array_combine(
30173021
array_column( $column_names, 'COLUMN_NAME_LOWERCASE' ),
@@ -8110,6 +8114,14 @@ private function convert_information_schema_exception( WP_SQLite_Information_Sch
81108114
null,
81118115
array( '42S21', 1060, $driver_message )
81128116
);
8117+
case WP_SQLite_Information_Schema_Exception::TYPE_COLUMN_NOT_FOUND:
8118+
$driver_message = sprintf( "Unknown column '%s' in '%s'", $e->get_data()['column_name'], $e->get_data()['table_name'] );
8119+
return $this->new_driver_exception(
8120+
'SQLSTATE[42S22]: Column not found: 1054 ' . $driver_message,
8121+
'42S22',
8122+
null,
8123+
array( '42S22', 1054, $driver_message )
8124+
);
81138125
case WP_SQLite_Information_Schema_Exception::TYPE_DUPLICATE_KEY_NAME:
81148126
$driver_message = sprintf( "Duplicate key name '%s'", $e->get_data()['key_name'] );
81158127
return $this->new_driver_exception(

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php‎

Lines changed: 153 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,16 @@ public function record_alter_table( WP_Parser_Node $node ): void {
765765
continue;
766766
}
767767
}
768+
769+
// ALTER [COLUMN]
770+
if ( WP_MySQL_Lexer::ALTER_SYMBOL === $first_token->id ) {
771+
// SET VISIBLE and SET INVISIBLE are not supported, so only defaults are recorded.
772+
$column_ref = $action->get_first_child_node( 'fieldIdentifier' );
773+
if ( null !== $column_ref && $action->has_child_token( WP_MySQL_Lexer::DEFAULT_SYMBOL ) ) {
774+
$name = $this->get_value( $column_ref );
775+
$this->record_alter_column_default( $table_is_temporary, $table_name, $name, $action );
776+
}
777+
}
768778
}
769779
}
770780

@@ -1002,6 +1012,104 @@ private function record_modify_column(
10021012
$this->record_change_column( $table_is_temporary, $table_name, $column_name, $column_name, $node );
10031013
}
10041014

1015+
/**
1016+
* Record SET DEFAULT or DROP DEFAULT data in the information schema.
1017+
*
1018+
* @param bool $table_is_temporary Whether the table is temporary.
1019+
* @param string $table_name The table name.
1020+
* @param string $column_name The column name.
1021+
* @param WP_Parser_Node $node The "alterListItem" AST node.
1022+
*/
1023+
private function record_alter_column_default(
1024+
bool $table_is_temporary,
1025+
string $table_name,
1026+
string $column_name,
1027+
WP_Parser_Node $node
1028+
): void {
1029+
$columns_table = $this->get_table_name( $table_is_temporary, 'columns' );
1030+
$column = $this->connection->query(
1031+
'SELECT DATA_TYPE, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . '
1032+
WHERE table_schema = ? AND table_name = ? AND column_name = ?',
1033+
array( self::SAVED_DATABASE_NAME, $table_name, $column_name )
1034+
)->fetch( PDO::FETCH_ASSOC );
1035+
if ( false === $column ) {
1036+
throw WP_SQLite_Information_Schema_Exception::column_not_found( $column_name, $table_name );
1037+
}
1038+
1039+
$default = null;
1040+
$extra = trim( str_replace( 'DEFAULT_GENERATED', '', $column['EXTRA'] ) );
1041+
if ( $node->has_child_token( WP_MySQL_Lexer::SET_SYMBOL ) ) {
1042+
$expression = $node->get_first_child_node( 'exprWithParentheses' );
1043+
$literal = $expression ? $this->get_parenthesized_default_literal( $expression ) : null;
1044+
$default = $literal
1045+
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name )
1046+
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name );
1047+
if ( null === $default && 'NO' === $column['IS_NULLABLE'] ) {
1048+
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
1049+
}
1050+
if ( $expression && ! $literal ) {
1051+
if ( str_contains( $extra, 'auto_increment' ) ) {
1052+
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
1053+
}
1054+
$extra = trim( 'DEFAULT_GENERATED ' . $extra );
1055+
}
1056+
}
1057+
1058+
/*
1059+
* MySQL hides SET DEFAULT and DROP DEFAULT on AUTO_INCREMENT columns from
1060+
* the schema, but applies them to inserts that omit the column. Emulating
1061+
* that would need hidden metadata, so the driver keeps generating IDs.
1062+
*/
1063+
if ( str_contains( $extra, 'auto_increment' ) ) {
1064+
$default = null;
1065+
}
1066+
1067+
$this->update_values(
1068+
$columns_table,
1069+
array(
1070+
'column_default' => $default,
1071+
'extra' => $extra,
1072+
),
1073+
array(
1074+
'table_schema' => self::SAVED_DATABASE_NAME,
1075+
'table_name' => $table_name,
1076+
'column_name' => $column_name,
1077+
)
1078+
);
1079+
}
1080+
1081+
/**
1082+
* Find a literal wrapped only in parentheses or unary plus operators.
1083+
*
1084+
* @param WP_Parser_Node $node The default expression.
1085+
* @return WP_Parser_Node|null The literal, or null for other expressions.
1086+
*/
1087+
private function get_parenthesized_default_literal( WP_Parser_Node $node ): ?WP_Parser_Node {
1088+
while ( 'literal' !== $node->rule_name ) {
1089+
$children = $node->get_children();
1090+
if (
1091+
3 === count( $children )
1092+
&& $children[0] instanceof WP_Parser_Token
1093+
&& WP_MySQL_Lexer::OPEN_PAR_SYMBOL === $children[0]->id
1094+
&& $children[2] instanceof WP_Parser_Token
1095+
&& WP_MySQL_Lexer::CLOSE_PAR_SYMBOL === $children[2]->id
1096+
) {
1097+
$children = array( $children[1] );
1098+
} elseif (
1099+
2 === count( $children )
1100+
&& $children[0] instanceof WP_Parser_Token
1101+
&& WP_MySQL_Lexer::PLUS_OPERATOR === $children[0]->id
1102+
) {
1103+
$children = array( $children[1] );
1104+
}
1105+
if ( 1 !== count( $children ) || ! $children[0] instanceof WP_Parser_Node ) {
1106+
return null;
1107+
}
1108+
$node = $children[0];
1109+
}
1110+
return $node;
1111+
}
1112+
10051113
/**
10061114
* Record DROP COLUMN data in the information schema.
10071115
*
@@ -2079,34 +2187,54 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st
20792187
if ( null === $default_attr ) {
20802188
return null;
20812189
}
2190+
return $this->get_default_value( $default_attr, $data_type, $column_name );
2191+
}
20822192

2193+
/**
2194+
* Extract a default value from a column attribute or ALTER COLUMN action.
2195+
*
2196+
* @param WP_Parser_Node $node The "columnAttribute" or "alterListItem" AST node.
2197+
* @param string $data_type The column data type as stored in information schema.
2198+
* @param string $column_name The column name.
2199+
* @return string|null The default value as stored in information schema.
2200+
*/
2201+
private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name ): ?string {
20832202
/*
20842203
* [GRAMMAR]
2085-
* DEFAULT_SYMBOL (
2086-
* signedLiteral
2087-
* | NOW_SYMBOL timeFunctionParameters?
2088-
* | {serverVersion >= 80013}? exprWithParentheses
2089-
* )
2204+
* columnAttribute:
2205+
* DEFAULT_SYMBOL (
2206+
* signedLiteral
2207+
* | NOW_SYMBOL timeFunctionParameters?
2208+
* | {serverVersion >= 80013}? exprWithParentheses
2209+
* )
2210+
*
2211+
* alterListItem:
2212+
* ALTER_SYMBOL COLUMN_SYMBOL? fieldIdentifier SET_SYMBOL DEFAULT_SYMBOL (
2213+
* {serverVersion >= 80014}? exprWithParentheses
2214+
* | signedLiteral
2215+
* )
20902216
*/
20912217

20922218
// DEFAULT NOW()
2093-
if ( $default_attr->has_child_token( WP_MySQL_Lexer::NOW_SYMBOL ) ) {
2219+
if ( $node->has_child_token( WP_MySQL_Lexer::NOW_SYMBOL ) ) {
20942220
return 'CURRENT_TIMESTAMP';
20952221
}
20962222

20972223
// DEFAULT signedLiteral
2098-
$signed_literal = $default_attr->get_first_child_node( 'signedLiteral' );
2224+
$signed_literal = $node->get_first_child_node( 'signedLiteral' );
20992225
if ( $signed_literal ) {
21002226
$literal = $signed_literal->get_first_child_node( 'literal' );
21012227
if ( null === $literal ) {
21022228
// A signed number, such as "-5", has no "literal" child node.
2103-
return $this->get_value( $signed_literal );
2229+
// Like MySQL, drop the unary plus, e.g., "+5" becomes "5".
2230+
$number = ltrim( $this->get_value( $signed_literal ), '+' );
2231+
return $this->normalize_literal_default( $number, $data_type, $column_name );
21042232
}
21052233
return $this->get_literal_default( $literal, $data_type, $column_name );
21062234
}
21072235

21082236
// DEFAULT (expression) - MySQL 8.0.13+ supports exprWithParentheses
2109-
$expr_with_parens = $default_attr->get_first_child_node( 'exprWithParentheses' );
2237+
$expr_with_parens = $node->get_first_child_node( 'exprWithParentheses' );
21102238
if ( $expr_with_parens ) {
21112239
return $this->serialize_mysql_expression( $expr_with_parens );
21122240
}
@@ -2135,14 +2263,24 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
21352263
return 'bit' === $data_type ? "b'{$bool_value}'" : $bool_value;
21362264
}
21372265

2138-
$default = $this->get_value( $literal );
2266+
return $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name );
2267+
}
21392268

2269+
/**
2270+
* Normalize a literal default value for the column data type.
2271+
*
2272+
* @param string $default_value The literal default value.
2273+
* @param string $data_type The column data type as stored in information schema.
2274+
* @param string $column_name The column name.
2275+
* @return string The default value as stored in information schema.
2276+
*/
2277+
private function normalize_literal_default( string $default_value, string $data_type, string $column_name ): string {
21402278
if ( 'bit' === $data_type ) {
21412279
/*
21422280
* @TODO: Validate and normalize defaults from their AST and the full
21432281
* column definition before storing them in the information schema.
21442282
*/
2145-
$bit_default = $this->get_bit_default( $default );
2283+
$bit_default = $this->get_bit_default( $default_value );
21462284
if ( null === $bit_default ) {
21472285
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
21482286
}
@@ -2158,13 +2296,13 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
21582296
* - The charset introducer dropped from text-literal defaults.
21592297
* - Numeric defaults normalized, e.g. 1.0 to 1 or 1e3 to 1000.
21602298
*/
2161-
return $default;
2299+
return $default_value;
21622300
}
21632301

21642302
/**
21652303
* Normalize a BIT default value to a MySQL bit literal.
21662304
*
2167-
* The value may be a bit literal, a hex literal, or a decimal.
2305+
* The value may be a bit literal, a hex literal, or a non-negative decimal.
21682306
*
21692307
* @param string $default_value The BIT default value.
21702308
* @return string|null The default as a bit literal, e.g. "b'101'", or null when not a bit value.
@@ -2194,8 +2332,8 @@ private function get_bit_default( string $default_value ): ?string {
21942332
return "b'" . decbin( hexdec( $matches[1] ) ) . "'";
21952333
}
21962334

2197-
// Decimal, e.g. 5, or a numeric string literal such as '0'.
2198-
if ( is_numeric( $value ) ) {
2335+
// Non-negative decimal, e.g. 5, or a numeric string literal such as '0'.
2336+
if ( is_numeric( $value ) && $value >= 0 ) {
21992337
return "b'" . decbin( (int) $value ) . "'";
22002338
}
22012339

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-exception.php‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ class WP_SQLite_Information_Schema_Exception extends Exception {
1212
// Information schema exception types.
1313
const TYPE_DUPLICATE_TABLE_NAME = 'duplicate-table-name';
1414
const TYPE_DUPLICATE_COLUMN_NAME = 'duplicate-column-name';
15+
const TYPE_COLUMN_NOT_FOUND = 'column-not-found';
1516
const TYPE_DUPLICATE_KEY_NAME = 'duplicate-key-name';
1617
const TYPE_KEY_COLUMN_NOT_FOUND = 'key-column-not-found';
1718
const TYPE_CONSTRAINT_DOES_NOT_EXIST = 'constraint-does-not-exist';
@@ -97,6 +98,24 @@ public static function duplicate_column_name( string $column_name ): WP_SQLite_I
9798
);
9899
}
99100

101+
/**
102+
* Create a column not found exception.
103+
*
104+
* @param string $column_name The name of the affected column.
105+
* @param string $table_name The name of the affected table.
106+
* @return self The exception instance.
107+
*/
108+
public static function column_not_found( string $column_name, string $table_name ): WP_SQLite_Information_Schema_Exception {
109+
return new self(
110+
self::TYPE_COLUMN_NOT_FOUND,
111+
sprintf( "Unknown column '%s' in '%s'.", $column_name, $table_name ),
112+
array(
113+
'column_name' => $column_name,
114+
'table_name' => $table_name,
115+
)
116+
);
117+
}
118+
100119
/**
101120
* Create a duplicate key name exception.
102121
*

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Metadata_Tests.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2413,7 +2413,7 @@ public function testInformationSchemaAlterTableDropMissingConstraint(): void {
24132413
$this->expectException( WP_MySQL_On_SQLite_Exception::class );
24142414
$this->expectExceptionMessage( "SQLSTATE[HY000]: General error: 3940 Constraint 'cnst' does not exist." );
24152415
$this->expectExceptionCode( 'HY000' );
2416-
$this->assertQuery( 'ALTER TABLE t2 DROP CONSTRAINT cnst' );
2416+
$this->assertQuery( 'ALTER TABLE t1 DROP CONSTRAINT cnst' );
24172417
}
24182418

24192419
public function testInformationSchemaAlterTableDropConstraintWithAmbiguousName(): void {

0 commit comments

Comments
 (0)