feat(ddl): formatted DDL display with dialog or tab mode
This commit is contained in:
1 parent
86bdf9f78a
commit
76e41a6a4d
30 files changed
+956
-51
No files matched your search
@@ -629,6 +629,7 @@ const completionTriggerModeDescription = computed(() => {
|
||||
});
|
||||
const editWordWrap = ref(settingsStore.editorSettings.wordWrap);
|
||||
const editShowWhitespace = ref(settingsStore.editorSettings.showWhitespace);
|
||||
const editDdlOpenMode = ref<EditorSettings["ddlOpenMode"]>(settingsStore.editorSettings.ddlOpenMode);
|
||||
const editVimModeEnabled = ref(settingsStore.editorSettings.vimModeEnabled);
|
||||
const editAutoCloseBrackets = ref(settingsStore.editorSettings.autoCloseBrackets);
|
||||
const editSqlSemanticDiagnosticsMode = ref<SqlSemanticDiagnosticsMode>(settingsStore.editorSettings.sqlSemanticDiagnosticsMode);
|
||||
@@ -985,6 +986,7 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {
|
||||
completionTriggerMode: editCompletionTriggerMode.value,
|
||||
wordWrap: editWordWrap.value,
|
||||
showWhitespace: editShowWhitespace.value,
|
||||
ddlOpenMode: editDdlOpenMode.value,
|
||||
vimModeEnabled: editVimModeEnabled.value,
|
||||
autoCloseBrackets: editAutoCloseBrackets.value,
|
||||
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode.value,
|
||||
@@ -1628,6 +1630,7 @@ function syncEditorSettingsDraftFromStore() {
|
||||
editCompletionTriggerMode.value = settingsStore.editorSettings.completionTriggerMode;
|
||||
editWordWrap.value = settingsStore.editorSettings.wordWrap;
|
||||
editShowWhitespace.value = settingsStore.editorSettings.showWhitespace;
|
||||
editDdlOpenMode.value = settingsStore.editorSettings.ddlOpenMode;
|
||||
editVimModeEnabled.value = settingsStore.editorSettings.vimModeEnabled;
|
||||
editAutoCloseBrackets.value = settingsStore.editorSettings.autoCloseBrackets;
|
||||
editSqlSemanticDiagnosticsMode.value = settingsStore.editorSettings.sqlSemanticDiagnosticsMode;
|
||||
@@ -1762,6 +1765,7 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {
|
||||
selectFirstCompletionOnOpen: editSelectFirstCompletionOnOpen,
|
||||
wordWrap: editWordWrap,
|
||||
showWhitespace: editShowWhitespace,
|
||||
ddlOpenMode: editDdlOpenMode,
|
||||
vimModeEnabled: editVimModeEnabled,
|
||||
autoCloseBrackets: editAutoCloseBrackets,
|
||||
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode,
|
||||
@@ -2231,6 +2235,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {
|
||||
editCompletionTriggerMode.value = DEFAULT_EDITOR_SETTINGS.completionTriggerMode;
|
||||
editWordWrap.value = DEFAULT_EDITOR_SETTINGS.wordWrap;
|
||||
editShowWhitespace.value = DEFAULT_EDITOR_SETTINGS.showWhitespace;
|
||||
editDdlOpenMode.value = DEFAULT_EDITOR_SETTINGS.ddlOpenMode;
|
||||
editVimModeEnabled.value = DEFAULT_EDITOR_SETTINGS.vimModeEnabled;
|
||||
editAutoCloseBrackets.value = DEFAULT_EDITOR_SETTINGS.autoCloseBrackets;
|
||||
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
|
||||
@@ -2383,6 +2388,7 @@ function resetAllDefaults() {
|
||||
editSelectFirstCompletionOnOpen.value = DEFAULT_EDITOR_SETTINGS.selectFirstCompletionOnOpen;
|
||||
editWordWrap.value = DEFAULT_EDITOR_SETTINGS.wordWrap;
|
||||
editShowWhitespace.value = DEFAULT_EDITOR_SETTINGS.showWhitespace;
|
||||
editDdlOpenMode.value = DEFAULT_EDITOR_SETTINGS.ddlOpenMode;
|
||||
editVimModeEnabled.value = DEFAULT_EDITOR_SETTINGS.vimModeEnabled;
|
||||
editAutoCloseBrackets.value = DEFAULT_EDITOR_SETTINGS.autoCloseBrackets;
|
||||
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
|
||||
@@ -2734,6 +2740,10 @@ function setRoutineSourceOpenMode(value: "query-tab" | "dialog") {
|
||||
editRoutineSourceOpenMode.value = value;
|
||||
}
|
||||
|
||||
function setDdlOpenMode(value: unknown) {
|
||||
if (value === "dialog" || value === "tab") editDdlOpenMode.value = value;
|
||||
}
|
||||
|
||||
function setIconTheme(value: DesktopIconTheme) {
|
||||
editIconTheme.value = value;
|
||||
}
|
||||
@@ -6325,6 +6335,22 @@ onUnmounted(() => {
|
||||
<Switch id="editor-word-wrap" v-model="editWordWrap" class="mt-0.5" />
|
||||
</div>
|
||||
|
||||
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
||||
<div class="space-y-1">
|
||||
<Label for="editor-ddl-open-mode">{{ t("settings.ddlOpenMode") }}</Label>
|
||||
<p class="text-xs text-muted-foreground">{{ t("settings.ddlOpenModeDescription") }}</p>
|
||||
</div>
|
||||
<Select :model-value="editDdlOpenMode" @update:model-value="setDdlOpenMode">
|
||||
<SelectTrigger id="editor-ddl-open-mode" class="h-8 w-36 shrink-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="dialog">{{ t("settings.ddlOpenModeDialog") }}</SelectItem>
|
||||
<SelectItem value="tab">{{ t("settings.ddlOpenModeTab") }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
||||
<div class="space-y-1">
|
||||
<Label for="editor-vim-mode">{{ t("settings.vimMode") }}</Label>
|
||||
|
||||
@@ -181,6 +181,9 @@ import { useTabScroll } from "@/composables/useTabScroll";
|
||||
import { useToolbarOverflow } from "@/composables/useToolbarOverflow";
|
||||
import { formatElapsedSeconds } from "@/lib/common/elapsedTime";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";
|
||||
import { formatDdlForDisplay } from "@/lib/sql/ddlDisplay";
|
||||
import { sqlObjectNavigationTypeFromTableType } from "@/lib/sql/sqlNavigation";
|
||||
import type { CustomSaveHandler } from "@/composables/useDataGridEditor";
|
||||
import type { QueryMessage, QueryTab, TableInfoTab, TreeNode, VectorCollectionMeta } from "@/types/database";
|
||||
import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
|
||||
@@ -280,6 +283,7 @@ const colorizeDataGridCellTypes = computed(() => settingsStore.editorSettings.co
|
||||
const setColorizeDataGridCellTypes = (value: boolean) => settingsStore.updateEditorSettings({ colorizeDataGridCellTypes: value });
|
||||
const { toast } = useToast();
|
||||
const DEFAULT_QUERY_RESULTS_PANE_SIZE = 68;
|
||||
const ddlRefreshInProgress = ref(false);
|
||||
|
||||
onMounted(() => {
|
||||
// The watcher below warms the grid for query/data tabs. Keep source-only
|
||||
@@ -700,6 +704,7 @@ const resultsPaneSize = ref(Number(safeLocalStorageGet("dbx-results-pane-size"))
|
||||
const editorPaneSize = computed(() => (props.editorOnly || !resultsPaneOpen.value ? 100 : 100 - resultsPaneSize.value));
|
||||
const queryRunningElapsed = ref(0);
|
||||
const sourceLoadElapsed = ref(0);
|
||||
const ddlLoadElapsed = ref(0);
|
||||
|
||||
function toggleResultsPane(): boolean {
|
||||
if (props.activeTab.mode !== "query" || !hasQueryOutput.value) return false;
|
||||
@@ -748,19 +753,27 @@ function pendingSourceLoadStartedAt(): number | undefined {
|
||||
return load && !load.error ? load.startedAt : undefined;
|
||||
}
|
||||
|
||||
// 一个 rAF 循环同时驱动「查询执行中」与「对象源码加载中」两个耗时显示:
|
||||
/** DDL 新标签仍在加载(未失败)时的开始时间;与源码加载共用同一个 rAF 循环。 */
|
||||
function pendingDdlLoadStartedAt(): number | undefined {
|
||||
const load = props.activeTab.ddlLoad;
|
||||
return load && !load.error ? load.startedAt : undefined;
|
||||
}
|
||||
|
||||
// 一个 rAF 循环同时驱动「查询执行中」「对象源码加载中」「DDL 加载中」三个耗时显示:
|
||||
// issue #9035 的核心体感就是「不知道要等多久」,所以源码加载也要显示已耗时。
|
||||
function updateRunningElapsed() {
|
||||
const startedAt = props.activeTab.queryExecutionStartedAt;
|
||||
queryRunningElapsed.value = props.activeTab.isExecuting && startedAt ? Math.max(0, Date.now() - startedAt) : 0;
|
||||
const sourceStartedAt = pendingSourceLoadStartedAt();
|
||||
sourceLoadElapsed.value = sourceStartedAt ? Math.max(0, Date.now() - sourceStartedAt) : 0;
|
||||
const ddlStartedAt = pendingDdlLoadStartedAt();
|
||||
ddlLoadElapsed.value = ddlStartedAt ? Math.max(0, Date.now() - ddlStartedAt) : 0;
|
||||
}
|
||||
|
||||
function startRunningElapsedTimer() {
|
||||
stopRunningElapsedTimer();
|
||||
updateRunningElapsed();
|
||||
const isTicking = () => (props.activeTab.isExecuting && !!props.activeTab.queryExecutionStartedAt) || pendingSourceLoadStartedAt() !== undefined;
|
||||
const isTicking = () => (props.activeTab.isExecuting && !!props.activeTab.queryExecutionStartedAt) || pendingSourceLoadStartedAt() !== undefined || pendingDdlLoadStartedAt() !== undefined;
|
||||
if (!isTicking()) return;
|
||||
const updateOnNextFrame = () => {
|
||||
updateRunningElapsed();
|
||||
@@ -773,8 +786,11 @@ function startRunningElapsedTimer() {
|
||||
|
||||
const queryRunningElapsedSeconds = computed(() => formatElapsedSeconds(queryRunningElapsed.value));
|
||||
const sourceLoadElapsedSeconds = computed(() => formatElapsedSeconds(sourceLoadElapsed.value));
|
||||
const ddlLoadElapsedSeconds = computed(() => formatElapsedSeconds(ddlLoadElapsed.value));
|
||||
|
||||
watch(() => [props.activeTab.id, props.activeTab.isExecuting, props.activeTab.queryExecutionStartedAt, props.activeTab.sourceLoad?.startedAt, props.activeTab.sourceLoad?.error] as const, startRunningElapsedTimer, { immediate: true });
|
||||
watch(() => [props.activeTab.id, props.activeTab.isExecuting, props.activeTab.queryExecutionStartedAt, props.activeTab.sourceLoad?.startedAt, props.activeTab.sourceLoad?.error, props.activeTab.ddlLoad?.startedAt, props.activeTab.ddlLoad?.error] as const, startRunningElapsedTimer, {
|
||||
immediate: true,
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
stopRunningElapsedTimer();
|
||||
@@ -976,6 +992,77 @@ function onHandleStructureViewData() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the DDL of the active DDL viewer tab. Serves the toolbar refresh, the
|
||||
* in-place retry, and the initial pending load of a freshly created tab (which
|
||||
* renders the loading state instead of an editor): a pending load that fails
|
||||
* lands in the tab itself with an in-place retry, while a refresh of
|
||||
* already-loaded content only reports through a toast.
|
||||
*/
|
||||
async function loadActiveDdlViewer(force: boolean) {
|
||||
const tab = props.activeTab;
|
||||
const ddlViewer = tab.ddlViewer;
|
||||
if (!ddlViewer || ddlRefreshInProgress.value) return;
|
||||
ddlRefreshInProgress.value = true;
|
||||
const pendingLoad = !!tab.ddlLoad;
|
||||
if (pendingLoad) tab.ddlLoad = { startedAt: Date.now() };
|
||||
try {
|
||||
const { ddl } = await loadObjectDdl(
|
||||
{
|
||||
connectionId: tab.connectionId,
|
||||
database: tab.database,
|
||||
schema: ddlViewer.schema || tab.database,
|
||||
tableName: ddlViewer.tableName,
|
||||
objectType: ddlViewer.objectType,
|
||||
catalog: tab.catalog,
|
||||
},
|
||||
{ force },
|
||||
);
|
||||
const dialect = ddlViewer.formatDialect ?? activeSqlFormatDialect.value;
|
||||
const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(tab.connectionId) ?? props.activeConnection);
|
||||
const displayed = await formatDdlForDisplay(
|
||||
ddl,
|
||||
{
|
||||
dialect,
|
||||
databaseType,
|
||||
database: tab.database,
|
||||
catalog: tab.catalog,
|
||||
includeDatabaseName: settingsStore.editorSettings.generateSqlIncludeDatabaseName,
|
||||
quoteIdentifiers: settingsStore.editorSettings.generateSqlQuoteIdentifiers,
|
||||
excludeDdlStorage: settingsStore.editorSettings.excludeDdlStorage,
|
||||
},
|
||||
settingsStore.editorSettings.sqlFormatter,
|
||||
);
|
||||
queryStore.updateSql(tab.id, displayed);
|
||||
tab.originalSql = displayed;
|
||||
if (pendingLoad) tab.ddlLoad = undefined;
|
||||
} catch (error: any) {
|
||||
if (pendingLoad) {
|
||||
tab.ddlLoad = { startedAt: Date.now(), error: error?.message || String(error) };
|
||||
} else {
|
||||
toast(t("contextMenu.ddlRefreshFailed", { message: error?.message || String(error) }), 5000);
|
||||
}
|
||||
} finally {
|
||||
ddlRefreshInProgress.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshDdlViewer() {
|
||||
void loadActiveDdlViewer(true);
|
||||
}
|
||||
|
||||
function viewDdlTableData() {
|
||||
const tab = props.activeTab;
|
||||
const ddlViewer = tab.ddlViewer;
|
||||
if (!ddlViewer) return;
|
||||
emit("viewTableData", tab.id, {
|
||||
name: ddlViewer.tableName,
|
||||
database: tab.database,
|
||||
schema: ddlViewer.schema,
|
||||
type: ddlViewer.objectType ? sqlObjectNavigationTypeFromTableType(ddlViewer.objectType) : "table",
|
||||
});
|
||||
}
|
||||
|
||||
function onHandleViewTableDdl(target: SqlObjectNavigationTarget) {
|
||||
emit("viewTableDdl", props.activeTab.id, target);
|
||||
}
|
||||
@@ -1503,11 +1590,22 @@ defineExpose({
|
||||
<Splitpanes horizontal class="query-output-splitpanes flex-1 min-h-0 overflow-hidden" @resize="onResultsSplitResize" @resized="onResultsResized">
|
||||
<Pane v-if="!resultOnly" class="min-h-0" :size="editorPaneSize" :min-size="resultsPaneOpen ? 15 : 100">
|
||||
<div class="h-full flex flex-col relative">
|
||||
<div v-if="activeTab.ddlViewer" class="flex h-10 shrink-0 items-center gap-2 border-b px-3">
|
||||
<Button variant="outline" size="sm" :disabled="ddlRefreshInProgress" @click="refreshDdlViewer">
|
||||
<RefreshCcw class="h-4 w-4" :class="ddlRefreshInProgress ? 'animate-spin' : ''" />
|
||||
{{ t("structureEditor.refresh") }}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="viewDdlTableData">
|
||||
<TableProperties class="h-4 w-4" />
|
||||
{{ t("contextMenu.viewData") }}
|
||||
</Button>
|
||||
</div>
|
||||
<div v-if="activeProductionContext.active" class="production-watermark pointer-events-none absolute inset-0 z-10 grid select-none" aria-hidden="true">
|
||||
<span v-for="index in 4" :key="index" class="production-watermark__label whitespace-nowrap font-mono text-6xl font-extrabold text-red-700/[0.12] dark:text-red-200/[0.1]">{{ productionWatermarkText }}</span>
|
||||
</div>
|
||||
<!-- issue #9035:源码 tab 先出现再加载。pending 期间不挂载编辑器
|
||||
(还没有内容可编辑,也省下一次 Monaco 初始化),失败则就地重试。 -->
|
||||
(还没有内容可编辑,也省下一次 Monaco 初始化),失败则就地重试。
|
||||
issue #9387:DDL 新标签同样先出 tab 再加载,失败就地显示错误。 -->
|
||||
<QueryLoadingState v-if="activeTab.sourceLoad && !activeTab.sourceLoad.error" class="relative z-0 flex-1" :elapsed-seconds="sourceLoadElapsedSeconds" />
|
||||
<div v-else-if="activeTab.sourceLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-object-source-load-error>
|
||||
<p class="max-w-[80%] text-center break-words text-destructive">{{ activeTab.sourceLoad.error }}</p>
|
||||
@@ -1516,6 +1614,14 @@ defineExpose({
|
||||
{{ t("common.retry") }}
|
||||
</Button>
|
||||
</div>
|
||||
<QueryLoadingState v-else-if="activeTab.ddlLoad && !activeTab.ddlLoad.error" class="relative z-0 flex-1" :elapsed-seconds="ddlLoadElapsedSeconds" />
|
||||
<div v-else-if="activeTab.ddlLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-ddl-load-error>
|
||||
<p class="max-w-[80%] text-center break-words text-destructive">{{ t("contextMenu.ddlRefreshFailed", { message: activeTab.ddlLoad.error }) }}</p>
|
||||
<Button variant="outline" size="sm" class="gap-1.5" @click="queryStore.retryDdlViewerTab(activeTab.id)">
|
||||
<RotateCcw class="h-4 w-4" />
|
||||
{{ t("common.retry") }}
|
||||
</Button>
|
||||
</div>
|
||||
<QueryEditor
|
||||
v-else
|
||||
ref="queryEditorRef"
|
||||
@@ -1546,6 +1652,8 @@ defineExpose({
|
||||
:initial-selection="activeTab.editorSelection"
|
||||
:reveal-request="activeTab.editorRevealRequest"
|
||||
:force-word-wrap="activeTab.forceWordWrap"
|
||||
:read-only="!!activeTab.ddlViewer"
|
||||
:hide-execution-controls="!!activeTab.ddlViewer"
|
||||
enable-explain-shortcut
|
||||
:can-explain="!activeTab.isExecuting && !activeTab.isExplaining && !!executableSql.trim()"
|
||||
@update:model-value="emit('editorUpdate', activeTab.id, $event)"
|
||||
|
||||
@@ -111,7 +111,7 @@ const groupTabs = computed(() => {
|
||||
});
|
||||
const activeTab = computed(() => groupTabs.value.find((tab) => tab.id === props.activeTabId) ?? groupTabs.value[0] ?? null);
|
||||
const activeConnection = computed(() => (activeTab.value ? connectionStore.getConfig(activeTab.value.connectionId) : undefined));
|
||||
const showGroupToolbar = computed(() => activeTab.value?.mode === "query" && !isPreviewTab(activeTab.value));
|
||||
const showGroupToolbar = computed(() => activeTab.value?.mode === "query" && !activeTab.value.ddlViewer && !isPreviewTab(activeTab.value));
|
||||
const isGroupStickyManualTransaction = computed(() => usesProvenReadOnlyStickyTransactionState(effectiveDatabaseTypeForConnection(activeConnection.value)) && (activeTab.value?.autoCommit ?? true) === false);
|
||||
// Each group previews the executable SQL of its own active tab (selection
|
||||
// stored on the tab), not the focused tab's global selection.
|
||||
|
||||
@@ -3,7 +3,7 @@ import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
|
||||
import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
|
||||
import { computed, nextTick, onUnmounted, ref, shallowRef, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Clipboard, Loader2, RefreshCw } from "@lucide/vue";
|
||||
import { Clipboard, ExternalLink, Loader2, RefreshCw } from "@lucide/vue";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { useTheme } from "@/composables/useTheme";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
@@ -11,11 +11,13 @@ import { loadEditorTheme, editorFontTheme } from "@/lib/editor/editorThemes";
|
||||
import { editorClipboardLineEndingsExtension } from "@/lib/editor/editorClipboardLineEndings";
|
||||
import { createDbxCodeMirrorSqlDialect } from "@/lib/editor/codemirrorSqlDialect";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import { formatSqlForDisplay, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
|
||||
import { applyDdlDatabaseQualifier, ddlFormatDialectFor, omitDdlIdentifierQuotes } from "@/lib/sql/ddlDisplay";
|
||||
import type { SqlFormatDialect } from "@/lib/sql/sqlFormatter";
|
||||
import { ddlFormatDialectFor, formatDdlForDisplay } from "@/lib/sql/ddlDisplay";
|
||||
import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";
|
||||
import { useQueryStore } from "@/stores/queryStore";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { HelpTooltip } from "@/components/ui/tooltip";
|
||||
import EditorSearchPanel from "@/components/editor/EditorSearchPanel.vue";
|
||||
@@ -50,13 +52,16 @@ const { toast } = useToast();
|
||||
const { isDark, themePalette } = useTheme();
|
||||
const settingsStore = useSettingsStore();
|
||||
|
||||
const rawDdlContent = ref("");
|
||||
const ddlContent = computed(() => applyDdlStoragePreference(rawDdlContent.value, props.databaseType, settingsStore.editorSettings.excludeDdlStorage));
|
||||
const originalDdlContent = ref("");
|
||||
const formattedDdlContent = ref("");
|
||||
const ddlDisplayMode = ref<"formatted" | "original">("formatted");
|
||||
const ddlContent = computed(() => applyDdlStoragePreference(ddlDisplayMode.value === "formatted" ? formattedDdlContent.value : originalDdlContent.value, props.databaseType, settingsStore.editorSettings.excludeDdlStorage));
|
||||
const ddlLoading = ref(false);
|
||||
const ddlError = ref("");
|
||||
const ddlEditorContainer = ref<HTMLDivElement>();
|
||||
const ddlSearchPanelRef = ref<InstanceType<typeof EditorSearchPanel>>();
|
||||
const ddlEditorView = shallowRef<EditorView | null>(null);
|
||||
let ddlEditorResizeObserver: ResizeObserver | null = null;
|
||||
|
||||
// Keep the dialog movable for the duration of one open cycle. This mirrors the
|
||||
// existing draggable dialogs without persisting a potentially off-screen position.
|
||||
@@ -65,14 +70,25 @@ const isDragging = ref(false);
|
||||
const dragStartPosition = ref({ x: 0, y: 0 });
|
||||
const dragStartOffset = ref({ x: 0, y: 0 });
|
||||
const activePointerId = ref<number | null>(null);
|
||||
const dialogSize = ref({ width: 980, height: 720 });
|
||||
const isResizing = ref(false);
|
||||
const resizeStartPosition = ref({ x: 0, y: 0 });
|
||||
const resizeStartSize = ref({ width: 980, height: 720 });
|
||||
const resizeStartOffset = ref({ x: 0, y: 0 });
|
||||
const resizeStartRect = ref({ left: 0, top: 0 });
|
||||
const activeResizePointerId = ref<number | null>(null);
|
||||
const dialogContentStyle = computed(() => {
|
||||
if (isDragging.value || dragOffset.value.x !== 0 || dragOffset.value.y !== 0) {
|
||||
return {
|
||||
transform: `translate(${dragOffset.value.x}px, ${dragOffset.value.y}px)`,
|
||||
transition: isDragging.value ? "none" : "transform 0.15s ease-out",
|
||||
};
|
||||
}
|
||||
return {};
|
||||
const moved = isDragging.value || dragOffset.value.x !== 0 || dragOffset.value.y !== 0;
|
||||
return {
|
||||
width: `min(${dialogSize.value.width}px, calc(100vw - 32px))`,
|
||||
height: `min(${dialogSize.value.height}px, calc(100vh - 32px))`,
|
||||
maxWidth: "calc(100vw - 32px)",
|
||||
maxHeight: "calc(100vh - 32px)",
|
||||
minWidth: "min(560px, calc(100vw - 32px))",
|
||||
minHeight: "min(420px, calc(100vh - 32px))",
|
||||
transform: moved ? `translate(${dragOffset.value.x}px, ${dragOffset.value.y}px)` : undefined,
|
||||
transition: isDragging.value || isResizing.value ? "none" : "transform 0.15s ease-out",
|
||||
};
|
||||
});
|
||||
|
||||
// The CodeMirror editor (if any) that was focused when this dialog opened, so focus can be
|
||||
@@ -83,6 +99,9 @@ function resetDialogDragOffset() {
|
||||
dragOffset.value = { x: 0, y: 0 };
|
||||
isDragging.value = false;
|
||||
activePointerId.value = null;
|
||||
dialogSize.value = { width: 980, height: 720 };
|
||||
isResizing.value = false;
|
||||
activeResizePointerId.value = null;
|
||||
}
|
||||
|
||||
function startDialogDrag(event: PointerEvent) {
|
||||
@@ -113,6 +132,46 @@ function endDialogDrag(event: PointerEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
function startDialogResize(event: PointerEvent) {
|
||||
if (event.button !== undefined && event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
isResizing.value = true;
|
||||
activeResizePointerId.value = event.pointerId;
|
||||
resizeStartPosition.value = { x: event.clientX, y: event.clientY };
|
||||
const dialogRect = (event.currentTarget as HTMLElement).closest<HTMLElement>("[data-slot='dialog-content']")?.getBoundingClientRect();
|
||||
resizeStartSize.value = dialogRect ? { width: dialogRect.width, height: dialogRect.height } : { ...dialogSize.value };
|
||||
resizeStartRect.value = dialogRect ? { left: dialogRect.left, top: dialogRect.top } : { left: 0, top: 0 };
|
||||
resizeStartOffset.value = { ...dragOffset.value };
|
||||
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
||||
}
|
||||
|
||||
function moveDialogResize(event: PointerEvent) {
|
||||
if (!isResizing.value || event.pointerId !== activeResizePointerId.value) return;
|
||||
const maxWidth = Math.max(1, Math.min(window.innerWidth - 32, window.innerWidth - 16 - resizeStartRect.value.left));
|
||||
const maxHeight = Math.max(1, Math.min(window.innerHeight - 32, window.innerHeight - 16 - resizeStartRect.value.top));
|
||||
const minWidth = Math.min(560, maxWidth);
|
||||
const minHeight = Math.min(420, maxHeight);
|
||||
const width = Math.min(maxWidth, Math.max(minWidth, resizeStartSize.value.width + event.clientX - resizeStartPosition.value.x));
|
||||
const height = Math.min(maxHeight, Math.max(minHeight, resizeStartSize.value.height + event.clientY - resizeStartPosition.value.y));
|
||||
dialogSize.value = { width, height };
|
||||
dragOffset.value = {
|
||||
x: resizeStartOffset.value.x + (width - resizeStartSize.value.width) / 2,
|
||||
y: resizeStartOffset.value.y + (height - resizeStartSize.value.height) / 2,
|
||||
};
|
||||
}
|
||||
|
||||
function endDialogResize(event: PointerEvent) {
|
||||
if (!isResizing.value || event.pointerId !== activeResizePointerId.value) return;
|
||||
isResizing.value = false;
|
||||
activeResizePointerId.value = null;
|
||||
try {
|
||||
(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId);
|
||||
} catch {
|
||||
// Pointer capture may already have been released by the browser.
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDdl(force = false) {
|
||||
ddlError.value = "";
|
||||
ddlLoading.value = true;
|
||||
@@ -131,9 +190,19 @@ async function loadDdl(force = false) {
|
||||
{ force },
|
||||
);
|
||||
const formatDialect = ddlFormatDialectFor({ formatDialect: props.formatDialect, databaseType: props.databaseType, highlightDialect: props.dialect });
|
||||
const formatted = await formatSqlForDisplay(ddl, formatDialect, settingsStore.editorSettings.sqlFormatter);
|
||||
const unqualified = applyDdlDatabaseQualifier(formatted, formatDialect, props.databaseType, settingsStore.editorSettings.generateSqlIncludeDatabaseName, props.database, props.catalog);
|
||||
rawDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? unqualified : omitDdlIdentifierQuotes(unqualified, formatDialect);
|
||||
originalDdlContent.value = ddl;
|
||||
formattedDdlContent.value = await formatDdlForDisplay(
|
||||
ddl,
|
||||
{
|
||||
dialect: formatDialect,
|
||||
databaseType: props.databaseType,
|
||||
database: props.database,
|
||||
catalog: props.catalog,
|
||||
includeDatabaseName: settingsStore.editorSettings.generateSqlIncludeDatabaseName,
|
||||
quoteIdentifiers: settingsStore.editorSettings.generateSqlQuoteIdentifiers,
|
||||
},
|
||||
settingsStore.editorSettings.sqlFormatter,
|
||||
);
|
||||
} catch (e: any) {
|
||||
ddlError.value = e?.message || String(e);
|
||||
} finally {
|
||||
@@ -149,7 +218,13 @@ watch(
|
||||
if (!open) return;
|
||||
const active = document.activeElement;
|
||||
editorRootToRestoreFocus = active instanceof HTMLElement ? active.closest(".cm-editor") : null;
|
||||
rawDdlContent.value = "";
|
||||
ddlDisplayMode.value = "formatted";
|
||||
originalDdlContent.value = "";
|
||||
formattedDdlContent.value = "";
|
||||
if (settingsStore.editorSettings.ddlOpenMode === "tab") {
|
||||
openDdlViewerTabPending();
|
||||
return;
|
||||
}
|
||||
await loadDdl(settingsStore.editorSettings.refreshDdlOnOpen);
|
||||
},
|
||||
{ immediate: true },
|
||||
@@ -236,11 +311,17 @@ async function initDdlEditor(content: string) {
|
||||
});
|
||||
const editorView = new EditorView({ state, parent: ddlEditorContainer.value });
|
||||
ddlEditorView.value = editorView;
|
||||
if (typeof ResizeObserver !== "undefined") {
|
||||
ddlEditorResizeObserver = new ResizeObserver(() => editorView.requestMeasure());
|
||||
ddlEditorResizeObserver.observe(ddlEditorContainer.value);
|
||||
}
|
||||
editorView.focus();
|
||||
}
|
||||
|
||||
/** Tears down the CodeMirror instance when the dialog closes. */
|
||||
function destroyDdlEditor() {
|
||||
ddlEditorResizeObserver?.disconnect();
|
||||
ddlEditorResizeObserver = null;
|
||||
ddlEditorView.value?.destroy();
|
||||
ddlEditorView.value = null;
|
||||
}
|
||||
@@ -253,15 +334,54 @@ function copyDdlContent() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the read-only DDL tab. With `ddl` empty the tab is created pending
|
||||
* (`ddlLoad`) and loads through the tab surface itself — the same "tab first,
|
||||
* load with visible state" flow as object-source tabs — so in tab mode the
|
||||
* click shows the tab and its loading state immediately instead of silently
|
||||
* waiting behind a closed dialog; a failure is shown in place with a retry.
|
||||
*/
|
||||
function createDdlViewerTab(ddl: string, pending: boolean) {
|
||||
const queryStore = useQueryStore();
|
||||
const tabId = queryStore.createTab(props.connectionId, props.database, `${t("contextMenu.viewDdl")} - ${props.tableName}`, "query", props.schema, ddl, props.catalog, { forceNew: true, sourceView: true });
|
||||
const tab = queryStore.tabs.find((item) => item.id === tabId);
|
||||
if (tab) {
|
||||
tab.ddlViewer = {
|
||||
schema: props.schema || props.database,
|
||||
tableName: props.tableName,
|
||||
objectType: props.objectType,
|
||||
formatDialect: ddlFormatDialectFor({ formatDialect: props.formatDialect, databaseType: props.databaseType, highlightDialect: props.dialect }),
|
||||
};
|
||||
if (pending) {
|
||||
tab.ddlLoad = { startedAt: Date.now() };
|
||||
void queryStore.loadDdlViewerTab(tabId);
|
||||
}
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
|
||||
function openDdlInNewTab() {
|
||||
const ddl = ddlContent.value.trim();
|
||||
if (!ddl) return;
|
||||
|
||||
createDdlViewerTab(ddl, false);
|
||||
}
|
||||
|
||||
function openDdlViewerTabPending() {
|
||||
createDdlViewerTab("", true);
|
||||
}
|
||||
|
||||
watch(ddlContent, (content) => {
|
||||
const view = ddlEditorView.value;
|
||||
if (view) view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: content } });
|
||||
});
|
||||
|
||||
// When DDL finishes loading, create the editor inside the dialog.
|
||||
watch(ddlLoading, (loading) => {
|
||||
if (!loading && ddlContent.value && props.open) {
|
||||
nextTick(() => initDdlEditor(ddlContent.value));
|
||||
watch([ddlLoading, ddlContent], ([loading, content]) => {
|
||||
if (!loading && content && props.open) {
|
||||
nextTick(() => {
|
||||
if (!ddlLoading.value && props.open && ddlContent.value === content) void initDdlEditor(content);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -281,7 +401,9 @@ onUnmounted(() => {
|
||||
});
|
||||
|
||||
function retry() {
|
||||
rawDdlContent.value = "";
|
||||
originalDdlContent.value = "";
|
||||
formattedDdlContent.value = "";
|
||||
ddlDisplayMode.value = "formatted";
|
||||
void loadDdl(true);
|
||||
}
|
||||
|
||||
@@ -290,6 +412,10 @@ function setRefreshDdlOnOpen(value: boolean) {
|
||||
if (value) void loadDdl(true);
|
||||
}
|
||||
|
||||
function setDdlOpenMode(value: unknown) {
|
||||
if (value === "dialog" || value === "tab") settingsStore.updateEditorSettings({ ddlOpenMode: value });
|
||||
}
|
||||
|
||||
function onClose() {
|
||||
emit("update:open", false);
|
||||
}
|
||||
@@ -297,29 +423,40 @@ function onClose() {
|
||||
|
||||
<template>
|
||||
<Dialog :open="props.open" @update:open="onClose">
|
||||
<DialogContent :style="dialogContentStyle" class="dbx-ddl-view-dialog sm:max-w-190" @close-auto-focus="onDdlDialogCloseAutoFocus">
|
||||
<DialogHeader class="cursor-move select-none" @pointerdown="startDialogDrag" @pointermove="moveDialogDrag" @pointerup="endDialogDrag" @pointercancel="endDialogDrag">
|
||||
<DialogContent :style="dialogContentStyle" class="dbx-ddl-view-dialog flex min-h-0 flex-col overflow-hidden sm:max-w-190" @close-auto-focus="onDdlDialogCloseAutoFocus">
|
||||
<DialogHeader class="shrink-0 cursor-move select-none" @pointerdown="startDialogDrag" @pointermove="moveDialogDrag" @pointerup="endDialogDrag" @pointercancel="endDialogDrag">
|
||||
<DialogTitle>DDL - {{ props.tableName }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div class="grid gap-3">
|
||||
<div v-if="ddlLoading" class="flex min-h-80 items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<div class="flex min-h-0 flex-1 flex-col gap-3">
|
||||
<div v-if="!ddlLoading && !ddlError && ddlContent" class="flex shrink-0 items-center justify-between gap-3">
|
||||
<span class="text-sm text-muted-foreground">{{ t("contextMenu.ddlDisplayMode") }}</span>
|
||||
<div class="flex items-center gap-1" role="group" :aria-label="t('contextMenu.ddlDisplayMode')">
|
||||
<Button variant="outline" size="sm" :class="ddlDisplayMode === 'formatted' ? 'border-primary bg-accent' : ''" :aria-pressed="ddlDisplayMode === 'formatted'" @click="ddlDisplayMode = 'formatted'">
|
||||
{{ t("contextMenu.ddlDisplayFormatted") }}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :class="ddlDisplayMode === 'original' ? 'border-primary bg-accent' : ''" :aria-pressed="ddlDisplayMode === 'original'" @click="ddlDisplayMode = 'original'">
|
||||
{{ t("contextMenu.ddlDisplayOriginal") }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="ddlLoading" class="flex min-h-80 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 class="h-4 w-4 animate-spin" />
|
||||
<span>{{ t("contextMenu.viewDdlLoading") }}</span>
|
||||
</div>
|
||||
<div v-else-if="ddlError" class="flex min-h-80 flex-col items-center justify-center gap-3 text-sm">
|
||||
<div v-else-if="ddlError" class="flex min-h-80 flex-1 flex-col items-center justify-center gap-3 text-sm">
|
||||
<p class="text-destructive">{{ ddlError }}</p>
|
||||
<Button variant="outline" size="sm" @click="retry">
|
||||
<RefreshCw />
|
||||
{{ t("common.retry") }}
|
||||
</Button>
|
||||
</div>
|
||||
<div v-else class="ddl-view-editor relative min-h-80 max-h-[60vh] overflow-hidden rounded border">
|
||||
<div v-else class="ddl-view-editor relative min-h-0 flex-1 overflow-hidden rounded border">
|
||||
<div ref="ddlEditorContainer" class="h-full" />
|
||||
<EditorSearchPanel v-if="ddlEditorView" ref="ddlSearchPanelRef" :view="ddlEditorView" />
|
||||
</div>
|
||||
</div>
|
||||
<DdlStorageToggle :database-type="props.databaseType" :disabled="ddlLoading || !!ddlError" />
|
||||
<DialogFooter>
|
||||
<DialogFooter class="shrink-0 pr-7">
|
||||
<div class="mr-auto flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Switch id="ddl-refresh-on-open" size="sm" :model-value="settingsStore.editorSettings.refreshDdlOnOpen" @update:model-value="setRefreshDdlOnOpen" />
|
||||
<div class="flex items-center gap-1">
|
||||
@@ -328,8 +465,22 @@ function onClose() {
|
||||
{{ t("contextMenu.refreshDdlOnOpenHint") }}
|
||||
</HelpTooltip>
|
||||
</div>
|
||||
<span class="ml-3">{{ t("contextMenu.ddlOpenMode") }}</span>
|
||||
<Select :model-value="settingsStore.editorSettings.ddlOpenMode" @update:model-value="setDdlOpenMode">
|
||||
<SelectTrigger class="h-8 w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="dialog">{{ t("contextMenu.ddlOpenModeDialog") }}</SelectItem>
|
||||
<SelectItem value="tab">{{ t("contextMenu.ddlOpenModeTab") }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" @click="onClose">{{ t("common.close") }}</Button>
|
||||
<Button variant="outline" :disabled="ddlLoading || !ddlContent" :title="t('contextMenu.openDdlInNewTab')" @click="openDdlInNewTab">
|
||||
<ExternalLink class="h-4 w-4" />
|
||||
{{ t("contextMenu.openDdlInNewTab") }}
|
||||
</Button>
|
||||
<Button variant="outline" :disabled="ddlLoading" :title="t('structureEditor.refresh')" @click="loadDdl(true)">
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
{{ t("structureEditor.refresh") }}
|
||||
@@ -339,6 +490,17 @@ function onClose() {
|
||||
{{ t("grid.copyDdl") }}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute bottom-1 right-1 z-20 grid size-6 touch-none cursor-nwse-resize place-items-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
:aria-label="t('contextMenu.resizeDdlDialog')"
|
||||
@pointerdown="startDialogResize"
|
||||
@pointermove="moveDialogResize"
|
||||
@pointerup="endDialogResize"
|
||||
@pointercancel="endDialogResize"
|
||||
>
|
||||
<span aria-hidden="true" class="h-3 w-3 border-b-2 border-r-2 border-current" />
|
||||
</button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
@@ -3,8 +3,14 @@
|
||||
import { createApp, defineComponent, h, nextTick, type App } from "vue";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import DdlScopeFixture from "./DdlDialog.legacyScope.fixture.vue";
|
||||
|
||||
const ddlViewDialogSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/objects/DdlViewDialog.vue"), "utf8");
|
||||
const ddlTabContentSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/layout/ContentArea.vue"), "utf8");
|
||||
const editorGroupSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/layout/EditorGroup.vue"), "utf8");
|
||||
|
||||
const mountedApps: App[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
@@ -57,4 +63,35 @@ describe("DdlViewDialog legacy fallback selectors", () => {
|
||||
expect(content!.hasAttribute(scopeId!)).toBe(false);
|
||||
expect(footer!.hasAttribute(scopeId!)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the DDL dialog free of per-dialog legacy fallback rules", () => {
|
||||
// The dialog content element is rendered through reka-ui's portal Teleport and
|
||||
// never carries this component's scoped data-v attribute, so per-dialog rules
|
||||
// are avoided entirely: width comes from the global sm:max-w-190 legacy entry
|
||||
// and the footer layout from the global dialog-footer rule.
|
||||
expect(ddlViewDialogSource).not.toContain("dbx-legacy-webview");
|
||||
expect(ddlViewDialogSource).not.toContain("@media");
|
||||
expect(ddlViewDialogSource).toContain('class="dbx-ddl-view-dialog flex min-h-0 flex-col overflow-hidden sm:max-w-190"');
|
||||
expect(ddlViewDialogSource).toContain("ddlDisplayOriginal");
|
||||
expect(ddlViewDialogSource).toContain("resizeDdlDialog");
|
||||
});
|
||||
|
||||
it("keeps the dialog as the default and offers opening the DDL in a new tab", () => {
|
||||
expect(ddlViewDialogSource).toContain('import { useQueryStore } from "@/stores/queryStore";');
|
||||
expect(ddlViewDialogSource).toContain("queryStore.createTab(props.connectionId, props.database");
|
||||
expect(ddlViewDialogSource).toContain("sourceView: true");
|
||||
expect(ddlViewDialogSource).toContain('ddlOpenMode === "tab"');
|
||||
expect(ddlViewDialogSource).toContain("ddlViewer = {");
|
||||
expect(ddlViewDialogSource).toContain("updateEditorSettings({ ddlOpenMode: value })");
|
||||
expect(ddlViewDialogSource).toContain('@click="openDdlInNewTab"');
|
||||
});
|
||||
|
||||
it("renders DDL tabs read-only with only refresh and table-data actions", () => {
|
||||
expect(editorGroupSource).toContain("!activeTab.value.ddlViewer");
|
||||
expect(ddlTabContentSource).toContain('v-if="activeTab.ddlViewer" class="flex h-10');
|
||||
expect(ddlTabContentSource).toContain('@click="refreshDdlViewer"');
|
||||
expect(ddlTabContentSource).toContain('@click="viewDdlTableData"');
|
||||
expect(ddlTabContentSource).toContain(':read-only="!!activeTab.ddlViewer"');
|
||||
expect(ddlTabContentSource).toContain(':hide-execution-controls="!!activeTab.ddlViewer"');
|
||||
});
|
||||
});
|
||||
@@ -32,11 +32,11 @@ import { useToast } from "@/composables/useToast";
|
||||
import { useVerticalOverlayScrollbar } from "@/composables/useVerticalOverlayScrollbar";
|
||||
import { type SqlHighlighter, createShikiSqlHighlighter } from "@/lib/sql/sqlHighlighter";
|
||||
import { joinSqlStatementsForScript } from "@/lib/sql/sqlBatchScript";
|
||||
import { applyDdlDatabaseQualifier, formatGeneratedDdlIdentifierQuotes, omitDdlIdentifierQuotes } from "@/lib/sql/ddlDisplay";
|
||||
import { applyDdlDatabaseQualifier, formatDdlForDisplay, formatGeneratedDdlIdentifierQuotes } from "@/lib/sql/ddlDisplay";
|
||||
import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import DataGridCopyColumnNamesDialog from "@/components/grid/DataGridCopyColumnNamesDialog.vue";
|
||||
import { formatSqlForDisplay, sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
|
||||
import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
|
||||
import { queryTimeoutSecsForConcurrentIndex, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
|
||||
import { isMacOS } from "@/lib/backend/platform";
|
||||
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
||||
@@ -264,6 +264,27 @@ function ddlEditorDocument(): string {
|
||||
return ddlDraft.value ?? (ddlContent.value || t("structureEditor.emptyReadonly"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats fetched DDL through the shared read-only display pipeline for the
|
||||
* structure editor's DDL tab. The storage preference is not baked in: the
|
||||
* `ddlContent` computed re-filters on read so toggling it updates without a
|
||||
* reload.
|
||||
*/
|
||||
function formatStructureDdl(ddl: string): Promise<string> {
|
||||
return formatDdlForDisplay(
|
||||
ddl,
|
||||
{
|
||||
dialect: sqlFormatDialectForDbType(databaseType.value),
|
||||
databaseType: databaseType.value,
|
||||
database: props.database,
|
||||
catalog: props.catalog,
|
||||
includeDatabaseName: settingsStore.editorSettings.generateSqlIncludeDatabaseName,
|
||||
quoteIdentifiers: settingsStore.editorSettings.generateSqlQuoteIdentifiers,
|
||||
},
|
||||
settingsStore.editorSettings.sqlFormatter,
|
||||
);
|
||||
}
|
||||
|
||||
function resetDdlDraft() {
|
||||
ddlDraft.value = null;
|
||||
updateDdlEditorContent(ddlEditorDocument());
|
||||
@@ -396,14 +417,15 @@ function scheduleDdlEditorInit() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the DDL display preferences (database qualifier + identifier quoting)
|
||||
* to DDL shown by the structure editor, whether loaded from the server or
|
||||
* generated from the pending structure changes.
|
||||
* Applies the SQL generation preferences (database qualifier + identifier
|
||||
* quoting) to a DDL statement generated from the pending structure changes
|
||||
* before it is executed. Oracle folds bare identifiers to uppercase, so safe
|
||||
* quoted names are uppercased before their quotes are removed.
|
||||
*/
|
||||
function formatDdlForDisplay(sql: string, dialect: SqlFormatDialect, generated = false): string {
|
||||
function applyDdlGenerationPreferences(sql: string, dialect: SqlFormatDialect): string {
|
||||
const unqualified = applyDdlDatabaseQualifier(sql, dialect, databaseType.value, settingsStore.editorSettings.generateSqlIncludeDatabaseName, props.database, props.catalog);
|
||||
if (settingsStore.editorSettings.generateSqlQuoteIdentifiers) return unqualified;
|
||||
return generated ? formatGeneratedDdlIdentifierQuotes(unqualified, dialect, false, { preserveCaseSensitiveIdentifiers: tableStoresCaseSensitiveIdentifiers.value }) : omitDdlIdentifierQuotes(unqualified, dialect);
|
||||
return formatGeneratedDdlIdentifierQuotes(unqualified, dialect, false, { preserveCaseSensitiveIdentifiers: tableStoresCaseSensitiveIdentifiers.value });
|
||||
}
|
||||
|
||||
function ddlRequest() {
|
||||
@@ -422,9 +444,7 @@ async function fetchDdl(force = false) {
|
||||
ddlLoading.value = true;
|
||||
try {
|
||||
const { ddl } = await loadObjectDdl(ddlRequest(), { force });
|
||||
const dialect = sqlFormatDialectForDbType(databaseType.value);
|
||||
const formatted = await formatSqlForDisplay(ddl, dialect, settingsStore.editorSettings.sqlFormatter);
|
||||
rawDdlContent.value = formatDdlForDisplay(formatted, dialect);
|
||||
rawDdlContent.value = await formatStructureDdl(ddl);
|
||||
ddlFetched.value = true;
|
||||
} catch (e: any) {
|
||||
rawDdlContent.value = `-- Error: ${e?.message || e}`;
|
||||
@@ -2017,9 +2037,7 @@ async function hydrateRestoredDraftFromDatabase() {
|
||||
if (databaseType.value === "manticoresearch" && tableMetadataCapabilities.value.ddl) {
|
||||
try {
|
||||
const { ddl } = await loadObjectDdl({ connectionId, database, schema, tableName, catalog });
|
||||
const dialect = sqlFormatDialectForDbType(databaseType.value);
|
||||
const formatted = await formatSqlForDisplay(ddl, dialect, settingsStore.editorSettings.sqlFormatter);
|
||||
rawDdlContent.value = formatDdlForDisplay(formatted, dialect);
|
||||
rawDdlContent.value = await formatStructureDdl(ddl);
|
||||
ddlFetched.value = true;
|
||||
nextColumns = applyManticoreDdlColumnExtras(nextColumns, ddl);
|
||||
} catch {
|
||||
@@ -2319,7 +2337,7 @@ async function refreshSqlPreview() {
|
||||
if (requestId !== sqlPreviewRequestId) return;
|
||||
const statements = [...result.statements, ...ownerResult.statements, ...(mysqlAutoIncrementStatement ? [mysqlAutoIncrementStatement] : []), ...partitionResult.statements];
|
||||
// SQLite type-change apply regenerates this revision-checked plan, so its preview must stay byte-for-byte aligned.
|
||||
pendingStatements.value = hasSqliteTypeChange.value ? statements : statements.map((statement) => formatDdlForDisplay(statement, sqlFormatDialectForDbType(databaseType.value), true));
|
||||
pendingStatements.value = hasSqliteTypeChange.value ? statements : statements.map((statement) => applyDdlGenerationPreferences(statement, sqlFormatDialectForDbType(databaseType.value)));
|
||||
warnings.value = [...result.warnings, ...ownerResult.warnings, ...partitionResult.warnings];
|
||||
sqliteSchemaRevision.value = "schemaRevision" in result && typeof result.schemaRevision === "string" ? result.schemaRevision : undefined;
|
||||
} catch (e: any) {
|
||||
@@ -2733,9 +2751,7 @@ async function loadStructure(
|
||||
if (databaseType.value === "manticoresearch" && tableMetadataCapabilities.value.ddl) {
|
||||
try {
|
||||
const { ddl } = await loadObjectDdl({ connectionId, database, schema, tableName, catalog }, { force: options.forceDdl });
|
||||
const dialect = sqlFormatDialectForDbType(databaseType.value);
|
||||
const formatted = await formatSqlForDisplay(ddl, dialect, settingsStore.editorSettings.sqlFormatter);
|
||||
rawDdlContent.value = formatDdlForDisplay(formatted, dialect);
|
||||
rawDdlContent.value = await formatStructureDdl(ddl);
|
||||
ddlFetched.value = true;
|
||||
nextColumns = applyManticoreDdlColumnExtras(nextColumns, ddl);
|
||||
} catch {
|
||||
|
||||
Reference in new issue
Block a user