fix(gaussdb): quote identifiers by compatibility mode

This commit is contained in:
zipg authored and GitHub committed 2026-07-29 23:34:58 +08:00
1 parent d0c3a3fd2e
commit 66f94f23f1
28 files changed
+1207 -134

No files matched your search

+11
View File
@@ -2785,6 +2785,17 @@ impl AppState {
.get(connection_id)
.cloned()
.ok_or_else(|| format!("Connection config not found: {connection_id}"))?;
if config.db_type == DatabaseType::Gaussdb {
let pool_key = self.get_or_create_pool(connection_id, database).await?;
let pool = {
let connections = self.connections.read().await;
match connections.get(&pool_key) {
Some(PoolKind::Postgres(pool)) => pool.clone(),
_ => return Ok(None),
}
};
return Ok(db::postgres::gaussdb_identifier_quote(&pool).await);
}
if !database_capabilities::is_agent_type(&config.db_type) {
return Ok(None);
}
+109 -2
View File
@@ -770,7 +770,10 @@ pub fn build_data_grid_column_distinct_values_sql(options: DataGridColumnDistinc
}
pub fn build_data_grid_count_sql(options: DataGridCountSqlOptions) -> String {
let table = if options.database_type == Some(DatabaseType::Kingbase) {
let table = if crate::sql_dialect::uses_connection_identifier_quote(
options.database_type,
options.identifier_quote.as_deref(),
) {
crate::sql_dialect::table_data_qualified_table_name(
options.database_type,
options.schema.as_deref(),
@@ -2691,7 +2694,7 @@ fn data_grid_qualified_table_name(
table_name: &str,
identifier_quote: Option<&str>,
) -> String {
if database_type == Some(DatabaseType::Kingbase) {
if crate::sql_dialect::uses_connection_identifier_quote(database_type, identifier_quote) {
crate::sql_dialect::table_data_qualified_table_name(database_type, schema, table_name, identifier_quote)
} else {
crate::sql_dialect::qualified_table_name_with_catalog(database_type, catalog, schema, database, table_name)
@@ -3191,6 +3194,33 @@ mod tests {
#[test]
fn builds_filter_conditions() {
for (database_type, identifier_quote, column_name, expected) in [
(DatabaseType::Gaussdb, Some("\""), "column_01", "column_01 = 1"),
(DatabaseType::Gaussdb, Some("\""), "MixedCase", "\"MixedCase\" = 1"),
(DatabaseType::Gaussdb, Some("\""), "order", "\"order\" = 1"),
(DatabaseType::Gaussdb, Some("\""), "order detail", "\"order detail\" = 1"),
(DatabaseType::Gaussdb, Some("\""), "\"AlreadyQuoted\"", "\"AlreadyQuoted\" = 1"),
(DatabaseType::Gaussdb, Some("`"), "MixedCase", "`MixedCase` = 1"),
(DatabaseType::Postgres, Some("`"), "order", "`order` = 1"),
(DatabaseType::OpenGauss, Some("`"), "order detail", "`order detail` = 1"),
(DatabaseType::Gaussdb, None, "column_01", "\"column_01\" = 1"),
(DatabaseType::OpenGauss, None, "column_01", "\"column_01\" = 1"),
] {
assert_eq!(
build_data_grid_context_filter_condition(DataGridContextFilterConditionOptions {
database_type: Some(database_type),
identifier_quote: identifier_quote.map(str::to_string),
column_name: column_name.to_string(),
mode: DataGridContextFilterMode::Equals,
value: json!(1),
values: Vec::new(),
end_value: None,
column_info: Some(column(column_name, "integer", false, None)),
})
.as_deref(),
Some(expected)
);
}
assert_eq!(
build_data_grid_context_filter_condition(DataGridContextFilterConditionOptions {
database_type: Some(DatabaseType::Kingbase),
@@ -3829,6 +3859,30 @@ mod tests {
}),
"SELECT COUNT(*) AS cnt FROM `cqbq_ls`.`ANALYZE`"
);
assert_eq!(
build_data_grid_count_sql(DataGridCountSqlOptions {
database_type: Some(DatabaseType::Gaussdb),
identifier_quote: Some("\"".to_string()),
catalog: None,
database: None,
schema: Some("schema_01".to_string()),
table_name: "table_01".to_string(),
where_input: None,
}),
"SELECT COUNT(*) AS cnt FROM schema_01.table_01"
);
assert_eq!(
build_data_grid_count_sql(DataGridCountSqlOptions {
database_type: Some(DatabaseType::Postgres),
identifier_quote: Some("`".to_string()),
catalog: None,
database: None,
schema: Some("App Schema".to_string()),
table_name: "order".to_string(),
where_input: None,
}),
"SELECT COUNT(*) AS cnt FROM `App Schema`.`order`"
);
}
#[test]
@@ -4478,6 +4532,59 @@ mod tests {
.all(|statement| statement.contains("`gc`.`docfileinfo`") && !statement.contains('"')));
}
#[test]
fn gaussdb_jdbc_save_selectively_quotes_identifiers() {
let result = prepare_data_grid_save(DataGridSaveStatementOptions {
database_type: Some(DatabaseType::Gaussdb),
identifier_quote: Some("\"".to_string()),
table_meta: DataGridTableMeta {
catalog: None,
database: None,
schema: Some("schema_01".to_string()),
table_name: "table_01".to_string(),
primary_keys: vec!["id".to_string()],
columns: Some(vec![column("id", "integer", false, None), column("name", "varchar", false, None)]),
},
columns: vec!["id".to_string(), "name".to_string()],
source_columns: None,
rows: vec![vec![json!(1), json!("old")]],
dirty_rows: vec![(0, vec![(1, json!("new"))])],
deleted_rows: vec![],
new_rows: vec![],
});
assert_eq!(result.validation_error, None);
assert_eq!(result.statements, vec!["UPDATE schema_01.table_01 SET name = 'new' WHERE id = 1;"]);
}
#[test]
fn postgres_driver_to_gaussdb_m_mode_save_uses_backticks() {
let result = prepare_data_grid_save(DataGridSaveStatementOptions {
database_type: Some(DatabaseType::Postgres),
identifier_quote: Some("`".to_string()),
table_meta: DataGridTableMeta {
catalog: None,
database: None,
schema: Some("App Schema".to_string()),
table_name: "order".to_string(),
primary_keys: vec!["ID".to_string()],
columns: Some(vec![
column("ID", "integer", false, None),
column("display name", "varchar", false, None),
]),
},
columns: vec!["ID".to_string(), "display name".to_string()],
source_columns: None,
rows: vec![vec![json!(1), json!("old")]],
dirty_rows: vec![(0, vec![(1, json!("new"))])],
deleted_rows: vec![],
new_rows: vec![],
});
assert_eq!(result.validation_error, None);
assert_eq!(result.statements, vec!["UPDATE `App Schema`.`order` SET `display name` = 'new' WHERE `ID` = 1;"]);
}
#[test]
fn postgres_save_uses_exact_quoted_primary_key_for_update_delete_and_rollback() {
let result = prepare_data_grid_save(DataGridSaveStatementOptions {
+31
View File
@@ -30,6 +30,25 @@ use crate::types::{
OwnerInfo, QueryResult, RuleInfo, SchemaInfo, SequenceInfo, TableInfo, TriggerInfo,
};
const GAUSSDB_COMPATIBILITY_SQL: &str =
"SELECT datcompatibility FROM pg_catalog.pg_database WHERE datname = current_database()";
pub async fn gaussdb_identifier_quote(pool: &Pool) -> Option<String> {
let timeout = super::connection_timeout();
let client = checkout_postgres_client(pool, None, timeout).await.ok()?;
let row = tokio::time::timeout(timeout, client.query_opt(GAUSSDB_COMPATIBILITY_SQL, &[])).await.ok()?.ok()??;
let compatibility_mode = row.try_get::<_, String>(0).ok()?;
gaussdb_identifier_quote_for_compatibility_mode(&compatibility_mode).map(str::to_string)
}
fn gaussdb_identifier_quote_for_compatibility_mode(compatibility_mode: &str) -> Option<&'static str> {
match compatibility_mode.trim().to_ascii_uppercase().as_str() {
"M" | "B" | "MYSQL" => Some("`"),
"A" | "PG" | "ORA" | "POSTGRESQL" => Some("\""),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostgresTablePrivilegeInfo {
pub grantor: String,
@@ -4045,6 +4064,18 @@ mod tests {
use std::time::Instant;
use tokio_postgres::types::FromSql;
#[test]
fn gaussdb_compatibility_mode_selects_identifier_quote() {
for mode in ["M", "B", "mysql", " MYSQL "] {
assert_eq!(gaussdb_identifier_quote_for_compatibility_mode(mode), Some("`"));
}
for mode in ["A", "PG", "ora", " PostgreSQL "] {
assert_eq!(gaussdb_identifier_quote_for_compatibility_mode(mode), Some("\""));
}
assert_eq!(gaussdb_identifier_quote_for_compatibility_mode("C"), None);
assert_eq!(gaussdb_identifier_quote_for_compatibility_mode(""), None);
}
fn pg_interval_bytes(microseconds: i64, days: i32, months: i32) -> [u8; 16] {
let mut raw = [0_u8; 16];
raw[0..8].copy_from_slice(&microseconds.to_be_bytes());
+3 -1
View File
@@ -39,7 +39,9 @@ pub use identifiers::{
};
pub(crate) use identifiers::{parse_sqlserver_linked_schema_ref, qualified_transfer_table, quote_transfer_identifier};
pub use table_select::{build_count_table_sql, build_table_data_select_sql, build_table_select_sql};
pub(crate) use table_select::{quote_table_data_identifier, table_data_qualified_table_name};
pub(crate) use table_select::{
quote_table_data_identifier, table_data_qualified_table_name, uses_connection_identifier_quote,
};
pub use type_rewrite::{
apply_auto_inc_to_column_def, column_is_auto_increment, rewrite_column_type, split_type_base_params,
type_looks_integer, AutoIncColumnBuild,
@@ -111,6 +111,11 @@ 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(),
// JDBC connections use the driver-reported identifier quote string
@@ -141,6 +146,221 @@ pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -
}
}
pub(crate) fn quote_gaussdb_jdbc_identifier(name: &str, identifier_quote: &str) -> String {
if is_explicitly_quoted_identifier(name) {
return name.to_string();
}
let quote = identifier_quote.trim();
if quote.is_empty() {
return name.to_string();
}
let requires_quote = !is_simple_lower_identifier(name)
|| is_postgres_reserved_identifier(name)
|| (quote == "`" && is_mysql_only_reserved_identifier(name));
if !requires_quote {
return name.to_string();
}
format!("{quote}{}{quote}", name.replace(quote, &format!("{quote}{quote}")))
}
fn is_explicitly_quoted_identifier(name: &str) -> bool {
name.len() >= 2
&& ((name.starts_with('"') && name.ends_with('"'))
|| (name.starts_with('`') && name.ends_with('`'))
|| (name.starts_with('[') && name.ends_with(']')))
}
fn is_simple_lower_identifier(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
(first == '_' || first.is_ascii_lowercase())
&& chars.all(|ch| ch == '_' || ch == '$' || ch.is_ascii_lowercase() || ch.is_ascii_digit())
}
fn is_postgres_reserved_identifier(name: &str) -> bool {
matches!(
name,
"all"
| "analyse"
| "analyze"
| "and"
| "any"
| "array"
| "as"
| "asc"
| "asymmetric"
| "authorization"
| "binary"
| "both"
| "case"
| "cast"
| "check"
| "collate"
| "collation"
| "column"
| "concurrently"
| "constraint"
| "create"
| "cross"
| "current_catalog"
| "current_date"
| "current_role"
| "current_schema"
| "current_time"
| "current_timestamp"
| "current_user"
| "default"
| "deferrable"
| "desc"
| "distinct"
| "do"
| "else"
| "end"
| "except"
| "false"
| "fetch"
| "for"
| "foreign"
| "freeze"
| "from"
| "full"
| "grant"
| "group"
| "having"
| "ilike"
| "in"
| "initially"
| "inner"
| "intersect"
| "into"
| "is"
| "isnull"
| "join"
| "lateral"
| "leading"
| "left"
| "like"
| "limit"
| "localtime"
| "localtimestamp"
| "natural"
| "not"
| "notnull"
| "null"
| "offset"
| "on"
| "only"
| "or"
| "order"
| "outer"
| "overlaps"
| "placing"
| "primary"
| "references"
| "returning"
| "right"
| "select"
| "session_user"
| "similar"
| "some"
| "symmetric"
| "system_user"
| "table"
| "tablesample"
| "then"
| "to"
| "trailing"
| "true"
| "union"
| "unique"
| "user"
| "using"
| "variadic"
| "verbose"
| "when"
| "where"
| "window"
| "with"
)
}
fn is_mysql_only_reserved_identifier(name: &str) -> bool {
matches!(
name,
"accessible"
| "auto_increment"
| "change"
| "database"
| "databases"
| "delayed"
| "describe"
| "div"
| "dual"
| "enclosed"
| "escaped"
| "explain"
| "force"
| "fulltext"
| "high_priority"
| "ignore"
| "index"
| "infile"
| "key"
| "keys"
| "kill"
| "linear"
| "lines"
| "load"
| "lock"
| "low_priority"
| "master_ssl_verify_server_cert"
| "maxvalue"
| "mediumint"
| "mod"
| "no_write_to_binlog"
| "optimize"
| "optionally"
| "outfile"
| "partition"
| "purge"
| "range"
| "read_write"
| "regexp"
| "release"
| "rename"
| "replace"
| "require"
| "rlike"
| "schema"
| "schemas"
| "separator"
| "show"
| "spatial"
| "sql_big_result"
| "sql_calc_found_rows"
| "sql_small_result"
| "ssl"
| "starting"
| "straight_join"
| "terminated"
| "tinyint"
| "unlock"
| "unsigned"
| "use"
| "utc_date"
| "utc_time"
| "utc_timestamp"
| "values"
| "varbinary"
| "varchar"
| "write"
| "xor"
| "zerofill"
)
}
pub fn normalize_where_input(where_input: Option<&str>) -> String {
let trimmed = where_input.unwrap_or("").trim().trim_end_matches(';').trim();
let mut chars = trimmed.chars();
@@ -4,7 +4,8 @@ use super::capabilities::{
firebird_rows_clause, table_pagination_strategy, uses_oracle_row_id, TablePaginationStrategy,
};
use super::identifiers::{
normalize_where_input, qualified_table_name, qualified_table_name_with_catalog, quote_table_identifier,
normalize_where_input, qualified_table_name, qualified_table_name_with_catalog, quote_gaussdb_jdbc_identifier,
quote_table_identifier,
};
use super::types::{
TableDataSelectSqlOptions, TableSelectSqlOptions, DBX_NEO4J_ELEMENT_ID_COLUMN, DBX_ROWID_COLUMN,
@@ -23,7 +24,7 @@ pub fn build_table_data_select_sql(options: TableDataSelectSqlOptions) -> String
}
// Doris / StarRocks multi-catalog: prefix the catalog for external-catalog tables.
let table = if database_type == Some(DatabaseType::Kingbase) {
let table = if uses_connection_identifier_quote(database_type, options.identifier_quote.as_deref()) {
table_data_qualified_table_name(
database_type,
options.schema.as_deref(),
@@ -166,7 +167,7 @@ pub(crate) fn table_data_qualified_table_name(
table_name: &str,
identifier_quote: Option<&str>,
) -> String {
if database_type != Some(DatabaseType::Kingbase) {
if !uses_connection_identifier_quote(database_type, identifier_quote) {
return qualified_table_name(database_type, schema, table_name);
}
let table = quote_table_data_identifier(database_type, table_name, identifier_quote);
@@ -182,18 +183,30 @@ pub(crate) fn quote_table_data_identifier(
name: &str,
identifier_quote: Option<&str>,
) -> String {
if database_type != Some(DatabaseType::Kingbase) {
if !uses_connection_identifier_quote(database_type, identifier_quote) {
return quote_table_identifier(database_type, name);
}
let Some(quote) = identifier_quote else {
return quote_table_identifier(database_type, name);
};
if matches!(database_type, Some(DatabaseType::Gaussdb | DatabaseType::OpenGauss | DatabaseType::Postgres)) {
return quote_gaussdb_jdbc_identifier(name, quote);
}
if quote.is_empty() {
return name.to_string();
}
format!("{quote}{}{quote}", name.replace(quote, &format!("{quote}{quote}")))
}
pub(crate) fn uses_connection_identifier_quote(
database_type: Option<DatabaseType>,
identifier_quote: Option<&str>,
) -> bool {
database_type == Some(DatabaseType::Kingbase)
|| (matches!(database_type, Some(DatabaseType::Gaussdb | DatabaseType::OpenGauss | DatabaseType::Postgres))
&& identifier_quote.is_some())
}
fn is_view_table_type(table_type: Option<&str>) -> bool {
table_type.is_some_and(|value| value.to_ascii_uppercase().contains("VIEW"))
}
+93
View File
@@ -26,12 +26,39 @@ fn quotes_identifiers_by_database_type() {
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "order"), "\"order\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "MixedCase"), "\"MixedCase\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "order detail"), "\"order detail\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Gaussdb), "\"MixedCase\""), "\"MixedCase\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::OpenGauss), "\"MixedCase\""), "\"MixedCase\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Informix), "users_1"), "users_1");
assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "users_1"), "users_1");
assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "user name"), "user name");
assert_eq!(quote_table_identifier(Some(DatabaseType::Iotdb), "root.test.device2"), "root.test.device2");
}
#[test]
fn quotes_gaussdb_jdbc_identifiers_selectively() {
for (name, expected) in [
("schema_01", "schema_01"),
("MixedCase", "\"MixedCase\""),
("order", "\"order\""),
("order detail", "\"order detail\""),
("already\"quoted", "\"already\"\"quoted\""),
("\"AlreadyQuoted\"", "\"AlreadyQuoted\""),
] {
assert_eq!(quote_table_data_identifier(Some(DatabaseType::Gaussdb), name, Some("\"")), expected);
}
for (name, expected) in [
("schema_01", "schema_01"),
("MixedCase", "`MixedCase`"),
("order", "`order`"),
("order detail", "`order detail`"),
("already`quoted", "`already``quoted`"),
("`AlreadyQuoted`", "`AlreadyQuoted`"),
] {
assert_eq!(quote_table_data_identifier(Some(DatabaseType::Gaussdb), name, Some("`")), expected);
}
}
#[test]
fn qualifies_schema_only_for_schema_aware_databases() {
assert_eq!(qualified_table_name(Some(DatabaseType::Postgres), Some("public"), "users"), "\"public\".\"users\"");
@@ -342,6 +369,72 @@ fn builds_table_data_where_and_schema_queries() {
}),
"SELECT * FROM \"App Schema\".\"ANALYZE\" LIMIT 100;"
);
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Gaussdb),
identifier_quote: Some("\"".to_string()),
schema: Some("schema_01".to_string()),
table_name: "table_01".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM schema_01.table_01 LIMIT 100;"
);
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Gaussdb),
identifier_quote: Some("`".to_string()),
schema: Some("App Schema".to_string()),
table_name: "order".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM `App Schema`.`order` LIMIT 100;"
);
for database_type in [DatabaseType::Postgres, DatabaseType::OpenGauss] {
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(database_type),
identifier_quote: Some("`".to_string()),
schema: Some("App Schema".to_string()),
table_name: "order".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM `App Schema`.`order` LIMIT 100;"
);
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(database_type),
identifier_quote: Some("\"".to_string()),
schema: Some("schema_01".to_string()),
table_name: "MixedCase".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM schema_01.\"MixedCase\" LIMIT 100;"
);
}
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Gaussdb),
schema: Some("schema_01".to_string()),
table_name: "table_01".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM \"schema_01\".\"table_01\" LIMIT 100;"
);
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::OpenGauss),
schema: Some("schema_01".to_string()),
table_name: "table_01".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM \"schema_01\".\"table_01\" LIMIT 100;"
);
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Xugu),