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): complete SHOW and scope keywords by dialect (#13269)

Pius-x9d972232ae71
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts
index 61db2706b8..79564fe20b 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.cockroachdb.spec.ts
@@ -78,6 +78,48 @@ describe("CockroachDB SQL completion (#13078)", () => {
expect(labelsFor("SELECT a FROM t GROUP BY ROLL")).toContain("ROLLUP");
});
+ it("offers SHOW and CRDB-specific SHOW clauses", () => {
+ expect(labelsFor("SHO")).toContain("SHOW");
+ expect(labelsFor("SHO", null)).toContain("SHOW");
+ expect(labelsFor("SHOW R")).toEqual(expect.arrayContaining(["RANGES", "REGIONS", "ROLES"]));
+ expect(labelsFor("SHOW J")).toContain("JOBS");
+ expect(labelsFor("SHOW Z")).toContain("ZONE CONFIGURATIONS");
+ });
+
+ it("prefers FROM after SHOW TABLES and object types after SHOW CREATE", () => {
+ expect(labelsFor("SHOW TABLES ")[0]).toBe("FROM");
+ expect(labelsFor("SHOW COLUMNS ")[0]).toBe("FROM");
+ expect(labelsFor("SHOW CREATE ")[0]).toBe("TABLE");
+ expect(labelsFor("SHOW CREATE V")[0]).toBe("VIEW");
+ });
+
+ it("offers common SQL keywords that were missing from the shared tables", () => {
+ expect(labelsFor("CREATE TEMP")).toEqual(expect.arrayContaining(["TEMP", "TEMPORARY"]));
+ expect(labelsFor("START TRANS")).toContain("TRANSACTION");
+ expect(labelsFor("CREATE SEQ")).toContain("SEQUENCE");
+ expect(labelsFor("DROP TABLE t CASC")).toContain("CASCADE");
+ expect(labelsFor("NULLS F")).toContain("FIRST");
+ expect(labelsFor("SHOW STAT")).toContain("STATISTICS");
+ });
+
+ it("keeps PG-only keywords out of MySQL connections", () => {
+ const mysql = (sql: string) => buildSqlCompletionItems(sql, sql.length, { databaseType: "mysql", tables: [], columnsByTable: new Map() }).map((item) => item.label);
+
+ expect(labelsFor("CREATE SEQ")).toContain("SEQUENCE");
+ expect(mysql("CREATE SEQ")).not.toContain("SEQUENCE");
+ expect(mysql("CREATE TEM")).toEqual(expect.arrayContaining(["TEMPORARY"]));
+ });
+
+ it.each(["STRING", "BYTES"])("preserves Spanner %s type completion without a CRDB profile", (type) => {
+ const sql = `CREATE TABLE t (value ${type.slice(0, 3)}`;
+ const items = buildSqlCompletionItems(sql, sql.length, {
+ databaseType: "spanner",
+ tables: [],
+ columnsByTable: new Map(),
+ });
+ expect(items.find((item) => item.label === type)?.detail).toBe("data type");
+ });
+
it("returns signature help for CRDB functions", () => {
const sql = "SELECT with_max_staleness(";
const help = getSqlFunctionSignatureHelp(sql, sql.length, "postgres", "cockroachdb");
diff --git a/apps/desktop/src/lib/database/cockroachdbProfile.ts b/apps/desktop/src/lib/database/cockroachdbProfile.ts
index fbff6a80de..d9a8af577b 100644
--- a/apps/desktop/src/lib/database/cockroachdbProfile.ts
+++ b/apps/desktop/src/lib/database/cockroachdbProfile.ts
@@ -1,4 +1,4 @@
-import type { DriverProfileExtensionDefinition } from "@/lib/database/driverProfileExtensions";
+import type { DriverProfileExtensionDefinition, DriverProfileKeywordContext } from "@/lib/database/driverProfileExtensions";
export const COCKROACHDB_DRIVER_PROFILE = "cockroachdb";
@@ -41,41 +41,11 @@ export const COCKROACHDB_SQL_KEYWORDS = [
"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",
@@ -83,10 +53,6 @@ export const COCKROACHDB_SQL_KEYWORDS = [
"UNSPLIT AT",
"EXPERIMENTAL_AUDIT",
"UPSERT",
- "PARTIAL",
- "MINVALUE",
- "MAXVALUE",
- "CYCLE",
// 备份、流、运维
"BACKUP",
"RESTORE",
@@ -114,7 +80,6 @@ export const COCKROACHDB_SQL_KEYWORDS = [
"ISERROR",
"ANNOTATE_TYPE",
"EXTRACT_DURATION",
- "GROUPING",
"TREAT",
"EXPERIMENTAL",
];
@@ -205,9 +170,71 @@ export function isCockroachDbDriverProfile(driverProfile?: string): boolean {
return driverProfile?.trim().toLowerCase() === COCKROACHDB_DRIVER_PROFILE;
}
+/**
+ * `SHOW` 后的常用子句。CRDB 的 SHOW 语句覆盖面比 PostgreSQL 大得多,
+ * 这些子句只在 `SHOW ` 之后作为高优先候选出现,不放进通用关键字表。
+ */
+export const COCKROACHDB_SHOW_CLAUSES = [
+ "ALL",
+ "CHANGEFEED JOBS",
+ "CLUSTER SETTING",
+ "COLUMNS",
+ "CONSTRAINTS",
+ "CREATE",
+ "DATABASES",
+ "FUNCTIONS",
+ "GRANTS",
+ "INDEXES",
+ "JOBS",
+ "LOCKS",
+ "PARTITIONS",
+ "PROCEDURES",
+ "QUERIES",
+ "RANGES",
+ "REGIONS",
+ "ROLES",
+ "SCHEDULES",
+ "SCHEMAS",
+ "SEQUENCES",
+ "SESSIONS",
+ "STATISTICS",
+ "TABLES",
+ "TENANTS",
+ "TRIGGERS",
+ "TYPES",
+ "USERS",
+ "ZONE CONFIGURATIONS",
+];
+
+/**
+ * `SHOW CREATE` 之后的对象类型。CRDB 支持比 PostgreSQL 更多的对象类型,
+ * 这些词本身在关键字池里也有,这里只用于在 `SHOW CREATE ` 后提高排序。
+ */
+export const COCKROACHDB_SHOW_CREATE_OBJECTS = ["TABLE", "VIEW", "DATABASE", "INDEX", "SCHEMA", "SEQUENCE", "FUNCTION", "TYPE"];
+
+/** CRDB 专有数据类型,只在 CRDB 连接的 DDL 列类型位置标为 "data type" 并提升排序。 */
+export const COCKROACHDB_DATA_TYPES = ["STRING", "BYTES", "VECTOR", "BOX2D"];
+
+function cockroachDbContextKeywords(context: DriverProfileKeywordContext): string[] {
+ const trimmedBeforeToken = context.beforeToken.trimEnd();
+ const keywords: string[] = [];
+ // `AS OF SYSTEM TIME` 只能跟在 FROM 之后;用户输入 `AS O` 时只替换 `O`,
+ // 因此补全 `OF SYSTEM TIME`,避免重复插入 `AS`。
+ if (/\bas$/i.test(trimmedBeforeToken) && /\bfrom\b/i.test(context.beforeToken)) keywords.push("OF SYSTEM TIME");
+ // CRDB 的 SHOW 子句远多于 PostgreSQL,在 `SHOW ` 之后给出上下文相关的子句。
+ if (/\bshow$/i.test(trimmedBeforeToken)) keywords.push(...COCKROACHDB_SHOW_CLAUSES);
+ // `SHOW CREATE ` 后优先给出对象类型,而不是 create table 这类语句片段。
+ if (/\bshow\s+create$/i.test(trimmedBeforeToken)) keywords.push(...COCKROACHDB_SHOW_CREATE_OBJECTS);
+ // `SHOW TABLES/COLUMNS/INDEXES/CONSTRAINTS` 之后只允许 FROM,这里把它提前。
+ if (/\bshow\s+(?:tables|columns|indexes|constraints)$/i.test(trimmedBeforeToken)) keywords.push("FROM");
+ return keywords;
+}
+
export const COCKROACHDB_DRIVER_PROFILE_EXTENSION: DriverProfileExtensionDefinition = {
id: COCKROACHDB_DRIVER_PROFILE,
sqlKeywords: () => COCKROACHDB_SQL_KEYWORDS,
functionSignatures: () => COCKROACHDB_FUNCTION_SIGNATURES,
+ completionContextKeywords: cockroachDbContextKeywords,
+ completionDataTypes: () => COCKROACHDB_DATA_TYPES,
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 7013f4aba3..e2bff74367 100644
--- a/apps/desktop/src/lib/database/driverProfileExtensions.ts
+++ b/apps/desktop/src/lib/database/driverProfileExtensions.ts
@@ -1,7 +1,7 @@
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";
+import type { ConnectionConfig, DatabaseType, QueryTab, TableNameFilter, TreeNodeType } from "@/types/database";
export type DriverProfileObjectTreeProfile = {
cacheKey: string;
@@ -23,6 +23,13 @@ export type DriverProfileSqlCompletionContext = {
export type DriverProfileCompletionTableMetadata = Pick<SqlCompletionTable, "detail" | "boost">;
+/** Cursor context passed to profile-specific contextual keyword hooks. */
+export type DriverProfileKeywordContext = {
+ beforeCursor: string;
+ beforeToken: string;
+ databaseType?: DatabaseType;
+};
+
export type DriverProfileWorkspaceTarget = {
database: string;
branch?: string;
@@ -53,6 +60,10 @@ export type DriverProfileExtensionDefinition = {
sqlKeywords?: () => readonly string[];
/** 叠加到方言函数表上,用于 profile 专有函数。 */
functionSignatures?: () => Map<string, string[]>;
+ /** 上下文相关的优先关键字(例如 CRDB 的 AS OF SYSTEM TIME 续写)。 */
+ completionContextKeywords?: (context: DriverProfileKeywordContext) => readonly string[];
+ /** profile 专有的数据类型关键字,追加到 DATA_TYPE_KEYWORDS。 */
+ completionDataTypes?: () => readonly string[];
routineSignatures?: () => Map<string, string[]>;
databaseWorkspace?: DriverProfileDatabaseWorkspace;
};
@@ -99,6 +110,14 @@ export function driverProfileFunctionSignatures(driverProfile?: string): Map<str
return driverProfileExtension(driverProfile)?.functionSignatures?.() ?? new Map();
}
+export function driverProfileContextKeywords(driverProfile: string | undefined, context: DriverProfileKeywordContext): readonly string[] {
+ return driverProfileExtension(driverProfile)?.completionContextKeywords?.(context) ?? [];
+}
+
+export function driverProfileDataTypes(driverProfile?: string): readonly string[] {
+ return driverProfileExtension(driverProfile)?.completionDataTypes?.() ?? [];
+}
+
export function driverProfileRoutineSignatures(driverProfile?: string): Map<string, string[]> {
return driverProfileExtension(driverProfile)?.routineSignatures?.() ?? new Map();
}
diff --git a/apps/desktop/src/lib/sql/sqlCompletion.ts b/apps/desktop/src/lib/sql/sqlCompletion.ts
index 1fbe755cb5..2f49cc4e3c 100644
--- a/apps/desktop/src/lib/sql/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sql/sqlCompletion.ts
@@ -18,8 +18,16 @@ import { requiresClickhouseIdentifierQuote, requiresMysqlIdentifierQuote, requir
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, driverProfileFunctionSignatures, driverProfileRoutineSignatures, driverProfileSqlKeywords } from "@/lib/database/driverProfileExtensions";
-import { isCockroachDbDriverProfile } from "@/lib/database/cockroachdbProfile";
+import {
+ driverProfileCompletionObjects,
+ driverProfileCompletionTableMetadata,
+ driverProfileCompletionTables,
+ driverProfileContextKeywords,
+ driverProfileDataTypes,
+ driverProfileFunctionSignatures,
+ driverProfileRoutineSignatures,
+ driverProfileSqlKeywords,
+} from "@/lib/database/driverProfileExtensions";
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";
@@ -376,6 +384,53 @@ const COMMON_SQL_KEYWORDS = [
"BEGIN",
"COMMIT",
"ROLLBACK",
+ "TRANSACTION",
+ "START",
+ "TEMPORARY",
+ "SCHEMA",
+ "RENAME",
+ "CASCADE",
+ "RESTRICT",
+ "RETURNS",
+ "LANGUAGE",
+ "REVOKE",
+ "ROLE",
+ "COLLATE",
+ "FIRST",
+ "LAST",
+ "ROWS",
+ "LEVEL",
+ "DO",
+ "VARYING",
+ "NULLS",
+ "FETCH",
+ "ONLY",
+ "ROLLUP",
+ "CUBE",
+ "UNBOUNDED",
+ "PRECEDING",
+ "FOLLOWING",
+ "SAVEPOINT",
+ "RELEASE",
+ "PREPARE",
+ "EXECUTE",
+ "DEALLOCATE",
+ "ISOLATION",
+ "SERIALIZABLE",
+ "REPEATABLE",
+ "READ",
+ "COMMITTED",
+ "UNCOMMITTED",
+ "CALL",
+ "PROCEDURE",
+ "FUNCTION",
+ "TRIGGER",
+ "TYPE",
+ "ENUM",
+ "ALWAYS",
+ "PARTIAL",
+ "MAXVALUE",
+ "GROUPING",
"TRUNCATE",
"EXPLAIN",
"ANALYZE",
@@ -409,6 +464,17 @@ const COMMON_SQL_KEYWORDS = [
];
const POSTGRES_SQL_KEYWORDS = [
+ "SHOW",
+ "TEMP",
+ "SEQUENCE",
+ "INCREMENT",
+ "MINVALUE",
+ "CYCLE",
+ "OVERLAPS",
+ "INCLUDE",
+ "PUBLIC",
+ "WITHIN",
+ "WITHIN GROUP",
"COMMENT",
"BIGSERIAL",
"JSON",
@@ -1019,10 +1085,10 @@ const DATA_TYPE_KEYWORDS = new Set([
"JSON",
"JSONB",
"UUID",
+ // Spanner and CockroachDB share these types. This set only classifies
+ // candidates; the active dialect's keyword table controls availability.
"STRING",
"BYTES",
- "VECTOR",
- "BOX2D",
"SERIAL",
"BIGSERIAL",
"SMALLSERIAL",
@@ -3720,9 +3786,7 @@ 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");
+ keywords.push(...driverProfileContextKeywords(driverProfile, { beforeCursor, beforeToken, databaseType }));
return keywords;
}
@@ -6753,19 +6817,21 @@ function buildKeywordItems(prefix: string, context: SqlCompletionContext, databa
// true there only reflects the `=` the predicate already used.
const clauseKeywordExpected = !!prefix && !context.suggestTables && (!!context.afterTableReference || !!context.afterJoinCondition);
const normalizedPrefix = prefix.toLowerCase();
+ const profileDataTypes = driverProfileDataTypes(driverProfile);
+ const dataTypeKeywords = profileDataTypes.length > 0 ? new Set([...DATA_TYPE_KEYWORDS, ...profileDataTypes]) : DATA_TYPE_KEYWORDS;
return activeSqlKeywords(databaseType, driverProfile)
.filter((keyword) => {
- if (functionSignatures.has(keyword) && !DATA_TYPE_KEYWORDS.has(keyword) && !DUAL_ROLE_SQL_KEYWORDS.has(keyword)) return false;
+ if (functionSignatures.has(keyword) && !dataTypeKeywords.has(keyword) && !DUAL_ROLE_SQL_KEYWORDS.has(keyword)) return false;
if (WINDOW_FUNCTIONS.has(keyword)) return false;
if (!matchesPrefix(keyword, prefix)) return false;
- if (!showDdl && isDml && (DDL_ONLY_KEYWORDS.has(keyword) || DATA_TYPE_KEYWORDS.has(keyword))) return false;
+ if (!showDdl && isDml && (DDL_ONLY_KEYWORDS.has(keyword) || dataTypeKeywords.has(keyword))) return false;
if (context.followingKeyword && keyword.includes(" ") && keyword.toUpperCase().endsWith(` ${context.followingKeyword}`)) return false;
return true;
})
.map((keyword) => {
const base = computeBoost(keyword, prefix);
- const isDataType = DATA_TYPE_KEYWORDS.has(keyword);
+ const isDataType = dataTypeKeywords.has(keyword);
const freqBoost = !context.dataTypeContext && HIGH_FREQUENCY_KEYWORDS.has(keyword) ? 100 : 0;
const typeBoost = context.dataTypeContext && isDataType ? 2500 : 0;
const followingBoost = context.followingKeyword && isPairPrefixKeywordForFollowing(keyword, context.followingKeyword) ? 1300 : 0;