diff --git a/apps/desktop/src/components/layout/SqlLibraryPanel.vue b/apps/desktop/src/components/layout/SqlLibraryPanel.vue index 007140ab9b..c2ccffa291 100644 --- a/apps/desktop/src/components/layout/SqlLibraryPanel.vue +++ b/apps/desktop/src/components/layout/SqlLibraryPanel.vue @@ -2,10 +2,12 @@ import { computed, nextTick, onBeforeUnmount, reactive, ref, watch } from "vue"; import type { CSSProperties } from "vue"; import { useI18n } from "vue-i18n"; -import { ArrowDownWideNarrow, ChevronsDownUp, Download, FilePlus, FileText, FolderCog, FolderClosed, FolderOpen, FolderPlus, Library, Loader2, LocateFixed, Pencil, Play, Search, Trash2, Upload, X } from "@lucide/vue"; +import { ArrowDownWideNarrow, ArrowRightLeft, ChevronsDownUp, Database, Download, FilePlus, FileText, FolderCog, FolderClosed, FolderOpen, FolderPlus, Layers, Library, Loader2, LocateFixed, Pencil, Play, Search, Trash2, Upload, X } from "@lucide/vue"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { SearchableSelect } from "@/components/ui/searchable-select"; import CustomContextMenu, { type ContextMenuItem as CtxMenuItem } from "@/components/ui/CustomContextMenu.vue"; +import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue"; import HelpTooltip from "@/components/ui/tooltip/HelpTooltip.vue"; import LightTooltip from "@/components/ui/LightTooltip.vue"; import { useToast } from "@/composables/useToast"; @@ -20,7 +22,7 @@ import { externalSqlEditorMaxBytes } from "@/lib/sql/sqlFileOpen"; import { focusSidebarRenameInput } from "@/lib/sidebar/sidebarRenameFocus"; import { savedSqlFolderBranchFileCount } from "@/lib/savedSql/savedSqlFolderCounts"; import { collectSavedSqlDirectoryImportFiles } from "@/lib/savedSql/savedSqlDirectoryImport"; -import { savedSqlErrorMessage } from "@/lib/savedSql/savedSqlErrors"; +import { savedSqlBatchErrorMessage, savedSqlErrorMessage } from "@/lib/savedSql/savedSqlErrors"; import { savedSqlDatabaseScopeKey } from "@/lib/savedSql/savedSqlDatabaseTree"; import { ensureSqlExtension, stripSqlExtension } from "@/lib/savedSql/savedSqlFileName"; import { savedSqlImportTarget } from "@/lib/savedSql/savedSqlImportTarget"; @@ -28,6 +30,9 @@ import { savedSqlExecutionTargetFromTab, type SavedSqlOpenTargetMode } from "@/l import { uniqueSavedSqlExportFileName, exportSavedSqlFileContent } from "@/lib/savedSql/savedSqlExport"; import { orderedListRangeAnchorIndex, orderedListSelectionIntent } from "@/lib/selection/orderedListSelection"; import { resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget"; +import { catalogDatabaseOptionsKey, normalizedQueryTabCatalog, queryCatalogSelectorVisible, useDatabaseOptions } from "@/composables/useDatabaseOptions"; +import { formatDatabaseLabel } from "@/lib/database/defaultDatabase"; +import { sqlExecutionTargetCapabilities, targetDefaultDatabase, targetUsesConnectionOnlyScope } from "@/lib/database/sqlExecutionTargetCapabilities"; import type { SavedSqlFile, SavedSqlFolder } from "@/types/database"; const { t } = useI18n(); @@ -36,6 +41,7 @@ const savedSqlStore = useSavedSqlStore(); const connectionStore = useConnectionStore(); const queryStore = useQueryStore(); const settingsStore = useSettingsStore(); +const { databaseOptions, loadingDatabaseOptions, loadDatabaseOptions, catalogOptions, loadingCatalogOptions, loadCatalogOptions, catalogDatabaseOptions, loadingCatalogDatabaseOptions, loadCatalogDatabaseOptions } = useDatabaseOptions(); const emit = defineEmits<{ close: []; @@ -516,6 +522,140 @@ const allSelectableItems = computed(() => { const hasSelection = computed(() => selectedFileIds.value.size > 0 || selectedFolderIds.value.size > 0); const selectedCount = computed(() => selectedFileIds.value.size + selectedFolderIds.value.size); +const showChangeTargetDialog = ref(false); +const changeTargetFileIds = ref([]); +const changeTargetConnectionId = ref(""); +const changeTargetCatalog = ref(""); +const changeTargetDatabase = ref(""); +const changingTarget = ref(false); + +const changeTargetConnections = computed(() => connectionStore.connections.filter((connection) => !!sqlExecutionTargetCapabilities(connection))); +const changeTargetConnection = computed(() => changeTargetConnections.value.find((connection) => connection.id === changeTargetConnectionId.value)); +const changeTargetCapabilities = computed(() => sqlExecutionTargetCapabilities(changeTargetConnection.value)); +const changeTargetCatalogs = computed(() => catalogOptions.value[changeTargetConnectionId.value] ?? []); +const normalizedChangeTargetCatalog = computed(() => normalizedQueryTabCatalog(changeTargetCatalogs.value, changeTargetCatalog.value)); +const showChangeTargetCatalog = computed(() => { + if (!changeTargetCapabilities.value?.supportsCatalog) return false; + return changeTargetCatalogs.value.length === 0 || queryCatalogSelectorVisible(changeTargetCatalogs.value); +}); +const changeTargetCatalogNames = computed(() => { + const names = changeTargetCatalogs.value.map((catalog) => catalog.name); + return changeTargetCatalog.value && !names.includes(changeTargetCatalog.value) ? [changeTargetCatalog.value, ...names] : names; +}); +const changeTargetDatabaseCacheKey = computed(() => (normalizedChangeTargetCatalog.value ? catalogDatabaseOptionsKey(changeTargetConnectionId.value, normalizedChangeTargetCatalog.value) : changeTargetConnectionId.value)); +const changeTargetDatabaseNames = computed(() => { + const names = normalizedChangeTargetCatalog.value ? (catalogDatabaseOptions.value[changeTargetDatabaseCacheKey.value] ?? []) : (databaseOptions.value[changeTargetConnectionId.value] ?? []); + return changeTargetDatabase.value && !names.includes(changeTargetDatabase.value) ? [changeTargetDatabase.value, ...names] : names; +}); +const changeTargetDatabaseLoading = computed(() => (normalizedChangeTargetCatalog.value ? (loadingCatalogDatabaseOptions.value[changeTargetDatabaseCacheKey.value] ?? false) : (loadingDatabaseOptions.value[changeTargetConnectionId.value] ?? false))); +const showChangeTargetDatabase = computed(() => !!changeTargetCapabilities.value?.supportsDatabase && !targetUsesConnectionOnlyScope(changeTargetConnection.value)); +const canConfirmChangeTarget = computed(() => { + if (changingTarget.value || changeTargetFileIds.value.length === 0 || !changeTargetConnection.value || !changeTargetCapabilities.value) return false; + return !changeTargetCapabilities.value.databaseRequired || !!changeTargetDatabase.value; +}); + +function resetChangeTargetConnection(connectionId: string) { + const connection = changeTargetConnections.value.find((candidate) => candidate.id === connectionId); + changeTargetConnectionId.value = connection?.id ?? ""; + changeTargetCatalog.value = ""; + changeTargetDatabase.value = connection && !targetUsesConnectionOnlyScope(connection) ? targetDefaultDatabase(connection) : ""; +} + +function openChangeTarget(fileIds: readonly string[]) { + const selectedFiles = [...new Set(fileIds)].map((id) => savedSqlStore.getFile(id)).filter((file): file is SavedSqlFile => Boolean(file)); + if (selectedFiles.length === 0) return; + changeTargetFileIds.value = selectedFiles.map((file) => file.id); + + const first = selectedFiles[0]!; + const commonConnectionId = selectedFiles.every((file) => file.connectionId === first.connectionId) && changeTargetConnections.value.some((connection) => connection.id === first.connectionId) ? first.connectionId : ""; + const fallbackConnectionId = [connectionStore.activeConnectionId, changeTargetConnections.value[0]?.id].find((id) => !!id && changeTargetConnections.value.some((connection) => connection.id === id)) ?? ""; + resetChangeTargetConnection(commonConnectionId || fallbackConnectionId); + + if (commonConnectionId) { + if (selectedFiles.every((file) => (file.catalog || "") === (first.catalog || ""))) changeTargetCatalog.value = first.catalog || ""; + if (selectedFiles.every((file) => file.database === first.database)) changeTargetDatabase.value = first.database; + } + showChangeTargetDialog.value = true; +} + +function cancelChangeTarget() { + if (changingTarget.value) return; + showChangeTargetDialog.value = false; + changeTargetFileIds.value = []; +} + +async function loadChangeTargetCatalogs() { + if (!changeTargetConnection.value || !changeTargetCapabilities.value?.supportsCatalog) return; + try { + await loadCatalogOptions(changeTargetConnection.value.id); + } catch (error) { + toast(t("sqlLibrary.changeTargetLoadFailed", { message: savedSqlErrorMessage(error, t) }), 5000); + } +} + +async function loadChangeTargetDatabases() { + const connection = changeTargetConnection.value; + if (!connection || targetUsesConnectionOnlyScope(connection)) return; + try { + if (normalizedChangeTargetCatalog.value) await loadCatalogDatabaseOptions(connection.id, normalizedChangeTargetCatalog.value); + else await loadDatabaseOptions(connection.id); + } catch (error) { + toast(t("sqlLibrary.changeTargetLoadFailed", { message: savedSqlErrorMessage(error, t) }), 5000); + } +} + +function selectChangeTargetCatalog(catalog: string) { + if (changeTargetCatalog.value === catalog) return; + changeTargetCatalog.value = catalog; + changeTargetDatabase.value = ""; +} + +function changeTargetDatabaseLabel(database: string) { + return formatDatabaseLabel(changeTargetConnection.value, database, { + defaultDatabase: t("editor.defaultDatabase"), + noDatabase: t("editor.noDatabase"), + }); +} + +async function executeChangeTarget() { + if (!canConfirmChangeTarget.value) return; + const connection = changeTargetConnection.value; + if (!connection || !connectionStore.getConfig(connection.id)) { + cancelChangeTarget(); + return; + } + + changingTarget.value = true; + try { + const result = await savedSqlStore.updateFilesExecutionTarget(changeTargetFileIds.value, { + connectionId: connection.id, + database: targetUsesConnectionOnlyScope(connection) ? "" : changeTargetDatabase.value, + catalog: changeTargetCapabilities.value?.supportsCatalog ? normalizedChangeTargetCatalog.value : undefined, + }); + showChangeTargetDialog.value = false; + changeTargetFileIds.value = []; + + if (result.failures.length === 0) { + if (result.succeeded.length === 0) return; + clearSelection(); + toast(t("sqlLibrary.changeTargetSuccess", { count: result.succeeded.length }), 2500); + return; + } + + selectedFileIds.value = new Set(result.failures.map((failure) => failure.fileId)); + selectedFolderIds.value = new Set(); + const message = savedSqlBatchErrorMessage(result.failures, t); + if (result.succeeded.length > 0) { + toast(t("sqlLibrary.changeTargetPartial", { count: result.succeeded.length, failed: result.failures.length, message }), 8000); + } else { + toast(t("sqlLibrary.changeTargetFailed", { message }), 8000); + } + } catch (error) { + toast(t("sqlLibrary.changeTargetFailed", { message: savedSqlErrorMessage(error, t) }), 8000); + } finally { + changingTarget.value = false; + } +} function clearSelection() { selectedFileIds.value = new Set(); @@ -860,6 +1000,12 @@ const contextMenuItems = computed(() => { if (hasSelection.value) { const selectedFiles = Array.from(selectedFileIds.value); return [ + { + label: t("sqlLibrary.changeTarget", { count: selectedFiles.length }), + action: () => openChangeTarget(selectedFiles), + icon: ArrowRightLeft, + visible: selectedFiles.length > 0, + }, { label: t("sqlLibrary.moveSelectedToFolder", { count: selectedFiles.length }), icon: FolderClosed, @@ -904,6 +1050,7 @@ const contextMenuItems = computed(() => { icon: Play, disabled: !hasCurrentSavedSqlExecutionTarget.value, }, + { label: t("sqlLibrary.changeTarget", { count: 1 }), action: () => openChangeTarget([target.id]), icon: ArrowRightLeft }, { label: t("sqlLibrary.exportFile"), action: () => exportSingleFile(target), icon: Upload }, { label: t("sqlLibrary.moveToFolder"), icon: FolderClosed, children: folderMoveMenuItems([target.id]) }, { label: "", separator: true }, @@ -1479,6 +1626,81 @@ function showDropInside(targetId: string) { + + + + {{ t("sqlLibrary.changeTargetTitle") }} + {{ t("sqlLibrary.changeTargetDescription", { count: changeTargetFileIds.length }) }} + +
+
+ + +
+
+ + + + +
+
+ + + + +
+
+

{{ t("sqlLibrary.noTargetConnection") }}

+ + + + +
+
+ diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts index 35e055e8c5..4c9e7982e4 100644 --- a/apps/desktop/src/i18n/locales/az.ts +++ b/apps/desktop/src/i18n/locales/az.ts @@ -561,6 +561,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "{count} SQL-i qovluğa köçür...", moveSuccess: "{count} SQL faylı köçürüldü", moveFailed: "SQL-i köçürmək mümkün olmadı: {message}", + changeTarget: "Əlaqəni/verilənlər bazasını dəyiş ({count})...", + changeTargetTitle: "Əlaqəni/verilənlər bazasını dəyiş", + changeTargetDescription: "Seçilmiş {count} SQL faylı üçün icra hədəfini seçin.", + targetConnection: "Əlaqə", + targetCatalog: "Kataloq", + targetDatabase: "Verilənlər bazası", + noTargetConnection: "İstifadə edilə bilən SQL əlaqəsi yoxdur.", + changeTargetConfirm: "Hədəfi dəyiş", + changeTargetLoadFailed: "Hədəf seçimlərini yükləmək mümkün olmadı: {message}", + changeTargetSuccess: "{count} SQL faylının hədəfi dəyişdirildi", + changeTargetPartial: "{count} SQL faylı dəyişdirildi; {failed} uğursuz oldu: {message}", + changeTargetFailed: "SQL hədəfini dəyişmək mümkün olmadı: {message}", clearSelection: "Seçimi təmizlə", sortByDate: "Dəyişiklik tarixinə görə sırala", sortByFolder: "Qovluq quruluşuna görə sırala", diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 8486437d5c..3db12bb563 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -797,6 +797,18 @@ export default { moveSelectedToFolder: "Move {count} SQL to Folder...", moveSuccess: "Moved {count} SQL file(s)", moveFailed: "Failed to move SQL: {message}", + changeTarget: "Change Connection/Database ({count})...", + changeTargetTitle: "Change Connection/Database", + changeTargetDescription: "Choose the execution target for {count} selected SQL file(s).", + targetConnection: "Connection", + targetCatalog: "Catalog", + targetDatabase: "Database", + noTargetConnection: "No SQL connection is available.", + changeTargetConfirm: "Change Target", + changeTargetLoadFailed: "Failed to load target options: {message}", + changeTargetSuccess: "Changed the target for {count} SQL file(s)", + changeTargetPartial: "Changed {count} SQL file(s); {failed} failed: {message}", + changeTargetFailed: "Failed to change SQL target: {message}", clearSelection: "Clear Selection", sortByDate: "Sort by Date Modified", sortByFolder: "Sort by Folder Structure", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index 420cdcb717..8d371c83cb 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -788,6 +788,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "Mover {count} SQL a carpeta...", moveSuccess: "Se movieron {count} SQL", moveFailed: "Error al mover SQL: {message}", + changeTarget: "Cambiar conexión/base de datos ({count})...", + changeTargetTitle: "Cambiar conexión/base de datos", + changeTargetDescription: "Elige el destino de ejecución para {count} archivos SQL seleccionados.", + targetConnection: "Conexión", + targetCatalog: "Catálogo", + targetDatabase: "Base de datos", + noTargetConnection: "No hay ninguna conexión SQL disponible.", + changeTargetConfirm: "Cambiar destino", + changeTargetLoadFailed: "No se pudieron cargar las opciones de destino: {message}", + changeTargetSuccess: "Se cambió el destino de {count} archivos SQL", + changeTargetPartial: "Se cambiaron {count} archivos SQL; {failed} fallaron: {message}", + changeTargetFailed: "No se pudo cambiar el destino SQL: {message}", clearSelection: "Limpiar selección", sortByDate: "Ordenar por fecha de modificación", sortByFolder: "Ordenar por estructura de carpetas", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 6fd6da526d..34f282edf6 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -783,6 +783,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "Sposta {count} SQL nella cartella...", moveSuccess: "{count} SQL spostati", moveFailed: "Impossibile spostare SQL: {message}", + changeTarget: "Cambia connessione/database ({count})...", + changeTargetTitle: "Cambia connessione/database", + changeTargetDescription: "Scegli la destinazione di esecuzione per {count} file SQL selezionati.", + targetConnection: "Connessione", + targetCatalog: "Catalogo", + targetDatabase: "Database", + noTargetConnection: "Nessuna connessione SQL disponibile.", + changeTargetConfirm: "Cambia destinazione", + changeTargetLoadFailed: "Impossibile caricare le opzioni di destinazione: {message}", + changeTargetSuccess: "Destinazione modificata per {count} file SQL", + changeTargetPartial: "Modificati {count} file SQL; {failed} non riusciti: {message}", + changeTargetFailed: "Impossibile cambiare la destinazione SQL: {message}", clearSelection: "Cancella selezione", sortByDate: "Ordina per data di modifica", sortByFolder: "Ordina per struttura cartelle", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 15dc558d2f..0607984f3d 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -783,6 +783,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "選択した {count} 個の SQL をフォルダへ移動...", moveSuccess: "{count} 個の SQL を移動しました", moveFailed: "SQLの移動に失敗しました: {message}", + changeTarget: "接続/データベースを変更({count})...", + changeTargetTitle: "接続/データベースを変更", + changeTargetDescription: "選択した {count} 個の SQL ファイルの実行先を選択します。", + targetConnection: "接続", + targetCatalog: "カタログ", + targetDatabase: "データベース", + noTargetConnection: "利用可能な SQL 接続がありません。", + changeTargetConfirm: "実行先を変更", + changeTargetLoadFailed: "実行先候補を読み込めませんでした: {message}", + changeTargetSuccess: "{count} 個の SQL ファイルの実行先を変更しました", + changeTargetPartial: "{count} 個の SQL ファイルを変更しました。{failed} 個失敗しました: {message}", + changeTargetFailed: "SQL の実行先を変更できませんでした: {message}", clearSelection: "選択を解除", sortByDate: "更新日時で並べ替え", sortByFolder: "フォルダ構造で並べ替え", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 4f93ac2d5c..e5c8466396 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -785,6 +785,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "SQL {count}개를 폴더로 이동...", moveSuccess: "SQL 파일 {count}개를 이동했습니다", moveFailed: "SQL 이동 실패: {message}", + changeTarget: "연결/데이터베이스 변경({count})...", + changeTargetTitle: "연결/데이터베이스 변경", + changeTargetDescription: "선택한 SQL 파일 {count}개의 실행 대상을 선택하세요.", + targetConnection: "연결", + targetCatalog: "카탈로그", + targetDatabase: "데이터베이스", + noTargetConnection: "사용 가능한 SQL 연결이 없습니다.", + changeTargetConfirm: "대상 변경", + changeTargetLoadFailed: "대상 옵션을 불러오지 못했습니다: {message}", + changeTargetSuccess: "SQL 파일 {count}개의 대상을 변경했습니다", + changeTargetPartial: "SQL 파일 {count}개를 변경했고 {failed}개는 실패했습니다: {message}", + changeTargetFailed: "SQL 대상 변경 실패: {message}", clearSelection: "선택 해제", sortByDate: "수정 날짜순 정렬", sortByFolder: "폴더 구조순 정렬", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index c99b58880a..539a44dfb2 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -783,6 +783,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "Mover {count} SQL para pasta...", moveSuccess: "{count} SQL movidos", moveFailed: "Falha ao mover SQL: {message}", + changeTarget: "Alterar conexão/banco de dados ({count})...", + changeTargetTitle: "Alterar conexão/banco de dados", + changeTargetDescription: "Escolha o destino de execução para {count} arquivos SQL selecionados.", + targetConnection: "Conexão", + targetCatalog: "Catálogo", + targetDatabase: "Banco de dados", + noTargetConnection: "Nenhuma conexão SQL está disponível.", + changeTargetConfirm: "Alterar destino", + changeTargetLoadFailed: "Falha ao carregar opções de destino: {message}", + changeTargetSuccess: "Destino alterado para {count} arquivos SQL", + changeTargetPartial: "{count} arquivos SQL alterados; {failed} falharam: {message}", + changeTargetFailed: "Falha ao alterar o destino SQL: {message}", clearSelection: "Limpar seleção", sortByDate: "Ordenar por data de modificação", sortByFolder: "Ordenar por estrutura de pastas", diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts index f48b9dd62f..057f01aae9 100644 --- a/apps/desktop/src/i18n/locales/ru.ts +++ b/apps/desktop/src/i18n/locales/ru.ts @@ -742,6 +742,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "Переместить SQL ({count}) в папку...", moveSuccess: "Перемещено файлов SQL: {count}", moveFailed: "Не удалось переместить SQL: {message}", + changeTarget: "Изменить подключение/базу ({count})...", + changeTargetTitle: "Изменить подключение/базу", + changeTargetDescription: "Выберите цель выполнения для файлов SQL: {count}.", + targetConnection: "Подключение", + targetCatalog: "Каталог", + targetDatabase: "База данных", + noTargetConnection: "Нет доступного подключения SQL.", + changeTargetConfirm: "Изменить цель", + changeTargetLoadFailed: "Не удалось загрузить варианты цели: {message}", + changeTargetSuccess: "Изменена цель для файлов SQL: {count}", + changeTargetPartial: "Изменено файлов SQL: {count}; ошибок: {failed}: {message}", + changeTargetFailed: "Не удалось изменить цель SQL: {message}", clearSelection: "Снять выделение", sortByDate: "Сортировать по дате изменения", sortByFolder: "Сортировать по структуре папок", diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts index fe005e3426..6b4373d80c 100644 --- a/apps/desktop/src/i18n/locales/tr.ts +++ b/apps/desktop/src/i18n/locales/tr.ts @@ -563,6 +563,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "{count} SQL dosyasını Klasöre Taşı...", moveSuccess: "{count} SQL dosyası taşındı", moveFailed: "SQL taşınamadı: {message}", + changeTarget: "Bağlantıyı/veritabanını değiştir ({count})...", + changeTargetTitle: "Bağlantıyı/veritabanını değiştir", + changeTargetDescription: "Seçili {count} SQL dosyası için yürütme hedefini seçin.", + targetConnection: "Bağlantı", + targetCatalog: "Katalog", + targetDatabase: "Veritabanı", + noTargetConnection: "Kullanılabilir SQL bağlantısı yok.", + changeTargetConfirm: "Hedefi değiştir", + changeTargetLoadFailed: "Hedef seçenekleri yüklenemedi: {message}", + changeTargetSuccess: "{count} SQL dosyasının hedefi değiştirildi", + changeTargetPartial: "{count} SQL dosyası değiştirildi; {failed} başarısız: {message}", + changeTargetFailed: "SQL hedefi değiştirilemedi: {message}", clearSelection: "Seçimi Temizle", sortByDate: "Değiştirilme Tarihine Göre Sırala", sortByFolder: "Klasör Yapısına Göre Sırala", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 8f1f63feda..c3d93d0004 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -713,6 +713,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "分类选中的 {count} 个 SQL 至...", moveSuccess: "已分类 {count} 个 SQL", moveFailed: "分类 SQL 失败:{message}", + changeTarget: "修改连接/数据库({count})...", + changeTargetTitle: "修改连接/数据库", + changeTargetDescription: "为选中的 {count} 个 SQL 文件选择执行目标。", + targetConnection: "连接", + targetCatalog: "目录", + targetDatabase: "数据库", + noTargetConnection: "当前没有可用的 SQL 连接。", + changeTargetConfirm: "修改目标", + changeTargetLoadFailed: "加载目标选项失败:{message}", + changeTargetSuccess: "已修改 {count} 个 SQL 文件的目标", + changeTargetPartial: "已修改 {count} 个 SQL 文件,{failed} 个失败:{message}", + changeTargetFailed: "修改 SQL 目标失败:{message}", clearSelection: "清除选择", sortByDate: "按修改日期排序", sortByFolder: "按文件夹结构排序", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index 8d3f20c90f..5fde20dbde 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -786,6 +786,18 @@ export default withEnglishFallback({ moveSelectedToFolder: "分類選取的 {count} 個 SQL 至...", moveSuccess: "已分類 {count} 個 SQL", moveFailed: "分類 SQL 失敗:{message}", + changeTarget: "修改連線/資料庫({count})...", + changeTargetTitle: "修改連線/資料庫", + changeTargetDescription: "為選取的 {count} 個 SQL 檔案選擇執行目標。", + targetConnection: "連線", + targetCatalog: "目錄", + targetDatabase: "資料庫", + noTargetConnection: "目前沒有可用的 SQL 連線。", + changeTargetConfirm: "修改目標", + changeTargetLoadFailed: "載入目標選項失敗:{message}", + changeTargetSuccess: "已修改 {count} 個 SQL 檔案的目標", + changeTargetPartial: "已修改 {count} 個 SQL 檔案,{failed} 個失敗:{message}", + changeTargetFailed: "修改 SQL 目標失敗:{message}", clearSelection: "清除選取", sortByDate: "依修改日期排序", sortByFolder: "依資料夾結構排序", diff --git a/apps/desktop/src/lib/__tests__/savedSql/savedSqlBatchTarget.spec.ts b/apps/desktop/src/lib/__tests__/savedSql/savedSqlBatchTarget.spec.ts new file mode 100644 index 0000000000..dc80bf5a8a --- /dev/null +++ b/apps/desktop/src/lib/__tests__/savedSql/savedSqlBatchTarget.spec.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; +import { savedSqlBatchReassignment } from "@/lib/savedSql/savedSqlBatchTarget"; +import { savedSqlBatchErrorMessage } from "@/lib/savedSql/savedSqlErrors"; +import type { SavedSqlFile, SavedSqlFolder } from "@/types/database"; + +const file: SavedSqlFile = { + id: "file-1", + connectionId: "source", + folderId: "folder-1", + name: "report.sql", + database: "sales", + catalog: "hive", + schema: "reporting", + sql: "SELECT 1;", + orderIndex: 2, + createdAt: "2026-09-01T00:00:00.000Z", + updatedAt: "2026-09-01T00:00:00.000Z", +}; + +const folder: SavedSqlFolder = { + id: "folder-1", + connectionId: "source", + name: "Reports", + createdAt: "2026-09-01T00:00:00.000Z", + updatedAt: "2026-09-01T00:00:00.000Z", +}; + +describe("savedSqlBatchReassignment", () => { + it("keeps the schema and folder when the execution namespace is unchanged", () => { + expect(savedSqlBatchReassignment(file, folder, { connectionId: "source", database: "sales", catalog: "hive" })).toEqual({ + target: { connectionId: "source", database: "sales", catalog: "hive", schema: "reporting" }, + folderId: "folder-1", + }); + }); + + it("clears the old catalog and schema while preserving the library folder across connections", () => { + expect(savedSqlBatchReassignment(file, folder, { connectionId: "target", database: "analytics" })).toEqual({ + target: { connectionId: "target", database: "analytics", catalog: undefined, schema: undefined }, + folderId: "folder-1", + }); + }); + + it("clears the schema when only the database changes and drops an orphaned folder", () => { + expect(savedSqlBatchReassignment(file, undefined, { connectionId: "source", database: "analytics", catalog: "hive" })).toEqual({ + target: { connectionId: "source", database: "analytics", catalog: "hive", schema: undefined }, + folderId: undefined, + }); + }); +}); + +describe("savedSqlBatchErrorMessage", () => { + it("keeps file identities in a bounded aggregate failure message", () => { + const failures = [ + { fileName: "one.sql", error: { code: "SAVED_SQL_NAME_CONFLICT", fileName: "one.sql" } }, + { fileName: "two.sql", error: new Error("write failed") }, + { fileName: "three.sql", error: new Error("offline") }, + ]; + + expect(savedSqlBatchErrorMessage(failures, (key, params) => (key === "savedSql.nameConflict" ? `${params?.name} exists` : key), 2)).toBe("one.sql: one.sql exists; two.sql: write failed; … (+1)"); + }); +}); diff --git a/apps/desktop/src/lib/savedSql/savedSqlBatchTarget.ts b/apps/desktop/src/lib/savedSql/savedSqlBatchTarget.ts new file mode 100644 index 0000000000..0d409174bd --- /dev/null +++ b/apps/desktop/src/lib/savedSql/savedSqlBatchTarget.ts @@ -0,0 +1,31 @@ +import type { SavedSqlFile, SavedSqlFolder } from "@/types/database"; +import type { SavedSqlExecutionTarget } from "@/lib/savedSql/savedSqlExecutionTarget"; + +export interface SavedSqlBatchTargetSelection { + connectionId: string; + database: string; + catalog?: string; +} + +export interface SavedSqlBatchReassignment { + target: SavedSqlExecutionTarget; + folderId?: string; +} + +function normalizedCatalog(catalog: string | null | undefined): string | undefined { + return catalog || undefined; +} + +export function savedSqlBatchReassignment(file: SavedSqlFile, folder: SavedSqlFolder | undefined, selection: SavedSqlBatchTargetSelection): SavedSqlBatchReassignment { + const catalog = normalizedCatalog(selection.catalog); + const keepsNamespace = file.connectionId === selection.connectionId && normalizedCatalog(file.catalog) === catalog && file.database === selection.database; + return { + target: { + connectionId: selection.connectionId, + database: selection.database, + catalog, + schema: keepsNamespace ? file.schema : undefined, + }, + folderId: folder?.id === file.folderId ? file.folderId : undefined, + }; +} diff --git a/apps/desktop/src/lib/savedSql/savedSqlErrors.ts b/apps/desktop/src/lib/savedSql/savedSqlErrors.ts index 64b77c8814..aa761804ef 100644 --- a/apps/desktop/src/lib/savedSql/savedSqlErrors.ts +++ b/apps/desktop/src/lib/savedSql/savedSqlErrors.ts @@ -8,6 +8,11 @@ interface SavedSqlNameConflictLike { message?: unknown; } +export interface SavedSqlBatchFailureLike { + fileName: string; + error: unknown; +} + export function savedSqlErrorMessage(error: unknown, translate: SavedSqlErrorTranslator): string { const candidate = error as SavedSqlNameConflictLike | null; if (candidate?.code === "SAVED_SQL_NAME_CONFLICT" && typeof candidate.fileName === "string") { @@ -16,3 +21,10 @@ export function savedSqlErrorMessage(error: unknown, translate: SavedSqlErrorTra if (typeof candidate?.message === "string") return candidate.message; return String(error); } + +export function savedSqlBatchErrorMessage(failures: readonly SavedSqlBatchFailureLike[], translate: SavedSqlErrorTranslator, limit = 3): string { + const visible = failures.slice(0, limit).map((failure) => `${failure.fileName}: ${savedSqlErrorMessage(failure.error, translate)}`); + const remaining = failures.length - visible.length; + if (remaining > 0) visible.push(`… (+${remaining})`); + return visible.join("; "); +} diff --git a/apps/desktop/src/stores/__tests__/queryStore.savedSqlTargetSync.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.savedSqlTargetSync.spec.ts new file mode 100644 index 0000000000..f069726d09 --- /dev/null +++ b/apps/desktop/src/stores/__tests__/queryStore.savedSqlTargetSync.spec.ts @@ -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()), + 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(); + 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" }); + }); +}); diff --git a/apps/desktop/src/stores/__tests__/savedSqlStore.batchTarget.spec.ts b/apps/desktop/src/stores/__tests__/savedSqlStore.batchTarget.spec.ts new file mode 100644 index 0000000000..07541828cb --- /dev/null +++ b/apps/desktop/src/stores/__tests__/savedSqlStore.batchTarget.spec.ts @@ -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 & Pick): 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(); + 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(); + }); +}); diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts index 612f8e8a4a..03d8c49127 100644 --- a/apps/desktop/src/stores/queryStore.ts +++ b/apps/desktop/src/stores/queryStore.ts @@ -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, diff --git a/apps/desktop/src/stores/savedSqlStore.ts b/apps/desktop/src/stores/savedSqlStore.ts index 5b1a51ed6d..4f70eb5bae 100644 --- a/apps/desktop/src/stores/savedSqlStore.ts +++ b/apps/desktop/src/stores/savedSqlStore.ts @@ -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>(); const fileTargetRevisions = new Map(); const pendingFileTargetSaves = new Map>(); - const persistedFileTargets = new Map(); + const persistedFileTargets = new Map(); const persistedFileTargetNameReleases = new Map void>(); const pendingNamesByScope = new Map>(); @@ -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 { + function updateFileExecutionTarget(id: string, target: SavedSqlExecutionTargetInput, options: SavedSqlExecutionTargetUpdateOptions = {}): Promise { 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 { + 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,