feat(oracle): add dblink completion, tree view and management

This commit is contained in:
zipg authored and GitHub committed 2026-09-13 02:00:09 +08:00
1 parent 6694e4382e
commit b8f39f9c24
25 files changed
+645 -13

No files matched your search

@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { ORACLE_DATABASE_LINKS_SQL, createOracleDatabaseLinkSql, alterOracleDatabaseLinkSql, dropOracleDatabaseLinkSql, oracleDatabaseLinkName } from "@/lib/database/oracleDatabaseLinks";
import { oracleDatabaseLinkCompletionContext as context, oracleDatabaseLinkCompletionItems as items } from "@/lib/sql/oracleDatabaseLinkCompletion";
const privateLink = { owner: "APP", name: "REMOTE.EXAMPLE.COM", username: "REMOTE_USER", host: "//localhost:1521/XE", created: "" };
describe("Oracle database links", () => {
it.each(["SELECT * FROM DUAL@", "SELECT * FROM APP.DUAL@", 'SELECT * FROM "Odd table"@', "UPDATE APP.T@", "BEGIN APP.PROC@", "INSERT INTO T@", "DELETE FROM T@", "SELECT * FROM A JOIN B@"])("offers suffix completion in %s", (sql) => {
expect(context(sql, sql.length, "oracle")).toEqual({ prefix: "", from: sql.length, to: sql.length });
});
it("replaces an entire domain suffix, including text after the cursor", () => {
const sql = "SELECT * FROM DUAL@REMOTE.EXAMPLE.COM";
const cursor = sql.indexOf("EXAMPLE");
expect(context(sql, cursor, "oracle")).toEqual({ prefix: "REMOTE.", from: sql.indexOf("REMOTE"), to: sql.length });
});
it.each(["SELECT '@", "-- DUAL@", "/* DUAL@", "SELECT @", "SELECT @@", "SELECT * FROM DUAL@@"])("suppresses non-link context %s", (sql) => expect(context(sql, sql.length, "oracle")).toBeNull());
it("does not affect other dialects", () => expect(context("SELECT T@", 9, "mysql")).toBeNull());
it("deduplicates public links shadowed by a private link and never inserts owner qualification", () => {
expect(items([{ ...privateLink, owner: "PUBLIC" }, privateLink], "remote.")).toEqual([{ label: privateLink.name, apply: privateLink.name, type: "namespace", detail: "APP · REMOTE_USER · //localhost:1521/XE" }]);
});
it("keeps the login user's private links visible regardless of the editor's current schema", () => {
const publicLink = { ...privateLink, owner: "PUBLIC", name: "PUBLIC.EXAMPLE.COM" };
expect(items([privateLink, publicLink], "")).toHaveLength(2);
expect(items([privateLink], "remote.")).toHaveLength(1);
expect(items([privateLink], "other.")).toEqual([]);
});
it("uses the login user's visibility independently of current schema", () => {
expect(ORACLE_DATABASE_LINKS_SQL).toContain("SESSION_USER");
expect(ORACLE_DATABASE_LINKS_SQL).toContain("'PUBLIC'");
expect(ORACLE_DATABASE_LINKS_SQL).not.toContain("CURRENT_SCHEMA");
});
it("creates fixed-user links with an escaped connect string", () => {
expect(createOracleDatabaseLinkSql({ name: privateLink.name, username: "REMOTE_USER", password: "p@ss", host: "test'host", public: false })).toBe(`CREATE DATABASE LINK REMOTE.EXAMPLE.COM CONNECT TO "REMOTE_USER" IDENTIFIED BY "p@ss" USING 'test''host'`);
});
it("updates the remote credential without redefining the link", () => expect(alterOracleDatabaseLinkSql(privateLink, "new-pass")).toBe('ALTER DATABASE LINK REMOTE.EXAMPLE.COM CONNECT TO "REMOTE_USER" IDENTIFIED BY "new-pass"'));
it("preserves a case-sensitive remote user read from metadata", () => expect(alterOracleDatabaseLinkSql({ ...privateLink, username: "MixedCase" }, "new-pass")).toContain('CONNECT TO "MixedCase"'));
it("normalizes unquoted usernames when creating links", () => expect(createOracleDatabaseLinkSql({ name: "REMOTE", username: "remote_user", password: "pass", host: "XE", public: false })).toContain('CONNECT TO "REMOTE_USER"'));
it("drops public links with the public modifier", () => expect(dropOracleDatabaseLinkSql({ ...privateLink, owner: "PUBLIC" })).toBe("DROP PUBLIC DATABASE LINK REMOTE.EXAMPLE.COM"));
it.each(["x; DROP TABLE t", "x--", 'x"', "a b", "a..b"])("rejects unsafe link names %s", (name) => expect(() => oracleDatabaseLinkName(name)).toThrow());
});
@@ -0,0 +1,57 @@
import type { QueryResult } from "@/types/database";
export interface OracleDatabaseLink {
name: string;
owner: string;
username: string;
host: string;
created: string;
}
// Links belong to the login user, independently of ALTER SESSION SET CURRENT_SCHEMA.
// Do not expose another user's private links when connected with catalog privileges.
export const ORACLE_DATABASE_LINKS_SQL = `SELECT OWNER, DB_LINK, USERNAME, HOST,
TO_CHAR(CREATED, 'YYYY-MM-DD HH24:MI:SS') AS CREATED
FROM ALL_DB_LINKS
WHERE OWNER IN (SYS_CONTEXT('USERENV', 'SESSION_USER'), 'PUBLIC')
ORDER BY DB_LINK, CASE WHEN OWNER = 'PUBLIC' THEN 1 ELSE 0 END`;
export function oracleDatabaseLinksFromResult(result: QueryResult): OracleDatabaseLink[] {
const indexes = new Map(result.columns.map((name, index) => [name.toUpperCase(), index]));
return result.rows
.map((row) => {
const value = (name: string) => String(row[indexes.get(name) ?? -1] ?? "");
return { name: value("DB_LINK"), owner: value("OWNER"), username: value("USERNAME"), host: value("HOST"), created: value("CREATED") };
})
.filter((link) => !!link.name && !!link.owner);
}
export function oracleDatabaseLinkName(name: string): string {
// Oracle link names are ASCII, case insensitive, and may include a domain.
// A dot is part of the link name, never a schema qualifier.
if (!/^[A-Za-z][A-Za-z0-9_$#]*(?:\.[A-Za-z0-9_$#]+)*$/.test(name) || name.length > 128) throw new Error("Invalid database link name");
return name;
}
function oracleQuotedIdentifier(value: string, fromMetadata = false): string {
if (!value || /[\0\r\n]/.test(value)) throw new Error("Invalid identifier");
const name = fromMetadata ? value : value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1).replaceAll('""', '"') : value.toUpperCase();
return `"${name.replaceAll('"', '""')}"`;
}
export function createOracleDatabaseLinkSql(input: { name: string; public: boolean; username: string; password: string; host: string }): string {
if (!input.host.trim() || !input.password || /[\0\r\n"]/.test(input.password)) throw new Error("A connect string and a password without double quotes or line breaks are required");
return `CREATE ${input.public ? "PUBLIC " : ""}DATABASE LINK ${oracleDatabaseLinkName(input.name)} CONNECT TO ${oracleQuotedIdentifier(input.username)} IDENTIFIED BY "${input.password}" USING '${input.host.replaceAll("'", "''")}'`;
}
export function alterOracleDatabaseLinkSql(link: OracleDatabaseLink, password: string): string {
if (!link.username || !password || /[\0\r\n"]/.test(password)) throw new Error("A fixed-user link and a password without double quotes or line breaks are required");
return `ALTER ${link.owner === "PUBLIC" ? "PUBLIC " : ""}DATABASE LINK ${oracleDatabaseLinkName(link.name)} CONNECT TO ${oracleQuotedIdentifier(link.username, true)} IDENTIFIED BY "${password}"`;
}
export function dropOracleDatabaseLinkSql(link: OracleDatabaseLink): string {
return `DROP ${link.owner === "PUBLIC" ? "PUBLIC " : ""}DATABASE LINK ${oracleDatabaseLinkName(link.name)}`;
}
export function testOracleDatabaseLinkSql(link: OracleDatabaseLink): string {
return `SELECT 1 AS DBX_LINK_OK FROM DUAL@${oracleDatabaseLinkName(link.name)}`;
}
@@ -632,6 +632,12 @@ const FUNCTION_ICON: LucideIconNode = [
["path", { d: "M4 4v7a4 4 0 0 0 4 4h12" }],
];
const DATABASE_LINK_ICON: LucideIconNode = [
["path", { d: "M9 17H7A5 5 0 0 1 7 7h2" }],
["path", { d: "M15 7h2a5 5 0 0 1 0 10h-2" }],
["path", { d: "M8 12h8" }],
];
const SCHEMA_ICON: LucideIconNode = [["path", { d: "M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2v11z" }]];
function encodeSvgIcon(iconNode: LucideIconNode): string {
@@ -1067,6 +1073,10 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
color: colorMixValue("var(--emerald-500, #10b981)", "color-mix(in oklch, var(--emerald-500, #10b981) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(FUNCTION_ICON),
},
".cm-completionIcon-namespace": {
color: colorMixValue("var(--sky-500, #0ea5e9)", "color-mix(in oklch, var(--sky-500, #0ea5e9) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(DATABASE_LINK_ICON),
},
".cm-completionIcon-schema": {
color: colorMixValue("var(--amber-500, #f59e0b)", "color-mix(in oklch, var(--amber-500, #f59e0b) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(SCHEMA_ICON),
@@ -9,6 +9,7 @@ const leafTypes: Set<TreeNodeType> = new Set([
"procedure",
"function",
"synonym",
"oracle-db-link",
"package",
"package-body",
"type-body",
@@ -1,6 +1,7 @@
import type { TreeNodeType } from "@/types/database";
const treeGroupNodeTypes = new Set<TreeNodeType>([
"oracle-db-links",
"group-columns",
"group-indexes",
"group-fkeys",
@@ -114,6 +114,8 @@ export function getTreeNodeIconInfo(node: TreeNode): TreeNodeIconInfo | null {
return { icon: Braces, colorClass: "text-amber-500" };
case "sequence":
return { icon: ListTree, colorClass: "text-emerald-500" };
case "oracle-db-links":
case "oracle-db-link":
case "synonym":
return { icon: Link2, colorClass: "text-sky-500" };
case "job":
@@ -0,0 +1,28 @@
import type { DatabaseType } from "@/types/database";
import type { OracleDatabaseLink } from "@/lib/database/oracleDatabaseLinks";
import { isSqlCompletionSuppressedContext } from "@/lib/sql/sqlCompletion";
export function oracleDatabaseLinkCompletionContext(sql: string, cursor: number, databaseType?: DatabaseType) {
if (databaseType !== "oracle" || isSqlCompletionSuppressedContext(sql, cursor, { databaseType })) return null;
const before = sql.slice(0, cursor);
const match = /(?:[A-Za-z0-9_$#]|"(?:[^"]|"")+"|\))@([A-Za-z0-9_$#.]*)$/.exec(before);
if (!match) return null;
const prefix = match[1];
return { prefix, from: cursor - prefix.length, to: cursor + (/^[A-Za-z0-9_$#.]*/.exec(sql.slice(cursor))?.[0].length ?? 0) };
}
export function oracleDatabaseLinkCompletionItems(links: readonly OracleDatabaseLink[], prefix: string) {
const seen = new Set<string>();
// Oracle resolves object@link against the login user's private links plus
// PUBLIC links; CURRENT_SCHEMA never enables or disables either, and the
// link query already restricts owners to SESSION_USER and PUBLIC.
return [...links]
.sort((a, b) => Number(a.owner === "PUBLIC") - Number(b.owner === "PUBLIC"))
.filter((link) => {
const key = link.name.toUpperCase();
if (seen.has(key) || !key.startsWith(prefix.toUpperCase())) return false;
seen.add(key);
return true;
})
.map((link) => ({ label: link.name, apply: link.name, type: "namespace", detail: `${link.owner} · ${link.username || "—"} · ${link.host}` }));
}