feat(sql-library): support batch connection and database changes
Closes #9471
This commit is contained in:
1 parent
32f60e1fd3
commit
43ddfce93d
19 files changed
+850
-14
No files matched your search
@@ -2,10 +2,12 @@
|
|||||||
import { computed, nextTick, onBeforeUnmount, reactive, ref, watch } from "vue";
|
import { computed, nextTick, onBeforeUnmount, reactive, ref, watch } from "vue";
|
||||||
import type { CSSProperties } from "vue";
|
import type { CSSProperties } from "vue";
|
||||||
import { useI18n } from "vue-i18n";
|
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 { Button } from "@/components/ui/button";
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
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 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 HelpTooltip from "@/components/ui/tooltip/HelpTooltip.vue";
|
||||||
import LightTooltip from "@/components/ui/LightTooltip.vue";
|
import LightTooltip from "@/components/ui/LightTooltip.vue";
|
||||||
import { useToast } from "@/composables/useToast";
|
import { useToast } from "@/composables/useToast";
|
||||||
@@ -20,7 +22,7 @@ import { externalSqlEditorMaxBytes } from "@/lib/sql/sqlFileOpen";
|
|||||||
import { focusSidebarRenameInput } from "@/lib/sidebar/sidebarRenameFocus";
|
import { focusSidebarRenameInput } from "@/lib/sidebar/sidebarRenameFocus";
|
||||||
import { savedSqlFolderBranchFileCount } from "@/lib/savedSql/savedSqlFolderCounts";
|
import { savedSqlFolderBranchFileCount } from "@/lib/savedSql/savedSqlFolderCounts";
|
||||||
import { collectSavedSqlDirectoryImportFiles } from "@/lib/savedSql/savedSqlDirectoryImport";
|
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 { savedSqlDatabaseScopeKey } from "@/lib/savedSql/savedSqlDatabaseTree";
|
||||||
import { ensureSqlExtension, stripSqlExtension } from "@/lib/savedSql/savedSqlFileName";
|
import { ensureSqlExtension, stripSqlExtension } from "@/lib/savedSql/savedSqlFileName";
|
||||||
import { savedSqlImportTarget } from "@/lib/savedSql/savedSqlImportTarget";
|
import { savedSqlImportTarget } from "@/lib/savedSql/savedSqlImportTarget";
|
||||||
@@ -28,6 +30,9 @@ import { savedSqlExecutionTargetFromTab, type SavedSqlOpenTargetMode } from "@/l
|
|||||||
import { uniqueSavedSqlExportFileName, exportSavedSqlFileContent } from "@/lib/savedSql/savedSqlExport";
|
import { uniqueSavedSqlExportFileName, exportSavedSqlFileContent } from "@/lib/savedSql/savedSqlExport";
|
||||||
import { orderedListRangeAnchorIndex, orderedListSelectionIntent } from "@/lib/selection/orderedListSelection";
|
import { orderedListRangeAnchorIndex, orderedListSelectionIntent } from "@/lib/selection/orderedListSelection";
|
||||||
import { resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
|
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";
|
import type { SavedSqlFile, SavedSqlFolder } from "@/types/database";
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
@@ -36,6 +41,7 @@ const savedSqlStore = useSavedSqlStore();
|
|||||||
const connectionStore = useConnectionStore();
|
const connectionStore = useConnectionStore();
|
||||||
const queryStore = useQueryStore();
|
const queryStore = useQueryStore();
|
||||||
const settingsStore = useSettingsStore();
|
const settingsStore = useSettingsStore();
|
||||||
|
const { databaseOptions, loadingDatabaseOptions, loadDatabaseOptions, catalogOptions, loadingCatalogOptions, loadCatalogOptions, catalogDatabaseOptions, loadingCatalogDatabaseOptions, loadCatalogDatabaseOptions } = useDatabaseOptions();
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
close: [];
|
close: [];
|
||||||
@@ -516,6 +522,140 @@ const allSelectableItems = computed(() => {
|
|||||||
|
|
||||||
const hasSelection = computed(() => selectedFileIds.value.size > 0 || selectedFolderIds.value.size > 0);
|
const hasSelection = computed(() => selectedFileIds.value.size > 0 || selectedFolderIds.value.size > 0);
|
||||||
const selectedCount = computed(() => selectedFileIds.value.size + selectedFolderIds.value.size);
|
const selectedCount = computed(() => selectedFileIds.value.size + selectedFolderIds.value.size);
|
||||||
|
const showChangeTargetDialog = ref(false);
|
||||||
|
const changeTargetFileIds = ref<string[]>([]);
|
||||||
|
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() {
|
function clearSelection() {
|
||||||
selectedFileIds.value = new Set();
|
selectedFileIds.value = new Set();
|
||||||
@@ -860,6 +1000,12 @@ const contextMenuItems = computed<CtxMenuItem[]>(() => {
|
|||||||
if (hasSelection.value) {
|
if (hasSelection.value) {
|
||||||
const selectedFiles = Array.from(selectedFileIds.value);
|
const selectedFiles = Array.from(selectedFileIds.value);
|
||||||
return [
|
return [
|
||||||
|
{
|
||||||
|
label: t("sqlLibrary.changeTarget", { count: selectedFiles.length }),
|
||||||
|
action: () => openChangeTarget(selectedFiles),
|
||||||
|
icon: ArrowRightLeft,
|
||||||
|
visible: selectedFiles.length > 0,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
label: t("sqlLibrary.moveSelectedToFolder", { count: selectedFiles.length }),
|
label: t("sqlLibrary.moveSelectedToFolder", { count: selectedFiles.length }),
|
||||||
icon: FolderClosed,
|
icon: FolderClosed,
|
||||||
@@ -904,6 +1050,7 @@ const contextMenuItems = computed<CtxMenuItem[]>(() => {
|
|||||||
icon: Play,
|
icon: Play,
|
||||||
disabled: !hasCurrentSavedSqlExecutionTarget.value,
|
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.exportFile"), action: () => exportSingleFile(target), icon: Upload },
|
||||||
{ label: t("sqlLibrary.moveToFolder"), icon: FolderClosed, children: folderMoveMenuItems([target.id]) },
|
{ label: t("sqlLibrary.moveToFolder"), icon: FolderClosed, children: folderMoveMenuItems([target.id]) },
|
||||||
{ label: "", separator: true },
|
{ label: "", separator: true },
|
||||||
@@ -1479,6 +1626,81 @@ function showDropInside(targetId: string) {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog :open="showChangeTargetDialog" @update:open="(open) => (open ? (showChangeTargetDialog = true) : cancelChangeTarget())">
|
||||||
|
<DialogContent class="sm:max-w-[460px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{{ t("sqlLibrary.changeTargetTitle") }}</DialogTitle>
|
||||||
|
<DialogDescription>{{ t("sqlLibrary.changeTargetDescription", { count: changeTargetFileIds.length }) }}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div v-if="changeTargetConnections.length" class="space-y-4 py-2">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<label class="text-sm font-medium">{{ t("sqlLibrary.targetConnection") }}</label>
|
||||||
|
<ConnectionTreeSelect
|
||||||
|
:model-value="changeTargetConnectionId"
|
||||||
|
:connections="changeTargetConnections"
|
||||||
|
:layout="connectionStore.sidebarLayout"
|
||||||
|
:placeholder="t('editor.selectConnection')"
|
||||||
|
:search-placeholder="t('editor.searchConnection')"
|
||||||
|
:empty-text="t('grid.noSearchResults')"
|
||||||
|
:disabled="changingTarget"
|
||||||
|
trigger-class="h-8 w-full max-w-none justify-between border border-input bg-background px-2.5 text-sm"
|
||||||
|
list-class="w-[410px] max-w-[calc(100vw-2rem)]"
|
||||||
|
@update:model-value="resetChangeTargetConnection"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div v-if="showChangeTargetCatalog" class="space-y-1.5">
|
||||||
|
<label class="text-sm font-medium">{{ t("sqlLibrary.targetCatalog") }}</label>
|
||||||
|
<SearchableSelect
|
||||||
|
:model-value="changeTargetCatalog"
|
||||||
|
:options="changeTargetCatalogNames"
|
||||||
|
:placeholder="t('editor.selectCatalog')"
|
||||||
|
:search-placeholder="t('editor.searchCatalog')"
|
||||||
|
:empty-text="t('grid.noSearchResults')"
|
||||||
|
:loading-text="t('common.loading')"
|
||||||
|
:loading="loadingCatalogOptions[changeTargetConnectionId] || false"
|
||||||
|
:disabled="changingTarget"
|
||||||
|
@update:model-value="selectChangeTargetCatalog"
|
||||||
|
@update:open="(open: boolean) => open && loadChangeTargetCatalogs()"
|
||||||
|
>
|
||||||
|
<template #trigger-label="{ label, loading }">
|
||||||
|
<Layers class="h-3.5 w-3.5 shrink-0" />
|
||||||
|
<span class="truncate">{{ loading ? t("common.loading") : label }}</span>
|
||||||
|
</template>
|
||||||
|
</SearchableSelect>
|
||||||
|
</div>
|
||||||
|
<div v-if="showChangeTargetDatabase" class="space-y-1.5">
|
||||||
|
<label class="text-sm font-medium">{{ t("sqlLibrary.targetDatabase") }}</label>
|
||||||
|
<SearchableSelect
|
||||||
|
:model-value="changeTargetDatabase"
|
||||||
|
:options="changeTargetDatabaseNames"
|
||||||
|
:placeholder="t('editor.selectDatabase')"
|
||||||
|
:search-placeholder="t('editor.searchDatabase')"
|
||||||
|
:empty-text="t('grid.noSearchResults')"
|
||||||
|
:loading-text="t('common.loading')"
|
||||||
|
:loading="changeTargetDatabaseLoading"
|
||||||
|
:disabled="changingTarget || !changeTargetConnection"
|
||||||
|
:display-name="changeTargetDatabaseLabel"
|
||||||
|
@update:model-value="(database) => (changeTargetDatabase = database)"
|
||||||
|
@update:open="(open: boolean) => open && loadChangeTargetDatabases()"
|
||||||
|
>
|
||||||
|
<template #trigger-label="{ label, loading }">
|
||||||
|
<Database class="h-3.5 w-3.5 shrink-0" />
|
||||||
|
<span class="truncate">{{ loading ? t("common.loading") : label }}</span>
|
||||||
|
</template>
|
||||||
|
</SearchableSelect>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p v-else class="py-4 text-sm text-muted-foreground">{{ t("sqlLibrary.noTargetConnection") }}</p>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" size="sm" :disabled="changingTarget" @click="cancelChangeTarget">{{ t("dangerDialog.cancel") }}</Button>
|
||||||
|
<Button size="sm" :disabled="!canConfirmChangeTarget" @click="executeChangeTarget">
|
||||||
|
<Loader2 v-if="changingTarget" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||||
|
{{ t("sqlLibrary.changeTargetConfirm") }}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
<!-- Batch Delete Confirmation Dialog -->
|
<!-- Batch Delete Confirmation Dialog -->
|
||||||
<Dialog :open="showBatchDeleteConfirm" @update:open="(open) => (showBatchDeleteConfirm = open)">
|
<Dialog :open="showBatchDeleteConfirm" @update:open="(open) => (showBatchDeleteConfirm = open)">
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
|
|||||||
@@ -561,6 +561,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "{count} SQL-i qovluğa köçür...",
|
moveSelectedToFolder: "{count} SQL-i qovluğa köçür...",
|
||||||
moveSuccess: "{count} SQL faylı köçürüldü",
|
moveSuccess: "{count} SQL faylı köçürüldü",
|
||||||
moveFailed: "SQL-i köçürmək mümkün olmadı: {message}",
|
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ə",
|
clearSelection: "Seçimi təmizlə",
|
||||||
sortByDate: "Dəyişiklik tarixinə görə sırala",
|
sortByDate: "Dəyişiklik tarixinə görə sırala",
|
||||||
sortByFolder: "Qovluq quruluşuna görə sırala",
|
sortByFolder: "Qovluq quruluşuna görə sırala",
|
||||||
|
|||||||
@@ -797,6 +797,18 @@ export default {
|
|||||||
moveSelectedToFolder: "Move {count} SQL to Folder...",
|
moveSelectedToFolder: "Move {count} SQL to Folder...",
|
||||||
moveSuccess: "Moved {count} SQL file(s)",
|
moveSuccess: "Moved {count} SQL file(s)",
|
||||||
moveFailed: "Failed to move SQL: {message}",
|
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",
|
clearSelection: "Clear Selection",
|
||||||
sortByDate: "Sort by Date Modified",
|
sortByDate: "Sort by Date Modified",
|
||||||
sortByFolder: "Sort by Folder Structure",
|
sortByFolder: "Sort by Folder Structure",
|
||||||
|
|||||||
@@ -788,6 +788,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "Mover {count} SQL a carpeta...",
|
moveSelectedToFolder: "Mover {count} SQL a carpeta...",
|
||||||
moveSuccess: "Se movieron {count} SQL",
|
moveSuccess: "Se movieron {count} SQL",
|
||||||
moveFailed: "Error al mover SQL: {message}",
|
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",
|
clearSelection: "Limpiar selección",
|
||||||
sortByDate: "Ordenar por fecha de modificación",
|
sortByDate: "Ordenar por fecha de modificación",
|
||||||
sortByFolder: "Ordenar por estructura de carpetas",
|
sortByFolder: "Ordenar por estructura de carpetas",
|
||||||
|
|||||||
@@ -783,6 +783,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "Sposta {count} SQL nella cartella...",
|
moveSelectedToFolder: "Sposta {count} SQL nella cartella...",
|
||||||
moveSuccess: "{count} SQL spostati",
|
moveSuccess: "{count} SQL spostati",
|
||||||
moveFailed: "Impossibile spostare SQL: {message}",
|
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",
|
clearSelection: "Cancella selezione",
|
||||||
sortByDate: "Ordina per data di modifica",
|
sortByDate: "Ordina per data di modifica",
|
||||||
sortByFolder: "Ordina per struttura cartelle",
|
sortByFolder: "Ordina per struttura cartelle",
|
||||||
|
|||||||
@@ -783,6 +783,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "選択した {count} 個の SQL をフォルダへ移動...",
|
moveSelectedToFolder: "選択した {count} 個の SQL をフォルダへ移動...",
|
||||||
moveSuccess: "{count} 個の SQL を移動しました",
|
moveSuccess: "{count} 個の SQL を移動しました",
|
||||||
moveFailed: "SQLの移動に失敗しました: {message}",
|
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: "選択を解除",
|
clearSelection: "選択を解除",
|
||||||
sortByDate: "更新日時で並べ替え",
|
sortByDate: "更新日時で並べ替え",
|
||||||
sortByFolder: "フォルダ構造で並べ替え",
|
sortByFolder: "フォルダ構造で並べ替え",
|
||||||
|
|||||||
@@ -785,6 +785,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "SQL {count}개를 폴더로 이동...",
|
moveSelectedToFolder: "SQL {count}개를 폴더로 이동...",
|
||||||
moveSuccess: "SQL 파일 {count}개를 이동했습니다",
|
moveSuccess: "SQL 파일 {count}개를 이동했습니다",
|
||||||
moveFailed: "SQL 이동 실패: {message}",
|
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: "선택 해제",
|
clearSelection: "선택 해제",
|
||||||
sortByDate: "수정 날짜순 정렬",
|
sortByDate: "수정 날짜순 정렬",
|
||||||
sortByFolder: "폴더 구조순 정렬",
|
sortByFolder: "폴더 구조순 정렬",
|
||||||
|
|||||||
@@ -783,6 +783,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "Mover {count} SQL para pasta...",
|
moveSelectedToFolder: "Mover {count} SQL para pasta...",
|
||||||
moveSuccess: "{count} SQL movidos",
|
moveSuccess: "{count} SQL movidos",
|
||||||
moveFailed: "Falha ao mover SQL: {message}",
|
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",
|
clearSelection: "Limpar seleção",
|
||||||
sortByDate: "Ordenar por data de modificação",
|
sortByDate: "Ordenar por data de modificação",
|
||||||
sortByFolder: "Ordenar por estrutura de pastas",
|
sortByFolder: "Ordenar por estrutura de pastas",
|
||||||
|
|||||||
@@ -742,6 +742,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "Переместить SQL ({count}) в папку...",
|
moveSelectedToFolder: "Переместить SQL ({count}) в папку...",
|
||||||
moveSuccess: "Перемещено файлов SQL: {count}",
|
moveSuccess: "Перемещено файлов SQL: {count}",
|
||||||
moveFailed: "Не удалось переместить SQL: {message}",
|
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: "Снять выделение",
|
clearSelection: "Снять выделение",
|
||||||
sortByDate: "Сортировать по дате изменения",
|
sortByDate: "Сортировать по дате изменения",
|
||||||
sortByFolder: "Сортировать по структуре папок",
|
sortByFolder: "Сортировать по структуре папок",
|
||||||
|
|||||||
@@ -563,6 +563,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "{count} SQL dosyasını Klasöre Taşı...",
|
moveSelectedToFolder: "{count} SQL dosyasını Klasöre Taşı...",
|
||||||
moveSuccess: "{count} SQL dosyası taşındı",
|
moveSuccess: "{count} SQL dosyası taşındı",
|
||||||
moveFailed: "SQL taşınamadı: {message}",
|
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",
|
clearSelection: "Seçimi Temizle",
|
||||||
sortByDate: "Değiştirilme Tarihine Göre Sırala",
|
sortByDate: "Değiştirilme Tarihine Göre Sırala",
|
||||||
sortByFolder: "Klasör Yapısına Göre Sırala",
|
sortByFolder: "Klasör Yapısına Göre Sırala",
|
||||||
|
|||||||
@@ -713,6 +713,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "分类选中的 {count} 个 SQL 至...",
|
moveSelectedToFolder: "分类选中的 {count} 个 SQL 至...",
|
||||||
moveSuccess: "已分类 {count} 个 SQL",
|
moveSuccess: "已分类 {count} 个 SQL",
|
||||||
moveFailed: "分类 SQL 失败:{message}",
|
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: "清除选择",
|
clearSelection: "清除选择",
|
||||||
sortByDate: "按修改日期排序",
|
sortByDate: "按修改日期排序",
|
||||||
sortByFolder: "按文件夹结构排序",
|
sortByFolder: "按文件夹结构排序",
|
||||||
|
|||||||
@@ -786,6 +786,18 @@ export default withEnglishFallback({
|
|||||||
moveSelectedToFolder: "分類選取的 {count} 個 SQL 至...",
|
moveSelectedToFolder: "分類選取的 {count} 個 SQL 至...",
|
||||||
moveSuccess: "已分類 {count} 個 SQL",
|
moveSuccess: "已分類 {count} 個 SQL",
|
||||||
moveFailed: "分類 SQL 失敗:{message}",
|
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: "清除選取",
|
clearSelection: "清除選取",
|
||||||
sortByDate: "依修改日期排序",
|
sortByDate: "依修改日期排序",
|
||||||
sortByFolder: "依資料夾結構排序",
|
sortByFolder: "依資料夾結構排序",
|
||||||
|
|||||||
@@ -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)");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -8,6 +8,11 @@ interface SavedSqlNameConflictLike {
|
|||||||
message?: unknown;
|
message?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SavedSqlBatchFailureLike {
|
||||||
|
fileName: string;
|
||||||
|
error: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
export function savedSqlErrorMessage(error: unknown, translate: SavedSqlErrorTranslator): string {
|
export function savedSqlErrorMessage(error: unknown, translate: SavedSqlErrorTranslator): string {
|
||||||
const candidate = error as SavedSqlNameConflictLike | null;
|
const candidate = error as SavedSqlNameConflictLike | null;
|
||||||
if (candidate?.code === "SAVED_SQL_NAME_CONFLICT" && typeof candidate.fileName === "string") {
|
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;
|
if (typeof candidate?.message === "string") return candidate.message;
|
||||||
return String(error);
|
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("; ");
|
||||||
|
}
|
||||||
@@ -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<typeof import("@/lib/backend/api")>()),
|
||||||
|
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<string, string>();
|
||||||
|
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" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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<SavedSqlFile> & Pick<SavedSqlFile, "id" | "name">): 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<string, string>();
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -115,7 +115,7 @@ import { createSavedSqlEditorPosition, initSavedSqlEditorPositions, restoreSaved
|
|||||||
import { isDetachedWindow, resolveWindowContext } from "@/lib/app/windowContext";
|
import { isDetachedWindow, resolveWindowContext } from "@/lib/app/windowContext";
|
||||||
import { normalizeDetachedTabRuntime, type DetachedTabHandoff, type DetachedTabRuntimeState } from "@/lib/app/detachedTabHandoff";
|
import { normalizeDetachedTabRuntime, type DetachedTabHandoff, type DetachedTabRuntimeState } from "@/lib/app/detachedTabHandoff";
|
||||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
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 { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";
|
||||||
import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";
|
import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";
|
||||||
import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";
|
import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";
|
||||||
@@ -5336,6 +5336,18 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
updateSchema(tab.id, target.schema, options);
|
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 = {}) {
|
function openSavedSql(file: SavedSqlFile, options: OpenSavedSqlOptions = {}) {
|
||||||
const targetMode = options.targetMode ?? useSettingsStore().editorSettings.savedSqlOpenTargetMode;
|
const targetMode = options.targetMode ?? useSettingsStore().editorSettings.savedSqlOpenTargetMode;
|
||||||
const currentTarget = targetMode === "current" ? currentSavedSqlExecutionTarget() : undefined;
|
const currentTarget = targetMode === "current" ? currentSavedSqlExecutionTarget() : undefined;
|
||||||
@@ -9393,6 +9405,7 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
openExternalSqlFile,
|
openExternalSqlFile,
|
||||||
openSavedSql,
|
openSavedSql,
|
||||||
hydrateSavedSqlTabs,
|
hydrateSavedSqlTabs,
|
||||||
|
syncSavedSqlExecutionTargets,
|
||||||
togglePinnedTab,
|
togglePinnedTab,
|
||||||
reorderTab,
|
reorderTab,
|
||||||
createExecutionTargetGuard,
|
createExecutionTargetGuard,
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import * as api from "@/lib/backend/api";
|
|||||||
import { forgetSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";
|
import { forgetSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";
|
||||||
import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName";
|
import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName";
|
||||||
import { nextSavedSqlCopyName } from "@/lib/savedSql/savedSqlClipboard";
|
import { nextSavedSqlCopyName } from "@/lib/savedSql/savedSqlClipboard";
|
||||||
|
import { savedSqlBatchReassignment, type SavedSqlBatchTargetSelection } from "@/lib/savedSql/savedSqlBatchTarget";
|
||||||
import { savedSqlDatabaseScopeKey } from "@/lib/savedSql/savedSqlDatabaseTree";
|
import { savedSqlDatabaseScopeKey } from "@/lib/savedSql/savedSqlDatabaseTree";
|
||||||
|
import { normalizeSqlExecutionTarget, sqlExecutionTargetCapabilities } from "@/lib/database/sqlExecutionTargetCapabilities";
|
||||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||||
import { useSettingsStore } from "@/stores/settingsStore";
|
import { useSettingsStore } from "@/stores/settingsStore";
|
||||||
import type { SavedSqlFile, SavedSqlFolder, SavedSqlLibrary } from "@/types/database";
|
import type { SavedSqlFile, SavedSqlFolder, SavedSqlLibrary } from "@/types/database";
|
||||||
@@ -35,6 +37,32 @@ interface SavedSqlExecutionTargetInput {
|
|||||||
schema?: string;
|
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 {
|
interface SavedSqlNameScope {
|
||||||
id: string;
|
id: string;
|
||||||
connectionId: string;
|
connectionId: string;
|
||||||
@@ -154,7 +182,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
const pendingFolderCreates = new Map<string, Promise<SavedSqlFolder>>();
|
const pendingFolderCreates = new Map<string, Promise<SavedSqlFolder>>();
|
||||||
const fileTargetRevisions = new Map<string, number>();
|
const fileTargetRevisions = new Map<string, number>();
|
||||||
const pendingFileTargetSaves = new Map<string, Promise<SavedSqlFile | undefined>>();
|
const pendingFileTargetSaves = new Map<string, Promise<SavedSqlFile | undefined>>();
|
||||||
const persistedFileTargets = new Map<string, SavedSqlExecutionTargetInput & { updatedAt: string }>();
|
const persistedFileTargets = new Map<string, PersistedSavedSqlFileTarget>();
|
||||||
const persistedFileTargetNameReleases = new Map<string, () => void>();
|
const persistedFileTargetNameReleases = new Map<string, () => void>();
|
||||||
const pendingNamesByScope = new Map<string, Map<string, PendingSavedSqlName>>();
|
const pendingNamesByScope = new Map<string, Map<string, PendingSavedSqlName>>();
|
||||||
|
|
||||||
@@ -383,15 +411,26 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
catalog: normalizedCatalog(file.catalog),
|
catalog: normalizedCatalog(file.catalog),
|
||||||
database: file.database,
|
database: file.database,
|
||||||
schema: file.schema,
|
schema: file.schema,
|
||||||
|
folderId: file.folderId,
|
||||||
|
orderIndex: file.orderIndex,
|
||||||
updatedAt: file.updatedAt,
|
updatedAt: file.updatedAt,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateFileExecutionTarget(id: string, target: SavedSqlExecutionTargetInput): Promise<SavedSqlFile | undefined> {
|
function updateFileExecutionTarget(id: string, target: SavedSqlExecutionTargetInput, options: SavedSqlExecutionTargetUpdateOptions = {}): Promise<SavedSqlFile | undefined> {
|
||||||
const existing = getFile(id);
|
const existing = getFile(id);
|
||||||
if (!existing) return Promise.resolve(undefined);
|
if (!existing) return Promise.resolve(undefined);
|
||||||
const normalizedTarget = { ...target, catalog: normalizedCatalog(target.catalog) };
|
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);
|
return Promise.resolve(existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,7 +439,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
}
|
}
|
||||||
const revision = (fileTargetRevisions.get(id) ?? 0) + 1;
|
const revision = (fileTargetRevisions.get(id) ?? 0) + 1;
|
||||||
fileTargetRevisions.set(id, revision);
|
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 });
|
bumpVersion({ tree: true });
|
||||||
|
|
||||||
const previousSave = pendingFileTargetSaves.get(id) ?? Promise.resolve(undefined);
|
const previousSave = pendingFileTargetSaves.get(id) ?? Promise.resolve(undefined);
|
||||||
@@ -411,13 +450,14 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
|
|
||||||
let releaseName: (() => void) | undefined;
|
let releaseName: (() => void) | undefined;
|
||||||
try {
|
try {
|
||||||
const loaded = await ensureFileContent(id);
|
const currentFile = options.metadataOnly ? getFile(id) : await ensureFileContent(id);
|
||||||
if (!loaded || fileTargetRevisions.get(id) !== revision) return getFile(id);
|
if (!currentFile || fileTargetRevisions.get(id) !== revision) return currentFile;
|
||||||
|
|
||||||
const candidate: SavedSqlFile = {
|
const candidate: SavedSqlFile = {
|
||||||
...loaded,
|
...currentFile,
|
||||||
...normalizedTarget,
|
...normalizedTarget,
|
||||||
sqlLoaded: true,
|
folderId,
|
||||||
|
orderIndex,
|
||||||
updatedAt: nowIso(),
|
updatedAt: nowIso(),
|
||||||
};
|
};
|
||||||
files.value = files.value.map((file) => (file.id === id ? candidate : file));
|
files.value = files.value.map((file) => (file.id === id ? candidate : file));
|
||||||
@@ -430,17 +470,18 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
connectionId: persistedTarget.connectionId,
|
connectionId: persistedTarget.connectionId,
|
||||||
catalog: persistedTarget.catalog,
|
catalog: persistedTarget.catalog,
|
||||||
database: persistedTarget.database,
|
database: persistedTarget.database,
|
||||||
|
folderId: persistedTarget.folderId,
|
||||||
})
|
})
|
||||||
: savedSqlNameIdentity(candidate);
|
: savedSqlNameIdentity(candidate);
|
||||||
if (persistedNameIdentity !== savedSqlNameIdentity(candidate)) releaseName = reserveFileName(candidate);
|
if (persistedNameIdentity !== savedSqlNameIdentity(candidate)) releaseName = reserveFileName(candidate);
|
||||||
const saved = normalizeSavedSqlFile(await api.saveSavedSqlFile(candidate));
|
const saved = normalizeSavedSqlFile(await api.saveSavedSqlFile(candidate));
|
||||||
setPersistedFileTarget(saved);
|
setPersistedFileTarget(saved);
|
||||||
if (fileTargetRevisions.get(id) !== revision) return getFile(id);
|
if (fileTargetRevisions.get(id) !== revision) return getFile(id);
|
||||||
const current = getFile(id);
|
const latest = getFile(id);
|
||||||
const persisted = { ...saved, sql: current?.sql ?? saved.sql, sqlLoaded: current?.sqlLoaded ?? true };
|
const persisted = { ...saved, sql: latest?.sql ?? saved.sql, sqlLoaded: latest?.sqlLoaded ?? true };
|
||||||
files.value = files.value.map((file) => (file.id === id ? persisted : file));
|
files.value = files.value.map((file) => (file.id === id ? persisted : file));
|
||||||
bumpVersion();
|
bumpVersion();
|
||||||
await syncToLocalDirectory();
|
if (options.syncLocalDirectory !== false) await syncToLocalDirectory();
|
||||||
return persisted;
|
return persisted;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (fileTargetRevisions.get(id) === revision) {
|
if (fileTargetRevisions.get(id) === revision) {
|
||||||
@@ -466,6 +507,68 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
return save;
|
return save;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function updateFilesExecutionTarget(fileIds: readonly string[], target: SavedSqlBatchTargetSelection): Promise<SavedSqlBatchTargetResult> {
|
||||||
|
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) {
|
async function renameFile(id: string, name: string) {
|
||||||
const existing = getFile(id);
|
const existing = getFile(id);
|
||||||
if (!existing) return;
|
if (!existing) return;
|
||||||
@@ -843,6 +946,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
|||||||
deleteFolder,
|
deleteFolder,
|
||||||
saveFile,
|
saveFile,
|
||||||
updateFileExecutionTarget,
|
updateFileExecutionTarget,
|
||||||
|
updateFilesExecutionTarget,
|
||||||
renameFile,
|
renameFile,
|
||||||
copyFilesToDatabase,
|
copyFilesToDatabase,
|
||||||
recordFileUsage,
|
recordFileUsage,
|
||||||
|
|||||||
Reference in new issue
Block a user