feat(editor): dialect-aware SQL quick actions with per-database templates
This commit is contained in:
1 parent
455117b8c5
commit
65b820e6a9
30 files changed
+1541
-150
No files matched your search
@@ -132,10 +132,14 @@ describe("QueryEditor execution routing", () => {
|
||||
|
||||
it("routes custom SQL shortcuts through selection-aware execution with dual keymap and DOM handlers", () => {
|
||||
expect(queryEditorSource).toContain("function runSqlShortcutAction(");
|
||||
expect(queryEditorSource).toContain("resolveSqlShortcutTemplate(action.sql, selected)");
|
||||
expect(queryEditorSource).toContain('if (queryEditorSelectionLanguage() !== "sql") return false;');
|
||||
expect(queryEditorSource).toContain("buildSqlShortcutExecutionSql(action, selected, props.databaseType)");
|
||||
expect(queryEditorSource).toContain("enabledSqlShortcutActions(settingsStore.editorSettings.sqlShortcuts)");
|
||||
expect(queryEditorSource).toContain("isCharacterProducingShortcut(action.shortcut)");
|
||||
expect(queryEditorSource).toContain("uniqueSqlShortcutBindings(sqlShortcutActions)");
|
||||
expect(queryEditorSource).toContain("resolveSqlShortcutForDatabase(settingsStore.editorSettings.sqlShortcuts, shortcut, props.databaseType)");
|
||||
expect(queryEditorSource).toContain("isCharacterProducingShortcut(shortcut)");
|
||||
expect(queryEditorSource).toContain("createQueryEditorSqlShortcutDomHandler(");
|
||||
expect(queryEditorSource).toContain("() => props.databaseType");
|
||||
expect(queryEditorSource).toContain("shouldBlockExecutionShortcut(event, currentView)");
|
||||
expect(queryEditorSource).toContain("if (props.readOnly) return true;");
|
||||
expect(queryEditorSource).toContain("settingsStore.editorSettings.sqlShortcuts");
|
||||
|
||||
@@ -47,7 +47,7 @@ describe("createQueryEditorSqlShortcutDomHandler", () => {
|
||||
|
||||
it("runs the action and prevents default when there is a selection", () => {
|
||||
const runAction = vi.fn(() => true);
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, "MacIntel");
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, undefined, "MacIntel");
|
||||
const event = keydownEvent({ key: "U", shiftKey: true });
|
||||
|
||||
expect(handler(event as unknown as KeyboardEvent, view)).toBe(true);
|
||||
@@ -58,7 +58,7 @@ describe("createQueryEditorSqlShortcutDomHandler", () => {
|
||||
|
||||
it("does not intercept when there is no selection", () => {
|
||||
const runAction = vi.fn(() => false);
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, "MacIntel");
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, undefined, "MacIntel");
|
||||
const event = keydownEvent({ key: "U", shiftKey: true });
|
||||
|
||||
expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);
|
||||
@@ -69,10 +69,38 @@ describe("createQueryEditorSqlShortcutDomHandler", () => {
|
||||
|
||||
it("ignores non character-producing shortcuts", () => {
|
||||
const runAction = vi.fn(() => true);
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Mod+Shift+9")], runAction, "MacIntel");
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Mod+Shift+9")], runAction, undefined, "MacIntel");
|
||||
const event = keydownEvent({ key: "9", metaKey: true, shiftKey: true });
|
||||
|
||||
expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);
|
||||
expect(runAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves the action for the active database type", () => {
|
||||
const runAction = vi.fn(() => true);
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(
|
||||
() => [action("mysql", "Shift+U", { databaseTypes: ["mysql"] }), action("sqlserver", "Shift+U", { databaseTypes: ["sqlserver"] })],
|
||||
runAction,
|
||||
() => "sqlserver",
|
||||
"MacIntel",
|
||||
);
|
||||
const event = keydownEvent({ key: "U", shiftKey: true });
|
||||
|
||||
expect(handler(event as unknown as KeyboardEvent, view)).toBe(true);
|
||||
expect(runAction).toHaveBeenCalledWith(expect.objectContaining({ id: "sqlserver" }), view, event);
|
||||
});
|
||||
|
||||
it("does not run a scoped action on an unrelated database", () => {
|
||||
const runAction = vi.fn(() => true);
|
||||
const handler = createQueryEditorSqlShortcutDomHandler(
|
||||
() => [action("mysql", "Shift+U", { databaseTypes: ["mysql"] })],
|
||||
runAction,
|
||||
() => "postgres",
|
||||
"MacIntel",
|
||||
);
|
||||
const event = keydownEvent({ key: "U", shiftKey: true });
|
||||
|
||||
expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);
|
||||
expect(runAction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+220
-13
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";
|
||||
import { parseShortcutParts } from "@/lib/editor/shortcutDisplay";
|
||||
import { enabledSqlShortcutActions } from "@/lib/sql/sqlShortcutActions";
|
||||
import type { SqlShortcutAction } from "@/types/database";
|
||||
import { resolveSqlShortcutForDatabase, uniqueSqlShortcutBindings } from "@/lib/sql/sqlShortcutActions";
|
||||
import type { DatabaseType, SqlShortcutAction } from "@/types/database";
|
||||
// pi-lens-ignore: typescript:2307
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
|
||||
@@ -16,11 +16,19 @@ export function isCharacterProducingShortcut(shortcut: string): boolean {
|
||||
return !modifiers.has("Mod") && !modifiers.has("Meta") && !modifiers.has("Ctrl") && !modifiers.has("Alt");
|
||||
}
|
||||
|
||||
export function createQueryEditorSqlShortcutDomHandler(getActions: () => readonly SqlShortcutAction[], runAction: (action: SqlShortcutAction, view: EditorView, event: KeyboardEvent) => boolean, platform = globalThis.navigator?.platform || ""): (event: KeyboardEvent, view: EditorView) => boolean {
|
||||
export function createQueryEditorSqlShortcutDomHandler(
|
||||
getActions: () => readonly SqlShortcutAction[],
|
||||
runAction: (action: SqlShortcutAction, view: EditorView, event: KeyboardEvent) => boolean,
|
||||
getDatabaseType?: () => DatabaseType | undefined,
|
||||
platform = globalThis.navigator?.platform || "",
|
||||
): (event: KeyboardEvent, view: EditorView) => boolean {
|
||||
return (event, view) => {
|
||||
for (const action of enabledSqlShortcutActions(getActions())) {
|
||||
if (!isCharacterProducingShortcut(action.shortcut)) continue;
|
||||
if (!matchesShortcut(event, action.shortcut, platform)) continue;
|
||||
const actions = getActions();
|
||||
for (const shortcut of uniqueSqlShortcutBindings(actions, platform)) {
|
||||
if (!isCharacterProducingShortcut(shortcut)) continue;
|
||||
if (!matchesShortcut(event, shortcut, platform)) continue;
|
||||
const action = resolveSqlShortcutForDatabase(actions, shortcut, getDatabaseType?.(), platform);
|
||||
if (!action) return false;
|
||||
if (!runAction(action, view, event)) return false;
|
||||
event.preventDefault();
|
||||
return true;
|
||||
|
||||
@@ -354,7 +354,17 @@ function isSqlSnippetItem(value: unknown): boolean {
|
||||
function isSqlShortcutActionItem(value: unknown): boolean {
|
||||
if (!isPlainObject(value)) return false;
|
||||
if (!isNonEmptyTrimmedString(value.id) || !isNonEmptyTrimmedString(value.label) || typeof value.shortcut !== "string" || typeof value.sql !== "string") return false;
|
||||
return value.enabled === undefined || typeof value.enabled === "boolean";
|
||||
if (value.enabled !== undefined && typeof value.enabled !== "boolean") return false;
|
||||
if (value.kind !== undefined && value.kind !== "template" && value.kind !== "select-limit") return false;
|
||||
if (value.limit !== undefined && (typeof value.limit !== "number" || !Number.isFinite(value.limit))) return false;
|
||||
if (value.databaseTypes !== undefined) {
|
||||
if (!Array.isArray(value.databaseTypes) || !value.databaseTypes.every((item) => typeof item === "string" && item.trim().length > 0)) return false;
|
||||
}
|
||||
if (value.sqlByDatabaseType !== undefined) {
|
||||
if (!isPlainObject(value.sqlByDatabaseType)) return false;
|
||||
if (!Object.values(value.sqlByDatabaseType).every((sql) => typeof sql === "string")) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const SHORTCUT_ACTION_IDS = new Set<string>(SHORTCUT_DEFINITIONS.map((definition) => definition.id));
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { DatabaseType } from "@/types/database";
|
||||
|
||||
/** Default row limit for built-in `sel` snippets. */
|
||||
export const DEFAULT_SELECT_ROW_LIMIT = 100;
|
||||
|
||||
/** Default row limit for SQL quick-action "select first N" kind. */
|
||||
export const DEFAULT_SQL_SHORTCUT_SELECT_LIMIT = 10;
|
||||
|
||||
export type SelectLimitStyle = "limit" | "top" | "first" | "fetch-first" | "rows" | "rownum";
|
||||
|
||||
const SELECT_LIMIT_STYLE_BY_DATABASE: Partial<Record<DatabaseType, SelectLimitStyle>> = {
|
||||
oracle: "rownum",
|
||||
"oceanbase-oracle": "rownum",
|
||||
oscar: "rownum",
|
||||
dameng: "rownum",
|
||||
db2: "fetch-first",
|
||||
sqlserver: "top",
|
||||
access: "top",
|
||||
iris: "top",
|
||||
teradata: "top",
|
||||
informix: "first",
|
||||
firebird: "rows",
|
||||
// Unknown JDBC dialects fall through to LIMIT (most common / safest default).
|
||||
// Known JDBC profiles are converted to their effective database type before
|
||||
// reaching the editor.
|
||||
};
|
||||
|
||||
export function selectLimitStyleForDatabase(databaseType?: DatabaseType): SelectLimitStyle {
|
||||
return databaseType ? (SELECT_LIMIT_STYLE_BY_DATABASE[databaseType] ?? "limit") : "limit";
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a dialect-aware `SELECT * FROM <table>` with a row limit.
|
||||
* `table` is inserted as-is (caller supplies quoting / `${table}` token).
|
||||
*/
|
||||
export function buildSelectStarWithLimitSql(table: string, limit: number, databaseType?: DatabaseType): string {
|
||||
const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_SELECT_ROW_LIMIT;
|
||||
const style = selectLimitStyleForDatabase(databaseType);
|
||||
switch (style) {
|
||||
case "top":
|
||||
return `SELECT TOP ${safeLimit} *\nFROM ${table}`;
|
||||
case "first":
|
||||
return `SELECT FIRST ${safeLimit} *\nFROM ${table}`;
|
||||
case "fetch-first":
|
||||
return `SELECT *\nFROM ${table}\nFETCH FIRST ${safeLimit} ROWS ONLY`;
|
||||
case "rows":
|
||||
return `SELECT *\nFROM ${table}\nROWS ${safeLimit}`;
|
||||
case "rownum":
|
||||
return `SELECT *\nFROM ${table}\nWHERE ROWNUM <= ${safeLimit}`;
|
||||
case "limit":
|
||||
return `SELECT *\nFROM ${table}\nLIMIT ${safeLimit}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Snippet bodies keep a trailing semicolon for insert-at-cursor UX.
|
||||
* An unknown JDBC driver may expose any SQL dialect, so the snippet stays
|
||||
* unbounded instead of guessing LIMIT; quick actions remain bounded via
|
||||
* `buildSelectStarWithLimitSql` regardless.
|
||||
*/
|
||||
export function buildSelectSnippetBody(databaseType?: DatabaseType, limit = DEFAULT_SELECT_ROW_LIMIT): string {
|
||||
if (databaseType === "jdbc") return "SELECT *\nFROM table;";
|
||||
return `${buildSelectStarWithLimitSql("table", limit, databaseType)};`;
|
||||
}
|
||||
@@ -1,23 +1,164 @@
|
||||
import { canonicalShortcutKey } from "@/lib/editor/shortcutDisplay";
|
||||
import { formatShortcut, SHORTCUT_DEFINITIONS, type ShortcutSettings } from "@/lib/editor/shortcutRegistry";
|
||||
import type { SqlShortcutAction } from "@/types/database";
|
||||
import { buildSelectStarWithLimitSql, DEFAULT_SQL_SHORTCUT_SELECT_LIMIT } from "@/lib/sql/sqlDialectSelectLimit";
|
||||
import type { DatabaseType, SqlShortcutAction, SqlShortcutKind } from "@/types/database";
|
||||
import { DATABASE_TYPES } from "@/types/generated/databaseTypes";
|
||||
|
||||
export const SQL_SHORTCUT_TABLE_TOKEN = "${table}";
|
||||
|
||||
export const BUILTIN_SQL_SHORTCUT_SELECT_LIMIT_ID = "builtin-select-limit";
|
||||
export const BUILTIN_SQL_SHORTCUT_COUNT_ID = "builtin-count";
|
||||
|
||||
const DATABASE_TYPE_SET = new Set<string>(DATABASE_TYPES);
|
||||
|
||||
/** Built-in quick actions shipped with empty / missing settings. */
|
||||
export const DEFAULT_SQL_SHORTCUTS: SqlShortcutAction[] = [
|
||||
{
|
||||
id: BUILTIN_SQL_SHORTCUT_SELECT_LIMIT_ID,
|
||||
label: "Select first N rows",
|
||||
shortcut: "Mod+Shift+1",
|
||||
kind: "select-limit",
|
||||
limit: DEFAULT_SQL_SHORTCUT_SELECT_LIMIT,
|
||||
sql: buildSelectStarWithLimitSql(SQL_SHORTCUT_TABLE_TOKEN, DEFAULT_SQL_SHORTCUT_SELECT_LIMIT),
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: BUILTIN_SQL_SHORTCUT_COUNT_ID,
|
||||
label: "Count rows",
|
||||
shortcut: "Mod+Shift+2",
|
||||
sql: `SELECT COUNT(*) AS row_count FROM ${SQL_SHORTCUT_TABLE_TOKEN}`,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
|
||||
export function isBuiltinSqlShortcut(id: string): boolean {
|
||||
return id === BUILTIN_SQL_SHORTCUT_SELECT_LIMIT_ID || id === BUILTIN_SQL_SHORTCUT_COUNT_ID;
|
||||
}
|
||||
|
||||
/** Append any missing built-in ids without overwriting user-edited entries. */
|
||||
export function mergeDefaultSqlShortcuts(actions: readonly SqlShortcutAction[]): SqlShortcutAction[] {
|
||||
const ids = new Set(actions.map((action) => action.id));
|
||||
const missing = DEFAULT_SQL_SHORTCUTS.filter((action) => !ids.has(action.id)).map((action) => ({ ...action }));
|
||||
return missing.length > 0 ? [...actions, ...missing] : [...actions];
|
||||
}
|
||||
|
||||
export function resolveSqlShortcutTemplate(template: string, selectedTable: string): string {
|
||||
return template.replace(/\$\{table\}/g, () => selectedTable.trim());
|
||||
}
|
||||
|
||||
export function normalizeSqlShortcutLimit(value: unknown, fallback = DEFAULT_SQL_SHORTCUT_SELECT_LIMIT): number {
|
||||
const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n) || n < 1) return fallback;
|
||||
return Math.min(Math.floor(n), 100_000);
|
||||
}
|
||||
|
||||
export function normalizeSqlShortcutKind(value: unknown): SqlShortcutKind {
|
||||
return value === "select-limit" ? "select-limit" : "template";
|
||||
}
|
||||
|
||||
export function normalizeSqlShortcutDatabaseTypes(value: unknown): DatabaseType[] | undefined {
|
||||
if (!Array.isArray(value) || value.length === 0) return undefined;
|
||||
const valid: DatabaseType[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of value) {
|
||||
if (typeof item !== "string" || !DATABASE_TYPE_SET.has(item) || seen.has(item)) continue;
|
||||
seen.add(item);
|
||||
valid.push(item as DatabaseType);
|
||||
}
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
}
|
||||
|
||||
export function normalizeSqlShortcutSqlByDatabaseType(value: unknown): Partial<Record<DatabaseType, string>> | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const result: Partial<Record<DatabaseType, string>> = {};
|
||||
for (const [key, sql] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (!DATABASE_TYPE_SET.has(key) || typeof sql !== "string") continue;
|
||||
result[key as DatabaseType] = sql;
|
||||
}
|
||||
return Object.keys(result).length > 0 ? result : undefined;
|
||||
}
|
||||
|
||||
/** When overrides exist without an explicit scope, treat override keys as the database scope. */
|
||||
export function deriveSqlShortcutDatabaseTypes(databaseTypes: DatabaseType[] | undefined, sqlByDatabaseType: Partial<Record<DatabaseType, string>> | undefined): DatabaseType[] | undefined {
|
||||
if (databaseTypes && databaseTypes.length > 0) return databaseTypes;
|
||||
if (!sqlByDatabaseType) return undefined;
|
||||
const derived = Object.keys(sqlByDatabaseType).filter((key): key is DatabaseType => DATABASE_TYPE_SET.has(key));
|
||||
return derived.length > 0 ? derived : undefined;
|
||||
}
|
||||
|
||||
export function resolveSqlShortcutBody(action: Pick<SqlShortcutAction, "sql" | "sqlByDatabaseType">, databaseType?: DatabaseType): string {
|
||||
if (databaseType && action.sqlByDatabaseType?.[databaseType] != null && action.sqlByDatabaseType[databaseType] !== "") {
|
||||
return action.sqlByDatabaseType[databaseType]!;
|
||||
}
|
||||
return action.sql;
|
||||
}
|
||||
|
||||
export function canonicalSqlShortcutSql(action: Pick<SqlShortcutAction, "kind" | "limit" | "sql">): string {
|
||||
if (normalizeSqlShortcutKind(action.kind) !== "select-limit") return action.sql;
|
||||
const limit = normalizeSqlShortcutLimit(action.limit);
|
||||
return buildSelectStarWithLimitSql(SQL_SHORTCUT_TABLE_TOKEN, limit);
|
||||
}
|
||||
|
||||
export function enabledSqlShortcutActions(actions: readonly SqlShortcutAction[]): SqlShortcutAction[] {
|
||||
return actions.filter((action) => action.enabled !== false && action.shortcut.trim().length > 0);
|
||||
}
|
||||
|
||||
function shortcutsUseSameKeys(first: string, second: string, platform = globalThis.navigator?.platform || ""): boolean {
|
||||
export function sqlShortcutAppliesToDatabase(action: Pick<SqlShortcutAction, "databaseTypes">, databaseType?: DatabaseType): boolean {
|
||||
const types = action.databaseTypes;
|
||||
if (!types || types.length === 0) return true;
|
||||
if (!databaseType) return false;
|
||||
return types.includes(databaseType);
|
||||
}
|
||||
|
||||
export function sqlShortcutDatabaseScopesOverlap(first?: readonly DatabaseType[], second?: readonly DatabaseType[]): boolean {
|
||||
const firstAll = !first || first.length === 0;
|
||||
const secondAll = !second || second.length === 0;
|
||||
if (firstAll || secondAll) return true;
|
||||
const secondSet = new Set(second);
|
||||
return first.some((dbType) => secondSet.has(dbType));
|
||||
}
|
||||
|
||||
export function shortcutsUseSameKeys(first: string, second: string, platform = globalThis.navigator?.platform || ""): boolean {
|
||||
if (!first || !second) return false;
|
||||
if (canonicalShortcutKey(first) === canonicalShortcutKey(second)) return true;
|
||||
return formatShortcut(first, platform).toLowerCase() === formatShortcut(second, platform).toLowerCase();
|
||||
}
|
||||
|
||||
export function uniqueSqlShortcutBindings(actions: readonly SqlShortcutAction[], platform = globalThis.navigator?.platform || ""): string[] {
|
||||
const bindings: string[] = [];
|
||||
for (const action of enabledSqlShortcutActions(actions)) {
|
||||
const shortcut = action.shortcut.trim();
|
||||
if (bindings.some((existing) => shortcutsUseSameKeys(existing, shortcut, platform))) continue;
|
||||
bindings.push(shortcut);
|
||||
}
|
||||
return bindings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer a scoped action over an all-databases action when both match the same key.
|
||||
*/
|
||||
export function resolveSqlShortcutForDatabase(actions: readonly SqlShortcutAction[], shortcut: string, databaseType?: DatabaseType, platform = globalThis.navigator?.platform || ""): SqlShortcutAction | undefined {
|
||||
const matches = enabledSqlShortcutActions(actions).filter((action) => shortcutsUseSameKeys(action.shortcut, shortcut, platform) && sqlShortcutAppliesToDatabase(action, databaseType));
|
||||
if (matches.length === 0) return undefined;
|
||||
matches.sort((a, b) => (b.databaseTypes?.length ?? 0) - (a.databaseTypes?.length ?? 0));
|
||||
return matches[0];
|
||||
}
|
||||
|
||||
export function buildSqlShortcutExecutionSql(action: SqlShortcutAction, selectedTable: string, databaseType?: DatabaseType): string {
|
||||
const table = selectedTable.trim();
|
||||
if (normalizeSqlShortcutKind(action.kind) === "select-limit") {
|
||||
return buildSelectStarWithLimitSql(table, normalizeSqlShortcutLimit(action.limit), databaseType);
|
||||
}
|
||||
return resolveSqlShortcutTemplate(resolveSqlShortcutBody(action, databaseType), table);
|
||||
}
|
||||
|
||||
export function sqlShortcutDisplaySql(action: SqlShortcutAction, databaseType?: DatabaseType): string {
|
||||
if (normalizeSqlShortcutKind(action.kind) === "select-limit") {
|
||||
return buildSelectStarWithLimitSql(SQL_SHORTCUT_TABLE_TOKEN, normalizeSqlShortcutLimit(action.limit), databaseType);
|
||||
}
|
||||
return resolveSqlShortcutBody(action, databaseType);
|
||||
}
|
||||
|
||||
export function findSqlShortcutConflicts(actions: readonly SqlShortcutAction[], fixedShortcuts: ShortcutSettings, platform = globalThis.navigator?.platform || ""): string[] {
|
||||
const conflicts = new Set<string>();
|
||||
const editorFixedShortcuts = SHORTCUT_DEFINITIONS.filter((item) => item.scope === "editor" || item.scope === "global");
|
||||
@@ -25,7 +166,7 @@ export function findSqlShortcutConflicts(actions: readonly SqlShortcutAction[],
|
||||
for (const action of actions) {
|
||||
if (action.enabled === false || !action.shortcut.trim()) continue;
|
||||
|
||||
const duplicate = actions.find((other) => other.id !== action.id && other.enabled !== false && other.shortcut.trim() && shortcutsUseSameKeys(other.shortcut, action.shortcut, platform));
|
||||
const duplicate = actions.find((other) => other.id !== action.id && other.enabled !== false && other.shortcut.trim() && shortcutsUseSameKeys(other.shortcut, action.shortcut, platform) && sqlShortcutDatabaseScopesOverlap(action.databaseTypes, other.databaseTypes));
|
||||
if (duplicate) {
|
||||
conflicts.add(action.id);
|
||||
conflicts.add(duplicate.id);
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { DatabaseType } from "@/types/database";
|
||||
|
||||
/** In-dialog state for custom SQL shortcut bodies (fallback + per-DB overrides). */
|
||||
export type SqlShortcutFormBodies = {
|
||||
/** Default fallback template persisted as payload.sql */
|
||||
sql: string;
|
||||
/** Textarea content for the current editing context */
|
||||
body: string;
|
||||
databaseTypes: DatabaseType[];
|
||||
sqlByDatabaseType: Partial<Record<DatabaseType, string>>;
|
||||
editingDatabaseType: DatabaseType | "";
|
||||
};
|
||||
|
||||
/** Stage the current textarea into the override map (scoped) or default sql (all-databases). */
|
||||
export function flushSqlShortcutEditingBody(form: SqlShortcutFormBodies): SqlShortcutFormBodies {
|
||||
if (!form.editingDatabaseType) {
|
||||
return { ...form, sql: form.body, sqlByDatabaseType: { ...form.sqlByDatabaseType } };
|
||||
}
|
||||
return {
|
||||
...form,
|
||||
sqlByDatabaseType: { ...form.sqlByDatabaseType, [form.editingDatabaseType]: form.body },
|
||||
};
|
||||
}
|
||||
|
||||
/** Flush current body, then load textarea for another selected database. */
|
||||
export function switchSqlShortcutEditingDatabaseType(form: SqlShortcutFormBodies, next: DatabaseType): SqlShortcutFormBodies {
|
||||
const flushed = flushSqlShortcutEditingBody(form);
|
||||
return {
|
||||
...flushed,
|
||||
editingDatabaseType: next,
|
||||
body: flushed.sqlByDatabaseType[next] ?? flushed.sql,
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleSqlShortcutFormDatabaseType(form: SqlShortcutFormBodies, dbType: DatabaseType): SqlShortcutFormBodies {
|
||||
const flushed = flushSqlShortcutEditingBody(form);
|
||||
const removing = flushed.databaseTypes.includes(dbType);
|
||||
const nextTypes = removing ? flushed.databaseTypes.filter((item) => item !== dbType) : [...flushed.databaseTypes, dbType];
|
||||
const sqlByDatabaseType = { ...flushed.sqlByDatabaseType };
|
||||
|
||||
if (removing) {
|
||||
delete sqlByDatabaseType[dbType];
|
||||
}
|
||||
|
||||
if (nextTypes.length === 0) {
|
||||
// Last scoped DB removed → same as "all databases": keep visible text as the only sql.
|
||||
const body = flushed.editingDatabaseType === dbType || !flushed.editingDatabaseType ? flushed.body : (sqlByDatabaseType[flushed.editingDatabaseType] ?? flushed.body);
|
||||
return {
|
||||
...flushed,
|
||||
databaseTypes: [],
|
||||
sqlByDatabaseType: {},
|
||||
editingDatabaseType: "",
|
||||
sql: body,
|
||||
body,
|
||||
};
|
||||
}
|
||||
|
||||
let editingDatabaseType = flushed.editingDatabaseType;
|
||||
if (!editingDatabaseType || !nextTypes.includes(editingDatabaseType)) {
|
||||
editingDatabaseType = nextTypes[0]!;
|
||||
}
|
||||
|
||||
return {
|
||||
...flushed,
|
||||
databaseTypes: nextTypes,
|
||||
sqlByDatabaseType,
|
||||
editingDatabaseType,
|
||||
body: sqlByDatabaseType[editingDatabaseType] ?? flushed.sql,
|
||||
sql: flushed.sql,
|
||||
};
|
||||
}
|
||||
|
||||
/** Switch back to all-databases: wipe overrides, keep currently visible text as sql. */
|
||||
export function clearSqlShortcutFormDatabaseTypes(form: SqlShortcutFormBodies): SqlShortcutFormBodies {
|
||||
const flushed = flushSqlShortcutEditingBody(form);
|
||||
const body = flushed.editingDatabaseType && flushed.sqlByDatabaseType[flushed.editingDatabaseType] != null ? flushed.sqlByDatabaseType[flushed.editingDatabaseType]! : flushed.body;
|
||||
return {
|
||||
...flushed,
|
||||
databaseTypes: [],
|
||||
sqlByDatabaseType: {},
|
||||
editingDatabaseType: "",
|
||||
sql: body,
|
||||
body,
|
||||
};
|
||||
}
|
||||
|
||||
/** Copy current textarea to every selected DB override and the default sql. */
|
||||
export function applySqlShortcutBodyToAllSelected(form: SqlShortcutFormBodies): SqlShortcutFormBodies {
|
||||
if (form.databaseTypes.length === 0) {
|
||||
return { ...form, sql: form.body, sqlByDatabaseType: {} };
|
||||
}
|
||||
const sqlByDatabaseType: Partial<Record<DatabaseType, string>> = {};
|
||||
for (const dbType of form.databaseTypes) {
|
||||
sqlByDatabaseType[dbType] = form.body;
|
||||
}
|
||||
return {
|
||||
...form,
|
||||
sql: form.body,
|
||||
sqlByDatabaseType,
|
||||
};
|
||||
}
|
||||
|
||||
/** Persistable bodies: default sql + overrides only for still-selected databases. */
|
||||
export function buildSqlShortcutBodiesForSave(form: SqlShortcutFormBodies): {
|
||||
sql: string;
|
||||
databaseTypes?: DatabaseType[];
|
||||
sqlByDatabaseType?: Partial<Record<DatabaseType, string>>;
|
||||
} {
|
||||
const flushed = flushSqlShortcutEditingBody(form);
|
||||
if (flushed.databaseTypes.length === 0) {
|
||||
return { sql: flushed.body };
|
||||
}
|
||||
const sqlByDatabaseType: Partial<Record<DatabaseType, string>> = {};
|
||||
for (const dbType of flushed.databaseTypes) {
|
||||
const override = flushed.sqlByDatabaseType[dbType];
|
||||
if (override != null) sqlByDatabaseType[dbType] = override;
|
||||
}
|
||||
return {
|
||||
sql: flushed.sql,
|
||||
databaseTypes: [...flushed.databaseTypes],
|
||||
...(Object.keys(sqlByDatabaseType).length > 0 ? { sqlByDatabaseType } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { extractQualifiedIdentifierAt, isSqlKeyword } from "@/lib/sql/sqlNavigation";
|
||||
|
||||
export type SqlShortcutTableSelection = {
|
||||
from: number;
|
||||
to: number;
|
||||
empty: boolean;
|
||||
/** Cursor / selection head used when selection is empty. */
|
||||
head: number;
|
||||
};
|
||||
|
||||
function identifierAtCursor(doc: string, pos: number): { start: number; end: number } | null {
|
||||
let located = extractQualifiedIdentifierAt(doc, pos);
|
||||
// CodeMirror can report the boundary immediately after the token.
|
||||
if (!located && pos > 0) located = extractQualifiedIdentifierAt(doc, pos - 1);
|
||||
if (!located || located.parts.length === 0) return null;
|
||||
const last = located.parts[located.parts.length - 1]!;
|
||||
if (!last.quoted && isSqlKeyword(last.value)) return null;
|
||||
return { start: located.start, end: located.end };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the `${table}` token for SQL quick actions:
|
||||
* non-empty selection wins; otherwise use the qualified identifier under the cursor
|
||||
* (preserving original quotes and dots from the document).
|
||||
*/
|
||||
export function resolveSqlShortcutTableToken(doc: string, selection: SqlShortcutTableSelection): string | null {
|
||||
if (!selection.empty) {
|
||||
const selected = doc.slice(selection.from, selection.to).trim();
|
||||
return selected.length > 0 ? selected : null;
|
||||
}
|
||||
const located = identifierAtCursor(doc, selection.head);
|
||||
if (!located) return null;
|
||||
const token = doc.slice(located.start, located.end).trim();
|
||||
return token.length > 0 ? token : null;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { buildSelectSnippetBody, DEFAULT_SELECT_ROW_LIMIT } from "@/lib/sql/sqlDialectSelectLimit";
|
||||
import type { DatabaseType, SqlSnippet } from "@/types/database";
|
||||
|
||||
const DEFAULT_SELECT_ROW_LIMIT = 100;
|
||||
|
||||
/**
|
||||
* Built-in SQL snippets shared by database types.
|
||||
*
|
||||
@@ -129,48 +128,9 @@ interface BuiltinSqlSnippetRule {
|
||||
buildBody: BuiltinSqlSnippetBodyBuilder;
|
||||
}
|
||||
|
||||
type SelectSnippetLimitStyle = "limit" | "top" | "first" | "fetch-first" | "rows" | "rownum" | "unbounded";
|
||||
|
||||
const SELECT_SNIPPET_LIMIT_STYLE_BY_DATABASE: Partial<Record<DatabaseType, SelectSnippetLimitStyle>> = {
|
||||
oracle: "rownum",
|
||||
"oceanbase-oracle": "rownum",
|
||||
oscar: "rownum",
|
||||
dameng: "rownum",
|
||||
db2: "fetch-first",
|
||||
sqlserver: "top",
|
||||
access: "top",
|
||||
iris: "top",
|
||||
teradata: "top",
|
||||
informix: "first",
|
||||
firebird: "rows",
|
||||
// An unknown JDBC driver may expose any SQL dialect. Known JDBC profiles are
|
||||
// converted to their effective database type before reaching the editor.
|
||||
jdbc: "unbounded",
|
||||
};
|
||||
|
||||
const PARENTHESIZED_ADD_COLUMN_DATABASES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "yashandb", "xugu", "dameng", "iris", "informix"]);
|
||||
const ADD_COLUMN_WITHOUT_COLUMN_KEYWORD_DATABASES = new Set<DatabaseType>(["sqlserver", "kingbase", "cassandra", "teradata"]);
|
||||
|
||||
function buildSelectSnippetBody(databaseType?: DatabaseType): string {
|
||||
const style = databaseType ? (SELECT_SNIPPET_LIMIT_STYLE_BY_DATABASE[databaseType] ?? "limit") : "limit";
|
||||
switch (style) {
|
||||
case "top":
|
||||
return `SELECT TOP ${DEFAULT_SELECT_ROW_LIMIT} *\nFROM table;`;
|
||||
case "first":
|
||||
return `SELECT FIRST ${DEFAULT_SELECT_ROW_LIMIT} *\nFROM table;`;
|
||||
case "fetch-first":
|
||||
return `SELECT *\nFROM table\nFETCH FIRST ${DEFAULT_SELECT_ROW_LIMIT} ROWS ONLY;`;
|
||||
case "rows":
|
||||
return `SELECT *\nFROM table\nROWS ${DEFAULT_SELECT_ROW_LIMIT};`;
|
||||
case "rownum":
|
||||
return `SELECT *\nFROM table\nWHERE ROWNUM <= ${DEFAULT_SELECT_ROW_LIMIT};`;
|
||||
case "unbounded":
|
||||
return "SELECT *\nFROM table;";
|
||||
case "limit":
|
||||
return `SELECT *\nFROM table\nLIMIT ${DEFAULT_SELECT_ROW_LIMIT};`;
|
||||
}
|
||||
}
|
||||
|
||||
function buildUpdateSnippetBody(databaseType?: DatabaseType): string {
|
||||
if (databaseType === "clickhouse") {
|
||||
return "ALTER TABLE table\nUPDATE column = value\nWHERE condition;";
|
||||
|
||||
Reference in new issue
Block a user