Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(export): quote standard insert identifiers per engine family

弈秋b9de5e8a714b
diff --git a/crates/dbx-core/src/data/database_export.rs b/crates/dbx-core/src/data/database_export.rs
index b4050b3132..c51627b136 100644
--- a/crates/dbx-core/src/data/database_export.rs
+++ b/crates/dbx-core/src/data/database_export.rs
@@ -1591,7 +1591,7 @@ pub(crate) fn build_export_insert_statements_excluding_with_dialect(
.iter()
.map(|(_, column, _)| {
if insert_dialect == SqlInsertDialect::Standard {
- crate::sql_dialect::quote_table_identifier(None, column)
+ standard_export_identifier(options.database_type, column, options.identifier_quote.as_deref())
} else {
crate::sql_dialect::quote_table_data_identifier(
options.database_type,
@@ -2065,6 +2065,26 @@ pub fn build_database_sql_export(options: BuildDatabaseSqlExportOptions) -> Resu
Ok(lines.join("\n"))
}
+/// Identifier quoting for the "Standard SQL" INSERT dialect.
+///
+/// "Standard SQL" output is meant to be ANSI-portable, so it keeps double-quoted
+/// identifiers for every engine that already accepts them (SQL Server, PostgreSQL
+/// family, Oracle, …). It only deviates to the source engine's native quoting for
+/// the backtick family (MySQL, Hive family, Neo4j/Nebula, …) where a double quote
+/// is a string literal and ANSI output cannot be replayed at all (#12158). This
+/// keeps the fix's blast radius on exactly the engines that were broken.
+fn standard_export_identifier(
+ database_type: Option<DatabaseType>,
+ name: &str,
+ identifier_quote: Option<&str>,
+) -> String {
+ if crate::sql_dialect::uses_backtick_identifier_quoting(database_type) {
+ crate::sql_dialect::quote_table_data_identifier(database_type, name, identifier_quote)
+ } else {
+ crate::sql_dialect::quote_table_identifier(None, name)
+ }
+}
+
fn export_qualified_table_name(
database_type: Option<DatabaseType>,
schema: Option<&str>,
@@ -2077,11 +2097,11 @@ fn export_qualified_table_name(
let table_name = table_name
.filter(|name| !name.trim().is_empty())
.ok_or_else(|| "tableName is required for Standard SQL INSERT output".to_string())?;
- let table = crate::sql_dialect::quote_table_identifier(None, table_name);
+ let table = standard_export_identifier(database_type, table_name, identifier_quote);
return Ok(schema
.map(str::trim)
.filter(|schema| !schema.is_empty())
- .map(|schema| format!("{}.{}", crate::sql_dialect::quote_table_identifier(None, schema), table))
+ .map(|schema| format!("{}.{}", standard_export_identifier(database_type, schema, identifier_quote), table))
.unwrap_or(table));
}
if let Some(name) = qualified_name.filter(|name| !name.trim().is_empty()) {
@@ -7949,6 +7969,32 @@ mod tests {
);
}
+ #[test]
+ fn database_row_writer_standard_dialect_uses_mysql_backticks() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("users.sql");
+ let mut file = std::fs::File::create(&path).unwrap();
+
+ write_database_export_rows(
+ &mut file,
+ &[vec![json!(1), json!("Ada")]],
+ &["id".to_string(), "name".to_string()],
+ &[Some("int".to_string()), Some("varchar(32)".to_string())],
+ &[None, None],
+ "users",
+ "app",
+ &DatabaseType::Mysql,
+ SqlInsertDialect::Standard,
+ )
+ .unwrap();
+ drop(file);
+
+ assert_eq!(
+ std::fs::read_to_string(path).unwrap(),
+ "INSERT INTO `app`.`users` (`id`, `name`) VALUES (1, 'Ada');\n\n"
+ );
+ }
+
#[test]
fn database_row_writer_supports_one_insert_statement_per_row() {
let directory = tempfile::tempdir().unwrap();
diff --git a/crates/dbx-sql-dialect/src/sql_dialect.rs b/crates/dbx-sql-dialect/src/sql_dialect.rs
index 622fd73264..d676a66f22 100644
--- a/crates/dbx-sql-dialect/src/sql_dialect.rs
+++ b/crates/dbx-sql-dialect/src/sql_dialect.rs
@@ -37,6 +37,7 @@ pub use descriptor::{
};
pub use identifiers::{
normalize_where_input, qualified_table_name, qualified_table_name_with_catalog, quote_table_identifier,
+ uses_backtick_identifier_quoting,
};
pub use identifiers::{
parse_sqlserver_linked_schema_ref, qualified_transfer_table, quote_gaussdb_jdbc_identifier, quote_iris_identifier,
diff --git a/crates/dbx-sql-dialect/src/sql_dialect/identifiers.rs b/crates/dbx-sql-dialect/src/sql_dialect/identifiers.rs
index 8a6f6f7172..efe14c1c2e 100644
--- a/crates/dbx-sql-dialect/src/sql_dialect/identifiers.rs
+++ b/crates/dbx-sql-dialect/src/sql_dialect/identifiers.rs
@@ -125,22 +125,15 @@ pub fn qualified_table_name_with_catalog(
}
}
-pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -> String {
- if matches!(database_type, Some(DatabaseType::Gaussdb | DatabaseType::OpenGauss))
- && is_explicitly_quoted_identifier(name)
- {
- return name.to_string();
- }
- match database_type {
- Some(DatabaseType::Iotdb) => name.to_string(),
- // SOQL has no delimited identifiers: `SELECT * FROM "Account"` fails with
- // MALFORMED_QUERY, and double quotes are string literals there. Object and
- // field API names are always sent bare.
- Some(DatabaseType::Salesforce) => name.to_string(),
- // JDBC connections use the driver-reported identifier quote string
- // (DatabaseMetaData.getIdentifierQuoteString()) inside the JDBC agent,
- // so the Rust layer passes identifiers through unquoted.
- Some(DatabaseType::Jdbc) => name.to_string(),
+/// Engines whose native identifier delimiter is the backtick (the MySQL/Hive
+/// family plus Neo4j/Nebula). For these engines a double quote is a string
+/// literal, so ANSI double-quoted identifiers cannot be replayed; callers that
+/// must stay ANSI-portable (the "Standard SQL" export dialect) only deviate to
+/// native quoting for this family. Keeping the list here lets
+/// [`quote_table_identifier`] and its consumers share a single source of truth.
+pub fn uses_backtick_identifier_quoting(database_type: Option<DatabaseType>) -> bool {
+ matches!(
+ database_type,
Some(
DatabaseType::Mysql
| DatabaseType::ClickHouse
@@ -164,8 +157,36 @@ pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -
// syntax error. PostgreSQL-dialect Spanner databases override this through
// the identifier quote reported by the agent on connect.
| DatabaseType::Spanner
- | DatabaseType::Questdb,
- ) => {
+ | DatabaseType::Questdb
+ | DatabaseType::Neo4j
+ | DatabaseType::Nebula,
+ )
+ )
+}
+
+pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -> String {
+ if matches!(database_type, Some(DatabaseType::Gaussdb | DatabaseType::OpenGauss))
+ && is_explicitly_quoted_identifier(name)
+ {
+ return name.to_string();
+ }
+ match database_type {
+ Some(DatabaseType::Iotdb) => name.to_string(),
+ // SOQL has no delimited identifiers: `SELECT * FROM "Account"` fails with
+ // MALFORMED_QUERY, and double quotes are string literals there. Object and
+ // field API names are always sent bare.
+ Some(DatabaseType::Salesforce) => name.to_string(),
+ // JDBC connections use the driver-reported identifier quote string
+ // (DatabaseMetaData.getIdentifierQuoteString()) inside the JDBC agent,
+ // so the Rust layer passes identifiers through unquoted.
+ Some(DatabaseType::Jdbc) => name.to_string(),
+ // Nebula belongs to the backtick family but escapes backslashes as well as
+ // backticks, so it is matched before the shared backtick arm below.
+ Some(DatabaseType::Nebula) => format!("`{}`", name.replace('\\', "\\\\").replace('`', "\\`")),
+ // MySQL/Hive family and Neo4j quote identifiers with backticks. The set is
+ // defined once in `uses_backtick_identifier_quoting` so the "Standard SQL"
+ // export dialect and this quoting never drift apart.
+ Some(db_type) if uses_backtick_identifier_quoting(Some(db_type)) => {
format!("`{}`", name.replace('`', "``"))
}
Some(DatabaseType::Informix) if is_simple_informix_identifier(name) => name.to_string(),
@@ -176,8 +197,6 @@ pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -
// table (#11986). Emit simple names unquoted, as Informix does; a name that
// needs quoting keeps the generic double-quote form.
Some(DatabaseType::Sundb) if is_simple_informix_identifier(name) => name.to_string(),
- Some(DatabaseType::Neo4j) => format!("`{}`", name.replace('`', "``")),
- Some(DatabaseType::Nebula) => format!("`{}`", name.replace('\\', "\\\\").replace('`', "\\`")),
Some(DatabaseType::SqlServer) => format!("[{}]", name.replace(']', "]]")),
_ => format!("\"{}\"", name.replace('"', "\"\"")),
}
diff --git a/crates/dbx-sql-dialect/src/sql_dialect/tests.rs b/crates/dbx-sql-dialect/src/sql_dialect/tests.rs
index 1e9699caba..3282459818 100644
--- a/crates/dbx-sql-dialect/src/sql_dialect/tests.rs
+++ b/crates/dbx-sql-dialect/src/sql_dialect/tests.rs
@@ -15,6 +15,23 @@ fn transfer_identifier_policy_preserves_legacy_output() {
assert_eq!(qualified_transfer_table("events", "warehouse", &DatabaseType::Mysql, None), "`events`");
}
+#[test]
+fn backtick_family_predicate_matches_quoting() {
+ // `uses_backtick_identifier_quoting` is the single source of truth the "Standard
+ // SQL" export dialect consults to decide when to deviate from ANSI double
+ // quotes. It must agree with what `quote_table_identifier` actually emits, so a
+ // new backtick-family engine cannot silently drift between the two.
+ for &database_type in DatabaseType::ALL {
+ let quoted = quote_table_identifier(Some(database_type), "tbl");
+ let emits_backtick = quoted.starts_with('`');
+ assert_eq!(
+ uses_backtick_identifier_quoting(Some(database_type)),
+ emits_backtick,
+ "{database_type:?} quoting/backtick-family mismatch: {quoted}"
+ );
+ }
+}
+
#[test]
fn quotes_identifiers_by_database_type() {
assert_eq!(quote_table_identifier(Some(DatabaseType::Nebula), "tag`name"), "`tag\\`name`");