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。

feat(sql): quote non-ASCII ClickHouse identifiers with backticks

lxk9557e4d65daa577
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionCompletion.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionCompletion.spec.ts
index 0434afdde3..d0c71fe8a3 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionCompletion.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionCompletion.spec.ts
@@ -38,6 +38,14 @@ describe("dataGridConditionColumnOptions", () => {
]);
});
+ it("backtick-quotes ClickHouse non-ASCII and keyword columns while keeping plain ASCII bare", () => {
+ expect(dataGridConditionColumnOptions(["姓名", "user_id", "final"], "clickhouse")).toEqual([
+ { name: "姓名", insertText: "`姓名`" },
+ { name: "user_id", insertText: "user_id" },
+ { name: "final", insertText: "`final`" },
+ ]);
+ });
+
it("uses the active dialect identifier quote while preserving runtime overrides", () => {
expect(dataGridConditionIdentifierQuote("postgres")).toBe('"');
expect(dataGridConditionIdentifierQuote("oracle")).toBe('"');
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorTableDrop.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorTableDrop.spec.ts
index d29cda2e07..fdb68d4850 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorTableDrop.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorTableDrop.spec.ts
@@ -113,6 +113,14 @@ describe("query editor table reference drop", () => {
databaseType: "postgres",
})!;
expect(tableReferenceInsertText(postgres, undefined, commaNewline)).toBe('id,\n"OrderNo",\n"select"');
+
+ const clickhouse = createColumnReferencePayload({
+ connectionId: "conn-1",
+ database: "app-db",
+ columnNames: ["id", "created_at", "姓名", "prewhere", "order", "col$1"],
+ databaseType: "clickhouse",
+ })!;
+ expect(tableReferenceInsertText(clickhouse, undefined, commaNewline)).toBe("id,\ncreated_at,\n`姓名`,\n`prewhere`,\n`order`,\n`col$1`");
});
it("uses columnNameSeparator from the payload for multi-column sidebar drag", () => {
diff --git a/apps/desktop/src/lib/__tests__/sql/clickhouseIdentifierQuoting.spec.ts b/apps/desktop/src/lib/__tests__/sql/clickhouseIdentifierQuoting.spec.ts
new file mode 100644
index 0000000000..f204ed238a
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/clickhouseIdentifierQuoting.spec.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from "vitest";
+import { buildSqlCompletionItems } from "@/lib/sql/sqlCompletion";
+import { quoteTableIdentifierIfNeeded } from "@/lib/table/tableSelectSql";
+import { omitDdlIdentifierQuotes } from "@/lib/sql/ddlDisplay";
+import { requiresClickhouseIdentifierQuote } from "@/lib/sql/sqlIdentifier";
+
+const clickhouseInput = {
+ databaseType: "clickhouse" as const,
+ tables: [
+ { name: "用户表", type: "table" as const },
+ { name: "orders", type: "table" as const },
+ ],
+ columnsByTable: new Map([
+ [
+ "orders",
+ [
+ { name: "id", table: "orders" },
+ { name: "user_id", table: "orders" },
+ { name: "姓名", table: "orders" },
+ { name: "时间", table: "orders" },
+ { name: "prewhere", table: "orders" },
+ { name: "final", table: "orders" },
+ { name: "format", table: "orders" },
+ { name: "settings", table: "orders" },
+ { name: "col$1", table: "orders" },
+ { name: "col-1", table: "orders" },
+ ],
+ ],
+ [
+ "用户表",
+ [
+ { name: "id", table: "用户表" },
+ { name: "姓名", table: "用户表" },
+ ],
+ ],
+ ]),
+};
+
+describe("clickhouse identifier quoting predicate", () => {
+ it("quotes Chinese and non-ASCII identifiers", () => {
+ expect(requiresClickhouseIdentifierQuote("姓名")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("时间")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("用户表")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("测试_col")).toBe(true);
+ });
+
+ it("quotes identifiers containing $ or hyphens or spaces", () => {
+ expect(requiresClickhouseIdentifierQuote("col$1")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("col-1")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("col name")).toBe(true);
+ });
+
+ it("quotes ClickHouse-specific and standard SQL reserved keywords", () => {
+ expect(requiresClickhouseIdentifierQuote("prewhere")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("final")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("format")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("settings")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("order")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("select")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("from")).toBe(true);
+ expect(requiresClickhouseIdentifierQuote("where")).toBe(true);
+ });
+
+ it("leaves standard ASCII identifiers unquoted", () => {
+ expect(requiresClickhouseIdentifierQuote("id")).toBe(false);
+ expect(requiresClickhouseIdentifierQuote("user_id")).toBe(false);
+ expect(requiresClickhouseIdentifierQuote("created_at")).toBe(false);
+ expect(requiresClickhouseIdentifierQuote("UserName")).toBe(false);
+ });
+});
+
+describe("clickhouse completion quoting", () => {
+ it("backticks Chinese columns in WHERE clause completions while keeping standard English unquoted", () => {
+ const sql = "SELECT * FROM orders WHERE ";
+ const items = buildSqlCompletionItems(sql, sql.length, clickhouseInput);
+
+ const nameCol = items.find((item) => item.type === "column" && item.label === "姓名");
+ expect(nameCol?.apply).toBe("`姓名`");
+
+ const timeCol = items.find((item) => item.type === "column" && item.label === "时间");
+ expect(timeCol?.apply).toBe("`时间`");
+
+ const idCol = items.find((item) => item.type === "column" && item.label === "id");
+ expect(idCol?.apply).toBe("id");
+
+ const userIdCol = items.find((item) => item.type === "column" && item.label === "user_id");
+ expect(userIdCol?.apply).toBe("user_id");
+ });
+
+ it("backticks ClickHouse reserved keywords used as column names", () => {
+ const sql = "SELECT * FROM orders WHERE ";
+ const items = buildSqlCompletionItems(sql, sql.length, clickhouseInput);
+
+ for (const keyword of ["prewhere", "final", "format", "settings"]) {
+ const col = items.find((item) => item.type === "column" && item.label === keyword);
+ expect(col?.apply).toBe(`\`${keyword}\``);
+ }
+ });
+
+ it("backticks table name completions when table name is Chinese", () => {
+ const sql = "SELECT * FROM ";
+ const items = buildSqlCompletionItems(sql, sql.length, clickhouseInput);
+
+ const chineseTable = items.find((item) => item.type === "table" && item.label === "用户表");
+ expect(chineseTable?.apply).toBe("`用户表`");
+
+ const ordersTable = items.find((item) => item.type === "table" && item.label === "orders");
+ expect(ordersTable?.apply).toBe("orders");
+ });
+
+ it("backticks Chinese columns in alias-qualified completions", () => {
+ const sql = "SELECT o. FROM orders o";
+ const cursor = sql.indexOf(".");
+ const items = buildSqlCompletionItems(sql, cursor + 1, clickhouseInput);
+
+ const nameCol = items.find((item) => item.type === "column" && item.label === "姓名");
+ expect(nameCol?.apply).toBe("`姓名`");
+
+ const idCol = items.find((item) => item.type === "column" && item.label === "id");
+ expect(idCol?.apply).toBe("id");
+ });
+});
+
+describe("clickhouse tableSelectSql and DDL identifier quoting", () => {
+ it("quotes Chinese and reserved names in quoteTableIdentifierIfNeeded", () => {
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "姓名")).toBe("`姓名`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "prewhere")).toBe("`prewhere`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "user_id")).toBe("user_id");
+ });
+
+ it("preserves quotes on Chinese column names when omitting DDL quotes for ClickHouse", () => {
+ const ddl = "CREATE TABLE `orders` (`id` Int32, `姓名` String, `created_at` DateTime) ENGINE = MergeTree() ORDER BY id;";
+ const cleaned = omitDdlIdentifierQuotes(ddl, "clickhouse");
+ expect(cleaned).toBe("CREATE TABLE orders (id Int32, `姓名` String, created_at DateTime) ENGINE = MergeTree() ORDER BY id;");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/sql/semantic/completion.spec.ts b/apps/desktop/src/lib/__tests__/sql/semantic/completion.spec.ts
index 08be2b23cd..4c15add73c 100644
--- a/apps/desktop/src/lib/__tests__/sql/semantic/completion.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/semantic/completion.spec.ts
@@ -497,6 +497,7 @@ FROM (
it.each([
["Oracle", "oracle", "mysql", 'ID, o."created at", o."SELECT", o."safe_name", o."OrderId", o."order_id"'],
["MySQL", "mysql", "mysql", "`ID`, o.`created at`, o.`SELECT`, o.safe_name, o.`OrderId`, o.order_id"],
+ ["ClickHouse", "clickhouse", "mysql", "ID, o.`created at`, o.`SELECT`, o.safe_name, o.OrderId, o.order_id"],
["PostgreSQL", "postgres", "postgres", '"ID", o."created at", o."SELECT", o.safe_name, o."OrderId", o.order_id'],
["SQL Server", "sqlserver", "sqlserver", "[ID], o.[created at], o.[SELECT], o.safe_name, o.[OrderId], o.order_id"],
["dialect fallback", undefined, "mysql", "`ID`, o.`created at`, o.`SELECT`, o.safe_name, o.`OrderId`, o.order_id"],
@@ -510,6 +511,38 @@ FROM (
expect(selectAllItems.find((item) => item.label === "o.*")?.apply).toBe(expected);
});
+ it("quotes non-ASCII/Chinese and reserved columns with backticks while leaving bare English identifiers unquoted for ClickHouse", () => {
+ const columnsByTable = new Map<string, SqlCompletionColumn[]>([["orders", ["id", "order_id", "姓名", "时间", "prewhere", "final", "status"].map((name) => ({ name, table: "orders" }))]]);
+
+ const { items: columnItems } = semanticCompletion("SELECT o.| FROM orders o", { columnsByTable }, { databaseType: "clickhouse", dialect: "mysql" });
+ expect(columnItems.find((item) => item.label === "姓名")?.apply).toBe("`姓名`");
+ expect(columnItems.find((item) => item.label === "时间")?.apply).toBe("`时间`");
+ expect(columnItems.find((item) => item.label === "prewhere")?.apply).toBe("`prewhere`");
+ expect(columnItems.find((item) => item.label === "final")?.apply).toBe("`final`");
+ expect(columnItems.find((item) => item.label === "id")?.apply).toBe("id");
+ expect(columnItems.find((item) => item.label === "order_id")?.apply).toBe("order_id");
+ expect(columnItems.find((item) => item.label === "status")?.apply).toBe("status");
+
+ const star = columnItems.find((item) => item.label === "o.*");
+ expect(star?.apply).toBe("id, o.order_id, o.`姓名`, o.`时间`, o.`prewhere`, o.`final`, o.status");
+
+ const { items: tableItems } = semanticCompletion(
+ "SELECT * FROM |",
+ {
+ tables: [
+ { name: "用户表", type: "table" },
+ { name: "normal_table", type: "table" },
+ { name: "order", type: "table" },
+ ],
+ },
+ { databaseType: "clickhouse", dialect: "mysql" },
+ );
+
+ expect(tableItems.find((item) => item.label === "用户表")?.apply).toBe("`用户表`");
+ expect(tableItems.find((item) => item.label === "normal_table")?.apply).toBe("normal_table");
+ expect(tableItems.find((item) => item.label === "order")?.apply).toBe("`order`");
+ });
+
it("uses Oracle quoting for an unqualified multi-table star completion item", () => {
const columnsByTable = new Map<string, SqlCompletionColumn[]>([
["ORDERS", ["ID", "created at", "OrderId"].map((name) => ({ name, table: "ORDERS" }))],
diff --git a/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts b/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts
index cf8efc3917..f9d3053db7 100644
--- a/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts
@@ -312,6 +312,13 @@ describe("quoteTableIdentifier", () => {
expect(quoteTableIdentifierIfNeeded("postgres", "Order")).toBe('"Order"');
expect(quoteTableIdentifierIfNeeded("mysql", "dbx_test")).toBe("dbx_test");
expect(quoteTableIdentifierIfNeeded("mysql", "order")).toBe("`order`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "dbx_test")).toBe("dbx_test");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "Order_Test")).toBe("Order_Test");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "order")).toBe("`order`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "prewhere")).toBe("`prewhere`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "姓名")).toBe("`姓名`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "时间")).toBe("`时间`");
+ expect(quoteTableIdentifierIfNeeded("clickhouse", "col$1")).toBe("`col$1`");
});
it("uses a JDBC driver's reported quote for required identifiers", () => {
diff --git a/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts b/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts
index b880531eea..0fdf4b9b5a 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts
@@ -52,7 +52,10 @@ export function dataGridConditionColumnOptions(columns: readonly DataGridConditi
// Oracle-family identifier quoting needs the completion apply dialect; the
// CodeMirror syntax dialect has no Oracle entry and falls back to MySQL,
// which never quotes, so case-sensitive columns would insert unresolvable.
- const dialect = databaseType !== undefined && ORACLE_COMPAT_IDENTIFIER_DATABASES.has(databaseType) ? "oracle" : codeMirrorSqlDialect(databaseType);
+ // ClickHouse needs its own quoting dialect for the same reason: the
+ // CodeMirror fallback is MySQL, whose bare pattern permits non-ASCII
+ // characters that ClickHouse rejects (#13687).
+ const dialect = databaseType !== undefined && ORACLE_COMPAT_IDENTIFIER_DATABASES.has(databaseType) ? "oracle" : databaseType === "clickhouse" ? "clickhouse" : codeMirrorSqlDialect(databaseType);
return columns.map((column) => {
const name = typeof column === "string" ? column : column.name;
const insertText = quoteSqlIdentifier(name, dialect);
diff --git a/apps/desktop/src/lib/editor/queryEditorTableDrop.ts b/apps/desktop/src/lib/editor/queryEditorTableDrop.ts
index 3bf9868098..48dce8153f 100644
--- a/apps/desktop/src/lib/editor/queryEditorTableDrop.ts
+++ b/apps/desktop/src/lib/editor/queryEditorTableDrop.ts
@@ -1,10 +1,10 @@
import type { DatabaseType } from "@/types/database";
import { COLUMN_NAME_COPY_SEPARATOR_VALUES, loadColumnNameCopySeparator, type ColumnNameCopySeparator, isColumnNameCopySeparator } from "@/lib/dataGrid/dataGridColumnNameCopy";
import { qualifiedTableName, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
-import { requiresMysqlIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier.ts";
+import { requiresClickhouseIdentifierQuote, requiresMysqlIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier.ts";
/** 智能引号使用反引号的方言族。 */
-const SMART_QUOTE_BACKTICK_TYPES = new Set<DatabaseType>(["mysql", "clickhouse", "hive", "argo", "transwarp", "kyuubi", "impala", "spark", "databricks", "databend", "tdengine", "access", "doris", "starrocks", "goldendb"]);
+const SMART_QUOTE_BACKTICK_TYPES = new Set<DatabaseType>(["mysql", "hive", "argo", "transwarp", "kyuubi", "impala", "spark", "databricks", "databend", "tdengine", "access", "doris", "starrocks", "goldendb"]);
/** 智能引号使用双引号的方言族(SQL Server 方括号除外)。 */
const SMART_QUOTE_DOUBLE_TYPES = new Set<DatabaseType>(["postgres", "gaussdb", "opengauss"]);
/** SQL Server 族智能引号使用方括号。 */
@@ -18,6 +18,9 @@ const SMART_QUOTE_BRACKET_TYPES = new Set<DatabaseType>(["sqlserver"]);
* 用「严格标识符正则 + PG/MySQL 保留字并集」做通用保守判定。
*/
function quoteColumnReferenceName(databaseType: DatabaseType | undefined, name: string): string {
+ if (databaseType === "clickhouse") {
+ return requiresClickhouseIdentifierQuote(name) ? `\`${name.replace(/`/g, "``")}\`` : name;
+ }
if (databaseType && SMART_QUOTE_BACKTICK_TYPES.has(databaseType)) {
return requiresMysqlIdentifierQuote(name) ? `\`${name.replace(/`/g, "``")}\`` : name;
}
diff --git a/apps/desktop/src/lib/sql/ddlDisplay.ts b/apps/desktop/src/lib/sql/ddlDisplay.ts
index eb00f6342a..7ea9f31b55 100644
--- a/apps/desktop/src/lib/sql/ddlDisplay.ts
+++ b/apps/desktop/src/lib/sql/ddlDisplay.ts
@@ -1,4 +1,4 @@
-import { requiresDamengIdentifierQuote, requiresMysqlIdentifierQuote, requiresOracleIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
+import { requiresClickhouseIdentifierQuote, requiresDamengIdentifierQuote, requiresMysqlIdentifierQuote, requiresOracleIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
import { tokenIsIdentifier, tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";
import type { SqlSemanticToken } from "@/lib/sql/semantic/types";
import { formatSqlForDisplay, sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
@@ -31,8 +31,9 @@ type DdlColumnAttributePositions = {
function canRenderUnquoted(identifier: string, dialect: SqlFormatDialect): boolean {
switch (dialect) {
case "mysql":
- case "clickhouse":
return !requiresMysqlIdentifierQuote(identifier);
+ case "clickhouse":
+ return !requiresClickhouseIdentifierQuote(identifier);
case "postgres":
case "sqlite":
case "duckdb":
diff --git a/apps/desktop/src/lib/sql/sqlCompletion.ts b/apps/desktop/src/lib/sql/sqlCompletion.ts
index 04a8b8aa10..1e20e80a01 100644
--- a/apps/desktop/src/lib/sql/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sql/sqlCompletion.ts
@@ -14,7 +14,7 @@ import type { SqlSemanticBuildOptions, SqlSemanticSpan } from "@/lib/sql/semanti
import { isEditorStatePlausibleFor, resolveLexicalLeafFromSyntaxTree, resolveSqlStatementWindow } from "@/lib/sql/sqlSyntaxTreeWindow";
import { DEFAULT_SQL_SNIPPETS, MANTICORESEARCH_SQL_SNIPPETS, resolveSqlSnippetBodyForDatabase } from "@/lib/sql/sqlSnippetTemplates";
import { BACKSLASH_ESCAPE_STRING_DIALECTS } from "@/lib/sql/sqlStatementRanges";
-import { requiresMysqlIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
+import { requiresClickhouseIdentifierQuote, requiresMysqlIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
import { identifierMatchScore, matchesIdentifierSearch } from "@/lib/sql/identifierSearch";
import { containsHan, orderedSubsequenceSpan, pinyinFirstLetters } from "@/lib/common/pinyin";
import { quoteTableIdentifier, quoteTableIdentifierIfNeeded } from "@/lib/table/tableSelectSql";
@@ -1691,18 +1691,19 @@ export function shouldChainSqlCompletionAfterAccept(item: { type?: string; apply
export type SqlKeywordCase = "preserve" | "upper" | "lower";
-type SqlCompletionApplyDialect = "mysql" | "postgres" | "sqlserver" | "oracle" | "upper";
+type SqlCompletionApplyDialect = "mysql" | "postgres" | "sqlserver" | "oracle" | "upper" | "clickhouse";
// QueryEditor may use another dialect as a CodeMirror syntax fallback.
// Completion apply text must still follow the connected database's identifier
// folding and quoting rules.
-const MYSQL_LIKE_IDENTIFIER_DATABASES = new Set<DatabaseType>(["mysql", "clickhouse", "hive", "argo", "transwarp", "kyuubi", "impala", "spark", "databend", "tdengine", "access", "doris", "starrocks"]);
+const MYSQL_LIKE_IDENTIFIER_DATABASES = new Set<DatabaseType>(["mysql", "hive", "argo", "transwarp", "kyuubi", "impala", "spark", "databend", "tdengine", "access", "doris", "starrocks"]);
const POSTGRES_LIKE_IDENTIFIER_DATABASES = new Set<DatabaseType>(["postgres", "redshift", "gaussdb", "kingbase", "highgo", "uxdb", "vastbase", "kwdb", "opengauss"]);
export const ORACLE_COMPAT_IDENTIFIER_DATABASES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "yashandb", "oscar", "xugu"]);
const UPPER_FOLDING_IDENTIFIER_DATABASES = new Set<DatabaseType>(["dameng", "db2", "snowflake"]);
function sqlCompletionApplyDialect(databaseType: DatabaseType | undefined, fallback: "mysql" | "postgres" | "sqlserver" | undefined): SqlCompletionApplyDialect | undefined {
if (!databaseType) return fallback;
+ if (databaseType === "clickhouse") return "clickhouse";
if (MYSQL_LIKE_IDENTIFIER_DATABASES.has(databaseType)) return "mysql";
if (POSTGRES_LIKE_IDENTIFIER_DATABASES.has(databaseType)) return "postgres";
if (ORACLE_COMPAT_IDENTIFIER_DATABASES.has(databaseType)) return "oracle";
@@ -4734,6 +4735,10 @@ export function quoteSqlIdentifier(identifier: string, dialect?: SqlCompletionAp
if (/^[A-Z][A-Z0-9_$#]*$/.test(identifier) && !POSTGRES_IDENTIFIER_KEYWORDS.has(identifier.toLowerCase())) return identifier;
return `"${identifier.replaceAll('"', '""')}"`;
}
+ if (dialect === "clickhouse") {
+ if (!requiresClickhouseIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
+ return `\`${identifier.replaceAll("`", "``")}\``;
+ }
if (dialect !== "postgres" || !requiresPostgresIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
return `"${identifier.replaceAll('"', '""')}"`;
}
@@ -4751,6 +4756,10 @@ function quoteCompletionApplyIdentifier(identifier: string, dialect?: SqlComplet
if (!requiresMysqlIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
return `\`${identifier.replaceAll("`", "``")}\``;
}
+ if (dialect === "clickhouse") {
+ if (!requiresClickhouseIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
+ return `\`${identifier.replaceAll("`", "``")}\``;
+ }
if (dialect === "sqlserver") {
if (SQLSERVER_REGULAR_IDENTIFIER.test(identifier) && !requiresMysqlIdentifierQuote(identifier.toLowerCase(), SQLSERVER_IDENTIFIER_KEYWORDS)) return identifier;
const escaped = identifier.replaceAll("]", "]]");
@@ -4760,7 +4769,7 @@ function quoteCompletionApplyIdentifier(identifier: string, dialect?: SqlComplet
}
function quoteCompletionApplyName(applyName: string, dialect?: SqlCompletionApplyDialect): string {
- if (dialect !== "mysql" && dialect !== "oracle" && dialect !== "sqlserver") return applyName;
+ if (dialect !== "mysql" && dialect !== "oracle" && dialect !== "sqlserver" && dialect !== "clickhouse") return applyName;
const parts = splitQualifiedNameRawParts(applyName);
if (parts.length === 0) return applyName;
return parts.map((part) => ((dialect === "sqlserver" && !part) || isQuotedIdentifier(part) ? part : quoteCompletionApplyIdentifier(part, dialect))).join(".");
@@ -4780,6 +4789,9 @@ function quoteCompletionRoutineName(applyName: string, dialect?: SqlCompletionAp
function quoteSelectStarColumnIdentifier(identifier: string, dialect?: SqlCompletionApplyDialect, databaseType?: DatabaseType): string {
if (databaseType === "oracle" || databaseType === "oceanbase-oracle" || (databaseType === undefined && dialect === "oracle")) return quoteTableIdentifierIfNeeded("oracle", identifier);
+ if (databaseType === "clickhouse" || (databaseType === undefined && dialect === "clickhouse")) {
+ return quoteTableIdentifierIfNeeded("clickhouse", identifier);
+ }
if (!requiresPostgresIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
if (databaseType) return quoteTableIdentifier(databaseType, identifier);
if (dialect === "mysql") return `\`${identifier.replaceAll("`", "``")}\``;
@@ -4973,7 +4985,7 @@ function buildTableItems(
const tableName = applySqlIdentifierCase(table.name, identifierCase, identifierDialect ?? dialect);
const unqualifiedApplyName = quoteCasedIdentifier(table.name, tableName, dialect);
const rawSuppliedApplyName = table.applyName?.trim();
- const suppliedApplyName = dialect === "sqlserver" && rawSuppliedApplyName ? quoteCompletionApplyName(rawSuppliedApplyName, dialect) : rawSuppliedApplyName;
+ const suppliedApplyName = (dialect === "sqlserver" || dialect === "clickhouse") && rawSuppliedApplyName ? quoteCompletionApplyName(rawSuppliedApplyName, dialect) : rawSuppliedApplyName;
const casedSuppliedApplyName = suppliedApplyName ? applySqlIdentifierCaseToName(suppliedApplyName, identifierCase, dialect, identifierDialect) : undefined;
const suppliedApplyNameIsQualified = suppliedApplyName?.includes(".") === true;
const applyName =
diff --git a/apps/desktop/src/lib/sql/sqlIdentifier.ts b/apps/desktop/src/lib/sql/sqlIdentifier.ts
index 385d7c6c5f..d8d85904d7 100644
--- a/apps/desktop/src/lib/sql/sqlIdentifier.ts
+++ b/apps/desktop/src/lib/sql/sqlIdentifier.ts
@@ -1,5 +1,6 @@
const SIMPLE_LOWER_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;
const SIMPLE_MYSQL_IDENTIFIER = /^[A-Za-z_$\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*$/u;
+const SIMPLE_CLICKHOUSE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
const SIMPLE_DAMENG_IDENTIFIER = /^[A-Z_][A-Z0-9_]*$/;
const SIMPLE_ORACLE_IDENTIFIER = /^[A-Z][A-Z0-9_$#]*$/;
@@ -313,6 +314,57 @@ const MYSQL_ONLY_RESERVED_IDENTIFIER_KEYWORDS = new Set([
"zerofill",
]);
+// ClickHouse identifiers: bare identifiers cannot contain `$` or non-ASCII characters
+// and cannot match reserved keywords. Keywords outside PostgreSQL's set are listed here.
+const CLICKHOUSE_ONLY_RESERVED_IDENTIFIER_KEYWORDS = new Set([
+ "alias",
+ "alter",
+ "anti",
+ "asof",
+ "attach",
+ "between",
+ "by",
+ "cluster",
+ "codec",
+ "database",
+ "databases",
+ "delete",
+ "describe",
+ "detach",
+ "drop",
+ "engine",
+ "ephemeral",
+ "exchange",
+ "exists",
+ "explain",
+ "final",
+ "format",
+ "global",
+ "if",
+ "insert",
+ "interval",
+ "kill",
+ "materialized",
+ "optimize",
+ "partition",
+ "populate",
+ "prewhere",
+ "qualify",
+ "rename",
+ "replace",
+ "sample",
+ "semi",
+ "set",
+ "settings",
+ "show",
+ "system",
+ "totals",
+ "ttl",
+ "values",
+ "view",
+ "watch",
+]);
+
// Oracle 11g SQL reserved words. Ordinary unquoted Oracle identifiers are
// uppercase-folded, so only uppercase names outside this set are safe to unwrap.
const ORACLE_RESERVED_IDENTIFIER_KEYWORDS = new Set([
@@ -679,6 +731,12 @@ export function requiresMysqlIdentifierQuote(identifier: string, additionalKeywo
return POSTGRES_RESERVED_IDENTIFIER_KEYWORDS.has(normalized) || additionalKeywords?.has(normalized) === true || MYSQL_ONLY_RESERVED_IDENTIFIER_KEYWORDS.has(normalized);
}
+export function requiresClickhouseIdentifierQuote(identifier: string, additionalKeywords?: ReadonlySet<string>): boolean {
+ if (!SIMPLE_CLICKHOUSE_IDENTIFIER.test(identifier)) return true;
+ const normalized = identifier.toLowerCase();
+ return POSTGRES_RESERVED_IDENTIFIER_KEYWORDS.has(normalized) || additionalKeywords?.has(normalized) === true || CLICKHOUSE_ONLY_RESERVED_IDENTIFIER_KEYWORDS.has(normalized);
+}
+
export function requiresOracleIdentifierQuote(identifier: string): boolean {
return !SIMPLE_ORACLE_IDENTIFIER.test(identifier) || isOracleReservedKeyword(identifier);
}
diff --git a/apps/desktop/src/lib/table/tableSelectSql.ts b/apps/desktop/src/lib/table/tableSelectSql.ts
index a345a6bc09..1b85d35c7a 100644
--- a/apps/desktop/src/lib/table/tableSelectSql.ts
+++ b/apps/desktop/src/lib/table/tableSelectSql.ts
@@ -4,7 +4,7 @@ import { DATABASE_SCHEMA_QUALIFIED_TYPES } from "@/lib/database/databaseCapabili
import { jdbcDriverProfileUsesSchemaQualification } from "@/lib/database/jdbcDialect";
import * as api from "@/lib/backend/api.ts";
import { parseSqlServerLinkedSchema, sqlServerLinkedTableName } from "@/lib/database/sqlServerLinkedServers.ts";
-import { isExplicitlyQuotedSqlIdentifier, quoteGaussDbJdbcIdentifier, requiresDamengIdentifierQuote, requiresMysqlIdentifierQuote, requiresOracleIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier.ts";
+import { isExplicitlyQuotedSqlIdentifier, quoteGaussDbJdbcIdentifier, requiresClickhouseIdentifierQuote, requiresDamengIdentifierQuote, requiresMysqlIdentifierQuote, requiresOracleIdentifierQuote, requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier.ts";
import { sqlSemanticDialectFor } from "@/lib/sql/semantic/dialect";
import { sqlSemanticTableNameSpans } from "@/lib/sql/semantic/model";
import { tokenIsIdentifier, tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";
@@ -149,8 +149,9 @@ function quoteWithDelimiter(name: string, delimiter: string): string {
function requiresIdentifierQuote(databaseType: DatabaseType | undefined, name: string, identifierQuote?: string): boolean {
if (isExplicitlyQuotedSqlIdentifier(name)) return false;
switch (databaseType) {
- case "mysql":
case "clickhouse":
+ return requiresClickhouseIdentifierQuote(name);
+ case "mysql":
case "hive":
case "argo":
case "transwarp":