Skip to content

Commit c2d9d32

Browse files
authored
Fix invalid default values in show create output (#141)
This PR addresses an issue where the output of `show create table` is incorrect when the table has a `NULL` column without a default value. Here is an example: ```sql -- Original MySQL query CREATE TABLE `wp_usermeta` ( `umeta_id` bigint(20) unsigned NOT NULL auto_increment, `user_id` bigint(20) unsigned NOT NULL default '0', `meta_key` varchar(255) default NULL, `meta_value` longtext, PRIMARY KEY (`umeta_id`), KEY `user_id` (`user_id`), KEY `meta_key` (`meta_key`(191)) ) -- Output by `SHOW CREATE TABLE` via SQLite plugin CREATE TABLE `wp_usermeta` ( `umeta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` bigint(20) unsigned NOT NULL DEFAULT '0', `meta_key` varchar(255) DEFAULT NULL, `meta_value` longtext DEFAULT , -- Default value missing PRIMARY KEY (`umeta_id`), KEY `meta_key` (`meta_key`), KEY `user_id` (`user_id`) ); -- After this fix CREATE TABLE `wp_usermeta` ( `umeta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` bigint(20) unsigned NOT NULL DEFAULT '0', `meta_key` varchar(255) DEFAULT NULL, `meta_value` longtext, PRIMARY KEY (`umeta_id`), KEY `meta_key` (`meta_key`), KEY `user_id` (`user_id`) ); ```
1 parent 5f862d3 commit c2d9d32

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

tests/WP_SQLite_Translator_Tests.php

+24
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,30 @@ public function testShowCreateTableWithColumnKeys() {
457457
);
458458
}
459459

460+
public function testShowCreateTableWithCorrectDefaultValues() {
461+
$this->assertQuery(
462+
"CREATE TABLE _tmp__table (
463+
ID BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL,
464+
default_empty_string VARCHAR(255) default '',
465+
null_no_default VARCHAR(255),
466+
);"
467+
);
468+
469+
$this->assertQuery(
470+
'SHOW CREATE TABLE _tmp__table;'
471+
);
472+
$results = $this->engine->get_query_results();
473+
$this->assertEquals(
474+
'CREATE TABLE `_tmp__table` (
475+
`ID` bigint NOT NULL AUTO_INCREMENT,
476+
`default_empty_string` varchar(255) DEFAULT \'\',
477+
`null_no_default` varchar(255),
478+
PRIMARY KEY (`ID`)
479+
);',
480+
$results[0]->{'Create Table'}
481+
);
482+
}
483+
460484
public function testSelectIndexHintForce() {
461485
$this->assertQuery( "INSERT INTO _options (option_name) VALUES ('first');" );
462486
$result = $this->assertQuery(

wp-includes/sqlite/class-wp-sqlite-translator.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -3522,7 +3522,7 @@ protected function get_column_definitions( $table_name, $columns ) {
35223522
$definition[] = 'NOT NULL';
35233523
}
35243524

3525-
if ( '' !== $column->dflt_value && ! $is_auto_incr ) {
3525+
if ( null !== $column->dflt_value && '' !== $column->dflt_value && ! $is_auto_incr ) {
35263526
$definition[] = 'DEFAULT ' . $column->dflt_value;
35273527
}
35283528

0 commit comments

Comments
 (0)