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。

fix(editor): avoid quadratic completion scans on long SQL

Acd-kk618ff2e115ba
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.performance.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.performance.spec.ts
index d206ce499f..6af8a63632 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.performance.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.performance.spec.ts
@@ -3,6 +3,7 @@ import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { getSqlCompletionContext } from "@/lib/sql/sqlCompletion";
+import { SqlCompletionAnalysisEngine } from "@/lib/sql/sqlCompletionAnalysis";
describe("SQL completion statement-local scanning", () => {
it.each(["\n", " "])("does not split unrelated statements separated by %j before the active syntax-tree window", (separator) => {
@@ -41,3 +42,35 @@ describe("SQL completion statement-local scanning", () => {
expect(context.referencedTables.map((table) => table.name)).toEqual(["current_table"]);
});
});
+
+describe("SQL completion with long string literals", () => {
+ it.each(["before semicolon", "after semicolon", "inside literal"] as const)("keeps completion responsive %s", (position) => {
+ const hex = "3c3f786d6c".repeat(20_000);
+ const document = `UPDATE app.documents\nSET data = decode('${hex}', 'hex')\nWHERE id = 1\nRETURNING name;`;
+ const cursor = position === "before semicolon" ? document.length - 1 : position === "after semicolon" ? document.length : document.indexOf(hex) + hex.length / 2;
+ const engine = new SqlCompletionAnalysisEngine();
+ const start = performance.now();
+ const result = engine.analyze({ sql: document, cursor, databaseType: "postgres", dialect: "postgres", semanticCompletionEnabled: true });
+ const elapsed = performance.now() - start;
+
+ expect(result.suppressed).toBe(position === "inside literal");
+ if (position !== "inside literal") {
+ expect(result.completionContext.prefix).toBe(position === "before semicolon" ? "name" : "");
+ }
+ // Leave ample CI headroom while catching quadratic scans over the 200 KB literal.
+ expect(elapsed).toBeLessThan(1_000);
+ });
+
+ it.each([
+ { sql: "SELECT 中文_name", databaseType: "postgres" as const, prefix: "中文_name" },
+ { sql: "SELECT 𐐀name", databaseType: "postgres" as const, prefix: "𐐀name" },
+ { sql: "SELECT @customer_", databaseType: "sqlserver" as const, prefix: "@customer_" },
+ { sql: "SELECT t.customer_", databaseType: "postgres" as const, prefix: "customer_", qualifier: "t" },
+ { sql: 'SELECT "Mixed.Schema"."Name"', databaseType: "postgres" as const, prefix: "Name", qualifier: "Mixed.Schema" },
+ { sql: "SELECT `column_name`", databaseType: "mysql" as const, prefix: "column_name" },
+ ])("preserves the identifier suffix in $sql", ({ sql: document, databaseType, prefix, qualifier }) => {
+ const context = getSqlCompletionContext(document, document.length, { databaseType });
+ expect(context.prefix).toBe(prefix);
+ expect(context.qualifier).toBe(qualifier);
+ });
+});
diff --git a/apps/desktop/src/lib/sql/sqlCompletion.ts b/apps/desktop/src/lib/sql/sqlCompletion.ts
index 73591b9043..04a8b8aa10 100644
--- a/apps/desktop/src/lib/sql/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sql/sqlCompletion.ts
@@ -2850,7 +2850,7 @@ function isCallRoutineContext(beforeToken: string): boolean {
}
const SQL_IDENTIFIER_START_CHAR = /[@_\p{ID_Start}]/u;
-const SQL_IDENTIFIER_SUFFIX = /[$@_\u200c\u200d\p{ID_Continue}]+$/u;
+const SQL_IDENTIFIER_SUFFIX_CHAR = /^[$@_\u200c\u200d\p{ID_Continue}]$/u;
const SQL_IDENTIFIER_CONTINUE_CHAR = /[$_\u200c\u200d\p{ID_Continue}]/u;
function hasTableAliasAfterCursor(sql: string, cursor: number): boolean {
@@ -2927,7 +2927,12 @@ export function getSqlCompletionContext(sql: string, cursor: number, options: Sq
const qualifierParts = trailingIdentifier?.qualifierParts;
const bareStart = trailingIdentifier?.start ?? beforeCursor.length;
const beforeToken = beforeCursor.slice(0, Math.max(0, bareStart)).trimEnd();
- const lastWord = /([A-Za-z_][\w$]*)$/.exec(beforeToken)?.[1]?.toLowerCase() ?? "";
+ let lastWordStart = beforeToken.length;
+ while (lastWordStart > 0 && /[\w$]/.test(beforeToken[lastWordStart - 1] ?? "")) {
+ lastWordStart -= 1;
+ }
+
+ const lastWord = /([A-Za-z_][\w$]*)$/.exec(beforeToken.slice(lastWordStart))?.[1]?.toLowerCase() ?? "";
// CTE bodies are their own scope: resolve them first so the outer query's
// referenced tables are read from a statement with those bodies blanked out.
@@ -3392,12 +3397,26 @@ function parseTrailingIdentifierPart(input: string, endExclusive: number): { sta
return null;
}
- const match = SQL_IDENTIFIER_SUFFIX.exec(input.slice(0, endExclusive));
- if (!match) return null;
- const raw = match[0];
+ let start = endExclusive;
+
+ while (start > 0) {
+ let previous = start - 1;
+ const low = input.charCodeAt(previous);
+ if (previous > 0 && low >= 0xdc00 && low <= 0xdfff) {
+ const high = input.charCodeAt(previous - 1);
+ if (high >= 0xd800 && high <= 0xdbff) previous--;
+ }
+ if (!SQL_IDENTIFIER_SUFFIX_CHAR.test(input.slice(previous, start))) break;
+ start = previous;
+ }
+ if (start === endExclusive) return null;
+ const raw = input.slice(start, endExclusive);
const firstCodePoint = raw.codePointAt(0);
- if (firstCodePoint === undefined || !SQL_IDENTIFIER_START_CHAR.test(String.fromCodePoint(firstCodePoint))) return null;
- return { start: match.index, raw };
+ if (firstCodePoint === undefined || !SQL_IDENTIFIER_START_CHAR.test(String.fromCodePoint(firstCodePoint))) {
+ return null;
+ }
+
+ return { start, raw };
}
/**