feat(sql-editor): reuse active connection for opened files

Closes #9263
This commit is contained in:
t8y2 committed 2026-09-27 14:19:10 +00:00
1 parent 0fd1d6108f
commit 5d13c5ecfc
12 files changed
+332 -40

No files matched your search

+17 -5
View File
@@ -93,7 +93,7 @@ import { uuid } from "@/lib/common/utils";
import { isMacOS, isWindows } from "@/lib/backend/platform";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { openQueryResultArchiveFile } from "@/lib/query/queryResultArchiveFile";
import { rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { activeTabExternalSqlFileTarget, rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab, unassociatedExternalSqlFileTarget, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, isSqlFilePath, readBrowserSqlFile, sqlFileTitleFromPath } from "@/lib/sql/sqlFileOpen";
import type { ConnectionConfig, DatabaseType, ObjectBrowserFilter, ObjectSourceKind, QueryTab, TabOutputView, TreeNode } from "@/types/database";
import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
@@ -2435,8 +2435,7 @@ async function saveActiveSqlAsLocalFile() {
if (tab) await saveExternalSqlTabAs(tab);
}
function applyExternalSqlFileTarget(tab: QueryTab, path: string) {
const target = resolveExternalSqlFileTarget(path, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
function applyExternalSqlTarget(tab: QueryTab, target: ExternalSqlFileTarget) {
if (target.connectionId !== tab.connectionId) {
queryStore.updateConnection(tab.id, target.connectionId, target.database);
}
@@ -2449,6 +2448,13 @@ function applyExternalSqlFileTarget(tab: QueryTab, path: string) {
if (target.schema !== tab.schema) queryStore.updateSchema(tab.id, target.schema);
}
function applyExternalSqlFileTarget(tab: QueryTab, path: string) {
applyExternalSqlTarget(
tab,
resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, tab.id, (connectionId) => connectionStore.getConfig(connectionId)),
);
}
async function openSqlFile() {
const tab = activeTab.value;
if (!tab) return;
@@ -2477,6 +2483,10 @@ async function openSqlFile() {
if (!file) return;
try {
queryStore.updateSql(tab.id, await readBrowserSqlFile(file, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb)));
applyExternalSqlTarget(
tab,
activeTabExternalSqlFileTarget(queryStore.tabs, tab.id, (connectionId) => connectionStore.getConfig(connectionId)),
);
} catch (e: any) {
toast(t("toolbar.sqlOpenFailed", { message: externalSqlFileOpenErrorMessage(e, (key, params) => t(key, params)) }), 5000);
}
@@ -2520,6 +2530,8 @@ async function openSqlFilePath(path: string) {
try {
await desktopOpenTabsRestorationBarrier?.settled;
const snapshot = await api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
// Startup and OS-open events have no initiating editor tab. Keep new files
// unassociated even if persisted tab restoration has since selected one.
const target = resolveExternalSqlFileTarget(path, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
queryStore.openExternalSqlFile(target.connectionId, target.database, path, snapshot.content, snapshot.version, target.catalog, target.schema);
} catch (e: any) {
@@ -3290,7 +3302,7 @@ async function handleQuickOpenSelect(item: any) {
if (item.type === "content_match" && item.filePath) {
try {
const snapshot = await api.readExternalSqlFileSnapshot(item.filePath, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
const target = resolveExternalSqlFileTarget(item.filePath, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
const target = resolveExternalSqlFileTargetForActiveTab(item.filePath, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
queryStore.openExternalSqlFile(target.connectionId, target.database, item.filePath, snapshot.content, snapshot.version, target.catalog, target.schema, { line: item.line ?? 1, column: item.column });
} catch (e: any) {
toast(
@@ -3304,7 +3316,7 @@ async function handleQuickOpenSelect(item: any) {
if (item.type === "sql_file" && item.filePath) {
try {
const snapshot = await api.readExternalSqlFileSnapshot(item.filePath, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
const target = resolveExternalSqlFileTarget(item.filePath, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
const target = resolveExternalSqlFileTargetForActiveTab(item.filePath, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
queryStore.openExternalSqlFile(target.connectionId, target.database, item.filePath, snapshot.content, snapshot.version, target.catalog, target.schema);
} catch (e: any) {
toast(
@@ -15,7 +15,7 @@ import { useToast } from "@/composables/useToast";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { translateBackendError } from "@/i18n/backend-errors";
import { copyToClipboard } from "@/lib/common/clipboard";
import { forgetExternalSqlFileTarget, moveExternalSqlFileTarget, resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { forgetExternalSqlFileTarget, moveExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath } from "@/lib/sql/sqlFileOpen";
import * as api from "@/lib/backend/api";
import type { SqlFileEntry } from "@/lib/backend/api";
@@ -256,7 +256,7 @@ async function openFile(path: string) {
if (!isTauriRuntime()) return;
try {
const snapshot = await api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
const target = resolveExternalSqlFileTarget(path, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
queryStore.openExternalSqlFile(target.connectionId, target.database, path, snapshot.content, snapshot.version, target.catalog, target.schema);
} catch (e: any) {
if (isExternalSqlFileTooLargeError(e) && isSqlFilePath(path)) {
@@ -271,7 +271,7 @@ async function openFile(path: string) {
// Open the App-level SQL file execution dialog with this file pre-selected so
// the user can review its statements and pick a connection/database before run.
function executeFile(path: string) {
const target = resolveExternalSqlFileTarget(path, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
connectionStore.sqlFileSource = {
connectionId: target.connectionId,
database: target.database,
@@ -23,6 +23,8 @@ const mocks = vi.hoisted(() => ({
inspectSqlFileTables: vi.fn(),
progressHandler: undefined as undefined | ((progress: Record<string, unknown>) => void),
changeDialogOpen: undefined as undefined | ((open: boolean) => void),
connections: [{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" }] as Array<{ id: string; name: string; db_type: string; driver_profile: string; database: string }>,
getConfig: vi.fn(),
refreshDatabaseTreeNode: vi.fn(),
requestConfirmation: vi.fn(),
toast: vi.fn(),
@@ -30,6 +32,10 @@ const mocks = vi.hoisted(() => ({
unlisten: vi.fn(),
updateSqlFileTask: vi.fn(),
uuid: vi.fn(),
queryStore: {
tabs: [{ id: "mysql-tab", connectionId: "mysql-1", database: "" }],
activeTabId: "mysql-tab" as string | null,
},
}));
function passthrough(tag: string) {
@@ -65,12 +71,15 @@ vi.mock("@/stores/productionSafetyStore", () => ({
}));
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
connections: [{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql" }],
get connections() {
return mocks.connections;
},
ensureConnected: mocks.ensureConnected,
getConfig: () => ({ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" }),
getConfig: mocks.getConfig,
refreshDatabaseTreeNode: mocks.refreshDatabaseTreeNode,
}),
}));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => mocks.queryStore }));
vi.mock("@/lib/backend/api", () => ({
beginManualTransaction: mocks.beginManualTransaction,
commitManualTransaction: mocks.commitManualTransaction,
@@ -126,6 +135,7 @@ vi.mock("@/components/icons/DatabaseIcon.vue", () => ({ default: passthrough("sp
vi.mock("@/components/connection/ConnectionGroupBadge.vue", () => ({ default: passthrough("span") }));
import SqlFileExecutionDialog from "./SqlFileExecutionDialog.vue";
import { rememberExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
let app: ReturnType<typeof createApp> | undefined;
let root: HTMLDivElement | undefined;
@@ -187,6 +197,7 @@ function deferred() {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
mocks.desktop = true;
mocks.releaseSqlFilePreview.mockResolvedValue(undefined);
mocks.progressHandler = undefined;
@@ -230,6 +241,8 @@ beforeEach(() => {
{ database: "archive", name: "users" },
]);
mocks.fetchSqlFileTargetOptions.mockResolvedValue([]);
mocks.connections = [{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" }];
mocks.getConfig.mockImplementation((connectionId: string) => mocks.connections.find((connection) => connection.id === connectionId));
mocks.openFileDialog.mockResolvedValue(["/tmp/first.sql", "/tmp/second.sql"]);
mocks.previewSqlFile.mockImplementation(async (filePath: string) => ({
fileName: filePath.split("/").pop()!,
@@ -246,6 +259,8 @@ beforeEach(() => {
mocks.refreshDatabaseTreeNode.mockResolvedValue(undefined);
mocks.requestConfirmation.mockResolvedValue(true);
mocks.uuid.mockReset().mockReturnValueOnce("run-1").mockReturnValueOnce("run-2");
mocks.queryStore.tabs = [{ id: "mysql-tab", connectionId: "mysql-1", database: "" }];
mocks.queryStore.activeTabId = "mysql-tab";
});
afterEach(() => {
@@ -604,6 +619,61 @@ describe("SqlFileExecutionDialog retries", () => {
expect(findButton("sqlFile.execute").disabled).toBe(true);
});
it("uses the active SQL tab instead of the first connection when opened from the toolbar", async () => {
mocks.connections = [
{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "first" },
{ id: "postgres-1", name: "PostgreSQL", db_type: "postgres", driver_profile: "postgres", database: "analytics" },
];
mocks.queryStore.tabs = [{ id: "postgres-tab", connectionId: "postgres-1", database: "reporting" }];
mocks.queryStore.activeTabId = "postgres-tab";
root = document.createElement("div");
document.body.append(root);
app = createApp(SqlFileExecutionDialog, { open: true });
app.mount(root);
await vi.waitFor(() => expect(mocks.ensureConnected).toHaveBeenCalledWith("postgres-1"));
expect(mocks.ensureConnected).not.toHaveBeenCalledWith("mysql-1");
});
it("does not select a connection when the active tab is non-SQL", async () => {
mocks.connections = [
{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "first" },
{ id: "kafka-1", name: "Kafka", db_type: "mq", driver_profile: "kafka", database: "invalid" },
];
mocks.queryStore.tabs = [{ id: "kafka-tab", connectionId: "kafka-1", database: "invalid" }];
mocks.queryStore.activeTabId = "kafka-tab";
root = document.createElement("div");
document.body.append(root);
app = createApp(SqlFileExecutionDialog, { open: true });
app.mount(root);
await nextTick();
expect(mocks.ensureConnected).not.toHaveBeenCalled();
expect(mocks.fetchSqlFileTargetOptions).not.toHaveBeenCalled();
});
it("lets a remembered file target override the active toolbar target", async () => {
mocks.connections = [
{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "app" },
{ id: "saved-1", name: "Saved", db_type: "postgres", driver_profile: "postgres", database: "saved_db" },
];
rememberExternalSqlFileTarget("/tmp/saved.sql", { connectionId: "saved-1", database: "saved_db" });
mocks.openFileDialog.mockResolvedValueOnce("/tmp/saved.sql");
root = document.createElement("div");
document.body.append(root);
app = createApp(SqlFileExecutionDialog, { open: true });
app.mount(root);
await vi.waitFor(() => expect(mocks.ensureConnected).toHaveBeenCalledWith("mysql-1"));
mocks.ensureConnected.mockClear();
findButton("sqlFile.browse").click();
await vi.waitFor(() => expect(mocks.ensureConnected).toHaveBeenCalledWith("saved-1"));
});
it("does not restore a completed run's file summary after an early retry failure", async () => {
await mountReadyDialog();
await completeFirstExecution();
@@ -14,14 +14,17 @@ import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import ConnectionGroupBadge from "@/components/connection/ConnectionGroupBadge.vue";
import { useToast } from "@/composables/useToast";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import { productionContextForDatabase } from "@/lib/database/productionSafety";
import { connectionIsEffectivelyReadOnly, ensureReadOnlyWriteAccess } from "@/lib/database/readOnlyWriteAccess";
import { supportsTransaction } from "@/lib/database/databaseFeatureSupport";
import { supportsSqlFileExecution, supportsTransaction } from "@/lib/database/databaseFeatureSupport";
import { formatError, isManualTransactionSessionExpired } from "@/lib/backend/errorUtils";
import { fetchSqlFileTargetOptions } from "@/composables/useDatabaseOptions";
import { requiresSqlFileTargetDatabaseSelection, supportsConnectionLevelDatabaseBootstrap } from "@/lib/connection/connectionLevelDatabaseBootstrap";
import { beginManualTransaction, commitManualTransaction, rollbackManualTransaction, cancelSqlFileExecution, executeSqlFiles, inspectSqlFileTables, listenSqlFileProgress, previewSqlFile, type SqlFilePreview, type SqlFileProgress, type SqlFileStatus, type SqlFileTable } from "@/lib/backend/api";
import { activeTabExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { isSqlFilePath } from "@/lib/sql/sqlFileOpen";
import { buildDisplayFileNames, tooltipText as computeTooltipText } from "./sqlFilePreviewLabel";
import { parseSqlFilePathInput } from "./sqlFilePathInput";
import SqlFileProgressIndicator from "./SqlFileProgressIndicator.vue";
@@ -43,6 +46,7 @@ const props = defineProps<{
}>();
const store = useConnectionStore();
const queryStore = useQueryStore();
const productionSafetyStore = useProductionSafetyStore();
// Tauri = real filesystem paths; Web = browser File.name (no path) + server temp paths.
const isDesktopRuntime = isTauriRuntime();
@@ -92,7 +96,7 @@ async function commitPathInput() {
return;
}
const typed = pathInput.value;
await loadPreviews(paths);
await loadPreviews(paths, true);
// Failed load: keep what was typed so the path can be corrected.
pathInput.value = previews.value.length > 0 ? filePathDisplay.value : typed;
}
@@ -116,6 +120,7 @@ const connectionId = ref("");
const database = ref("");
const databaseOptions = ref<string[]>([]);
const loadingDatabases = ref(false);
const preferredTarget = ref<ExternalSqlFileTarget>();
const continueOnError = ref(false);
const skipRelationalConstraints = ref(false);
const manualTransaction = ref(false);
@@ -169,7 +174,7 @@ function resetPerFileState() {
currentFileName.value = "";
}
const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(c.db_type)));
const sqlConnections = computed(() => store.connections.filter((connection) => supportsSqlFileExecution(connection.db_type)));
// Mirrors the core executor gate (`relational_constraint_bypass_kind` in
// sql_file_import.rs): MySQL-family types use the session-scoped
// FOREIGN_KEY_CHECKS toggle, PostgreSQL-family types use DISABLE/ENABLE
@@ -376,22 +381,29 @@ function statusLabel(status: SqlFileStatus | "idle") {
return t(`sqlFile.status.${status}`);
}
function resolveInitialConnectionId() {
function resolveInitialTarget(): ExternalSqlFileTarget {
if (props.prefillConnectionId && sqlConnections.value.some((c) => c.id === props.prefillConnectionId)) {
return props.prefillConnectionId;
return { connectionId: props.prefillConnectionId, database: props.prefillDatabase ?? "" };
}
if (props.prefillFilePath) return "";
return sqlConnections.value[0]?.id ?? "";
if (props.prefillFilePath) return { connectionId: "", database: "" };
return activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId));
}
function applyTarget(target: ExternalSqlFileTarget) {
preferredTarget.value = target;
connectionId.value = target.connectionId;
database.value = target.database;
}
function chooseDatabase(names: string[], id: string) {
const configDatabase = store.getConfig(id)?.database ?? "";
const preferredDatabase = preferredTarget.value?.connectionId === id ? preferredTarget.value.database : props.prefillDatabase;
if (names.length > 0) {
if (props.prefillDatabase && names.includes(props.prefillDatabase)) return props.prefillDatabase;
if (preferredDatabase && names.includes(preferredDatabase)) return preferredDatabase;
if (configDatabase && names.includes(configDatabase)) return configDatabase;
return names.length === 1 ? names[0] : "";
}
return props.prefillDatabase ?? configDatabase;
return preferredDatabase ?? configDatabase;
}
function resetExecution() {
@@ -410,11 +422,11 @@ function resetExecution() {
}
function resetState() {
const initialTarget = resolveInitialTarget();
previews.value = [];
selectingFile.value = false;
loadingPreview.value = false;
connectionId.value = resolveInitialConnectionId();
database.value = "";
applyTarget(initialTarget);
databaseOptions.value = [];
loadingDatabases.value = false;
continueOnError.value = false;
@@ -469,7 +481,7 @@ async function previewSelectedSqlFile(fileOrPath: string | File) {
return previewWebSqlFile(file);
}
async function loadPreviews(filesOrPaths: Array<string | File>) {
async function loadPreviews(filesOrPaths: Array<string | File>, resolveSelectedFileTarget = false) {
if (executionLocked.value) return;
await releaseManagedPreviews();
loadingPreview.value = true;
@@ -481,6 +493,11 @@ async function loadPreviews(filesOrPaths: Array<string | File>) {
nextPreviews.push(await previewSelectedSqlFile(fileOrPath));
}
previews.value = nextPreviews;
if (resolveSelectedFileTarget) {
const firstPath = typeof filesOrPaths[0] === "string" && isSqlFilePath(filesOrPaths[0]) ? filesOrPaths[0] : undefined;
const target = firstPath ? resolveExternalSqlFileTargetForActiveTab(firstPath, queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId)) : activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId));
applyTarget(target);
}
} catch (e: any) {
toast(e?.message || String(e), 5000);
} finally {
@@ -515,7 +532,7 @@ async function selectFile() {
});
const paths = Array.isArray(selected) ? selected : selected ? [selected] : [];
if (paths.length > 0) {
await loadPreviews(paths);
await loadPreviews(paths, true);
}
} catch (e: any) {
toast(e?.message || String(e), 5000);
@@ -531,7 +548,7 @@ async function handleFileInputChange(event: Event) {
if (files.length === 0 || executionLocked.value) return;
selectingFile.value = true;
try {
await loadPreviews(files);
await loadPreviews(files, true);
} finally {
selectingFile.value = false;
}
@@ -772,7 +789,7 @@ watch(connectionId, (id) => {
watch(sqlConnections, () => {
if (!open.value || executionLocked.value || selectedConnection.value) return;
connectionId.value = resolveInitialConnectionId();
applyTarget(resolveInitialTarget());
});
watch(
@@ -46,6 +46,8 @@ it("hands prepared Web previews to the dialog, clears them on close, and preserv
expect(mocks.store.sqlFileSource).toBeNull();
dialogs.showSqlFileDialog.value = false;
await nextTick();
expect(dialogs.sqlFilePrefillConnectionId.value).toBe("");
expect(dialogs.sqlFilePrefillDatabase.value).toBe("");
expect(dialogs.sqlFilePrefillPreview.value).toBeUndefined();
mocks.store.sqlFileSource = { connectionId: "mysql", database: "app", filePath: "/local/backup.sql" };
await nextTick();
@@ -0,0 +1,90 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
connectionStore: {
activeConnectionId: null as string | null,
connections: [] as Array<{ id: string; db_type: string }>,
getConfig: vi.fn(),
},
queryStore: {
tabs: [] as Array<{ id: string; connectionId: string; database: string; catalog?: string; schema?: string }>,
activeTabId: null as string | null,
createTab: vi.fn(() => "opened-tab"),
updateSql: vi.fn(),
openExternalSqlFile: vi.fn(),
},
readBrowserSqlFile: vi.fn(async () => "select 1"),
toast: vi.fn(),
}));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => mocks.connectionStore }));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => mocks.queryStore }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { externalSqlEditorMaxMb: 64 } }) }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
vi.mock("@/composables/useLargeSqlFileFallback", () => ({ useLargeSqlFileStreamingFallback: () => ({ openInStreamingExecutorOnTooLarge: vi.fn(() => false) }) }));
vi.mock("@/lib/sql/sqlFileOpen", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/sql/sqlFileOpen")>()),
readBrowserSqlFile: mocks.readBrowserSqlFile,
}));
import { useFileDrop } from "@/composables/useFileDrop";
let app: ReturnType<typeof createApp> | undefined;
beforeEach(() => {
vi.clearAllMocks();
mocks.connectionStore.activeConnectionId = null;
mocks.connectionStore.connections = [];
mocks.connectionStore.getConfig.mockReset();
mocks.queryStore.tabs = [];
mocks.queryStore.activeTabId = null;
mocks.queryStore.createTab.mockReturnValue("opened-tab");
});
afterEach(() => {
app?.unmount();
app = undefined;
});
describe("useFileDrop SQL target", () => {
it("uses only an active SQL tab for browser-dropped files", async () => {
let setupFileDrop!: ReturnType<typeof useFileDrop>["setupFileDrop"];
app = createApp(
defineComponent({
setup() {
({ setupFileDrop } = useFileDrop());
return () => h("div");
},
}),
);
app.mount(document.createElement("div"));
await setupFileDrop();
mocks.queryStore.tabs = [{ id: "sql-tab", connectionId: "postgres-1", database: "analytics", catalog: "hive", schema: "reporting" }];
mocks.queryStore.activeTabId = "sql-tab";
mocks.connectionStore.getConfig.mockImplementation((connectionId: string) => (connectionId === "postgres-1" ? { id: connectionId, db_type: "postgres" } : undefined));
dispatchSqlDrop("active.sql");
await vi.waitFor(() => expect(mocks.queryStore.createTab).toHaveBeenCalledTimes(1));
expect(mocks.queryStore.createTab).toHaveBeenNthCalledWith(1, "postgres-1", "analytics", "active.sql", "query", "reporting", undefined, "hive");
mocks.queryStore.tabs = [{ id: "mq-tab", connectionId: "kafka-1", database: "invalid", schema: "invalid" }];
mocks.queryStore.activeTabId = "mq-tab";
mocks.connectionStore.getConfig.mockImplementation((connectionId: string) => (connectionId === "kafka-1" ? { id: connectionId, db_type: "mq" } : undefined));
dispatchSqlDrop("non-sql.sql");
await vi.waitFor(() => expect(mocks.queryStore.createTab).toHaveBeenCalledTimes(2));
expect(mocks.queryStore.createTab).toHaveBeenNthCalledWith(2, "", "", "non-sql.sql", "query", undefined, undefined, undefined);
});
});
function dispatchSqlDrop(name: string) {
const event = new Event("drop", { bubbles: true, cancelable: true });
Object.defineProperty(event, "dataTransfer", { value: { files: [new File(["select 1"], name)] } });
document.dispatchEvent(event);
}
@@ -8,13 +8,18 @@ import { ExternalSqlFileTooLargeError } from "@/lib/sql/sqlFileOpen";
const mocks = vi.hoisted(() => ({
toast: vi.fn(),
store: {
connections: [] as { id: string }[],
connections: [] as { id: string; db_type: string }[],
sqlFileSource: null as { connectionId: string; database: string; filePath?: string } | null,
getConfig: vi.fn(),
},
queryStore: {
tabs: [] as Array<{ id: string; connectionId: string; database: string; catalog?: string; schema?: string }>,
activeTabId: null as string | null,
},
}));
vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => mocks.store }));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => mocks.queryStore }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
import { useLargeSqlFileStreamingFallback } from "@/composables/useLargeSqlFileFallback";
@@ -25,6 +30,8 @@ beforeEach(() => {
mocks.store.connections = [];
mocks.store.sqlFileSource = null;
mocks.store.getConfig.mockReset().mockReturnValue(undefined);
mocks.queryStore.tabs = [];
mocks.queryStore.activeTabId = null;
mocks.toast.mockReset();
});
@@ -67,6 +74,21 @@ describe("useLargeSqlFileStreamingFallback", () => {
expect(String(mocks.toast.mock.calls[0][0])).toContain("100.0 MB");
});
it("passes the active SQL tab target to the streaming executor", () => {
mocks.queryStore.tabs = [{ id: "tab-1", connectionId: "postgres-1", database: "app", schema: "reporting" }];
mocks.queryStore.activeTabId = "tab-1";
mocks.store.getConfig.mockImplementation((connectionId: string) => (connectionId === "postgres-1" ? { id: connectionId, db_type: "postgres" } : undefined));
const outcome = withComposable((fallback) => fallback.openInStreamingExecutorOnTooLarge("/tmp/dbx_export.sql", new ExternalSqlFileTooLargeError(100 * 1024 * 1024, 64 * 1024 * 1024)));
expect(outcome).toBe(true);
expect(mocks.store.sqlFileSource).toEqual({
connectionId: "postgres-1",
database: "app",
filePath: "/tmp/dbx_export.sql",
});
});
it("keeps unrelated open failures as errors", () => {
const outcome = withComposable((fallback) => fallback.openInStreamingExecutorOnTooLarge("/tmp/dbx_export.sql", new Error("disk failure")));
@@ -209,13 +209,13 @@ export function useDialogSources() {
},
);
// Clear the pre-filled file path once the dialog closes so a later open
// via the toolbar (which doesn't go through sqlFileSource) doesn't re-load
// the previously previewed file. prefillConnectionId/database are harmless
// when stale (they only preselect dropdowns), but a stale path triggers an
// async file read + preview render — a visible side effect.
// Clear the complete prefill once the dialog closes. A later toolbar open
// derives its target from the then-active SQL tab, so neither the old path
// nor its connection context may leak into that session.
watch(showSqlFileDialog, (open) => {
if (!open) {
sqlFilePrefillConnectionId.value = "";
sqlFilePrefillDatabase.value = "";
sqlFilePrefillFilePath.value = "";
sqlFilePrefillPreview.value = undefined;
}
+4 -6
View File
@@ -10,7 +10,7 @@ import * as api from "@/lib/backend/api";
import type { ConnectionConfig, ExternalSqlFileVersion } from "@/types/database";
import { detectDatabaseFileType } from "@/lib/database/databaseFileDetection";
import { externalSqlEditorMaxBytes, externalSqlFileOpenErrorMessage, readBrowserSqlFile } from "@/lib/sql/sqlFileOpen";
import { resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { activeTabExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
function isSqlFilePath(path: string): boolean {
return /\.sql$/i.test(path);
@@ -30,13 +30,11 @@ export function useFileDrop() {
async function openDroppedSqlFile(name: string, content: string, path?: string, version?: ExternalSqlFileVersion) {
if (path) {
const target = resolveExternalSqlFileTarget(path, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
queryStore.openExternalSqlFile(target.connectionId, target.database, path, content, version, target.catalog, target.schema);
} else {
const connectionId = connectionStore.activeConnectionId || connectionStore.connections[0]?.id || "";
const connection = connectionId ? connectionStore.getConfig(connectionId) : undefined;
const database = connection?.database || "";
const tabId = queryStore.createTab(connectionId, database, name, "query");
const target = activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
const tabId = queryStore.createTab(target.connectionId, target.database, name, "query", target.schema, undefined, target.catalog);
queryStore.updateSql(tabId, content);
}
toast(t("welcome.fileOpened", { name }));
@@ -1,7 +1,8 @@
import { useI18n } from "vue-i18n";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useToast } from "@/composables/useToast";
import { resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
import { formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath } from "@/lib/sql/sqlFileOpen";
/**
@@ -12,10 +13,11 @@ import { formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath } from
export function useLargeSqlFileStreamingFallback() {
const { t } = useI18n();
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
const { toast } = useToast();
function openInStreamingExecutor(path: string, sizeBytes: number) {
const target = resolveExternalSqlFileTarget(path, (savedConnectionId) => !!connectionStore.getConfig(savedConnectionId), unassociatedExternalSqlFileTarget());
const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
connectionStore.sqlFileSource = {
connectionId: target.connectionId,
database: target.database,
@@ -1,7 +1,17 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it } from "vitest";
import { EXTERNAL_SQL_FILE_TARGETS_STORAGE_KEY, MAX_EXTERNAL_SQL_FILE_TARGETS, forgetExternalSqlFileTarget, moveExternalSqlFileTarget, rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import {
activeTabExternalSqlFileTarget,
EXTERNAL_SQL_FILE_TARGETS_STORAGE_KEY,
MAX_EXTERNAL_SQL_FILE_TARGETS,
forgetExternalSqlFileTarget,
moveExternalSqlFileTarget,
rememberExternalSqlFileTarget,
resolveExternalSqlFileTarget,
resolveExternalSqlFileTargetForActiveTab,
unassociatedExternalSqlFileTarget,
} from "@/lib/sql/externalSqlFileTarget";
describe("external SQL file targets", () => {
beforeEach(() => {
@@ -18,6 +28,53 @@ describe("external SQL file targets", () => {
});
});
it("prefers a remembered target over the active SQL tab", () => {
rememberExternalSqlFileTarget("/work/report.sql", { connectionId: "saved-connection", database: "saved_db", catalog: "saved_catalog", schema: "saved_schema" });
const tabs = [{ id: "active-tab", connectionId: "active-connection", database: "active_db", catalog: "active_catalog", schema: "active_schema", mode: "query" as const }];
expect(
resolveExternalSqlFileTargetForActiveTab("/work/report.sql", tabs, "active-tab", (connectionId) => {
if (connectionId === "saved-connection" || connectionId === "active-connection") return { db_type: "postgres" };
return undefined;
}),
).toEqual({
connectionId: "saved-connection",
database: "saved_db",
catalog: "saved_catalog",
schema: "saved_schema",
});
});
it("uses the active SQL tab context for a previously unassociated file", () => {
const tabs = [{ id: "active-tab", connectionId: "active-connection", database: "analytics", catalog: "hive", schema: "reporting", mode: "query" as const }];
expect(resolveExternalSqlFileTargetForActiveTab("/work/new.sql", tabs, "active-tab", () => ({ db_type: "postgres" }))).toEqual({
connectionId: "active-connection",
database: "analytics",
catalog: "hive",
schema: "reporting",
});
});
it("keeps the fallback unassociated without an active tab", () => {
const tabs = [{ id: "inactive-tab", connectionId: "sql-connection", database: "analytics", mode: "query" as const }];
expect(activeTabExternalSqlFileTarget(tabs, null, () => ({ db_type: "postgres" }))).toEqual(unassociatedExternalSqlFileTarget());
expect(activeTabExternalSqlFileTarget(tabs, "missing-tab", () => ({ db_type: "postgres" }))).toEqual(unassociatedExternalSqlFileTarget());
});
it.each(["mq", "zookeeper", "plugin", "redis"] as const)("does not reuse a non-SQL %s tab target", (dbType) => {
const tabs = [{ id: "active-tab", connectionId: "non-sql-connection", database: "invalid", catalog: "invalid", schema: "invalid", mode: "query" as const }];
expect(activeTabExternalSqlFileTarget(tabs, "active-tab", () => ({ db_type: dbType }))).toEqual(unassociatedExternalSqlFileTarget());
});
it.each(["plugin-workbench", "plugin-filesystem"] as const)("does not reuse a SQL connection borrowed by a %s tab", (mode) => {
const tabs = [{ id: "plugin-tab", connectionId: "sql-connection", database: "invalid", mode }];
expect(activeTabExternalSqlFileTarget(tabs, "plugin-tab", () => ({ db_type: "postgres" }))).toEqual(unassociatedExternalSqlFileTarget());
});
it("keeps same-named databases in different catalogs distinct", () => {
rememberExternalSqlFileTarget("/work/hive.sql", { connectionId: "saved-connection", database: "sales", catalog: "hive" });
rememberExternalSqlFileTarget("/work/iceberg.sql", { connectionId: "saved-connection", database: "sales", catalog: "iceberg" });
@@ -1,4 +1,6 @@
import { normalizeExternalSqlPath } from "@/lib/sql/sqlFileOpen";
import { supportsSqlFileExecution } from "@/lib/database/databaseFeatureSupport";
import type { ConnectionConfig, QueryTab } from "@/types/database";
export const EXTERNAL_SQL_FILE_TARGETS_STORAGE_KEY = "dbx-external-sql-file-targets-v1";
export const MAX_EXTERNAL_SQL_FILE_TARGETS = 200;
@@ -10,10 +12,26 @@ export interface ExternalSqlFileTarget {
schema?: string;
}
type ExternalSqlFileTargetTab = Pick<QueryTab, "id" | "connectionId" | "database" | "catalog" | "schema" | "mode">;
type ExternalSqlFileTargetConnection = Pick<ConnectionConfig, "db_type">;
type ExternalSqlFileConnectionLookup = (connectionId: string) => ExternalSqlFileTargetConnection | undefined;
export function unassociatedExternalSqlFileTarget(): ExternalSqlFileTarget {
return { connectionId: "", database: "", catalog: undefined, schema: undefined };
}
export function activeTabExternalSqlFileTarget(tabs: readonly ExternalSqlFileTargetTab[], activeTabId: string | null | undefined, getConnection: ExternalSqlFileConnectionLookup): ExternalSqlFileTarget {
const activeTab = activeTabId ? tabs.find((tab) => tab.id === activeTabId) : undefined;
const connection = activeTab?.connectionId ? getConnection(activeTab.connectionId) : undefined;
if (!activeTab || activeTab.mode === "plugin-workbench" || activeTab.mode === "plugin-filesystem" || !connection || !supportsSqlFileExecution(connection.db_type)) return unassociatedExternalSqlFileTarget();
return {
connectionId: activeTab.connectionId,
database: activeTab.database,
catalog: activeTab.catalog,
schema: activeTab.schema,
};
}
interface StoredExternalSqlFileTarget extends ExternalSqlFileTarget {
path: string;
updatedAt: number;
@@ -84,3 +102,7 @@ export function resolveExternalSqlFileTarget(path: string, connectionExists: (co
if (!saved || !connectionExists(saved.connectionId)) return fallback;
return { connectionId: saved.connectionId, database: saved.database, catalog: saved.catalog, schema: saved.schema };
}
export function resolveExternalSqlFileTargetForActiveTab(path: string, tabs: readonly ExternalSqlFileTargetTab[], activeTabId: string | null | undefined, getConnection: ExternalSqlFileConnectionLookup): ExternalSqlFileTarget {
return resolveExternalSqlFileTarget(path, (connectionId) => !!getConnection(connectionId), activeTabExternalSqlFileTarget(tabs, activeTabId, getConnection));
}