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
refactor(sql): share DDL rendering between transfer and schema diff
jearhe88755811ba2a
diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rsindex 855e619a0d..3413185353 100644--- a/crates/dbx-core/src/data/transfer.rs+++ b/crates/dbx-core/src/data/transfer.rs@@ -5,6 +5,7 @@ pub use dbx_sql::value_literals::{quote_postgres_string_literal,};+use dbx_sql::postgres_index_key::decorate_postgres_index_key;use regex::Regex;use serde::{Deserialize, Serialize};use std::collections::{HashMap, HashSet};@@ -2417,18 +2418,7 @@ fn postgres_index_column_sql(// The opclass is read separately from `pg_index.indclass` for every key position// (including expression keys) and appended uniformly — it never lives inside the// expression text, so there is no duplication risk.- let with_opclass = match opclass.filter(|o| !o.is_empty()) {- Some(opc) => format!("{base} {opc}"),- None => base,- };- match key_options {- Some(options) => format!(- "{with_opclass} {} NULLS {}",- if options & 1 != 0 { "DESC" } else { "ASC" },- if options & 2 != 0 { "FIRST" } else { "LAST" }- ),- None => with_opclass,- }+ decorate_postgres_index_key(&base, opclass, key_options)}/// `CREATE INDEX/SEQUENCE IF NOT EXISTS` was added in PostgreSQL 9.5: 9.2/9.3/9.4diff --git a/crates/dbx-core/src/data/transfer/structure_plan.rs b/crates/dbx-core/src/data/transfer/structure_plan.rsindex 84285dfdf5..1f64205dec 100644--- a/crates/dbx-core/src/data/transfer/structure_plan.rs+++ b/crates/dbx-core/src/data/transfer/structure_plan.rs@@ -542,21 +542,26 @@ mod tests {fn structured_ddl_metadata_produces_operation_dtos() {let index = db::IndexInfo {name: "idx_orders_created_at".into(),- columns: vec!["created_at".into()],+ columns: vec!["lower(\"email\")".into()],is_unique: false,is_primary: false,filter: None,- index_type: None,+ index_type: Some("btree".into()),included_columns: None,comment: None,- key_is_expression: Vec::new(),- column_opclasses: Vec::new(),- key_options: Vec::new(),+ key_is_expression: vec![true],+ column_opclasses: vec![Some("text_pattern_ops".into())],+ key_options: vec![1],constraint_backed: false,};let index_sql = generate_postgres_index_ddl(std::slice::from_ref(&index), "orders", "public", true);let index_operations = postgres_index_operations(std::slice::from_ref(&index), "orders", "orders");- assert!(index_sql[0].contains("idx_orders_created_at"));+ assert_eq!(+ index_sql,+ vec![+ "CREATE INDEX IF NOT EXISTS \"idx_orders_created_at\" ON \"public\".\"orders\" USING btree (lower(\"email\") text_pattern_ops DESC NULLS LAST)"+ ]+ );assert_eq!(index_operations[0].kind, TransferStructureOperationKind::CreateIndex);assert_eq!(index_operations[0].object_name.as_deref(), Some("idx_orders_created_at"));diff --git a/crates/dbx-sql-core/src/value_literals.rs b/crates/dbx-sql-core/src/value_literals.rsindex 6c2f687a12..9be03396e2 100644--- a/crates/dbx-sql-core/src/value_literals.rs+++ b/crates/dbx-sql-core/src/value_literals.rs@@ -158,6 +158,14 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ fn string_literal_quotes_normal_unicode_empty_and_apostrophe_values() {+ assert_eq!(quote_string_literal("hello"), "'hello'");+ assert_eq!(quote_string_literal("O'Reilly"), "'O''Reilly'");+ assert_eq!(quote_string_literal(""), "''");+ assert_eq!(quote_string_literal("中文注释"), "'中文注释'");+ }+#[test]fn pg_array_literal_without_backslashes_stays_a_plain_string() {assert_eq!(format_pg_array_sql_literal(&[]), "'{}'");diff --git a/crates/dbx-sql-dialect/src/lib.rs b/crates/dbx-sql-dialect/src/lib.rsindex ea89bf44e6..35a791f863 100644--- a/crates/dbx-sql-dialect/src/lib.rs+++ b/crates/dbx-sql-dialect/src/lib.rs@@ -3,4 +3,5 @@pub use dbx_types::{database_manifest, models, types};pub mod dml_binding;+pub mod postgres_index_key;pub mod sql_dialect;diff --git a/crates/dbx-sql-dialect/src/postgres_index_key.rs b/crates/dbx-sql-dialect/src/postgres_index_key.rsnew file mode 100644index 0000000000..230823a94c--- /dev/null+++ b/crates/dbx-sql-dialect/src/postgres_index_key.rs@@ -0,0 +1,56 @@+/// Adds PostgreSQL operator-class and ordering suffixes to an already-rendered index key.+///+/// `rendered_key` must already contain the caller's identifier quoting or expression rendering.+/// `key_options` uses PostgreSQL `pg_index.indoption` bits: bit 0 selects DESC instead of ASC,+/// and bit 1 selects NULLS FIRST instead of NULLS LAST. When ordering options are present, both+/// clauses are emitted explicitly to preserve the existing transfer and schema-sync SQL.+pub fn decorate_postgres_index_key(rendered_key: &str, opclass: Option<&str>, key_options: Option<i16>) -> String {+ let with_opclass = match opclass.filter(|opclass| !opclass.is_empty()) {+ Some(opclass) => format!("{rendered_key} {opclass}"),+ None => rendered_key.to_string(),+ };++ match key_options {+ Some(options) => format!(+ "{with_opclass} {} NULLS {}",+ if options & 1 != 0 { "DESC" } else { "ASC" },+ if options & 2 != 0 { "FIRST" } else { "LAST" }+ ),+ None => with_opclass,+ }+}++#[cfg(test)]+mod tests {+ use super::decorate_postgres_index_key;++ #[test]+ fn leaves_plain_rendered_key_unchanged() {+ assert_eq!(decorate_postgres_index_key("\"name\"", None, None), "\"name\"");+ }++ #[test]+ fn appends_nonempty_opclass() {+ assert_eq!(+ decorate_postgres_index_key("\"name\"", Some("text_pattern_ops"), None),+ "\"name\" text_pattern_ops"+ );+ assert_eq!(decorate_postgres_index_key("\"name\"", Some(""), None), "\"name\"");+ }++ #[test]+ fn renders_ascending_and_descending_order_with_null_order() {+ assert_eq!(decorate_postgres_index_key("\"name\"", None, Some(0)), "\"name\" ASC NULLS LAST");+ assert_eq!(decorate_postgres_index_key("\"name\"", None, Some(1)), "\"name\" DESC NULLS LAST");+ assert_eq!(decorate_postgres_index_key("\"name\"", None, Some(2)), "\"name\" ASC NULLS FIRST");+ assert_eq!(decorate_postgres_index_key("\"name\"", None, Some(3)), "\"name\" DESC NULLS FIRST");+ }++ #[test]+ fn decorates_an_already_rendered_expression() {+ assert_eq!(+ decorate_postgres_index_key("lower(\"email\")", Some("text_pattern_ops"), Some(1)),+ "lower(\"email\") text_pattern_ops DESC NULLS LAST"+ );+ }+}diff --git a/crates/dbx-sql-schema/src/schema_diff.rs b/crates/dbx-sql-schema/src/schema_diff.rsindex e85d74ea52..650097e133 100644--- a/crates/dbx-sql-schema/src/schema_diff.rs+++ b/crates/dbx-sql-schema/src/schema_diff.rs@@ -1,3 +1,5 @@+use dbx_sql_core::value_literals::quote_string_literal;+use dbx_sql_dialect::postgres_index_key::decorate_postgres_index_key;use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};use log;@@ -4182,7 +4184,7 @@ fn column_def_with_charset(}if profile.inline_column_comment {if let Some(comment) = &col.comment {- definition.push_str(&format!(" COMMENT {}", comment_literal(comment)));+ definition.push_str(&format!(" COMMENT {}", quote_string_literal(comment)));}}definition@@ -4449,18 +4451,7 @@ fn postgres_index_column_sql() -> String {let trimmed = column.trim();let base = if is_expression.unwrap_or(false) { trimmed.to_string() } else { quote_id(column, db_type) };- let with_opclass = match opclass.filter(|opclass| !opclass.is_empty()) {- Some(opclass) => format!("{base} {opclass}"),- None => base,- };- match key_options {- Some(options) => format!(- "{with_opclass} {} NULLS {}",- if options & 1 != 0 { "DESC" } else { "ASC" },- if options & 2 != 0 { "FIRST" } else { "LAST" }- ),- None => with_opclass,- }+ decorate_postgres_index_key(&base, opclass, key_options)}pub fn create_index_sql(table_name: &str, index: &IndexInfo, db_type: DatabaseType, schema: Option<&str>) -> String {@@ -4562,7 +4553,7 @@ pub fn create_index_sql(table_name: &str, index: &IndexInfo, db_type: DatabaseTylet filter_clause = if filter.is_empty() { String::new() } else { format!(" WHERE {filter}") };let comment = index.comment.as_deref().unwrap_or("");let comment_clause = if !comment.trim().is_empty() && profile.index_supports_comment {- format!(" COMMENT {}", comment_literal(comment))+ format!(" COMMENT {}", quote_string_literal(comment))} else {String::new()};@@ -4669,10 +4660,6 @@ fn drop_object_sql(diff: &TableDiff, db_type: DatabaseType, schema: Option<&str>format!("DROP {object_type} IF EXISTS {name}{cascade};")}-fn comment_literal(comment: &str) -> String {- format!("'{}'", comment.replace('\'', "''"))-}-/// Bare temporal keywords that are defaults in their own right and must not be quoted.const TEMPORAL_DEFAULT_KEYWORDS: [&str; 8] =["current_timestamp", "current_date", "current_time", "now", "localtime", "localtimestamp", "getdate", "sysdate"];@@ -5460,7 +5447,7 @@ fn column_comment_sql(if profile.column_comment_via_modify_only {return vec![format!("-- Column comment for {column_name}: use ALTER TABLE ... MODIFY COLUMN to set comment")];}- vec![format!("COMMENT ON COLUMN {table}.{} IS {};", quote_id(column_name, db_type), comment_literal(comment))]+ vec![format!("COMMENT ON COLUMN {table}.{} IS {};", quote_id(column_name, db_type), quote_string_literal(comment))]}fn table_comment_sql(table_name: &str, comment: &str, db_type: DatabaseType, schema: Option<&str>) -> Vec<String> {@@ -5470,9 +5457,9 @@ fn table_comment_sql(table_name: &str, comment: &str, db_type: DatabaseType, schreturn build_sqlserver_table_comment_sql(&table, schema, table_name, comment);}if profile.table_comment_via_alter {- vec![format!("ALTER TABLE {table} COMMENT = {};", comment_literal(comment))]+ vec![format!("ALTER TABLE {table} COMMENT = {};", quote_string_literal(comment))]} else {- vec![format!("COMMENT ON TABLE {table} IS {};", comment_literal(comment))]+ vec![format!("COMMENT ON TABLE {table} IS {};", quote_string_literal(comment))]}}@@ -5599,7 +5586,7 @@ fn generate_create_table_sql(def.push_str(&column_modifier_tail(&profile, col, &mapped_type, db_type, source_dialect, skip_default));if profile.inline_column_comment {if let Some(comment) = col.comment.as_deref().filter(|c| !c.is_empty()) {- def.push_str(&format!(" COMMENT {}", comment_literal(comment)));+ def.push_str(&format!(" COMMENT {}", quote_string_literal(comment)));}}if !suffix.is_empty() {@@ -5625,7 +5612,7 @@ fn generate_create_table_sql(def.push_str(&column_modifier_tail(&profile, col, &mapped_type, db_type, source_dialect, skip_default));if profile.inline_column_comment {if let Some(comment) = col.comment.as_deref().filter(|c| !c.is_empty()) {- def.push_str(&format!(" COMMENT {}", comment_literal(comment)));+ def.push_str(&format!(" COMMENT {}", quote_string_literal(comment)));}}col_defs.push(def);@@ -12115,6 +12102,18 @@ mod tests {assert!(sql.contains("COMMENT ON COLUMN"), "PG comment: {sql}");}+ #[test]+ fn schema_diff_comment_sql_uses_shared_literal_escaping() {+ let cases = [("hello", "'hello'"), ("O'Reilly", "'O''Reilly'"), ("", "''"), ("中文注释", "'中文注释'")];++ for (comment, literal) in cases {+ assert_eq!(+ column_comment_sql("users", "display_name", comment, DatabaseType::Postgres, Some("public")),+ vec![format!("COMMENT ON COLUMN \"public\".\"users\".\"display_name\" IS {literal};")]+ );+ }+ }+#[test]fn table_comment_change_mysql() {let _diffs: Vec<ColumnDiff> = vec![];diff --git a/crates/dbx-sql/src/lib.rs b/crates/dbx-sql/src/lib.rsindex 38f24a6fc2..f059c7d9b6 100644--- a/crates/dbx-sql/src/lib.rs+++ b/crates/dbx-sql/src/lib.rs@@ -5,6 +5,6 @@ pub use dbx_sql_core::{sql_diagnostics, sql_editability, sql_error_position, sql_risk, sqlserver_temporal, tdsql_mysql, value_literals,};pub use dbx_sql_data::{data_grid_extractors, data_grid_sql, database_search_sql, query_result_sql};-pub use dbx_sql_dialect::{dml_binding, sql_dialect};+pub use dbx_sql_dialect::{dml_binding, postgres_index_key, sql_dialect};pub use dbx_sql_schema::{db_admin_sql, schema_diff, sql_parser, table_structure_sql};pub use dbx_types::{database_manifest, models, types};