feat(sql-library): support batch connection and database changes
Closes #9471
This commit is contained in:
1 parent
32f60e1fd3
commit
43ddfce93d
19 files changed
+850
-14
No files matched your search
@@ -0,0 +1,78 @@
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { useQueryStore } from "@/stores/queryStore";
|
||||
import type { SavedSqlFile } from "@/types/database";
|
||||
|
||||
vi.mock("@/lib/backend/api", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/backend/api")>()),
|
||||
executeMulti: vi.fn(),
|
||||
executeQuery: vi.fn(),
|
||||
}));
|
||||
|
||||
const timestamp = "2026-09-01T00:00:00.000Z";
|
||||
const savedFile: SavedSqlFile = {
|
||||
id: "saved-1",
|
||||
connectionId: "source",
|
||||
database: "sales",
|
||||
catalog: "hive",
|
||||
schema: "reporting",
|
||||
name: "report.sql",
|
||||
sql: "SELECT persisted;",
|
||||
sqlLoaded: true,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
};
|
||||
|
||||
function installLocalStorage() {
|
||||
const data = new Map<string, string>();
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: (key: string) => data.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => data.set(key, value),
|
||||
removeItem: (key: string) => data.delete(key),
|
||||
});
|
||||
}
|
||||
|
||||
describe("queryStore saved SQL target synchronization", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
installLocalStorage();
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("retargets every matching tab while preserving unsaved editor state", () => {
|
||||
const store = useQueryStore();
|
||||
const firstId = store.openSavedSql(savedFile);
|
||||
const secondId = store.createTab("source", "sales", "second", "query", "reporting", "SELECT second;", "hive", { forceNew: true });
|
||||
store.linkSavedSql(secondId, savedFile.id);
|
||||
store.updateSql(firstId, "SELECT unsaved first;");
|
||||
store.updateSql(secondId, "SELECT unsaved second;");
|
||||
|
||||
const first = store.tabs.find((tab) => tab.id === firstId)!;
|
||||
const second = store.tabs.find((tab) => tab.id === secondId)!;
|
||||
first.editorSelection = { anchor: 8, head: 8 };
|
||||
first.editorViewport = { scrollTop: 120, scrollLeft: 8 };
|
||||
|
||||
expect(store.syncSavedSqlExecutionTargets([{ ...savedFile, connectionId: "target", database: "analytics", catalog: undefined, schema: undefined }])).toBe(2);
|
||||
|
||||
expect(first).toMatchObject({ connectionId: "target", database: "analytics", sql: "SELECT unsaved first;", originalSql: savedFile.sql, editorSelection: { anchor: 8, head: 8 }, editorViewport: { scrollTop: 120, scrollLeft: 8 } });
|
||||
expect(second).toMatchObject({ connectionId: "target", database: "analytics", sql: "SELECT unsaved second;", originalSql: "SELECT second;" });
|
||||
expect(first.catalog).toBeUndefined();
|
||||
expect(first.schema).toBeUndefined();
|
||||
expect(store.tabs.find((tab) => tab.id === firstId)).toBe(first);
|
||||
expect(store.tabs.find((tab) => tab.id === secondId)).toBe(second);
|
||||
expect(store.isTabDirty(first)).toBe(true);
|
||||
expect(store.isTabDirty(second)).toBe(true);
|
||||
expect(api.executeMulti).not.toHaveBeenCalled();
|
||||
expect(api.executeQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not change tabs for files omitted from a successful batch", () => {
|
||||
const store = useQueryStore();
|
||||
const tabId = store.openSavedSql(savedFile);
|
||||
|
||||
expect(store.syncSavedSqlExecutionTargets([])).toBe(0);
|
||||
expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({ connectionId: "source", database: "sales", catalog: "hive", schema: "reporting" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { useSavedSqlStore } from "@/stores/savedSqlStore";
|
||||
import type { SavedSqlFile, SavedSqlLibrary } from "@/types/database";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
library: { folders: [], files: [] } as SavedSqlLibrary,
|
||||
syncDir: null as string | null,
|
||||
tauri: false,
|
||||
getConfig: vi.fn((id: string) => (id === "missing" ? undefined : { id, name: id, db_type: "mysql" })),
|
||||
syncTargets: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => mocks.tauri }));
|
||||
vi.mock("@/stores/settingsStore", () => ({
|
||||
useSettingsStore: () => ({ desktopSettings: { saved_sql_sync_dir: mocks.syncDir } }),
|
||||
}));
|
||||
vi.mock("@/stores/connectionStore", () => ({
|
||||
useConnectionStore: () => ({ getConfig: mocks.getConfig }),
|
||||
}));
|
||||
vi.mock("@/stores/queryStore", () => ({
|
||||
useQueryStore: () => ({ syncSavedSqlExecutionTargets: mocks.syncTargets }),
|
||||
}));
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
loadSavedSqlLibrary: vi.fn(),
|
||||
loadSavedSqlFilesForSync: vi.fn(),
|
||||
loadSavedSqlFile: vi.fn(),
|
||||
saveSavedSqlFile: vi.fn(),
|
||||
syncSavedSqlDirectory: vi.fn(),
|
||||
}));
|
||||
|
||||
const timestamp = "2026-09-01T00:00:00.000Z";
|
||||
|
||||
function savedFile(overrides: Partial<SavedSqlFile> & Pick<SavedSqlFile, "id" | "name">): SavedSqlFile {
|
||||
return {
|
||||
connectionId: "source",
|
||||
database: "sales",
|
||||
catalog: "hive",
|
||||
schema: "reporting",
|
||||
sql: "",
|
||||
sqlLoaded: false,
|
||||
orderIndex: 0,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function installLocalStorage() {
|
||||
const data = new Map<string, string>();
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: (key: string) => data.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => data.set(key, value),
|
||||
removeItem: (key: string) => data.delete(key),
|
||||
});
|
||||
}
|
||||
|
||||
async function loadStore(library: SavedSqlLibrary) {
|
||||
mocks.library = library;
|
||||
vi.mocked(api.loadSavedSqlLibrary).mockImplementation(async () => structuredClone(mocks.library));
|
||||
const store = useSavedSqlStore();
|
||||
await store.initFromStorage();
|
||||
return store;
|
||||
}
|
||||
|
||||
describe("savedSqlStore batch execution target changes", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
installLocalStorage();
|
||||
setActivePinia(createPinia());
|
||||
mocks.syncDir = null;
|
||||
mocks.tauri = false;
|
||||
mocks.getConfig.mockImplementation((id: string) => (id === "missing" ? undefined : { id, name: id, db_type: "mysql" }));
|
||||
vi.mocked(api.saveSavedSqlFile).mockImplementation(async (file) => ({ ...file }));
|
||||
vi.mocked(api.syncSavedSqlDirectory).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("keeps the existing single-file target update behavior", async () => {
|
||||
const store = await loadStore({
|
||||
folders: [{ id: "folder-1", connectionId: "source", name: "Reports", orderIndex: 0, createdAt: timestamp, updatedAt: timestamp }],
|
||||
files: [savedFile({ id: "single", folderId: "folder-1", name: "single.sql", orderIndex: 3 })],
|
||||
});
|
||||
vi.mocked(api.loadSavedSqlFile).mockResolvedValue({ ...savedFile({ id: "single", folderId: "folder-1", name: "single.sql", orderIndex: 3 }), sql: "SELECT single;", sqlLoaded: true });
|
||||
|
||||
await store.updateFileExecutionTarget("single", { connectionId: "target", database: "analytics", schema: "public" });
|
||||
|
||||
expect(store.getFile("single")).toMatchObject({ connectionId: "target", database: "analytics", schema: "public", folderId: "folder-1", orderIndex: 3, sql: "SELECT single;", sqlLoaded: true });
|
||||
expect(api.loadSavedSqlFile).toHaveBeenCalledWith("single");
|
||||
expect(mocks.syncTargets).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reassigns unloaded files in place without reading their SQL bodies", async () => {
|
||||
const store = await loadStore({
|
||||
folders: [{ id: "folder-1", connectionId: "source", name: "Reports", orderIndex: 0, createdAt: timestamp, updatedAt: timestamp }],
|
||||
files: [
|
||||
savedFile({ id: "daily", folderId: "folder-1", name: "daily.sql", orderIndex: 0 }),
|
||||
savedFile({ id: "weekly", folderId: "folder-1", name: "weekly.sql", orderIndex: 1 }),
|
||||
savedFile({ id: "existing", connectionId: "target", database: "analytics", catalog: undefined, schema: undefined, name: "other.sql", orderIndex: 4 }),
|
||||
],
|
||||
});
|
||||
|
||||
const result = await store.updateFilesExecutionTarget(["daily", "weekly"], { connectionId: "target", database: "analytics" });
|
||||
|
||||
expect(result.failures).toEqual([]);
|
||||
expect(result.updated.map((file) => file.id)).toEqual(["daily", "weekly"]);
|
||||
expect(api.loadSavedSqlFile).not.toHaveBeenCalled();
|
||||
expect(api.saveSavedSqlFile).toHaveBeenCalledTimes(2);
|
||||
expect(vi.mocked(api.saveSavedSqlFile).mock.calls.map(([file]) => file)).toEqual([
|
||||
expect.objectContaining({ id: "daily", connectionId: "target", database: "analytics", catalog: undefined, schema: undefined, folderId: "folder-1", orderIndex: 0, sql: "", sqlLoaded: false }),
|
||||
expect.objectContaining({ id: "weekly", connectionId: "target", database: "analytics", catalog: undefined, schema: undefined, folderId: "folder-1", orderIndex: 1, sql: "", sqlLoaded: false }),
|
||||
]);
|
||||
expect(store.getFile("daily")).toMatchObject({ id: "daily", name: "daily.sql", connectionId: "target", database: "analytics", folderId: "folder-1", orderIndex: 0, sqlLoaded: false });
|
||||
expect(mocks.syncTargets).toHaveBeenCalledOnce();
|
||||
expect(mocks.syncTargets.mock.calls[0]?.[0].map((file: SavedSqlFile) => file.id)).toEqual(["daily", "weekly"]);
|
||||
});
|
||||
|
||||
it("rolls back only failed files and exposes partial persistence", async () => {
|
||||
const store = await loadStore({
|
||||
folders: [{ id: "folder-1", connectionId: "source", name: "Reports", orderIndex: 0, createdAt: timestamp, updatedAt: timestamp }],
|
||||
files: [savedFile({ id: "ok", folderId: "folder-1", name: "ok.sql" }), savedFile({ id: "failed", folderId: "folder-1", name: "failed.sql", orderIndex: 1 })],
|
||||
});
|
||||
vi.mocked(api.saveSavedSqlFile).mockImplementation(async (file) => {
|
||||
if (file.id === "failed") throw new Error("disk full");
|
||||
return { ...file };
|
||||
});
|
||||
|
||||
const result = await store.updateFilesExecutionTarget(["ok", "failed"], { connectionId: "target", database: "analytics" });
|
||||
|
||||
expect(result.succeeded.map((file) => file.id)).toEqual(["ok"]);
|
||||
expect(result.failures).toEqual([expect.objectContaining({ fileId: "failed", fileName: "failed.sql", error: expect.objectContaining({ message: "disk full" }) })]);
|
||||
expect(store.getFile("ok")).toMatchObject({ connectionId: "target", database: "analytics", folderId: "folder-1" });
|
||||
expect(store.getFile("failed")).toMatchObject({ connectionId: "source", database: "sales", catalog: "hive", schema: "reporting", folderId: "folder-1", orderIndex: 1 });
|
||||
expect(mocks.syncTargets).toHaveBeenCalledWith([expect.objectContaining({ id: "ok" })]);
|
||||
});
|
||||
|
||||
it("reports destination name collisions without persisting or losing the source", async () => {
|
||||
const source = savedFile({ id: "source-file", folderId: "folder-1", name: "report.sql", orderIndex: 2 });
|
||||
const store = await loadStore({
|
||||
folders: [{ id: "folder-1", connectionId: "source", name: "Reports", orderIndex: 0, createdAt: timestamp, updatedAt: timestamp }],
|
||||
files: [source, savedFile({ id: "target-file", connectionId: "target", database: "analytics", catalog: undefined, schema: undefined, folderId: "folder-1", name: "report.sql", orderIndex: 0 })],
|
||||
});
|
||||
|
||||
const result = await store.updateFilesExecutionTarget([source.id], { connectionId: "target", database: "analytics" });
|
||||
|
||||
expect(result.succeeded).toEqual([]);
|
||||
expect(result.failures[0]).toMatchObject({ fileId: source.id, fileName: source.name, error: expect.objectContaining({ code: "SAVED_SQL_NAME_CONFLICT" }) });
|
||||
expect(api.saveSavedSqlFile).not.toHaveBeenCalled();
|
||||
expect(store.getFile(source.id)).toEqual(source);
|
||||
expect(mocks.syncTargets).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats empty selections and missing target connections as no-ops", async () => {
|
||||
const store = await loadStore({ folders: [], files: [savedFile({ id: "file", name: "file.sql" })] });
|
||||
|
||||
await expect(store.updateFilesExecutionTarget([], { connectionId: "target", database: "analytics" })).resolves.toEqual({ succeeded: [], updated: [], failures: [] });
|
||||
await expect(store.updateFilesExecutionTarget(["file"], { connectionId: "missing", database: "analytics" })).resolves.toEqual({ succeeded: [], updated: [], failures: [] });
|
||||
expect(api.saveSavedSqlFile).not.toHaveBeenCalled();
|
||||
expect(mocks.syncTargets).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("synchronizes the configured local directory once after a batch", async () => {
|
||||
mocks.tauri = true;
|
||||
mocks.syncDir = "/workspace/sql-sync";
|
||||
const store = await loadStore({
|
||||
folders: [],
|
||||
files: [savedFile({ id: "one", name: "one.sql", sql: "SELECT 1;", sqlLoaded: true }), savedFile({ id: "two", name: "two.sql", sql: "SELECT 2;", sqlLoaded: true, orderIndex: 1 })],
|
||||
});
|
||||
|
||||
await store.updateFilesExecutionTarget(["one", "two"], { connectionId: "target", database: "analytics" });
|
||||
|
||||
expect(api.syncSavedSqlDirectory).toHaveBeenCalledOnce();
|
||||
expect(api.syncSavedSqlDirectory).toHaveBeenCalledWith({
|
||||
targetDir: "/workspace/sql-sync",
|
||||
entries: [
|
||||
{ folderName: undefined, fileName: "one.sql", sql: "SELECT 1;" },
|
||||
{ folderName: undefined, fileName: "two.sql", sql: "SELECT 2;" },
|
||||
],
|
||||
});
|
||||
expect(api.loadSavedSqlFilesForSync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -115,7 +115,7 @@ import { createSavedSqlEditorPosition, initSavedSqlEditorPositions, restoreSaved
|
||||
import { isDetachedWindow, resolveWindowContext } from "@/lib/app/windowContext";
|
||||
import { normalizeDetachedTabRuntime, type DetachedTabHandoff, type DetachedTabRuntimeState } from "@/lib/app/detachedTabHandoff";
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import { resolveSavedSqlExecutionTarget, savedSqlExecutionTargetFromTab, type SavedSqlExecutionTarget, type SavedSqlOpenTargetMode } from "@/lib/savedSql/savedSqlExecutionTarget";
|
||||
import { resolveSavedSqlExecutionTarget, savedSqlExecutionTargetFromFile, savedSqlExecutionTargetFromTab, type SavedSqlExecutionTarget, type SavedSqlOpenTargetMode } from "@/lib/savedSql/savedSqlExecutionTarget";
|
||||
import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";
|
||||
import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";
|
||||
import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";
|
||||
@@ -5336,6 +5336,18 @@ export const useQueryStore = defineStore("query", () => {
|
||||
updateSchema(tab.id, target.schema, options);
|
||||
}
|
||||
|
||||
function syncSavedSqlExecutionTargets(files: readonly SavedSqlFile[]) {
|
||||
const targetsByFileId = new Map(files.map((file) => [file.id, savedSqlExecutionTargetFromFile(file)]));
|
||||
let synchronized = 0;
|
||||
for (const tab of tabs.value) {
|
||||
const target = tab.savedSqlId ? targetsByFileId.get(tab.savedSqlId) : undefined;
|
||||
if (!target) continue;
|
||||
applySavedSqlExecutionTarget(tab, target);
|
||||
synchronized++;
|
||||
}
|
||||
return synchronized;
|
||||
}
|
||||
|
||||
function openSavedSql(file: SavedSqlFile, options: OpenSavedSqlOptions = {}) {
|
||||
const targetMode = options.targetMode ?? useSettingsStore().editorSettings.savedSqlOpenTargetMode;
|
||||
const currentTarget = targetMode === "current" ? currentSavedSqlExecutionTarget() : undefined;
|
||||
@@ -9393,6 +9405,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
openExternalSqlFile,
|
||||
openSavedSql,
|
||||
hydrateSavedSqlTabs,
|
||||
syncSavedSqlExecutionTargets,
|
||||
togglePinnedTab,
|
||||
reorderTab,
|
||||
createExecutionTargetGuard,
|
||||
|
||||
@@ -5,7 +5,9 @@ import * as api from "@/lib/backend/api";
|
||||
import { forgetSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";
|
||||
import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName";
|
||||
import { nextSavedSqlCopyName } from "@/lib/savedSql/savedSqlClipboard";
|
||||
import { savedSqlBatchReassignment, type SavedSqlBatchTargetSelection } from "@/lib/savedSql/savedSqlBatchTarget";
|
||||
import { savedSqlDatabaseScopeKey } from "@/lib/savedSql/savedSqlDatabaseTree";
|
||||
import { normalizeSqlExecutionTarget, sqlExecutionTargetCapabilities } from "@/lib/database/sqlExecutionTargetCapabilities";
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import type { SavedSqlFile, SavedSqlFolder, SavedSqlLibrary } from "@/types/database";
|
||||
@@ -35,6 +37,32 @@ interface SavedSqlExecutionTargetInput {
|
||||
schema?: string;
|
||||
}
|
||||
|
||||
interface SavedSqlExecutionTargetUpdateOptions {
|
||||
folderId?: string;
|
||||
metadataOnly?: boolean;
|
||||
orderIndex?: number;
|
||||
updateFolder?: boolean;
|
||||
syncLocalDirectory?: boolean;
|
||||
}
|
||||
|
||||
interface PersistedSavedSqlFileTarget extends SavedSqlExecutionTargetInput {
|
||||
folderId?: string;
|
||||
orderIndex?: number;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SavedSqlBatchTargetFailure {
|
||||
fileId: string;
|
||||
fileName: string;
|
||||
error: unknown;
|
||||
}
|
||||
|
||||
export interface SavedSqlBatchTargetResult {
|
||||
succeeded: SavedSqlFile[];
|
||||
updated: SavedSqlFile[];
|
||||
failures: SavedSqlBatchTargetFailure[];
|
||||
}
|
||||
|
||||
interface SavedSqlNameScope {
|
||||
id: string;
|
||||
connectionId: string;
|
||||
@@ -154,7 +182,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
const pendingFolderCreates = new Map<string, Promise<SavedSqlFolder>>();
|
||||
const fileTargetRevisions = new Map<string, number>();
|
||||
const pendingFileTargetSaves = new Map<string, Promise<SavedSqlFile | undefined>>();
|
||||
const persistedFileTargets = new Map<string, SavedSqlExecutionTargetInput & { updatedAt: string }>();
|
||||
const persistedFileTargets = new Map<string, PersistedSavedSqlFileTarget>();
|
||||
const persistedFileTargetNameReleases = new Map<string, () => void>();
|
||||
const pendingNamesByScope = new Map<string, Map<string, PendingSavedSqlName>>();
|
||||
|
||||
@@ -383,15 +411,26 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
catalog: normalizedCatalog(file.catalog),
|
||||
database: file.database,
|
||||
schema: file.schema,
|
||||
folderId: file.folderId,
|
||||
orderIndex: file.orderIndex,
|
||||
updatedAt: file.updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
function updateFileExecutionTarget(id: string, target: SavedSqlExecutionTargetInput): Promise<SavedSqlFile | undefined> {
|
||||
function updateFileExecutionTarget(id: string, target: SavedSqlExecutionTargetInput, options: SavedSqlExecutionTargetUpdateOptions = {}): Promise<SavedSqlFile | undefined> {
|
||||
const existing = getFile(id);
|
||||
if (!existing) return Promise.resolve(undefined);
|
||||
const normalizedTarget = { ...target, catalog: normalizedCatalog(target.catalog) };
|
||||
if (existing.connectionId === normalizedTarget.connectionId && normalizedCatalog(existing.catalog) === normalizedTarget.catalog && existing.database === normalizedTarget.database && existing.schema === normalizedTarget.schema) {
|
||||
const folderId = options.updateFolder ? options.folderId || undefined : existing.folderId;
|
||||
const orderIndex = options.updateFolder ? options.orderIndex : existing.orderIndex;
|
||||
if (
|
||||
existing.connectionId === normalizedTarget.connectionId &&
|
||||
normalizedCatalog(existing.catalog) === normalizedTarget.catalog &&
|
||||
existing.database === normalizedTarget.database &&
|
||||
existing.schema === normalizedTarget.schema &&
|
||||
existing.folderId === folderId &&
|
||||
existing.orderIndex === orderIndex
|
||||
) {
|
||||
return Promise.resolve(existing);
|
||||
}
|
||||
|
||||
@@ -400,7 +439,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
}
|
||||
const revision = (fileTargetRevisions.get(id) ?? 0) + 1;
|
||||
fileTargetRevisions.set(id, revision);
|
||||
files.value = files.value.map((file) => (file.id === id ? { ...file, ...normalizedTarget, updatedAt: nowIso() } : file));
|
||||
files.value = files.value.map((file) => (file.id === id ? { ...file, ...normalizedTarget, folderId, orderIndex, updatedAt: nowIso() } : file));
|
||||
bumpVersion({ tree: true });
|
||||
|
||||
const previousSave = pendingFileTargetSaves.get(id) ?? Promise.resolve(undefined);
|
||||
@@ -411,13 +450,14 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
|
||||
let releaseName: (() => void) | undefined;
|
||||
try {
|
||||
const loaded = await ensureFileContent(id);
|
||||
if (!loaded || fileTargetRevisions.get(id) !== revision) return getFile(id);
|
||||
const currentFile = options.metadataOnly ? getFile(id) : await ensureFileContent(id);
|
||||
if (!currentFile || fileTargetRevisions.get(id) !== revision) return currentFile;
|
||||
|
||||
const candidate: SavedSqlFile = {
|
||||
...loaded,
|
||||
...currentFile,
|
||||
...normalizedTarget,
|
||||
sqlLoaded: true,
|
||||
folderId,
|
||||
orderIndex,
|
||||
updatedAt: nowIso(),
|
||||
};
|
||||
files.value = files.value.map((file) => (file.id === id ? candidate : file));
|
||||
@@ -430,17 +470,18 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
connectionId: persistedTarget.connectionId,
|
||||
catalog: persistedTarget.catalog,
|
||||
database: persistedTarget.database,
|
||||
folderId: persistedTarget.folderId,
|
||||
})
|
||||
: savedSqlNameIdentity(candidate);
|
||||
if (persistedNameIdentity !== savedSqlNameIdentity(candidate)) releaseName = reserveFileName(candidate);
|
||||
const saved = normalizeSavedSqlFile(await api.saveSavedSqlFile(candidate));
|
||||
setPersistedFileTarget(saved);
|
||||
if (fileTargetRevisions.get(id) !== revision) return getFile(id);
|
||||
const current = getFile(id);
|
||||
const persisted = { ...saved, sql: current?.sql ?? saved.sql, sqlLoaded: current?.sqlLoaded ?? true };
|
||||
const latest = getFile(id);
|
||||
const persisted = { ...saved, sql: latest?.sql ?? saved.sql, sqlLoaded: latest?.sqlLoaded ?? true };
|
||||
files.value = files.value.map((file) => (file.id === id ? persisted : file));
|
||||
bumpVersion();
|
||||
await syncToLocalDirectory();
|
||||
if (options.syncLocalDirectory !== false) await syncToLocalDirectory();
|
||||
return persisted;
|
||||
} catch (error) {
|
||||
if (fileTargetRevisions.get(id) === revision) {
|
||||
@@ -466,6 +507,68 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
return save;
|
||||
}
|
||||
|
||||
async function updateFilesExecutionTarget(fileIds: readonly string[], target: SavedSqlBatchTargetSelection): Promise<SavedSqlBatchTargetResult> {
|
||||
const uniqueFileIds = [...new Set(fileIds)];
|
||||
if (uniqueFileIds.length === 0 || !target.connectionId) return { succeeded: [], updated: [], failures: [] };
|
||||
|
||||
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||
const targetConnection = useConnectionStore().getConfig(target.connectionId);
|
||||
const targetCapabilities = sqlExecutionTargetCapabilities(targetConnection);
|
||||
if (!targetConnection || !targetCapabilities || (targetCapabilities.databaseRequired && !target.database)) return { succeeded: [], updated: [], failures: [] };
|
||||
const normalizedTarget = normalizeSqlExecutionTarget(targetConnection, target);
|
||||
|
||||
const selectedFiles = uniqueFileIds.map((id) => getFile(id)).filter((file): file is SavedSqlFile => Boolean(file));
|
||||
if (selectedFiles.length === 0) return { succeeded: [], updated: [], failures: [] };
|
||||
|
||||
let nextUnfiledOrder = maxOrderIndex(files.value.filter((file) => !file.folderId)) + 1;
|
||||
const succeeded: SavedSqlFile[] = [];
|
||||
const updated: SavedSqlFile[] = [];
|
||||
const failures: SavedSqlBatchTargetFailure[] = [];
|
||||
|
||||
for (const file of selectedFiles) {
|
||||
const folder = file.folderId ? folders.value.find((candidate) => candidate.id === file.folderId) : undefined;
|
||||
const reassignment = savedSqlBatchReassignment(file, folder, normalizedTarget);
|
||||
const leavesFolder = !!file.folderId && !reassignment.folderId;
|
||||
const orderIndex = leavesFolder ? nextUnfiledOrder++ : file.orderIndex;
|
||||
const targetChanged =
|
||||
file.connectionId !== reassignment.target.connectionId ||
|
||||
normalizedCatalog(file.catalog) !== normalizedCatalog(reassignment.target.catalog) ||
|
||||
file.database !== reassignment.target.database ||
|
||||
file.schema !== reassignment.target.schema ||
|
||||
file.folderId !== reassignment.folderId ||
|
||||
file.orderIndex !== orderIndex;
|
||||
|
||||
try {
|
||||
const saved = await updateFileExecutionTarget(file.id, reassignment.target, {
|
||||
folderId: reassignment.folderId,
|
||||
metadataOnly: true,
|
||||
orderIndex,
|
||||
updateFolder: true,
|
||||
syncLocalDirectory: false,
|
||||
});
|
||||
if (!saved) continue;
|
||||
succeeded.push(saved);
|
||||
if (targetChanged) updated.push(saved);
|
||||
} catch (error) {
|
||||
failures.push({ fileId: file.id, fileName: file.name, error });
|
||||
}
|
||||
}
|
||||
|
||||
if (succeeded.length > 0) {
|
||||
const { useQueryStore } = await import("@/stores/queryStore");
|
||||
useQueryStore().syncSavedSqlExecutionTargets(succeeded);
|
||||
}
|
||||
if (updated.length > 0) {
|
||||
try {
|
||||
await syncToLocalDirectory();
|
||||
} catch (error) {
|
||||
console.warn("[DBX][saved-sql:sync:error]", error);
|
||||
}
|
||||
}
|
||||
|
||||
return { succeeded, updated, failures };
|
||||
}
|
||||
|
||||
async function renameFile(id: string, name: string) {
|
||||
const existing = getFile(id);
|
||||
if (!existing) return;
|
||||
@@ -843,6 +946,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
deleteFolder,
|
||||
saveFile,
|
||||
updateFileExecutionTarget,
|
||||
updateFilesExecutionTarget,
|
||||
renameFile,
|
||||
copyFilesToDatabase,
|
||||
recordFileUsage,
|
||||
|
||||
Reference in new issue
Block a user