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

+62 -1
View File
@@ -1,5 +1,16 @@
import { describe, expect, it } from "vitest";
import { connectionObjectTreeNodeSchema, connectionQueryExecutionSchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, inferJdbcDialect } from "@/lib/database/jdbcDialect";
import {
connectionObjectTreeNodeSchema,
connectionQueryExecutionSchema,
connectionShouldLoadIdentifierQuote,
connectionUsesDatabaseObjectTreeMode,
effectiveDatabaseTypeForConnection,
gaussdbIdentifierQuoteOverride,
gaussdbIdentifierQuoteStyle,
inferJdbcDialect,
setGaussdbIdentifierQuoteStyle,
supportsGaussdbIdentifierQuoteStyle,
} from "@/lib/database/jdbcDialect";
describe("jdbc dialect inference", () => {
it("detects InterSystems IRIS and Caché JDBC connections", () => {
@@ -65,6 +76,56 @@ describe("jdbc dialect inference", () => {
expect(connectionUsesDatabaseObjectTreeMode(opengaussConnection)).toBe(false);
});
it("loads driver-reported identifier quotes for compatible JDBC connections", () => {
expect(connectionShouldLoadIdentifierQuote({ db_type: "jdbc", jdbc_driver_paths: ["/drivers/gaussdb.jar"] })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "jdbc", jdbc_driver_class: "org.opengauss.Driver" })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "jdbc", jdbc_driver_class: "org.postgresql.Driver" })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "kingbase" })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "gaussdb" })).toBe(true);
expect(
connectionShouldLoadIdentifierQuote({
db_type: "jdbc",
jdbc_driver_class: "org.postgresql.Driver",
external_config: { gaussdbIdentifierQuoteStyle: "backtick" },
}),
).toBe(false);
});
it("recognizes GaussDB reached through PostgreSQL-compatible JDBC drivers", () => {
const connection = {
db_type: "jdbc" as const,
connection_string: "jdbc:postgresql://localhost:5432/postgres",
jdbc_driver_class: "org.postgresql.Driver",
database_info: { productName: "GaussDB Kernel", driverName: "PostgreSQL JDBC Driver" },
};
expect(inferJdbcDialect(connection)).toBe("gaussdb");
expect(effectiveDatabaseTypeForConnection(connection)).toBe("gaussdb");
expect(supportsGaussdbIdentifierQuoteStyle(connection)).toBe(true);
});
it("supports persisted GaussDB identifier quote overrides", () => {
const native = { db_type: "gaussdb" as const, external_config: undefined as unknown };
const jdbc = { db_type: "jdbc" as const, jdbc_driver_paths: ["/drivers/gaussdb.jar"], external_config: { retained: true } as unknown };
expect(supportsGaussdbIdentifierQuoteStyle(native)).toBe(true);
expect(gaussdbIdentifierQuoteStyle(native)).toBe("auto");
expect(gaussdbIdentifierQuoteOverride(native)).toBeUndefined();
setGaussdbIdentifierQuoteStyle(native, "backtick");
expect(gaussdbIdentifierQuoteStyle(native)).toBe("backtick");
expect(gaussdbIdentifierQuoteOverride(native)).toBe("`");
setGaussdbIdentifierQuoteStyle(jdbc, "double");
expect(jdbc.external_config).toEqual({ retained: true, gaussdbIdentifierQuoteStyle: "double" });
expect(gaussdbIdentifierQuoteOverride(jdbc)).toBe('"');
expect(connectionShouldLoadIdentifierQuote(jdbc)).toBe(false);
setGaussdbIdentifierQuoteStyle(jdbc, "auto");
expect(jdbc.external_config).toEqual({ retained: true });
expect(connectionShouldLoadIdentifierQuote(jdbc)).toBe(true);
});
it("detects Dameng JDBC connections", () => {
const damengConnection = {
db_type: "jdbc" as const,
@@ -54,6 +54,42 @@ describe("quoteTableIdentifier", () => {
expect(quoteTableDataIdentifier("kingbase", "order detail", "`")).toBe("`order detail`");
});
it("selectively quotes GaussDB JDBC identifiers with the driver-reported quote", () => {
expect(quoteTableDataIdentifier("gaussdb", "table_01", '"')).toBe("table_01");
expect(quoteTableDataIdentifier("gaussdb", "MixedCase", '"')).toBe('"MixedCase"');
expect(quoteTableDataIdentifier("gaussdb", "order", '"')).toBe('"order"');
expect(quoteTableDataIdentifier("gaussdb", "order detail", '"')).toBe('"order detail"');
expect(quoteTableDataIdentifier("gaussdb", 'already"quoted', '"')).toBe('"already""quoted"');
expect(quoteTableDataIdentifier("gaussdb", '"AlreadyQuoted"', '"')).toBe('"AlreadyQuoted"');
expect(quoteTableDataIdentifier("gaussdb", "table_01", "`")).toBe("table_01");
expect(quoteTableDataIdentifier("gaussdb", "MixedCase", "`")).toBe("`MixedCase`");
expect(quoteTableDataIdentifier("gaussdb", "order", "`")).toBe("`order`");
expect(quoteTableDataIdentifier("gaussdb", "order detail", "`")).toBe("`order detail`");
expect(quoteTableDataIdentifier("gaussdb", "already`quoted", "`")).toBe("`already``quoted`");
expect(quoteTableDataIdentifier("gaussdb", "`AlreadyQuoted`", "`")).toBe("`AlreadyQuoted`");
});
it("uses detected GaussDB compatibility quotes through PostgreSQL-compatible JDBC dialects", () => {
for (const databaseType of ["postgres", "opengauss"] as const) {
expect(quoteTableDataIdentifier(databaseType, "table_01", "`")).toBe("table_01");
expect(quoteTableDataIdentifier(databaseType, "MixedCase", "`")).toBe("`MixedCase`");
expect(quoteTableDataIdentifier(databaseType, "order", "`")).toBe("`order`");
expect(quoteTableDataIdentifier(databaseType, "order detail", "`")).toBe("`order detail`");
expect(quoteTableDataIdentifier(databaseType, "`AlreadyQuoted`", "`")).toBe("`AlreadyQuoted`");
expect(quoteTableDataIdentifier(databaseType, "MixedCase", '"')).toBe('"MixedCase"');
}
});
it("preserves native GaussDB and openGauss quoting behavior", () => {
expect(quoteTableDataIdentifier("gaussdb", "table_01")).toBe('"table_01"');
expect(quoteTableDataIdentifier("gaussdb", "MixedCase")).toBe('"MixedCase"');
expect(quoteTableDataIdentifier("gaussdb", '"AlreadyQuoted"')).toBe('"AlreadyQuoted"');
expect(quoteTableDataIdentifier("opengauss", "table_01")).toBe('"table_01"');
expect(quoteTableDataIdentifier("opengauss", "MixedCase")).toBe('"MixedCase"');
expect(quoteTableDataIdentifier("opengauss", '"AlreadyQuoted"')).toBe('"AlreadyQuoted"');
});
it("escapes Kingbase identifiers without maintaining a reserved-word list", () => {
expect(quoteTableDataIdentifier("kingbase", "ANALYZE", "`")).toBe("`ANALYZE`");
expect(quoteTableDataIdentifier("kingbase", "AUTHORIZATION", '"')).toBe('"AUTHORIZATION"');
+51 -2
View File
@@ -2,7 +2,11 @@ import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { isSchemaAware, usesDatabaseObjectTreeMode, usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";
import type { CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";
type JdbcDialectConnection = Pick<ConnectionConfig, "db_type"> & Partial<Pick<ConnectionConfig, "driver_profile" | "driver_label" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info">>;
type JdbcDialectConnection = Pick<ConnectionConfig, "db_type"> & Partial<Pick<ConnectionConfig, "driver_profile" | "driver_label" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info" | "external_config">>;
export type GaussdbIdentifierQuoteStyle = "auto" | "double" | "backtick";
const GAUSSDB_IDENTIFIER_QUOTE_STYLE_KEY = "gaussdbIdentifierQuoteStyle";
const DATABASE_AS_EXECUTION_SCHEMA_TYPES = new Set<DatabaseType>(["hive", "spark"]);
@@ -34,7 +38,9 @@ const JDBC_ASE_PROFILE_PATTERNS = [/(?:^|[\s_-])ase(?:$|[\s_-])/i, /\bsap[\s_-]+
export function inferJdbcDialect(connection?: JdbcDialectConnection): DatabaseType | undefined {
if (!connection || connection.db_type !== "jdbc") return undefined;
const haystack = [connection.driver_profile, connection.connection_string, connection.jdbc_driver_class, ...(connection.jdbc_driver_paths ?? [])].filter(Boolean).join("\n");
const haystack = [connection.driver_profile, connection.driver_label, connection.connection_string, connection.jdbc_driver_class, ...(connection.jdbc_driver_paths ?? []), connection.database_info?.productName, connection.database_info?.serverComment, connection.database_info?.driverName]
.filter(Boolean)
.join("\n");
if (!haystack) return undefined;
return JDBC_DIALECT_MATCHERS.find((matcher) => matcher.patterns.some((pattern) => pattern.test(haystack)))?.type;
}
@@ -57,6 +63,45 @@ export function effectiveDatabaseTypeForConnection(connection?: JdbcDialectConne
return inferJdbcDialect(connection) ?? "jdbc";
}
export function connectionShouldLoadIdentifierQuote(connection: JdbcDialectConnection | undefined): boolean {
if (!connection) return false;
if (connection.db_type === "kingbase") return true;
if (gaussdbIdentifierQuoteStyle(connection) !== "auto") return false;
if (connection.db_type === "gaussdb") return true;
if (connection.db_type !== "jdbc") return false;
return ["gaussdb", "opengauss", "postgres"].includes(inferJdbcDialect(connection) ?? "");
}
export function supportsGaussdbIdentifierQuoteStyle(connection: JdbcDialectConnection | undefined): boolean {
return effectiveDatabaseTypeForConnection(connection) === "gaussdb";
}
export function gaussdbIdentifierQuoteStyle(connection: JdbcDialectConnection | undefined): GaussdbIdentifierQuoteStyle {
const external = externalConfigRecord(connection?.external_config);
const style = external[GAUSSDB_IDENTIFIER_QUOTE_STYLE_KEY];
return style === "double" || style === "backtick" ? style : "auto";
}
export function gaussdbIdentifierQuoteOverride(connection: JdbcDialectConnection | undefined): string | undefined {
const style = gaussdbIdentifierQuoteStyle(connection);
if (style === "double") return '"';
if (style === "backtick") return "`";
return undefined;
}
export function setGaussdbIdentifierQuoteStyle(
connection: Pick<ConnectionConfig, "db_type"> & Partial<Pick<ConnectionConfig, "driver_profile" | "driver_label" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info" | "external_config">>,
style: GaussdbIdentifierQuoteStyle,
) {
const external = externalConfigRecord(connection.external_config);
if (style === "auto") {
delete external[GAUSSDB_IDENTIFIER_QUOTE_STYLE_KEY];
} else {
external[GAUSSDB_IDENTIFIER_QUOTE_STYLE_KEY] = style;
}
connection.external_config = Object.keys(external).length > 0 ? external : undefined;
}
export function sqlSnippetDatabaseTypeForConnection(connection?: JdbcDialectConnection): DatabaseType | undefined {
// ASE uses T-SQL snippets, but mapping it globally to SQL Server would also
// enable incompatible SQL Server metadata and pagination behavior.
@@ -142,3 +187,7 @@ function isJdbcAseProfile(connection?: JdbcDialectConnection): boolean {
function isGbase8sProfile(driverProfile?: string): boolean {
return driverProfile === "gbase8s";
}
function externalConfigRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? { ...(value as Record<string, unknown>) } : {};
}
+3 -115
View File
@@ -7,6 +7,7 @@ import { sqlSemanticDialectFor } from "@/lib/sql/semantic/dialect";
import { findActiveSqlStatementSpan, tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
import type { SqlSemanticBuildOptions, SqlSemanticSpan } from "@/lib/sql/semantic/types";
import { DEFAULT_SQL_SNIPPETS, MANTICORESEARCH_SQL_SNIPPETS, resolveSqlSnippetBodyForDatabase } from "@/lib/sql/sqlSnippetTemplates";
import { requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
export { DEFAULT_SQL_SNIPPETS, resolveSqlSnippetBodyForDatabase } from "@/lib/sql/sqlSnippetTemplates";
@@ -2781,124 +2782,11 @@ function unquoteIdentifier(value: string): string {
}
export function quoteSqlIdentifier(identifier: string, dialect?: "mysql" | "postgres" | "sqlserver"): string {
if (dialect !== "postgres" || !requiresPostgresIdentifierQuote(identifier)) return identifier;
if (dialect !== "postgres" || !requiresPostgresIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
return `"${identifier.replaceAll('"', '""')}"`;
}
function requiresPostgresIdentifierQuote(identifier: string): boolean {
if (!/^[a-z_][a-z0-9_$]*$/.test(identifier)) return true;
return POSTGRES_IDENTIFIER_KEYWORDS.has(identifier);
}
// PostgreSQL reserved_keyword + type_func_name_keyword categories (pg_get_keywords()
// catcodes R and T) — identifiers matching these cannot appear as a bare column
// reference and must be quoted. SQL_KEYWORDS alone misses most of them because it is
// a completion phrase list ("ORDER BY", not "order").
const POSTGRES_RESERVED_KEYWORDS = [
"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",
];
const POSTGRES_IDENTIFIER_KEYWORDS = new Set(SQL_KEYWORDS.map((keyword) => keyword.toLowerCase()).concat(POSTGRES_RESERVED_KEYWORDS));
const POSTGRES_IDENTIFIER_KEYWORDS = new Set(SQL_KEYWORDS.map((keyword) => keyword.toLowerCase()));
function buildTableItems(
context: Pick<SqlCompletionContext, "prefix" | "qualifier">,
+200
View File
@@ -0,0 +1,200 @@
const SIMPLE_LOWER_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;
// PostgreSQL pg_get_keywords() categories R and T. GaussDB's PostgreSQL-
// compatible modes use the same identifier constraints for bare names.
const POSTGRES_RESERVED_IDENTIFIER_KEYWORDS = new Set([
"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",
]);
// GaussDB MySQL-compatible drivers report a backtick. These additional words
// cover MySQL-only names that cannot safely be emitted as bare identifiers.
const MYSQL_ONLY_RESERVED_IDENTIFIER_KEYWORDS = new Set([
"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",
]);
export function isExplicitlyQuotedSqlIdentifier(value: string): boolean {
if (value.length < 2) return false;
return (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("`") && value.endsWith("`")) || (value.startsWith("[") && value.endsWith("]"));
}
export function requiresPostgresIdentifierQuote(identifier: string, additionalKeywords?: ReadonlySet<string>): boolean {
if (!SIMPLE_LOWER_IDENTIFIER.test(identifier)) return true;
return POSTGRES_RESERVED_IDENTIFIER_KEYWORDS.has(identifier) || additionalKeywords?.has(identifier) === true;
}
export function quoteGaussDbJdbcIdentifier(identifier: string, identifierQuote: string): string {
if (isExplicitlyQuotedSqlIdentifier(identifier)) return identifier;
const quote = identifierQuote.trim();
if (!quote) return identifier;
const requiresQuote = !SIMPLE_LOWER_IDENTIFIER.test(identifier) || POSTGRES_RESERVED_IDENTIFIER_KEYWORDS.has(identifier) || (quote === "`" && MYSQL_ONLY_RESERVED_IDENTIFIER_KEYWORDS.has(identifier));
if (!requiresQuote) return identifier;
return `${quote}${identifier.replaceAll(quote, quote + quote)}${quote}`;
}
@@ -2,6 +2,7 @@ import type { DatabaseType } from "@/types/database.ts";
import { isSchemaAware, usesDatabaseObjectTreeMode } from "@/lib/database/databaseCapabilities.ts";
import * as api from "@/lib/backend/api.ts";
import { parseSqlServerLinkedSchema, sqlServerLinkedTableName } from "@/lib/database/sqlServerLinkedServers.ts";
import { isExplicitlyQuotedSqlIdentifier, quoteGaussDbJdbcIdentifier } from "@/lib/sql/sqlIdentifier.ts";
export interface BuildTableSelectSqlOptions {
databaseType?: DatabaseType;
@@ -22,6 +23,7 @@ export interface BuildTableSelectSqlOptions {
}
export function quoteTableIdentifier(databaseType: DatabaseType | undefined, name: string): string {
if ((databaseType === "gaussdb" || databaseType === "opengauss") && isExplicitlyQuotedSqlIdentifier(name)) return name;
if (databaseType === "iotdb") return name;
// JDBC connections use the driver-reported identifier quote string
// (DatabaseMetaData.getIdentifierQuoteString()) — pass through unquoted.
@@ -36,6 +38,7 @@ export function quoteTableIdentifier(databaseType: DatabaseType | undefined, nam
}
export function quoteTableDataIdentifier(databaseType: DatabaseType | undefined, name: string, identifierQuote?: string): string {
if ((databaseType === "gaussdb" || databaseType === "opengauss" || databaseType === "postgres") && identifierQuote != null) return quoteGaussDbJdbcIdentifier(name, identifierQuote);
if (databaseType === "kingbase" && identifierQuote != null) {
if (!identifierQuote) return name;
return `${identifierQuote}${name.replaceAll(identifierQuote, identifierQuote + identifierQuote)}${identifierQuote}`;