feat(sql-editor): reuse active connection for opened files
Closes #9263
This commit is contained in:
1 parent
0fd1d6108f
commit
5d13c5ecfc
12 files changed
+332
-40
No files matched your search
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user