feat(mongo): open and save js files in mongo tabs

This commit is contained in:
lxk955 authored and GitHub committed 2026-10-01 22:53:16 +08:00
1 parent 906f5c271c
commit 51b8342f5d
7 files changed
+152 -36

No files matched your search

+16 -10
View File
@@ -94,7 +94,7 @@ import { isMacOS, isWindows } from "@/lib/backend/platform";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { openQueryResultArchiveFile } from "@/lib/query/queryResultArchiveFile";
import { activeTabExternalSqlFileTarget, rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab, unassociatedExternalSqlFileTarget, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, isSqlFilePath, readBrowserSqlFile, sqlFileTitleFromPath } from "@/lib/sql/sqlFileOpen";
import { defaultSavedQueryFileName, externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, isSqlFilePath, queryEditorOpenFileAccept, queryEditorOpenFileFilters, readBrowserSqlFile, sqlFileTitleFromPath } from "@/lib/sql/sqlFileOpen";
import type { ConnectionConfig, DatabaseType, ObjectBrowserFilter, ObjectSourceKind, QueryTab, TabOutputView, TreeNode } from "@/types/database";
import { OPEN_PLUGIN_SETTINGS, type PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
import { parsePluginInstallDeepLink } from "@/lib/plugins/pluginInstallDeepLink";
@@ -2174,11 +2174,11 @@ function savedSqlTargetForSave(tab: QueryTab) {
*/
async function formattedSqlForSave(tab: QueryTab): Promise<string> {
if (!settingsStore.editorSettings.formatSqlOnSqlFileSave) return tab.sql;
if (tab.externalSqlPath && !isSqlFilePath(tab.externalSqlPath)) return tab.sql;
const sqlSnapshot = tab.sql;
if (!sqlSnapshot.trim()) return sqlSnapshot;
const connection = connectionStore.getConfig(tab.connectionId);
const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection?.db_type;
if (tab.externalSqlPath && !isSqlFilePath(tab.externalSqlPath) && !(databaseType === "mongodb" && /\.js$/i.test(tab.externalSqlPath))) return tab.sql;
const sqlSnapshot = tab.sql;
if (!sqlSnapshot.trim()) return sqlSnapshot;
if (!canFormatSqlForDatabaseType(databaseType)) return sqlSnapshot;
try {
return await formatSqlSnapshotForSave(
@@ -2460,8 +2460,12 @@ async function saveExternalSqlTabAs(tab: QueryTab): Promise<boolean> {
// Non-SQL external tabs (custom-filtered text files) keep their own file
// name and extension when saving a copy instead of being forced to .sql.
const currentFileName = tab.externalSqlPath?.split(/[\\/]/).pop()?.trim() ?? "";
const filterExtension = currentFileName.includes(".") ? currentFileName.split(".").pop()?.toLowerCase() : undefined;
const saved = await api.saveExternalSqlFile(currentFileName || defaultSavedSqlName(tab.title), await formattedSqlForSave(tab), filterExtension);
const connection = connectionStore.getConfig(tab.connectionId);
const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection?.db_type;
const isMongo = databaseType === "mongodb";
const filterExtension = currentFileName.includes(".") ? currentFileName.split(".").pop()?.toLowerCase() : isMongo ? "js" : undefined;
const defaultName = currentFileName || defaultSavedQueryFileName(tab.title, databaseType);
const saved = await api.saveExternalSqlFile(defaultName, await formattedSqlForSave(tab), filterExtension);
if (!saved) return false;
queryStore.linkExternalSqlPath(tab.id, saved.path, sqlFileTitleFromPath(saved.path), saved.version);
rememberExternalSqlFileTarget(saved.path, { connectionId: tab.connectionId, database: tab.database, catalog: tab.catalog, schema: tab.schema });
@@ -2497,19 +2501,21 @@ function applyExternalSqlTarget(tab: QueryTab, target: ExternalSqlFileTarget) {
function applyExternalSqlFileTarget(tab: QueryTab, path: string) {
applyExternalSqlTarget(
tab,
resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, tab.id, (connectionId) => connectionStore.getConfig(connectionId)),
resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, tab.id, (connectionId) => connectionStore.getConfig(connectionId), { allowMongoScripts: true }),
);
}
async function openSqlFile() {
const tab = activeTab.value;
if (!tab) return;
const connection = connectionStore.getConfig(tab.connectionId);
const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection?.db_type;
let openedSqlPath: string | undefined;
try {
if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog");
const path = await open({
filters: [{ name: "SQL", extensions: ["sql"] }],
filters: queryEditorOpenFileFilters(databaseType),
multiple: false,
});
if (path) {
@@ -2523,7 +2529,7 @@ async function openSqlFile() {
} else {
const input = document.createElement("input");
input.type = "file";
input.accept = ".sql";
input.accept = queryEditorOpenFileAccept(databaseType);
input.onchange = async () => {
const file = input.files?.[0];
if (!file) return;
@@ -2531,7 +2537,7 @@ async function openSqlFile() {
queryStore.updateSql(tab.id, await readBrowserSqlFile(file, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb)));
applyExternalSqlTarget(
tab,
activeTabExternalSqlFileTarget(queryStore.tabs, tab.id, (connectionId) => connectionStore.getConfig(connectionId)),
activeTabExternalSqlFileTarget(queryStore.tabs, tab.id, (connectionId) => connectionStore.getConfig(connectionId), { allowMongoScripts: true }),
);
} catch (e: any) {
toast(t("toolbar.sqlOpenFailed", { message: externalSqlFileOpenErrorMessage(e, (key, params) => t(key, params)) }), 5000);
+38 -11
View File
@@ -53,17 +53,7 @@ afterEach(() => {
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();
await mountFileDrop();
mocks.queryStore.tabs = [{ id: "sql-tab", connectionId: "postgres-1", database: "analytics", catalog: "hive", schema: "reporting" }];
mocks.queryStore.activeTabId = "sql-tab";
@@ -80,9 +70,46 @@ describe("useFileDrop SQL target", () => {
await vi.waitFor(() => expect(mocks.queryStore.createTab).toHaveBeenCalledTimes(2));
expect(mocks.queryStore.createTab).toHaveBeenNthCalledWith(2, "", "", "non-sql.sql", "query", undefined, undefined, undefined);
mocks.queryStore.tabs = [{ id: "mongo-tab", connectionId: "mongo-1", database: "admin", schema: undefined }];
mocks.queryStore.activeTabId = "mongo-tab";
mocks.connectionStore.getConfig.mockImplementation((connectionId: string) => (connectionId === "mongo-1" ? { id: connectionId, db_type: "mongodb" } : undefined));
dispatchSqlDrop("script.js");
await vi.waitFor(() => expect(mocks.queryStore.createTab).toHaveBeenCalledTimes(3));
expect(mocks.queryStore.createTab).toHaveBeenNthCalledWith(3, "mongo-1", "admin", "script.js", "query", undefined, undefined, undefined);
});
it("ignores dropped .js files that do not resolve to a MongoDB target", async () => {
await mountFileDrop();
mocks.queryStore.tabs = [{ id: "sql-tab", connectionId: "postgres-1", database: "analytics" }];
mocks.queryStore.activeTabId = "sql-tab";
mocks.connectionStore.getConfig.mockImplementation((connectionId: string) => (connectionId === "postgres-1" ? { id: connectionId, db_type: "postgres" } : undefined));
dispatchSqlDrop("script.js");
await vi.waitFor(() => expect(mocks.readBrowserSqlFile).toHaveBeenCalled());
await new Promise((resolve) => setTimeout(resolve, 20));
expect(mocks.queryStore.createTab).not.toHaveBeenCalled();
expect(mocks.queryStore.openExternalSqlFile).not.toHaveBeenCalled();
expect(mocks.toast).not.toHaveBeenCalled();
});
});
async function mountFileDrop() {
let setupFileDrop!: ReturnType<typeof useFileDrop>["setupFileDrop"];
app = createApp(
defineComponent({
setup() {
({ setupFileDrop } = useFileDrop());
return () => h("div");
},
}),
);
app.mount(document.createElement("div"));
await setupFileDrop();
}
function dispatchSqlDrop(name: string) {
const event = new Event("drop", { bubbles: true, cancelable: true });
Object.defineProperty(event, "dataTransfer", { value: { files: [new File(["select 1"], name)] } });
+11 -10
View File
@@ -9,13 +9,9 @@ import { useLargeSqlFileStreamingFallback } from "@/composables/useLargeSqlFileF
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 { externalSqlEditorMaxBytes, externalSqlFileOpenErrorMessage, isScriptFilePath, isSqlFilePath, readBrowserSqlFile } from "@/lib/sql/sqlFileOpen";
import { activeTabExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
function isSqlFilePath(path: string): boolean {
return /\.sql$/i.test(path);
}
function getDataFileQuery(path: string): Promise<string | undefined> {
return api.buildDroppedFilePreviewSql({ path });
}
@@ -29,11 +25,16 @@ export function useFileDrop() {
const { openInStreamingExecutorOnTooLarge } = useLargeSqlFileStreamingFallback();
async function openDroppedSqlFile(name: string, content: string, path?: string, version?: ExternalSqlFileVersion) {
const options = { allowMongoScripts: !isSqlFilePath(name) };
const target = path
? resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId), options)
: activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId), options);
// Dropped .js files only open when they resolve to a MongoDB target so they
// never bind to a relational SQL tab.
if (!isSqlFilePath(name) && connectionStore.getConfig(target.connectionId)?.db_type !== "mongodb") return;
if (path) {
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 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);
}
@@ -85,7 +86,7 @@ export function useFileDrop() {
continue;
}
if (isSqlFilePath(path)) {
if (isScriptFilePath(path)) {
try {
const snapshot = await api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
await openDroppedSqlFile(name, snapshot.content, path, snapshot.version);
@@ -127,7 +128,7 @@ export function useFileDrop() {
event.preventDefault();
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!isSqlFilePath(file.name)) continue;
if (!isScriptFilePath(file.name)) continue;
void readBrowserSqlFile(file, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb))
.then((content) => openDroppedSqlFile(file.name, content))
.catch((e: any) => {
@@ -139,7 +140,7 @@ export function useFileDrop() {
const files = event.dataTransfer?.files;
if (!files || files.length === 0) return;
for (let i = 0; i < files.length; i++) {
if (isSqlFilePath(files[i].name)) {
if (isScriptFilePath(files[i].name)) {
event.preventDefault();
return;
}
@@ -56,6 +56,18 @@ describe("external SQL file targets", () => {
});
});
it("reuses the active MongoDB tab context for a script file only when explicitly allowed", () => {
const tabs = [{ id: "mongo-tab", connectionId: "mongo-connection", database: "app_db", mode: "query" as const }];
const lookup = () => ({ db_type: "mongodb" as const });
const target = { connectionId: "mongo-connection", database: "app_db", catalog: undefined, schema: undefined };
expect(activeTabExternalSqlFileTarget(tabs, "mongo-tab", lookup)).toEqual(unassociatedExternalSqlFileTarget());
expect(resolveExternalSqlFileTargetForActiveTab("/work/query.js", tabs, "mongo-tab", lookup)).toEqual(unassociatedExternalSqlFileTarget());
expect(activeTabExternalSqlFileTarget(tabs, "mongo-tab", lookup, { allowMongoScripts: true })).toEqual(target);
expect(resolveExternalSqlFileTargetForActiveTab("/work/query.js", tabs, "mongo-tab", lookup, { allowMongoScripts: true })).toEqual(target);
expect(activeTabExternalSqlFileTarget(tabs, "mongo-tab", () => ({ db_type: "redis" }), { allowMongoScripts: true })).toEqual(unassociatedExternalSqlFileTarget());
});
it("keeps the fallback unassociated without an active tab", () => {
const tabs = [{ id: "inactive-tab", connectionId: "sql-connection", database: "analytics", mode: "query" as const }];
@@ -63,7 +75,7 @@ describe("external SQL file targets", () => {
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) => {
it.each(["mq", "zookeeper", "plugin", "redis", "mongodb"] 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());
+37
View File
@@ -2,18 +2,22 @@
import { describe, expect, it } from "vitest";
import {
defaultSavedQueryFileName,
ExternalSqlFileTooLargeError,
clampExternalSqlEditorMaxMbInput,
externalSqlEditorMaxBytes,
externalSqlFileDisplayTitles,
externalSqlFileOpenErrorMessage,
formatSqlFileSize,
isScriptFilePath,
isSqlFilePath,
MAX_EXTERNAL_SQL_EDITOR_FILE_BYTES,
MAX_EXTERNAL_SQL_EDITOR_FILE_MB,
MIN_EXTERNAL_SQL_EDITOR_FILE_MB,
normalizeExternalSqlEditorMaxMb,
normalizeExternalSqlPath,
queryEditorOpenFileAccept,
queryEditorOpenFileFilters,
readBrowserSqlFile,
} from "@/lib/sql/sqlFileOpen";
@@ -27,6 +31,12 @@ describe("external SQL file paths", () => {
expect(isSqlFilePath("/work/script.py")).toBe(false);
});
it("distinguishes script files (.sql and .js) from unsupported files", () => {
expect(isScriptFilePath("C:\\work\\demo.SQL")).toBe(true);
expect(isScriptFilePath("/work/mongo_query.js")).toBe(true);
expect(isScriptFilePath("/work/script.py")).toBe(false);
});
it("uses the shortest unique parent path for duplicate filenames", () => {
expect(externalSqlFileDisplayTitles(["/work/demo/create.sql", "/work/learn/create.sql", "/work/query.sql"])).toEqual(["demo/create.sql", "learn/create.sql", "query.sql"]);
});
@@ -36,6 +46,33 @@ describe("external SQL file paths", () => {
});
});
describe("query editor script file filters and names", () => {
it("provides MongoDB script filters for MongoDB database type", () => {
const filters = queryEditorOpenFileFilters("mongodb");
expect(filters).toEqual([
{ name: "MongoDB Script", extensions: ["js"] },
{ name: "SQL", extensions: ["sql"] },
{ name: "All Files", extensions: ["*"] },
]);
expect(queryEditorOpenFileAccept("mongodb")).toBe(".js,.sql");
});
it("keeps non-MongoDB pickers SQL-only", () => {
expect(queryEditorOpenFileFilters("postgres")).toEqual([{ name: "SQL", extensions: ["sql"] }]);
expect(queryEditorOpenFileFilters(undefined)).toEqual([{ name: "SQL", extensions: ["sql"] }]);
expect(queryEditorOpenFileAccept("postgres")).toBe(".sql");
expect(queryEditorOpenFileAccept(undefined)).toBe(".sql");
});
it("generates correct default save file names for MongoDB vs SQL", () => {
expect(defaultSavedQueryFileName("query_1", "mongodb")).toBe("query_1.js");
expect(defaultSavedQueryFileName("users list", "mongodb")).toBe("users_list.js");
expect(defaultSavedQueryFileName("existing.js", "mongodb")).toBe("existing.js");
expect(defaultSavedQueryFileName("query_1", "mysql")).toBe("query_1.sql");
expect(defaultSavedQueryFileName("query_1")).toBe("query_1.sql");
});
});
describe("external SQL file editor limit", () => {
it("accepts the exact browser editor limit", async () => {
const file = new Blob(["select 1;"]);
@@ -15,15 +15,16 @@ export interface ExternalSqlFileTarget {
type ExternalSqlFileTargetTab = Pick<QueryTab, "id" | "connectionId" | "database" | "catalog" | "schema" | "mode">;
type ExternalSqlFileTargetConnection = Pick<ConnectionConfig, "db_type">;
type ExternalSqlFileConnectionLookup = (connectionId: string) => ExternalSqlFileTargetConnection | undefined;
type ExternalSqlFileTargetOptions = { allowMongoScripts?: boolean };
export function unassociatedExternalSqlFileTarget(): ExternalSqlFileTarget {
return { connectionId: "", database: "", catalog: undefined, schema: undefined };
}
export function activeTabExternalSqlFileTarget(tabs: readonly ExternalSqlFileTargetTab[], activeTabId: string | null | undefined, getConnection: ExternalSqlFileConnectionLookup): ExternalSqlFileTarget {
export function activeTabExternalSqlFileTarget(tabs: readonly ExternalSqlFileTargetTab[], activeTabId: string | null | undefined, getConnection: ExternalSqlFileConnectionLookup, options: ExternalSqlFileTargetOptions = {}): 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();
if (!activeTab || activeTab.mode === "plugin-workbench" || activeTab.mode === "plugin-filesystem" || !connection || !(supportsSqlFileExecution(connection.db_type) || (options.allowMongoScripts === true && connection.db_type === "mongodb"))) return unassociatedExternalSqlFileTarget();
return {
connectionId: activeTab.connectionId,
database: activeTab.database,
@@ -103,6 +104,6 @@ export function resolveExternalSqlFileTarget(path: string, connectionExists: (co
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));
export function resolveExternalSqlFileTargetForActiveTab(path: string, tabs: readonly ExternalSqlFileTargetTab[], activeTabId: string | null | undefined, getConnection: ExternalSqlFileConnectionLookup, options: ExternalSqlFileTargetOptions = {}): ExternalSqlFileTarget {
return resolveExternalSqlFileTarget(path, (connectionId) => !!getConnection(connectionId), activeTabExternalSqlFileTarget(tabs, activeTabId, getConnection, options));
}
+32
View File
@@ -2,6 +2,38 @@ export function isSqlFilePath(path: string): boolean {
return /\.sql$/i.test(path.trim());
}
export function isScriptFilePath(path: string): boolean {
return /\.(sql|js)$/i.test(path.trim());
}
export interface QueryEditorFileDialogFilter {
name: string;
extensions: string[];
}
export function queryEditorOpenFileFilters(databaseType?: string): QueryEditorFileDialogFilter[] {
if (databaseType === "mongodb") {
return [
{ name: "MongoDB Script", extensions: ["js"] },
{ name: "SQL", extensions: ["sql"] },
{ name: "All Files", extensions: ["*"] },
];
}
return [{ name: "SQL", extensions: ["sql"] }];
}
export function queryEditorOpenFileAccept(databaseType?: string): string {
return databaseType === "mongodb" ? ".js,.sql" : ".sql";
}
export function defaultSavedQueryFileName(title: string, databaseType?: string): string {
const defaultExt = databaseType === "mongodb" ? "js" : "sql";
const trimmed = title.trim() || "query";
const normalized = trimmed.replace(/\s+/g, "_");
const extSuffix = `.${defaultExt}`;
return normalized.toLowerCase().endsWith(extSuffix) ? normalized : `${normalized}${extSuffix}`;
}
export function sqlFileTitleFromPath(path: string): string {
const normalized = normalizeExternalSqlPath(path);
const name = normalized.split("/").filter(Boolean).pop();