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(oracle): create tables with unquoted plain identifiers

jearhe8cc04f3af414
diff --git a/crates/dbx-core/src/db_admin_sql.rs b/crates/dbx-core/src/db_admin_sql.rs
index fc95af973d..12bc866a2d 100644
--- a/crates/dbx-core/src/db_admin_sql.rs
+++ b/crates/dbx-core/src/db_admin_sql.rs
@@ -803,11 +803,24 @@ pub fn build_copy_table_data_sql(options: CopyTableDataSqlOptions) -> String {
let Some(columns) = options.columns.filter(|columns| !columns.is_empty()) else {
return format!("INSERT INTO {target} SELECT * FROM {source};");
};
- let column_list = columns
+ let source_column_list = columns
.iter()
.map(|column| quote_table_identifier(options.database_type, column))
.collect::<Vec<_>>()
.join(", ");
+ // The unquoted Oracle clone DDL creates the target columns case-folded while the source
+ // keeps its exact stored spelling, so the INSERT target list must reference the folded
+ // forms and the SELECT list keeps reading the source exactly.
+ let target_column_list = if options.normalize_new_target_name && options.database_type == Some(DatabaseType::Oracle)
+ {
+ columns
+ .iter()
+ .map(|column| crate::table_structure_sql::oracle_new_object_reference(column))
+ .collect::<Vec<_>>()
+ .join(", ")
+ } else {
+ source_column_list.clone()
+ };
let postgres_override = if options.postgres_overriding_system_value
&& matches!(options.database_type, Some(DatabaseType::Postgres | DatabaseType::Gaussdb | DatabaseType::Kwdb))
{
@@ -815,8 +828,9 @@ pub fn build_copy_table_data_sql(options: CopyTableDataSqlOptions) -> String {
} else {
""
};
- let insert_sql =
- format!("INSERT INTO {target} ({column_list}){postgres_override} SELECT {column_list} FROM {source};");
+ let insert_sql = format!(
+ "INSERT INTO {target} ({target_column_list}){postgres_override} SELECT {source_column_list} FROM {source};"
+ );
if options.sqlserver_identity_insert && options.database_type == Some(DatabaseType::SqlServer) {
return format!("SET IDENTITY_INSERT {target} ON;\n{insert_sql}\nSET IDENTITY_INSERT {target} OFF;");
}
@@ -1079,10 +1093,14 @@ fn qualified_name_with_quote(
}
fn qualified_duplicate_target_name(database_type: Option<DatabaseType>, schema: Option<&str>, name: &str) -> String {
- if database_type != Some(DatabaseType::Dameng) {
- return qualified_name(database_type, schema, name);
- }
- let target = profile_for(DatabaseType::Dameng).quote_ident(name);
+ // Both duplicate-target normalizations emit the spelling a freshly created clone resolves
+ // to: Oracle's clone DDL creates plain identifiers unquoted (uppercase fold), and Dameng's
+ // clone keeps the same fold convention through its profile. Every other type stays exact.
+ let target = match database_type {
+ Some(DatabaseType::Oracle) => crate::table_structure_sql::oracle_new_object_reference(name),
+ Some(DatabaseType::Dameng) => profile_for(DatabaseType::Dameng).quote_ident(name),
+ _ => return qualified_name(database_type, schema, name),
+ };
if schema.is_some_and(|schema| !schema.is_empty()) {
format!("{}.{}", quote_rename_identifier(database_type, schema.unwrap()), target)
} else {
@@ -2120,7 +2138,7 @@ mod tests {
column_comments: vec![],
identifier_quote: None,
}),
- "CREATE TABLE \"HR\".\"USERS_COPY\" AS SELECT * FROM \"HR\".\"USERS\" WHERE 1=0"
+ "CREATE TABLE \"HR\".USERS_COPY AS SELECT * FROM \"HR\".\"USERS\" WHERE 1=0"
);
let dameng_sql = build_duplicate_table_structure_sql(DuplicateTableStructureSqlOptions {
database_type: Some(DatabaseType::Dameng),
@@ -2320,6 +2338,93 @@ mod tests {
}),
"INSERT INTO \"APP\".\"users_copy\" SELECT * FROM \"APP\".\"users\";"
);
+ assert_eq!(
+ build_copy_table_data_sql(CopyTableDataSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ source_name: "orders".to_string(),
+ target_name: "orders_copy".to_string(),
+ columns: Some(vec!["user_id".to_string(), "userName".to_string(), "order total".to_string()]),
+ postgres_overriding_system_value: false,
+ sqlserver_identity_insert: false,
+ normalize_new_target_name: true,
+ identifier_quote: None,
+ }),
+ "INSERT INTO \"APP\".orders_copy (user_id, userName, \"order total\") SELECT \"user_id\", \"userName\", \"order total\" FROM \"APP\".\"orders\";"
+ );
+ assert_eq!(
+ build_copy_table_data_sql(CopyTableDataSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ source_name: "orders".to_string(),
+ target_name: "orders_copy".to_string(),
+ columns: Some(vec!["user_id".to_string()]),
+ postgres_overriding_system_value: false,
+ sqlserver_identity_insert: false,
+ normalize_new_target_name: false,
+ identifier_quote: None,
+ }),
+ "INSERT INTO \"APP\".\"orders_copy\" (\"user_id\") SELECT \"user_id\" FROM \"APP\".\"orders\";"
+ );
+ }
+
+ #[test]
+ fn oracle_clone_data_copy_matches_unquoted_create_identifiers() {
+ // Clone-with-data regression: a lowercase user-typed target and quoted-lowercase source
+ // columns. The clone DDL creates plain identifiers unquoted (Oracle stores them folded),
+ // so the data-copy INSERT must reference the created spellings while the SELECT keeps
+ // the exact quoted spelling of the existing source.
+ let column = |name: &str| crate::table_structure_sql::EditableStructureColumn {
+ id: name.to_string(),
+ name: name.to_string(),
+ data_type: "NUMBER".to_string(),
+ is_nullable: true,
+ default_value: String::new(),
+ comment: String::new(),
+ is_primary_key: false,
+ extra: None,
+ original: None,
+ original_position: None,
+ marked_for_drop: false,
+ character_set: String::new(),
+ collation: String::new(),
+ };
+ let create =
+ crate::table_structure_sql::build_create_table_sql(crate::table_structure_sql::TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ table_name: "orders_copy".to_string(),
+ columns: vec![column("user_id"), column("userName")],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+ assert_eq!(create.warnings, Vec::<String>::new());
+ assert_eq!(
+ create.statements[0],
+ "CREATE TABLE \"APP\".orders_copy (\n user_id NUMBER,\n userName NUMBER\n);"
+ );
+
+ let copy = build_copy_table_data_sql(CopyTableDataSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ source_name: "orders".to_string(),
+ target_name: "orders_copy".to_string(),
+ columns: Some(vec!["user_id".to_string(), "userName".to_string()]),
+ postgres_overriding_system_value: false,
+ sqlserver_identity_insert: false,
+ normalize_new_target_name: true,
+ identifier_quote: None,
+ });
+ assert_eq!(
+ copy,
+ "INSERT INTO \"APP\".orders_copy (user_id, userName) SELECT \"user_id\", \"userName\" FROM \"APP\".\"orders\";"
+ );
}
#[test]
diff --git a/crates/dbx-core/src/table_structure_sql.rs b/crates/dbx-core/src/table_structure_sql.rs
index 7fd6fa1925..68825ba6d1 100644
--- a/crates/dbx-core/src/table_structure_sql.rs
+++ b/crates/dbx-core/src/table_structure_sql.rs
@@ -27,7 +27,7 @@ pub(crate) use column_alter::{
build_sqlserver_alter_column_preserving_default_sql, build_sqlserver_drop_default_constraint_sql,
};
pub(crate) use comments::{build_sqlserver_column_comment_sql, build_sqlserver_table_comment_sql};
-pub(crate) use util::sqlserver_unicode_string_literal;
+pub(crate) use util::{oracle_new_object_reference, sqlserver_unicode_string_literal};
use crate::models::connection::DatabaseType;
diff --git a/crates/dbx-core/src/table_structure_sql/create_table.rs b/crates/dbx-core/src/table_structure_sql/create_table.rs
index cdbba70262..e9663c79dc 100644
--- a/crates/dbx-core/src/table_structure_sql/create_table.rs
+++ b/crates/dbx-core/src/table_structure_sql/create_table.rs
@@ -4,12 +4,14 @@ use super::column_format::{
};
use super::comments::{build_sqlserver_column_comment_sql, build_sqlserver_table_comment_sql};
use super::dialect::{capabilities_for, database_label, StructureDialect};
-use super::foreign_keys::build_foreign_key_sql;
+use super::foreign_keys::build_foreign_key_sql_for_new_table;
use super::indexes::build_create_index_statements;
use super::mysql_engine::{append_mysql_table_option, validate_mysql_engine};
-use super::triggers::build_trigger_sql;
+use super::triggers::build_trigger_sql_for_new_table;
use super::types::{TableStructureSqlOptions, TableStructureSqlResult};
-use super::util::{clean, format_default_for_sql, normalize_default, qualified_table, quote_ident, quote_string};
+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 crate::models::connection::DatabaseType;
@@ -42,7 +44,7 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
if !warnings.is_empty() {
return TableStructureSqlResult { statements: Vec::new(), warnings };
}
- let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
+ let table = qualified_new_table(options.database_type, dialect, options.schema.as_deref(), &options.table_name);
if dialect == StructureDialect::Dameng {
for column in &active_columns {
if has_dameng_identity(column) && !is_dameng_identity_compatible_type(&column.data_type) {
@@ -61,7 +63,7 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
for column in &active_columns {
let data_type = column_data_type(dialect, column);
- let mut parts = vec![quote_ident(dialect, &column.name), data_type];
+ let mut parts = vec![quote_new_ident(options.database_type, dialect, &column.name), data_type];
if options.database_type == Some(DatabaseType::Mysql) && is_mysql_character_data_type(&column.data_type) {
if !column.character_set.trim().is_empty() {
parts.push(format!("CHARACTER SET {}", quote_ident(dialect, &column.character_set)));
@@ -105,7 +107,11 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
.filter(|column| column.is_primary_key && dialect != StructureDialect::ManticoreSearch)
.collect();
if !pk_columns.is_empty() {
- let pk_list = pk_columns.iter().map(|column| quote_ident(dialect, &column.name)).collect::<Vec<_>>().join(", ");
+ let pk_list = pk_columns
+ .iter()
+ .map(|column| quote_new_ident(options.database_type, dialect, &column.name))
+ .collect::<Vec<_>>()
+ .join(", ");
column_definitions.push(format!("PRIMARY KEY ({pk_list})"));
}
@@ -160,7 +166,7 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
if !clean(&column.comment).is_empty() {
statements.push(format!(
"COMMENT ON COLUMN {table}.{} IS {};",
- quote_ident(dialect, &column.name),
+ quote_new_ident(options.database_type, dialect, &column.name),
quote_string(&clean(&column.comment))
));
}
@@ -171,7 +177,7 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
if !clean(&column.comment).is_empty() {
statements.push(format!(
"ALTER TABLE {table} COMMENT COLUMN {} {};",
- quote_ident(dialect, &column.name),
+ quote_new_ident(options.database_type, dialect, &column.name),
quote_string(&clean(&column.comment))
));
}
@@ -200,6 +206,7 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
continue;
}
statements.extend(build_create_index_statements(
+ options.database_type,
dialect,
&table,
index,
@@ -208,11 +215,12 @@ pub fn build_create_table_sql(mut options: TableStructureSqlOptions) -> TableStr
&options.table_name,
false,
capabilities.index_concurrent,
+ true,
));
}
- statements.extend(build_foreign_key_sql(&options, &mut warnings));
- statements.extend(build_trigger_sql(&options, &mut warnings));
+ statements.extend(build_foreign_key_sql_for_new_table(&options, &mut warnings));
+ statements.extend(build_trigger_sql_for_new_table(&options, &mut warnings));
TableStructureSqlResult { statements, warnings }
}
diff --git a/crates/dbx-core/src/table_structure_sql/foreign_keys.rs b/crates/dbx-core/src/table_structure_sql/foreign_keys.rs
index af981b4ac1..dde4147d36 100644
--- a/crates/dbx-core/src/table_structure_sql/foreign_keys.rs
+++ b/crates/dbx-core/src/table_structure_sql/foreign_keys.rs
@@ -1,8 +1,23 @@
use super::dialect::{database_label, StructureDialect};
use super::types::{EditableStructureForeignKey, ForeignKeyInfo, TableStructureSqlOptions};
-use super::util::{clean, qualified_table, quote_ident};
+use super::util::{clean, qualified_new_table, qualified_table, quote_ident, quote_new_ident};
pub(super) fn build_foreign_key_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
+ build_foreign_key_sql_with_mode(options, warnings, false)
+}
+
+pub(super) fn build_foreign_key_sql_for_new_table(
+ options: &TableStructureSqlOptions,
+ warnings: &mut Vec<String>,
+) -> Vec<String> {
+ build_foreign_key_sql_with_mode(options, warnings, true)
+}
+
+fn build_foreign_key_sql_with_mode(
+ options: &TableStructureSqlOptions,
+ warnings: &mut Vec<String>,
+ for_new_table: bool,
+) -> Vec<String> {
if options.foreign_keys.is_empty() {
return Vec::new();
}
@@ -17,7 +32,11 @@ pub(super) fn build_foreign_key_sql(options: &TableStructureSqlOptions, warnings
return Vec::new();
}
- let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
+ let table = if for_new_table {
+ qualified_new_table(options.database_type, dialect, options.schema.as_deref(), &options.table_name)
+ } else {
+ qualified_table(dialect, options.schema.as_deref(), &options.table_name)
+ };
let mut statements = Vec::new();
for foreign_key in &options.foreign_keys {
@@ -35,7 +54,9 @@ pub(super) fn build_foreign_key_sql(options: &TableStructureSqlOptions, warnings
statements.push(drop_foreign_key_sql(dialect, &table, &original.name));
}
- if let Some(sql) = create_foreign_key_sql(dialect, &table, foreign_key, warnings) {
+ if let Some(sql) =
+ create_foreign_key_sql(options.database_type, dialect, &table, foreign_key, warnings, for_new_table)
+ {
statements.push(sql);
}
}
@@ -87,10 +108,12 @@ fn drop_foreign_key_sql(dialect: StructureDialect, table: &str, name: &str) -> S
}
fn create_foreign_key_sql(
+ database_type: Option<crate::models::connection::DatabaseType>,
dialect: StructureDialect,
table: &str,
foreign_key: &EditableStructureForeignKey,
warnings: &mut Vec<String>,
+ for_new_table: bool,
) -> Option<String> {
let name = clean(&foreign_key.name);
let columns = identifier_list(&foreign_key.column);
@@ -111,13 +134,25 @@ fn create_foreign_key_sql(
format!("{}.{}", quote_ident(dialect, &foreign_key.ref_schema), quote_ident(dialect, &ref_table))
};
+ let constraint_name =
+ if for_new_table { quote_new_ident(database_type, dialect, &name) } else { quote_ident(dialect, &name) };
+ let local_columns =
+ columns
+ .iter()
+ .map(|column| {
+ if for_new_table {
+ quote_new_ident(database_type, dialect, column)
+ } else {
+ quote_ident(dialect, column)
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ let referenced_columns =
+ ref_columns.iter().map(|column| quote_ident(dialect, column)).collect::<Vec<_>>().join(", ");
let mut sql = format!(
- "ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {ref_target} ({}",
- quote_ident(dialect, &name),
- columns.iter().map(|column| quote_ident(dialect, column)).collect::<Vec<_>>().join(", "),
- ref_columns.iter().map(|column| quote_ident(dialect, column)).collect::<Vec<_>>().join(", ")
+ "ALTER TABLE {table} ADD CONSTRAINT {constraint_name} FOREIGN KEY ({local_columns}) REFERENCES {ref_target} ({referenced_columns})"
);
- sql.push(')');
if let Some(action) = action_clause(dialect, "ON DELETE", &foreign_key.on_delete, warnings) {
sql.push(' ');
diff --git a/crates/dbx-core/src/table_structure_sql/indexes.rs b/crates/dbx-core/src/table_structure_sql/indexes.rs
index 02e6fc3250..e6d9e7c7b3 100644
--- a/crates/dbx-core/src/table_structure_sql/indexes.rs
+++ b/crates/dbx-core/src/table_structure_sql/indexes.rs
@@ -1,7 +1,7 @@
use super::comments::build_sqlserver_index_comment_sql;
use super::dialect::{capabilities_for, database_label, database_type_for_dialect, dialect_label, StructureDialect};
use super::types::{EditableStructureIndex, TableStructureSqlOptions};
-use super::util::{clean, qualified_table, quote_ident, quote_string};
+use super::util::{clean, qualified_table, quote_ident, quote_new_ident, quote_string};
use crate::models::connection::DatabaseType;
pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
@@ -68,6 +68,7 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
));
}
statements.extend(build_create_index_statements(
+ options.database_type,
dialect,
&table,
index,
@@ -76,6 +77,7 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
&options.table_name,
or_replace,
capabilities.index_concurrent,
+ false,
));
continue;
}
@@ -85,6 +87,7 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
continue;
}
statements.extend(build_create_index_statements(
+ options.database_type,
dialect,
&table,
index,
@@ -93,6 +96,7 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
&options.table_name,
false,
capabilities.index_concurrent,
+ false,
));
}
@@ -244,6 +248,7 @@ pub(super) fn build_drop_index_sql(
}
pub(super) fn build_create_index_statements(
+ database_type: Option<DatabaseType>,
dialect: StructureDialect,
table: &str,
index: &EditableStructureIndex,
@@ -252,6 +257,7 @@ pub(super) fn build_create_index_statements(
table_name: &str,
or_replace: bool,
concurrently_supported: bool,
+ for_new_table: bool,
) -> Vec<String> {
let capabilities = capabilities_for(database_type_for_dialect(dialect));
let name = clean(&index.name);
@@ -282,6 +288,8 @@ pub(super) fn build_create_index_statements(
gaussdbm_index_column_sql(column, key_is_expression[i])
} else if dialect == StructureDialect::Postgres {
postgres_index_column_sql(column, key_is_expression[i])
+ } else if for_new_table {
+ quote_new_ident(database_type, dialect, column)
} else {
quote_ident(dialect, column)
}
@@ -321,7 +329,17 @@ pub(super) fn build_create_index_statements(
{
format!(
" INCLUDE ({})",
- included_columns.iter().map(|column| quote_ident(dialect, column)).collect::<Vec<_>>().join(", ")
+ included_columns
+ .iter()
+ .map(|column| {
+ if for_new_table {
+ quote_new_ident(database_type, dialect, column)
+ } else {
+ quote_ident(dialect, column)
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(", ")
)
} else {
String::new()
@@ -339,10 +357,12 @@ pub(super) fn build_create_index_statements(
let supports_where = capabilities.index_filter
&& matches!(dialect, StructureDialect::Postgres | StructureDialect::SqlServer | StructureDialect::Sqlite);
let where_clause = if !filter.is_empty() && supports_where { format!(" WHERE {filter}") } else { String::new() };
+ let quoted_index_name =
+ if for_new_table { quote_new_ident(database_type, dialect, &name) } else { quote_ident(dialect, &name) };
let index_name = if dialect == StructureDialect::Sqlite && schema.is_some_and(|schema| !schema.trim().is_empty()) {
- format!("{}.{}", quote_ident(dialect, schema.unwrap()), quote_ident(dialect, &name))
+ format!("{}.{}", quote_ident(dialect, schema.unwrap()), quoted_index_name)
} else {
- quote_ident(dialect, &name)
+ quoted_index_name
};
// SQLite assigns an index to the database named by the qualified index.
// Its CREATE INDEX grammar does not allow a qualified table name.
diff --git a/crates/dbx-core/src/table_structure_sql/tests.rs b/crates/dbx-core/src/table_structure_sql/tests.rs
index 8f3895954b..0950fec996 100644
--- a/crates/dbx-core/src/table_structure_sql/tests.rs
+++ b/crates/dbx-core/src/table_structure_sql/tests.rs
@@ -998,8 +998,226 @@ fn oracle_create_table_preserves_character_length_units() {
is_gaussdb_m_mode: false,
});
- assert!(result.statements[0].contains("\"BYTE_COL\" VARCHAR2(12 BYTE)"));
- assert!(result.statements[0].contains("\"CHAR_COL\" VARCHAR2(12 CHAR)"));
+ assert!(result.statements[0].contains("BYTE_COL VARCHAR2(12 BYTE)"));
+ assert!(result.statements[0].contains("CHAR_COL VARCHAR2(12 CHAR)"));
+}
+
+#[test]
+fn oracle_create_table_uses_unquoted_identifiers_for_new_objects() {
+ let mut user_id = column("user_id");
+ user_id.data_type = "NUMBER".to_string();
+ user_id.is_primary_key = true;
+ user_id.comment = "identifier".to_string();
+ let mut user_name = column("userName");
+ user_name.data_type = "VARCHAR2(100)".to_string();
+ let mut upper_id = column("USER_CODE");
+ upper_id.data_type = "NUMBER".to_string();
+ let mut dollar_id = column("ABC$01");
+ dollar_id.data_type = "NUMBER".to_string();
+ let mut hash_id = column("ABC#01");
+ hash_id.data_type = "NUMBER".to_string();
+ let idx = index("idx_user_id", &["user_id"]);
+
+ let result = build_create_table_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ table_name: "orders".to_string(),
+ columns: vec![user_id, user_name, upper_id, dollar_id, hash_id],
+ indexes: vec![idx],
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: Some("user table".to_string()),
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements[0],
+ "CREATE TABLE \"APP\".orders (\n user_id NUMBER,\n userName VARCHAR2(100),\n USER_CODE NUMBER,\n ABC$01 NUMBER,\n ABC#01 NUMBER,\n PRIMARY KEY (user_id)\n);"
+ );
+ assert!(result.statements.iter().any(|statement| statement == "COMMENT ON TABLE \"APP\".orders IS 'user table';"));
+ assert!(result
+ .statements
+ .iter()
+ .any(|statement| statement == "COMMENT ON COLUMN \"APP\".orders.user_id IS 'identifier';"));
+ assert!(result
+ .statements
+ .iter()
+ .any(|statement| statement == "CREATE INDEX idx_user_id ON \"APP\".orders (user_id);"));
+}
+
+#[test]
+fn oracle_create_table_leaves_uppercase_regular_identifier_unquoted() {
+ let mut user_id = column("USER_ID");
+ user_id.data_type = "NUMBER".to_string();
+
+ let result = build_create_table_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: None,
+ table_name: "USERS".to_string(),
+ columns: vec![user_id],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(result.statements, vec!["CREATE TABLE USERS (\n USER_ID NUMBER\n);".to_string()]);
+}
+
+#[test]
+fn oracle_create_table_quotes_special_and_reserved_identifiers() {
+ let mut special = column("user name");
+ special.data_type = "VARCHAR2(100)".to_string();
+ special.comment = "special".to_string();
+ let mut escaped = column(r#"a"b"#);
+ escaped.data_type = "VARCHAR2(100)".to_string();
+ let mut select = column("SELECT");
+ select.data_type = "VARCHAR2(100)".to_string();
+ let mut from = column("FROM");
+ from.data_type = "VARCHAR2(100)".to_string();
+ let mut table = column("TABLE");
+ table.data_type = "VARCHAR2(100)".to_string();
+ let mut leading_digit = column("123column");
+ leading_digit.data_type = "VARCHAR2(100)".to_string();
+
+ let result = build_create_table_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ table_name: "order detail".to_string(),
+ columns: vec![special, escaped, select, from, table, leading_digit],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ let ddl = &result.statements[0];
+ assert!(ddl.starts_with("CREATE TABLE \"APP\".\"order detail\" ("));
+ assert!(ddl.contains("\"user name\" VARCHAR2(100)"));
+ assert!(ddl.contains("\"a\"\"b\" VARCHAR2(100)"));
+ assert!(ddl.contains("\"SELECT\" VARCHAR2(100)"));
+ assert!(ddl.contains("\"FROM\" VARCHAR2(100)"));
+ assert!(ddl.contains("\"TABLE\" VARCHAR2(100)"));
+ assert!(ddl.contains("\"123column\" VARCHAR2(100)"));
+ assert!(result
+ .statements
+ .iter()
+ .any(|statement| statement == "COMMENT ON COLUMN \"APP\".\"order detail\".\"user name\" IS 'special';"));
+}
+
+#[test]
+fn oracle_create_table_distinguishes_new_and_referenced_foreign_key_identifiers() {
+ let mut user_id = column("user_id");
+ user_id.data_type = "NUMBER".to_string();
+ let mut customer_fk = foreign_key("fk_orders_user", "user_id", "CamelCase", "UserName");
+ customer_fk.ref_schema = "CaseSchema".to_string();
+ let audit_trigger = trigger("auditTrigger", "BEFORE", "INSERT", "BEGIN\n NULL;\nEND");
+
+ let result = build_create_table_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("APP".to_string()),
+ table_name: "orders".to_string(),
+ columns: vec![user_id],
+ indexes: Vec::new(),
+ foreign_keys: vec![customer_fk],
+ triggers: vec![audit_trigger],
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "CREATE TABLE \"APP\".orders (\n user_id NUMBER\n);",
+ "ALTER TABLE \"APP\".orders ADD CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES \"CaseSchema\".\"CamelCase\" (\"UserName\");",
+ "CREATE OR REPLACE TRIGGER \"APP\".auditTrigger BEFORE INSERT ON \"APP\".orders\nFOR EACH ROW\nBEGIN\n NULL;\nEND;",
+ ]
+ );
+}
+
+#[test]
+fn oracle_existing_quoted_identifiers_keep_exact_spelling() {
+ let mut column = column("CamelCase");
+ column.data_type = "NUMBER".to_string();
+ column.original = Some(ColumnInfo {
+ name: "CamelCase".to_string(),
+ data_type: "VARCHAR2(100)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: None,
+ comment: None,
+ ..Default::default()
+ });
+
+ let result = build_table_structure_change_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Oracle),
+ schema: Some("CaseSchema".to_string()),
+ table_name: "CaseTable".to_string(),
+ columns: vec![column],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec!["ALTER TABLE \"CaseSchema\".\"CaseTable\" MODIFY (\"CamelCase\" NUMBER);".to_string()]
+ );
+}
+
+#[test]
+fn oracle_new_identifier_formatting_does_not_change_other_dialects() {
+ for (database_type, expected) in [
+ (DatabaseType::Postgres, "CREATE TABLE \"users\" (\n \"user_id\" INTEGER\n);"),
+ (DatabaseType::Mysql, "CREATE TABLE `users` (\n `user_id` INTEGER\n);"),
+ (DatabaseType::SqlServer, "CREATE TABLE [users] (\n [user_id] INTEGER\n);"),
+ (DatabaseType::Dameng, "CREATE TABLE \"users\" (\n \"user_id\" INTEGER\n);"),
+ ] {
+ let mut user_id = column("user_id");
+ user_id.data_type = "INTEGER".to_string();
+ let result = build_create_table_sql(TableStructureSqlOptions {
+ database_type: Some(database_type),
+ schema: None,
+ table_name: "users".to_string(),
+ columns: vec![user_id],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new(), "{database_type:?}");
+ assert_eq!(result.statements, vec![expected.to_string()], "{database_type:?}");
+ }
}
#[test]
@@ -4870,7 +5088,7 @@ fn builds_oracle_foreign_key_with_supported_actions() {
assert_eq!(result.warnings, Vec::<String>::new());
assert_eq!(
result.statements[1],
- "ALTER TABLE \"HR\".\"ORDERS_COPY\" ADD CONSTRAINT \"ORDERS_COPY_FK1\" FOREIGN KEY (\"CUSTOMER_ID\") REFERENCES \"CRM\".\"CUSTOMERS\" (\"ID\") ON DELETE CASCADE;"
+ "ALTER TABLE \"HR\".ORDERS_COPY ADD CONSTRAINT ORDERS_COPY_FK1 FOREIGN KEY (CUSTOMER_ID) REFERENCES \"CRM\".\"CUSTOMERS\" (\"ID\") ON DELETE CASCADE;"
);
}
diff --git a/crates/dbx-core/src/table_structure_sql/triggers.rs b/crates/dbx-core/src/table_structure_sql/triggers.rs
index f7bc98635e..870c8a38d7 100644
--- a/crates/dbx-core/src/table_structure_sql/triggers.rs
+++ b/crates/dbx-core/src/table_structure_sql/triggers.rs
@@ -1,8 +1,23 @@
use super::dialect::{database_label, StructureDialect};
use super::types::{EditableStructureTrigger, TableStructureSqlOptions, TriggerInfo};
-use super::util::{clean, qualified_table, quote_ident};
+use super::util::{clean, qualified_new_table, qualified_table, quote_ident, quote_new_ident};
pub(super) fn build_trigger_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
+ build_trigger_sql_with_mode(options, warnings, false)
+}
+
+pub(super) fn build_trigger_sql_for_new_table(
+ options: &TableStructureSqlOptions,
+ warnings: &mut Vec<String>,
+) -> Vec<String> {
+ build_trigger_sql_with_mode(options, warnings, true)
+}
+
+fn build_trigger_sql_with_mode(
+ options: &TableStructureSqlOptions,
+ warnings: &mut Vec<String>,
+ for_new_table: bool,
+) -> Vec<String> {
if options.triggers.is_empty() {
return Vec::new();
}
@@ -16,7 +31,11 @@ pub(super) fn build_trigger_sql(options: &TableStructureSqlOptions, warnings: &m
return Vec::new();
}
- let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
+ let table = if for_new_table {
+ qualified_new_table(options.database_type, dialect, options.schema.as_deref(), &options.table_name)
+ } else {
+ qualified_table(dialect, options.schema.as_deref(), &options.table_name)
+ };
let mut statements = Vec::new();
for trigger in &options.triggers {
@@ -46,7 +65,15 @@ pub(super) fn build_trigger_sql(options: &TableStructureSqlOptions, warnings: &m
}
}
- if let Some(sql) = create_trigger_sql(dialect, options.schema.as_deref(), &table, trigger, warnings) {
+ if let Some(sql) = create_trigger_sql(
+ options.database_type,
+ dialect,
+ options.schema.as_deref(),
+ &table,
+ trigger,
+ warnings,
+ for_new_table,
+ ) {
statements.push(sql);
// SQL Server rebuilds via DROP + CREATE, which resets is_disabled to
// enabled; restore the catalog-reported disabled state explicitly.
@@ -93,11 +120,13 @@ fn drop_trigger_sql(dialect: StructureDialect, schema: Option<&str>, name: &str)
}
fn create_trigger_sql(
+ database_type: Option<crate::models::connection::DatabaseType>,
dialect: StructureDialect,
schema: Option<&str>,
table: &str,
trigger: &EditableStructureTrigger,
warnings: &mut Vec<String>,
+ for_new_table: bool,
) -> Option<String> {
let name = clean(&trigger.name);
let timing = normalize_keyword(&trigger.timing);
@@ -113,9 +142,17 @@ fn create_trigger_sql(
StructureDialect::SqlServer => {
create_sqlserver_trigger_sql(schema, table, &name, &timing, &event, &statement, warnings)
}
- StructureDialect::Oracle => {
- create_oracle_trigger_sql(schema, table, &name, &timing, &event, &statement, warnings)
- }
+ StructureDialect::Oracle => create_oracle_trigger_sql(
+ database_type,
+ schema,
+ table,
+ &name,
+ &timing,
+ &event,
+ &statement,
+ warnings,
+ for_new_table,
+ ),
_ => None,
}
}
@@ -239,6 +276,7 @@ fn create_mysql_trigger_sql(
}
fn create_oracle_trigger_sql(
+ database_type: Option<crate::models::connection::DatabaseType>,
schema: Option<&str>,
table: &str,
name: &str,
@@ -246,6 +284,7 @@ fn create_oracle_trigger_sql(
event: &str,
statement: &str,
warnings: &mut Vec<String>,
+ for_new_table: bool,
) -> Option<String> {
let Some((timing_clause, row_level)) = oracle_trigger_timing(timing) else {
warnings.push(format!("Unsupported Oracle trigger timing \"{timing}\"."));
@@ -256,15 +295,16 @@ fn create_oracle_trigger_sql(
return None;
}
- let trigger_name = if schema.is_some_and(|schema| !schema.trim().is_empty()) {
- format!(
- "{}.{}",
- quote_ident(StructureDialect::Oracle, schema.unwrap()),
- quote_ident(StructureDialect::Oracle, name)
- )
+ let trigger_identifier = if for_new_table {
+ quote_new_ident(database_type, StructureDialect::Oracle, name)
} else {
quote_ident(StructureDialect::Oracle, name)
};
+ let trigger_name = if schema.is_some_and(|schema| !schema.trim().is_empty()) {
+ format!("{}.{}", quote_ident(StructureDialect::Oracle, schema.unwrap()), trigger_identifier)
+ } else {
+ trigger_identifier
+ };
let row_clause = if row_level { "\nFOR EACH ROW" } else { "" };
let statement = statement.trim_end().trim_end_matches('/').trim_end().trim_end_matches(';').trim_end();
diff --git a/crates/dbx-core/src/table_structure_sql/util.rs b/crates/dbx-core/src/table_structure_sql/util.rs
index 7a986892ee..55931962c2 100644
--- a/crates/dbx-core/src/table_structure_sql/util.rs
+++ b/crates/dbx-core/src/table_structure_sql/util.rs
@@ -1,8 +1,10 @@
use super::dialect::StructureDialect;
use super::types::EditableStructureColumn;
+use crate::models::connection::DatabaseType;
-pub(super) fn qualified_table(dialect: StructureDialect, schema: Option<&str>, table_name: &str) -> String {
- if matches!(
+/// Dialects whose qualified names use `schema.table` when a non-empty schema is present.
+fn is_schema_qualifying_dialect(dialect: StructureDialect) -> bool {
+ matches!(
dialect,
StructureDialect::Postgres
| StructureDialect::Oracle
@@ -12,13 +14,37 @@ pub(super) fn qualified_table(dialect: StructureDialect, schema: Option<&str>, t
| StructureDialect::H2
| StructureDialect::Informix
| StructureDialect::Sqlite
- ) && schema.is_some_and(|schema| !schema.trim().is_empty())
- {
+ )
+}
+
+pub(super) fn qualified_table(dialect: StructureDialect, schema: Option<&str>, table_name: &str) -> String {
+ if is_schema_qualifying_dialect(dialect) && schema.is_some_and(|schema| !schema.trim().is_empty()) {
return format!("{}.{}", quote_ident(dialect, schema.unwrap()), quote_ident(dialect, table_name));
}
quote_ident(dialect, table_name)
}
+/// Qualify a table being created while preserving the schema as an existing object.
+///
+/// Oracle's ordinary identifiers are case-insensitive and are folded to uppercase. The
+/// regular `qualified_table`/`quote_ident` pair must remain exact because it is also used
+/// for tables already loaded from metadata, including quoted mixed-case names.
+pub(super) fn qualified_new_table(
+ database_type: Option<DatabaseType>,
+ dialect: StructureDialect,
+ schema: Option<&str>,
+ table_name: &str,
+) -> String {
+ if is_schema_qualifying_dialect(dialect) && schema.is_some_and(|schema| !schema.trim().is_empty()) {
+ return format!(
+ "{}.{}",
+ quote_ident(dialect, schema.unwrap()),
+ quote_new_ident(database_type, dialect, table_name)
+ );
+ }
+ quote_new_ident(database_type, dialect, table_name)
+}
+
pub(super) fn quote_ident(dialect: StructureDialect, name: &str) -> String {
match dialect {
StructureDialect::Mysql
@@ -43,6 +69,53 @@ fn is_simple_informix_identifier(name: &str) -> bool {
&& chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$')
}
+/// Format an identifier that will be created by a CREATE/ADD statement.
+///
+/// This is deliberately separate from `quote_ident`: metadata-backed DDL must preserve the
+/// exact spelling of an existing quoted Oracle object, while a newly entered ordinary name
+/// should use Oracle's normal case-insensitive identifier semantics.
+pub(super) fn quote_new_ident(database_type: Option<DatabaseType>, dialect: StructureDialect, name: &str) -> String {
+ if database_type == Some(DatabaseType::Oracle) && dialect == StructureDialect::Oracle {
+ oracle_new_object_reference(name)
+ } else {
+ quote_ident(dialect, name)
+ }
+}
+
+/// Reference spelling that resolves to an object created through [`quote_new_ident`]'s Oracle path.
+///
+/// Plain Oracle identifiers are created unquoted and are therefore stored uppercase-folded; a
+/// later reference with the same unquoted spelling folds to the same object. Names that had to
+/// stay quoted at creation (special characters, reserved words) keep exact quoting here too, so
+/// generated references always line up with the created object.
+pub(crate) fn oracle_new_object_reference(name: &str) -> String {
+ if is_simple_oracle_identifier(name) && !is_oracle_reserved_identifier(name) {
+ name.to_string()
+ } else {
+ quote_ident(StructureDialect::Oracle, name)
+ }
+}
+
+fn is_simple_oracle_identifier(name: &str) -> bool {
+ let mut chars = name.chars();
+ let Some(first) = chars.next() else {
+ return false;
+ };
+ first.is_ascii_alphabetic() && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$' || ch == '#')
+}
+
+// sqlparser maintains the shared SQL keyword vocabulary used by this crate. It intentionally
+// includes more than Oracle's reserved words, so the conservative check is supplemented only
+// with Oracle-specific legacy words missing from that maintained list instead of copying a
+// separate several-hundred-entry keyword table here.
+const ORACLE_RESERVED_WORDS_MISSING_FROM_SQLPARSER: &[&str] =
+ &["MAXEXTENTS", "NOAUDIT", "ROWID", "ROWNUM", "SUCCESSFUL", "UID"];
+
+fn is_oracle_reserved_identifier(name: &str) -> bool {
+ sqlparser::keywords::ALL_KEYWORDS.iter().any(|keyword| keyword.eq_ignore_ascii_case(name))
+ || ORACLE_RESERVED_WORDS_MISSING_FROM_SQLPARSER.iter().any(|keyword| keyword.eq_ignore_ascii_case(name))
+}
+
pub(super) fn quote_string(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}