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(cockroachdb): add CockroachDB-specific SQL completion

Pius-x6c2d8a69064c
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts
new file mode 100644
index 0000000000..61db2706b8
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+import { buildSqlCompletionItems, getSqlFunctionSignatureHelp } from "@/lib/sql/sqlCompletion";
+
+describe("CockroachDB SQL completion (#13078)", () => {
+ function itemsFor(sql: string, driverProfile: "cockroachdb" | null = "cockroachdb") {
+ return buildSqlCompletionItems(sql, sql.length, {
+ databaseType: "postgres",
+ driverProfile: driverProfile ?? undefined,
+ tables: [],
+ columnsByTable: new Map(),
+ });
+ }
+
+ function labelsFor(sql: string, driverProfile?: "cockroachdb" | null) {
+ return itemsFor(sql, driverProfile).map((item) => item.label);
+ }
+
+ it("offers AS OF SYSTEM TIME after the typed AS prefix", () => {
+ const items = itemsFor("SELECT * FROM t AS O");
+ const item = items.find((candidate) => candidate.label === "OF SYSTEM TIME");
+
+ expect(item).toBeDefined();
+ expect(items.indexOf(item!)).toBeLessThan(3);
+ });
+
+ it("offers CRDB table options and distributed keywords", () => {
+ expect(labelsFor("CREATE TABLE t (id INT PRIMARY KEY) FAM")).toContain("FAMILY");
+ expect(labelsFor("ALTER TABLE t SPLIT")).toContain("SPLIT AT");
+ expect(labelsFor("ALTER TABLE t UNS")).toContain("UNSPLIT AT");
+ expect(labelsFor("ALTER TABLE t SET LOCAL")).toContain("LOCALITY");
+ expect(labelsFor("ALTER TABLE t REGIONAL BY")).toContain("REGIONAL BY ROW");
+ expect(labelsFor("UPS")).toContain("UPSERT");
+ });
+
+ it("offers CRDB-only types as data types", () => {
+ const bytes = itemsFor("CREATE TABLE t (payload BYT").find((item) => item.label === "BYTES");
+ const vector = itemsFor("CREATE TABLE t (embedding VEC").find((item) => item.label === "VECTOR");
+
+ expect(bytes?.detail).toBe("data type");
+ expect(vector?.detail).toBe("data type");
+ });
+
+ it("offers CRDB built-in functions that PostgreSQL does not provide", () => {
+ expect(labelsFor("SELECT cluster_logical_")).toContain("CLUSTER_LOGICAL_TIMESTAMP");
+ expect(labelsFor("SELECT timeofday(")).toContain("TIMEOFDAY");
+ expect(labelsFor("SELECT follower_")).toContain("FOLLOWER_READ_TIMESTAMP");
+ expect(labelsFor("SELECT with_")).toEqual(expect.arrayContaining(["WITH_MIN_TIMESTAMP", "WITH_MAX_STALENESS"]));
+ expect(labelsFor("SELECT l2_d")).toContain("L2_DISTANCE");
+ });
+
+ it("keeps PostgreSQL functions available on CockroachDB connections", () => {
+ expect(labelsFor("SELECT now(")).toContain("NOW");
+ expect(labelsFor("SELECT jsonb_build_object(")).toContain("JSONB_BUILD_OBJECT");
+ });
+
+ it("does not leak CockroachDB completions into a plain PostgreSQL connection", () => {
+ expect(labelsFor("SELECT * FROM t AS O", null)).not.toContain("OF SYSTEM TIME");
+ expect(labelsFor("SELECT cluster_logical_", null)).not.toContain("CLUSTER_LOGICAL_TIMESTAMP");
+ expect(labelsFor("CREATE TABLE t (id INT PRIMARY KEY) FAM", null)).not.toContain("FAMILY");
+ });
+
+ it("offers CRDB key-generation and aggregate helpers", () => {
+ expect(labelsFor("SELECT unique_")).toEqual(expect.arrayContaining(["UNIQUE_ROWID", "UNORDERED_UNIQUE_ROWID"]));
+ expect(labelsFor("SELECT uuid_v")).toContain("UUID_V4");
+ expect(labelsFor("SELECT ulid_to_")).toContain("ULID_TO_UUID");
+ expect(labelsFor("SELECT sum_")).toContain("SUM_INT");
+ expect(labelsFor("SELECT xor_")).toContain("XOR_AGG");
+ expect(labelsFor("SELECT vector_")).toEqual(expect.arrayContaining(["VECTOR_DIMS", "VECTOR_NORM"]));
+ expect(labelsFor("SELECT prettify_")).toContain("PRETTIFY_STATEMENT");
+ });
+
+ it("offers multi-region, chained, and transactional keywords", () => {
+ expect(labelsFor("ALTER DATABASE db ADD REGI")).toContain("REGION");
+ expect(labelsFor("ALTER DATABASE db SURV")).toContain("SURVIVE");
+ expect(labelsFor("CREATE INDEX i ON t (a) STOR")).toContain("STORING");
+ expect(labelsFor("CREATE TABLE t (id INT GENERATED ALW")).toContain("ALWAYS");
+ expect(labelsFor("SAVE")).toContain("SAVEPOINT");
+ expect(labelsFor("SELECT a FROM t GROUP BY ROLL")).toContain("ROLLUP");
+ });
+
+ it("returns signature help for CRDB functions", () => {
+ const sql = "SELECT with_max_staleness(";
+ const help = getSqlFunctionSignatureHelp(sql, sql.length, "postgres", "cockroachdb");
+
+ expect(help?.name).toBe("WITH_MAX_STALENESS");
+ expect(help?.parameters).toEqual(["max_staleness", "nearest_only"]);
+ });
+});
diff --git a/apps/desktop/src/lib/database/cockroachdbProfile.ts b/apps/desktop/src/lib/database/cockroachdbProfile.ts
new file mode 100644
index 0000000000..fbff6a80de
--- /dev/null
+++ b/apps/desktop/src/lib/database/cockroachdbProfile.ts
@@ -0,0 +1,213 @@
+import type { DriverProfileExtensionDefinition } from "@/lib/database/driverProfileExtensions";
+
+export const COCKROACHDB_DRIVER_PROFILE = "cockroachdb";
+
+/**
+ * CockroachDB 在 DBX 里是 `postgres` + `driver_profile="cockroachdb"`,不是独立的
+ * `DatabaseType`,所以 PostgreSQL 方言的关键字和函数表本来就已经生效。这里只补
+ * CRDB 专有部分,由 `driverProfileExtensions` 叠加到 PG 方言之上。
+ *
+ * 关键字来源:CRDB SQL Grammar(`pkg/sql/parser/sql.y`)的 reserved /
+ * type_func_name / col_name / cockroachdb_extra_reserved 四类,去掉与
+ * `COMMON_SQL_KEYWORDS`、`POSTGRES_SQL_KEYWORDS` 重复的项,并按日常 SQL 写作场景
+ * 筛掉了纯管理员语法(例如 `NOVIEWACTIVITY`、`SKIP_MISSING_UDFS`),避免补全列表
+ * 被低频关键字淹没。多词关键字与现有表保持一致,用空格分隔。
+ */
+export const COCKROACHDB_SQL_KEYWORDS = [
+ // 类型:STRING / BYTES 是 CRDB 对 TEXT / BYTEA 的别名,VECTOR 是向量列类型
+ "STRING",
+ "BYTES",
+ "VECTOR",
+ "BOX2D",
+ "GEOGRAPHY",
+ "GEOMETRY",
+ // 时间旅行
+ "AS OF SYSTEM TIME",
+ // 多区域 / 地域
+ "LOCALITY",
+ "REGIONAL",
+ "REGIONAL BY ROW",
+ "REGIONAL BY TABLE",
+ "REGIONAL IN",
+ "REGION",
+ "REGIONS",
+ "SURVIVE",
+ "FAILURE",
+ "GLOBAL",
+ // 列族、索引、生成列
+ "FAMILY",
+ "INVERTED",
+ "INVERTED INDEX",
+ "STORED",
+ "STORING",
+ "VIRTUAL",
+ "INCLUDE",
+ "VISIBLE",
+ "INVISIBLE",
+ "HASH",
+ "ON UPDATE",
+ "WITH ORDINALITY",
+ "ALWAYS",
+ // 查询子句
+ "NULLS",
+ "FETCH",
+ "ONLY",
+ "ROLLUP",
+ "CUBE",
+ "WITHIN GROUP",
+ "UNBOUNDED",
+ "PRECEDING",
+ "FOLLOWING",
+ // 例程、类型与事务
+ "CALL",
+ "PROCEDURE",
+ "FUNCTION",
+ "TRIGGER",
+ "TYPE",
+ "ENUM",
+ "SAVEPOINT",
+ "RELEASE",
+ "PREPARE",
+ "EXECUTE",
+ "DEALLOCATE",
+ "ISOLATION",
+ "SERIALIZABLE",
+ "REPEATABLE",
+ "READ",
+ "COMMITTED",
+ "UNCOMMITTED",
+ // 表与数据管理
+ "SPLIT",
+ "SPLIT AT",
+ "UNSPLIT",
+ "UNSPLIT AT",
+ "EXPERIMENTAL_AUDIT",
+ "UPSERT",
+ "PARTIAL",
+ "MINVALUE",
+ "MAXVALUE",
+ "CYCLE",
+ // 备份、流、运维
+ "BACKUP",
+ "RESTORE",
+ "CHANGEFEED",
+ "SCHEDULE",
+ "CANCELQUERY",
+ "COMPACT",
+ "SCRUB",
+ "ANALYZE",
+ "JOB",
+ "JOBS",
+ "TENANT",
+ "CLUSTER",
+ "NODE",
+ "RANGE",
+ "ZONE",
+ "CONFIGURE",
+ "CONFIGURE ZONE",
+ "RELOCATE",
+ "SCATTER",
+ "PAUSE",
+ "RESUME",
+ // 表达式
+ "IFERROR",
+ "ISERROR",
+ "ANNOTATE_TYPE",
+ "EXTRACT_DURATION",
+ "GROUPING",
+ "TREAT",
+ "EXPERIMENTAL",
+];
+
+/**
+ * CRDB 专有内置函数,取自 docs.cockroachlabs.com 的 functions-and-operators。
+ * 参数名只用于补全提示与签名提示,不做语法校验;PG 已有的函数由 PG 表提供,
+ * 这里不重复登记。
+ */
+export const COCKROACHDB_FUNCTION_SIGNATURES = new Map<string, string[]>([
+ // 时间与时间旅行
+ ["CLUSTER_LOGICAL_TIMESTAMP", []],
+ ["TIMEOFDAY", []],
+ ["FOLLOWER_READ_TIMESTAMP", []],
+ ["EXPERIMENTAL_FOLLOWER_READ_TIMESTAMP", []],
+ ["WITH_MIN_TIMESTAMP", ["min_timestamp", "nearest_only"]],
+ ["WITH_MAX_STALENESS", ["max_staleness", "nearest_only"]],
+ ["HLC_TO_TIMESTAMP", ["hlc"]],
+ ["EXPERIMENTAL_STRFTIME", ["timestamp", "format"]],
+ ["EXPERIMENTAL_STRPTIME", ["string", "format"]],
+ // 拓扑与租户
+ ["GATEWAY_REGION", []],
+ ["DEFAULT_TO_DATABASE_PRIMARY_REGION", ["region"]],
+ // 主键与行标识
+ ["UNIQUE_ROWID", []],
+ ["UNORDERED_UNIQUE_ROWID", []],
+ ["UUID_V4", []],
+ ["EXPERIMENTAL_UUID_V4", []],
+ ["ULID_TO_UUID", ["val"]],
+ ["UUID_TO_ULID", ["val"]],
+ ["REHOME_ROW", []],
+ // 标识符与哈希
+ ["GEN_RANDOM_ULID", []],
+ ["GEN_RANDOM_BYTES", ["count"]],
+ ["CRC32C", ["string"]],
+ ["CRC32IEEE", ["string"]],
+ ["FNV32", ["string"]],
+ ["FNV32A", ["string"]],
+ ["FNV64", ["string"]],
+ ["FNV64A", ["string"]],
+ ["SHA1", ["string"]],
+ ["SHA256", ["string"]],
+ ["SHA512", ["string"]],
+ ["DIGEST", ["data", "algorithm"]],
+ ["FROM_IP", ["string"]],
+ ["FROM_UUID", ["uuid"]],
+ ["TO_UUID", ["bytes"]],
+ // JSON
+ ["JSON_VALID", ["json"]],
+ ["JSON_REMOVE_PATH", ["json", "path"]],
+ ["JSON_SET", ["json", "path", "value"]],
+ ["JSONB_ARRAY_TO_STRING_ARRAY", ["jsonb"]],
+ // 解析
+ ["PARSE_DATE", ["string"]],
+ ["PARSE_TIME", ["string"]],
+ ["PARSE_TIMETZ", ["string"]],
+ ["PARSE_TIMESTAMP", ["string"]],
+ ["PARSE_INTERVAL", ["string"]],
+ ["PARSE_IDENT", ["string"]],
+ // 向量距离(CRDB v25.2+)
+ ["L1_DISTANCE", ["vector1", "vector2"]],
+ ["L2_DISTANCE", ["vector1", "vector2"]],
+ ["COSINE_DISTANCE", ["vector1", "vector2"]],
+ ["INNER_PRODUCT", ["vector1", "vector2"]],
+ ["VECTOR_DIMS", ["vector"]],
+ ["VECTOR_NORM", ["vector"]],
+ // 网络与分布式
+ ["TO_IP", ["val"]],
+ ["BROADCAST", ["val"]],
+ // 格式化与元数据
+ ["PRETTIFY_STATEMENT", ["statement", "line_width", "align_mode", "case_mode"]],
+ ["STRFTIME", ["input", "extract_format"]],
+ ["STRPTIME", ["input", "format"]],
+ ["PG_GET_KEYWORDS", []],
+ ["PG_GET_SEQUENCE_DATA", ["sequence_oid"]],
+ // 聚合
+ ["COUNT_ROWS", []],
+ ["SUM_INT", ["arg1"]],
+ ["XOR_AGG", ["arg1"]],
+ ["ARRAY_CAT_AGG", ["array"]],
+ ["CONCAT_AGG", ["expression"]],
+ ["BITMASK_AND", ["bit"]],
+ ["BITMASK_OR", ["bit"]],
+ ["BITMASK_XOR", ["bit"]],
+]);
+
+export function isCockroachDbDriverProfile(driverProfile?: string): boolean {
+ return driverProfile?.trim().toLowerCase() === COCKROACHDB_DRIVER_PROFILE;
+}
+
+export const COCKROACHDB_DRIVER_PROFILE_EXTENSION: DriverProfileExtensionDefinition = {
+ id: COCKROACHDB_DRIVER_PROFILE,
+ sqlKeywords: () => COCKROACHDB_SQL_KEYWORDS,
+ functionSignatures: () => COCKROACHDB_FUNCTION_SIGNATURES,
+ sqlBuiltinTerms: () => Array.from(COCKROACHDB_FUNCTION_SIGNATURES.keys(), (name) => name.toLowerCase()).join(" "),
+};
diff --git a/apps/desktop/src/lib/database/driverProfileExtensions.ts b/apps/desktop/src/lib/database/driverProfileExtensions.ts
index c159a2c770..7013f4aba3 100644
--- a/apps/desktop/src/lib/database/driverProfileExtensions.ts
+++ b/apps/desktop/src/lib/database/driverProfileExtensions.ts
@@ -1,3 +1,4 @@
+import { COCKROACHDB_DRIVER_PROFILE_EXTENSION } from "@/lib/database/cockroachdbProfile";
import { DOLT_DRIVER_PROFILE_EXTENSION } from "@/lib/database/doltProfile";
import type { SqlCompletionObject, SqlCompletionTable, SqlStatementKind } from "@/lib/sql/sqlCompletion";
import type { ConnectionConfig, QueryTab, TableNameFilter, TreeNodeType } from "@/types/database";
@@ -48,11 +49,15 @@ export type DriverProfileExtensionDefinition = {
completionObjects?: (context: DriverProfileSqlCompletionContext) => SqlCompletionObject[];
completionTables?: (context: DriverProfileSqlCompletionContext) => SqlCompletionTable[];
sqlBuiltinTerms?: () => string;
+ /** 叠加到方言关键字表上,用于 profile 专有语法(例如 CockroachDB 的 FAMILY)。 */
+ sqlKeywords?: () => readonly string[];
+ /** 叠加到方言函数表上,用于 profile 专有函数。 */
+ functionSignatures?: () => Map<string, string[]>;
routineSignatures?: () => Map<string, string[]>;
databaseWorkspace?: DriverProfileDatabaseWorkspace;
};
-export const DRIVER_PROFILE_EXTENSIONS = [DOLT_DRIVER_PROFILE_EXTENSION] as const satisfies readonly DriverProfileExtensionDefinition[];
+export const DRIVER_PROFILE_EXTENSIONS = [DOLT_DRIVER_PROFILE_EXTENSION, COCKROACHDB_DRIVER_PROFILE_EXTENSION] as const satisfies readonly DriverProfileExtensionDefinition[];
export function driverProfileExtension(driverProfile?: string): DriverProfileExtensionDefinition | undefined {
const normalized = driverProfile?.trim().toLowerCase();
@@ -86,6 +91,14 @@ export function driverProfileSqlBuiltinTerms(driverProfile?: string): string {
return driverProfileExtension(driverProfile)?.sqlBuiltinTerms?.() ?? "";
}
+export function driverProfileSqlKeywords(driverProfile?: string): readonly string[] {
+ return driverProfileExtension(driverProfile)?.sqlKeywords?.() ?? [];
+}
+
+export function driverProfileFunctionSignatures(driverProfile?: string): Map<string, string[]> {
+ return driverProfileExtension(driverProfile)?.functionSignatures?.() ?? new Map();
+}
+
export function driverProfileRoutineSignatures(driverProfile?: string): Map<string, string[]> {
return driverProfileExtension(driverProfile)?.routineSignatures?.() ?? new Map();
}
diff --git a/apps/desktop/src/lib/sql/semantic/types.ts b/apps/desktop/src/lib/sql/semantic/types.ts
index ad9c3ec0b8..8b947a5db8 100644
--- a/apps/desktop/src/lib/sql/semantic/types.ts
+++ b/apps/desktop/src/lib/sql/semantic/types.ts
@@ -173,6 +173,8 @@ export interface SqlSemanticModel {
export interface SqlSemanticBuildOptions {
databaseType?: DatabaseType;
dialect?: "mysql" | "postgres" | "sqlserver" | "clickhouse" | "doris";
+ /** Connection driver profile (for example `cockroachdb`), when the caller has one. */
+ driverProfile?: string;
/**
* Live CodeMirror state for the document being edited, when the caller has one (i.e. this is a
* real editor completion request, not a pure-string test/utility call). When present and its
diff --git a/apps/desktop/src/lib/sql/sqlCompletion.ts b/apps/desktop/src/lib/sql/sqlCompletion.ts
index 5110f53eda..364f13299a 100644
--- a/apps/desktop/src/lib/sql/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sql/sqlCompletion.ts
@@ -18,7 +18,8 @@ import { requiresMysqlIdentifierQuote, requiresPostgresIdentifierQuote } from "@
import { identifierMatchScore, matchesIdentifierSearch } from "@/lib/sql/identifierSearch";
import { containsHan, orderedSubsequenceSpan, pinyinFirstLetters } from "@/lib/common/pinyin";
import { quoteTableIdentifier, quoteTableIdentifierIfNeeded } from "@/lib/table/tableSelectSql";
-import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, driverProfileCompletionTables, driverProfileRoutineSignatures } from "@/lib/database/driverProfileExtensions";
+import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, driverProfileCompletionTables, driverProfileFunctionSignatures, driverProfileRoutineSignatures, driverProfileSqlKeywords } from "@/lib/database/driverProfileExtensions";
+import { isCockroachDbDriverProfile } from "@/lib/database/cockroachdbProfile";
import { DORIS_FUNCTION_DOCS, DORIS_FUNCTION_SIGNATURES } from "@/lib/sql/doris/functions";
import { DUCKDB_FUNCTION_SIGNATURES } from "@/lib/sql/functionSignatures/duckdb";
import { HIVE_SPARK_FUNCTION_APPLY_TEMPLATES, HIVE_SPARK_FUNCTION_SIGNATURES } from "@/lib/sql/functionSignatures/hiveSpark";
@@ -919,6 +920,10 @@ const DATA_TYPE_KEYWORDS = new Set([
"JSON",
"JSONB",
"UUID",
+ "STRING",
+ "BYTES",
+ "VECTOR",
+ "BOX2D",
"SERIAL",
"BIGSERIAL",
"SMALLSERIAL",
@@ -1927,7 +1932,9 @@ class SqlCompletionProvider {
this.items.push(...buildSnippetItems(context.prefix, snippets.filter(shouldFormatBuiltinSnippet), this.input.keywordCase, this.databaseType));
}
if ((!preferReferencedColumns && !context.dataTypeContext) || context.suggestRoutines) {
- const functionItems = context.dataTypeContext ? [] : buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(this.t), this.databaseType, context.openingParenAfterCursor, this.input.keywordCase, this.input.functionCase, this.input.functionCompletionIncludeParams);
+ const functionItems = context.dataTypeContext
+ ? []
+ : buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(this.t), this.databaseType, context.openingParenAfterCursor, this.input.keywordCase, this.input.functionCase, this.input.functionCompletionIncludeParams, this.input.driverProfile);
this.items.push(...(preferReferencedColumns ? functionItems.filter((item) => item.label.toLowerCase().startsWith(context.prefix.toLowerCase())) : functionItems));
if (isOracleLikeDatabase(this.databaseType)) {
this.items.push(...buildOracleSystemValueItems(context.prefix, this.input.keywordCase));
@@ -1973,9 +1980,9 @@ class SqlCompletionProvider {
if (context.suggestKeywords && !context.exclusiveRoutineSuggestions && !pendingJoinKeyword) {
this.items.push(...buildJoinModifierKeywordItems(context.prefix, this.input.keywordCase, context.followingKeyword));
- this.items.push(...buildKeywordItems(context.prefix, context, this.databaseType, this.input.keywordCase));
+ this.items.push(...buildKeywordItems(context.prefix, context, this.databaseType, this.input.keywordCase, this.input.driverProfile));
} else if (shouldOfferKeywordPrefixContinuations(context, pendingJoinKeyword)) {
- this.items.push(...buildKeywordPrefixContinuationItems(context.prefix, context, this.databaseType, this.input.keywordCase));
+ this.items.push(...buildKeywordPrefixContinuationItems(context.prefix, context, this.databaseType, this.input.keywordCase, this.input.driverProfile));
}
if (!context.exclusiveTableSuggestions && context.suggestColumns) {
@@ -2661,7 +2668,7 @@ export function getSqlFunctionSignatureHelp(sql: string, cursor: number, databas
const observedParameter = countTopLevelCommas(call.groupText);
if (databaseType !== "clickhouse") {
const lookupName = call.name.toUpperCase();
- const parameters = activeFunctionSignatures(databaseType).get(lookupName) ?? driverProfileRoutineSignatures(driverProfile).get(lookupName);
+ const parameters = activeFunctionSignatures(databaseType, driverProfile).get(lookupName) ?? driverProfileRoutineSignatures(driverProfile).get(lookupName);
if (!parameters) return null;
const activeParameter = Math.min(observedParameter, Math.max(0, parameters.length - 1));
const signature = `${lookupName}(${parameters.join(", ")})`;
@@ -2882,7 +2889,7 @@ export function getSqlCompletionContext(sql: string, cursor: number, options: Sq
const preferredValueKeywords = sqlServerDatepartCompletionValues(beforeCursor, options.databaseType);
const mysqlVariablesAllowed = (options.databaseType === "mysql" || (!options.databaseType && options.dialect === "mysql")) && !prefix.startsWith("@") && !qualifier && !dataTypeContext && !afterTableTrigger && !insertInfo && !inCallRoutineContext;
const localVariables = prefix.startsWith("@") ? collectSqlServerLocalVariables(sql, cursor, options) : mysqlVariablesAllowed ? collectMysqlRoutineVariables(sql, cursor) : undefined;
- const preferredKeywords = qualifier ? [] : preferredKeywordsForCompletion(beforeCursor, beforeToken, selectListColumnContext, exclusiveTableSuggestions, updateInfo, deleteInfo, options.databaseType);
+ const preferredKeywords = qualifier ? [] : preferredKeywordsForCompletion(beforeCursor, beforeToken, selectListColumnContext, exclusiveTableSuggestions, updateInfo, deleteInfo, options.databaseType, options.driverProfile);
const contextKind = detectCompletionContextKind({
qualifier,
exclusiveTableSuggestions,
@@ -3575,6 +3582,7 @@ function preferredKeywordsForCompletion(
updateInfo: ReturnType<typeof detectUpdateCompletionContext>,
deleteInfo: ReturnType<typeof detectDeleteCompletionContext>,
databaseType: DatabaseType | undefined,
+ driverProfile?: string,
): string[] {
const keywords: string[] = [];
if (databaseType !== "sqlserver" && databaseType !== "sqlite" && /^create\s+or$/i.test(maskSqlLiteralsAndComments(beforeToken, databaseType).trim())) {
@@ -3587,6 +3595,9 @@ function preferredKeywordsForCompletion(
if (updateInfo?.afterTarget) keywords.push("SET");
if (updateInfo?.afterSetAssignments) keywords.push("WHERE");
if (deleteInfo?.afterTarget) keywords.push("WHERE");
+ // `AS OF SYSTEM TIME` 只能跟在 FROM 之后;用户输入 `AS O` 时只替换 `O`,
+ // 因此补全 `OF SYSTEM TIME`,避免重复插入 `AS`。
+ if (isCockroachDbDriverProfile(driverProfile) && /\bas$/i.test(beforeToken.trimEnd()) && /\bfrom\b/i.test(beforeToken)) keywords.push("OF SYSTEM TIME");
return keywords;
}
@@ -6323,13 +6334,14 @@ function buildSnippetItems(prefix: string, snippets: SqlSnippet[], keywordCase?:
});
}
-function activeFunctionSignatures(databaseType?: DatabaseType): Map<string, string[]> {
+function activeFunctionSignatures(databaseType?: DatabaseType, driverProfile?: string): Map<string, string[]> {
const commonFunctionNames = databaseType === "cloudflare-d1" ? CLOUDFLARE_D1_COMMON_FUNCTION_NAMES : COMMON_SQL_FUNCTION_NAMES;
const signatures = databaseType ? new Map(Array.from(SQL_FUNCTION_SIGNATURES.entries()).filter(([name]) => commonFunctionNames.has(name))) : new Map(SQL_FUNCTION_SIGNATURES);
const databaseSignatures = databaseType ? DATABASE_FUNCTION_SIGNATURES[databaseType] : undefined;
if (databaseSignatures) {
for (const [name, parameters] of databaseSignatures) signatures.set(name, parameters);
}
+ for (const [name, parameters] of driverProfileFunctionSignatures(driverProfile)) signatures.set(name, parameters);
return signatures;
}
@@ -6382,11 +6394,11 @@ function buildClickHouseFunctionItems(prefix: string, omitOpeningParen: boolean,
});
}
-function buildFunctionSnippetItems(prefix: string, functionDescriptions: Map<string, string>, databaseType?: DatabaseType, omitOpeningParen = false, keywordCase?: SqlKeywordCase, functionCase?: SqlKeywordCase, includeParams = true): SqlCompletionItem[] {
+function buildFunctionSnippetItems(prefix: string, functionDescriptions: Map<string, string>, databaseType?: DatabaseType, omitOpeningParen = false, keywordCase?: SqlKeywordCase, functionCase?: SqlKeywordCase, includeParams = true, driverProfile?: string): SqlCompletionItem[] {
if (databaseType === "clickhouse") return buildClickHouseFunctionItems(prefix, omitOpeningParen, undefined, includeParams);
const items: SqlCompletionItem[] = [];
- for (const [name, parameters] of activeFunctionSignatures(databaseType).entries()) {
+ for (const [name, parameters] of activeFunctionSignatures(databaseType, driverProfile).entries()) {
if (!matchesPrefix(name, prefix)) continue;
const functionName = applySqlFunctionCase(name, functionCase);
const paramStr = parameters.length > 0 ? parameters.map((p) => `\${${applyGeneratedSqlTemplateKeywordCase(p, keywordCase)}}`).join(", ") : "";
@@ -6509,10 +6521,11 @@ function buildNonAggregatedColumnItems(context: SqlCompletionContext, columnsByT
return items;
}
-function activeSqlKeywords(databaseType?: DatabaseType): string[] {
+function activeSqlKeywords(databaseType?: DatabaseType, driverProfile?: string): string[] {
if (databaseType === "mongodb") return [];
const databaseKeywords = databaseType ? DATABASE_SQL_KEYWORDS[databaseType] : undefined;
- const keywords = databaseType ? Array.from(new Set([...COMMON_SQL_KEYWORDS, ...(databaseKeywords ?? [])])) : Array.from(new Set(SQL_KEYWORDS));
+ const profileKeywords = driverProfileSqlKeywords(driverProfile);
+ const keywords = databaseType ? Array.from(new Set([...COMMON_SQL_KEYWORDS, ...(databaseKeywords ?? []), ...profileKeywords])) : Array.from(new Set([...SQL_KEYWORDS, ...profileKeywords]));
return isOracleLikeDatabase(databaseType) ? keywords.filter((keyword) => !NON_ORACLE_COMPLETION_WORDS.has(keyword)) : keywords;
}
@@ -6548,12 +6561,12 @@ function isPendingJoinKeywordContext(context: SqlCompletionContext): boolean {
return !context.prefix && context.preferredKeywords.includes("JOIN") && !!context.tableTriggerWord && JOIN_MODIFIERS.has(context.tableTriggerWord);
}
-function buildKeywordItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType, keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
+function buildKeywordItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType, keywordCase?: SqlKeywordCase, driverProfile?: string): SqlCompletionItem[] {
const isDml = context.statementKind === "select" || context.statementKind === "insert" || context.statementKind === "update" || context.statementKind === "delete";
const showDdl = !isDml || context.suggestTables || context.dataTypeContext;
- const functionSignatures = activeFunctionSignatures(databaseType);
+ const functionSignatures = activeFunctionSignatures(databaseType, driverProfile);
- return activeSqlKeywords(databaseType)
+ return activeSqlKeywords(databaseType, driverProfile)
.filter((keyword) => {
if (functionSignatures.has(keyword) && !DATA_TYPE_KEYWORDS.has(keyword) && !DUAL_ROLE_SQL_KEYWORDS.has(keyword)) return false;
if (WINDOW_FUNCTIONS.has(keyword)) return false;
@@ -6581,9 +6594,9 @@ function shouldOfferKeywordPrefixContinuations(context: SqlCompletionContext, pe
return !!context.prefix && !pendingJoinKeyword && !context.qualifier && !context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions;
}
-function buildKeywordPrefixContinuationItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType, keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
+function buildKeywordPrefixContinuationItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType, keywordCase?: SqlKeywordCase, driverProfile?: string): SqlCompletionItem[] {
const normalizedPrefix = prefix.toLowerCase();
- return buildKeywordItems(prefix, context, databaseType, keywordCase).filter((item) => {
+ return buildKeywordItems(prefix, context, databaseType, keywordCase, driverProfile).filter((item) => {
const normalizedLabel = item.label.toLowerCase();
return (normalizedLabel.length > normalizedPrefix.length && normalizedLabel.startsWith(normalizedPrefix)) || (normalizedLabel === normalizedPrefix && item.label !== prefix);
});
diff --git a/apps/desktop/src/lib/sql/sqlCompletionAnalysis.ts b/apps/desktop/src/lib/sql/sqlCompletionAnalysis.ts
index 1377450212..27f968cb82 100644
--- a/apps/desktop/src/lib/sql/sqlCompletionAnalysis.ts
+++ b/apps/desktop/src/lib/sql/sqlCompletionAnalysis.ts
@@ -80,6 +80,7 @@ export function analyzeSqlCompletion(request: SqlCompletionAnalysisRequest, edit
const options = {
databaseType: request.databaseType,
dialect: request.dialect,
+ driverProfile: request.driverProfile,
editorState,
};
const legacyContext = getSqlCompletionContext(request.sql, request.cursor, options);