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): prompt for Oracle & substitution variables before execution (#12634)

lxk9557ef31a1aa6a3
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 17f296526c..6916fac0a6 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -272,7 +272,7 @@ import { currentExecutableStatementRange, type SqlTextRange } from "@/lib/sql/sq
import { executableStatementRangeCacheForDoc, executableStatementRangeStartingAt, type ExecutableStatementRangeCache } from "@/lib/sql/executableStatementRangeCache";
import { EMPTY_TABLE_COLUMN_TEMPLATE_DATA_TYPE, parseTableColumnTemplateFields, TABLE_COLUMN_TEMPLATE_DATABASE_TYPES, tableColumnTemplateRowsToSettings } from "@/lib/table/tableColumnTemplates";
import {
- DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES,
+ isModeDependentSubstitutionDatabase,
normalizeSqlVariableSyntaxOverrides,
resolveSqlVariableSyntaxToggles,
SQL_VARIABLE_SYNTAX_DATABASE_TYPES,
@@ -280,6 +280,7 @@ import {
SQL_VARIABLE_SYNTAX_TOKENS,
type SqlVariableSyntaxOverrides,
type SqlVariableSyntaxToggles,
+ updateSqlVariableSyntaxToggle,
} from "@/lib/sql/sqlVariableSyntax";
import {
buildMcpCherryStudioConfig,
@@ -359,6 +360,7 @@ import {
import { applyEditorSettingsDraftToRefs, type EditorSettingsDraftRefMap } from "@/lib/settings/applyEditorSettingsDraft";
import { serializeSettingsTransfer, sortTransferCategories, transferCategoryForKey, type SettingsTransferCategoryId } from "@/lib/settings/settingsTransfer";
import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
import { usePromptTemplateStore } from "@/stores/promptTemplateStore";
@@ -432,6 +434,7 @@ const { draft: editHistoryRetentionLimit, loaded: historyRetentionLoaded, loadin
const { draft: editMcpHistoryRetentionLimit, loaded: mcpHistoryRetentionLoaded, loading: mcpHistoryRetentionLoading, saving: mcpHistoryRetentionSaving, loadError: mcpHistoryRetentionLoadError } = mcpHistoryRetention;
const mcpHistoryCleanupLoading = ref(false);
const connectionStore = useConnectionStore();
+const queryStore = useQueryStore();
const hasSqlServerConnection = computed(() => connectionStore.connections.some((connection) => effectiveDatabaseTypeForConnection(connection) === "sqlserver"));
const savedSqlStore = useSavedSqlStore();
const promptTemplateStore = usePromptTemplateStore();
@@ -901,32 +904,56 @@ function updateExternalSqlEditorMaxMbInput(event: Event) {
editExternalSqlEditorMaxMb.value = normalized;
}
+const currentSqlVariableSyntaxCompatibilityMode = computed<string | undefined>(() => {
+ const dbType = editSqlVariableSyntaxDatabaseType.value;
+ if (!isModeDependentSubstitutionDatabase(dbType)) return undefined;
+
+ const activeTab = queryStore.tabs.find((tab) => tab.id === queryStore.activeTabId);
+ if (activeTab?.connectionId) {
+ const activeConn = connectionStore.getConfig(activeTab.connectionId);
+ const connDbType = activeConn ? (effectiveDatabaseTypeForConnection(activeConn) ?? activeConn.db_type) : undefined;
+ if (connDbType === dbType) {
+ if (dbType === "opengauss" || dbType === "gaussdb") {
+ return connectionStore.databaseCompatibilityMode(activeTab.connectionId, activeTab.database || activeConn?.database);
+ }
+ if (dbType === "kingbase") {
+ return activeConn?.database_info?.compatibilityMode;
+ }
+ }
+ }
+
+ if (connectionStore.activeConnectionId) {
+ const activeConn = connectionStore.getConfig(connectionStore.activeConnectionId);
+ const connDbType = activeConn ? (effectiveDatabaseTypeForConnection(activeConn) ?? activeConn.db_type) : undefined;
+ if (activeConn && connDbType === dbType) {
+ if (dbType === "opengauss" || dbType === "gaussdb") {
+ return connectionStore.databaseCompatibilityMode(activeConn.id, activeConn.database);
+ }
+ if (dbType === "kingbase") {
+ return activeConn.database_info?.compatibilityMode;
+ }
+ }
+ }
+
+ const conn = connectionStore.connections.find((c) => (effectiveDatabaseTypeForConnection(c) ?? c.db_type) === dbType);
+ if (conn) {
+ if (dbType === "opengauss" || dbType === "gaussdb") {
+ return connectionStore.databaseCompatibilityMode(conn.id, conn.database);
+ }
+ if (dbType === "kingbase") {
+ return conn.database_info?.compatibilityMode;
+ }
+ }
+
+ return undefined;
+});
+
function sqlVariableSyntaxToggle(key: keyof SqlVariableSyntaxToggles): boolean {
- return resolveSqlVariableSyntaxToggles(editSqlVariableSyntaxOverrides.value, editSqlVariableSyntaxDatabaseType.value)[key];
+ return resolveSqlVariableSyntaxToggles(editSqlVariableSyntaxOverrides.value, editSqlVariableSyntaxDatabaseType.value, true, currentSqlVariableSyntaxCompatibilityMode.value)[key];
}
function setSqlVariableSyntaxToggle(key: keyof SqlVariableSyntaxToggles, value: boolean) {
- const dbType = editSqlVariableSyntaxDatabaseType.value;
- if ((dbType === "neo4j" || dbType === "nebula") && key === "named") return;
- const merged: SqlVariableSyntaxToggles = {
- ...DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES,
- ...editSqlVariableSyntaxOverrides.value[dbType],
- [key]: value,
- };
- const next: SqlVariableSyntaxOverrides = {
- ...editSqlVariableSyntaxOverrides.value,
- };
- // Keep storage sparse: an all-enabled type has no entry; otherwise persist only the disabled syntaxes.
- if (SQL_VARIABLE_SYNTAX_KEYS.every((toggleKey) => merged[toggleKey])) {
- delete next[dbType];
- } else {
- const partial: Partial<SqlVariableSyntaxToggles> = {};
- for (const toggleKey of SQL_VARIABLE_SYNTAX_KEYS) {
- if (!merged[toggleKey]) partial[toggleKey] = false;
- }
- next[dbType] = partial;
- }
- editSqlVariableSyntaxOverrides.value = next;
+ editSqlVariableSyntaxOverrides.value = updateSqlVariableSyntaxToggle(editSqlVariableSyntaxOverrides.value, editSqlVariableSyntaxDatabaseType.value, key, value, currentSqlVariableSyntaxCompatibilityMode.value);
}
const tableColumnTemplateSectionRef = ref<HTMLElement | null>(null);
const draggedTableColumnTemplateRowId = ref<string | null>(null);
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index f9936228cf..da6fe144d1 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -260,10 +260,11 @@ const kingbaseConfig = computed(() => (props.databaseType === "kingbase" && prop
const kingbaseSqlType = computed(() => kingbaseSqlDatabaseType(kingbaseConfig.value));
function sqlStatementParameterOptions() {
- const toggles = resolveSqlVariableSyntaxToggles(settingsStore.editorSettings.sqlVariableSyntaxOverrides, props.databaseType, settingsStore.editorSettings.sqlVariableSubstitutionEnabled);
+ const compatibilityMode = props.databaseType === "opengauss" ? connectionStore.databaseCompatibilityMode(props.connectionId, props.database) : kingbaseConfig.value?.database_info?.compatibilityMode;
+ const toggles = resolveSqlVariableSyntaxToggles(settingsStore.editorSettings.sqlVariableSyntaxOverrides, props.databaseType, settingsStore.editorSettings.sqlVariableSubstitutionEnabled, compatibilityMode);
return {
databaseType: kingbaseSqlType.value ?? props.databaseType,
- compatibilityMode: props.databaseType === "opengauss" ? connectionStore.databaseCompatibilityMode(props.connectionId, props.database) : kingbaseConfig.value?.database_info?.compatibilityMode,
+ compatibilityMode,
enabledSyntaxes: enabledSqlParameterSyntaxes(toggles),
};
}
diff --git a/apps/desktop/src/components/editor/SqlParameterDialog.vue b/apps/desktop/src/components/editor/SqlParameterDialog.vue
index 4f9894a56d..0e1d7274fd 100644
--- a/apps/desktop/src/components/editor/SqlParameterDialog.vue
+++ b/apps/desktop/src/components/editor/SqlParameterDialog.vue
@@ -48,6 +48,7 @@ const syntaxLabels: Record<SqlParameterSyntax, string> = {
shell: "${name}",
mybatis: "#{name}",
sqlserver: "@name",
+ substitution: "&name",
};
function syntaxLabel(parameter: SqlParameterDescriptor): string {
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.sqlVariableSyntax.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.sqlVariableSyntax.integration.spec.ts
new file mode 100644
index 0000000000..e29da51923
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.sqlVariableSyntax.integration.spec.ts
@@ -0,0 +1,400 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createPinia, setActivePinia } from "pinia";
+import { useSettingsStore, DEFAULT_EDITOR_SETTINGS, DEFAULT_DESKTOP_SETTINGS } from "@/stores/settingsStore";
+import { useConnectionStore, type ConnectionConfig } from "@/stores/connectionStore";
+import { useQueryStore, type QueryTab } from "@/stores/queryStore";
+import { useHistoryStore } from "@/stores/historyStore";
+import { useSqlExecution } from "@/composables/useSqlExecution";
+import { computed } from "vue";
+
+vi.mock("vue-i18n", async () => {
+ const { ref } = await import("vue");
+ const locale = ref("en");
+ const t = (key: string) => key;
+ return {
+ createI18n: () => ({ global: { t, locale }, install: () => undefined }),
+ useI18n: () => ({ t, locale }),
+ };
+});
+
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const passthrough = defineComponent({
+ setup(_props, { slots }) {
+ return () => h("div", slots.default?.());
+ },
+ });
+ return {
+ Dialog: defineComponent({
+ props: { open: { type: Boolean, default: false } },
+ setup:
+ (props, { slots }) =>
+ () =>
+ props.open ? h("div", slots.default?.()) : null,
+ }),
+ DialogContent: passthrough,
+ DialogFooter: passthrough,
+ DialogHeader: passthrough,
+ DialogTitle: passthrough,
+ };
+});
+
+vi.mock("@/components/ui/button", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Button: defineComponent({
+ inheritAttrs: false,
+ setup(props, { attrs, slots }) {
+ return () => h("button", { ...attrs, disabled: (props as { disabled?: boolean }).disabled ? true : undefined }, slots.default?.());
+ },
+ props: { disabled: { type: Boolean, default: false } },
+ }),
+ };
+});
+
+vi.mock("@/components/ui/switch", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Switch: defineComponent({
+ props: { id: String, modelValue: Boolean, disabled: Boolean },
+ emits: ["update:modelValue"],
+ setup(props, { emit }) {
+ return () =>
+ h("button", {
+ id: props.id,
+ role: "switch",
+ "aria-checked": props.modelValue,
+ disabled: props.disabled,
+ onClick: () => emit("update:modelValue", !props.modelValue),
+ });
+ },
+ }),
+ };
+});
+
+let selectEmitMap = new Map<string, (val: any) => void>();
+
+vi.mock("@/components/ui/select", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Select = defineComponent({
+ props: { modelValue: { type: [String, Number], default: "" } },
+ emits: ["update:modelValue"],
+ setup(props, { emit, slots }) {
+ selectEmitMap.set("current", (val) => emit("update:modelValue", val));
+ return () => h("div", { "data-select-value": props.modelValue }, slots.default?.());
+ },
+ });
+ const passthrough = defineComponent({
+ setup(_props, { slots }) {
+ return () => h("div", slots.default?.());
+ },
+ });
+ const SelectItem = defineComponent({
+ props: { value: String },
+ setup(props, { slots }) {
+ return () =>
+ h(
+ "button",
+ {
+ "data-item-value": props.value,
+ onClick: () => selectEmitMap.get("current")?.(props.value),
+ },
+ slots.default?.(),
+ );
+ },
+ });
+ return {
+ Select,
+ SelectContent: passthrough,
+ SelectItem,
+ SelectTrigger: passthrough,
+ SelectValue: passthrough,
+ };
+});
+
+vi.mock("@/components/settings/ChangelogPanel.vue", async () => {
+ const { defineComponent } = await import("vue");
+ return { default: defineComponent({ setup: () => () => null }) };
+});
+
+const hoisted = vi.hoisted(() => ({
+ savedEditorSettings: [] as any[],
+}));
+
+vi.mock("@/lib/backend/api", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/backend/api")>();
+ return {
+ ...actual,
+ loadEditorSettings: async () => null,
+ saveEditorSettings: async (settings: any) => {
+ hoisted.savedEditorSettings.push(JSON.parse(JSON.stringify(settings)));
+ },
+ loadHistoryRetentionLimit: async () => 5000,
+ loadMcpHistoryRetentionLimit: async () => 5000,
+ loadMcpGlobalPolicy: async () => null,
+ loadDesktopSettings: async () => null,
+ loadAiConfigs: async () => [],
+ loadAiConfig: async () => null,
+ loadAiProviderConfigs: async () => ({}),
+ loadAiChatSelection: async () => null,
+ webdavSyncSecretsStatus: async () => ({}),
+ webdavPasswordStatus: async () => ({}),
+ snippetTokenStatus: async () => ({ hasSavedToken: false }),
+ snippetPassphraseStatus: async () => ({ hasSavedPassphrase: false }),
+ snippetSavedTokenStatus: async () => ({}),
+ snippetSyncSettings: async () => ({}),
+ getAppSupportInfo: async () => {
+ throw new Error("unavailable in tests");
+ },
+ listInstalledAgentsLocal: async () => [],
+ checkMcpServerStatus: async () => {
+ throw new Error("unavailable in tests");
+ },
+ };
+});
+
+import EditorSettingsDialog from "../EditorSettingsDialog.vue";
+
+if (!("ResizeObserver" in globalThis)) {
+ (globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ };
+}
+
+const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
+
+afterEach(() => {
+ for (const { app, host } of mountedApps.splice(0)) {
+ app.unmount();
+ host.remove();
+ }
+ document.body.innerHTML = "";
+});
+
+async function settle() {
+ for (let i = 0; i < 10; i++) {
+ await nextTick();
+ await Promise.resolve();
+ }
+}
+
+function connection(id: string, db_type: any): ConnectionConfig {
+ return {
+ id,
+ name: id,
+ db_type,
+ host: "127.0.0.1",
+ port: 5432,
+ user: "postgres",
+ database: "demo",
+ save_password: false,
+ };
+}
+
+function queryTab(id: string, connectionId: string, databaseType: any, sql: string): QueryTab {
+ return {
+ id,
+ title: id,
+ query: sql,
+ sql,
+ connectionId,
+ databaseType,
+ database: "demo",
+ isExecuting: false,
+ historyIndex: 0,
+ history: [],
+ };
+}
+
+describe("EditorSettingsDialog SQL variable syntax integration", () => {
+ beforeEach(() => {
+ hoisted.savedEditorSettings = [];
+ });
+
+ it("openGauss: previously saved substitution=false -> UI toggles shell=false in B mode -> preserves substitution=false -> executes in A mode without parameter prompt", async () => {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+
+ const settingsStore = useSettingsStore();
+ const connectionStore = useConnectionStore();
+ const queryStore = useQueryStore();
+
+ // 1. Initial state: user previously saved opengauss.substitution = false
+ settingsStore.editorSettings = {
+ ...DEFAULT_EDITOR_SETTINGS,
+ sqlVariableSyntaxOverrides: {
+ opengauss: { substitution: false },
+ },
+ };
+ settingsStore.desktopSettings = { ...DEFAULT_DESKTOP_SETTINGS };
+
+ // 2. Active connection is openGauss in B mode
+ const conn = connection("conn-og-b", "opengauss");
+ connectionStore.connections = [conn];
+ connectionStore.activeConnectionId = conn.id;
+ const tab = queryTab("tab-1", conn.id, "opengauss", "SELECT * FROM t WHERE col = &var;");
+ queryStore.tabs = [tab];
+ queryStore.activeTabId = tab.id;
+
+ const modeSpy = vi.spyOn(connectionStore, "databaseCompatibilityMode").mockReturnValue("B");
+
+ // 3. Mount EditorSettingsDialog on the 'editor' tab
+ const host = document.createElement("div");
+ document.body.append(host);
+ const app = createApp(
+ defineComponent({
+ setup: () => () => h(EditorSettingsDialog, { variant: "page", open: true, initialTab: "editor", "onUpdate:open": () => undefined }),
+ }),
+ );
+ app.use(pinia);
+ app.mount(host);
+ mountedApps.push({ app, host });
+ await settle();
+
+ // 4. In the dialog, select openGauss
+ const ogOption = host.querySelector<HTMLButtonElement>('[data-item-value="opengauss"]');
+ expect(ogOption).toBeTruthy();
+ ogOption!.click();
+ await settle();
+
+ // Switch the shell toggle to false
+ const shellSwitch = host.querySelector<HTMLButtonElement>("#sql-var-syntax-shell");
+ expect(shellSwitch).toBeTruthy();
+ shellSwitch!.click();
+ await settle();
+
+ // 5. Click the Apply button
+ const applyBtn = [...host.querySelectorAll<HTMLButtonElement>("button")].find((b) => b.textContent?.trim() === "settings.apply");
+ expect(applyBtn).toBeTruthy();
+ expect(applyBtn!.disabled).toBe(false);
+ applyBtn!.click();
+ await settle();
+
+ // 6. Verify persistence: substitution: false was preserved alongside shell: false!
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.opengauss).toEqual({
+ substitution: false,
+ shell: false,
+ });
+
+ // 7. Execution in A mode: active connection mode is switched to A mode
+ modeSpy.mockReturnValue("A");
+ const activeTab = ref<QueryTab | undefined>(tab);
+ const activeConnection = ref<ConnectionConfig | undefined>(conn);
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+
+ const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
+ if (activeTab.value) activeTab.value.result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+
+ const execution = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => tab.sql),
+ activeOutputView,
+ });
+ await execution.tryExecute();
+
+ // Must NOT prompt parameter dialog because substitution: false was preserved!
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(executeCurrentSql).toHaveBeenCalledWith(tab.sql, expect.anything());
+ });
+
+ it("Kingbase: previously saved substitution=false -> UI toggles shell=false in pg mode -> preserves substitution=false -> executes in oracle mode without parameter prompt", async () => {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+
+ const settingsStore = useSettingsStore();
+ const connectionStore = useConnectionStore();
+ const queryStore = useQueryStore();
+
+ // 1. Initial state: user previously saved kingbase.substitution = false
+ settingsStore.editorSettings = {
+ ...DEFAULT_EDITOR_SETTINGS,
+ sqlVariableSyntaxOverrides: {
+ kingbase: { substitution: false },
+ },
+ };
+ settingsStore.desktopSettings = { ...DEFAULT_DESKTOP_SETTINGS };
+
+ // 2. Active connection is Kingbase in pg mode
+ const conn: ConnectionConfig = {
+ ...connection("conn-kb-pg", "kingbase"),
+ database_info: { compatibilityMode: "pg" },
+ };
+ connectionStore.connections = [conn];
+ connectionStore.activeConnectionId = conn.id;
+ const tab = queryTab("tab-kb", conn.id, "kingbase", "SELECT * FROM t WHERE col = &var;");
+ queryStore.tabs = [tab];
+ queryStore.activeTabId = tab.id;
+
+ // 3. Mount EditorSettingsDialog on the 'editor' tab
+ const host = document.createElement("div");
+ document.body.append(host);
+ const app = createApp(
+ defineComponent({
+ setup: () => () => h(EditorSettingsDialog, { variant: "page", open: true, initialTab: "editor", "onUpdate:open": () => undefined }),
+ }),
+ );
+ app.use(pinia);
+ app.mount(host);
+ mountedApps.push({ app, host });
+ await settle();
+
+ // 4. Select Kingbase
+ const kbOption = host.querySelector<HTMLButtonElement>('[data-item-value="kingbase"]');
+ expect(kbOption).toBeTruthy();
+ kbOption!.click();
+ await settle();
+
+ // Toggle shell switch
+ const shellSwitch = host.querySelector<HTMLButtonElement>("#sql-var-syntax-shell");
+ expect(shellSwitch).toBeTruthy();
+ shellSwitch!.click();
+ await settle();
+
+ // 5. Apply
+ const applyBtn = [...host.querySelectorAll<HTMLButtonElement>("button")].find((b) => b.textContent?.trim() === "settings.apply");
+ expect(applyBtn).toBeTruthy();
+ expect(applyBtn!.disabled).toBe(false);
+ applyBtn!.click();
+ await settle();
+
+ // 6. Verify persistence: substitution: false was preserved!
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.kingbase).toEqual({
+ substitution: false,
+ shell: false,
+ });
+
+ // 7. Execution in oracle mode
+ const oracleConn: ConnectionConfig = {
+ ...conn,
+ database_info: { compatibilityMode: "oracle" },
+ };
+ const activeTab = ref<QueryTab | undefined>(tab);
+ const activeConnection = ref<ConnectionConfig | undefined>(oracleConn);
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+
+ const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
+ if (activeTab.value) activeTab.value.result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+
+ const execution = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => tab.sql),
+ activeOutputView,
+ });
+ await execution.tryExecute();
+
+ // Must NOT prompt parameter dialog!
+ expect(execution.showSqlParameterDialog.value).toBe(false);
+ expect(executeCurrentSql).toHaveBeenCalledWith(tab.sql, expect.anything());
+ });
+});
diff --git a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
index dbc61e1fd3..fc940fefff 100644
--- a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
@@ -11,6 +11,7 @@ import { createQueryEditorExecutionViewportOwnership } from "@/lib/editor/queryE
import * as objectMetadataCache from "@/lib/metadata/objectMetadataCache";
import type { ConnectionConfig, QueryTab } from "@/types/database";
import { formatSqlText } from "@/lib/sql/sqlFormatter";
+import { normalizeSqlVariableSyntaxOverrides, updateSqlVariableSyntaxToggle } from "@/lib/sql/sqlVariableSyntax";
import type { SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget";
vi.mock("vue-i18n", () => ({
@@ -2202,6 +2203,259 @@ SELECT @value AS Message;`;
await pendingExecution;
expect(executeCurrentSql).toHaveBeenCalledTimes(1);
});
+
+ describe("mode-dependent substitution variable prompt overrides", () => {
+ it("openGauss A-mode disables substitution -> saved/reloaded -> does not prompt parameter dialog on &var", async () => {
+ const sql = "SELECT * FROM t WHERE col = &var;";
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("demo"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection("opengauss"));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const queryStore = useQueryStore();
+ const connectionStore = useConnectionStore();
+ const settingsStore = useSettingsStore();
+
+ connectionStore.connections = [activeConnection.value!];
+ queryStore.tabs = [activeTab.value!];
+ queryStore.activeTabId = activeTab.value!.id;
+ const modeSpy = vi.spyOn(connectionStore, "databaseCompatibilityMode").mockReturnValue("A");
+
+ const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
+ if (activeTab.value) activeTab.value.result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+
+ // Verify that by default in A-mode, &var triggers parameter prompt
+ const defaultExecution = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sql),
+ activeOutputView,
+ });
+ await defaultExecution.tryExecute();
+ expect(defaultExecution.showSqlParameterDialog.value).toBe(true);
+ expect(defaultExecution.sqlParameterNames.value.map((p) => p.name)).toEqual(["var"]);
+
+ // User disables substitution for openGauss in settings UI
+ const initialOverrides = updateSqlVariableSyntaxToggle({}, "opengauss", "substitution", false, "A");
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: initialOverrides,
+ });
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.opengauss?.substitution).toBe(false);
+
+ // Realistic settings interaction while connected to B-mode:
+ // The current connection is in B-mode, where substitution defaults to false.
+ // User only toggles shell=false in settings.
+ modeSpy.mockReturnValue("B");
+ const toggledInB = updateSqlVariableSyntaxToggle(settingsStore.editorSettings.sqlVariableSyntaxOverrides, "opengauss", "shell", false, "B");
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: toggledInB,
+ });
+ // The explicit false substitution override must NOT be dropped, even though current mode was B
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.opengauss).toEqual({
+ substitution: false,
+ shell: false,
+ });
+
+ // Switch back to A-mode and execute -> must NOT prompt parameter dialog
+ modeSpy.mockReturnValue("A");
+ 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).toHaveBeenCalledWith(sql, expect.anything());
+ });
+
+ it("Kingbase Oracle mode disables substitution -> UI toggles shell in pg mode -> reloads in oracle mode -> does not prompt parameter dialog on &var", async () => {
+ const sql = "SELECT * FROM t WHERE col = &var;";
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("demo"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>({
+ ...connection("kingbase"),
+ database_info: { compatibilityMode: "oracle" },
+ });
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const queryStore = useQueryStore();
+ const connectionStore = useConnectionStore();
+ const settingsStore = useSettingsStore();
+
+ connectionStore.connections = [activeConnection.value!];
+ queryStore.tabs = [activeTab.value!];
+ queryStore.activeTabId = activeTab.value!.id;
+
+ const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
+ if (activeTab.value) activeTab.value.result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+
+ // Verify that by default in Kingbase oracle mode, &var triggers parameter prompt
+ const defaultExecution = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sql),
+ activeOutputView,
+ });
+ await defaultExecution.tryExecute();
+ expect(defaultExecution.showSqlParameterDialog.value).toBe(true);
+
+ // User disables substitution for Kingbase in settings UI
+ const initialOverrides = updateSqlVariableSyntaxToggle({}, "kingbase", "substitution", false, "oracle");
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: initialOverrides,
+ });
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.kingbase?.substitution).toBe(false);
+
+ // Realistic settings interaction while connected to pg mode:
+ // Current connection is in pg mode (where substitution defaults to false).
+ // User only toggles shell=false in settings.
+ activeConnection.value = {
+ ...activeConnection.value!,
+ database_info: { compatibilityMode: "pg" },
+ };
+ const toggledInPg = updateSqlVariableSyntaxToggle(settingsStore.editorSettings.sqlVariableSyntaxOverrides, "kingbase", "shell", false, "pg");
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: toggledInPg,
+ });
+ // Explicit substitution: false must NOT be dropped
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.kingbase).toEqual({
+ substitution: false,
+ shell: false,
+ });
+
+ // Switch back to oracle mode and execute -> must NOT prompt parameter dialog
+ activeConnection.value = {
+ ...activeConnection.value!,
+ database_info: { compatibilityMode: "oracle" },
+ };
+ 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).toHaveBeenCalledWith(sql, expect.anything());
+ });
+
+ it("Kingbase explicitly enables substitution -> UI toggles shell in oracle mode -> executes in pg mode -> prompts parameter dialog on &var", async () => {
+ const sql = "SELECT * FROM t WHERE col = &var;";
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("demo"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>({
+ ...connection("kingbase"),
+ database_info: { compatibilityMode: "oracle" },
+ });
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const queryStore = useQueryStore();
+ const connectionStore = useConnectionStore();
+ const settingsStore = useSettingsStore();
+
+ connectionStore.connections = [activeConnection.value!];
+ queryStore.tabs = [activeTab.value!];
+ queryStore.activeTabId = activeTab.value!.id;
+
+ const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
+ if (activeTab.value) activeTab.value.result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+
+ // User explicitly enables substitution for Kingbase (sets substitution=true)
+ const initialOverrides = updateSqlVariableSyntaxToggle({}, "kingbase", "substitution", true, "oracle");
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: initialOverrides,
+ });
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.kingbase?.substitution).toBe(true);
+
+ // While in oracle mode (where substitution default is already true), user toggles shell=false
+ const toggledInOracle = updateSqlVariableSyntaxToggle(settingsStore.editorSettings.sqlVariableSyntaxOverrides, "kingbase", "shell", false, "oracle");
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: toggledInOracle,
+ });
+ // Explicit substitution: true must be preserved
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.kingbase).toEqual({
+ substitution: true,
+ shell: false,
+ });
+
+ // Switch to pg mode (where default is false) and execute -> MUST prompt parameter dialog because explicit true was preserved
+ activeConnection.value = {
+ ...activeConnection.value!,
+ database_info: { compatibilityMode: "pg" },
+ };
+ const execution = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sql),
+ activeOutputView,
+ });
+ await execution.tryExecute();
+ expect(execution.showSqlParameterDialog.value).toBe(true);
+ expect(execution.sqlParameterNames.value.map((p) => p.name)).toEqual(["var"]);
+ expect(executeCurrentSql).not.toHaveBeenCalled();
+ });
+
+ it("PostgreSQL bitwise & and array overlap && do not prompt by default, but prompt when explicitly enabled", async () => {
+ const sqlBitwise = "SELECT flags &mask FROM t;";
+ const sqlArrayOverlap = "SELECT a &&b FROM t;";
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("public"), sql: sqlBitwise });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection("postgres"));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ const queryStore = useQueryStore();
+ const connectionStore = useConnectionStore();
+ const settingsStore = useSettingsStore();
+
+ connectionStore.connections = [activeConnection.value!];
+ queryStore.tabs = [activeTab.value!];
+ queryStore.activeTabId = activeTab.value!.id;
+
+ const executeCurrentSql = vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {
+ if (activeTab.value) activeTab.value.result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+
+ // Default: no prompt for PostgreSQL bitwise &
+ const executionBitwise = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sqlBitwise),
+ activeOutputView,
+ });
+ await executionBitwise.tryExecute();
+ expect(executionBitwise.showSqlParameterDialog.value).toBe(false);
+
+ // Default: no prompt for PostgreSQL array overlap &&
+ activeTab.value = { ...queryTab("public"), sql: sqlArrayOverlap };
+ const executionArray = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sqlArrayOverlap),
+ activeOutputView,
+ });
+ await executionArray.tryExecute();
+ expect(executionArray.showSqlParameterDialog.value).toBe(false);
+
+ // Explicitly enable substitution for postgres
+ settingsStore.updateEditorSettings({
+ sqlVariableSyntaxOverrides: normalizeSqlVariableSyntaxOverrides({ postgres: { substitution: true } }),
+ });
+ expect(settingsStore.editorSettings.sqlVariableSyntaxOverrides.postgres?.substitution).toBe(true);
+
+ const sqlWithVar = "SELECT * FROM t WHERE col = &var;";
+ activeTab.value = { ...queryTab("public"), sql: sqlWithVar };
+ const executionExplicit = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sqlWithVar),
+ activeOutputView,
+ });
+ await executionExplicit.tryExecute();
+ expect(executionExplicit.showSqlParameterDialog.value).toBe(true);
+ expect(executionExplicit.sqlParameterNames.value.map((p) => p.name)).toEqual(["var"]);
+ expect(executeCurrentSql).toHaveBeenCalledTimes(2);
+ });
+ });
});
describe("snapshotResultForMerge", () => {
diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.ts
index a14ab9b09d..f509e5466c 100644
--- a/apps/desktop/src/composables/useSqlExecution.ts
+++ b/apps/desktop/src/composables/useSqlExecution.ts
@@ -426,10 +426,12 @@ export function useSqlExecution(deps: {
function prepareSqlParameterDialog(sql: string, sourceOffset?: number, options: SqlExecutionOptions = {}, continuation?: (sql: string, sourceOffset?: number) => Promise<void> | void): boolean {
const connection = resolveExecutionConnection(options.tabId);
const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection?.db_type;
- const toggles = resolveSqlVariableSyntaxToggles(settingsStore.editorSettings.sqlVariableSyntaxOverrides, databaseType, settingsStore.editorSettings.sqlVariableSubstitutionEnabled);
+ const tab = resolveExecutionTab(options.tabId);
+ const compatibilityMode = databaseType === "opengauss" ? (tab ? connectionStore.databaseCompatibilityMode(tab.connectionId, tab.database) : undefined) : databaseType === "kingbase" ? connection?.database_info?.compatibilityMode : undefined;
+ const toggles = resolveSqlVariableSyntaxToggles(settingsStore.editorSettings.sqlVariableSyntaxOverrides, databaseType, settingsStore.editorSettings.sqlVariableSubstitutionEnabled, compatibilityMode);
const enabledSyntaxes = enabledSqlParameterSyntaxes(toggles);
const parameterDatabaseType = kingbaseSqlDatabaseType(connection) ?? databaseType;
- const parameters = extractSqlParameterDescriptors(sql, { databaseType: parameterDatabaseType, enabledSyntaxes });
+ const parameters = extractSqlParameterDescriptors(sql, { databaseType: parameterDatabaseType, compatibilityMode, enabledSyntaxes });
if (!parameters.length) {
return false;
}
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index c2795159fc..22c96299a8 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -8184,6 +8184,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "MyBatis üslublu yer tutucuları əvəz etmək üçün dəyər soruş.",
sqlVariableSyntax_sqlserver: "SQL Server üslublu yer tutucu",
sqlVariableSyntax_sqlserverDescription: "SQL Server üslublu yer tutucuları əvəz etmək üçün dəyər soruş (sessiya dəyişənləri ilə toqquşa bilər).",
+ sqlVariableSyntax_substitution: "Əvəzetmə dəyişəni",
+ sqlVariableSyntax_substitutionDescription: "Oracle üslublu əvəzetmə dəyişənlərini (&name və &&name) əvəz etmək üçün dəyər soruş.",
sqlVariableSyntax_atSet: "Sətirdaxili dəyişənlərin açılması",
sqlVariableSyntax_atSetDescription: "İşlətməzdən əvvəl sətirdaxili dəyişən elanlarını aç və dəyərlərini yerinə qoy.",
tableCompletionSchemaQualification: "Cədvəl tamamlamasında sxem ixtisaslaşdırması",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index a945987ad5..53f11a7470 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -9891,6 +9891,8 @@ export default {
sqlVariableSyntax_mybatisDescription: "Prompt for a value to substitute MyBatis-style placeholders.",
sqlVariableSyntax_sqlserver: "SQL Server-style placeholder",
sqlVariableSyntax_sqlserverDescription: "Prompt for a value to substitute SQL Server-style placeholders (may collide with session variables).",
+ sqlVariableSyntax_substitution: "Substitution variable",
+ sqlVariableSyntax_substitutionDescription: "Prompt for a value to substitute Oracle-style substitution variables (&name and &&name).",
sqlVariableSyntax_atSet: "Inline variable expansion",
sqlVariableSyntax_atSetDescription: "Expand inline variable declarations and substitute their values before running.",
tableCompletionSchemaQualification: "Schema qualification for table completion",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 6ce3e2d27c..c8b558239b 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -8848,6 +8848,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "Solicita un valor para sustituir los marcadores de estilo MyBatis.",
sqlVariableSyntax_sqlserver: "Marcador estilo SQL Server",
sqlVariableSyntax_sqlserverDescription: "Solicita un valor para sustituir los marcadores de estilo SQL Server (pueden entrar en conflicto con variables de sesión).",
+ sqlVariableSyntax_substitution: "Variable de sustitución",
+ sqlVariableSyntax_substitutionDescription: "Solicita un valor para sustituir variables de sustitución estilo Oracle (&name y &&name).",
sqlVariableSyntax_atSet: "Expansión de variables en línea",
sqlVariableSyntax_atSetDescription: "Expande las declaraciones de variables en línea y sustituye sus valores antes de ejecutar.",
tableCompletionSchemaQualification: "Calificación de esquema al completar tablas",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 5461b52a2e..f0157a30fd 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8992,6 +8992,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "Minta nilai untuk mensubstitusi placeholder bergaya MyBatis.",
sqlVariableSyntax_sqlserver: "Placeholder bergaya SQL Server",
sqlVariableSyntax_sqlserverDescription: "Minta nilai untuk mensubstitusi placeholder bergaya SQL Server (dapat bertabrakan dengan variabel sesi).",
+ sqlVariableSyntax_substitution: "Variabel substitusi",
+ sqlVariableSyntax_substitutionDescription: "Minta nilai untuk mensubstitusi variabel substitusi bergaya Oracle (&name dan &&name).",
sqlVariableSyntax_atSet: "Ekspansi variabel inline",
sqlVariableSyntax_atSetDescription: "Perluas deklarasi variabel inline dan substitusi nilainya sebelum dijalankan.",
tableCompletionSchemaQualification: "Kualifikasi skema untuk pelengkapan tabel",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 9f0986c93e..56800e80ba 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -8611,6 +8611,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "Richiede un valore per sostituire i segnaposto in stile MyBatis.",
sqlVariableSyntax_sqlserver: "Segnaposto stile SQL Server",
sqlVariableSyntax_sqlserverDescription: "Richiede un valore per sostituire i segnaposto in stile SQL Server (possono entrare in conflitto con le variabili di sessione).",
+ sqlVariableSyntax_substitution: "Variabile di sostituzione",
+ sqlVariableSyntax_substitutionDescription: "Richiede un valore per sostituire le variabili di sostituzione in stile Oracle (&name e &&name).",
sqlVariableSyntax_atSet: "Espansione di variabili inline",
sqlVariableSyntax_atSetDescription: "Espande le dichiarazioni di variabili inline e ne sostituisce i valori prima dell'esecuzione.",
tableCompletionSchemaQualification: "Qualificazione dello schema nel completamento tabelle",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 7f5050cdee..c3bcb3cb45 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -8608,6 +8608,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "MyBatis 形式プレースホルダーを置き換える値の入力を求めます。",
sqlVariableSyntax_sqlserver: "SQL Server 形式プレースホルダー",
sqlVariableSyntax_sqlserverDescription: "SQL Server 形式プレースホルダーを置き換える値の入力を求めます(セッション変数と競合する場合があります)。",
+ sqlVariableSyntax_substitution: "置換変数",
+ sqlVariableSyntax_substitutionDescription: "Oracle 形式の置換変数(&name および &&name)を置き換える値の入力を求めます。",
sqlVariableSyntax_atSet: "インライン変数展開",
sqlVariableSyntax_atSetDescription: "実行前にインライン変数宣言を展開し、その値をインライン化します。",
tableCompletionSchemaQualification: "テーブル補完のスキーマ修飾",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 77b2e53f97..d9d2d212fe 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -8603,6 +8603,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "MyBatis 스타일 자리표시자를 치환할 값을 입력하라는 메시지를 표시합니다.",
sqlVariableSyntax_sqlserver: "SQL Server 스타일 자리표시자",
sqlVariableSyntax_sqlserverDescription: "SQL Server 스타일 자리표시자를 치환할 값을 입력하라는 메시지를 표시합니다 (세션 변수와 충돌할 수 있음).",
+ sqlVariableSyntax_substitution: "치환 변수",
+ sqlVariableSyntax_substitutionDescription: "Oracle 스타일 치환 변수(&name 및 &&name)를 치환할 값을 입력하라는 메시지를 표시합니다.",
sqlVariableSyntax_atSet: "인라인 변수 확장",
sqlVariableSyntax_atSetDescription: "실행 전에 인라인 변수 선언을 확장하고 값을 치환합니다.",
tableCompletionSchemaQualification: "테이블 완성 스키마 한정",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 1a3a1eddb2..f6fa5862f5 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -9030,6 +9030,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "Pytaj o wartość do podstawienia dla symboli zastępczych w stylu MyBatis.",
sqlVariableSyntax_sqlserver: "Symbol zastępczy w stylu SQL Server",
sqlVariableSyntax_sqlserverDescription: "Pytaj o wartość dla symboli zastępczych w stylu SQL Server (może kolidować ze zmiennymi sesyjnymi).",
+ sqlVariableSyntax_substitution: "Zmienna podstawiania",
+ sqlVariableSyntax_substitutionDescription: "Pytaj o wartość dla zmiennych podstawiania w stylu Oracle (&name i &&name).",
sqlVariableSyntax_atSet: "Rozwijanie zmiennych w linii",
sqlVariableSyntax_atSetDescription: "Rozwijaj deklaracje zmiennych w kodzie i podstawiaj ich wartości przed uruchomieniem.",
tableCompletionSchemaQualification: "Kwalifikacja schematu przy uzupełnianiu tabel",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 3c64ca876d..6382ae9ae4 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -8609,6 +8609,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "Solicita um valor para substituir os espaços reservados de estilo MyBatis.",
sqlVariableSyntax_sqlserver: "Espaço reservado estilo SQL Server",
sqlVariableSyntax_sqlserverDescription: "Solicita um valor para substituir os espaços reservados de estilo SQL Server (podem colidir com variáveis de sessão).",
+ sqlVariableSyntax_substitution: "Variável de substituição",
+ sqlVariableSyntax_substitutionDescription: "Solicita um valor para substituir variáveis de substituição estilo Oracle (&name e &&name).",
sqlVariableSyntax_atSet: "Expansão de variáveis inline",
sqlVariableSyntax_atSetDescription: "Expande as declarações de variáveis inline e substitui seus valores antes de executar.",
tableCompletionSchemaQualification: "Qualificação de schema no autocompletar de tabelas",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 27c49a7877..b0134f479e 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -10074,6 +10074,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "Запрашивать значение для подстановки заполнителей в стиле MyBatis.",
sqlVariableSyntax_sqlserver: "Заполнитель в стиле SQL Server",
sqlVariableSyntax_sqlserverDescription: "Запрашивать значение для подстановки заполнителей в стиле SQL Server (может конфликтовать с переменными сеанса).",
+ sqlVariableSyntax_substitution: "Переменная подстановки",
+ sqlVariableSyntax_substitutionDescription: "Запрашивать значение для подстановки переменных подстановки в стиле Oracle (&name и &&name).",
sqlVariableSyntax_atSet: "Раскрытие встроенных переменных",
sqlVariableSyntax_atSetDescription: "Раскрывать встроенные объявления переменных и подставлять их значения перед выполнением.",
tableCompletionSchemaQualification: "Указание схемы при автодополнении таблиц",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 7c6fadfa19..222815d1cd 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -10503,6 +10503,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "ขอค่าเพื่อแทนที่ Placeholder แบบ MyBatis",
sqlVariableSyntax_sqlserver: "Placeholder แบบ SQL Server",
sqlVariableSyntax_sqlserverDescription: "ขอค่าเพื่อแทนที่ Placeholder แบบ SQL Server (อาจชนกับตัวแปรเซสชัน)",
+ sqlVariableSyntax_substitution: "ตัวแปรแทนที่",
+ sqlVariableSyntax_substitutionDescription: "ขอค่าเพื่อแทนที่ตัวแปรแทนที่แบบ Oracle (&name และ &&name)",
sqlVariableSyntax_atSet: "ขยายตัวแปรแบบ Inline",
sqlVariableSyntax_atSetDescription: "ขยายการประกาศตัวแปรแบบ Inline และแทนค่าก่อนเรียกใช้",
tableCompletionSchemaQualification: "ระบุ Schema สำหรับการเติมตาราง",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index f5e0e802c5..e699284619 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -8082,6 +8082,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "MyBatis biçemli yer tutucuları değiştirmek için değer sor.",
sqlVariableSyntax_sqlserver: "SQL Server biçemli yer tutucu",
sqlVariableSyntax_sqlserverDescription: "SQL Server biçemli yer tutucuları değiştirmek için değer sor (oturum değişkenleriyle çakışabilir).",
+ sqlVariableSyntax_substitution: "Değiştirme değişkeni",
+ sqlVariableSyntax_substitutionDescription: "Oracle biçemli değiştirme değişkenlerini (&name ve &&name) değiştirmek için değer sor.",
sqlVariableSyntax_atSet: "Satır içi değişken genişletme",
sqlVariableSyntax_atSetDescription: "Satır içi değişken bildirimlerini genişlet ve çalıştırmadan önce değerlerini yerine koy.",
tableCompletionSchemaQualification: "Tablo tamamlamasında şema nitelemesi",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f4223e218a..e1d426866b 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -9855,6 +9855,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "为 MyBatis 风格占位符提示输入替换值。",
sqlVariableSyntax_sqlserver: "SQL Server 风格占位符",
sqlVariableSyntax_sqlserverDescription: "为 SQL Server 风格占位符提示输入替换值(可能与会话变量冲突)。",
+ sqlVariableSyntax_substitution: "替换变量",
+ sqlVariableSyntax_substitutionDescription: "为 Oracle 风格替换变量(&name 与 &&name)提示输入替换值。",
sqlVariableSyntax_atSet: "内联变量展开",
sqlVariableSyntax_atSetDescription: "执行前展开内联变量声明并就地代入其值。",
tableCompletionSchemaQualification: "SQL 表补全的模式限定",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index cb9d7c7ab7..af8435bf4b 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7953,6 +7953,8 @@ export default withEnglishFallback({
sqlVariableSyntax_mybatisDescription: "為 MyBatis 風格佔位符提示輸入替換值。",
sqlVariableSyntax_sqlserver: "SQL Server 風格佔位符",
sqlVariableSyntax_sqlserverDescription: "為 SQL Server 風格佔位符提示輸入替換值(可能與工作階段變數衝突)。",
+ sqlVariableSyntax_substitution: "替換變數",
+ sqlVariableSyntax_substitutionDescription: "為 Oracle 風格替換變數(&name 與 &&name)提示輸入替換值。",
sqlVariableSyntax_atSet: "內聯變數展開",
sqlVariableSyntax_atSetDescription: "執行前展開內聯變數宣告並就地代入其值。",
tableCompletionSchemaQualification: "SQL 資料表補全的結構描述限定",
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
index d279ea52fa..c5c325b5f3 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
@@ -631,13 +631,14 @@ describe("extractSqlParameters", () => {
});
it("describes each placeholder syntax for the parameter dialog", () => {
- const sql = "select ? as a, :named as b, ${shell_name} as c, #{mybatis_name} as d, @sql_server_name as e";
- expect(extractSqlParameterDescriptors(sql)).toEqual([
+ const sql = "select ? as a, :named as b, ${shell_name} as c, #{mybatis_name} as d, @sql_server_name as e, &substitution_name as f";
+ expect(extractSqlParameterDescriptors(sql, { databaseType: "oracle" })).toEqual([
{ key: "?1", name: "?1", syntax: "positional", token: "?" },
{ key: "named", name: "named", syntax: "named", token: ":named" },
{ key: "shell_name", name: "shell_name", syntax: "shell", token: "${shell_name}" },
{ key: "mybatis_name", name: "mybatis_name", syntax: "mybatis", token: "#{mybatis_name}" },
{ key: "sql_server_name", name: "sql_server_name", syntax: "sqlserver", token: "@sql_server_name" },
+ { key: "substitution_name", name: "substitution_name", syntax: "substitution", token: "&substitution_name" },
]);
});
@@ -1572,6 +1573,137 @@ describe("enabledSyntaxes option", () => {
});
});
+describe("Oracle substitution variables", () => {
+ const oracleOptions = { databaseType: "oracle" as const };
+
+ it("extracts single and double ampersand substitution variables in Oracle", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept_id AND mgr_dept = &&dept_id";
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual(["dept_id"]);
+ expect(extractSqlParameterDescriptors(sql, oracleOptions)).toEqual([{ key: "dept_id", name: "dept_id", syntax: "substitution", token: "&dept_id" }]);
+ });
+
+ it("extracts positional numeric substitution variables in Oracle", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &1 AND job_id = &&2";
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual(["1", "2"]);
+ expect(extractSqlParameterDescriptors(sql, oracleOptions)).toEqual([
+ { key: "1", name: "1", syntax: "substitution", token: "&1" },
+ { key: "2", name: "2", syntax: "substitution", token: "&&2" },
+ ]);
+ });
+
+ it("handles optional dot terminator on substitution variables in Oracle", () => {
+ const sql = "SELECT * FROM &table_name. WHERE id = 1";
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual(["table_name"]);
+ expect(extractSqlParameterDescriptors(sql, oracleOptions)).toEqual([{ key: "table_name", name: "table_name", syntax: "substitution", token: "&table_name." }]);
+ expect(substituteSqlParameters(sql, { table_name: { kind: "raw", value: "employees" } }, oracleOptions)).toBe("SELECT * FROM employees WHERE id = 1");
+ });
+
+ it("handles double dot for schema and table concatenation in Oracle", () => {
+ const sql = "SELECT * FROM &schema..table_name";
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual(["schema"]);
+ expect(extractSqlParameterDescriptors(sql, oracleOptions)).toEqual([{ key: "schema", name: "schema", syntax: "substitution", token: "&schema." }]);
+ expect(substituteSqlParameters(sql, { schema: { kind: "raw", value: "hr" } }, oracleOptions)).toBe("SELECT * FROM hr.table_name");
+ });
+
+ it("extracts and replaces quoted substitution variables in Oracle", () => {
+ const sql = "SELECT * FROM emp WHERE ename = '&ename' AND job = '&job.' AND dept = '&&dept'";
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual(["ename", "job", "dept"]);
+ expect(extractSqlParameterDescriptors(sql, oracleOptions)).toEqual([
+ { key: "ename", name: "ename", syntax: "substitution", token: "'&ename'" },
+ { key: "job", name: "job", syntax: "substitution", token: "'&job.'" },
+ { key: "dept", name: "dept", syntax: "substitution", token: "'&&dept'" },
+ ]);
+ expect(
+ substituteSqlParameters(
+ sql,
+ {
+ ename: { kind: "string", value: "O'Brien" },
+ job: { kind: "string", value: "CLERK" },
+ dept: { kind: "string", value: "SALES" },
+ },
+ oracleOptions,
+ ),
+ ).toBe("SELECT * FROM emp WHERE ename = 'O''Brien' AND job = 'CLERK' AND dept = 'SALES'");
+ });
+
+ it("does not falsely treat ordinary ampersands as substitution variables in Oracle", () => {
+ const sql = "SELECT 'Tom & Jerry' as a, 'AT&T' as b, flags & 1 as c, array1 && array2 as d, id &lt; 10 as e FROM dual";
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual([]);
+ });
+
+ it("ignores substitution variables in line and block comments in Oracle", () => {
+ const sql = `
+ -- &comment_var
+ /* &block_var */
+ SELECT * FROM emp WHERE id = &real_var
+ `;
+ expect(extractSqlParameters(sql, oracleOptions)).toEqual(["real_var"]);
+ });
+
+ it("substitutes various parameter kinds for substitution variables in Oracle", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept AND ename = &name AND active = &active";
+ expect(
+ substituteSqlParameters(
+ sql,
+ {
+ dept: { kind: "number", value: "10" },
+ name: { kind: "string", value: "KING" },
+ active: { kind: "boolean", value: "true" },
+ },
+ oracleOptions,
+ ),
+ ).toBe("SELECT * FROM emp WHERE deptno = 10 AND ename = 'KING' AND active = TRUE");
+ });
+
+ it.each(["oracle", "oceanbase-oracle", "dameng", "yashandb", "oscar"] as const)("defaults substitution variables to enabled for %s", (databaseType) => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept_id AND code = '&code'";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["dept_id", "code"]);
+ });
+
+ it("enables substitution variables by default for openGauss in A mode but disables in PG mode", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept_id";
+ expect(extractSqlParameters(sql, { databaseType: "opengauss", compatibilityMode: "A" })).toEqual(["dept_id"]);
+ expect(extractSqlParameters(sql, { databaseType: "opengauss", compatibilityMode: "PG" })).toEqual([]);
+ });
+
+ it("enables substitution variables by default for Kingbase in oracle mode but disables in pg mode", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept_id";
+ expect(extractSqlParameters(sql, { databaseType: "kingbase", compatibilityMode: "oracle" })).toEqual(["dept_id"]);
+ expect(extractSqlParameters(sql, { databaseType: "kingbase", compatibilityMode: "pg" })).toEqual([]);
+ });
+
+ it("disables substitution variables by default when databaseType is undefined or non-Oracle", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept_id";
+ expect(extractSqlParameters(sql)).toEqual([]);
+ expect(extractSqlParameters(sql, { databaseType: "mysql" })).toEqual([]);
+ });
+
+ it("does not treat PostgreSQL bitwise & or array overlap && as substitution variables", () => {
+ expect(extractSqlParameters("SELECT flags &mask FROM t", { databaseType: "postgres" })).toEqual([]);
+ expect(extractSqlParameters("SELECT flags & 1 FROM t", { databaseType: "postgres" })).toEqual([]);
+ expect(extractSqlParameters("SELECT a &&b FROM t", { databaseType: "postgres" })).toEqual([]);
+ expect(extractSqlParameters("SELECT array1 && array2 FROM t", { databaseType: "postgres" })).toEqual([]);
+ });
+
+ it("does not treat SQL Server bitwise & as substitution variables", () => {
+ expect(extractSqlParameters("SELECT flags &mask FROM t", { databaseType: "sqlserver" })).toEqual([]);
+ expect(extractSqlParameters("SELECT flags & 1 FROM t", { databaseType: "sqlserver" })).toEqual([]);
+ });
+
+ it("respects enabledSyntaxes toggle for substitution syntax across database types", () => {
+ const sql = "SELECT * FROM emp WHERE deptno = &dept AND id = :id";
+ // Oracle with substitution explicitly excluded
+ expect(extractSqlParameters(sql, { databaseType: "oracle", enabledSyntaxes: ["named"] })).toEqual(["id"]);
+ // PostgreSQL with substitution explicitly included
+ expect(extractSqlParameters(sql, { databaseType: "postgres", enabledSyntaxes: ["substitution"] })).toEqual(["dept"]);
+ expect(extractSqlParameters("SELECT flags &mask FROM t", { databaseType: "postgres", enabledSyntaxes: ["substitution"] })).toEqual(["mask"]);
+ expect(extractSqlParameters("SELECT a &&b FROM t", { databaseType: "postgres", enabledSyntaxes: ["substitution"] })).toEqual(["b"]);
+ // Substitution execution
+ expect(substituteSqlParameters("SELECT * FROM emp WHERE deptno = &dept", { dept: { kind: "number", value: "10" } }, { databaseType: "oracle", enabledSyntaxes: ["named"] })).toBe("SELECT * FROM emp WHERE deptno = &dept");
+ expect(substituteSqlParameters("SELECT * FROM emp WHERE deptno = &dept", { dept: { kind: "number", value: "10" } }, { databaseType: "postgres", enabledSyntaxes: ["substitution"] })).toBe("SELECT * FROM emp WHERE deptno = 10");
+ });
+});
+
describe("sqlParameterLiteral", () => {
it("falls back to quoted strings for invalid boolean input", () => {
expect(sqlParameterLiteral({ kind: "boolean", value: "maybe" })).toBe("'maybe'");
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts
index e30fef0017..9ce301759d 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts
@@ -1,13 +1,124 @@
import { describe, expect, it } from "vitest";
import { reactive } from "vue";
-import { DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES, enabledSqlParameterSyntaxes, normalizeSqlVariableSyntaxOverrides, resolveSqlVariableSyntaxToggles } from "@/lib/sql/sqlVariableSyntax";
+import {
+ DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES,
+ defaultSqlVariableSyntaxToggles,
+ enabledSqlParameterSyntaxes,
+ isApplicableCompatibilityMode,
+ isModeDependentSubstitutionDatabase,
+ isOracleSubstitutionDatabase,
+ normalizeSqlVariableSyntaxOverrides,
+ resolveSqlVariableSyntaxToggles,
+ updateSqlVariableSyntaxToggle,
+} from "@/lib/sql/sqlVariableSyntax";
+
+describe("isModeDependentSubstitutionDatabase", () => {
+ it("identifies mode-dependent database types", () => {
+ expect(isModeDependentSubstitutionDatabase("opengauss")).toBe(true);
+ expect(isModeDependentSubstitutionDatabase("gaussdb")).toBe(true);
+ expect(isModeDependentSubstitutionDatabase("kingbase")).toBe(true);
+ });
+
+ it("returns false for mode-independent databases or undefined", () => {
+ expect(isModeDependentSubstitutionDatabase("oracle")).toBe(false);
+ expect(isModeDependentSubstitutionDatabase("postgres")).toBe(false);
+ expect(isModeDependentSubstitutionDatabase("mysql")).toBe(false);
+ expect(isModeDependentSubstitutionDatabase("sqlserver")).toBe(false);
+ expect(isModeDependentSubstitutionDatabase("sqlite")).toBe(false);
+ expect(isModeDependentSubstitutionDatabase(undefined)).toBe(false);
+ });
+});
+
+describe("isApplicableCompatibilityMode", () => {
+ it("validates openGauss and GaussDB compatibility modes", () => {
+ expect(isApplicableCompatibilityMode("opengauss", "A")).toBe(true);
+ expect(isApplicableCompatibilityMode("opengauss", "b")).toBe(true);
+ expect(isApplicableCompatibilityMode("gaussdb", "C")).toBe(true);
+ expect(isApplicableCompatibilityMode("opengauss", "oracle")).toBe(false);
+ });
+
+ it("validates Kingbase compatibility modes", () => {
+ expect(isApplicableCompatibilityMode("kingbase", "oracle")).toBe(true);
+ expect(isApplicableCompatibilityMode("kingbase", "pg")).toBe(true);
+ expect(isApplicableCompatibilityMode("kingbase", "A")).toBe(false);
+ });
+
+ it("returns false for non-mode-dependent databases or undefined inputs", () => {
+ expect(isApplicableCompatibilityMode("postgres", "pg")).toBe(false);
+ expect(isApplicableCompatibilityMode(undefined, "A")).toBe(false);
+ expect(isApplicableCompatibilityMode("opengauss", undefined)).toBe(false);
+ });
+});
+
+describe("isOracleSubstitutionDatabase", () => {
+ it("identifies Oracle and Oracle-compatible databases", () => {
+ expect(isOracleSubstitutionDatabase("oracle")).toBe(true);
+ expect(isOracleSubstitutionDatabase("oceanbase-oracle")).toBe(true);
+ expect(isOracleSubstitutionDatabase("dameng")).toBe(true);
+ expect(isOracleSubstitutionDatabase("yashandb")).toBe(true);
+ expect(isOracleSubstitutionDatabase("oscar")).toBe(true);
+ });
+
+ it("checks compatibility modes for openGauss and Kingbase", () => {
+ expect(isOracleSubstitutionDatabase("opengauss", "A")).toBe(true);
+ expect(isOracleSubstitutionDatabase("opengauss", "a")).toBe(true);
+ expect(isOracleSubstitutionDatabase("opengauss", "PG")).toBe(false);
+ expect(isOracleSubstitutionDatabase("opengauss", undefined)).toBe(false);
+
+ expect(isOracleSubstitutionDatabase("gaussdb", "A")).toBe(true);
+ expect(isOracleSubstitutionDatabase("gaussdb", "B")).toBe(false);
+
+ expect(isOracleSubstitutionDatabase("kingbase", "oracle")).toBe(true);
+ expect(isOracleSubstitutionDatabase("kingbase", "ORACLE")).toBe(true);
+ expect(isOracleSubstitutionDatabase("kingbase", "pg")).toBe(false);
+ expect(isOracleSubstitutionDatabase("kingbase", undefined)).toBe(false);
+ });
+
+ it("returns false for non-Oracle database types or undefined", () => {
+ expect(isOracleSubstitutionDatabase("mysql")).toBe(false);
+ expect(isOracleSubstitutionDatabase("postgres")).toBe(false);
+ expect(isOracleSubstitutionDatabase("sqlserver")).toBe(false);
+ expect(isOracleSubstitutionDatabase("sqlite")).toBe(false);
+ expect(isOracleSubstitutionDatabase(undefined)).toBe(false);
+ });
+});
+
+describe("defaultSqlVariableSyntaxToggles", () => {
+ it("defaults substitution to false for generic, MySQL, PostgreSQL, etc.", () => {
+ expect(defaultSqlVariableSyntaxToggles("mysql")).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
+ expect(defaultSqlVariableSyntaxToggles("postgres")).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
+ expect(defaultSqlVariableSyntaxToggles("sqlserver")).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
+ expect(defaultSqlVariableSyntaxToggles(undefined)).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
+ });
+
+ it("defaults substitution to true for Oracle-compatible databases", () => {
+ expect(defaultSqlVariableSyntaxToggles("oracle").substitution).toBe(true);
+ expect(defaultSqlVariableSyntaxToggles("oceanbase-oracle").substitution).toBe(true);
+ expect(defaultSqlVariableSyntaxToggles("dameng").substitution).toBe(true);
+ expect(defaultSqlVariableSyntaxToggles("yashandb").substitution).toBe(true);
+ expect(defaultSqlVariableSyntaxToggles("oscar").substitution).toBe(true);
+ expect(defaultSqlVariableSyntaxToggles("opengauss", "A").substitution).toBe(true);
+ expect(defaultSqlVariableSyntaxToggles("kingbase", "oracle").substitution).toBe(true);
+ });
+
+ it("defaults named to false for Neo4j and NebulaGraph", () => {
+ expect(defaultSqlVariableSyntaxToggles("neo4j").named).toBe(false);
+ expect(defaultSqlVariableSyntaxToggles("nebula").named).toBe(false);
+ });
+});
describe("resolveSqlVariableSyntaxToggles", () => {
- it("enables every syntax when there are no overrides", () => {
+ it("enables default syntaxes when there are no overrides", () => {
expect(resolveSqlVariableSyntaxToggles(undefined, "mysql")).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
expect(resolveSqlVariableSyntaxToggles({}, "mysql")).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
});
+ it("enables database-specific defaults for Oracle without overrides", () => {
+ const oracleToggles = resolveSqlVariableSyntaxToggles(undefined, "oracle");
+ expect(oracleToggles.substitution).toBe(true);
+ expect(oracleToggles.named).toBe(true);
+ });
+
it("enables every syntax for a database type without an entry", () => {
expect(resolveSqlVariableSyntaxToggles({ mysql: { shell: false } }, "postgres")).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
});
@@ -26,21 +137,29 @@ describe("resolveSqlVariableSyntaxToggles", () => {
expect(resolveSqlVariableSyntaxToggles(undefined, "mysql").named).toBe(true);
});
- it("enables every syntax when the database type is unknown", () => {
+ it("enables default syntaxes when the database type is unknown", () => {
expect(resolveSqlVariableSyntaxToggles({ mysql: { shell: false } }, undefined)).toEqual(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES);
});
- it("applies only the disabled syntaxes for the matching database type", () => {
+ it("applies only the overridden syntaxes for the matching database type", () => {
expect(resolveSqlVariableSyntaxToggles({ mysql: { sqlserver: false, atSet: false } }, "mysql")).toEqual({
positional: true,
named: true,
shell: true,
mybatis: true,
sqlserver: false,
+ substitution: false,
atSet: false,
});
});
+ it("allows user to explicitly override substitution on non-Oracle and Oracle databases", () => {
+ // Explicitly enabling substitution on PostgreSQL
+ expect(resolveSqlVariableSyntaxToggles({ postgres: { substitution: true } }, "postgres").substitution).toBe(true);
+ // Explicitly disabling substitution on Oracle
+ expect(resolveSqlVariableSyntaxToggles({ oracle: { substitution: false } }, "oracle").substitution).toBe(false);
+ });
+
it("disables every syntax when substitution is globally disabled", () => {
expect(resolveSqlVariableSyntaxToggles({ mysql: { shell: false } }, "mysql", false)).toEqual({
positional: false,
@@ -48,6 +167,16 @@ describe("resolveSqlVariableSyntaxToggles", () => {
shell: false,
mybatis: false,
sqlserver: false,
+ substitution: false,
+ atSet: false,
+ });
+ expect(resolveSqlVariableSyntaxToggles(undefined, "oracle", false)).toEqual({
+ positional: false,
+ named: false,
+ shell: false,
+ mybatis: false,
+ sqlserver: false,
+ substitution: false,
atSet: false,
});
});
@@ -63,6 +192,7 @@ describe("resolveSqlVariableSyntaxToggles", () => {
shell: false,
mybatis: true,
sqlserver: true,
+ substitution: false,
atSet: false,
});
expect(overrides).toEqual({ mysql: { shell: false, atSet: false } });
@@ -70,17 +200,21 @@ describe("resolveSqlVariableSyntaxToggles", () => {
});
describe("enabledSqlParameterSyntaxes", () => {
- it("returns the five placeholder syntaxes and never atSet", () => {
+ it("returns the five default placeholder syntaxes for generic databases and never atSet", () => {
expect(enabledSqlParameterSyntaxes(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES)).toEqual(["positional", "named", "shell", "mybatis", "sqlserver"]);
});
+ it("returns all six placeholder syntaxes when substitution is enabled", () => {
+ expect(enabledSqlParameterSyntaxes({ ...DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES, substitution: true })).toEqual(["positional", "named", "shell", "mybatis", "sqlserver", "substitution"]);
+ });
+
it("filters out disabled placeholder syntaxes", () => {
- expect(enabledSqlParameterSyntaxes({ positional: false, named: true, shell: false, mybatis: true, sqlserver: false, atSet: true })).toEqual(["named", "mybatis"]);
+ expect(enabledSqlParameterSyntaxes({ positional: false, named: true, shell: false, mybatis: true, sqlserver: false, substitution: true, atSet: true })).toEqual(["named", "mybatis", "substitution"]);
});
it("ignores the atSet toggle entirely", () => {
- expect(enabledSqlParameterSyntaxes({ positional: true, named: true, shell: true, mybatis: true, sqlserver: true, atSet: false })).toEqual(["positional", "named", "shell", "mybatis", "sqlserver"]);
- expect(enabledSqlParameterSyntaxes({ positional: false, named: false, shell: false, mybatis: false, sqlserver: false, atSet: true })).toEqual([]);
+ expect(enabledSqlParameterSyntaxes({ positional: true, named: true, shell: true, mybatis: true, sqlserver: true, substitution: true, atSet: false })).toEqual(["positional", "named", "shell", "mybatis", "sqlserver", "substitution"]);
+ expect(enabledSqlParameterSyntaxes({ positional: false, named: false, shell: false, mybatis: false, sqlserver: false, substitution: false, atSet: true })).toEqual([]);
});
});
@@ -92,12 +226,23 @@ describe("normalizeSqlVariableSyntaxOverrides", () => {
expect(normalizeSqlVariableSyntaxOverrides("mysql")).toEqual({});
});
- it("keeps only syntaxes explicitly set to false", () => {
- expect(normalizeSqlVariableSyntaxOverrides({ mysql: { positional: true, shell: false, atSet: false } })).toEqual({ mysql: { shell: false, atSet: false } });
+ it("keeps only syntaxes that deviate from defaults", () => {
+ expect(
+ normalizeSqlVariableSyntaxOverrides({
+ mysql: { positional: true, shell: false, substitution: false, atSet: false },
+ postgres: { substitution: true },
+ oracle: { substitution: false, shell: true },
+ }),
+ ).toEqual({
+ mysql: { shell: false, atSet: false },
+ postgres: { substitution: true },
+ oracle: { substitution: false },
+ });
});
- it("drops entries with no disabled syntaxes", () => {
- expect(normalizeSqlVariableSyntaxOverrides({ mysql: { positional: true }, postgres: {} })).toEqual({});
+ it("drops entries with no deviating syntaxes", () => {
+ expect(normalizeSqlVariableSyntaxOverrides({ mysql: { positional: true, substitution: false }, postgres: {} })).toEqual({});
+ expect(normalizeSqlVariableSyntaxOverrides({ oracle: { positional: true, substitution: true } })).toEqual({});
});
it("ignores non-boolean values and unknown keys", () => {
@@ -109,16 +254,194 @@ describe("normalizeSqlVariableSyntaxOverrides", () => {
});
it("is stable across a round-trip", () => {
- const normalized = normalizeSqlVariableSyntaxOverrides({ mysql: { shell: false }, oracle: { atSet: false, named: false } });
+ const normalized = normalizeSqlVariableSyntaxOverrides({
+ mysql: { shell: false },
+ postgres: { substitution: true },
+ oracle: { atSet: false, substitution: false },
+ });
expect(normalizeSqlVariableSyntaxOverrides(normalized)).toEqual(normalized);
});
it("reads through a Vue reactive proxy without throwing (settings store is reactive; structuredClone would throw DataCloneError here)", () => {
- const overrides = reactive({ mysql: { shell: false, atSet: false } });
+ const overrides = reactive({ mysql: { shell: false, atSet: false }, postgres: { substitution: true } });
const cloned = normalizeSqlVariableSyntaxOverrides(overrides);
- expect(cloned).toEqual({ mysql: { shell: false, atSet: false } });
+ expect(cloned).toEqual({ mysql: { shell: false, atSet: false }, postgres: { substitution: true } });
// Detached from the reactive source: mutating the clone must not touch the proxy.
cloned.mysql = {};
expect(overrides.mysql).toEqual({ shell: false, atSet: false });
});
+
+ it("preserves explicit substitution: false for mode-dependent databases without compatibility mode", () => {
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: false } })).toEqual({ opengauss: { substitution: false } });
+ expect(normalizeSqlVariableSyntaxOverrides({ gaussdb: { substitution: false } })).toEqual({ gaussdb: { substitution: false } });
+ expect(normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: false } })).toEqual({ kingbase: { substitution: false } });
+ });
+
+ it("preserves explicit substitution: true for mode-dependent databases without compatibility mode", () => {
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: true } })).toEqual({ opengauss: { substitution: true } });
+ expect(normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: true } })).toEqual({ kingbase: { substitution: true } });
+ });
+
+ it("preserves explicit substitution overrides for mode-dependent databases regardless of compatibilityMode", () => {
+ // openGauss substitution: false and true are always preserved across A, B, and unspecified modes
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: false } }, "A")).toEqual({ opengauss: { substitution: false } });
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: true } }, "A")).toEqual({ opengauss: { substitution: true } });
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: true } }, "B")).toEqual({ opengauss: { substitution: true } });
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: false } }, "B")).toEqual({ opengauss: { substitution: false } });
+
+ // Kingbase substitution: false and true are always preserved across oracle, pg, and unspecified modes
+ expect(normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: false } }, "oracle")).toEqual({ kingbase: { substitution: false } });
+ expect(normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: true } }, "oracle")).toEqual({ kingbase: { substitution: true } });
+ expect(normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: true } }, "pg")).toEqual({ kingbase: { substitution: true } });
+ expect(normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: false } }, "pg")).toEqual({ kingbase: { substitution: false } });
+ });
+
+ it("does not let unrelated compatibility modes affect another database type during normalization", () => {
+ // openGauss "A" mode must not cause Kingbase substitution: false to be dropped
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: false }, kingbase: { substitution: false } }, "A")).toEqual({
+ opengauss: { substitution: false },
+ kingbase: { substitution: false },
+ });
+ // Kingbase "oracle" mode must not cause openGauss substitution: false to be dropped
+ expect(normalizeSqlVariableSyntaxOverrides({ opengauss: { substitution: false }, kingbase: { substitution: false } }, "oracle")).toEqual({
+ opengauss: { substitution: false },
+ kingbase: { substitution: false },
+ });
+ });
+
+ it("round-trips mode-dependent overrides correctly into resolution", () => {
+ const rawSaved = { opengauss: { substitution: false } };
+ const normalized = normalizeSqlVariableSyntaxOverrides(rawSaved);
+ expect(normalized).toEqual({ opengauss: { substitution: false } });
+
+ // Runtime resolution in A-mode honors the explicit false override
+ expect(resolveSqlVariableSyntaxToggles(normalized, "opengauss", true, "A").substitution).toBe(false);
+
+ // Kingbase runtime resolution in oracle mode honors explicit false override
+ const kbNormalized = normalizeSqlVariableSyntaxOverrides({ kingbase: { substitution: false } });
+ expect(resolveSqlVariableSyntaxToggles(kbNormalized, "kingbase", true, "oracle").substitution).toBe(false);
+
+ // Control: without override, A-mode and oracle-mode default to true
+ expect(resolveSqlVariableSyntaxToggles({}, "opengauss", true, "A").substitution).toBe(true);
+ expect(resolveSqlVariableSyntaxToggles({}, "kingbase", true, "oracle").substitution).toBe(true);
+ expect(resolveSqlVariableSyntaxToggles({}, "postgres", true).substitution).toBe(false);
+ });
+});
+
+describe("updateSqlVariableSyntaxToggle", () => {
+ it("preserves explicit substitution: false for openGauss in B mode when toggling shell", () => {
+ // User already saved opengauss.substitution = false.
+ // In B-mode, substitution defaults to false. Toggling shell to false must NOT drop substitution: false!
+ const initial = { opengauss: { substitution: false } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "opengauss", "shell", false, "B");
+ expect(updated).toEqual({
+ opengauss: {
+ substitution: false,
+ shell: false,
+ },
+ });
+
+ // When switched back to A-mode, substitution is still explicitly false
+ expect(resolveSqlVariableSyntaxToggles(updated, "opengauss", true, "A").substitution).toBe(false);
+ });
+
+ it("preserves explicit substitution: false for openGauss in A mode when toggling shell", () => {
+ const initial = { opengauss: { substitution: false } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "opengauss", "shell", false, "A");
+ expect(updated).toEqual({
+ opengauss: {
+ substitution: false,
+ shell: false,
+ },
+ });
+ });
+
+ it("preserves explicit substitution: false for Kingbase in pg mode when toggling shell", () => {
+ const initial = { kingbase: { substitution: false } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "kingbase", "shell", false, "pg");
+ expect(updated).toEqual({
+ kingbase: {
+ substitution: false,
+ shell: false,
+ },
+ });
+ // In oracle mode, substitution resolves to false because override is preserved
+ expect(resolveSqlVariableSyntaxToggles(updated, "kingbase", true, "oracle").substitution).toBe(false);
+ });
+
+ it("preserves explicit substitution: false for Kingbase in oracle mode when toggling shell", () => {
+ const initial = { kingbase: { substitution: false } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "kingbase", "shell", false, "oracle");
+ expect(updated).toEqual({
+ kingbase: {
+ substitution: false,
+ shell: false,
+ },
+ });
+ });
+
+ it("preserves explicit substitution: true for Kingbase in oracle mode when toggling shell", () => {
+ const initial = { kingbase: { substitution: true } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "kingbase", "shell", false, "oracle");
+ expect(updated).toEqual({
+ kingbase: {
+ substitution: true,
+ shell: false,
+ },
+ });
+ // In pg mode, substitution resolves to true because override is preserved
+ expect(resolveSqlVariableSyntaxToggles(updated, "kingbase", true, "pg").substitution).toBe(true);
+ });
+
+ it("preserves explicit substitution: true for openGauss in A mode when toggling shell", () => {
+ const initial = { opengauss: { substitution: true } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "opengauss", "shell", false, "A");
+ expect(updated).toEqual({
+ opengauss: {
+ substitution: true,
+ shell: false,
+ },
+ });
+ // In B mode, substitution resolves to true because override is preserved
+ expect(resolveSqlVariableSyntaxToggles(updated, "opengauss", true, "B").substitution).toBe(true);
+ });
+
+ it("does not introduce substitution override when toggling another syntax if substitution was not overridden", () => {
+ const updated = updateSqlVariableSyntaxToggle({}, "opengauss", "shell", false, "B");
+ expect(updated).toEqual({
+ opengauss: {
+ shell: false,
+ },
+ });
+ });
+
+ it("explicitly sets substitution to false or true for mode-dependent databases", () => {
+ const setFalse = updateSqlVariableSyntaxToggle({}, "opengauss", "substitution", false, "B");
+ expect(setFalse).toEqual({ opengauss: { substitution: false } });
+
+ const setTrue = updateSqlVariableSyntaxToggle({}, "opengauss", "substitution", true, "A");
+ expect(setTrue).toEqual({ opengauss: { substitution: true } });
+ });
+
+ it("retains explicit substitution override when reverting other toggles back to defaults", () => {
+ const initial = { opengauss: { substitution: false, shell: false } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "opengauss", "shell", true, "B");
+ expect(updated).toEqual({
+ opengauss: {
+ substitution: false,
+ },
+ });
+ });
+
+ it("drops non-mode-dependent toggles when matching database defaults", () => {
+ const initial = { mysql: { shell: false } };
+ const updated = updateSqlVariableSyntaxToggle(initial, "mysql", "shell", true);
+ expect(updated).toEqual({});
+ });
+
+ it("ignores named parameter changes for Neo4j and NebulaGraph", () => {
+ const initial = {};
+ expect(updateSqlVariableSyntaxToggle(initial, "neo4j", "named", true)).toEqual({});
+ expect(updateSqlVariableSyntaxToggle(initial, "nebula", "named", true)).toEqual({});
+ });
});
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts
index 87724930b6..ae463aaea0 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts
@@ -587,6 +587,13 @@ describe("settingsTransfer", () => {
if (result.ok) expect(result.value.editorSettings.sqlFormatter).toEqual(sqlFormatter);
});
+ it("accepts and transfers sql variable syntax overrides with boolean flags", () => {
+ const overrides = { postgres: { substitution: true }, oracle: { substitution: false } };
+ const result = parseSettingsTransferFile(fileWith({ sqlVariableSyntaxOverrides: overrides }));
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.value.editorSettings.sqlVariableSyntaxOverrides).toEqual(overrides);
+ });
+
it("rejects malformed sql variable syntax overrides", () => {
const result = parseSettingsTransferFile(fileWith({ sqlVariableSyntaxOverrides: { mysql: { positional: "yes" } } }));
expect(result.ok).toBe(false);
diff --git a/apps/desktop/src/lib/settings/settingsTransfer.ts b/apps/desktop/src/lib/settings/settingsTransfer.ts
index 5c0fdd1a35..32d6b6d736 100644
--- a/apps/desktop/src/lib/settings/settingsTransfer.ts
+++ b/apps/desktop/src/lib/settings/settingsTransfer.ts
@@ -521,7 +521,7 @@ const NESTED_FIELD_VALIDATORS: Partial<Record<EditorSettingsDraftKey, (value: un
snippets: (value) => isArrayOfShape(value, isSqlSnippetItem),
modelGenerationTemplates: isModelGenerationTemplatesShape,
sqlShortcuts: (value) => isArrayOfShape(value, isSqlShortcutActionItem),
- sqlVariableSyntaxOverrides: (value) => isSqlVariableSyntaxOverridesShape(value, (toggle) => toggle === false),
+ sqlVariableSyntaxOverrides: (value) => isSqlVariableSyntaxOverridesShape(value, (toggle) => typeof toggle === "boolean"),
};
/**
diff --git a/apps/desktop/src/lib/sql/sqlParameters.ts b/apps/desktop/src/lib/sql/sqlParameters.ts
index 2be7c0e37e..59389c39f1 100644
--- a/apps/desktop/src/lib/sql/sqlParameters.ts
+++ b/apps/desktop/src/lib/sql/sqlParameters.ts
@@ -1,5 +1,6 @@
import type { DatabaseType } from "@/types/database";
import { collectSqlDatabaseLinkStarts } from "@/lib/sql/sqlDatabaseLinks";
+import { isOracleSubstitutionDatabase } from "@/lib/sql/sqlVariableSyntax";
export type SqlParameterValueKind = "string" | "number" | "boolean" | "null" | "raw";
@@ -8,7 +9,7 @@ export interface SqlParameterInput {
value: string;
}
-export type SqlParameterSyntax = "positional" | "named" | "shell" | "mybatis" | "sqlserver";
+export type SqlParameterSyntax = "positional" | "named" | "shell" | "mybatis" | "sqlserver" | "substitution";
export interface SqlParameterDescriptor {
key: string;
@@ -381,7 +382,13 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
const nativeSqlServerParameters = collectNativeSqlServerParameters(sql, databaseType);
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 isSyntaxEnabled = (syntax: SqlParameterSyntax) => {
+ if (enabledSyntaxes) return enabledSyntaxes.has(syntax);
+ if (syntax === "substitution") {
+ return isOracleSubstitutionDatabase(databaseType, options?.compatibilityMode);
+ }
+ return true;
+ };
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>();
@@ -445,6 +452,14 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
i = quoted.end;
continue;
}
+ if (ch === "'" && isSyntaxEnabled("substitution")) {
+ const quotedSubstitution = tryReadQuotedSubstitutionPlaceholder(sql, i, databaseType);
+ if (quotedSubstitution) {
+ occurrences.push(quotedSubstitution);
+ i = quotedSubstitution.end;
+ continue;
+ }
+ }
const quotedEnd = skipQuoted(sql, i, ch, databaseType);
// Double quotes can delimit identifiers, so only ordinary single-quoted
// values opt into embedded interpolation.
@@ -556,6 +571,14 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
continue;
}
}
+ if (ch === "&" && isSyntaxEnabled("substitution")) {
+ const occurrence = readSubstitutionParameterOccurrence(sql, i);
+ if (occurrence) {
+ occurrences.push(occurrence);
+ i = occurrence.end;
+ continue;
+ }
+ }
if (ch === "$") {
const marker = readDollarQuoteMarker(sql, i);
if (marker) {
@@ -1636,7 +1659,82 @@ function tryReadQuotedBracedPlaceholder(sql: string, start: number, quote: "'" |
name,
syntax,
token: sql.slice(start, end),
- ...(quote === "\'" ? { replacement: "quoted-string" as const } : {}),
+ ...(quote === "'" ? { replacement: "quoted-string" as const } : {}),
+ start,
+ end,
+ };
+}
+
+function tryReadQuotedSubstitutionPlaceholder(sql: string, start: number, databaseType?: DatabaseType): ParameterOccurrence | null {
+ if (sql[start] !== "'") return null;
+ if (hasSqlStringLiteralPrefix(sql, start)) return null;
+
+ const contentStart = start + 1;
+ if (sql[contentStart] !== "&") return null;
+
+ const isDouble = sql[contentStart + 1] === "&";
+ const prefixLength = isDouble ? 2 : 1;
+ const nameStart = contentStart + prefixLength;
+ if (sql[nameStart] === "&") return null;
+ if (/^&(?:lt|gt|amp|quot|apos);/i.test(sql.slice(contentStart))) return null;
+
+ let nameEnd = nameStart;
+ if (/[0-9]/.test(sql[nameStart] ?? "")) {
+ while (nameEnd < sql.length && /[0-9]/.test(sql[nameEnd] ?? "")) nameEnd += 1;
+ } else if (PARAMETER_NAME_START_RE.test(sql[nameStart] ?? "")) {
+ while (nameEnd < sql.length && PARAMETER_NAME_CHAR_RE.test(sql[nameEnd] ?? "")) nameEnd += 1;
+ } else {
+ return null;
+ }
+ if (nameEnd === nameStart) return null;
+
+ const name = sql.slice(nameStart, nameEnd);
+ let contentEnd = nameEnd;
+ if (sql[contentEnd] === ".") contentEnd += 1;
+
+ if (sql[contentEnd] !== "'") return null;
+ const quoteEnd = contentEnd + 1;
+ if (skipQuoted(sql, start, "'", databaseType) !== quoteEnd) return null;
+
+ return {
+ key: name,
+ name,
+ syntax: "substitution",
+ token: sql.slice(start, quoteEnd),
+ replacement: "quoted-string",
+ start,
+ end: quoteEnd,
+ };
+}
+
+function readSubstitutionParameterOccurrence(sql: string, start: number): ParameterOccurrence | null {
+ if (start > 0 && (PARAMETER_NAME_CHAR_RE.test(sql[start - 1] ?? "") || sql[start - 1] === "?" || sql[start - 1] === "&")) return null;
+
+ const isDouble = sql[start + 1] === "&";
+ const prefixLength = isDouble ? 2 : 1;
+ const nameStart = start + prefixLength;
+ if (sql[nameStart] === "&") return null;
+ if (/^&(?:lt|gt|amp|quot|apos);/i.test(sql.slice(start))) return null;
+
+ let nameEnd = nameStart;
+ if (/[0-9]/.test(sql[nameStart] ?? "")) {
+ while (nameEnd < sql.length && /[0-9]/.test(sql[nameEnd] ?? "")) nameEnd += 1;
+ } else if (PARAMETER_NAME_START_RE.test(sql[nameStart] ?? "")) {
+ while (nameEnd < sql.length && PARAMETER_NAME_CHAR_RE.test(sql[nameEnd] ?? "")) nameEnd += 1;
+ } else {
+ return null;
+ }
+ if (nameEnd === nameStart) return null;
+
+ const name = sql.slice(nameStart, nameEnd);
+ let end = nameEnd;
+ if (sql[end] === ".") end += 1;
+
+ return {
+ key: name,
+ name,
+ syntax: "substitution",
+ token: sql.slice(start, end),
start,
end,
};
diff --git a/apps/desktop/src/lib/sql/sqlVariableSyntax.ts b/apps/desktop/src/lib/sql/sqlVariableSyntax.ts
index c698b6615b..3189b47ed8 100644
--- a/apps/desktop/src/lib/sql/sqlVariableSyntax.ts
+++ b/apps/desktop/src/lib/sql/sqlVariableSyntax.ts
@@ -1,13 +1,15 @@
// Per-database-type configuration for SQL variable/placeholder substitution.
//
// DBX runs two client-side substitution systems before sending SQL to a backend:
-// the placeholder parameter dialog (`sqlParameters.ts`, five syntaxes) and the
+// the placeholder parameter dialog (`sqlParameters.ts`, six syntaxes) and the
// `@set name = value;` expansion (`sqlVariables.ts`). This module lets users opt
// out of individual syntaxes per database type. SQL syntaxes default to `true`,
-// except Neo4j's `:label` patterns, which are not named parameters.
+// except Neo4j's `:label` patterns, which are not named parameters, and Oracle
+// substitution variables (`&name`, `&&name`), which default to enabled only for
+// Oracle and Oracle-compatible dialects/modes.
//
-// Storage is sparse: only syntaxes explicitly turned off (`false`) are persisted,
-// keyed by database type. Unset values use the database-specific defaults.
+// Storage is sparse: only syntaxes that deviate from the database-specific defaults
+// are persisted, keyed by database type. Unset values use the database-specific defaults.
import type { DatabaseType } from "@/types/database";
import type { SqlParameterSyntax } from "@/lib/sql/sqlParameters";
@@ -19,6 +21,7 @@ export interface SqlVariableSyntaxToggles {
shell: boolean; // ${name}
mybatis: boolean; // #{name}
sqlserver: boolean; // @name
+ substitution: boolean; // &name, &&name
atSet: boolean; // @set name = value; (expandSqlVariables)
}
@@ -28,11 +31,12 @@ export const DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES: SqlVariableSyntaxToggles = {
shell: true,
mybatis: true,
sqlserver: true,
+ substitution: false,
atSet: true,
};
// Fixed order for iterating the toggles in the settings UI.
-export const SQL_VARIABLE_SYNTAX_KEYS = ["positional", "named", "shell", "mybatis", "sqlserver", "atSet"] as const satisfies readonly (keyof SqlVariableSyntaxToggles)[];
+export const SQL_VARIABLE_SYNTAX_KEYS = ["positional", "named", "shell", "mybatis", "sqlserver", "substitution", "atSet"] as const satisfies readonly (keyof SqlVariableSyntaxToggles)[];
// Display tokens (code symbols, not translated) shown next to each toggle.
export const SQL_VARIABLE_SYNTAX_TOKENS: Record<keyof SqlVariableSyntaxToggles, string> = {
@@ -41,24 +45,64 @@ export const SQL_VARIABLE_SYNTAX_TOKENS: Record<keyof SqlVariableSyntaxToggles,
shell: "${name}",
mybatis: "#{name}",
sqlserver: "@name",
+ substitution: "&name",
atSet: "@set …;",
};
-// The first five toggles map one-to-one onto placeholder parameter syntaxes.
-const PARAMETER_SYNTAX_KEYS = ["positional", "named", "shell", "mybatis", "sqlserver"] as const satisfies readonly SqlParameterSyntax[];
+// The first six toggles map one-to-one onto placeholder parameter syntaxes.
+const PARAMETER_SYNTAX_KEYS = ["positional", "named", "shell", "mybatis", "sqlserver", "substitution"] as const satisfies readonly SqlParameterSyntax[];
export type SqlVariableSyntaxOverrides = Partial<Record<DatabaseType, Partial<SqlVariableSyntaxToggles>>>;
// Database types offered in the settings selector — every connectable type.
export const SQL_VARIABLE_SYNTAX_DATABASE_TYPES: DatabaseType[] = manifestDatabaseTypes();
+const ORACLE_SUBSTITUTION_DATABASE_TYPES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "dameng", "yashandb", "oscar"]);
+const MODE_DEPENDENT_SUBSTITUTION_DATABASE_TYPES = new Set<DatabaseType>(["opengauss", "gaussdb", "kingbase"]);
+
+export function isModeDependentSubstitutionDatabase(dbType?: DatabaseType): boolean {
+ return !dbType ? false : MODE_DEPENDENT_SUBSTITUTION_DATABASE_TYPES.has(dbType);
+}
+
+export function isApplicableCompatibilityMode(dbType?: DatabaseType, compatibilityMode?: string): boolean {
+ if (!dbType || !compatibilityMode) return false;
+ const mode = compatibilityMode.trim().toLowerCase();
+ if (dbType === "opengauss" || dbType === "gaussdb") {
+ return mode === "a" || mode === "b" || mode === "c" || mode === "d" || mode === "pg";
+ }
+ if (dbType === "kingbase") {
+ return mode === "oracle" || mode === "pg" || mode === "mysql" || mode === "sqlserver";
+ }
+ return false;
+}
+
+export function isOracleSubstitutionDatabase(dbType?: DatabaseType, compatibilityMode?: string): boolean {
+ if (!dbType) return false;
+ if (ORACLE_SUBSTITUTION_DATABASE_TYPES.has(dbType)) return true;
+ if (dbType === "opengauss" || dbType === "gaussdb") return compatibilityMode?.trim().toUpperCase() === "A";
+ if (dbType === "kingbase") return compatibilityMode?.trim().toLowerCase() === "oracle";
+ return false;
+}
+
+export function defaultSqlVariableSyntaxToggles(dbType?: DatabaseType, compatibilityMode?: string): SqlVariableSyntaxToggles {
+ return {
+ positional: true,
+ named: dbType !== "neo4j" && dbType !== "nebula",
+ shell: true,
+ mybatis: true,
+ sqlserver: true,
+ substitution: isOracleSubstitutionDatabase(dbType, compatibilityMode),
+ atSet: true,
+ };
+}
+
/**
* Resolve the effective toggles for a database type. The global gate disables
* every syntax without modifying the saved overrides. Otherwise, any syntax not
- * explicitly disabled in `overrides` is enabled. A pure function safe to call
+ * explicitly overridden uses database-specific defaults. A pure function safe to call
* on every execution.
*/
-export function resolveSqlVariableSyntaxToggles(overrides: SqlVariableSyntaxOverrides | undefined, dbType: DatabaseType | undefined, enabled = true): SqlVariableSyntaxToggles {
+export function resolveSqlVariableSyntaxToggles(overrides: SqlVariableSyntaxOverrides | undefined, dbType: DatabaseType | undefined, enabled = true, compatibilityMode?: string): SqlVariableSyntaxToggles {
if (!enabled) {
return {
positional: false,
@@ -66,17 +110,20 @@ export function resolveSqlVariableSyntaxToggles(overrides: SqlVariableSyntaxOver
shell: false,
mybatis: false,
sqlserver: false,
+ substitution: false,
atSet: false,
};
}
+ const defaults = defaultSqlVariableSyntaxToggles(dbType, compatibilityMode);
const partial = dbType ? overrides?.[dbType] : undefined;
return {
- positional: partial?.positional ?? true,
- named: dbType === "neo4j" || dbType === "nebula" ? false : (partial?.named ?? true),
- shell: partial?.shell ?? true,
- mybatis: partial?.mybatis ?? true,
- sqlserver: partial?.sqlserver ?? true,
- atSet: partial?.atSet ?? true,
+ positional: partial?.positional ?? defaults.positional,
+ named: dbType === "neo4j" || dbType === "nebula" ? false : (partial?.named ?? defaults.named),
+ shell: partial?.shell ?? defaults.shell,
+ mybatis: partial?.mybatis ?? defaults.mybatis,
+ sqlserver: partial?.sqlserver ?? defaults.sqlserver,
+ substitution: partial?.substitution ?? defaults.substitution,
+ atSet: partial?.atSet ?? defaults.atSet,
};
}
@@ -85,18 +132,78 @@ export function enabledSqlParameterSyntaxes(toggles: SqlVariableSyntaxToggles):
return PARAMETER_SYNTAX_KEYS.filter((key) => toggles[key]);
}
+/**
+ * Update a single variable syntax toggle in the given overrides map, maintaining
+ * sparse representation against database defaults.
+ *
+ * For mode-dependent databases (openGauss, GaussDB, Kingbase), explicit substitution
+ * boolean overrides are always preserved (whether true or false) across mode changes
+ * and other toggle updates, since the setting is stored globally per database type.
+ */
+export function updateSqlVariableSyntaxToggle(overrides: SqlVariableSyntaxOverrides, dbType: DatabaseType, key: keyof SqlVariableSyntaxToggles, value: boolean, compatibilityMode?: string): SqlVariableSyntaxOverrides {
+ if ((dbType === "neo4j" || dbType === "nebula") && key === "named") return overrides;
+ const defaults = defaultSqlVariableSyntaxToggles(dbType, compatibilityMode);
+ const current = resolveSqlVariableSyntaxToggles(overrides, dbType, true, compatibilityMode);
+ const merged: SqlVariableSyntaxToggles = {
+ ...current,
+ [key]: value,
+ };
+ const next: SqlVariableSyntaxOverrides = {
+ ...overrides,
+ };
+ const isModeDependent = isModeDependentSubstitutionDatabase(dbType);
+ const partial: Partial<SqlVariableSyntaxToggles> = {};
+ for (const toggleKey of SQL_VARIABLE_SYNTAX_KEYS) {
+ if ((dbType === "neo4j" || dbType === "nebula") && toggleKey === "named") continue;
+ if (toggleKey === "substitution" && isModeDependent) {
+ if (toggleKey === key) {
+ partial[toggleKey] = value;
+ } else if (overrides[dbType]?.substitution !== undefined) {
+ partial[toggleKey] = overrides[dbType]!.substitution;
+ }
+ } else if (merged[toggleKey] !== defaults[toggleKey]) {
+ partial[toggleKey] = merged[toggleKey];
+ }
+ }
+ if (Object.keys(partial).length === 0) {
+ delete next[dbType];
+ } else {
+ next[dbType] = partial;
+ }
+ return next;
+}
+
/**
* Normalize persisted overrides into a sparse structure: drop non-object entries
- * and only keep syntaxes explicitly set to `false`. Absence resolves to enabled.
+ * and only keep syntaxes that differ from database-specific defaults.
+ *
+ * For databases whose substitution default depends on compatibility mode
+ * (openGauss, GaussDB, Kingbase), an explicit boolean override cannot be assumed
+ * redundant across all modes unless an applicable compatibilityMode is supplied.
*/
-export function normalizeSqlVariableSyntaxOverrides(value: unknown): SqlVariableSyntaxOverrides {
+export function normalizeSqlVariableSyntaxOverrides(value: unknown, compatibilityMode?: string): SqlVariableSyntaxOverrides {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const result: SqlVariableSyntaxOverrides = {};
for (const [dbType, raw] of Object.entries(value as Record<string, unknown>)) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
+ const isModeDependent = isModeDependentSubstitutionDatabase(dbType as DatabaseType);
+ const applicableMode = isApplicableCompatibilityMode(dbType as DatabaseType, compatibilityMode) ? compatibilityMode : undefined;
+ const defaults = defaultSqlVariableSyntaxToggles(dbType as DatabaseType, applicableMode);
const partial: Partial<SqlVariableSyntaxToggles> = {};
for (const key of SQL_VARIABLE_SYNTAX_KEYS) {
- if ((raw as Record<string, unknown>)[key] === false) partial[key] = false;
+ if ((dbType === "neo4j" || dbType === "nebula") && key === "named") continue;
+ const val = (raw as Record<string, unknown>)[key];
+ if (typeof val !== "boolean") continue;
+
+ if (key === "substitution" && isModeDependent) {
+ // Mode-dependent databases (openGauss, GaussDB, Kingbase) have different substitution
+ // defaults depending on compatibility mode (A/Oracle mode is true, B/PG mode is false).
+ // Retain any explicit boolean override (true or false) so that the user's intent is
+ // preserved across mode changes, settings save/reopen, and runtime execution.
+ partial[key] = val;
+ } else if (val !== defaults[key]) {
+ partial[key] = val;
+ }
}
if (Object.keys(partial).length > 0) result[dbType as DatabaseType] = partial;
}