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(sql): preserve DBLinks and SQL function templates

Hang169fc05087af
diff --git a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
index 6596809278..169993318a 100644
--- a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
@@ -10,6 +10,7 @@ import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import { createQueryEditorExecutionViewportOwnership } from "@/lib/editor/queryEditorExecutionViewport";
import * as objectMetadataCache from "@/lib/metadata/objectMetadataCache";
import type { ConnectionConfig, QueryTab } from "@/types/database";
+import { formatSqlText } from "@/lib/sql/sqlFormatter";
import type { SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget";
vi.mock("vue-i18n", () => ({
@@ -898,10 +899,12 @@ SELECT @value AS Message;`;
expect(executeCurrentSql).toHaveBeenCalledWith(sql, { tabId: "tab-1" });
});
- it("executes Oracle database-link queries without opening the parameter dialog", async () => {
- const sql = "SELECT 1 FROM DUAL@WDHIS160;";
- const activeTab = ref<QueryTab | undefined>(queryTab("ORCL"));
- const activeConnection = ref<ConnectionConfig | undefined>(connection("oracle"));
+ it.each([
+ { databaseType: "oracle", database: "ORCL", sql: "SELECT 1 FROM DUAL@WDHIS160;" },
+ { databaseType: "dameng", database: "test", sql: "select * from test.table_name@dm1" },
+ ] as const)("executes $databaseType database-link queries without opening the parameter dialog", async ({ databaseType, database, sql }) => {
+ const activeTab = ref<QueryTab | undefined>(queryTab(database));
+ const activeConnection = ref<ConnectionConfig | undefined>(connection(databaseType));
const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
const queryStore = useQueryStore();
const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
@@ -923,6 +926,104 @@ SELECT @value AS Message;`;
expect(executeCurrentSql).toHaveBeenCalledWith(sql, { tabId: "tab-1" });
});
+ it("executes a formatted Dameng DBLink query without a parameter dialog or SQL changes", async () => {
+ const sql = await formatSqlText("select * from test.table_name@dm1", "dameng");
+ expect(sql).toContain("table_name @dm1");
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("test"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection("dameng"));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const executeCurrentSql = vi.spyOn(useQueryStore(), "executeCurrentSql").mockResolvedValue(undefined);
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+ const execution = useSqlExecution({ activeTab: computed(() => activeTab.value), activeConnection: computed(() => activeConnection.value), executableSql: computed(() => sql), activeOutputView });
+
+ await execution.tryExecute();
+
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(execution.sqlParameterNames.value).toEqual([]);
+ expect(executeCurrentSql).toHaveBeenCalledWith(sql, { tabId: "tab-1" });
+ });
+
+ it.each(["", " ", "/* separator */", "-- separator\n"])("preserves a Dameng link separated by %j in the full @set execution flow", async (separator) => {
+ const target = `select * from test.table_name${separator}@dm1 where id=@DM1`;
+ const sql = `@set dm1 = 7;\n${target}`;
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("test"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection("dameng"));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const executeCurrentSql = vi.spyOn(useQueryStore(), "executeCurrentSql").mockResolvedValue(undefined);
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+ const execution = useSqlExecution({ activeTab: computed(() => activeTab.value), activeConnection: computed(() => activeConnection.value), executableSql: computed(() => sql), activeOutputView });
+
+ await execution.tryExecute();
+
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(execution.sqlParameterNames.value).toEqual([]);
+ expect(executeCurrentSql).toHaveBeenCalledWith(`select * from test.table_name${separator}@dm1 where id=7`, { tabId: "tab-1" });
+ });
+
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("executes %s XML templates without treating CONTENT as a linked object", async (databaseType) => {
+ const sql = "@set value = XMLTYPE('<a/>');\nSELECT XMLSERIALIZE(CONTENT @value AS CLOB) FROM DUAL";
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("test"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection(databaseType));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const executeCurrentSql = vi.spyOn(useQueryStore(), "executeCurrentSql").mockResolvedValue(undefined);
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+ const execution = useSqlExecution({ activeTab: computed(() => activeTab.value), activeConnection: computed(() => activeConnection.value), executableSql: computed(() => sql), activeOutputView });
+
+ await execution.tryExecute();
+
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(execution.sqlParameterNames.value).toEqual([]);
+ expect(executeCurrentSql).toHaveBeenCalledWith("SELECT XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB) FROM DUAL", { tabId: "tab-1" });
+ });
+
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("expands %s SQL/XML function names before execution", async (databaseType) => {
+ const selectedSql = "SELECT XMLSERIALIZE(CONTENT @fn('<a/>') AS CLOB) FROM DUAL";
+ const sql = `@set fn = XMLTYPE;\n${selectedSql}`;
+ const selectionFrom = sql.indexOf("SELECT");
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("test"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection(databaseType));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const executeCurrentSql = vi.spyOn(useQueryStore(), "executeCurrentSql").mockResolvedValue(undefined);
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+ const execution = useSqlExecution({ activeTab: computed(() => activeTab.value), activeConnection: computed(() => activeConnection.value), executableSql: computed(() => sql), activeOutputView });
+
+ await execution.tryExecute();
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(executeCurrentSql).toHaveBeenLastCalledWith("SELECT XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB) FROM DUAL", { tabId: "tab-1" });
+
+ await execution.tryExecute({ fullSql: sql, selectedSql, cursorPos: selectionFrom, selectionFrom, selectionTo: sql.length });
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(executeCurrentSql).toHaveBeenCalledTimes(2);
+ expect(executeCurrentSql).toHaveBeenLastCalledWith("SELECT XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB) FROM DUAL", { tabId: "tab-1" });
+ });
+
+ it.each([
+ { databaseType: "oracle", target: "SELECT XMLQUERY('/a' PASSING BY VALUE @fn('<a/>') RETURNING CONTENT) FROM DUAL", value: "XMLTYPE" },
+ { databaseType: "oracle", target: "SELECT XMLTABLE('/a' PASSING @fn('<a/>') COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL", value: "XMLTYPE" },
+ { databaseType: "dameng", target: "SELECT XMLTABLE('/a' PASSING BY VALUE @fn('<a/>') COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL", value: "XMLTYPE" },
+ { databaseType: "oceanbase-oracle", target: "SELECT XMLQUERY('/a' PASSING BY VALUE @fn('<a/>') RETURNING CONTENT) FROM DUAL", value: "XMLTYPE" },
+ { databaseType: "oracle", target: "BEGIN @fn('ok'); END;", value: "DBMS_OUTPUT.PUT_LINE" },
+ { databaseType: "oceanbase-oracle", target: "BEGIN LOOP @fn('ok'); EXIT; END LOOP; END;", value: "DBMS_OUTPUT.PUT_LINE" },
+ ] as const)("executes full and selected $databaseType function templates in $target", async ({ databaseType, target, value }) => {
+ const sql = `@set fn = ${value};\n${target}`;
+ const selectionFrom = sql.indexOf(target);
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("test"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection(databaseType));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const executeCurrentSql = vi.spyOn(useQueryStore(), "executeCurrentSql").mockResolvedValue(undefined);
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+ const execution = useSqlExecution({ activeTab: computed(() => activeTab.value), activeConnection: computed(() => activeConnection.value), executableSql: computed(() => sql), activeOutputView });
+
+ await execution.tryExecute();
+ await execution.tryExecute({ fullSql: sql, selectedSql: target, cursorPos: selectionFrom, selectionFrom, selectionTo: sql.length });
+
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(execution.sqlParameterNames.value).toEqual([]);
+ expect(executeCurrentSql).toHaveBeenCalledTimes(2);
+ expect(executeCurrentSql).toHaveBeenNthCalledWith(1, target.replaceAll("@fn", value), { tabId: "tab-1" });
+ expect(executeCurrentSql).toHaveBeenNthCalledWith(2, target.replaceAll("@fn", value), { tabId: "tab-1" });
+ });
+
it("sends native SET variables without client-side expansion", async () => {
const activeTab = ref<QueryTab | undefined>(queryTab("app"));
const activeConnection = ref<ConnectionConfig | undefined>(connection("mysql"));
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
index cff633f360..d279ea52fa 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
@@ -310,7 +310,13 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters("select @amount/2, @total / 4")).toEqual(["amount", "total"]);
});
- it.each(["oracle", "oceanbase-oracle"] as const)("ignores %s database links while preserving standalone at-sign placeholders", (databaseType) => {
+ it("does not treat the Dameng DBLink in issue #11247 as a parameter", () => {
+ const sql = "select * from test.table_name@dm1";
+ expect(extractSqlParameterDescriptors(sql, { databaseType: "dameng" })).toEqual([]);
+ expect(substituteSqlParameters(sql, { dm1: { kind: "string", value: "WRONG" } }, { databaseType: "dameng" })).toBe(sql);
+ });
+
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("ignores %s database links while preserving standalone at-sign placeholders", (databaseType) => {
const sql = 'SELECT * FROM HR.EMPLOYEES@REMOTE_DB, "AUDIT_LOG"@ARCHIVE_DB WHERE tenant_id = @tenant_id';
expect(extractSqlParameters("SELECT 1 FROM DUAL@WDHIS160;", { databaseType })).toEqual([]);
expect(extractSqlParameters(sql, { databaseType })).toEqual(["tenant_id"]);
@@ -318,7 +324,7 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters("SELECT * FROM EMPLOYEES@REMOTE_DB", { databaseType: "postgres" })).toEqual(["REMOTE_DB"]);
});
- it.each(["oracle", "oceanbase-oracle"] as const)("preserves %s links, quoted names, strings and comments during substitution", (databaseType) => {
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("preserves %s links, quoted names, strings and comments during substitution", (databaseType) => {
const sql = `SELECT '@literal' FROM "Hr"."Audit Log"@ARCHIVE_DB /* @comment */ WHERE "Id" = :id AND tenant_id = @tenant_id -- @tail`;
expect(extractSqlParameters(sql, { databaseType })).toEqual(["id", "tenant_id"]);
expect(
@@ -337,7 +343,7 @@ describe("extractSqlParameters", () => {
).toBe(`SELECT '@literal' FROM "Hr"."Audit Log"@ARCHIVE_DB /* @comment */ WHERE "Id" = 3 AND tenant_id = 7 -- @tail`);
});
- it.each(["oracle", "oceanbase-oracle"] as const)("extracts only real %s parameters around separated database links", (databaseType) => {
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("extracts only real %s parameters around separated database links", (databaseType) => {
const sql = `SELECT @projection FROM SYS.ALL_TABLES @LINK
JOIN "Hr"."Audit Log"/* comment */@ARCHIVE_DB ON 1 = 1
JOIN employees -- comment with /* and @ignored
@@ -346,7 +352,7 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters(sql, { databaseType })).toEqual(["projection", "owner", "tenant_id"]);
});
- describe.each(["oracle", "oceanbase-oracle"] as const)("%s database link separators", (databaseType) => {
+ describe.each(["oracle", "oceanbase-oracle", "dameng"] as const)("%s strict database link contexts", (databaseType) => {
it.each([
["SELECT XMLSERIALIZE(CONTENT @value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')"],
["SELECT XMLSERIALIZE(CONTENT@value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')"],
@@ -360,6 +366,55 @@ describe("extractSqlParameters", () => {
expect(substituteSqlParameters(sql, { value: { kind: "raw", value } }, { databaseType })).toBe(sql.replace("@value", value));
});
+ it.each([
+ ["SELECT XMLSERIALIZE(CONTENT @fn('<a/>') AS CLOB) FROM DUAL", "SELECT XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["SELECT XMLSERIALIZE(DOCUMENT @fn('<a/>') AS CLOB) FROM DUAL", "SELECT XMLSERIALIZE(DOCUMENT XMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["SELECT XMLQUERY('/a' PASSING @fn('<a/>') RETURNING CONTENT) FROM DUAL", "SELECT XMLQUERY('/a' PASSING XMLTYPE('<a/>') RETURNING CONTENT) FROM DUAL"],
+ ["SELECT XMLQUERY(fn_nested('/a') PASSING @fn('<a/>') RETURNING CONTENT) FROM DUAL", "SELECT XMLQUERY(fn_nested('/a') PASSING XMLTYPE('<a/>') RETURNING CONTENT) FROM DUAL"],
+ ["SELECT COALESCE(XMLSERIALIZE(CONTENT @fn('<a/>') AS CLOB), 'empty') FROM DUAL", "SELECT COALESCE(XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB), 'empty') FROM DUAL"],
+ ])("keeps function-name templates after SQL/XML keywords in %s", (sql, expected) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["fn"]);
+ expect(substituteSqlParameters(sql, { fn: { kind: "raw", value: "XMLTYPE" } }, { databaseType })).toBe(expected);
+ });
+
+ it.each([
+ "SELECT XMLQUERY('/a' PASSING BY VALUE @fn('<a/>') RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING @fn('<a/>') COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING BY /* separator */ VALUE @fn('<a/>') COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING BY VALUE @fn('<a/>'), @fn('<b/>') AS b RETURNING CONTENT) FROM DUAL",
+ "SELECT COALESCE(XMLQUERY(fn_nested('/a') PASSING BY VALUE @fn('<a/>') RETURNING CONTENT), NULL) FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING BY VALUE XMLQUERY('/b' PASSING BY VALUE @fn('<a/>') RETURNING CONTENT) RETURNING CONTENT) FROM DUAL",
+ ])("keeps complete SQL/XML PASSING function templates in %s", (sql) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["fn"]);
+ expect(substituteSqlParameters(sql, { fn: { kind: "raw", value: "XMLTYPE" } }, { databaseType })).toBe(sql.replaceAll("@fn", "XMLTYPE"));
+ });
+
+ it.each([
+ "SELECT XMLQUERY('/a' PASSING BY VALUE value@LINK(1) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING passing@LINK(1) COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING BY VALUE HR.value@LINK(1), \"VALUE\"@LINK(1) AS b COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING BY VALUE (value@LINK(1)) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING COALESCE(passing@LINK(1), NULL) RETURNING CONTENT) FROM DUAL",
+ ])("preserves remote routines inside complete SQL/XML PASSING clauses in %s", (sql) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual([]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" } }, { databaseType })).toBe(sql);
+ });
+
+ it.each([
+ "SELECT content@LINK('<a/>'), document@LINK('<a/>'), passing@LINK('<a/>') FROM DUAL",
+ 'SELECT HR.content@LINK(1), "CONTENT"@LINK(1) FROM DUAL',
+ 'SELECT XMLSERIALIZE(CONTENT HR.content@LINK(1) AS CLOB), XMLSERIALIZE(DOCUMENT "DOCUMENT"@LINK(1) AS CLOB) FROM DUAL',
+ "SELECT XMLQUERY('/a' PASSING HR.passing@LINK(1) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLSERIALIZE(CONTENT (content@LINK(1)) AS CLOB) FROM DUAL",
+ "SELECT XMLSERIALIZE(CONTENT content@LINK(1) AS CLOB), XMLSERIALIZE(DOCUMENT document@LINK(1) AS CLOB) FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING passing@LINK(1) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLQUERY(passing@LINK(1)) FROM DUAL",
+ "SELECT XMLQUERY(fn_nested('/a') PASSING passing@LINK(1) RETURNING CONTENT) FROM DUAL",
+ ])("preserves real remote routines named after SQL/XML keywords in %s", (sql) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual([]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" } }, { databaseType })).toBe(sql);
+ });
+
it("preserves remote routine links in expressions and PL/SQL calls", () => {
const sql = "SELECT HR.get_value@LINK(:id) FROM DUAL; BEGIN HR.run_job /* link */ @LINK(:id); END;";
expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
@@ -374,6 +429,19 @@ describe("extractSqlParameters", () => {
}
});
+ it.each(["DELETE FROM @table WHERE id = :id", "INSERT INTO @table VALUES (:id)"])("keeps parameters after reserved keywords in %s", (sql) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["table", "id"]);
+ expect(substituteSqlParameters(sql, { table: { kind: "raw", value: "employees" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe(sql.replace("@table", "employees").replace(":id", "7"));
+ });
+
+ it("preserves remote routine links in comma-separated select lists", () => {
+ const sql = "SELECT ename, HR.get_sal@LINK(empno) FROM emp WHERE id = :id";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT ename, HR.get_sal@LINK(empno) FROM emp WHERE id = 7");
+ });
+ });
+
+ describe.each(["oracle", "oceanbase-oracle"] as const)("%s database link separators", (databaseType) => {
it.each(["", " ", "\t\r\n", "/* comment with -- and @ignored */", " /* first */ \n /* second */ ", "-- comment with /* and @ignored\n"])("preserves database links separated by %j during replacement", (separator) => {
const sql = `SELECT '@literal', @projection FROM "Hr"."Audit Log"${separator}@LINK WHERE id = :id -- @tail`;
expect(
@@ -421,17 +489,6 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters(sql, { databaseType })).toEqual(["value", "source", "target", "column", "offset", "count", "sql", "input"]);
});
- it.each(["DELETE FROM @table WHERE id = :id", "INSERT INTO @table VALUES (:id)"])("keeps parameters after reserved keywords in %s", (sql) => {
- expect(extractSqlParameters(sql, { databaseType })).toEqual(["table", "id"]);
- expect(substituteSqlParameters(sql, { table: { kind: "raw", value: "employees" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe(sql.replace("@table", "employees").replace(":id", "7"));
- });
-
- it("preserves remote routine links in comma-separated select lists", () => {
- const sql = "SELECT ename, HR.get_sal@LINK(empno) FROM emp WHERE id = :id";
- expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
- expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT ename, HR.get_sal@LINK(empno) FROM emp WHERE id = 7");
- });
-
it.each(["HR.NEXT", "HR.OFFSET", "HR.FIRST", "FIRST", "-- comment\nFIRST", "employees, FIRST", "(SELECT id FROM employees) e, FIRST"])("preserves database links on the non-reserved object %s", (objectName) => {
const sql = `SELECT * FROM ${objectName} /* separator */ @LINK WHERE id = :id`;
expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
@@ -479,7 +536,95 @@ describe("extractSqlParameters", () => {
});
});
- it.each(["postgres", "sqlserver", "dameng"] as const)("keeps separated at-sign parameters unchanged for %s", (databaseType) => {
+ it.each([" ", ""])("keeps Dameng THEN%s template calls as real parameters", (separator) => {
+ const sql = `SELECT CASE WHEN 1=1 THEN${separator}@value(1) ELSE 0 END FROM DUAL`;
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["value"]);
+ expect(substituteSqlParameters(sql, { value: { kind: "raw", value: "ABS" } }, { databaseType: "dameng" })).toBe(`SELECT CASE WHEN 1=1 THEN${separator}ABS(1) ELSE 0 END FROM DUAL`);
+ });
+
+ it("preserves a large expression of SQL/XML-keyword-named remote calls", () => {
+ const expression = Array.from({ length: 8000 }, (_, tokenIndex) => `${["content", "document", "passing"][tokenIndex % 3]}@LINK(1)`).join(" + ");
+ const sql = `SELECT ${expression} FROM DUAL WHERE id = :id`;
+ expect(extractSqlParameters(sql, { databaseType: "oracle" })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType: "oracle" })).toBe(sql.replace(":id", "7"));
+ });
+
+ describe.each(["oracle", "oceanbase-oracle"] as const)("%s PL/SQL function templates", (databaseType) => {
+ it.each(["BEGIN @fn('ok'); END;", "BEGIN LOOP @fn('ok'); EXIT; END LOOP; END;", "BEGIN IF @fn(1)>0 THEN NULL; ELSIF @fn(2)>0 THEN NULL; END IF; END;", "BEGIN WHILE @fn(1)>0 LOOP NULL; END LOOP; END;", "BEGIN RETURN @fn(1); END;"])(
+ "keeps function templates after control keywords in %s",
+ (sql) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["fn"]);
+ expect(substituteSqlParameters(sql, { fn: { kind: "raw", value: "test_fn" } }, { databaseType })).toBe(sql.replaceAll("@fn", "test_fn"));
+ },
+ );
+
+ it.each(["begin", "loop", "elsif", "if", "while", "return"])("preserves qualified and quoted remote routines named %s", (name) => {
+ const sql = `BEGIN HR.${name}@LINK(1); "${name}"@LINK(1); END; SELECT * FROM ${name}@LINK`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual([]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" } }, { databaseType })).toBe(sql);
+ });
+ });
+
+ it("preserves Dameng quoted THEN objects and qualified THEN routines", () => {
+ const sql = 'SELECT HR.then@LINK(:id) FROM "THEN"@LINK WHERE id = :id';
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType: "dameng" })).toBe('SELECT HR.then@LINK(7) FROM "THEN"@LINK WHERE id = 7');
+ });
+
+ it.each(["", " "])("preserves Dameng unquoted THEN tables separated by %j", (separator) => {
+ const sql = `SELECT * FROM then${separator}@LINK WHERE id = :id`;
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType: "dameng" })).toBe(`SELECT * FROM then${separator}@LINK WHERE id = 7`);
+ });
+
+ describe("Dameng database link separators", () => {
+ it.each(["", " ", "\t", "\n", "/* @ignored */", " /* first */ \n /* second */ ", "-- @ignored\n"])("preserves links separated by %j alongside same-name parameters", (separator) => {
+ for (const objectName of ["test.table_name", '"Hr"."Audit Log"', "订单", '"SELECT"']) {
+ const sql = `SELECT @id FROM ${objectName}${separator}@id WHERE id = :id AND tenant_id = @tenant_id`;
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["id", "tenant_id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" }, tenant_id: { kind: "number", value: "3" } }, { databaseType: "dameng" })).toBe(`SELECT 7 FROM ${objectName}${separator}@id WHERE id = 7 AND tenant_id = 3`);
+ }
+ });
+
+ it.each([
+ ["SELECT * FROM test.remote_view /* link */ @dm1", [], "SELECT * FROM test.remote_view /* link */ @dm1"],
+ ["SELECT test.remote_fn /* link */ @dm1(:id) FROM DUAL", ["id"], "SELECT test.remote_fn /* link */ @dm1(7) FROM DUAL"],
+ ["CALL test.remote_proc /* link */ @dm1(@id)", ["id"], "CALL test.remote_proc /* link */ @dm1(7)"],
+ ["SELECT * FROM ACCESS /* link */ @dm1 WHERE id = :id", ["id"], "SELECT * FROM ACCESS /* link */ @dm1 WHERE id = 7"],
+ ] as const)("preserves links on remote objects in %s", (sql, names, expected) => {
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(names);
+ expect(substituteSqlParameters(sql, { dm1: { kind: "number", value: "99" }, id: { kind: "number", value: "7" } }, { databaseType: "dameng" })).toBe(expected);
+ });
+
+ it.each([
+ ["SELECT TOP @count * FROM test.table_name @dm1", ["count"], "SELECT TOP 7 * FROM test.table_name @dm1"],
+ ["SELECT * FROM test.table_name @dm1 LIMIT @offset, @count", ["offset", "count"], "SELECT * FROM test.table_name @dm1 LIMIT 7, 7"],
+ ["SELECT CASE WHEN/* comment */@condition THEN @yes ELSE @no END FROM DUAL", ["condition", "yes", "no"], "SELECT CASE WHEN/* comment */7 THEN 7 ELSE 7 END FROM DUAL"],
+ ["BEGIN IF @condition THEN NULL; END IF; RETURN @result; END;", ["condition", "result"], "BEGIN IF 7 THEN NULL; END IF; RETURN 7; END;"],
+ ] as const)("keeps real parameters after Dameng keywords in %s", (sql, names, expected) => {
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(names);
+ const values = Object.fromEntries(names.map((name) => [name, { kind: "number" as const, value: "7" }]));
+ expect(substituteSqlParameters(sql, values, { databaseType: "dameng" })).toBe(expected);
+ });
+
+ it("respects disabled parameter syntaxes without changing links", () => {
+ const sql = "SELECT @id FROM test.table_name /* link */ @id WHERE id = :id";
+ expect(extractSqlParameters(sql, { databaseType: "dameng", enabledSyntaxes: ["named"] })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType: "dameng", enabledSyntaxes: ["named"] })).toBe("SELECT @id FROM test.table_name /* link */ @id WHERE id = 7");
+ expect(extractSqlParameters(sql, { databaseType: "dameng", enabledSyntaxes: [] })).toEqual([]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType: "dameng", enabledSyntaxes: [] })).toBe(sql);
+ });
+
+ it.each([
+ ["SELECT DATE @value FROM DUAL", "'2026-10-10'", "SELECT DATE '2026-10-10' FROM DUAL"],
+ ["SELECT TIMESTAMP @value FROM DUAL", "'2026-10-10 12:00:00'", "SELECT TIMESTAMP '2026-10-10 12:00:00' FROM DUAL"],
+ ])("keeps Dameng datetime literal parameters in %s", (sql, value, expected) => {
+ expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["value"]);
+ expect(substituteSqlParameters(sql, { value: { kind: "raw", value } }, { databaseType: "dameng" })).toBe(expected);
+ });
+ });
+
+ it.each(["postgres", "sqlserver", "mysql"] as const)("keeps separated at-sign parameters unchanged for %s", (databaseType) => {
const sql = "SELECT * FROM employees /* comment */ @LINK WHERE id = :id";
expect(extractSqlParameters(sql, { databaseType })).toEqual(["LINK", "id"]);
expect(substituteSqlParameters(sql, { LINK: { kind: "number", value: "9" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT * FROM employees /* comment */ 9 WHERE id = 7");
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlVariables.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlVariables.spec.ts
index 68bddef599..fe77e8a64d 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlVariables.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlVariables.spec.ts
@@ -75,6 +75,128 @@ describe("expandSqlVariables", () => {
expect(expandSqlVariables(sql)).toEqual({ sql, expanded: false });
});
+ describe.each(["dameng", "oracle", "oceanbase-oracle"] as const)("%s database links", (databaseType) => {
+ it.each(["", " ", "\t", "\n", "/* @ignored */", " /* first */ \n /* second */ ", "-- @ignored\n"])("preserves a link separated by %j while expanding same-name references", (separator) => {
+ const target = `SELECT @Dm1 FROM test.table_name${separator}@dM1 WHERE id = @DM1 AND tenant_id = \${dm1}`;
+ const expected = `SELECT 7 FROM test.table_name${separator}@dM1 WHERE id = 7 AND tenant_id = 7`;
+ expect(expandSqlVariables(`@set DM1 = 7;\n${target}`, { databaseType })).toEqual({ sql: expected, expanded: true });
+ expect(expandSqlVariables(target, { databaseType, declarationSql: `@set DM1 = 7;\n${target}` })).toEqual({ sql: expected, expanded: true });
+ });
+
+ it.each(['"Hr"."Audit Log"', '"SELECT"', "订单"])("preserves quoted and Unicode object %s", (objectName) => {
+ const target = `SELECT @dm1 FROM ${objectName} /* separator */ @dm1 WHERE id = @dm1`;
+ expect(expandSqlVariables(`@set dm1 = 7;\n${target}`, { databaseType }).sql).toBe(`SELECT 7 FROM ${objectName} /* separator */ @dm1 WHERE id = 7`);
+ });
+
+ it.each([
+ ["SELECT XMLSERIALIZE(CONTENT @value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')", "SELECT XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["SELECT XMLSERIALIZE(CONTENT@value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')", "SELECT XMLSERIALIZE(CONTENTXMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["SELECT XMLSERIALIZE(DOCUMENT @value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')", "SELECT XMLSERIALIZE(DOCUMENT XMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["CREATE OR REPLACE PACKAGE BODY @value AS PROCEDURE p IS BEGIN NULL; END; END;", "test_package", "CREATE OR REPLACE PACKAGE BODY test_package AS PROCEDURE p IS BEGIN NULL; END; END;"],
+ ["DROP DATABASE LINK @value", "remote_db", "DROP DATABASE LINK remote_db"],
+ ["CREATE DATABASE LINK @value CONNECT TO remote_user IDENTIFIED BY password USING 'remote'", "remote_db", "CREATE DATABASE LINK remote_db CONNECT TO remote_user IDENTIFIED BY password USING 'remote'"],
+ ['SELECT "xml_column" @value FROM DUAL', "AS xml_alias", 'SELECT "xml_column" AS xml_alias FROM DUAL'],
+ ])("expands real templates outside object references in %s", (target, value, expected) => {
+ expect(expandSqlVariables(`@set value = ${value};\n${target}`, { databaseType }).sql).toBe(expected);
+ expect(expandSqlVariables(target, { databaseType, declarationSql: `@set value = ${value};` }).sql).toBe(expected);
+ });
+
+ it.each([
+ ["SELECT XMLSERIALIZE(CONTENT @fn('<a/>') AS CLOB) FROM DUAL", "SELECT XMLSERIALIZE(CONTENT XMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["SELECT XMLSERIALIZE(DOCUMENT @fn('<a/>') AS CLOB) FROM DUAL", "SELECT XMLSERIALIZE(DOCUMENT XMLTYPE('<a/>') AS CLOB) FROM DUAL"],
+ ["SELECT XMLQUERY('/a' PASSING @fn('<a/>') RETURNING CONTENT) FROM DUAL", "SELECT XMLQUERY('/a' PASSING XMLTYPE('<a/>') RETURNING CONTENT) FROM DUAL"],
+ ["SELECT XMLQUERY(fn_nested('/a') PASSING @fn('<a/>') RETURNING CONTENT) FROM DUAL", "SELECT XMLQUERY(fn_nested('/a') PASSING XMLTYPE('<a/>') RETURNING CONTENT) FROM DUAL"],
+ ])("expands SQL/XML function-name templates in %s", (target, expected) => {
+ const declarationSql = `@set fn = XMLTYPE;\n${target}`;
+ expect(expandSqlVariables(declarationSql, { databaseType }).sql).toBe(expected);
+ expect(expandSqlVariables(target, { databaseType, declarationSql }).sql).toBe(expected);
+ });
+
+ it.each([
+ "SELECT XMLQUERY('/a' PASSING BY VALUE @fn('<a/>') RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING @fn('<a/>') COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING BY /* separator */ VALUE @fn('<a/>') COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING BY VALUE @fn('<a/>'), @fn('<b/>') AS b RETURNING CONTENT) FROM DUAL",
+ ])("expands complete SQL/XML PASSING templates in full and selected SQL in %s", (target) => {
+ const declarationSql = `@set fn = XMLTYPE;\n${target}`;
+ const expected = target.replaceAll("@fn", "XMLTYPE");
+ expect(expandSqlVariables(declarationSql, { databaseType }).sql).toBe(expected);
+ expect(expandSqlVariables(target, { databaseType, declarationSql }).sql).toBe(expected);
+ });
+
+ it("preserves SQL/XML keyword-named remote routines with a same-name declaration", () => {
+ const target = 'SELECT content@LINK(1), document@LINK(1), passing@LINK(1), HR.content@LINK(1), "CONTENT"@LINK(1) FROM DUAL WHERE id = @LINK';
+ expect(expandSqlVariables(`@set LINK = 7;\n${target}`, { databaseType }).sql).toBe('SELECT content@LINK(1), document@LINK(1), passing@LINK(1), HR.content@LINK(1), "CONTENT"@LINK(1) FROM DUAL WHERE id = 7');
+ });
+
+ it.each([
+ "SELECT XMLSERIALIZE(CONTENT content@LINK(1) AS CLOB) FROM DUAL",
+ "SELECT XMLSERIALIZE(DOCUMENT document@LINK(1) AS CLOB) FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING passing@LINK(1) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLQUERY(passing@LINK(1)) FROM DUAL",
+ "SELECT XMLQUERY(fn_nested('/a') PASSING passing@LINK(1) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLQUERY('/a' PASSING BY VALUE value@LINK(1) RETURNING CONTENT) FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING passing@LINK(1) COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ "SELECT XMLTABLE('/a' PASSING BY VALUE HR.value@LINK(1), \"VALUE\"@LINK(1) AS b COLUMNS name VARCHAR2(50) PATH '.') FROM DUAL",
+ ])("preserves real routines inside SQL/XML clauses in %s", (target) => {
+ expect(expandSqlVariables(`@set LINK = WRONG;\n${target}`, { databaseType }).sql).toBe(target);
+ });
+
+ it("preserves remote routines alongside same-name variable references", () => {
+ const target = 'SELECT HR.get_value@LINK(@LINK) FROM "Hr"."Employees" /* link */ @LINK WHERE id = @LINK; BEGIN HR.run_job@LINK(@LINK); END;';
+ expect(expandSqlVariables(`@set LINK = 7;\n${target}`, { databaseType }).sql).toBe('SELECT HR.get_value@LINK(7) FROM "Hr"."Employees" /* link */ @LINK WHERE id = 7; BEGIN HR.run_job@LINK(7); END;');
+ });
+
+ it("expands keyword-led references and leaves unresolved references intact", () => {
+ const target = "SELECT CASE WHEN @dm1 THEN @dm1 ELSE @missing END FROM DUAL; BEGIN IF @dm1 THEN NULL; END IF; RETURN @dm1; END;";
+ expect(expandSqlVariables(`@set dm1 = 7;\n${target}`, { databaseType }).sql).toBe("SELECT CASE WHEN 7 THEN 7 ELSE @missing END FROM DUAL; BEGIN IF 7 THEN NULL; END IF; RETURN 7; END;");
+ });
+ });
+
+ describe.each(["oracle", "oceanbase-oracle"] as const)("%s PL/SQL function templates", (databaseType) => {
+ it.each(["BEGIN @fn('ok'); END;", "BEGIN LOOP @fn('ok'); EXIT; END LOOP; END;", "BEGIN IF @fn(1)>0 THEN NULL; ELSIF @fn(2)>0 THEN NULL; END IF; END;", "BEGIN WHILE @fn(1)>0 LOOP NULL; END LOOP; END;", "BEGIN RETURN @fn(1); END;"])(
+ "expands full and selected function templates in %s",
+ (target) => {
+ const declarationSql = `@set fn = test_fn;\n${target}`;
+ const expected = target.replaceAll("@fn", "test_fn");
+ expect(expandSqlVariables(declarationSql, { databaseType }).sql).toBe(expected);
+ expect(expandSqlVariables(target, { databaseType, declarationSql }).sql).toBe(expected);
+ },
+ );
+
+ it.each(["begin", "loop", "elsif", "if", "while", "return"])("preserves qualified and quoted routines named %s with a same-name declaration", (name) => {
+ const target = `BEGIN HR.${name}@LINK(1); "${name}"@LINK(1); END; SELECT * FROM ${name}@LINK`;
+ expect(expandSqlVariables(`@set LINK = WRONG;\n${target}`, { databaseType }).sql).toBe(target);
+ });
+ });
+
+ it.each([" ", ""])("expands Dameng THEN%s template calls", (separator) => {
+ const sql = `@set value = ABS;\nSELECT CASE WHEN 1=1 THEN${separator}@value(1) ELSE 0 END FROM DUAL`;
+ expect(expandSqlVariables(sql, { databaseType: "dameng" }).sql).toBe(`SELECT CASE WHEN 1=1 THEN${separator}ABS(1) ELSE 0 END FROM DUAL`);
+ });
+
+ it.each(["", " "])("preserves Dameng THEN table links separated by %j during expansion", (separator) => {
+ const sql = `@set LINK = 7;\nSELECT * FROM then${separator}@LINK WHERE id = @LINK`;
+ expect(expandSqlVariables(sql, { databaseType: "dameng" }).sql).toBe(`SELECT * FROM then${separator}@LINK WHERE id = 7`);
+ });
+
+ it("expands Dameng TOP and LIMIT variables while preserving links", () => {
+ const sql = "@set count = 7;\n@set offset = 3;\nSELECT TOP @count * FROM test.table_name @count LIMIT @offset, @count";
+ expect(expandSqlVariables(sql, { databaseType: "dameng" }).sql).toBe("SELECT TOP 7 * FROM test.table_name @count LIMIT 3, 7");
+ });
+
+ it.each([
+ ["@set value = '2026-10-10';\nSELECT DATE @value FROM DUAL", "SELECT DATE '2026-10-10' FROM DUAL"],
+ ["@set value = '2026-10-10 12:00:00';\nSELECT TIMESTAMP @value FROM DUAL", "SELECT TIMESTAMP '2026-10-10 12:00:00' FROM DUAL"],
+ ])("expands Dameng datetime literal variables in %s", (sql, expected) => {
+ expect(expandSqlVariables(sql, { databaseType: "dameng" }).sql).toBe(expected);
+ });
+
+ it.each(["postgres", "sqlserver", "mysql"] as const)("keeps legacy at-sign variable expansion for %s", (databaseType) => {
+ const sql = "@set dm1 = 7;\nSELECT @dm1 FROM test.table_name@dm1, other_table /* separator */ @dm1";
+ expect(expandSqlVariables(sql, { databaseType }).sql).toBe("SELECT 7 FROM test.table_name7, other_table /* separator */ 7");
+ });
+
it("keeps PostgreSQL ARRAY literals from corrupting later variable references", () => {
const sql = ["@set selected = 7;", "select ARRAY[']']::varchar[], @selected, ${missing}"].join("\n");
expect(expandSqlVariables(sql, { databaseType: "postgres" }).sql).toBe("select ARRAY[']']::varchar[], 7, ${missing}");
diff --git a/apps/desktop/src/lib/sql/sqlDatabaseLinks.ts b/apps/desktop/src/lib/sql/sqlDatabaseLinks.ts
new file mode 100644
index 0000000000..5148798de0
--- /dev/null
+++ b/apps/desktop/src/lib/sql/sqlDatabaseLinks.ts
@@ -0,0 +1,98 @@
+import type { DatabaseType } from "@/types/database";
+import { isDamengReservedKeyword, isOracleReservedKeyword } from "@/lib/sql/sqlIdentifier";
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
+import type { SqlSemanticToken } from "@/lib/sql/semantic/types";
+
+const ORACLE_OBJECT_PREFIX_KEYWORDS = new Set(["from", "join", "update", "into", "table", "delete"]);
+const ORACLE_TABLE_LIST_BOUNDARIES = new Set(["select", "from", "where", "group", "having", "order", "connect", "start", "union", "intersect", "minus", "for", "returning", "set", "values"]);
+const PLSQL_TEMPLATE_PREFIX_KEYWORDS = new Set(["begin", "if", "elsif", "loop", "while", "return", "then", "else", "case", "when"]);
+
+function collectSqlXmlKeywordPositions(tokens: readonly SqlSemanticToken[]): Set<number> {
+ const keywords = new Set<number>();
+ const contexts: { openingIndex: number; functionName: string; passingIndex?: number }[] = [];
+ for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex += 1) {
+ const token = tokens[tokenIndex];
+ if (token.text === ";") {
+ contexts.length = 0;
+ continue;
+ }
+ if (token.text === "(" || token.text === "(") {
+ const enclosingFunction = tokens[tokenIndex - 1];
+ contexts.push({ openingIndex: tokenIndex, functionName: enclosingFunction?.kind === "word" && tokens[tokenIndex - 2]?.text !== "." ? enclosingFunction.normalized : "" });
+ continue;
+ }
+ if (token.text === ")" || token.text === ")") {
+ contexts.pop();
+ continue;
+ }
+ const context = contexts[contexts.length - 1];
+ if (!context || token.kind !== "word" || tokens[tokenIndex - 1]?.text === ".") continue;
+ if (context.functionName === "xmlserialize") {
+ if (tokenIndex === context.openingIndex + 1 && (token.normalized === "content" || token.normalized === "document")) keywords.add(tokenIndex);
+ } else if (context.functionName === "xmlquery" || context.functionName === "xmltable") {
+ if (token.normalized === "passing" && context.passingIndex === undefined && tokenIndex > context.openingIndex + 1) {
+ context.passingIndex = tokenIndex;
+ keywords.add(tokenIndex);
+ } else if (context.passingIndex !== undefined && tokenIndex === context.passingIndex + 2 && tokens[tokenIndex - 1]?.normalized === "by" && token.normalized === "value") {
+ keywords.add(tokenIndex);
+ }
+ }
+ }
+ return keywords;
+}
+
+// 仅服务 SQL 解析,不扩展 Oracle 元数据或 UI 能力。每批扫描一次并保留原始位置,
+// 参数替换和 @set 展开共同保护对象链接,避免宽松前缀判断吞掉表达式或 DDL 参数。
+export function collectSqlDatabaseLinkStarts(sql: string, databaseType?: DatabaseType): Set<number> {
+ const links = new Set<number>();
+ if ((databaseType !== "oracle" && databaseType !== "oceanbase-oracle" && databaseType !== "dameng") || !sql.includes("@")) return links;
+ const isReservedKeyword = databaseType === "dameng" ? isDamengReservedKeyword : isOracleReservedKeyword;
+ const tokens = tokenizeSqlSemantic(sql, "oracle")
+ .filter((token) => token.kind !== "comment")
+ .flatMap((token) => {
+ const marker = token.kind === "word" ? token.text.indexOf("@") : -1;
+ if (marker <= 0) return [token];
+ // 紧邻 object@link 在语义 tokenizer 中是单个 word;拆分后也必须经过
+ // 相同的对象上下文判定,不能把 CONTENT@value 等表达式误当链接。
+ return [
+ { ...token, text: token.text.slice(0, marker), normalized: token.normalized.slice(0, marker), span: { ...token.span, end: token.span.start + marker } },
+ { ...token, text: token.text.slice(marker), normalized: token.normalized.slice(marker), span: { ...token.span, start: token.span.start + marker } },
+ ];
+ });
+ const sqlXmlKeywords = collectSqlXmlKeywordPositions(tokens);
+ for (let i = 1; i < tokens.length; i += 1) {
+ const token = tokens[i];
+ if (token.kind !== "word" || !token.text.startsWith("@")) continue;
+ const isObjectIdentifier = (position: number) => {
+ const candidate = tokens[position];
+ return candidate && ((candidate.kind === "quoted_identifier" && candidate.quote === '"') || (candidate.kind === "word" && /^[\p{L}_][\p{L}\p{N}_$#]*$/u.test(candidate.text) && !isReservedKeyword(candidate.text)));
+ };
+ if (!isObjectIdentifier(i - 1)) continue;
+ let objectStart = i - 1;
+ while (tokens[objectStart - 1]?.text === "." && isObjectIdentifier(objectStart - 2)) objectStart -= 2;
+ const prefix = tokens[objectStart - 1]?.normalized ?? "";
+ // 只识别表对象上下文或远程调用;CONTENT、BODY、LINK 等表达式/DDL
+ // 关键字及带引号的普通表达式后仍允许使用真实模板参数。
+ const object = tokens[i - 1];
+ // SQL 保留字表未涵盖所有 PL/SQL 控制关键字;只排除未限定的裸关键字,
+ // 仍允许带引号对象及 HR.then@link(...) 等限定远程调用。
+ const proceduralExpression = objectStart === i - 1 && object.kind === "word" && PLSQL_TEMPLATE_PREFIX_KEYWORDS.has(object.normalized);
+ const sqlXmlExpression = objectStart === i - 1 && sqlXmlKeywords.has(objectStart);
+ const routineCall = !proceduralExpression && !sqlXmlExpression && tokens[i + 1]?.text === "(" && (object.kind === "quoted_identifier" || !isReservedKeyword(object.text));
+ let objectContext = (ORACLE_OBJECT_PREFIX_KEYWORDS.has(prefix) && !(prefix === "update" && tokens[objectStart - 2]?.normalized === "for")) || routineCall;
+ // A comma can separate tables or expressions. Only a FROM list makes the
+ // following non-reserved keyword an object name, including after subqueries.
+ if (prefix === ",") {
+ for (let j = objectStart - 2; j >= 0; j -= 1) {
+ const before = tokens[j];
+ if (before.depth < token.depth || before.text === ";") break;
+ if (before.depth === token.depth && before.kind === "word" && ORACLE_TABLE_LIST_BOUNDARIES.has(before.normalized)) {
+ objectContext = before.normalized === "from" || routineCall;
+ break;
+ }
+ }
+ }
+ if (objectContext) links.add(token.span.start);
+ }
+ return links;
+}
diff --git a/apps/desktop/src/lib/sql/sqlIdentifier.ts b/apps/desktop/src/lib/sql/sqlIdentifier.ts
index 39cbcd58ad..cf51ecc46f 100644
--- a/apps/desktop/src/lib/sql/sqlIdentifier.ts
+++ b/apps/desktop/src/lib/sql/sqlIdentifier.ts
@@ -557,6 +557,10 @@ export function isOracleReservedKeyword(identifier: string): boolean {
return ORACLE_RESERVED_IDENTIFIER_KEYWORDS.has(identifier.toUpperCase());
}
+export function isDamengReservedKeyword(identifier: string): boolean {
+ return DAMENG_RESERVED_IDENTIFIER_KEYWORDS.has(identifier.toUpperCase());
+}
+
export function requiresDamengIdentifierQuote(identifier: string): boolean {
return !SIMPLE_DAMENG_IDENTIFIER.test(identifier) || DAMENG_RESERVED_IDENTIFIER_KEYWORDS.has(identifier);
}
diff --git a/apps/desktop/src/lib/sql/sqlParameters.ts b/apps/desktop/src/lib/sql/sqlParameters.ts
index a2732f80c8..2be7c0e37e 100644
--- a/apps/desktop/src/lib/sql/sqlParameters.ts
+++ b/apps/desktop/src/lib/sql/sqlParameters.ts
@@ -1,7 +1,5 @@
import type { DatabaseType } from "@/types/database";
-import { supportsOracleDatabaseLinks } from "@/lib/database/oracleDatabaseLinks";
-import { isOracleReservedKeyword } from "@/lib/sql/sqlIdentifier";
-import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
+import { collectSqlDatabaseLinkStarts } from "@/lib/sql/sqlDatabaseLinks";
export type SqlParameterValueKind = "string" | "number" | "boolean" | "null" | "raw";
@@ -67,8 +65,6 @@ export interface SqlParameterOptions {
const PARAMETER_NAME_RE = /^[\p{L}_][\p{L}\p{N}_]*(?:\.[\p{L}_][\p{L}\p{N}_]*)*$/u;
const PARAMETER_NAME_START_RE = /[\p{L}_]/u;
const PARAMETER_NAME_CHAR_RE = /[\p{L}\p{N}_]/u;
-const ORACLE_OBJECT_PREFIX_KEYWORDS = new Set(["from", "join", "update", "into", "table", "delete"]);
-const ORACLE_TABLE_LIST_BOUNDARIES = new Set(["select", "from", "where", "group", "having", "order", "connect", "start", "union", "intersect", "minus", "for", "returning", "set", "values"]);
const SQL_SERVER_TEMP_TABLE_CONTEXT_KEYWORDS = new Set(["table", "from", "join", "into", "update", "truncate"]);
const MYSQL_ROUTINE_LABEL_STATEMENTS = new Set(["begin", "loop", "while", "repeat"]);
const MYSQL_ROUTINE_LABEL_CONTEXTS = new Set(["begin", "then", "else", "do", "loop", "repeat"]);
@@ -386,7 +382,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
const supportsNamedParameters = databaseType !== "saphana" && databaseType !== "neo4j" && databaseType !== "nebula";
const enabledSyntaxes = options?.enabledSyntaxes ? new Set(options.enabledSyntaxes) : null;
const isSyntaxEnabled = (syntax: SqlParameterSyntax) => !enabledSyntaxes || enabledSyntaxes.has(syntax);
- const separatedOracleDatabaseLinks = isSyntaxEnabled("sqlserver") ? collectSeparatedOracleDatabaseLinks(sql, databaseType) : new Set<number>();
+ const databaseLinkStarts = isSyntaxEnabled("sqlserver") ? collectSqlDatabaseLinkStarts(sql, databaseType) : new Set<number>();
const complexTypeFieldSeparators = supportsNamedParameters && isSyntaxEnabled("named") ? collectComplexTypeFieldSeparators(sql, databaseType) : new Set<number>();
const duckDbStructFieldSeparators = supportsNamedParameters && isSyntaxEnabled("named") && databaseType === "duckdb" ? collectDuckDbStructFieldSeparators(sql) : new Set<number>();
const triggerPseudoRecordFieldStarts = supportsNamedParameters && isSyntaxEnabled("named") ? collectTriggerPseudoRecordFieldStarts(sql, databaseType) : new Set<number>();
@@ -547,7 +543,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
}
if (ch === "@" && isSyntaxEnabled("sqlserver")) {
const name = readParameterName(sql, i + 1);
- if (name && next !== "@" && sql[i - 1] !== "@" && !separatedOracleDatabaseLinks.has(i) && !isJdbcxMcpScopedPackage(sql, i, i + 1 + name.length) && !nativeSqlServerParameters.declared.has(name.toLowerCase()) && !nativeSqlServerParameters.ignoredStarts.has(i)) {
+ if (name && next !== "@" && sql[i - 1] !== "@" && !databaseLinkStarts.has(i) && !isJdbcxMcpScopedPackage(sql, i, i + 1 + name.length) && !nativeSqlServerParameters.declared.has(name.toLowerCase()) && !nativeSqlServerParameters.ignoredStarts.has(i)) {
occurrences.push({
key: name,
name,
@@ -730,54 +726,6 @@ function isDuckDbCompactPrefixAliasSeparator(sql: string, index: number, databas
return PARAMETER_NAME_CHAR_RE.test(previous) || previous === '"';
}
-function collectSeparatedOracleDatabaseLinks(sql: string, databaseType: DatabaseType | undefined): Set<number> {
- const links = new Set<number>();
- if (!supportsOracleDatabaseLinks(databaseType) || !sql.includes("@")) return links;
- const tokens = tokenizeSqlSemantic(sql, "oracle")
- .filter((token) => token.kind !== "comment")
- .flatMap((token) => {
- const marker = token.kind === "word" ? token.text.indexOf("@") : -1;
- if (marker <= 0) return [token];
- // The semantic tokenizer keeps an unquoted compact object@link in one word.
- // Split it without changing source offsets so it uses the same context check.
- return [
- { ...token, text: token.text.slice(0, marker), normalized: token.normalized.slice(0, marker), span: { ...token.span, end: token.span.start + marker } },
- { ...token, text: token.text.slice(marker), normalized: token.normalized.slice(marker), span: { ...token.span, start: token.span.start + marker } },
- ];
- });
- for (let i = 1; i < tokens.length; i += 1) {
- const token = tokens[i];
- if (token.kind !== "word" || !token.text.startsWith("@")) continue;
- const isObjectIdentifier = (position: number) => {
- const candidate = tokens[position];
- return candidate && ((candidate.kind === "quoted_identifier" && candidate.quote === '"') || (candidate.kind === "word" && /^[\p{L}_][\p{L}\p{N}_$#]*$/u.test(candidate.text) && !isOracleReservedKeyword(candidate.text)));
- };
- if (!isObjectIdentifier(i - 1)) continue;
- let objectStart = i - 1;
- while (tokens[objectStart - 1]?.text === "." && isObjectIdentifier(objectStart - 2)) objectStart -= 2;
- const prefix = tokens[objectStart - 1]?.normalized ?? "";
- // Require a table reference or a remote routine call. Unknown expression
- // keywords (CONTENT, BODY, LINK) must not hide template parameters.
- const object = tokens[i - 1];
- const routineCall = tokens[i + 1]?.text === "(" && (object.kind === "quoted_identifier" || !isOracleReservedKeyword(object.text));
- let objectContext = (ORACLE_OBJECT_PREFIX_KEYWORDS.has(prefix) && !(prefix === "update" && tokens[objectStart - 2]?.normalized === "for")) || routineCall;
- // A comma can separate tables or expressions. Only a FROM list makes the
- // following non-reserved keyword an object name, including after subqueries.
- if (prefix === ",") {
- for (let j = objectStart - 2; j >= 0; j -= 1) {
- const before = tokens[j];
- if (before.depth < token.depth || before.text === ";") break;
- if (before.depth === token.depth && before.kind === "word" && ORACLE_TABLE_LIST_BOUNDARIES.has(before.normalized)) {
- objectContext = before.normalized === "from" || routineCall;
- break;
- }
- }
- }
- if (objectContext) links.add(token.span.start);
- }
- return links;
-}
-
function isPostgresQuestionMarkOperator(sql: string, index: number, databaseType: DatabaseType | undefined): boolean {
if (databaseType !== "postgres") return false;
if (sql[index - 1] === "@" || sql[index + 1] === "|" || sql[index + 1] === "&") return true;
diff --git a/apps/desktop/src/lib/sql/sqlVariables.ts b/apps/desktop/src/lib/sql/sqlVariables.ts
index ae4ede84aa..313ed290e5 100644
--- a/apps/desktop/src/lib/sql/sqlVariables.ts
+++ b/apps/desktop/src/lib/sql/sqlVariables.ts
@@ -12,6 +12,7 @@
// unresolved `${name}` or `@name` remains available to the parameter dialog.
import type { DatabaseType } from "@/types/database";
+import { collectSqlDatabaseLinkStarts } from "@/lib/sql/sqlDatabaseLinks";
const VARIABLE_NAME_START_RE = /[\p{L}_]/u;
const VARIABLE_NAME_CHAR_RE = /[\p{L}\p{N}_]/u;
@@ -242,6 +243,8 @@ function readValueEnd(sql: string, start: number, databaseType?: DatabaseType, i
}
function replaceReferences(sql: string, values: Map<string, string>, databaseType?: DatabaseType): string {
+ // 声明移除后再计算位置,保护与 @set 同名的 DBLink,只展开真正的变量引用。
+ const databaseLinkStarts = collectSqlDatabaseLinkStarts(sql, databaseType);
let result = "";
let i = 0;
let dollarQuoteEnd = "";
@@ -304,7 +307,7 @@ function replaceReferences(sql: string, values: Map<string, string>, databaseTyp
}
}
}
- if (ch === "@" && next !== "@" && sql[i - 1] !== "@") {
+ if (ch === "@" && next !== "@" && sql[i - 1] !== "@" && !databaseLinkStarts.has(i)) {
const name = readVariableName(sql, i + 1);
if (name) {
const value = values.get(name.toLowerCase());