Skip to content

Commit 503958e

Browse files
authored
Add support for ALTER COLUMN with SET DEFAULT and DROP DEFAULT (#555)
Previously, `ALTER TABLE ... ALTER COLUMN ... SET DEFAULT` and `DROP DEFAULT` succeeded but left the old defaults in place. This PR makes **new inserts and schema metadata use the changed defaults**, while preserving existing row values and unrelated column attributes. For example, after setting an integer column's default from `1` to `5` and dropping a string column's default of `'x'`, an insert that omits both columns now uses `5` and `NULL`. The change also handles the related error and compatibility cases: - Rejects `NULL` defaults on `NOT NULL` columns and preserves automatic ID generation. - Applies `ALTER COLUMN` changes in order with the other `ALTER TABLE` actions, reports missing tables and columns correctly, and rolls back failed changes. - Covers permanent and temporary tables, quoted names, literal and expression defaults, inserted values, and schema metadata with regression tests. `SET DEFAULT (expr)` on an `ON UPDATE CURRENT_TIMESTAMP` column **stops its automatic update**, because the driver doesn't create the update trigger for columns with an expression default. Fixing that detection alone would let the trigger overwrite explicitly written timestamps on many more tables, so it's fixed together with the trigger in #554. Keeping a nullable column without a default after `DROP DEFAULT` is tracked in #556. The existing PDO coding-standard exemption also covers the plugin's symlinked copy of the driver. Fixes #553. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added support for changing or removing column defaults with `ALTER TABLE`, including literal and expression defaults. Updated defaults appear in column metadata and apply to subsequent inserts. * **Bug Fixes** * Improved handling and validation of signed numeric and `BIT` defaults. * Missing tables and columns now return more accurate MySQL-compatible errors. * Improved recognition of `ON UPDATE CURRENT_TIMESTAMP` column settings. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent b5dc0cc commit 503958e

6 files changed

Lines changed: 589 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: 152 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 DEFAULT and DROP DEFAULT
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,103 @@ 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+
/*
1040+
* MySQL accepts these changes but hides them from its schema.
1041+
* These are known MySQL bugs that are not worth replicating.
1042+
*
1043+
* @see https://bugs.mysql.com/bug.php?id=111702
1044+
* @see https://bugs.mysql.com/bug.php?id=80222
1045+
*/
1046+
if ( str_contains( $column['EXTRA'], 'auto_increment' ) ) {
1047+
throw new Exception( 'SET DEFAULT and DROP DEFAULT on AUTO_INCREMENT columns are not supported.' );
1048+
}
1049+
1050+
$default = null;
1051+
$extra = trim( str_replace( 'DEFAULT_GENERATED', '', $column['EXTRA'] ) );
1052+
if ( $node->has_child_token( WP_MySQL_Lexer::SET_SYMBOL ) ) {
1053+
$expression = $node->get_first_child_node( 'exprWithParentheses' );
1054+
$literal = $expression ? $this->get_parenthesized_default_literal( $expression ) : null;
1055+
$default = $literal
1056+
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name )
1057+
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name );
1058+
if ( null === $default && 'NO' === $column['IS_NULLABLE'] ) {
1059+
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
1060+
}
1061+
if ( $expression && ! $literal ) {
1062+
$extra = trim( 'DEFAULT_GENERATED ' . $extra );
1063+
}
1064+
}
1065+
1066+
$this->update_values(
1067+
$columns_table,
1068+
array(
1069+
'column_default' => $default,
1070+
'extra' => $extra,
1071+
),
1072+
array(
1073+
'table_schema' => self::SAVED_DATABASE_NAME,
1074+
'table_name' => $table_name,
1075+
'column_name' => $column_name,
1076+
)
1077+
);
1078+
}
1079+
1080+
/**
1081+
* Find a literal wrapped only in parentheses or unary plus operators.
1082+
*
1083+
* @param WP_Parser_Node $node The default expression.
1084+
* @return WP_Parser_Node|null The literal, or null for other expressions.
1085+
*/
1086+
private function get_parenthesized_default_literal( WP_Parser_Node $node ): ?WP_Parser_Node {
1087+
while ( 'literal' !== $node->rule_name ) {
1088+
$children = $node->get_children();
1089+
if (
1090+
3 === count( $children )
1091+
&& $children[0] instanceof WP_Parser_Token
1092+
&& WP_MySQL_Lexer::OPEN_PAR_SYMBOL === $children[0]->id
1093+
&& $children[2] instanceof WP_Parser_Token
1094+
&& WP_MySQL_Lexer::CLOSE_PAR_SYMBOL === $children[2]->id
1095+
) {
1096+
$children = array( $children[1] );
1097+
} elseif (
1098+
2 === count( $children )
1099+
&& $children[0] instanceof WP_Parser_Token
1100+
&& WP_MySQL_Lexer::PLUS_OPERATOR === $children[0]->id
1101+
) {
1102+
$children = array( $children[1] );
1103+
}
1104+
if ( 1 !== count( $children ) || ! $children[0] instanceof WP_Parser_Node ) {
1105+
return null;
1106+
}
1107+
$node = $children[0];
1108+
}
1109+
return $node;
1110+
}
1111+
10051112
/**
10061113
* Record DROP COLUMN data in the information schema.
10071114
*
@@ -2079,34 +2186,54 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st
20792186
if ( null === $default_attr ) {
20802187
return null;
20812188
}
2189+
return $this->get_default_value( $default_attr, $data_type, $column_name );
2190+
}
20822191

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

20922217
// DEFAULT NOW()
2093-
if ( $default_attr->has_child_token( WP_MySQL_Lexer::NOW_SYMBOL ) ) {
2218+
if ( $node->has_child_token( WP_MySQL_Lexer::NOW_SYMBOL ) ) {
20942219
return 'CURRENT_TIMESTAMP';
20952220
}
20962221

20972222
// DEFAULT signedLiteral
2098-
$signed_literal = $default_attr->get_first_child_node( 'signedLiteral' );
2223+
$signed_literal = $node->get_first_child_node( 'signedLiteral' );
20992224
if ( $signed_literal ) {
21002225
$literal = $signed_literal->get_first_child_node( 'literal' );
21012226
if ( null === $literal ) {
21022227
// A signed number, such as "-5", has no "literal" child node.
2103-
return $this->get_value( $signed_literal );
2228+
// Like MySQL, drop the unary plus, e.g., "+5" becomes "5".
2229+
$number = ltrim( $this->get_value( $signed_literal ), '+' );
2230+
return $this->normalize_literal_default( $number, $data_type, $column_name );
21042231
}
21052232
return $this->get_literal_default( $literal, $data_type, $column_name );
21062233
}
21072234

21082235
// DEFAULT (expression) - MySQL 8.0.13+ supports exprWithParentheses
2109-
$expr_with_parens = $default_attr->get_first_child_node( 'exprWithParentheses' );
2236+
$expr_with_parens = $node->get_first_child_node( 'exprWithParentheses' );
21102237
if ( $expr_with_parens ) {
21112238
return $this->serialize_mysql_expression( $expr_with_parens );
21122239
}
@@ -2135,14 +2262,24 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
21352262
return 'bit' === $data_type ? "b'{$bool_value}'" : $bool_value;
21362263
}
21372264

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

2268+
/**
2269+
* Normalize a literal default value for the column data type.
2270+
*
2271+
* @param string $default_value The literal default value.
2272+
* @param string $data_type The column data type as stored in information schema.
2273+
* @param string $column_name The column name.
2274+
* @return string The default value as stored in information schema.
2275+
*/
2276+
private function normalize_literal_default( string $default_value, string $data_type, string $column_name ): string {
21402277
if ( 'bit' === $data_type ) {
21412278
/*
21422279
* @TODO: Validate and normalize defaults from their AST and the full
21432280
* column definition before storing them in the information schema.
21442281
*/
2145-
$bit_default = $this->get_bit_default( $default );
2282+
$bit_default = $this->get_bit_default( $default_value );
21462283
if ( null === $bit_default ) {
21472284
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
21482285
}
@@ -2158,13 +2295,13 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
21582295
* - The charset introducer dropped from text-literal defaults.
21592296
* - Numeric defaults normalized, e.g. 1.0 to 1 or 1e3 to 1000.
21602297
*/
2161-
return $default;
2298+
return $default_value;
21622299
}
21632300

21642301
/**
21652302
* Normalize a BIT default value to a MySQL bit literal.
21662303
*
2167-
* The value may be a bit literal, a hex literal, or a decimal.
2304+
* The value may be a bit literal, a hex literal, or a non-negative decimal.
21682305
*
21692306
* @param string $default_value The BIT default value.
21702307
* @return string|null The default as a bit literal, e.g. "b'101'", or null when not a bit value.
@@ -2194,8 +2331,8 @@ private function get_bit_default( string $default_value ): ?string {
21942331
return "b'" . decbin( hexdec( $matches[1] ) ) . "'";
21952332
}
21962333

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

‎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)