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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(mysql): drop and recreate routines when running source tab CREATE
t8y2a544218dd6a3
diff --git a/apps/desktop/src/lib/__tests__/table/objectSourceEditor.spec.ts b/apps/desktop/src/lib/__tests__/table/objectSourceEditor.spec.tsindex dfb62dcf7d..a9b095d5a8 100644--- a/apps/desktop/src/lib/__tests__/table/objectSourceEditor.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/objectSourceEditor.spec.ts@@ -1,10 +1,12 @@import { beforeEach, describe, expect, it, vi } from "vitest";import * as api from "@/lib/backend/api";-import { executeObjectSourceSave, fingerprintOracleRoutineObjectSource, formatObjectSourceSaveError, resolveObjectSourceEditDraft, rewriteOracleRoutineReferences, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";+import { executeObjectSourceSave, fingerprintOracleRoutineObjectSource, formatObjectSourceSaveError, prepareRoutineSourceRun, resolveObjectSourceEditDraft, rewriteOracleRoutineReferences, supportsRoutineSourceReplaceOnRun, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";+import { beginSourceSave, captureSourceIdentity } from "@/lib/table/objectSourceIdentity";import { supportsObjectRename } from "@/lib/table/objectRenameSql";import { formatSqlForDisplay } from "@/lib/sql/sqlFormatter";vi.mock("@/lib/backend/api", () => ({+ buildExecutableObjectSourceStatements: vi.fn(),executeInTransaction: vi.fn().mockResolvedValue({}),executeQuery: vi.fn().mockResolvedValue({}),executeScript: vi.fn().mockResolvedValue({}),@@ -62,6 +64,138 @@ describe("executeObjectSourceSave", () => {});});+describe("routine source Run replacement (issue #12855)", () => {+ const identity = (name: string) => captureSourceIdentity({ connectionId: "conn-1", database: "app", schema: "app", objectType: "PROCEDURE", name });+ const prepare = (sql: string, name = "refresh_cache", objectType: "PROCEDURE" | "FUNCTION" = "PROCEDURE") => prepareRoutineSourceRun({ identity: identity(name), connectionId: "conn-1", database: "app", databaseType: "mysql", schema: "app", objectType, name, sql });+ // The backend's replace sequence: validate under a temporary name, drop the old routine, then the CREATE itself.+ const replaceSequence = (create: string) => ["DROP PROCEDURE IF EXISTS `app`.`dbx_routine_check_1`;", "CREATE PROCEDURE `dbx_routine_check_1`() BEGIN SELECT 1; END;", "DROP PROCEDURE IF EXISTS `app`.`dbx_routine_check_1`;", "DROP PROCEDURE IF EXISTS `app`.`refresh_cache`;", create];++ it("only applies to MySQL-family procedures and functions", () => {+ for (const databaseType of ["mysql", "goldendb"] as const) {+ expect(supportsRoutineSourceReplaceOnRun(databaseType, "PROCEDURE")).toBe(true);+ expect(supportsRoutineSourceReplaceOnRun(databaseType, "FUNCTION")).toBe(true);+ }+ expect(supportsRoutineSourceReplaceOnRun("mysql", "VIEW")).toBe(false);+ expect(supportsRoutineSourceReplaceOnRun("mysql", "TRIGGER")).toBe(false);+ expect(supportsRoutineSourceReplaceOnRun("mysql", "EVENT")).toBe(false);+ for (const databaseType of ["postgres", "oracle", "sqlserver", "doris", "starrocks", undefined] as const) {+ expect(supportsRoutineSourceReplaceOnRun(databaseType, "PROCEDURE")).toBe(false);+ expect(supportsRoutineSourceReplaceOnRun(databaseType, "FUNCTION")).toBe(false);+ }+ });++ it("runs the validate + drop steps of the Save sequence ahead of the tab's own CREATE", async () => {+ const create = "CREATE DEFINER=`root`@`%` PROCEDURE `refresh_cache`() BEGIN SELECT 2; END";+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue(replaceSequence(`${create};`));++ await expect(prepare(create)).resolves.toBe(true);++ expect(api.buildExecutableObjectSourceStatements).toHaveBeenCalledWith({ databaseType: "mysql", objectType: "PROCEDURE", schema: "app", name: "refresh_cache", source: create });+ const executed = vi.mocked(api.executeQuery).mock.calls.map((call) => call[2]);+ expect(executed).toEqual(replaceSequence("").slice(0, -1));+ expect(api.executeQuery).toHaveBeenNthCalledWith(1, "conn-1", "app", "DROP PROCEDURE IF EXISTS `app`.`dbx_routine_check_1`;", "app");+ // The CREATE is left to the normal query pipeline.+ expect(executed.some((sql) => sql.includes("DEFINER"))).toBe(false);+ });++ it.each([+ ["bare name", "CREATE PROCEDURE refresh_cache() BEGIN SELECT 1; END"],+ ["case-insensitive quoted name", " create\nprocedure `Refresh_Cache` (IN a INT) BEGIN SELECT 1; END"],+ ["bare definer", "CREATE DEFINER=root@localhost PROCEDURE `refresh_cache`() BEGIN SELECT 1; END"],+ ["quoted definer with a space", "CREATE DEFINER = 'app user'@'%' PROCEDURE `refresh_cache`() BEGIN SELECT 1; END"],+ ["backquoted definer containing @", "CREATE DEFINER=`a@b`@`%` PROCEDURE `refresh_cache`() BEGIN SELECT 1; END"],+ ["CURRENT_USER() definer", "CREATE DEFINER=CURRENT_USER() PROCEDURE `refresh_cache`() BEGIN SELECT 1; END"],+ ])("treats a %s as the tab's own CREATE", async (_description, create) => {+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue(replaceSequence(`${create};`));+ await expect(prepare(create)).resolves.toBe(true);+ expect(api.executeQuery).toHaveBeenCalledTimes(4);+ });++ it("matches functions by their own kind and backquote-escaped names", async () => {+ const create = "CREATE FUNCTION `odd``name`(a INT) RETURNS int DETERMINISTIC RETURN a";+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue([+ "DROP FUNCTION IF EXISTS `app`.`dbx_routine_check_2`;",+ "CREATE FUNCTION `dbx_routine_check_2`(a INT) RETURNS int DETERMINISTIC RETURN a;",+ "DROP FUNCTION IF EXISTS `app`.`dbx_routine_check_2`;",+ "DROP FUNCTION IF EXISTS `app`.`odd``name`;",+ `${create};`,+ ]);++ await expect(prepare(create, "odd`name", "FUNCTION")).resolves.toBe(true);+ expect(api.executeQuery).toHaveBeenCalledTimes(4);+ });++ it.each([+ ["a plain query", "SELECT 1"],+ ["a routine call", "CALL refresh_cache()"],+ ["ALTER PROCEDURE", "ALTER PROCEDURE `refresh_cache` COMMENT 'x'"],+ ["an explicit DROP", "DROP PROCEDURE IF EXISTS `refresh_cache`"],+ ["a rename to another name", "CREATE PROCEDURE `other_cache`() BEGIN SELECT 1; END"],+ ["a different routine kind", "CREATE FUNCTION `refresh_cache`() RETURNS int RETURN 1"],+ ["IF NOT EXISTS", "CREATE PROCEDURE IF NOT EXISTS `refresh_cache`() BEGIN SELECT 1; END"],+ ["a schema-qualified name", "CREATE PROCEDURE `app`.`refresh_cache`() BEGIN SELECT 1; END"],+ ["an unquoted schema-qualified name", "CREATE PROCEDURE app.refresh_cache() BEGIN SELECT 1; END"],+ ["a name that only starts like the tab's", "CREATE PROCEDURE refresh_cache_v2() BEGIN SELECT 1; END"],+ ["a leading comment", "-- edited\nCREATE PROCEDURE `refresh_cache`() BEGIN SELECT 1; END"],+ ])("leaves %s untouched", async (_description, sql) => {+ await expect(prepare(sql)).resolves.toBe(false);+ expect(api.buildExecutableObjectSourceStatements).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("skips non-MySQL tabs and non-routine objects without calling the backend", async () => {+ const create = "CREATE PROCEDURE `refresh_cache`() BEGIN SELECT 1; END";+ await expect(prepareRoutineSourceRun({ identity: identity("refresh_cache"), connectionId: "conn-1", database: "app", databaseType: "postgres", schema: "app", objectType: "PROCEDURE", name: "refresh_cache", sql: create })).resolves.toBe(false);+ await expect(prepareRoutineSourceRun({ identity: identity("refresh_cache"), connectionId: "conn-1", database: "app", databaseType: "mysql", schema: "app", objectType: "VIEW", name: "refresh_cache", sql: create })).resolves.toBe(false);+ expect(api.buildExecutableObjectSourceStatements).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("does nothing when the backend turns the CREATE into a rename (trailing cleanup DROP)", async () => {+ const create = "CREATE PROCEDURE `refresh_cache`() BEGIN SELECT 1; END";+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue([...replaceSequence(`${create};`), "DROP PROCEDURE IF EXISTS `app`.`refresh_cache_old`;"]);++ await expect(prepare(create)).resolves.toBe(false);+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("does nothing when the backend returns a bare statement", async () => {+ const create = "CREATE PROCEDURE `refresh_cache`() BEGIN SELECT 1; END";+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue([`${create};`]);++ await expect(prepare(create)).resolves.toBe(false);+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("stops at the failing validation step and releases the source-save lock", async () => {+ const create = "CREATE PROCEDURE `refresh_cache`() BEGIN SELEC 1; END";+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue(replaceSequence(`${create};`));+ vi.mocked(api.executeQuery)+ .mockResolvedValueOnce({} as Awaited<ReturnType<typeof api.executeQuery>>)+ .mockRejectedValueOnce(new Error("You have an error in your SQL syntax"));++ await expect(prepare(create)).rejects.toThrow("You have an error in your SQL syntax");++ // The old routine's DROP never ran, so the original stays in place.+ expect(api.executeQuery).toHaveBeenCalledTimes(2);+ const release = beginSourceSave(identity("refresh_cache"));+ release();+ });++ it("refuses to run while the same routine is being saved", async () => {+ const create = "CREATE PROCEDURE `refresh_cache`() BEGIN SELECT 1; END";+ vi.mocked(api.buildExecutableObjectSourceStatements).mockResolvedValue(replaceSequence(`${create};`));+ const busy = identity("refresh_cache");+ const release = beginSourceSave(busy);+ try {+ await expect(prepareRoutineSourceRun({ identity: busy, connectionId: "conn-1", database: "app", databaseType: "mysql", schema: "app", objectType: "PROCEDURE", name: "refresh_cache", sql: create })).rejects.toThrow();+ expect(api.executeQuery).not.toHaveBeenCalled();+ } finally {+ release();+ }+ });+});+describe("Oracle routine dependency source rewrite", () => {it("routes complete caller source through the shared backend implementation", async () => {const input = { databaseType: "oceanbase-oracle" as const, callerType: "VIEW" as const, targetType: "FUNCTION" as const, schema: "APP", oldName: "F_OLD", newName: "F_NEW", source: "CREATE VIEW v AS SELECT F_OLD(id) FROM t" };diff --git a/apps/desktop/src/lib/table/objectSourceEditor.ts b/apps/desktop/src/lib/table/objectSourceEditor.tsindex 64f29fdcf6..97c5c65f2a 100644--- a/apps/desktop/src/lib/table/objectSourceEditor.ts+++ b/apps/desktop/src/lib/table/objectSourceEditor.ts@@ -1,5 +1,6 @@import type { DatabaseType, ObjectSourceKind } from "@/types/database";import * as api from "@/lib/backend/api";+import { beginSourceSave, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";export type BuildEditableObjectSourceSqlInput = {databaseType: DatabaseType;@@ -127,3 +128,59 @@ export async function executeObjectSourceSave(connectionId: string, database: st}}}++// Mirrors the backend's MySQL routine declaration parser: `CREATE [DEFINER = account] {PROCEDURE|FUNCTION} name (`.+const mysqlCreateRoutineHeader = /^\s*CREATE\s+(?:DEFINER\s*=\s*(?:(?:`(?:``|[^`])+`|'(?:''|[^'])+'|\S+)\s*@\s*(?:`(?:``|[^`])+`|'(?:''|[^'])+'|\S+)|CURRENT_USER(?:\(\))?)\s+)?(FUNCTION|PROCEDURE)\s+(`(?:``|[^`])+`|[A-Za-z_][\w$]*)\s*\(/i;++/**+ * MySQL has no CREATE OR REPLACE for stored routines, so the CREATE statement a routine source tab shows fails with+ * "already exists" when it is simply run. Saving replaces the routine safely (validate the new body under a temporary+ * name, DROP ... IF EXISTS, CREATE); running the tab's CREATE needs the same statements ahead of it.+ */+export function supportsRoutineSourceReplaceOnRun(databaseType: DatabaseType | undefined, objectType: ObjectSourceKind): boolean {+ return (objectType === "PROCEDURE" || objectType === "FUNCTION") && !!databaseType && mysqlLikeRoutineRenameTypes.has(databaseType);+}++// Only a plain `CREATE <same kind> <same unqualified name>(...)` replaces the tab's routine. Renames, other routines,+// `IF NOT EXISTS` and schema-qualified targets keep the normal CREATE semantics.+function createsSourceRoutine(objectType: ObjectSourceKind, name: string, sql: string): boolean {+ const header = mysqlCreateRoutineHeader.exec(sql);+ if (!header || header[1].toUpperCase() !== objectType) return false;+ const declared = header[2].startsWith("`") ? header[2].slice(1, -1).replaceAll("``", "`") : header[2];+ return declared.toLowerCase() === name.toLowerCase();+}++export type RoutineSourceRunPreparationInput = {+ identity: SourceIdentitySnapshot;+ connectionId: string;+ database: string;+ databaseType: DatabaseType;+ schema: string;+ objectType: ObjectSourceKind;+ name: string;+ /** The single statement about to run. */+ sql: string;+};++/**+ * Executes the Save sequence up to, but excluding, its final CREATE so that `sql` itself can then run through the+ * normal query pipeline (results, error positions and history stay untouched). The new body is validated under a+ * temporary name before the existing routine is dropped, so a syntax error never leaves the routine deleted.+ * Returns false, executing nothing, when `sql` is not a plain CREATE of the tab's routine.+ */+export async function prepareRoutineSourceRun(input: RoutineSourceRunPreparationInput): Promise<boolean> {+ const { databaseType, objectType, name, sql } = input;+ if (!supportsRoutineSourceReplaceOnRun(databaseType, objectType) || !createsSourceRoutine(objectType, name, sql)) return false;++ const statements = await buildExecutableObjectSourceStatements({ databaseType, objectType, schema: input.schema, name, source: sql });+ // A trailing DROP means the backend treated the CREATE as a rename, which Run must not turn into a replace.+ if (statements.length < 2 || !/^\s*CREATE\b/i.test(statements[statements.length - 1])) return false;++ const release = beginSourceSave(input.identity);+ try {+ await executeObjectSourceSave(input.connectionId, input.database, databaseType, statements.slice(0, -1), input.schema);+ } finally {+ release();+ }+ return true;+}diff --git a/apps/desktop/src/stores/__tests__/queryStore.mysqlRoutineSourceRun.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.mysqlRoutineSourceRun.spec.tsnew file mode 100644index 0000000000..31ef808da4--- /dev/null+++ b/apps/desktop/src/stores/__tests__/queryStore.mysqlRoutineSourceRun.spec.ts@@ -0,0 +1,171 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, it, vi } from "vitest";++// Issue #12855: the CREATE statement of a MySQL routine source tab cannot simply be re-run (no CREATE OR REPLACE+// for stored routines), so Run first executes the validate + drop steps of the Save sequence, then runs the tab's own+// statement through the normal pipeline.+const executeMulti = vi.fn();+const executeMultiWithProgress = vi.fn();+const executeQuery = vi.fn();+const buildExecutableObjectSourceStatements = vi.fn();+const analyzeEditableQueryEditability = vi.fn();+const getConnectionConfig = vi.fn();+const prepareQueryPaginationExecutionPlan = vi.fn(async (options) => ({+ sqlToExecute: options.sql,+ pageSql: undefined,+ pageLimit: undefined,+ pageOffset: undefined,+ countSql: undefined,+ useAgentResultSession: false,+}));+const editorSettings = {+ pageSize: 100,+ autoCalculateTotalRows: false,+};++vi.mock("@/lib/backend/api", () => ({+ analyzeEditableQueryEditability,+ buildExecutableObjectSourceStatements,+ closeClientConnectionSession: vi.fn().mockResolvedValue(undefined),+ closeQuerySession: vi.fn().mockResolvedValue(undefined),+ executeMulti,+ executeMultiWithProgress,+ executeQuery,+ prepareQueryPaginationExecutionPlan,+ saveOpenTabsState: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("@/stores/connectionStore", () => ({+ useConnectionStore: () => ({+ ensureConnected: vi.fn().mockResolvedValue(undefined),+ getConfig: getConnectionConfig,+ lookupLocalCompletionTables: vi.fn().mockReturnValue([]),+ recordConnectionLostError: vi.fn(),+ }),+}));++vi.mock("@/stores/settingsStore", () => ({+ useSettingsStore: () => ({ editorSettings }),+}));++const CREATE = "CREATE DEFINER=`root`@`%` PROCEDURE `refresh_cache`(IN a INT)\nBEGIN\n SELECT a + 100 AS v;\nEND";+const REPLACE_SEQUENCE = [+ "DROP PROCEDURE IF EXISTS `app`.`dbx_routine_check_1`;",+ "CREATE DEFINER=`root`@`%` PROCEDURE `dbx_routine_check_1`(IN a INT)\nBEGIN\n SELECT a + 100 AS v;\nEND;",+ "DROP PROCEDURE IF EXISTS `app`.`dbx_routine_check_1`;",+ "DROP PROCEDURE IF EXISTS `app`.`refresh_cache`;",+ `${CREATE};`,+];++describe("queryStore MySQL routine source Run", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("localStorage", { getItem: vi.fn(() => null), setItem: vi.fn(), removeItem: vi.fn() });+ setActivePinia(createPinia());+ getConnectionConfig.mockReturnValue({ id: "mysql-1", name: "MySQL", db_type: "mysql", database: "app", query_timeout_secs: 30 });+ buildExecutableObjectSourceStatements.mockResolvedValue(REPLACE_SEQUENCE);+ analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "not-select" });+ executeQuery.mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 });+ executeMulti.mockResolvedValue([{ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 }]);+ executeMultiWithProgress.mockResolvedValue([+ { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 },+ { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 },+ ]);+ });++ async function openSourceTab(sql: string, objectType: "PROCEDURE" | "FUNCTION" | "VIEW" = "PROCEDURE", name = "refresh_cache") {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.openObjectSourceTab({ connectionId: "mysql-1", database: "app", title: `Source - ${name}`, schema: "app", sql, objectSource: { schema: "app", name, objectType } });+ return { store, id };+ }++ it("validates and drops the existing routine before running the tab's own CREATE unchanged", async () => {+ const { store, id } = await openSourceTab(CREATE);++ await store.executeTabSql(id, CREATE);++ expect(buildExecutableObjectSourceStatements).toHaveBeenCalledWith({ databaseType: "mysql", objectType: "PROCEDURE", schema: "app", name: "refresh_cache", source: CREATE });+ expect(executeQuery.mock.calls.map((call) => call[2])).toEqual(REPLACE_SEQUENCE.slice(0, -1));+ expect(executeQuery.mock.calls.every((call) => call[0] === "mysql-1" && call[1] === "app")).toBe(true);+ // The CREATE itself goes through the normal pipeline exactly as typed, after every preparation step.+ expect(executeMulti).toHaveBeenCalledTimes(1);+ expect(executeMulti.mock.calls[0]?.[2]).toBe(CREATE);+ expect(Math.max(...executeQuery.mock.invocationCallOrder)).toBeLessThan(executeMulti.mock.invocationCallOrder[0]!);+ expect(store.tabs.find((tab) => tab.id === id)?.result?.execution_error).not.toBe(true);+ });++ it("covers functions with the same flow", async () => {+ const createFunction = "CREATE FUNCTION `active_count`() RETURNS int DETERMINISTIC RETURN 1";+ const sequence = ["DROP FUNCTION IF EXISTS `app`.`dbx_routine_check_2`;", "CREATE FUNCTION `dbx_routine_check_2`() RETURNS int DETERMINISTIC RETURN 1;", "DROP FUNCTION IF EXISTS `app`.`dbx_routine_check_2`;", "DROP FUNCTION IF EXISTS `app`.`active_count`;", `${createFunction};`];+ buildExecutableObjectSourceStatements.mockResolvedValue(sequence);+ const { store, id } = await openSourceTab(createFunction, "FUNCTION", "active_count");++ await store.executeTabSql(id, createFunction);++ expect(executeQuery.mock.calls.map((call) => call[2])).toEqual(sequence.slice(0, -1));+ expect(executeMulti.mock.calls[0]?.[2]).toBe(createFunction);+ });++ it("leaves a plain query tab alone, so CREATE keeps its normal semantics there", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");++ await store.executeTabSql(id, CREATE);++ expect(buildExecutableObjectSourceStatements).not.toHaveBeenCalled();+ expect(executeQuery).not.toHaveBeenCalled();+ expect(executeMulti.mock.calls[0]?.[2]).toBe(CREATE);+ });++ it("leaves scripts with other statements and other routines to run exactly as written", async () => {+ const { store, id } = await openSourceTab(CREATE);++ const script = `${CREATE};\nCALL refresh_cache(1);`;+ await store.executeTabSql(id, script);+ await store.executeTabSql(id, "CREATE PROCEDURE `refresh_cache_v2`() BEGIN SELECT 1; END");+ await store.executeTabSql(id, "CALL refresh_cache(1)");++ expect(buildExecutableObjectSourceStatements).not.toHaveBeenCalled();+ expect(executeQuery).not.toHaveBeenCalled();+ expect(executeMultiWithProgress.mock.calls.map((call) => call[2])).toEqual([script]);+ expect(executeMulti.mock.calls.map((call) => call[2])).toEqual(["CREATE PROCEDURE `refresh_cache_v2`() BEGIN SELECT 1; END", "CALL refresh_cache(1)"]);+ });++ it("does not apply to non-routine source tabs or other databases", async () => {+ const view = await openSourceTab("ALTER VIEW `v` AS SELECT 1", "VIEW", "v");+ await view.store.executeTabSql(view.id, "ALTER VIEW `v` AS SELECT 1");++ getConnectionConfig.mockReturnValue({ id: "mysql-1", name: "Postgres", db_type: "postgres", database: "app", query_timeout_secs: 30 });+ const postgres = await openSourceTab(CREATE);+ await postgres.store.executeTabSql(postgres.id, CREATE);++ expect(buildExecutableObjectSourceStatements).not.toHaveBeenCalled();+ expect(executeQuery).not.toHaveBeenCalled();+ });++ it("still runs the statement when the preparation fails, so the real error is reported", async () => {+ executeQuery.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error("You have an error in your SQL syntax"));+ executeMulti.mockResolvedValue([{ columns: ["Error"], rows: [["You have an error in your SQL syntax near 'SELEC'"]], affected_rows: 0, execution_time_ms: 1, execution_error: true }]);+ const { store, id } = await openSourceTab(CREATE);++ await store.executeTabSql(id, CREATE);++ // Validation failed at step 2, so the old routine's DROP never ran and the statement itself reports the error.+ expect(executeQuery).toHaveBeenCalledTimes(2);+ expect(executeMulti).toHaveBeenCalledTimes(1);+ expect(executeMulti.mock.calls[0]?.[2]).toBe(CREATE);+ expect(store.tabs.find((tab) => tab.id === id)?.result?.rows[0]?.[0]).toContain("syntax");+ });++ it("still runs the statement when the backend cannot build the replace sequence", async () => {+ buildExecutableObjectSourceStatements.mockRejectedValue(new Error("backend unavailable"));+ const { store, id } = await openSourceTab(CREATE);++ await store.executeTabSql(id, CREATE);++ expect(executeQuery).not.toHaveBeenCalled();+ expect(executeMulti).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 1a25584cce..2db4768f4d 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -146,7 +146,7 @@ import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeSimport { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";import { assertSourceIdentity, captureSourceIdentity, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";-import { buildEditableObjectSource } from "@/lib/table/objectSourceEditor";+import { buildEditableObjectSource, prepareRoutineSourceRun, supportsRoutineSourceReplaceOnRun } from "@/lib/table/objectSourceEditor";import { disposeAllSqlServerActivityTraces, disposeSqlServerActivityTrace } from "@/lib/sqlserver/sqlServerActivityTraceRuntime";import type { SavedSqlFile } from "@/types/database";import i18n, { currentLocale } from "@/i18n";@@ -1656,6 +1656,24 @@ export const useQueryStore = defineStore("query", () => {appendDebugLog(level, `[DBX][executeTabSql:${event}]`, details);}+ /**+ * MySQL cannot replace a stored routine in place, so running the CREATE statement of a routine source tab would fail+ * with "already exists". Run the replace preparation (validate the new body, drop the old routine) first. Best effort:+ * when it does not apply or fails, the statement runs unchanged and reports the real error (e.g. the syntax error+ * the validation hit) instead of this step masking it.+ */+ async function prepareObjectSourceRoutineRun(tab: QueryTab, databaseType: DatabaseType, database: string, sql: string, parameterOptions: SqlParameterOptions | undefined, traceId: string) {+ const source = tab.objectSource;+ if (!source || !supportsRoutineSourceReplaceOnRun(databaseType, source.objectType)) return;+ // The preparation targets one routine; a script with other statements runs exactly as written.+ if (splitSqlStatementRanges(sql, databaseType, parameterOptions).length !== 1) return;+ try {+ await prepareRoutineSourceRun({ identity: getObjectSourceIdentitySnapshot(tab)!, connectionId: tab.connectionId, database, databaseType, schema: source.schema || tab.schema || database, objectType: source.objectType, name: source.name, sql });+ } catch (error) {+ queryExecutionLog("warn", "routine-source-run:prepare-failed", { traceId, error });+ }+ }+function findExecutionTab(id: string): QueryTab | undefined {return tabs.value.find((tab) => tab.id === id) ?? multiDbExecutionWorkers.get(id);}@@ -8680,6 +8698,9 @@ export const useQueryStore = defineStore("query", () => {}const sourceLabelDatabase = targetDatabase || conn?.database;const executionClientSessionId = options?.pagination?.clientSessionId ?? (tab.mode === "query" || tab.mode === "data" ? tabClientSessionId(tab) : undefined);+ if (tab.mode === "query" && tab.objectSource && !usesExternalExecutionTarget && effectiveDbType && tabs.value.includes(tab) && executionConnectionId === tab.connectionId && executionDatabase === tab.database) {+ await prepareObjectSourceRoutineRun(tab, effectiveDbType, executionDatabase, sqlToExecute, sqlStatementParameterOptions, traceId);+ }const currentBeforeDispatch = findExecutionTab(id);if (currentBeforeDispatch?.executionId !== executionId || currentBeforeDispatch.isCancelling || manualTransactionTargetEpoch(currentBeforeDispatch) !== executionTargetEpoch) {queryExecutionLog("info", "dispatch:skipped-cancelled", { traceId, elapsed: elapsed() });diff --git a/crates/dbx-core/tests/live_mysql_routine_source_replace.rs b/crates/dbx-core/tests/live_mysql_routine_source_replace.rsnew file mode 100644index 0000000000..c5fc71b769--- /dev/null+++ b/crates/dbx-core/tests/live_mysql_routine_source_replace.rs@@ -0,0 +1,257 @@+//! Live coverage for issue #12855: the CREATE statement a MySQL routine source tab shows cannot be+//! re-run (`ERROR 1304 ... already exists`) because MySQL has no `CREATE OR REPLACE` for stored routines.+//!+//! Saving replaces the routine with the `object_source_sql` sequence (validate under a temporary name,+//! then `DROP ... IF EXISTS`, then `CREATE`). The desktop "Run" path executes every statement of that+//! sequence except the trailing `CREATE` first, then runs the tab's own `CREATE` through the normal+//! query pipeline so results and error positions stay untouched. These tests drive both flows through+//! the backend executor against a real server.++use dbx_core::connection::AppState;+use dbx_core::models::connection::{ConnectionConfig, DatabaseType};+use dbx_core::object_source_sql::{+ build_editable_object_source, build_executable_object_source_statements, EditableObjectSourceSqlInput,+};+use dbx_core::query::execute_sql_statement;+use dbx_core::types::ObjectSourceKind;+use serde_json::json;++fn live_mysql_config(id: &str) -> ConnectionConfig {+ let host = std::env::var("DBX_LIVE_MYSQL_ROUTINE_HOST").expect("DBX_LIVE_MYSQL_ROUTINE_HOST");+ let port =+ std::env::var("DBX_LIVE_MYSQL_ROUTINE_PORT").ok().and_then(|value| value.parse::<u16>().ok()).unwrap_or(3306);+ let username = std::env::var("DBX_LIVE_MYSQL_ROUTINE_USER").unwrap_or_else(|_| "root".to_string());+ let password = std::env::var("DBX_LIVE_MYSQL_ROUTINE_PASSWORD").expect("DBX_LIVE_MYSQL_ROUTINE_PASSWORD");++ serde_json::from_value(json!({+ "id": id,+ "name": id,+ "db_type": DatabaseType::Mysql,+ "host": host,+ "port": port,+ "username": username,+ "password": password,+ "database": null,+ "connect_timeout_secs": 10,+ "query_timeout_secs": 30,+ "idle_timeout_secs": 60,+ "keepalive_interval_secs": 0+ }))+ .expect("live MySQL routine config should deserialize")+}++struct LiveRoutineEnv {+ state: AppState,+ connection_id: String,+ database: String,+ definer: String,+ db_path: std::path::PathBuf,+}++impl LiveRoutineEnv {+ async fn create() -> Self {+ let suffix = uuid::Uuid::new_v4().simple().to_string();+ let config = live_mysql_config(&format!("live-mysql-routine-source-{suffix}"));+ let db_path = std::env::temp_dir().join(format!("dbx-live-routine-source-{suffix}.db"));+ let storage = dbx_core::persistence::test_storage::open(&db_path).await.expect("open temp storage");+ let state = AppState::new(storage);+ let connection_id = config.id.clone();+ state.configs.write().await.insert(connection_id.clone(), config);++ let env = Self {+ state,+ connection_id,+ database: format!("dbx_routine_source_{suffix}"),+ definer: format!("dbx_definer_{}", &suffix[..8]),+ db_path,+ };+ env.exec_on("", &format!("CREATE DATABASE `{}`", env.database)).await.expect("create isolated database");+ env.exec_on("", &format!("CREATE USER '{}'@'%'", env.definer)).await.expect("create definer account");+ // Routines run with the definer's privileges (SQL SECURITY DEFINER), so the account needs access to call them.+ env.exec_on("", &format!("GRANT ALL PRIVILEGES ON `{}`.* TO '{}'@'%'", env.database, env.definer))+ .await+ .expect("grant definer account access");+ env+ }++ async fn exec_on(&self, database: &str, sql: &str) -> Result<dbx_core::db::QueryResult, String> {+ execute_sql_statement(&self.state, &self.connection_id, database, sql, None, None).await+ }++ async fn exec(&self, sql: &str) -> Result<dbx_core::db::QueryResult, String> {+ self.exec_on(&self.database, sql).await+ }++ /// The text DBX loads into the source tab: `SHOW CREATE ...` run through the editable-source builder.+ async fn source_tab_text(&self, kind: ObjectSourceKind, name: &str) -> String {+ let keyword = if kind == ObjectSourceKind::Function { "FUNCTION" } else { "PROCEDURE" };+ let result = self.exec(&format!("SHOW CREATE {keyword} `{name}`")).await.expect("SHOW CREATE routine");+ let ddl = result.rows[0][2].as_str().expect("routine DDL column").to_string();+ build_editable_object_source(self.input(kind, name, &ddl))+ }++ fn input(&self, kind: ObjectSourceKind, name: &str, source: &str) -> EditableObjectSourceSqlInput {+ EditableObjectSourceSqlInput {+ database_type: DatabaseType::Mysql,+ object_type: kind,+ schema: Some(self.database.clone()),+ name: name.to_string(),+ source: source.to_string(),+ }+ }++ /// Everything the desktop Run path executes before the tab's own CREATE.+ fn run_preparation(&self, kind: ObjectSourceKind, name: &str, source: &str) -> Vec<String> {+ let mut statements =+ build_executable_object_source_statements(self.input(kind, name, source)).expect("executable statements");+ let create = statements.pop().expect("replace sequence ends with the routine CREATE");+ assert!(create.trim_start().to_ascii_uppercase().starts_with("CREATE"), "unexpected tail: {create}");+ statements+ }++ async fn run_all(&self, statements: &[String]) -> Result<(), String> {+ for statement in statements {+ self.exec(statement).await?;+ }+ Ok(())+ }++ async fn cleanup(self) {+ let database = self.exec_on("", &format!("DROP DATABASE IF EXISTS `{}`", self.database)).await;+ let user = self.exec_on("", &format!("DROP USER IF EXISTS '{}'@'%'", self.definer)).await;+ let _ = std::fs::remove_file(&self.db_path);+ database.expect("drop isolated database");+ user.expect("drop definer account");+ }+}++#[tokio::test]+#[ignore = "requires a writable MySQL 8 endpoint (DBX_LIVE_MYSQL_ROUTINE_HOST/PORT/USER/PASSWORD)"]+async fn live_mysql_procedure_source_run_replaces_existing_routine_and_keeps_definer() {+ let env = LiveRoutineEnv::create().await;+ let name = "p_issue_12855";+ let outcome = async {+ let definer = &env.definer;+ env.exec(&format!(+ "CREATE DEFINER=`{definer}`@`%` PROCEDURE `{name}`(IN a INT)\nBEGIN\n SELECT a + 1 AS v;\nEND"+ ))+ .await?;++ let tab_text = env.source_tab_text(ObjectSourceKind::Procedure, name).await;+ assert!(tab_text.contains(&format!("DEFINER=`{definer}`@`%`")), "{tab_text}");+ let edited = tab_text.replace("SELECT a + 1 AS v", "SELECT a + 100 AS v");++ // The bug: running the edited CREATE as-is hits the existing routine.+ let direct = env.exec(&edited).await.expect_err("re-running CREATE on an existing routine must fail");+ assert!(direct.contains("already exists"), "{direct}");++ // Preparation + the tab's own CREATE replaces the routine and keeps its DEFINER.+ let preparation = env.run_preparation(ObjectSourceKind::Procedure, name, &edited);+ env.run_all(&preparation).await?;+ env.exec(&edited).await?;+ let called = env.exec(&format!("CALL `{name}`(1)")).await?;+ assert_eq!(called.rows, vec![vec![json!("101")]]);+ let replaced = env.source_tab_text(ObjectSourceKind::Procedure, name).await;+ assert!(replaced.contains(&format!("DEFINER=`{definer}`@`%`")), "{replaced}");++ // A second edit goes through the very same sequence (idempotent), and no validation routine lingers.+ let edited_again = replaced.replace("a + 100", "a + 200");+ env.run_all(&env.run_preparation(ObjectSourceKind::Procedure, name, &edited_again)).await?;+ env.exec(&edited_again).await?;+ assert_eq!(env.exec(&format!("CALL `{name}`(1)")).await?.rows, vec![vec![json!("201")]]);++ // Save runs the complete sequence, ending with the CREATE, and lands on the same routine.+ let saved = edited_again.replace("a + 200", "a + 300");+ let save_statements =+ build_executable_object_source_statements(env.input(ObjectSourceKind::Procedure, name, &saved))+ .map_err(|error| error.to_string())?;+ env.run_all(&save_statements).await?;+ assert_eq!(env.exec(&format!("CALL `{name}`(1)")).await?.rows, vec![vec![json!("301")]]);+ let leftovers = env+ .exec(&format!(+ "SELECT ROUTINE_NAME FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = '{}'",+ env.database+ ))+ .await?;+ assert_eq!(leftovers.rows, vec![vec![json!(name)]]);+ Ok::<_, String>(())+ }+ .await;+ env.cleanup().await;+ outcome.expect("procedure Run replacement should succeed on a live MySQL server");+}++#[tokio::test]+#[ignore = "requires a writable MySQL 8 endpoint (DBX_LIVE_MYSQL_ROUTINE_HOST/PORT/USER/PASSWORD)"]+async fn live_mysql_function_source_run_replaces_existing_routine_and_keeps_definer() {+ let env = LiveRoutineEnv::create().await;+ let name = "f_issue_12855";+ let outcome = async {+ let definer = &env.definer;+ env.exec(&format!(+ "CREATE DEFINER=`{definer}`@`%` FUNCTION `{name}`(a INT) RETURNS int\n DETERMINISTIC\nBEGIN\n RETURN a + 1;\nEND"+ ))+ .await?;++ let tab_text = env.source_tab_text(ObjectSourceKind::Function, name).await;+ let edited = tab_text.replace("a + 1", "a + 100");+ let direct = env.exec(&edited).await.expect_err("re-running CREATE on an existing function must fail");+ assert!(direct.contains("already exists"), "{direct}");++ env.run_all(&env.run_preparation(ObjectSourceKind::Function, name, &edited)).await?;+ env.exec(&edited).await?;+ assert_eq!(env.exec(&format!("SELECT `{name}`(1)")).await?.rows, vec![vec![json!("101")]]);+ let replaced = env.source_tab_text(ObjectSourceKind::Function, name).await;+ assert!(replaced.contains(&format!("DEFINER=`{definer}`@`%`")), "{replaced}");+ Ok::<_, String>(())+ }+ .await;+ env.cleanup().await;+ outcome.expect("function Run replacement should succeed on a live MySQL server");+}++#[tokio::test]+#[ignore = "requires a writable MySQL 8 endpoint (DBX_LIVE_MYSQL_ROUTINE_HOST/PORT/USER/PASSWORD)"]+async fn live_mysql_routine_source_run_keeps_original_when_the_edited_body_is_invalid() {+ let env = LiveRoutineEnv::create().await;+ let name = "p_issue_12855_invalid";+ let outcome = async {+ env.exec(&format!("CREATE PROCEDURE `{name}`()\nBEGIN\n SELECT 1 AS v;\nEND")).await?;+ let tab_text = env.source_tab_text(ObjectSourceKind::Procedure, name).await;+ let broken = tab_text.replace("SELECT 1 AS v", "SELEC 1 AS v");++ // Validation under the temporary name fails first, so the preparation never reaches the DROP.+ let preparation = env.run_preparation(ObjectSourceKind::Procedure, name, &broken);+ let validation = env.run_all(&preparation).await.expect_err("invalid body must fail validation");+ assert!(validation.contains("syntax"), "{validation}");++ // The tab's own CREATE then reports the real syntax error rather than "already exists".+ let direct = env.exec(&broken).await.expect_err("invalid CREATE must fail");+ assert!(direct.contains("syntax") && !direct.contains("already exists"), "{direct}");++ // The original routine is untouched and still callable.+ assert_eq!(env.exec(&format!("CALL `{name}`()")).await?.rows, vec![vec![json!("1")]]);+ Ok::<_, String>(())+ }+ .await;+ env.cleanup().await;+ outcome.expect("an invalid edit must leave the original routine in place");+}++#[tokio::test]+#[ignore = "requires a writable MySQL 8 endpoint (DBX_LIVE_MYSQL_ROUTINE_HOST/PORT/USER/PASSWORD)"]+async fn live_mysql_routine_source_run_creates_a_missing_routine_without_error() {+ let env = LiveRoutineEnv::create().await;+ let name = "p_issue_12855_missing";+ let outcome = async {+ // First creation: nothing to drop, so every preparation step (DROP ... IF EXISTS) must be a no-op.+ let source = format!("CREATE PROCEDURE `{name}`()\nBEGIN\n SELECT 7 AS v;\nEND");+ env.run_all(&env.run_preparation(ObjectSourceKind::Procedure, name, &source)).await?;+ env.exec(&source).await?;+ assert_eq!(env.exec(&format!("CALL `{name}`()")).await?.rows, vec![vec![json!("7")]]);+ Ok::<_, String>(())+ }+ .await;+ env.cleanup().await;+ outcome.expect("creating a routine that does not exist yet must not fail");+}diff --git a/crates/dbx-sql-core/src/object_source_sql.rs b/crates/dbx-sql-core/src/object_source_sql.rsindex cc64ab7775..1ae3cc547e 100644--- a/crates/dbx-sql-core/src/object_source_sql.rs+++ b/crates/dbx-sql-core/src/object_source_sql.rs@@ -2987,6 +2987,38 @@ mod tests {);}+ #[test]+ fn mysql_routine_replace_sequence_keeps_the_create_last_for_the_desktop_run_path() {+ // The desktop Run path of a routine source tab (issue #12855) executes every statement before the last one+ // as the replace preparation and then runs the tab's own CREATE through the normal query pipeline. That only+ // holds while the CREATE stays last; a rename ends with the cleanup DROP instead and is never prepared.+ for (object_type, source) in [+ (ObjectSourceKind::Procedure, "CREATE DEFINER=`root`@`%` PROCEDURE `refresh_cache`() BEGIN SELECT 1; END"),+ (ObjectSourceKind::Function, "CREATE FUNCTION `refresh_cache`() RETURNS INT RETURN 1"),+ ] {+ let keyword = object_type_keyword(&object_type);+ let input = |name: &str| EditableObjectSourceSqlInput {+ database_type: DatabaseType::Mysql,+ object_type: object_type.clone(),+ schema: Some("app".to_string()),+ name: name.to_string(),+ source: source.to_string(),+ };++ let statements = build_executable_object_source_statements(input("refresh_cache")).unwrap();+ let (create, preparation) = statements.split_last().unwrap();+ assert_eq!(create, &format!("{source};"));+ assert_eq!(preparation.len(), 4);+ assert!(preparation[0].starts_with(&format!("DROP {keyword} IF EXISTS `app`.`dbx_routine_check_")));+ assert!(preparation[1].starts_with("CREATE") && preparation[1].contains("`dbx_routine_check_"));+ assert_eq!(preparation[2], preparation[0]);+ assert_eq!(preparation[3], format!("DROP {keyword} IF EXISTS `app`.`refresh_cache`;"));++ let renamed = build_executable_object_source_statements(input("refresh_cache_old")).unwrap();+ assert_eq!(renamed.last().unwrap(), &format!("DROP {keyword} IF EXISTS `app`.`refresh_cache_old`;"));+ }+ }+#[test]fn mysql_transfer_routine_replacement_uses_scoped_validation_name() {let statements = build_mysql_routine_replacement_statements(