Skip to content

Commit 0e17bbd

Browse files
committed
Apply ALTER COLUMN default changes
Record SET DEFAULT and DROP DEFAULT using shared default handling. Preserve unrelated column metadata and reject missing columns or conflicting actions. 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 0e17bbd

5 files changed

Lines changed: 585 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: 174 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,41 @@ public function record_alter_table( WP_Parser_Node $node ): void {
659659
// Check if a temporary table with the given name exists.
660660
$table_is_temporary = $this->temporary_table_exists( $table_name );
661661

662+
// ALTER [COLUMN] applies once to an existing column that is not changed by another action.
663+
$altered_columns = array();
664+
$changed_columns = array();
665+
foreach ( $actions as $action ) {
666+
$first_token = $action->get_first_child_token();
667+
$column_ref = $action->get_first_child_node( 'fieldIdentifier' );
668+
if ( null === $column_ref ) {
669+
continue;
670+
}
671+
$name = $this->get_value( $column_ref );
672+
$key = strtolower( $name );
673+
if ( WP_MySQL_Lexer::ALTER_SYMBOL === $first_token->id ) {
674+
if ( isset( $altered_columns[ $key ] ) ) {
675+
throw WP_SQLite_Information_Schema_Exception::column_not_found( $name, $table_name );
676+
}
677+
$altered_columns[ $key ] = array( $name, $action );
678+
} elseif (
679+
WP_MySQL_Lexer::CHANGE_SYMBOL === $first_token->id
680+
|| WP_MySQL_Lexer::MODIFY_SYMBOL === $first_token->id
681+
|| ( WP_MySQL_Lexer::DROP_SYMBOL === $first_token->id && ! $action->has_child_token( WP_MySQL_Lexer::FOREIGN_SYMBOL ) )
682+
) {
683+
$changed_columns[ $key ] = true;
684+
}
685+
}
686+
foreach ( $altered_columns as $key => list( $name, $action ) ) {
687+
if ( isset( $changed_columns[ $key ] ) ) {
688+
throw WP_SQLite_Information_Schema_Exception::column_not_found( $name, $table_name );
689+
}
690+
691+
// SET VISIBLE and SET INVISIBLE are not supported, so only defaults are recorded.
692+
if ( $action->has_child_token( WP_MySQL_Lexer::DEFAULT_SYMBOL ) ) {
693+
$this->record_alter_column_default( $table_is_temporary, $table_name, $name, $action );
694+
}
695+
}
696+
662697
foreach ( $actions as $action ) {
663698
$first_token = $action->get_first_child_token();
664699

@@ -1002,6 +1037,100 @@ private function record_modify_column(
10021037
$this->record_change_column( $table_is_temporary, $table_name, $column_name, $column_name, $node );
10031038
}
10041039

1040+
/**
1041+
* Record SET DEFAULT or DROP DEFAULT data in the information schema.
1042+
*
1043+
* @param bool $table_is_temporary Whether the table is temporary.
1044+
* @param string $table_name The table name.
1045+
* @param string $column_name The column name.
1046+
* @param WP_Parser_Node $node The "alterListItem" AST node.
1047+
*/
1048+
private function record_alter_column_default(
1049+
bool $table_is_temporary,
1050+
string $table_name,
1051+
string $column_name,
1052+
WP_Parser_Node $node
1053+
): void {
1054+
$columns_table = $this->get_table_name( $table_is_temporary, 'columns' );
1055+
$column = $this->connection->query(
1056+
'SELECT DATA_TYPE, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . '
1057+
WHERE table_schema = ? AND table_name = ? AND column_name = ?',
1058+
array( self::SAVED_DATABASE_NAME, $table_name, $column_name )
1059+
)->fetch( PDO::FETCH_ASSOC );
1060+
if ( false === $column ) {
1061+
throw WP_SQLite_Information_Schema_Exception::column_not_found( $column_name, $table_name );
1062+
}
1063+
1064+
$default = null;
1065+
$extra = trim( str_replace( 'DEFAULT_GENERATED', '', $column['EXTRA'] ) );
1066+
if ( $node->has_child_token( WP_MySQL_Lexer::SET_SYMBOL ) ) {
1067+
$expression = $node->get_first_child_node( 'exprWithParentheses' );
1068+
$literal = $expression ? $this->get_parenthesized_default_literal( $expression ) : null;
1069+
$default = $literal
1070+
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name )
1071+
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name );
1072+
if ( null === $default && 'NO' === $column['IS_NULLABLE'] ) {
1073+
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
1074+
}
1075+
if ( $expression && ! $literal ) {
1076+
if ( str_contains( $extra, 'auto_increment' ) ) {
1077+
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
1078+
}
1079+
$extra = trim( 'DEFAULT_GENERATED ' . $extra );
1080+
}
1081+
}
1082+
1083+
// MySQL accepts literal defaults for AUTO_INCREMENT columns but ignores them.
1084+
if ( str_contains( $extra, 'auto_increment' ) ) {
1085+
$default = null;
1086+
}
1087+
1088+
$this->update_values(
1089+
$columns_table,
1090+
array(
1091+
'column_default' => $default,
1092+
'extra' => $extra,
1093+
),
1094+
array(
1095+
'table_schema' => self::SAVED_DATABASE_NAME,
1096+
'table_name' => $table_name,
1097+
'column_name' => $column_name,
1098+
)
1099+
);
1100+
}
1101+
1102+
/**
1103+
* Find a literal wrapped only in parentheses or unary plus operators.
1104+
*
1105+
* @param WP_Parser_Node $node The default expression.
1106+
* @return WP_Parser_Node|null The literal, or null for other expressions.
1107+
*/
1108+
private function get_parenthesized_default_literal( WP_Parser_Node $node ): ?WP_Parser_Node {
1109+
while ( 'literal' !== $node->rule_name ) {
1110+
$children = $node->get_children();
1111+
if (
1112+
3 === count( $children )
1113+
&& $children[0] instanceof WP_Parser_Token
1114+
&& WP_MySQL_Lexer::OPEN_PAR_SYMBOL === $children[0]->id
1115+
&& $children[2] instanceof WP_Parser_Token
1116+
&& WP_MySQL_Lexer::CLOSE_PAR_SYMBOL === $children[2]->id
1117+
) {
1118+
$children = array( $children[1] );
1119+
} elseif (
1120+
2 === count( $children )
1121+
&& $children[0] instanceof WP_Parser_Token
1122+
&& WP_MySQL_Lexer::PLUS_OPERATOR === $children[0]->id
1123+
) {
1124+
$children = array( $children[1] );
1125+
}
1126+
if ( 1 !== count( $children ) || ! $children[0] instanceof WP_Parser_Node ) {
1127+
return null;
1128+
}
1129+
$node = $children[0];
1130+
}
1131+
return $node;
1132+
}
1133+
10051134
/**
10061135
* Record DROP COLUMN data in the information schema.
10071136
*
@@ -2079,34 +2208,54 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st
20792208
if ( null === $default_attr ) {
20802209
return null;
20812210
}
2211+
return $this->get_default_value( $default_attr, $data_type, $column_name );
2212+
}
20822213

2214+
/**
2215+
* Extract a default value from a column attribute or ALTER COLUMN action.
2216+
*
2217+
* @param WP_Parser_Node $node The "columnAttribute" or "alterListItem" AST node.
2218+
* @param string $data_type The column data type as stored in information schema.
2219+
* @param string $column_name The column name.
2220+
* @return string|null The default value as stored in information schema.
2221+
*/
2222+
private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name ): ?string {
20832223
/*
20842224
* [GRAMMAR]
2085-
* DEFAULT_SYMBOL (
2086-
* signedLiteral
2087-
* | NOW_SYMBOL timeFunctionParameters?
2088-
* | {serverVersion >= 80013}? exprWithParentheses
2089-
* )
2225+
* columnAttribute:
2226+
* DEFAULT_SYMBOL (
2227+
* signedLiteral
2228+
* | NOW_SYMBOL timeFunctionParameters?
2229+
* | {serverVersion >= 80013}? exprWithParentheses
2230+
* )
2231+
*
2232+
* alterListItem:
2233+
* ALTER_SYMBOL COLUMN_SYMBOL? fieldIdentifier SET_SYMBOL DEFAULT_SYMBOL (
2234+
* {serverVersion >= 80014}? exprWithParentheses
2235+
* | signedLiteral
2236+
* )
20902237
*/
20912238

20922239
// DEFAULT NOW()
2093-
if ( $default_attr->has_child_token( WP_MySQL_Lexer::NOW_SYMBOL ) ) {
2240+
if ( $node->has_child_token( WP_MySQL_Lexer::NOW_SYMBOL ) ) {
20942241
return 'CURRENT_TIMESTAMP';
20952242
}
20962243

20972244
// DEFAULT signedLiteral
2098-
$signed_literal = $default_attr->get_first_child_node( 'signedLiteral' );
2245+
$signed_literal = $node->get_first_child_node( 'signedLiteral' );
20992246
if ( $signed_literal ) {
21002247
$literal = $signed_literal->get_first_child_node( 'literal' );
21012248
if ( null === $literal ) {
21022249
// A signed number, such as "-5", has no "literal" child node.
2103-
return $this->get_value( $signed_literal );
2250+
// Like MySQL, drop the unary plus, e.g., "+5" becomes "5".
2251+
$number = ltrim( $this->get_value( $signed_literal ), '+' );
2252+
return $this->normalize_literal_default( $number, $data_type, $column_name );
21042253
}
21052254
return $this->get_literal_default( $literal, $data_type, $column_name );
21062255
}
21072256

21082257
// DEFAULT (expression) - MySQL 8.0.13+ supports exprWithParentheses
2109-
$expr_with_parens = $default_attr->get_first_child_node( 'exprWithParentheses' );
2258+
$expr_with_parens = $node->get_first_child_node( 'exprWithParentheses' );
21102259
if ( $expr_with_parens ) {
21112260
return $this->serialize_mysql_expression( $expr_with_parens );
21122261
}
@@ -2135,14 +2284,24 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
21352284
return 'bit' === $data_type ? "b'{$bool_value}'" : $bool_value;
21362285
}
21372286

2138-
$default = $this->get_value( $literal );
2287+
return $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name );
2288+
}
21392289

2290+
/**
2291+
* Normalize a literal default value for the column data type.
2292+
*
2293+
* @param string $default_value The literal default value.
2294+
* @param string $data_type The column data type as stored in information schema.
2295+
* @param string $column_name The column name.
2296+
* @return string The default value as stored in information schema.
2297+
*/
2298+
private function normalize_literal_default( string $default_value, string $data_type, string $column_name ): string {
21402299
if ( 'bit' === $data_type ) {
21412300
/*
21422301
* @TODO: Validate and normalize defaults from their AST and the full
21432302
* column definition before storing them in the information schema.
21442303
*/
2145-
$bit_default = $this->get_bit_default( $default );
2304+
$bit_default = $this->get_bit_default( $default_value );
21462305
if ( null === $bit_default ) {
21472306
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
21482307
}
@@ -2158,13 +2317,13 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
21582317
* - The charset introducer dropped from text-literal defaults.
21592318
* - Numeric defaults normalized, e.g. 1.0 to 1 or 1e3 to 1000.
21602319
*/
2161-
return $default;
2320+
return $default_value;
21622321
}
21632322

21642323
/**
21652324
* Normalize a BIT default value to a MySQL bit literal.
21662325
*
2167-
* The value may be a bit literal, a hex literal, or a decimal.
2326+
* The value may be a bit literal, a hex literal, or a non-negative decimal.
21682327
*
21692328
* @param string $default_value The BIT default value.
21702329
* @return string|null The default as a bit literal, e.g. "b'101'", or null when not a bit value.
@@ -2194,8 +2353,8 @@ private function get_bit_default( string $default_value ): ?string {
21942353
return "b'" . decbin( hexdec( $matches[1] ) ) . "'";
21952354
}
21962355

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

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