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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(editor): support qualified table navigation
大峰9083dc0e5337
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vueindex 14f8ed9401..93ee614c4f 100644--- a/apps/desktop/src/components/editor/QueryEditor.vue+++ b/apps/desktop/src/components/editor/QueryEditor.vue@@ -31,7 +31,7 @@ import {} from "@/lib/sqlCompletion";import { buildElasticsearchCompletionItemsFromContext, getElasticsearchCompletionContext, getElasticsearchCompletionResultValidFor, shouldAutoOpenElasticsearchCompletion, type ElasticsearchCompletionItem } from "@/lib/elasticsearchCompletion";import { buildMongoCompletionItemsFromContext, getMongoCompletionContext, getMongoCompletionResultValidFor, shouldAutoOpenMongoCompletion, type MongoCompletionItem } from "@/lib/mongoCompletion";-import { extractIdentifierAt, isSqlKeyword, matchTable } from "@/lib/sqlNavigation";+import { extractIdentifierAt, isSqlKeyword, matchTable, splitQualifiedIdentifier } from "@/lib/sqlNavigation";import { lineColumnToOffset, parseSqlErrorLocation } from "@/lib/sqlDiagnostics";import {DBX_TABLE_REFERENCE_MIME,@@ -2432,11 +2432,15 @@ onMounted(async () => {event.preventDefault();setTimeout(async () => {try {+ const identifierParts = splitQualifiedIdentifier(identifier);+ const tableLookupFilter = identifierParts[identifierParts.length - 1] ?? identifier;+// Ensure table cache is populatedif (cachedTables.length === 0) {+ // Some metadata providers only accept table-name masks, not schema.table masks.cachedTables = usesLocalOnlyCompletionMetadata()- ? connectionStore.lookupLocalCompletionTables(props.connectionId!, props.database!, identifier, MAX_COMPLETION_TABLES, props.schema)- : await connectionStore.listCompletionTables(props.connectionId!, props.database!, identifier, MAX_COMPLETION_TABLES, props.schema);+ ? connectionStore.lookupLocalCompletionTables(props.connectionId!, props.database!, tableLookupFilter, MAX_COMPLETION_TABLES, props.schema)+ : await connectionStore.listCompletionTables(props.connectionId!, props.database!, tableLookupFilter, MAX_COMPLETION_TABLES, props.schema);}// 1. Check if it's a table name@@ -2459,20 +2463,14 @@ onMounted(async () => {});// Check if identifier has a qualifier (e.g., c.card_name or schema.table)- const qualifierMatch = /^(.+)\.(.+)$/.exec(identifier);- const qualifier = qualifierMatch ? qualifierMatch[1] : null;-- // 2b. Qualified identifier (schema.table): check against SQL-parsed referenced tables- if (qualifierMatch) {- const qQualifier = qualifierMatch[1].toLowerCase();- const qTableName = qualifierMatch[2].toLowerCase();- const matchedRef = referencedTables.find((rt) => rt.name.toLowerCase() === qTableName && rt.schema?.toLowerCase() === qQualifier);- if (matchedRef) {- emit("clickTable", matchedRef.schema ? `${matchedRef.schema}.${matchedRef.name}` : matchedRef.name);- return;- }+ const qualifier = identifierParts.length >= 2 ? identifierParts[identifierParts.length - 2] : null;++ const matchedRef = matchTable(identifier, referencedTables);+ if (matchedRef) {+ emit("clickTable", matchedRef.schema ? `${matchedRef.schema}.${matchedRef.name}` : matchedRef.name);+ return;}- const colName = qualifierMatch ? qualifierMatch[2] : identifier;+ const colName = identifierParts[identifierParts.length - 1] ?? identifier;const colLower = colName.toLowerCase();if (referencedTables.length === 0) {diff --git a/apps/desktop/src/lib/__tests__/sqlNavigation.spec.ts b/apps/desktop/src/lib/__tests__/sqlNavigation.spec.tsindex 0af09dccf8..2a3b3e9ecb 100644--- a/apps/desktop/src/lib/__tests__/sqlNavigation.spec.ts+++ b/apps/desktop/src/lib/__tests__/sqlNavigation.spec.ts@@ -1,5 +1,33 @@import { describe, expect, it } from "vitest";-import { matchTable } from "@/lib/sqlNavigation";+import { extractIdentifierAt, matchTable, splitQualifiedIdentifier } from "@/lib/sqlNavigation";++describe("extractIdentifierAt", () => {+ it("extracts unquoted qualified identifiers", () => {+ const sql = "select * from MAAC00.Accounts";++ expect(extractIdentifierAt(sql, sql.indexOf("Accounts"))).toBe("MAAC00.Accounts");+ });++ it("extracts backtick-quoted qualified identifiers", () => {+ const sql = "select * from `MAAC00`.Accounts";++ expect(extractIdentifierAt(sql, sql.indexOf("Accounts"))).toBe("MAAC00.Accounts");+ expect(extractIdentifierAt(sql, sql.indexOf("MAAC00"))).toBe("MAAC00.Accounts");+ });++ it("extracts double-quoted qualified identifiers", () => {+ const sql = 'select * from "MAAC00"."Accounts"';++ expect(extractIdentifierAt(sql, sql.indexOf("Accounts"))).toBe("MAAC00.Accounts");+ });+});++describe("splitQualifiedIdentifier", () => {+ it("splits quoted and multi-part identifiers", () => {+ expect(splitQualifiedIdentifier('catalog."MAAC00".Accounts')).toEqual(["catalog", "MAAC00", "Accounts"]);+ expect(splitQualifiedIdentifier("`MAAC00`.Accounts")).toEqual(["MAAC00", "Accounts"]);+ });+});describe("matchTable", () => {it("matches schema-qualified table identifiers", () => {@@ -8,6 +36,18 @@ describe("matchTable", () => {expect(matchTable("maac00.accounts", [table])).toBe(table);});+ it("matches catalog.schema.table identifiers against schema-scoped tables", () => {+ const table = { schema: "MAAC00", name: "Accounts" };++ expect(matchTable("catalog.maac00.accounts", [table])).toBe(table);+ });++ it("matches quoted schema-qualified table identifiers", () => {+ const table = { schema: "MAAC00", name: "Accounts" };++ expect(matchTable("`MAAC00`.Accounts", [table])).toBe(table);+ });+it("does not treat non-schema qualifiers as table matches", () => {expect(matchTable("u.users", [{ schema: "public", name: "users" }])).toBeNull();});diff --git a/apps/desktop/src/lib/sqlNavigation.ts b/apps/desktop/src/lib/sqlNavigation.tsindex 6c2dc9bd9c..6ecf134cd8 100644--- a/apps/desktop/src/lib/sqlNavigation.ts+++ b/apps/desktop/src/lib/sqlNavigation.ts@@ -121,42 +121,92 @@ const SQL_KEYWORDS_SET = new Set(["list_transform",]);-/** Extract identifier at position `pos` in the document. */-export function extractIdentifierAt(doc: string, pos: number): string | null {- if (pos < 0 || pos > doc.length) return null;+type IdentifierPart = { value: string; start: number; end: number };- const char = doc[pos];- const idChar = (c: string) => /^[A-Za-z0-9_]$/.test(c);+function isIdentifierChar(char: string | undefined): boolean {+ return !!char && /^[A-Za-z0-9_$]$/.test(char);+}- // Backtick-quoted: `identifier`- if (char === "`") {- let start = pos;- while (start > 0 && doc[start - 1] === "`") start--;- const end = doc.indexOf("`", start + 1);- if (end < 0) return null;- return doc.slice(start + 1, end);+function readQuotedPart(text: string, start: number): IdentifierPart | null {+ const open = text[start];+ const close = open === "[" ? "]" : open;+ if (open !== "`" && open !== '"' && open !== "[") return null;++ let value = "";+ for (let i = start + 1; i < text.length; i += 1) {+ const char = text[i];+ if (char === close) {+ if (text[i + 1] === close) {+ value += close;+ i += 1;+ continue;+ }+ return { value, start, end: i + 1 };+ }+ value += char;}+ return null;+}- // Double-quoted: "identifier"- if (char === '"') {- let start = pos;- while (start > 0 && doc[start - 1] === '"') start--;- const end = doc.indexOf('"', start + 1);- if (end < 0) return null;- return doc.slice(start + 1, end);+function readUnquotedPart(text: string, start: number): IdentifierPart | null {+ if (!isIdentifierChar(text[start])) return null;+ let end = start + 1;+ while (end < text.length && isIdentifierChar(text[end])) end += 1;+ return { value: text.slice(start, end), start, end };+}++function readIdentifierPart(text: string, start: number): IdentifierPart | null {+ return readQuotedPart(text, start) ?? readUnquotedPart(text, start);+}++function parseQualifiedIdentifier(text: string, start: number): { parts: IdentifierPart[]; start: number; end: number } | null {+ const first = readIdentifierPart(text, start);+ if (!first) return null;++ const parts = [first];+ let end = first.end;+ while (text[end] === ".") {+ const next = readIdentifierPart(text, end + 1);+ if (!next) break;+ parts.push(next);+ end = next.end;}- // Unquoted identifier (may be qualified like schema.table)- if (!idChar(char) && char !== ".") return null;+ return { parts, start, end };+}+function identifierSearchBounds(doc: string, pos: number): { start: number; end: number } {let start = pos;- while (start > 0 && (idChar(doc[start - 1]) || doc[start - 1] === ".")) start--;+ while (start > 0 && doc[start - 1] !== "\n" && doc[start - 1] !== "\r") start -= 1;+let end = pos;- while (end < doc.length && (idChar(doc[end]) || doc[end] === ".")) end++;+ while (end < doc.length && doc[end] !== "\n" && doc[end] !== "\r") end += 1;- const result = doc.slice(start, end);- if (!/[A-Za-z0-9_]/.test(result)) return null;- return result;+ return { start, end };+}++/** Extract identifier at position `pos` in the document. */+export function extractIdentifierAt(doc: string, pos: number): string | null {+ if (pos < 0 || pos > doc.length) return null;++ const clickPos = pos === doc.length ? pos - 1 : pos;+ if (clickPos < 0) return null;++ const bounds = identifierSearchBounds(doc, clickPos);+ let index = bounds.start;+ while (index < bounds.end) {+ const parsed = parseQualifiedIdentifier(doc, index);+ if (parsed) {+ if (clickPos >= parsed.start && clickPos < parsed.end) {+ return parsed.parts.map((part) => part.value).join(".");+ }+ index = Math.max(parsed.end, index + 1);+ continue;+ }+ index += 1;+ }++ return null;}/** Check whether the identifier is a SQL keyword (not a table/column name). */@@ -164,19 +214,27 @@ export function isSqlKeyword(identifier: string): boolean {return SQL_KEYWORDS_SET.has(identifier.toLowerCase());}+export function splitQualifiedIdentifier(identifier: string): string[] {+ const trimmed = identifier.trim();+ if (!trimmed) return [];++ const parsed = parseQualifiedIdentifier(trimmed, 0);+ if (!parsed || parsed.end !== trimmed.length) return [trimmed];+ return parsed.parts.map((part) => part.value);+}+/** Match identifier against known table names (case-insensitive). Supports qualified identifiers like schema.table. */export function matchTable(identifier: string, tables: Array<{ name: string; schema?: string }>): { name: string; schema?: string } | null {- const lower = identifier.toLowerCase();+ const parts = splitQualifiedIdentifier(identifier);+ const normalizedIdentifier = parts.length > 0 ? parts.join(".").toLowerCase() : identifier.toLowerCase();- // Direct match (simple table name)- const direct = tables.find((t) => t.name.toLowerCase() === lower);+ const direct = tables.find((t) => t.name.toLowerCase() === normalizedIdentifier);if (direct) return direct;- // Qualified match: schema.table- const dotIndex = identifier.indexOf(".");- if (dotIndex > 0) {- const qualifier = identifier.substring(0, dotIndex).toLowerCase();- const name = identifier.substring(dotIndex + 1).toLowerCase();+ if (parts.length >= 2) {+ // Use the final two parts so catalog.schema.table still resolves against schema-scoped metadata.+ const qualifier = parts[parts.length - 2].toLowerCase();+ const name = parts[parts.length - 1].toLowerCase();const qualified = tables.find((t) => t.name.toLowerCase() === name && t.schema?.toLowerCase() === qualifier);if (qualified) return qualified;}