fix(oracle): create tables with unquoted plain identifiers
This commit is contained in:
1 parent
c9f0ee89f9
commit
8cc04f3af4
8 files changed
+549
-50
No files matched your search
@@ -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 }
|
||||
}
|
||||
@@ -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(' ');
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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('\'', "''"))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user