feat(editor): dialect-aware SQL quick actions with per-database templates

This commit is contained in:
Mo-Moore authored and GitHub committed 2026-09-17 17:29:01 +08:00
1 parent 455117b8c5
commit 65b820e6a9
30 files changed
+1541 -150

No files matched your search

+220 -13
View File
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SHORTCUT_SETTINGS } from "@/lib/editor/shortcutRegistry";
import { enabledSqlShortcutActions, findSqlShortcutConflicts, hasSqlShortcutConflicts, resolveSqlShortcutTemplate } from "@/lib/sql/sqlShortcutActions";
import { buildSelectStarWithLimitSql } from "@/lib/sql/sqlDialectSelectLimit";
import { buildSqlShortcutExecutionSql, enabledSqlShortcutActions, findSqlShortcutConflicts, hasSqlShortcutConflicts, resolveSqlShortcutForDatabase, resolveSqlShortcutTemplate, sqlShortcutAppliesToDatabase, uniqueSqlShortcutBindings } from "@/lib/sql/sqlShortcutActions";
import type { SqlShortcutAction } from "@/types/database";
function action(id: string, shortcut: string, overrides: Partial<SqlShortcutAction> = {}): SqlShortcutAction {
@@ -48,6 +49,21 @@ describe("findSqlShortcutConflicts", () => {
expect(hasSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toBe(true);
});
it("allows the same shortcut across non-overlapping database types", () => {
const actions = [action("mysql", "Mod+Shift+1", { databaseTypes: ["mysql"] }), action("sqlserver", "Mod+Shift+1", { databaseTypes: ["sqlserver"] })];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual([]);
});
it("detects conflicts when database type scopes overlap", () => {
const actions = [action("a", "Mod+Shift+1", { databaseTypes: ["mysql", "postgres"] }), action("b", "Mod+Shift+1", { databaseTypes: ["postgres"] })];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["a", "b"]));
});
it("treats all-databases scope as overlapping any scoped action", () => {
const actions = [action("all", "Mod+Shift+1"), action("mysql", "Mod+Shift+1", { databaseTypes: ["mysql"] })];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["all", "mysql"]));
});
it("detects duplicate custom shortcuts with different modifier order", () => {
const actions = [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")];
expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["a", "b"]));
@@ -64,25 +80,216 @@ describe("findSqlShortcutConflicts", () => {
});
});
describe("resolveSqlShortcutForDatabase", () => {
it("prefers a scoped action over an all-databases action", () => {
const actions = [action("all", "Mod+Shift+1", { sql: "ALL" }), action("mysql", "Mod+Shift+1", { databaseTypes: ["mysql"], sql: "MYSQL" })];
expect(resolveSqlShortcutForDatabase(actions, "Mod+Shift+1", "mysql")?.id).toBe("mysql");
});
it("returns undefined when the current database is outside the scope", () => {
const actions = [action("mysql", "Mod+Shift+1", { databaseTypes: ["mysql"] })];
expect(resolveSqlShortcutForDatabase(actions, "Mod+Shift+1", "postgres")).toBeUndefined();
});
it("unique bindings collapse duplicate keys", () => {
const actions = [action("mysql", "Mod+Shift+1", { databaseTypes: ["mysql"] }), action("sqlserver", "Mod+Shift+1", { databaseTypes: ["sqlserver"] })];
expect(uniqueSqlShortcutBindings(actions)).toEqual(["Mod+Shift+1"]);
});
});
describe("buildSqlShortcutExecutionSql", () => {
it("builds dialect-aware select-limit SQL", () => {
const selectLimit = action("top10", "Mod+Shift+1", { kind: "select-limit", limit: 10 });
expect(buildSqlShortcutExecutionSql(selectLimit, "orders", "mysql")).toBe("SELECT *\nFROM orders\nLIMIT 10");
expect(buildSqlShortcutExecutionSql(selectLimit, "orders", "sqlserver")).toBe("SELECT TOP 10 *\nFROM orders");
expect(buildSqlShortcutExecutionSql(selectLimit, "orders", "oracle")).toBe("SELECT *\nFROM orders\nWHERE ROWNUM <= 10");
});
it("keeps quick actions bounded for unknown jdbc dialects", () => {
const selectLimit = action("top10", "Mod+Shift+1", { kind: "select-limit", limit: 10 });
expect(buildSqlShortcutExecutionSql(selectLimit, "orders", "jdbc")).toBe("SELECT *\nFROM orders\nLIMIT 10");
});
it("keeps plain templates unchanged aside from ${table}", () => {
expect(buildSqlShortcutExecutionSql(action("count", "Mod+C", { sql: "SELECT COUNT(*) FROM ${table}" }), "t")).toBe("SELECT COUNT(*) FROM t");
});
it("prefers sqlByDatabaseType for the active database", () => {
const scoped = action("per-db", "Mod+Shift+9", {
sql: "SELECT * FROM ${table} /* default */",
sqlByDatabaseType: {
mysql: "SELECT * FROM ${table} /* mysql */",
postgres: "SELECT * FROM ${table} /* postgres */",
},
});
expect(buildSqlShortcutExecutionSql(scoped, "orders", "mysql")).toBe("SELECT * FROM orders /* mysql */");
expect(buildSqlShortcutExecutionSql(scoped, "orders", "postgres")).toBe("SELECT * FROM orders /* postgres */");
expect(buildSqlShortcutExecutionSql(scoped, "orders", "sqlserver")).toBe("SELECT * FROM orders /* default */");
expect(buildSqlShortcutExecutionSql(scoped, "orders")).toBe("SELECT * FROM orders /* default */");
});
});
describe("isBuiltinSqlShortcut", () => {
it("recognizes shipped built-in ids", async () => {
const { isBuiltinSqlShortcut, BUILTIN_SQL_SHORTCUT_COUNT_ID, BUILTIN_SQL_SHORTCUT_SELECT_LIMIT_ID } = await import("@/lib/sql/sqlShortcutActions");
expect(isBuiltinSqlShortcut(BUILTIN_SQL_SHORTCUT_SELECT_LIMIT_ID)).toBe(true);
expect(isBuiltinSqlShortcut(BUILTIN_SQL_SHORTCUT_COUNT_ID)).toBe(true);
expect(isBuiltinSqlShortcut("custom")).toBe(false);
});
});
describe("sqlShortcutAppliesToDatabase", () => {
it("treats empty scope as all databases", () => {
expect(sqlShortcutAppliesToDatabase({}, "mysql")).toBe(true);
expect(sqlShortcutAppliesToDatabase({ databaseTypes: [] }, "mysql")).toBe(true);
});
it("requires a matching database type when scoped", () => {
expect(sqlShortcutAppliesToDatabase({ databaseTypes: ["mysql"] }, "mysql")).toBe(true);
expect(sqlShortcutAppliesToDatabase({ databaseTypes: ["mysql"] }, "postgres")).toBe(false);
expect(sqlShortcutAppliesToDatabase({ databaseTypes: ["mysql"] }, undefined)).toBe(false);
});
});
describe("buildSelectStarWithLimitSql", () => {
it("covers the main dialect styles", () => {
expect(buildSelectStarWithLimitSql("t", 5, "postgres")).toContain("LIMIT 5");
expect(buildSelectStarWithLimitSql("t", 5, "sqlserver")).toContain("TOP 5");
expect(buildSelectStarWithLimitSql("t", 5, "db2")).toContain("FETCH FIRST 5");
expect(buildSelectStarWithLimitSql("t", 5, "informix")).toContain("FIRST 5");
expect(buildSelectStarWithLimitSql("t", 5, "firebird")).toContain("ROWS 5");
expect(buildSelectStarWithLimitSql("t", 5, "jdbc")).toBe("SELECT *\nFROM t\nLIMIT 5");
});
});
describe("normalizeSqlShortcuts", () => {
afterEach(() => {
vi.unstubAllGlobals();
vi.resetModules();
});
it("falls back to the built-in select-limit shortcut when the list is empty", async () => {
const { normalizeEditorSettings, DEFAULT_EDITOR_SETTINGS } = await import("@/stores/settingsStore");
const { DEFAULT_SQL_SHORTCUTS } = await import("@/lib/sql/sqlShortcutActions");
expect(DEFAULT_EDITOR_SETTINGS.sqlShortcuts).toEqual(DEFAULT_SQL_SHORTCUTS);
expect(normalizeEditorSettings({ sqlShortcuts: [] }).sqlShortcuts).toEqual(DEFAULT_SQL_SHORTCUTS);
expect(DEFAULT_SQL_SHORTCUTS.map((item) => item.id)).toEqual(["builtin-select-limit", "builtin-count"]);
});
it("restores defaults even when previous settings had an empty sqlShortcuts list", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const { DEFAULT_SQL_SHORTCUTS } = await import("@/lib/sql/sqlShortcutActions");
const previous = normalizeEditorSettings({ sqlShortcuts: DEFAULT_SQL_SHORTCUTS });
previous.sqlShortcuts = [];
expect(normalizeEditorSettings({ sqlShortcuts: [] }, previous).sqlShortcuts.map((item) => item.id)).toEqual(["builtin-select-limit", "builtin-count"]);
});
it("appends missing built-in shortcuts without overwriting existing ones", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const normalized = normalizeEditorSettings({
sqlShortcuts: [
action("builtin-select-limit", "Mod+Shift+9", {
label: "Custom top",
kind: "select-limit",
limit: 5,
sql: "ignored",
}),
],
}).sqlShortcuts;
expect(normalized.map((item) => item.id)).toEqual(["builtin-select-limit", "builtin-count"]);
expect(normalized[0]?.shortcut).toBe("Mod+Shift+9");
expect(normalized[0]?.limit).toBe(5);
expect(normalized[1]?.sql).toContain("COUNT(*)");
});
it("preserves a single shortcut through normalizeEditorSettings", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const source = [action("count", "Mod+Shift+C", { label: "Count rows", sql: "SELECT COUNT(*) FROM ${table}" })];
const normalized = normalizeEditorSettings({ sqlShortcuts: source }).sqlShortcuts;
expect(normalized).toEqual([
{
id: "count",
label: "Count rows",
shortcut: "Mod+Shift+C",
sql: "SELECT COUNT(*) FROM ${table}",
enabled: true,
},
]);
expect(normalized[0]).toEqual({
id: "count",
label: "Count rows",
shortcut: "Mod+Shift+C",
sql: "SELECT COUNT(*) FROM ${table}",
enabled: true,
});
expect(normalized.map((item) => item.id)).toEqual(["count", "builtin-select-limit", "builtin-count"]);
});
it("normalizes select-limit kind and limit, and strips database scope", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const normalized = normalizeEditorSettings({
sqlShortcuts: [
action("top", "Mod+Shift+1", {
kind: "select-limit",
limit: 10.8,
databaseTypes: ["mysql", "mysql", "not-a-db" as never],
sql: "ignored",
}),
],
}).sqlShortcuts;
expect(normalized[0]).toMatchObject({
id: "top",
kind: "select-limit",
limit: 10,
sql: "SELECT *\nFROM ${table}\nLIMIT 10",
});
expect(normalized[0]?.databaseTypes).toBeUndefined();
});
it("preserves sqlByDatabaseType for custom templates and strips it from select-limit", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const normalized = normalizeEditorSettings({
sqlShortcuts: [
action("custom", "Mod+Shift+3", {
databaseTypes: ["mysql", "postgres"],
sql: "SELECT * FROM ${table} /* default */",
sqlByDatabaseType: {
mysql: "SELECT * FROM ${table} /* mysql */",
postgres: "SELECT 1 FROM ${table}",
"not-a-db": "nope",
} as never,
}),
action("top", "Mod+Shift+4", {
kind: "select-limit",
limit: 5,
sqlByDatabaseType: { mysql: "ignored" } as never,
}),
],
}).sqlShortcuts;
expect(normalized.find((item) => item.id === "custom")?.sqlByDatabaseType).toEqual({
mysql: "SELECT * FROM ${table} /* mysql */",
postgres: "SELECT 1 FROM ${table}",
});
expect(normalized.find((item) => item.id === "top")?.sqlByDatabaseType).toBeUndefined();
});
it("derives databaseTypes from sqlByDatabaseType when scope is missing", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
const { deriveSqlShortcutDatabaseTypes } = await import("@/lib/sql/sqlShortcutActions");
expect(
deriveSqlShortcutDatabaseTypes(undefined, {
mysql: "SELECT 1 FROM ${table}",
postgres: "SELECT 2 FROM ${table}",
}),
).toEqual(["mysql", "postgres"]);
const normalized = normalizeEditorSettings({
sqlShortcuts: [
action("imported", "Mod+Shift+5", {
sql: "SELECT * FROM ${table} /* default */",
sqlByDatabaseType: {
mysql: "SELECT * FROM ${table} /* mysql */",
oracle: "SELECT COUNT(*) FROM ${table}",
},
}),
],
}).sqlShortcuts;
const imported = normalized.find((item) => item.id === "imported");
expect(imported?.databaseTypes).toEqual(["mysql", "oracle"]);
expect(imported?.sqlByDatabaseType).toEqual({
mysql: "SELECT * FROM ${table} /* mysql */",
oracle: "SELECT COUNT(*) FROM ${table}",
});
});
it("keeps modifier-order variants when loading settings", async () => {
@@ -90,8 +297,8 @@ describe("normalizeSqlShortcuts", () => {
const normalized = normalizeEditorSettings({
sqlShortcuts: [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")],
}).sqlShortcuts;
expect(normalized).toHaveLength(2);
expect(normalized.map((item) => item.id)).toEqual(["a", "b"]);
expect(normalized.map((item) => item.id).slice(0, 2)).toEqual(["a", "b"]);
expect(normalized.map((item) => item.id)).toEqual(["a", "b", "builtin-select-limit", "builtin-count"]);
});
it("drops a macOS-reserved shortcut so legacy/synced SQL shortcuts cannot hijack ⌘H", async () => {
@@ -104,7 +311,7 @@ describe("normalizeSqlShortcuts", () => {
}).sqlShortcuts;
expect(normalized.find((item) => item.id === "h")?.shortcut).toBe("");
expect(normalized.find((item) => item.id === "ok")?.shortcut).toBe("Mod+Shift+K");
expect(normalized).toHaveLength(2);
expect(normalized.map((item) => item.id)).toEqual(["h", "ok", "builtin-select-limit", "builtin-count"]);
});
it("keeps Ctrl+H on non-mac platforms where it is a legitimate SQL shortcut", async () => {
@@ -0,0 +1,126 @@
import { describe, expect, it } from "vitest";
import { applySqlShortcutBodyToAllSelected, buildSqlShortcutBodiesForSave, clearSqlShortcutFormDatabaseTypes, flushSqlShortcutEditingBody, switchSqlShortcutEditingDatabaseType, toggleSqlShortcutFormDatabaseType, type SqlShortcutFormBodies } from "@/lib/sql/sqlShortcutFormBodies";
function form(overrides: Partial<SqlShortcutFormBodies> = {}): SqlShortcutFormBodies {
return {
sql: "SELECT * FROM ${table} /* default */",
body: "SELECT * FROM ${table} /* default */",
databaseTypes: [],
sqlByDatabaseType: {},
editingDatabaseType: "",
...overrides,
};
}
describe("sqlShortcutFormBodies", () => {
it("flushes scoped edits into the override map without changing default sql", () => {
const next = flushSqlShortcutEditingBody(
form({
databaseTypes: ["mysql", "postgres"],
editingDatabaseType: "mysql",
body: "SELECT 1 FROM ${table} /* mysql */",
}),
);
expect(next.sql).toBe("SELECT * FROM ${table} /* default */");
expect(next.sqlByDatabaseType.mysql).toBe("SELECT 1 FROM ${table} /* mysql */");
});
it("switches database by flushing current and loading override or default sql", () => {
const afterMysql = flushSqlShortcutEditingBody(
form({
databaseTypes: ["mysql", "postgres"],
editingDatabaseType: "mysql",
body: "SELECT 1 FROM ${table} /* mysql */",
}),
);
const afterPostgres = switchSqlShortcutEditingDatabaseType(afterMysql, "postgres");
expect(afterPostgres.sqlByDatabaseType.mysql).toBe("SELECT 1 FROM ${table} /* mysql */");
expect(afterPostgres.body).toBe("SELECT * FROM ${table} /* default */");
expect(afterPostgres.sql).toBe("SELECT * FROM ${table} /* default */");
});
it("does not fill unedited databases on save", () => {
const edited = flushSqlShortcutEditingBody(
form({
databaseTypes: ["mysql", "postgres"],
editingDatabaseType: "mysql",
body: "SELECT 1 FROM ${table} /* mysql */",
}),
);
const saved = buildSqlShortcutBodiesForSave(edited);
expect(saved.sql).toBe("SELECT * FROM ${table} /* default */");
expect(saved.databaseTypes).toEqual(["mysql", "postgres"]);
expect(saved.sqlByDatabaseType).toEqual({ mysql: "SELECT 1 FROM ${table} /* mysql */" });
});
it("removes override when unchecking a database and does not pollute default sql", () => {
const start = form({
databaseTypes: ["mysql", "postgres"],
editingDatabaseType: "mysql",
body: "SELECT 1 FROM ${table} /* mysql */",
sqlByDatabaseType: {
mysql: "SELECT 1 FROM ${table} /* mysql */",
postgres: "SELECT 2 FROM ${table} /* postgres */",
},
});
const afterUncheck = toggleSqlShortcutFormDatabaseType(start, "mysql");
expect(afterUncheck.databaseTypes).toEqual(["postgres"]);
expect(afterUncheck.sqlByDatabaseType.mysql).toBeUndefined();
expect(afterUncheck.sqlByDatabaseType.postgres).toBe("SELECT 2 FROM ${table} /* postgres */");
expect(afterUncheck.sql).toBe("SELECT * FROM ${table} /* default */");
expect(afterUncheck.editingDatabaseType).toBe("postgres");
expect(afterUncheck.body).toBe("SELECT 2 FROM ${table} /* postgres */");
});
it("clears all overrides when returning to all databases", () => {
const start = form({
databaseTypes: ["mysql", "postgres"],
editingDatabaseType: "postgres",
body: "SELECT 2 FROM ${table} /* postgres */",
sqlByDatabaseType: {
mysql: "SELECT 1 FROM ${table} /* mysql */",
postgres: "SELECT 2 FROM ${table} /* postgres */",
},
});
const cleared = clearSqlShortcutFormDatabaseTypes(start);
expect(cleared.databaseTypes).toEqual([]);
expect(cleared.sqlByDatabaseType).toEqual({});
expect(cleared.editingDatabaseType).toBe("");
expect(cleared.sql).toBe("SELECT 2 FROM ${table} /* postgres */");
expect(cleared.body).toBe("SELECT 2 FROM ${table} /* postgres */");
});
it("does not revive overrides when re-checking a database", () => {
const afterRemove = toggleSqlShortcutFormDatabaseType(
form({
databaseTypes: ["mysql"],
editingDatabaseType: "mysql",
body: "SELECT 1 FROM ${table} /* mysql */",
sqlByDatabaseType: { mysql: "SELECT 1 FROM ${table} /* mysql */" },
}),
"mysql",
);
expect(afterRemove.databaseTypes).toEqual([]);
expect(afterRemove.sqlByDatabaseType).toEqual({});
const reAdd = toggleSqlShortcutFormDatabaseType(afterRemove, "mysql");
expect(reAdd.databaseTypes).toEqual(["mysql"]);
expect(reAdd.sqlByDatabaseType.mysql).toBeUndefined();
expect(reAdd.body).toBe(afterRemove.sql);
});
it("applies current body to all selected databases and default sql", () => {
const applied = applySqlShortcutBodyToAllSelected(
form({
databaseTypes: ["mysql", "postgres"],
editingDatabaseType: "mysql",
body: "SELECT 9 FROM ${table}",
sqlByDatabaseType: { mysql: "SELECT 1 FROM ${table}" },
}),
);
expect(applied.sql).toBe("SELECT 9 FROM ${table}");
expect(applied.sqlByDatabaseType).toEqual({
mysql: "SELECT 9 FROM ${table}",
postgres: "SELECT 9 FROM ${table}",
});
});
});
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { resolveSqlShortcutTableToken } from "@/lib/sql/sqlShortcutTableTarget";
describe("resolveSqlShortcutTableToken", () => {
it("prefers a non-empty selection over the cursor identifier", () => {
const doc = "SELECT * FROM schema.orders WHERE id = 1";
const from = doc.indexOf("orders");
const to = from + "orders".length;
expect(
resolveSqlShortcutTableToken(doc, {
from,
to,
empty: false,
head: doc.indexOf("schema"),
}),
).toBe("orders");
});
it("uses the qualified identifier at the cursor when selection is empty", () => {
const doc = "SELECT * FROM schema.orders WHERE id = 1";
const head = doc.indexOf("orders") + 2;
expect(resolveSqlShortcutTableToken(doc, { from: head, to: head, empty: true, head })).toBe("schema.orders");
});
it("preserves original quotes in the document slice", () => {
const doc = 'SELECT * FROM "HR"."EMPLOYEES" WHERE 1=1';
const head = doc.indexOf("EMPLOYEES") + 1;
expect(resolveSqlShortcutTableToken(doc, { from: head, to: head, empty: true, head })).toBe('"HR"."EMPLOYEES"');
});
it("falls back to the previous character at a token boundary", () => {
const doc = "SELECT * FROM orders WHERE id = 1";
const head = doc.indexOf("orders") + "orders".length;
expect(resolveSqlShortcutTableToken(doc, { from: head, to: head, empty: true, head })).toBe("orders");
});
it("returns null on SQL keywords", () => {
const doc = "SELECT * FROM orders WHERE id = 1";
const head = doc.indexOf("WHERE") + 1;
expect(resolveSqlShortcutTableToken(doc, { from: head, to: head, empty: true, head })).toBeNull();
});
it("returns null when the cursor is not on an identifier", () => {
const doc = "SELECT * FROM orders WHERE id = 1";
const head = doc.indexOf("*");
expect(resolveSqlShortcutTableToken(doc, { from: head, to: head, empty: true, head })).toBeNull();
});
it("returns null for whitespace-only selection", () => {
const doc = "SELECT FROM orders";
expect(resolveSqlShortcutTableToken(doc, { from: 6, to: 8, empty: false, head: 7 })).toBeNull();
});
});