25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(mysql): refuse literal defaults on BLOB, TEXT, GEOMETRY and JSON columns
Jeff2189baacae56
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs b/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rsindex 5d96aadd35..fe2f8a5a6f 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs@@ -11,10 +11,15 @@ use super::util::{clean, format_default_for_sql, is_protected_manticore_id_column, normalize_default, original_comment,original_default, qualified_table, quote_ident, quote_string,};+use super::validation::mysql_literal_default_error;use crate::table_structure_sql::ColumnExtra;const SINGLE_COLUMN_ADD_PREVIEW_ID_PREFIX: &str = "ddl-preview:";+fn single_column_literal_default_error(options: &SingleColumnAlterSqlOptions) -> Option<String> {+ mysql_literal_default_error(options.database_type, options.driver_profile.as_deref(), false, &options.column)+}+pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> TableStructureSqlResult {let capabilities = capabilities_for(options.database_type, options.driver_profile.as_deref());let dialect = capabilities.dialect;@@ -61,6 +66,10 @@ pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> Tawarnings.push("Column type cannot be empty.".to_string());return TableStructureSqlResult { statements, warnings };}+ if let Some(warning) = single_column_literal_default_error(&options) {+ warnings.push(warning);+ return TableStructureSqlResult { statements, warnings };+ }if !capabilities.comment && !clean(&options.column.comment).is_empty() {warnings.push(format!("Column comments are not supported for {database_label} from this editor; the comment for \"{}\" was ignored.",@@ -92,6 +101,10 @@ pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> Tawarnings.push("No changes detected for this column.".to_string());return TableStructureSqlResult { statements, warnings };}+ if let Some(warning) = single_column_literal_default_error(&options) {+ warnings.push(warning);+ return TableStructureSqlResult { statements, warnings };+ }let has_rename = options.column.name != original.name;let has_comment_change = clean(&options.column.comment) != original_comment(&options.column);diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rsindex c287c62c68..3aae6188d3 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs@@ -14,7 +14,9 @@ use super::types::{TableStructureSqlOptions, TableStructureSqlResult};use super::util::{clean, format_default_for_sql, normalize_default, qualified_new_table, quote_ident, quote_new_ident, quote_string,};-use super::validation::{validate_columns, validate_concurrent_index_scope, validate_dameng_identity};+use super::validation::{+ validate_columns, validate_concurrent_index_scope, validate_dameng_identity, validate_mysql_literal_defaults,+};use crate::models::connection::DatabaseType;fn is_sqlite_integer_family_type(data_type: &str) -> bool {@@ -64,6 +66,7 @@ pub(super) fn build_create_table_sql_with_partition_clause(}validate_columns(&active_columns, &mut warnings);validate_dameng_identity(&options, &active_columns, &mut warnings);+ validate_mysql_literal_defaults(&options, &active_columns, &mut warnings);transwarp::validate_create_options(&options, &active_columns, &mut warnings);if !warnings.is_empty() {return TableStructureSqlResult { statements: Vec::new(), warnings };diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rsindex ab791fa046..9752cd7bb1 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs@@ -6832,9 +6832,11 @@ fn mysql_text_default_is_quoted() {col.data_type = "text".to_string();col.default_value = "default value".to_string();+ // MariaDB accepts a literal default on TEXT; MySQL refuses it (see+ // `mysql_literal_default_on_blob_text_json_geometry_is_refused`).let result = build_create_table_sql(TableStructureSqlOptions {database_type: Some(DatabaseType::Mysql),- driver_profile: None,+ driver_profile: Some("mariadb".to_string()),schema: None,table_name: "products".to_string(),columns: vec![col],@@ -9441,3 +9443,88 @@ fn create_partitioned_table_is_supported_for_kingbase() {assert!(result.warnings.is_empty(), "{:?}", result.warnings);assert!(result.statements[0].ends_with(") PARTITION BY LIST (\"region\");"), "{}", result.statements[0]);}++#[test]+fn mysql_literal_default_on_blob_text_json_geometry_is_refused() {+ // (data type, default, driver profile, expected DEFAULT clause; None means refused)+ let cases: &[(&str, &str, Option<&str>, Option<&str>)] = &[+ ("text", "''", None, None),+ ("TEXT", "x", None, None),+ ("mediumtext", "''", None, None),+ ("longtext", "a(b)", None, None),+ ("blob", "abc", None, None),+ ("json", "{}", None, None),+ ("geometry", "x", None, None),+ ("text", "('')", None, Some("DEFAULT ('')")),+ ("json", "(json_object())", None, Some("DEFAULT (json_object())")),+ ("text", "''", Some("mariadb"), Some("DEFAULT ''")),+ ("text", "", None, Some("`note` text NOT NULL")),+ ("text", "NULL", None, Some("`note` text NOT NULL")),+ ("varchar(255)", "''", None, Some("DEFAULT ''")),+ ("char(10)", "abc", None, Some("DEFAULT 'abc'")),+ ];+ for (data_type, default_value, driver_profile, expected) in cases {+ let mut note = column("note");+ note.data_type = data_type.to_string();+ note.is_nullable = false;+ note.default_value = default_value.to_string();+ let mut options = structure_change_options(DatabaseType::Mysql, None, "t", vec![note.clone()]);+ options.driver_profile = driver_profile.map(str::to_string);+ let added = build_table_structure_change_sql(options.clone());+ let created = build_create_table_sql(options);+ note.id = "ddl-preview:new:note".to_string();+ let single = build_single_column_alter_sql(SingleColumnAlterSqlOptions {+ database_type: Some(DatabaseType::Mysql),+ driver_profile: driver_profile.map(str::to_string),+ schema: None,+ table_name: "t".to_string(),+ column: note,+ });+ let case = format!("{data_type} DEFAULT {default_value:?} ({driver_profile:?})");+ match expected {+ None => {+ let warning = format!(+ "MySQL does not allow a literal default on {} column \"note\". Remove the default, or on MySQL 8.0.13 or later use an expression default such as ('').",+ data_type.to_ascii_lowercase()+ );+ assert_eq!(added.warnings, vec![warning.clone()], "{case}");+ assert_eq!(created.warnings, vec![warning.clone()], "{case}");+ assert!(created.statements.is_empty(), "{case}: {:?}", created.statements);+ assert_eq!(single.warnings, vec![warning], "{case}");+ assert!(single.statements.is_empty(), "{case}: {:?}", single.statements);+ }+ Some(clause) => {+ for result in [&added, &created, &single] {+ assert!(result.warnings.is_empty(), "{case}: {:?}", result.warnings);+ assert_eq!(result.statements.len(), 1, "{case}: {:?}", result.statements);+ assert!(result.statements[0].contains(clause), "{case}: {}", result.statements[0]);+ }+ }+ }+ }+}++#[test]+fn mysql_literal_default_check_only_covers_defaults_the_draft_emits() {+ // MySQL 8.0.13+ reports an expression default on TEXT this way. Leaving it+ // unchanged must not block an unrelated edit to the column.+ let mut kept = existing_pk_column("note", "text", false, false);+ kept.original.as_mut().unwrap().column_default = Some("_utf8mb4\\'\\'".to_string());+ kept.default_value = "_utf8mb4\\'\\'".to_string();+ kept.is_nullable = true;+ let result = build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "t", vec![kept]));+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);++ // Turning a VARCHAR with a literal default into TEXT would carry the+ // literal into the MODIFY statement.+ let mut retyped = existing_pk_column("note", "varchar(255)", false, false);+ retyped.original.as_mut().unwrap().column_default = Some("".to_string());+ retyped.data_type = "text".to_string();+ retyped.default_value = "''".to_string();+ let result =+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "t", vec![retyped]));+ assert_eq!(+ result.warnings,+ vec!["MySQL does not allow a literal default on text column \"note\". Remove the default, or on MySQL 8.0.13 or later use an expression default such as ('').".to_string()]+ );+}diff --git a/crates/dbx-sql-schema/src/table_structure_sql/validation.rs b/crates/dbx-sql-schema/src/table_structure_sql/validation.rsindex a63d7eded6..363e9adef5 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/validation.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/validation.rs@@ -2,7 +2,8 @@ use super::column_format::has_dameng_identity;use super::dialect::{capabilities_for, StructureDialect};use super::indexes::has_existing_index_change;use super::types::{EditableStructureColumn, TableStructureSqlOptions};-use super::util::clean;+use super::util::{clean, normalize_default, original_default};+use crate::models::connection::DatabaseType;/// Hard errors for `CREATE INDEX CONCURRENTLY` requests the editor cannot/// honor safely. Unlike the advisory warnings in [`validate_draft`], these@@ -43,6 +44,7 @@ pub fn validate_draft(options: &TableStructureSqlOptions) -> Vec<String> {let active_columns: Vec<_> = options.columns.iter().filter(|column| !column.marked_for_drop).collect();validate_columns(&active_columns, &mut warnings);validate_dameng_identity(options, &active_columns, &mut warnings);+ validate_mysql_literal_defaults(options, &active_columns, &mut warnings);validate_gin_opclass_warnings(options, &mut warnings);for index in options.indexes@@ -62,6 +64,90 @@ pub fn validate_draft(options: &TableStructureSqlOptions) -> Vec<String> {warnings}+pub(super) fn validate_mysql_literal_defaults(+ options: &TableStructureSqlOptions,+ columns: &[&EditableStructureColumn],+ warnings: &mut Vec<String>,+) {+ for column in columns {+ if let Some(warning) = mysql_literal_default_error(+ options.database_type,+ options.driver_profile.as_deref(),+ options.is_gaussdb_m_mode,+ column,+ ) {+ warnings.push(warning);+ }+ }+}++/// MySQL rejects a literal default on BLOB, TEXT, GEOMETRY and JSON columns+/// with `ERROR 1101`. The DDL runs statement by statement, so letting it+/// through leaves the earlier statements of the batch applied. MySQL 8.0.13+/// and later accept an expression default written in parentheses, such as+/// `('')`, which the generator passes through unchanged, so only a value that+/// would be rendered as a literal is refused. MariaDB accepts the literal form+/// and is not checked.+///+/// A column is only checked when the draft would emit its default: a new+/// column, or an existing one whose type or default changed. An unchanged+/// default on an existing column came from the server, and refusing it would+/// block unrelated edits to the table.+pub(super) fn mysql_literal_default_error(+ database_type: Option<DatabaseType>,+ driver_profile: Option<&str>,+ is_gaussdb_m_mode: bool,+ column: &EditableStructureColumn,+) -> Option<String> {+ if database_type != Some(DatabaseType::Mysql)+ || is_gaussdb_m_mode+ || driver_profile.is_some_and(|profile| profile.trim().eq_ignore_ascii_case("mariadb"))+ {+ return None;+ }+ let base_type = column.data_type.split('(').next().unwrap_or_default().trim().to_ascii_lowercase();+ if !is_mysql_type_without_literal_default(&base_type) {+ return None;+ }+ let default_value = normalize_default(Some(&column.default_value));+ if default_value.is_empty() || (default_value.starts_with('(') && default_value.ends_with(')')) {+ return None;+ }+ if let Some(original) = &column.original {+ if column.data_type.trim() == original.data_type.trim() && default_value == original_default(column) {+ return None;+ }+ }+ Some(format!(+ "MySQL does not allow a literal default on {base_type} column \"{}\". Remove the default, or on MySQL 8.0.13 or later use an expression default such as ('').",+ column.name+ ))+}++fn is_mysql_type_without_literal_default(base_type: &str) -> bool {+ matches!(+ base_type,+ "tinytext"+ | "text"+ | "mediumtext"+ | "longtext"+ | "tinyblob"+ | "blob"+ | "mediumblob"+ | "longblob"+ | "json"+ | "geometry"+ | "point"+ | "linestring"+ | "polygon"+ | "multipoint"+ | "multilinestring"+ | "multipolygon"+ | "geometrycollection"+ | "geomcollection"+ )+}+pub(super) fn validate_dameng_identity(options: &TableStructureSqlOptions,columns: &[&EditableStructureColumn],