Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

6.8 KB
Raw Blame
import { useI18n } from "vue-i18n";
import { uuid } from "@/lib/common/utils";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
import { useLargeSqlFileStreamingFallback } from "@/composables/useLargeSqlFileFallback";
import * as api from "@/lib/backend/api";
import type { ConnectionConfig, ExternalSqlFileVersion } from "@/types/database";
import { detectDatabaseFileType } from "@/lib/database/databaseFileDetection";
import { externalSqlEditorMaxBytes, externalSqlFileOpenErrorMessage, isScriptFilePath, isSqlFilePath, readBrowserSqlFile } from "@/lib/sql/sqlFileOpen";
import { activeTabExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";

function getDataFileQuery(path: string): Promise<string | undefined> {
  return api.buildDroppedFilePreviewSql({ path });
}

export function useFileDrop() {
  const { t } = useI18n();
  const connectionStore = useConnectionStore();
  const queryStore = useQueryStore();
  const settingsStore = useSettingsStore();
  const { toast } = useToast();
  const { openInStreamingExecutorOnTooLarge } = useLargeSqlFileStreamingFallback();

  async function openDroppedSqlFile(name: string, content: string, path?: string, version?: ExternalSqlFileVersion, encoding?: import("@/types/database").QueryTab["externalSqlEncoding"]) {
    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) {
      queryStore.openExternalSqlFile(target.connectionId, target.database, path, content, version, target.catalog, target.schema, undefined, encoding);
    } else {
      const tabId = queryStore.createTab(target.connectionId, target.database, name, "query", target.schema, undefined, target.catalog);
      queryStore.updateSql(tabId, content);
    }
    toast(t("welcome.fileOpened", { name }));
  }

  async function setupFileDrop() {
    if (isTauriRuntime()) {
      const { getCurrentWebview } = await import("@tauri-apps/api/webview");
      const webview = getCurrentWebview();
      await webview.onDragDropEvent(async (event) => {
        const routedEvent = new CustomEvent("dbx:tauri-file-drop", {
          detail: event.payload,
          cancelable: true,
        });
        const handledByPanel = !document.dispatchEvent(routedEvent);
        if (event.payload.type !== "drop") return;
        if (handledByPanel) return;
        for (const path of event.payload.paths) {
          const name = path.split("/").pop()?.split("\\").pop() || path;

          const dataQuery = await getDataFileQuery(path);
          if (dataQuery) {
            const config: ConnectionConfig = {
              id: uuid(),
              name: `[Preview] ${name}`,
              db_type: "duckdb",
              driver_profile: "duckdb",
              driver_label: "DuckDB",
              url_params: "",
              host: ":memory:",
              port: 0,
              username: "",
              password: "",
              one_time: true,
            };
            let connectionId: string;
            try {
              connectionId = await api.connectDb(config);
            } catch (e: any) {
              toast(t("welcome.fileOpenFailed", { name, message: e?.message || String(e) }), 5000);
              continue;
            }
            connectionStore.addEphemeralConnection({ ...config, id: connectionId });
            const tabId = queryStore.createTab(connectionId, "", name, "query");
            queryStore.updateSql(tabId, dataQuery);
            queryStore.executeCurrentTab();
            toast(t("welcome.fileOpened", { name }));
            continue;
          }

          if (isScriptFilePath(path)) {
            try {
              const snapshot = await api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
              await openDroppedSqlFile(name, snapshot.content, path, snapshot.version, snapshot.encoding);
            } catch (e: any) {
              if (!openInStreamingExecutorOnTooLarge(path, e)) {
                toast(t("toolbar.sqlOpenFailed", { message: externalSqlFileOpenErrorMessage(e, (key, params) => t(key, params)) }), 5000);
              }
            }
            continue;
          }

          const dbType = await detectDatabaseFileType(path);
          if (!dbType) continue;
          const config: ConnectionConfig = {
            id: uuid(),
            name,
            db_type: dbType,
            driver_profile: dbType,
            driver_label: dbType === "duckdb" ? "DuckDB" : "SQLite",
            url_params: "",
            host: path,
            port: 0,
            username: "",
            password: "",
          };
          try {
            await connectionStore.addConnection(config);
            await connectionStore.connect(config);
            toast(t("welcome.fileOpened", { name }));
          } catch (e: any) {
            toast(t("welcome.fileOpenFailed", { name, message: e?.message || String(e) }), 5000);
          }
        }
      });
    } else {
      document.addEventListener("drop", (event) => {
        const files = event.dataTransfer?.files;
        if (!files || files.length === 0) return;
        event.preventDefault();
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          if (!isScriptFilePath(file.name)) continue;
          void readBrowserSqlFile(file, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb))
            .then((content) => openDroppedSqlFile(file.name, content))
            .catch((e: any) => {
              toast(t("toolbar.sqlOpenFailed", { message: externalSqlFileOpenErrorMessage(e, (key, params) => t(key, params)) }), 5000);
            });
        }
      });
      document.addEventListener("dragover", (event) => {
        const files = event.dataTransfer?.files;
        if (!files || files.length === 0) return;
        for (let i = 0; i < files.length; i++) {
          if (isScriptFilePath(files[i].name)) {
            event.preventDefault();
            return;
          }
        }
      });
    }
  }

  return { setupFileDrop };
}