Skip to content

armgit / dbx

Public Imported from GitHub
0

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

feat: show username/password fields for Access database connections

t8y2edba8214b542
diff --git a/.github/scripts/check-jdbc-plugin-version.mjs b/.github/scripts/check-jdbc-plugin-version.mjs
index 266930d5ee..538b2015b7 100644
--- a/.github/scripts/check-jdbc-plugin-version.mjs
+++ b/.github/scripts/check-jdbc-plugin-version.mjs
@@ -13,10 +13,7 @@ function manifestVersion(manifestJson) {
return JSON.parse(manifestJson).version ?? "";
}
-export function evaluateJdbcPluginVersionChange({
- headPomVersion,
- headManifestVersion,
-}) {
+export function evaluateJdbcPluginVersionChange({ headPomVersion, headManifestVersion }) {
const errors = [];
if (headPomVersion !== headManifestVersion) {
errors.push(`JDBC plugin version mismatch: pom.xml is ${headPomVersion} but manifest.json is ${headManifestVersion}.`);
diff --git a/.github/scripts/sync-changelog.mjs b/.github/scripts/sync-changelog.mjs
index b42bbea43e..8011641729 100644
--- a/.github/scripts/sync-changelog.mjs
+++ b/.github/scripts/sync-changelog.mjs
@@ -1,38 +1,35 @@
#!/usr/bin/env node
-import { createHash } from 'node:crypto';
-import { writeFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const REPO = 't8y2/dbx';
-const GITHUB_TOKEN = process.env.GITHUB_TOKEN || '';
-const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || '';
-const OUT_CN = 'releases-cn.json';
-const OUT_EN = 'releases-en.json';
-const EN_CACHE_URL = process.env.CHANGELOG_EN_CACHE_URL || 'https://dl.dbxio.com/changelog/releases-en.json';
+import { createHash } from "node:crypto";
+import { writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const REPO = "t8y2/dbx";
+const GITHUB_TOKEN = process.env.GITHUB_TOKEN || "";
+const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || "";
+const OUT_CN = "releases-cn.json";
+const OUT_EN = "releases-en.json";
+const EN_CACHE_URL = process.env.CHANGELOG_EN_CACHE_URL || "https://dl.dbxio.com/changelog/releases-en.json";
const SECTION_MAP = {
- '新功能': 'added',
- 'Added': 'added',
- '改进': 'improved',
- 'Improved': 'improved',
- '修复': 'fixed',
- 'Fixed': 'fixed',
- '变更': 'changed',
- 'Changed': 'changed',
- '移除': 'removed',
- 'Removed': 'removed',
+ 新功能: "added",
+ Added: "added",
+ 改进: "improved",
+ Improved: "improved",
+ 修复: "fixed",
+ Fixed: "fixed",
+ 变更: "changed",
+ Changed: "changed",
+ 移除: "removed",
+ Removed: "removed",
};
export async function fetchAllReleases() {
const releases = [];
let page = 1;
while (true) {
- const res = await fetch(
- `https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`,
- { headers: { Authorization: `token ${GITHUB_TOKEN}`, Accept: 'application/vnd.github+json' } },
- );
+ const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`, { headers: { Authorization: `token ${GITHUB_TOKEN}`, Accept: "application/vnd.github+json" } });
if (!res.ok) throw new Error(`GitHub API ${res.status}: ${await res.text()}`);
const data = await res.json();
if (data.length === 0) break;
@@ -43,7 +40,7 @@ export async function fetchAllReleases() {
}
export function stripDownloadSection(body) {
- const markers = ['### 下载安装', '### Download', '### 系统要求', '### System Requirements'];
+ const markers = ["### 下载安装", "### Download", "### 系统要求", "### System Requirements"];
let idx = body.length;
for (const m of markers) {
const i = body.indexOf(m);
@@ -57,11 +54,11 @@ export function parseBody(body) {
const sections = [];
let current = null;
- for (const line of cleaned.split('\n')) {
+ for (const line of cleaned.split("\n")) {
const headerMatch = line.match(/^###\s+(.+)/);
if (headerMatch) {
const title = headerMatch[1].trim();
- const type = SECTION_MAP[title] || 'other';
+ const type = SECTION_MAP[title] || "other";
current = { type, title, items: [] };
sections.push(current);
continue;
@@ -77,7 +74,7 @@ export function parseBody(body) {
const plainMatch = line.match(/^-\s+(.+)/);
if (plainMatch) {
- current.items.push({ title: plainMatch[1].trim(), desc: '' });
+ current.items.push({ title: plainMatch[1].trim(), desc: "" });
}
}
@@ -85,16 +82,16 @@ export function parseBody(body) {
}
export function buildReleaseSourceHash(release) {
- return createHash('sha256')
+ return createHash("sha256")
.update(
JSON.stringify({
tag: release.tag_name,
name: release.name || release.tag_name,
- publishedAt: release.published_at || '',
- body: release.body || '',
+ publishedAt: release.published_at || "",
+ body: release.body || "",
}),
)
- .digest('hex');
+ .digest("hex");
}
export function buildReleasesJson(releases, now = new Date()) {
@@ -108,7 +105,7 @@ export function buildReleasesJson(releases, now = new Date()) {
name: r.name || r.tag_name,
date: r.published_at.slice(0, 10),
_sourceHash: buildReleaseSourceHash(r),
- sections: parseBody(r.body || ''),
+ sections: parseBody(r.body || ""),
})),
};
}
@@ -116,18 +113,15 @@ export function buildReleasesJson(releases, now = new Date()) {
function releaseToMarkdown(release) {
return release.sections
.map((s) => {
- const items = s.items.map((i) => (i.desc ? `- **${i.title}** — ${i.desc}` : `- ${i.title}`)).join('\n');
+ const items = s.items.map((i) => (i.desc ? `- **${i.title}** — ${i.desc}` : `- ${i.title}`)).join("\n");
return `### ${s.title}\n${items}`;
})
- .join('\n\n');
+ .join("\n\n");
}
-export async function fetchCachedEnglish({
- cacheUrl = EN_CACHE_URL,
- fetchImpl = fetch,
-} = {}) {
+export async function fetchCachedEnglish({ cacheUrl = EN_CACHE_URL, fetchImpl = fetch } = {}) {
try {
- const res = await fetchImpl(cacheUrl, { headers: { Accept: 'application/json' } });
+ const res = await fetchImpl(cacheUrl, { headers: { Accept: "application/json" } });
if (!res.ok) {
console.warn(`English changelog cache unavailable: ${res.status}`);
return null;
@@ -139,17 +133,9 @@ export async function fetchCachedEnglish({
}
}
-export async function translateToEnglish(
- cnJson,
- {
- cachedEnJson = null,
- deepseekApiKey = DEEPSEEK_API_KEY,
- fetchImpl = fetch,
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
- } = {},
-) {
+export async function translateToEnglish(cnJson, { cachedEnJson = null, deepseekApiKey = DEEPSEEK_API_KEY, fetchImpl = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
if (!deepseekApiKey) {
- console.warn('DEEPSEEK_API_KEY not set, skipping translation');
+ console.warn("DEEPSEEK_API_KEY not set, skipping translation");
return null;
}
@@ -178,18 +164,18 @@ export async function translateToEnglish(
continue;
}
- const res = await fetchImpl('https://api.deepseek.com/chat/completions', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deepseekApiKey}` },
+ const res = await fetchImpl("https://api.deepseek.com/chat/completions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${deepseekApiKey}` },
body: JSON.stringify({
- model: 'deepseek-chat',
+ model: "deepseek-chat",
messages: [
{
- role: 'system',
+ role: "system",
content:
- 'You are a technical translator. Translate the following Chinese software changelog to English. Keep the exact markdown format (### headers, - bullet points, **bold** titles, — dashes). Only translate, do not add or remove content. Keep technical terms, product names, and contributor names unchanged.',
+ "You are a technical translator. Translate the following Chinese software changelog to English. Keep the exact markdown format (### headers, - bullet points, **bold** titles, — dashes). Only translate, do not add or remove content. Keep technical terms, product names, and contributor names unchanged.",
},
- { role: 'user', content: sectionsText },
+ { role: "user", content: sectionsText },
],
temperature: 0.1,
}),
@@ -202,7 +188,7 @@ export async function translateToEnglish(
}
const data = await res.json();
- const translated = data.choices?.[0]?.message?.content || '';
+ const translated = data.choices?.[0]?.message?.content || "";
const enSections = parseBody(translated);
enReleases.push({ ...release, sections: enSections.length > 0 ? enSections : release.sections });
translatedCount++;
@@ -215,7 +201,7 @@ export async function translateToEnglish(
}
async function main() {
- console.log('Fetching releases from GitHub...');
+ console.log("Fetching releases from GitHub...");
const releases = await fetchAllReleases();
console.log(`Found ${releases.length} releases`);
@@ -225,17 +211,17 @@ async function main() {
writeFileSync(OUT_CN, JSON.stringify(cnJson, null, 2));
console.log(`Wrote ${OUT_CN}`);
- console.log('Fetching cached English changelog...');
+ console.log("Fetching cached English changelog...");
const cachedEnJson = await fetchCachedEnglish();
- console.log('Translating to English...');
+ console.log("Translating to English...");
const enJson = await translateToEnglish(cnJson, { cachedEnJson });
if (enJson) {
writeFileSync(OUT_EN, JSON.stringify(enJson, null, 2));
console.log(`Wrote ${OUT_EN}`);
}
- console.log('Done!');
+ console.log("Done!");
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 969a06083a..74eb283b46 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -66,7 +66,7 @@ jobs:
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
- workspaces: './ -> target'
+ workspaces: "./ -> target"
shared-key: ci-x86_64-unknown-linux-gnu
- name: Cargo fmt check
@@ -89,7 +89,7 @@ jobs:
uses: actions/setup-java@v4
with:
distribution: temurin
- java-version: '17'
+ java-version: "17"
cache: maven
- name: JDBC plugin version guard
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 45dfa9df9b..c23e88cef9 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -3,9 +3,9 @@ name: Deploy Docs
on:
push:
branches: [main]
- paths: ['docs/**']
+ paths: ["docs/**"]
workflow_run:
- workflows: ['Publish Packages']
+ workflows: ["Publish Packages"]
types: [completed]
workflow_dispatch:
diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml
index 3dcb328931..522fc34232 100644
--- a/.github/workflows/publish-packages.yml
+++ b/.github/workflows/publish-packages.yml
@@ -4,7 +4,7 @@ on:
workflow_dispatch:
inputs:
tag:
- description: 'Release tag (e.g. v0.3.10)'
+ description: "Release tag (e.g. v0.3.10)"
required: true
permissions:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index d3c98f87d8..f89ce602f2 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -3,7 +3,7 @@ name: Release
on:
push:
tags:
- - 'v*'
+ - "v*"
permissions:
contents: write
@@ -107,7 +107,7 @@ jobs:
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
- workspaces: './ -> target'
+ workspaces: "./ -> target"
shared-key: release-${{ matrix.target }}-${{ steps.deps-hash.outputs.hash }}
add-rust-environment-hash-key: false
cache-on-failure: true
@@ -173,7 +173,7 @@ jobs:
APPLE_TEAM_ID: ${{ startsWith(matrix.platform, 'macos') && secrets.APPLE_TEAM_ID || '' }}
with:
tagName: ${{ github.ref_name }}
- releaseName: 'DBX ${{ github.ref_name }}'
+ releaseName: "DBX ${{ github.ref_name }}"
releaseBody: ${{ steps.release-notes.outputs.body }}
releaseDraft: true
prerelease: false
@@ -246,7 +246,7 @@ jobs:
uses: actions/setup-java@v4
with:
distribution: temurin
- java-version: '17'
+ java-version: "17"
cache: maven
- name: Apply automatic JDBC plugin version bump
@@ -302,7 +302,6 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh release edit ${{ github.ref_name }} --repo ${{ github.repository }} --draft=false --prerelease
-
docker:
runs-on: ubuntu-latest
strategy:
diff --git a/.github/workflows/sync-changelog.yml b/.github/workflows/sync-changelog.yml
index 833e554f2c..8f7f173340 100644
--- a/.github/workflows/sync-changelog.yml
+++ b/.github/workflows/sync-changelog.yml
@@ -2,7 +2,7 @@ name: Sync Changelog to R2
on:
workflow_run:
- workflows: ['Publish Packages']
+ workflows: ["Publish Packages"]
types: [completed]
workflow_dispatch:
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index 98e1cc0438..660b096c30 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -1,6 +1,6 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
- "printWidth": 120,
+ "printWidth": 300,
"tabWidth": 2,
"singleQuote": false,
"trailingComma": "all",
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 04d03284c1..2018a9a4ac 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -258,13 +258,13 @@ pnpm tauri build
## 技术栈
-| 层级 | 技术 |
-|------|------|
-| 框架 | [Tauri 2](https://tauri.app/) |
-| 前端 | [Vue 3](https://vuejs.org/) + TypeScript |
-| UI | [shadcn-vue](https://www.shadcn-vue.com/) + Tailwind CSS |
-| 编辑器 | [CodeMirror 6](https://codemirror.net/) |
-| 后端 | Rust + [sqlx](https://github.com/launchbadge/sqlx) / [tiberius](https://github.com/prisma/tiberius) / [redis-rs](https://github.com/redis-rs/redis-rs) / [mongodb](https://github.com/mongodb/mongo-rust-driver) |
+| 层级 | 技术 |
+| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 框架 | [Tauri 2](https://tauri.app/) |
+| 前端 | [Vue 3](https://vuejs.org/) + TypeScript |
+| UI | [shadcn-vue](https://www.shadcn-vue.com/) + Tailwind CSS |
+| 编辑器 | [CodeMirror 6](https://codemirror.net/) |
+| 后端 | Rust + [sqlx](https://github.com/launchbadge/sqlx) / [tiberius](https://github.com/prisma/tiberius) / [redis-rs](https://github.com/redis-rs/redis-rs) / [mongodb](https://github.com/mongodb/mongo-rust-driver) |
## 社区
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index b56c3aae60..30540d9db9 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -86,21 +86,7 @@ const settingsStore = useSettingsStore();
const savedSqlStore = useSavedSqlStore();
const { message: toastMessage, visible: toastVisible, toast } = useToast();
const { isDark, themeMode, applyTheme, setThemeMode } = useTheme();
-const {
- checkingUpdates,
- updateInfo,
- updateCheckMessage,
- showUpdateDialog,
- isDownloadingUpdate,
- downloadProgress,
- updateReady,
- hasUpdateAvailable,
- openUrl,
- checkUpdates,
- openLatestRelease,
- downloadAndInstallUpdate,
- restartApp,
-} = useAppUpdater();
+const { checkingUpdates, updateInfo, updateCheckMessage, showUpdateDialog, isDownloadingUpdate, downloadProgress, updateReady, hasUpdateAvailable, openUrl, checkUpdates, openLatestRelease, downloadAndInstallUpdate, restartApp } = useAppUpdater();
const { setupFileDrop } = useFileDrop();
const isDesktop = isTauriRuntime();
@@ -120,16 +106,7 @@ const showAiPanel = ref(safeLocalStorageGet("dbx-ai-panel-open") === "true");
const showSqlLibraryPanel = ref(safeLocalStorageGet("dbx-sql-library-open") === "true");
const sidebarOpen = ref(safeLocalStorageGet("dbx-sidebar-open") !== "false");
const aiPanelReady = ref(false);
-const {
- sidebarWidth,
- aiPanelWidth,
- historyWidth,
- sqlLibraryWidth,
- startSidebarResize,
- startAiPanelResize,
- startHistoryResize,
- startSqlLibraryResize,
-} = usePanelResize();
+const { sidebarWidth, aiPanelWidth, historyWidth, sqlLibraryWidth, startSidebarResize, startAiPanelResize, startHistoryResize, startSqlLibraryResize } = usePanelResize();
const aiAssistantRef = ref<AiAssistantHandle | null>(null);
const appSidebarRef = ref<InstanceType<typeof AppSidebar> | null>(null);
const contentAreaRef = ref<InstanceType<typeof ContentArea> | null>(null);
@@ -206,18 +183,7 @@ async function resolveActiveExecutableSql() {
: "";
}
-const {
- dangerSql,
- pendingDangerSql,
- showDangerDialog,
- suppressDangerConfirm,
- tryExecute,
- doExecute,
- cancelActiveExecution,
- tryExplain,
- onDangerConfirm,
- explainMode,
-} = useSqlExecution({
+const { dangerSql, pendingDangerSql, showDangerDialog, suppressDangerConfirm, tryExecute, doExecute, cancelActiveExecution, tryExplain, onDangerConfirm, explainMode } = useSqlExecution({
activeTab,
activeConnection,
executableSql,
@@ -227,8 +193,7 @@ const {
const dialogs = useDialogSources();
const { getDatabaseOptions } = useDatabaseOptions();
-const { openLineageTarget, openDatabaseSearchTarget, onStructureEditorSaved, openTableTarget } =
- useNavigationTargets(dialogs);
+const { openLineageTarget, openDatabaseSearchTarget, onStructureEditorSaved, openTableTarget } = useNavigationTargets(dialogs);
const { onExecuteSql, onReloadData, onPaginate, onSort } = useDataGridActions(activeTab);
const { setupTauriListeners, cleanupTauriListeners } = useTauriEvents({
openTableTarget,
@@ -241,13 +206,9 @@ useVisibilityChange();
const appVersion = ref("");
const isClassicLayout = computed(() => settingsStore.editorSettings.appLayout === "classic");
const updateNotificationsEnabled = computed(() => settingsStore.editorSettings.updateNotificationsEnabled);
-const toolbarAgentDriverUpdateCount = computed(() =>
- updateNotificationsEnabled.value ? agentDriverUpdateCount.value : 0,
-);
+const toolbarAgentDriverUpdateCount = computed(() => (updateNotificationsEnabled.value ? agentDriverUpdateCount.value : 0));
const toolbarHasUpdateAvailable = computed(() => updateNotificationsEnabled.value && hasUpdateAvailable.value);
-const hasSqlFileConnections = computed(() =>
- connectionStore.connections.some((c) => supportsSqlFileExecution(c.db_type)),
-);
+const hasSqlFileConnections = computed(() => connectionStore.connections.some((c) => supportsSqlFileExecution(c.db_type)));
const connectionStats = computed(() => ({
total: connectionStore.connections.length,
connected: connectionStore.connectedIds.size,
@@ -290,11 +251,7 @@ function isGlobalUiZoomTarget(target: EventTarget | null): target is Element {
if (target.closest("[data-query-editor-root], [data-cell-detail-editor-root], [data-object-source-editor]")) {
return true;
}
- if (
- target instanceof HTMLInputElement ||
- target instanceof HTMLTextAreaElement ||
- (target instanceof HTMLElement && target.isContentEditable)
- ) {
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || (target instanceof HTMLElement && target.isContentEditable)) {
return false;
}
return !target.closest("[contenteditable='true']");
@@ -503,8 +460,7 @@ async function openSqlFilePath(path: string) {
if (!isTauriRuntime()) return;
try {
const content = await api.readExternalSqlFile(path);
- const connectionId =
- connectionStore.activeConnectionId || activeTab.value?.connectionId || connectionStore.connections[0]?.id || "";
+ const connectionId = connectionStore.activeConnectionId || activeTab.value?.connectionId || connectionStore.connections[0]?.id || "";
const connection = connectionId ? connectionStore.getConfig(connectionId) : undefined;
const database = activeTab.value?.database || (connection ? resolveDefaultDatabase(connection, []) : "");
const tabId = queryStore.createTab(connectionId, database, sqlFileTitleFromPath(path), "query");
@@ -828,12 +784,7 @@ function handleKeydown(e: KeyboardEvent) {
void openSaveSqlDialog();
return;
}
- if (
- activeTab.value?.mode === "query" &&
- isExecuteSqlShortcut(e, shortcuts) &&
- e.target instanceof Element &&
- e.target.closest("[data-query-editor-root]")
- ) {
+ if (activeTab.value?.mode === "query" && isExecuteSqlShortcut(e, shortcuts) && e.target instanceof Element && e.target.closest("[data-query-editor-root]")) {
e.preventDefault();
e.stopPropagation();
tryExecute();
@@ -1009,16 +960,10 @@ onUnmounted(() => {
</script>
<template>
- <LoginPage
- v-if="setupRequired || (needsAuth && !authenticated)"
- :setup-mode="setupRequired"
- @authenticated="onLoginSuccess"
- />
+ <LoginPage v-if="setupRequired || (needsAuth && !authenticated)" :setup-mode="setupRequired" @authenticated="onLoginSuccess" />
<div v-show="!setupRequired && (!needsAuth || authenticated)" class="h-screen w-screen overflow-hidden">
<TooltipProvider :delay-duration="300">
- <div
- class="h-screen w-screen max-w-full min-w-[760px] min-h-[600px] flex flex-col bg-background text-foreground overflow-hidden"
- >
+ <div class="h-screen w-screen max-w-full min-w-[760px] min-h-[600px] flex flex-col bg-background text-foreground overflow-hidden">
<AppToolbar
:is-dark="isDark"
:theme-mode="themeMode"
@@ -1047,60 +992,18 @@ onUnmounted(() => {
@open-data-compare="dialogs.showDataCompareDialog.value = true"
/>
- <div
- :class="
- isClassicLayout
- ? 'app-layout-classic flex-1 flex min-h-0'
- : 'app-panel-gutter flex-1 flex min-h-0 gap-1 p-1'
- "
- >
- <AppSidebar
- v-show="sidebarOpen"
- ref="appSidebarRef"
- :sidebar-width="sidebarWidth"
- :classic-layout="isClassicLayout"
- @import="dialogs.onImportClick"
- @export="dialogs.onExportClick"
- @start-resize="startSidebarResize"
- @collapse="setSidebarOpen(false)"
- />
- <div
- v-show="!sidebarOpen"
- class="flex h-full w-8 shrink-0 items-start justify-center border-r bg-background/80 pt-2"
- :class="isClassicLayout ? '' : 'rounded-md border border-border/80'"
- >
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7"
- :title="t('sidebar.expand')"
- :aria-label="t('sidebar.expand')"
- @click="setSidebarOpen(true)"
- >
+ <div :class="isClassicLayout ? 'app-layout-classic flex-1 flex min-h-0' : 'app-panel-gutter flex-1 flex min-h-0 gap-1 p-1'">
+ <AppSidebar v-show="sidebarOpen" ref="appSidebarRef" :sidebar-width="sidebarWidth" :classic-layout="isClassicLayout" @import="dialogs.onImportClick" @export="dialogs.onExportClick" @start-resize="startSidebarResize" @collapse="setSidebarOpen(false)" />
+ <div v-show="!sidebarOpen" class="flex h-full w-8 shrink-0 items-start justify-center border-r bg-background/80 pt-2" :class="isClassicLayout ? '' : 'rounded-md border border-border/80'">
+ <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('sidebar.expand')" :aria-label="t('sidebar.expand')" @click="setSidebarOpen(true)">
<ChevronsRight class="h-4 w-4" />
</Button>
</div>
- <div
- :class="
- isClassicLayout
- ? 'flex-1 min-w-0 overflow-hidden'
- : 'flex-1 min-w-0 overflow-hidden rounded-md border border-border/80 bg-background'
- "
- >
+ <div :class="isClassicLayout ? 'flex-1 min-w-0 overflow-hidden' : 'flex-1 min-w-0 overflow-hidden rounded-md border border-border/80 bg-background'">
<div class="h-full flex flex-col min-w-0">
- <AppTabBar
- :show-driver-store="showDriverStore"
- :agent-driver-update-count="toolbarAgentDriverUpdateCount"
- @toggle-driver-store="showDriverStore = true"
- @close-driver-store="showDriverStore = false"
- />
- <DriverStorePage
- v-if="showDriverStore"
- class="flex-1 min-h-0"
- :update-notifications-enabled="updateNotificationsEnabled"
- @update-count-change="updateAgentDriverUpdateCount"
- />
+ <AppTabBar :show-driver-store="showDriverStore" :agent-driver-update-count="toolbarAgentDriverUpdateCount" @toggle-driver-store="showDriverStore = true" @close-driver-store="showDriverStore = false" />
+ <DriverStorePage v-if="showDriverStore" class="flex-1 min-h-0" :update-notifications-enabled="updateNotificationsEnabled" @update-count-change="updateAgentDriverUpdateCount" />
<div v-else-if="activeTab" class="flex flex-col flex-1 min-h-0">
<EditorToolbar
v-if="activeTab.mode === 'query' && !isPreviewTab(activeTab)"
@@ -1140,26 +1043,11 @@ onUnmounted(() => {
@editor-update="(tabId: string, v: string) => queryStore.updateSql(tabId, v)"
@editor-selection-change="(v: string) => (selectedSql = v)"
@editor-cursor-change="(p: number) => (cursorPos = p)"
- @editor-viewport-change="
- (tabId: string, viewport: { scrollTop: number; scrollLeft: number }) =>
- queryStore.updateEditorViewport(tabId, viewport)
- "
- @editor-selection-state-change="
- (tabId: string, selection: { anchor: number; head: number }) =>
- queryStore.updateEditorSelection(tabId, selection)
- "
+ @editor-viewport-change="(tabId: string, viewport: { scrollTop: number; scrollLeft: number }) => queryStore.updateEditorViewport(tabId, viewport)"
+ @editor-selection-state-change="(tabId: string, selection: { anchor: number; head: number }) => queryStore.updateEditorSelection(tabId, selection)"
@format-error="toast(t('toolbar.formatSqlFailed'))"
@save-sql="void openSaveSqlDialog()"
- @reload="
- (
- sql?: string,
- searchText?: string,
- whereInput?: string,
- orderBy?: string,
- limit?: number,
- offset?: number,
- ) => onReloadData(sql, searchText, whereInput, orderBy, limit, offset)
- "
+ @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => onReloadData(sql, searchText, whereInput, orderBy, limit, offset)"
@paginate="onPaginate"
@sort="onSort"
@execute-sql="onExecuteSql"
@@ -1211,56 +1099,19 @@ onUnmounted(() => {
</div>
</div>
- <div
- v-if="showAiPanel"
- :class="
- isClassicLayout
- ? 'h-full shrink-0 relative z-30 isolate bg-background'
- : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'
- "
- :style="{ width: aiPanelWidth + 'px' }"
- >
+ <div v-if="showAiPanel" :class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'" :style="{ width: aiPanelWidth + 'px' }">
<div class="panel-resize-handle panel-resize-handle--left" @mousedown="startAiPanelResize" />
<div class="h-full min-h-0 overflow-hidden">
- <AiAssistant
- v-if="aiPanelReady"
- ref="aiAssistantRef"
- :tab="activeTab"
- :connection="activeConnection"
- @replace-sql="onAiReplaceSql"
- @execute-sql="onAiExecuteSql"
- @request-auto-execute-sql="onAiRequestAutoExecuteSql"
- @close="toggleAiPanel"
- />
+ <AiAssistant v-if="aiPanelReady" ref="aiAssistantRef" :tab="activeTab" :connection="activeConnection" @replace-sql="onAiReplaceSql" @execute-sql="onAiExecuteSql" @request-auto-execute-sql="onAiRequestAutoExecuteSql" @close="toggleAiPanel" />
</div>
</div>
- <div
- v-if="showHistory"
- :class="
- isClassicLayout
- ? 'h-full shrink-0 relative z-30 isolate bg-background'
- : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'
- "
- :style="{ width: historyWidth + 'px' }"
- >
+ <div v-if="showHistory" :class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'" :style="{ width: historyWidth + 'px' }">
<div class="panel-resize-handle panel-resize-handle--left" @mousedown="startHistoryResize" />
- <QueryHistory
- @restore="restoreHistorySql"
- @analyze-ai="analyzeHistoryWithAi"
- @close="showHistory = false"
- />
+ <QueryHistory @restore="restoreHistorySql" @analyze-ai="analyzeHistoryWithAi" @close="showHistory = false" />
</div>
- <div
- v-if="showSqlLibraryPanel"
- :class="
- isClassicLayout
- ? 'h-full shrink-0 relative z-30 isolate bg-background'
- : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'
- "
- :style="{ width: sqlLibraryWidth + 'px' }"
- >
+ <div v-if="showSqlLibraryPanel" :class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'" :style="{ width: sqlLibraryWidth + 'px' }">
<div class="panel-resize-handle panel-resize-handle--left" @mousedown="startSqlLibraryResize" />
<div class="h-full min-h-0 overflow-hidden">
<SqlLibraryPanel @close="showSqlLibraryPanel = false" />
@@ -1283,9 +1134,7 @@ onUnmounted(() => {
@danger-confirm="onDangerConfirm"
@connect-started="(name: string) => toast(t('connection.connecting', { name }), 30000)"
@connect-succeeded="(name: string) => toast(t('connection.connectSuccess', { name }), 2000)"
- @connect-failed="
- (msg: string) => toast(t('connection.connectFailed', { message: translateBackendError(t, msg) }), 5000)
- "
+ @connect-failed="(msg: string) => toast(t('connection.connectFailed', { message: translateBackendError(t, msg) }), 5000)"
@open-driver-store="
setConnectionDialogOpen(false);
showDriverStore = true;
@@ -1306,10 +1155,7 @@ onUnmounted(() => {
@restart="restartApp"
/>
<Transition name="toast">
- <div
- v-if="toastVisible"
- class="fixed bottom-6 left-1/2 -translate-x-1/2 z-100 px-4 py-2 rounded-lg bg-foreground text-background text-sm shadow-lg"
- >
+ <div v-if="toastVisible" class="fixed bottom-6 left-1/2 -translate-x-1/2 z-100 px-4 py-2 rounded-lg bg-foreground text-background text-sm shadow-lg">
{{ toastMessage }}
</div>
</Transition>
diff --git a/apps/desktop/src/components/admin/DatabaseUserAdmin.vue b/apps/desktop/src/components/admin/DatabaseUserAdmin.vue
index 77889b3d05..e4dc18515d 100644
--- a/apps/desktop/src/components/admin/DatabaseUserAdmin.vue
+++ b/apps/desktop/src/components/admin/DatabaseUserAdmin.vue
@@ -1,20 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import {
- AlertTriangle,
- Check,
- KeyRound,
- Lock,
- Loader2,
- Plus,
- RefreshCcw,
- Search,
- ShieldCheck,
- Trash2,
- Unlock,
- UserRound,
-} from "@lucide/vue";
+import { AlertTriangle, Check, KeyRound, Lock, Loader2, Plus, RefreshCcw, Search, ShieldCheck, Trash2, Unlock, UserRound } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -25,13 +12,7 @@ import { useToast } from "@/composables/useToast";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import type { ConnectionConfig } from "@/types/database";
import * as api from "@/lib/api";
-import {
- grantsFromQueryResult,
- getDatabaseUserAdminProvider,
- supportsDatabaseUserAdmin,
- type DatabaseUserIdentity,
- type PrivilegeScope,
-} from "@/lib/databaseUserAdmin";
+import { grantsFromQueryResult, getDatabaseUserAdminProvider, supportsDatabaseUserAdmin, type DatabaseUserIdentity, type PrivilegeScope } from "@/lib/databaseUserAdmin";
const props = defineProps<{
connection: ConnectionConfig;
@@ -119,29 +100,15 @@ async function loadUsers() {
await ensureConnection();
let nextUsers: DatabaseUserIdentity[] = [];
try {
- const result = await api.executeQuery(
- props.connection.id,
- "",
- userProvider.listUsersSql(),
- undefined,
- undefined,
- {
- maxRows: 5000,
- },
- );
+ const result = await api.executeQuery(props.connection.id, "", userProvider.listUsersSql(), undefined, undefined, {
+ maxRows: 5000,
+ });
nextUsers = userProvider.parseUsers(result);
} catch (error) {
if (!userProvider.fallbackListUsersSql || !userProvider.parseFallbackUsers) throw error;
- const fallback = await api.executeQuery(
- props.connection.id,
- "",
- userProvider.fallbackListUsersSql(),
- undefined,
- undefined,
- {
- maxRows: 5000,
- },
- );
+ const fallback = await api.executeQuery(props.connection.id, "", userProvider.fallbackListUsersSql(), undefined, undefined, {
+ maxRows: 5000,
+ });
nextUsers = userProvider.parseFallbackUsers(fallback);
}
users.value = nextUsers;
@@ -163,16 +130,9 @@ async function loadGrants() {
loadingGrants.value = true;
grantError.value = "";
try {
- const result = await api.executeQuery(
- props.connection.id,
- "",
- userProvider.showGrantsSql(user),
- undefined,
- undefined,
- {
- maxRows: 1000,
- },
- );
+ const result = await api.executeQuery(props.connection.id, "", userProvider.showGrantsSql(user), undefined, undefined, {
+ maxRows: 1000,
+ });
grants.value = grantsFromQueryResult(result);
} catch (error: any) {
grantError.value = error?.message || String(error);
@@ -364,10 +324,7 @@ onMounted(loadUsers);
</div>
</div>
- <div
- v-if="!supported"
- class="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground"
- >
+ <div v-if="!supported" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
{{ t("userAdmin.unsupported") }}
</div>
@@ -376,11 +333,7 @@ onMounted(loadUsers);
<div class="flex h-12 items-center border-b px-2">
<div class="flex h-8 items-center gap-2 rounded-md border bg-background px-2">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <input
- v-model="search"
- class="min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground"
- :placeholder="t('userAdmin.searchUser')"
- />
+ <input v-model="search" class="min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground" :placeholder="t('userAdmin.searchUser')" />
</div>
</div>
<div class="min-h-0 flex-1 overflow-auto">
@@ -400,18 +353,12 @@ onMounted(loadUsers);
<UserRound class="h-4 w-4" />
<span class="min-w-0">
<span class="block truncate font-medium">{{ userLabel(user) || t("userAdmin.anonymous") }}</span>
- <span
- v-if="userDetail(user)"
- class="mt-1 inline-flex max-w-full rounded-full border bg-muted/40 px-1.5 py-0.5 text-[10px] leading-none text-muted-foreground"
- >
+ <span v-if="userDetail(user)" class="mt-1 inline-flex max-w-full rounded-full border bg-muted/40 px-1.5 py-0.5 text-[10px] leading-none text-muted-foreground">
<span class="truncate">{{ userDetail(user) }}</span>
</span>
</span>
</button>
- <div
- v-if="!loadingUsers && !loadError && filteredUsers.length === 0"
- class="px-3 py-8 text-center text-xs text-muted-foreground"
- >
+ <div v-if="!loadingUsers && !loadError && filteredUsers.length === 0" class="px-3 py-8 text-center text-xs text-muted-foreground">
{{ t("grid.noSearchResults") }}
</div>
</div>
@@ -424,11 +371,7 @@ onMounted(loadUsers);
</div>
<div class="flex min-w-0 items-center gap-2">
<div class="truncate text-sm font-semibold">{{ userLabel(selectedUser) }}</div>
- <Badge
- v-if="selectedDetail"
- variant="outline"
- class="h-5 max-w-[180px] rounded-full px-2 py-0 text-[10px] font-normal"
- >
+ <Badge v-if="selectedDetail" variant="outline" class="h-5 max-w-[180px] rounded-full px-2 py-0 text-[10px] font-normal">
<span class="truncate">{{ selectedDetail }}</span>
</Badge>
</div>
@@ -464,11 +407,7 @@ onMounted(loadUsers);
{{ t("userAdmin.loadingGrants") }}
</div>
<div v-else-if="grantError" class="text-xs text-destructive">{{ grantError }}</div>
- <pre
- v-else
- class="min-h-full whitespace-pre-wrap rounded-md bg-muted/30 p-3 font-mono text-xs leading-5 text-foreground"
- v-html="highlightedGrantsSql"
- />
+ <pre v-else class="min-h-full whitespace-pre-wrap rounded-md bg-muted/30 p-3 font-mono text-xs leading-5 text-foreground" v-html="highlightedGrantsSql" />
</div>
</section>
@@ -501,11 +440,7 @@ onMounted(loadUsers);
<label class="mb-2 block text-xs font-medium">
{{ isPostgres && privilegeScope !== "database" ? t("userAdmin.schema") : t("userAdmin.database") }}
</label>
- <Input
- v-model="privilegeDatabase"
- class="mb-3 h-8 text-xs"
- :placeholder="isPostgres ? 'public' : '*'"
- />
+ <Input v-model="privilegeDatabase" class="mb-3 h-8 text-xs" :placeholder="isPostgres ? 'public' : '*'" />
<template v-if="!isPostgres || privilegeScope === 'table'">
<label class="mb-2 block text-xs font-medium">{{ t("userAdmin.table") }}</label>
<Input v-model="privilegeTable" class="mb-3 h-8 text-xs" placeholder="*" />
@@ -519,19 +454,10 @@ onMounted(loadUsers);
:key="privilege"
type="button"
class="flex h-7 items-center gap-1.5 rounded-md border px-2 text-left text-[11px] hover:bg-accent"
- :class="
- selectedPrivilegeSet.has(privilege) ? 'border-primary bg-primary/10 text-primary' : 'bg-background'
- "
+ :class="selectedPrivilegeSet.has(privilege) ? 'border-primary bg-primary/10 text-primary' : 'bg-background'"
@click="togglePrivilege(privilege)"
>
- <span
- class="flex h-3.5 w-3.5 items-center justify-center rounded border"
- :class="
- selectedPrivilegeSet.has(privilege)
- ? 'border-primary bg-primary text-primary-foreground'
- : 'border-border'
- "
- >
+ <span class="flex h-3.5 w-3.5 items-center justify-center rounded border" :class="selectedPrivilegeSet.has(privilege) ? 'border-primary bg-primary text-primary-foreground' : 'border-border'">
<Check v-if="selectedPrivilegeSet.has(privilege)" class="h-2.5 w-2.5" />
</span>
<span class="truncate">{{ privilege }}</span>
@@ -608,10 +534,7 @@ onMounted(loadUsers);
{{ t("userAdmin.sqlPreview") }}
</DialogTitle>
</DialogHeader>
- <pre
- class="max-h-[50vh] min-h-44 overflow-auto whitespace-pre-wrap rounded-md border bg-muted/30 p-3 font-mono text-xs leading-5"
- v-html="highlightedPendingSql"
- />
+ <pre class="max-h-[50vh] min-h-44 overflow-auto whitespace-pre-wrap rounded-md border bg-muted/30 p-3 font-mono text-xs leading-5" v-html="highlightedPendingSql" />
<DialogFooter>
<Button variant="outline" @click="sqlDialogOpen = false">{{ t("dangerDialog.cancel") }}</Button>
<Button :variant="pendingDanger ? 'destructive' : 'default'" :disabled="applying" @click="applyPendingSql">
diff --git a/apps/desktop/src/components/auth/LoginPage.vue b/apps/desktop/src/components/auth/LoginPage.vue
index ef51915ab5..74778c9cb1 100644
--- a/apps/desktop/src/components/auth/LoginPage.vue
+++ b/apps/desktop/src/components/auth/LoginPage.vue
@@ -51,9 +51,7 @@ async function submit() {
</script>
<template>
- <div
- class="flex items-center justify-center h-screen bg-gradient-to-br from-background via-background to-blue-950/20"
- >
+ <div class="flex items-center justify-center h-screen bg-gradient-to-br from-background via-background to-blue-950/20">
<div class="w-[360px] space-y-8">
<div class="flex flex-col items-center gap-4">
<AppLogo class="w-20 h-20 rounded-2xl shadow-lg shadow-blue-500/20" />
@@ -72,31 +70,14 @@ async function submit() {
</div>
<div class="relative">
<Lock class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
- <Input
- v-model="password"
- type="password"
- :placeholder="setupMode ? t('auth.newPassword') : t('auth.enterPassword')"
- class="pl-10 h-11"
- autocomplete="off"
- autofocus
- />
+ <Input v-model="password" type="password" :placeholder="setupMode ? t('auth.newPassword') : t('auth.enterPassword')" class="pl-10 h-11" autocomplete="off" autofocus />
</div>
<div v-if="setupMode" class="relative">
<Lock class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
- <Input
- v-model="confirmPassword"
- type="password"
- :placeholder="t('auth.confirmPassword')"
- class="pl-10 h-11"
- autocomplete="off"
- />
+ <Input v-model="confirmPassword" type="password" :placeholder="t('auth.confirmPassword')" class="pl-10 h-11" autocomplete="off" />
</div>
<p v-if="error" class="text-sm text-destructive text-center">{{ error }}</p>
- <Button
- type="submit"
- class="w-full h-11 text-sm font-medium"
- :disabled="loading || !password || (setupMode && !confirmPassword)"
- >
+ <Button type="submit" class="w-full h-11 text-sm font-medium" :disabled="loading || !password || (setupMode && !confirmPassword)">
<Loader2 v-if="loading" class="w-4 h-4 animate-spin mr-2" />
{{ loading ? t("auth.processing") : setupMode ? t("auth.setPassword") : t("auth.login") }}
</Button>
diff --git a/apps/desktop/src/components/chart/QueryChart.vue b/apps/desktop/src/components/chart/QueryChart.vue
index 5395f80a3d..b7a41e1d40 100644
--- a/apps/desktop/src/components/chart/QueryChart.vue
+++ b/apps/desktop/src/components/chart/QueryChart.vue
@@ -26,9 +26,7 @@ const chartType = ref<ChartType>("bar");
const xColumn = ref("");
const yColumns = ref<string[]>([]);
-const numericColumns = computed(() =>
- props.result.columns.filter((_, idx) => props.result.rows.some((row) => typeof row[idx] === "number")),
-);
+const numericColumns = computed(() => props.result.columns.filter((_, idx) => props.result.rows.some((row) => typeof row[idx] === "number")));
const allColumns = computed(() => props.result.columns);
@@ -118,14 +116,7 @@ const hasData = computed(() => props.result.rows.length > 0 && numericColumns.va
<div class="flex items-center gap-1.5">
<span class="text-muted-foreground">{{ t("chart.type") }}</span>
<div class="flex gap-0.5">
- <Button
- v-for="ct in ['bar', 'line', 'pie'] as ChartType[]"
- :key="ct"
- size="sm"
- :variant="chartType === ct ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs"
- @click="chartType = ct"
- >
+ <Button v-for="ct in ['bar', 'line', 'pie'] as ChartType[]" :key="ct" size="sm" :variant="chartType === ct ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs" @click="chartType = ct">
{{ t(`chart.${ct}`) }}
</Button>
</div>
@@ -146,14 +137,7 @@ const hasData = computed(() => props.result.rows.length > 0 && numericColumns.va
<div class="flex items-center gap-1.5">
<span class="text-muted-foreground">Y</span>
<div class="flex gap-0.5">
- <Button
- v-for="col in numericColumns"
- :key="col"
- size="sm"
- :variant="yColumns.includes(col) ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs"
- @click="toggleYColumn(col)"
- >
+ <Button v-for="col in numericColumns" :key="col" size="sm" :variant="yColumns.includes(col) ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs" @click="toggleYColumn(col)">
{{ col }}
</Button>
</div>
diff --git a/apps/desktop/src/components/config/ConfigPassphraseDialog.vue b/apps/desktop/src/components/config/ConfigPassphraseDialog.vue
index f4804bd4f6..1c8e2570a1 100644
--- a/apps/desktop/src/components/config/ConfigPassphraseDialog.vue
+++ b/apps/desktop/src/components/config/ConfigPassphraseDialog.vue
@@ -76,22 +76,12 @@ const displayError = computed(() => error.value || props.externalError || "");
<div class="grid gap-2">
<Label>{{ t("configExport.passphrase") }}</Label>
- <Input
- v-model="passphrase"
- type="password"
- :placeholder="t('configExport.passphrasePlaceholder')"
- @keydown.enter="mode === 'import' ? confirm() : undefined"
- />
+ <Input v-model="passphrase" type="password" :placeholder="t('configExport.passphrasePlaceholder')" @keydown.enter="mode === 'import' ? confirm() : undefined" />
</div>
<div v-if="mode === 'export'" class="grid gap-2">
<Label>{{ t("configExport.passphraseConfirm") }}</Label>
- <Input
- v-model="passphraseConfirm"
- type="password"
- :placeholder="t('configExport.passphraseConfirmPlaceholder')"
- @keydown.enter="confirm"
- />
+ <Input v-model="passphraseConfirm" type="password" :placeholder="t('configExport.passphraseConfirmPlaceholder')" @keydown.enter="confirm" />
</div>
<p v-if="displayError" class="text-sm text-destructive">{{ displayError }}</p>
diff --git a/apps/desktop/src/components/config/DriverInstallProgressCircle.vue b/apps/desktop/src/components/config/DriverInstallProgressCircle.vue
index be21107667..8eced5e8c4 100644
--- a/apps/desktop/src/components/config/DriverInstallProgressCircle.vue
+++ b/apps/desktop/src/components/config/DriverInstallProgressCircle.vue
@@ -6,27 +6,10 @@ const props = defineProps<{
</script>
<template>
- <span
- class="relative flex h-8 w-8 shrink-0 items-center justify-center rounded-full"
- role="status"
- :aria-label="title"
- :title="title"
- >
+ <span class="relative flex h-8 w-8 shrink-0 items-center justify-center rounded-full" role="status" :aria-label="title" :title="title">
<svg class="absolute inset-0 h-8 w-8 -rotate-90" viewBox="0 0 32 32" aria-hidden="true">
<circle class="text-green-600/20" cx="16" cy="16" r="13" fill="none" stroke="currentColor" stroke-width="3" />
- <circle
- class="text-green-600 transition-[stroke-dashoffset] duration-200"
- cx="16"
- cy="16"
- r="13"
- fill="none"
- stroke="currentColor"
- stroke-width="3"
- stroke-linecap="round"
- pathLength="100"
- stroke-dasharray="100"
- :stroke-dashoffset="100 - (props.percent ?? 0)"
- />
+ <circle class="text-green-600 transition-[stroke-dashoffset] duration-200" cx="16" cy="16" r="13" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" pathLength="100" stroke-dasharray="100" :stroke-dashoffset="100 - (props.percent ?? 0)" />
</svg>
<span class="relative z-10 font-mono text-[10px] font-semibold leading-none text-green-700 tabular-nums">
{{ props.percent ?? "..." }}
diff --git a/apps/desktop/src/components/config/DriverStoreDialog.vue b/apps/desktop/src/components/config/DriverStoreDialog.vue
index 5e7e7e8735..388efaafd4 100644
--- a/apps/desktop/src/components/config/DriverStoreDialog.vue
+++ b/apps/desktop/src/components/config/DriverStoreDialog.vue
@@ -1,23 +1,7 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
-import {
- Activity,
- ExternalLink,
- Cpu,
- FolderOpen,
- MemoryStick,
- Search,
- Square,
- Trash2,
- Download,
- RotateCcw,
- Loader2,
- RefreshCw,
- Check,
- Clock3,
- FileUp,
-} from "@lucide/vue";
+import { Activity, ExternalLink, Cpu, FolderOpen, MemoryStick, Search, Square, Trash2, Download, RotateCcw, Loader2, RefreshCw, Check, Clock3, FileUp } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -30,29 +14,9 @@ import { isTauriRuntime } from "@/lib/tauriRuntime";
import { countAvailableDriverUpdates } from "@/lib/agentDriverUpdateBadge";
import type { JdbcDriverInfo, JdbcPluginStatus } from "@/types/database";
import * as api from "@/lib/api";
-import type {
- AgentDriverInfo,
- DriverRuntimeInfo,
- DriverRuntimeSummary,
- DriverStoreUsage,
- JavaRuntimeConfig,
-} from "@/lib/api";
-import {
- formatRuntimeBytes,
- formatRuntimeCpu,
- formatRuntimeUptime,
- runtimeHealthClass,
- runtimeStatusClass,
- runtimeStatusDotClass,
-} from "@/lib/driverRuntimePresentation";
-import {
- addDriverInstallQueue,
- driverInstallProgressPercent,
- isDriverInstallProgressTarget,
- removeDriverInstallQueue,
- takeNextDriverInstallQueue,
- type DriverInstallProgress,
-} from "@/lib/driverInstallProgressUi";
+import type { AgentDriverInfo, DriverRuntimeInfo, DriverRuntimeSummary, DriverStoreUsage, JavaRuntimeConfig } from "@/lib/api";
+import { formatRuntimeBytes, formatRuntimeCpu, formatRuntimeUptime, runtimeHealthClass, runtimeStatusClass, runtimeStatusDotClass } from "@/lib/driverRuntimePresentation";
+import { addDriverInstallQueue, driverInstallProgressPercent, isDriverInstallProgressTarget, removeDriverInstallQueue, takeNextDriverInstallQueue, type DriverInstallProgress } from "@/lib/driverInstallProgressUi";
const { t } = useI18n();
const { toast } = useToast();
@@ -107,9 +71,7 @@ const installedJres = computed(() => {
jreMap.set(d.jre, d.jre_installed);
}
}
- return [...jreMap.entries()]
- .map(([key, installed]) => ({ key, installed }))
- .sort((a, b) => b.key.localeCompare(a.key));
+ return [...jreMap.entries()].map(([key, installed]) => ({ key, installed })).sort((a, b) => b.key.localeCompare(a.key));
});
const progressText = computed(() => {
@@ -121,18 +83,13 @@ const progressText = computed(() => {
const pct = Math.round(((p.downloaded ?? 0) / p.total) * 100);
const dl = formatSize(p.downloaded ?? 0);
const total = formatSize(p.total);
- const prefix =
- upgradingAll.value && upgradingCurrent.value
- ? `[${upgradingIndex.value}/${upgradingTotal.value}] ${upgradingCurrent.value} — `
- : "";
+ const prefix = upgradingAll.value && upgradingCurrent.value ? `[${upgradingIndex.value}/${upgradingTotal.value}] ${upgradingCurrent.value} — ` : "";
return `${prefix}${label} ${dl} / ${total} (${pct}%)`;
});
const progressNumber = computed(() => driverInstallProgressPercent(progress.value));
-const updatableCount = computed(() =>
- props.updateNotificationsEnabled ? drivers.value.filter((d) => d.update_available).length : 0,
-);
+const updatableCount = computed(() => (props.updateNotificationsEnabled ? drivers.value.filter((d) => d.update_available).length : 0));
const usageSummary = computed(() => {
const usage = driverStoreUsage.value;
if (!usage) return [];
@@ -157,12 +114,8 @@ function updateAgentDrivers(nextDrivers: AgentDriverInfo[]) {
emitDriverUpdateCount();
}
-const agentTabUpdateCount = computed(() =>
- props.updateNotificationsEnabled ? drivers.value.filter((d) => d.update_available).length : 0,
-);
-const jdbcTabUpdateCount = computed(() =>
- props.updateNotificationsEnabled && jdbcPluginStatus.value?.update_available ? 1 : 0,
-);
+const agentTabUpdateCount = computed(() => (props.updateNotificationsEnabled ? drivers.value.filter((d) => d.update_available).length : 0));
+const jdbcTabUpdateCount = computed(() => (props.updateNotificationsEnabled && jdbcPluginStatus.value?.update_available ? 1 : 0));
function emitDriverUpdateCount() {
if (!props.updateNotificationsEnabled) {
@@ -321,9 +274,7 @@ async function upgradeAll() {
const result = await api.upgradeAllAgents();
await refreshAgents();
if (result.failed.length > 0) {
- const failedLabels = result.failed
- .map((item) => drivers.value.find((driver) => driver.db_type === item.db_type)?.label ?? item.db_type)
- .join(", ");
+ const failedLabels = result.failed.map((item) => drivers.value.find((driver) => driver.db_type === item.db_type)?.label ?? item.db_type).join(", ");
toast(t("driverStore.upgradeAllPartial", { count: result.upgraded, failed: failedLabels }));
} else {
toast(t("driverStore.upgradeAllSuccess", { count: result.upgraded }));
@@ -493,21 +444,13 @@ const jdbcDriverPathInput = ref("");
const filteredAgentDrivers = computed(() => {
const query = agentDriverSearch.value.trim().toLowerCase();
if (!query) return drivers.value;
- return drivers.value.filter((driver) =>
- [driver.label, driver.db_type, driver.version, driver.installed_version, driver.jre]
- .filter(Boolean)
- .join(" ")
- .toLowerCase()
- .includes(query),
- );
+ return drivers.value.filter((driver) => [driver.label, driver.db_type, driver.version, driver.installed_version, driver.jre].filter(Boolean).join(" ").toLowerCase().includes(query));
});
const filteredJdbcDrivers = computed(() => {
const query = jdbcDriverSearch.value.trim().toLowerCase();
if (!query) return jdbcDrivers.value;
- return jdbcDrivers.value.filter((driver) =>
- [driver.name, driver.path, String(driver.size)].join(" ").toLowerCase().includes(query),
- );
+ return jdbcDrivers.value.filter((driver) => [driver.name, driver.path, String(driver.size)].join(" ").toLowerCase().includes(query));
});
function formatBytes(bytes: number) {
@@ -543,9 +486,7 @@ function runtimeKindLabel(runtime: DriverRuntimeInfo) {
}
function runtimeSourceLabel(runtime: DriverRuntimeInfo) {
- return runtime.source === "connection"
- ? t("driverStore.runtimeSourceConnection")
- : t("driverStore.runtimeSourceDaemon");
+ return runtime.source === "connection" ? t("driverStore.runtimeSourceConnection") : t("driverStore.runtimeSourceDaemon");
}
function runtimeStatusLabel(status: DriverRuntimeInfo["status"]) {
@@ -744,9 +685,7 @@ async function importJdbcDrivers() {
});
if (!selected) return;
- const paths = (Array.isArray(selected) ? selected : [selected]).filter(
- (path): path is string => typeof path === "string",
- );
+ const paths = (Array.isArray(selected) ? selected : [selected]).filter((path): path is string => typeof path === "string");
await importJdbcDriverPaths(paths);
}
@@ -820,19 +759,11 @@ watch(driverStoreTab, (tab) => {
<div class="flex items-center justify-between gap-3">
<div class="text-sm font-medium">{{ t("driverStore.usageTitle") }}</div>
<div class="text-xs text-muted-foreground">
- {{
- usageSummary.length
- ? t("driverStore.usageTotal", { size: formatBytes(usageSummary[0].bytes) })
- : t("driverStore.calculating")
- }}
+ {{ usageSummary.length ? t("driverStore.usageTotal", { size: formatBytes(usageSummary[0].bytes) }) : t("driverStore.calculating") }}
</div>
</div>
<div v-if="usageSummary.length" class="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-5">
- <div
- v-for="item in usageSummary"
- :key="item.key"
- class="rounded-lg border bg-background/50 px-2.5 py-2 text-center"
- >
+ <div v-for="item in usageSummary" :key="item.key" class="rounded-lg border bg-background/50 px-2.5 py-2 text-center">
<div class="text-[11px] text-muted-foreground">{{ item.label }}</div>
<div class="mt-0.5 text-xs font-medium">{{ formatBytes(item.bytes) }}</div>
</div>
@@ -842,12 +773,7 @@ watch(driverStoreTab, (tab) => {
<div class="min-w-0 truncate text-xs text-muted-foreground">
{{ t("driverStore.offlineDownloadHint") }}
</div>
- <Button
- variant="outline"
- size="sm"
- class="h-7 shrink-0 rounded-full text-xs gap-1 whitespace-nowrap"
- @click="openOfflineDriverDownload"
- >
+ <Button variant="outline" size="sm" class="h-7 shrink-0 rounded-full text-xs gap-1 whitespace-nowrap" @click="openOfflineDriverDownload">
<ExternalLink class="h-3.5 w-3.5" />
{{ t("driverStore.offlineDownloadLink") }}
</Button>
@@ -870,23 +796,11 @@ watch(driverStoreTab, (tab) => {
</TabsTrigger>
</TabsList>
<div v-if="driverStoreTab !== 'runtime'" class="flex items-center gap-2">
- <Button
- variant="ghost"
- size="sm"
- class="h-7 rounded-full text-xs gap-1 text-muted-foreground"
- :disabled="importingZip"
- @click="importOfflineZip"
- >
+ <Button variant="ghost" size="sm" class="h-7 rounded-full text-xs gap-1 text-muted-foreground" :disabled="importingZip" @click="importOfflineZip">
<FileUp class="h-3.5 w-3.5" />
{{ importingZip ? t("driverStore.importing") : t("driverStore.importOfflinePackage") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-7 rounded-full text-xs gap-1 text-muted-foreground"
- :disabled="refreshing"
- @click="forceRefresh"
- >
+ <Button variant="ghost" size="sm" class="h-7 rounded-full text-xs gap-1 text-muted-foreground" :disabled="refreshing" @click="forceRefresh">
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': refreshing }" />
{{ t("driverStore.refresh") }}
</Button>
@@ -909,96 +823,40 @@ watch(driverStoreTab, (tab) => {
<SelectItem value="custom">{{ t("driverStore.javaRuntimeCustom") }}</SelectItem>
</SelectContent>
</Select>
- <Input
- v-if="javaRuntimeConfig.mode === 'custom'"
- v-model="customJavaPath"
- class="h-8 min-w-[180px] flex-1 text-xs"
- :placeholder="t('driverStore.customJavaPathPlaceholder')"
- @keydown.enter.prevent="saveJavaRuntimeConfig"
- />
+ <Input v-if="javaRuntimeConfig.mode === 'custom'" v-model="customJavaPath" class="h-8 min-w-[180px] flex-1 text-xs" :placeholder="t('driverStore.customJavaPathPlaceholder')" @keydown.enter.prevent="saveJavaRuntimeConfig" />
<span v-else class="min-w-0 flex-1 truncate text-xs text-muted-foreground">
- {{
- javaRuntimeConfig.mode === "system"
- ? t("driverStore.systemJavaHint")
- : t("driverStore.jreRuntimeAutoDownloadHint")
- }}
+ {{ javaRuntimeConfig.mode === "system" ? t("driverStore.systemJavaHint") : t("driverStore.jreRuntimeAutoDownloadHint") }}
</span>
- <Button
- v-if="javaRuntimeConfig.mode === 'custom'"
- variant="outline"
- class="h-8 shrink-0 rounded-full text-xs"
- @click="chooseCustomJavaPath"
- >
+ <Button v-if="javaRuntimeConfig.mode === 'custom'" variant="outline" class="h-8 shrink-0 rounded-full text-xs" @click="chooseCustomJavaPath">
<FolderOpen class="h-3.5 w-3.5" />
{{ t("driverStore.choose") }}
</Button>
- <Button
- class="h-8 shrink-0 rounded-full text-xs"
- :disabled="savingJavaRuntime || (javaRuntimeConfig.mode === 'custom' && !customJavaPath.trim())"
- @click="saveJavaRuntimeConfig"
- >
+ <Button class="h-8 shrink-0 rounded-full text-xs" :disabled="savingJavaRuntime || (javaRuntimeConfig.mode === 'custom' && !customJavaPath.trim())" @click="saveJavaRuntimeConfig">
{{ savingJavaRuntime ? t("driverStore.saving") : t("settings.save") }}
</Button>
</div>
<div v-if="installedJres.length > 0" class="divide-y rounded-lg border bg-background/50">
- <div
- v-for="jre in installedJres"
- :key="jre.key"
- class="flex items-center justify-between gap-3 px-3 py-2.5"
- >
+ <div v-for="jre in installedJres" :key="jre.key" class="flex items-center justify-between gap-3 px-3 py-2.5">
<div class="min-w-0">
<div class="text-sm font-medium">{{ t("driverStore.jreRuntimeTitle", { jre: jre.key }) }}</div>
</div>
<div class="flex shrink-0 items-center gap-3">
- <span
- v-if="jreUsageLabel(jre.key)"
- class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground"
- >
+ <span v-if="jreUsageLabel(jre.key)" class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">
{{ jreUsageLabel(jre.key) }}
</span>
<Check v-if="jre.installed" class="h-4 w-4 text-green-600" />
<span v-else class="text-xs text-muted-foreground">{{ t("driverStore.notInstalled") }}</span>
- <DriverInstallProgressCircle
- v-if="reinstallingJre === jre.key"
- :percent="progressNumber"
- :title="
- progressTitle(jre.installed ? t('driverStore.reinstalling') : t('driverStore.installing'))
- "
- />
- <Button
- v-else-if="!jre.installed"
- type="button"
- variant="default"
- size="sm"
- class="h-8 rounded-full text-xs"
- :disabled="reinstallingJre !== null || installing !== null"
- @click="reinstallJre(jre.key)"
- >
+ <DriverInstallProgressCircle v-if="reinstallingJre === jre.key" :percent="progressNumber" :title="progressTitle(jre.installed ? t('driverStore.reinstalling') : t('driverStore.installing'))" />
+ <Button v-else-if="!jre.installed" type="button" variant="default" size="sm" class="h-8 rounded-full text-xs" :disabled="reinstallingJre !== null || installing !== null" @click="reinstallJre(jre.key)">
<Download class="h-3.5 w-3.5 mr-1" />
{{ t("driverStore.install") }}
</Button>
- <Button
- v-else-if="jre.installed"
- type="button"
- variant="outline"
- size="sm"
- class="h-8 rounded-full text-xs"
- :disabled="reinstallingJre !== null || installing !== null"
- @click="reinstallJre(jre.key)"
- >
+ <Button v-else-if="jre.installed" type="button" variant="outline" size="sm" class="h-8 rounded-full text-xs" :disabled="reinstallingJre !== null || installing !== null" @click="reinstallJre(jre.key)">
<RotateCcw class="h-3.5 w-3.5 mr-1" />
{{ t("driverStore.reinstall") }}
</Button>
- <Button
- v-if="jre.installed"
- type="button"
- variant="ghost"
- size="sm"
- class="h-8 rounded-full text-xs text-muted-foreground hover:text-destructive"
- :disabled="reinstallingJre !== null || installing !== null"
- @click="uninstallJre(jre.key)"
- >
+ <Button v-if="jre.installed" type="button" variant="ghost" size="sm" class="h-8 rounded-full text-xs text-muted-foreground hover:text-destructive" :disabled="reinstallingJre !== null || installing !== null" @click="uninstallJre(jre.key)">
{{ t("driverStore.uninstall") }}
</Button>
</div>
@@ -1009,11 +867,7 @@ watch(driverStoreTab, (tab) => {
<!-- Driver List -->
<div class="relative">
<Search class="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- v-model="agentDriverSearch"
- class="h-8 pl-8 text-xs"
- :placeholder="t('driverStore.searchDrivers')"
- />
+ <Input v-model="agentDriverSearch" class="h-8 pl-8 text-xs" :placeholder="t('driverStore.searchDrivers')" />
</div>
<div v-if="drivers.length === 0" class="py-12 text-center text-sm text-muted-foreground">
{{ t("common.loading") }}
@@ -1023,29 +877,14 @@ watch(driverStoreTab, (tab) => {
</div>
<div v-else class="rounded-md border divide-y">
<div v-if="updatableCount > 0" class="flex items-center justify-between px-4 py-2 bg-muted/30">
- <span class="text-xs text-muted-foreground">{{
- t("driverStore.driversUpdatable", { count: updatableCount })
- }}</span>
- <Button
- size="sm"
- class="h-7 rounded-full text-xs"
- :disabled="installing !== null || upgradingAll"
- @click="upgradeAll"
- >
+ <span class="text-xs text-muted-foreground">{{ t("driverStore.driversUpdatable", { count: updatableCount }) }}</span>
+ <Button size="sm" class="h-7 rounded-full text-xs" :disabled="installing !== null || upgradingAll" @click="upgradeAll">
<Loader2 v-if="upgradingAll" class="h-3 w-3 animate-spin mr-1" />
<Download v-else class="h-3 w-3 mr-1" />
- {{
- upgradingAll
- ? t("driverStore.upgradingProgress", { current: upgradingIndex, total: upgradingTotal })
- : t("driverStore.upgradeAll")
- }}
+ {{ upgradingAll ? t("driverStore.upgradingProgress", { current: upgradingIndex, total: upgradingTotal }) : t("driverStore.upgradeAll") }}
</Button>
</div>
- <div
- v-for="driver in filteredAgentDrivers"
- :key="driver.db_type"
- class="flex items-center gap-3 px-4 py-2.5 transition hover:bg-muted/30"
- >
+ <div v-for="driver in filteredAgentDrivers" :key="driver.db_type" class="flex items-center gap-3 px-4 py-2.5 transition hover:bg-muted/30">
<span class="flex h-9 w-9 items-center justify-center rounded-lg bg-muted/60 shrink-0">
<DatabaseIcon :db-type="driver.db_type" class="h-5 w-5" />
</span>
@@ -1053,66 +892,28 @@ watch(driverStoreTab, (tab) => {
<div class="text-sm font-medium">{{ driver.label }}</div>
</div>
<div class="flex shrink-0 items-center gap-1.5">
- <span
- v-if="driver.jre"
- class="rounded-full px-2 py-0.5 text-[11px]"
- :class="driver.jre !== '21' ? 'bg-blue-500/10 text-blue-600' : 'bg-muted text-muted-foreground'"
- >JRE {{ driver.jre }}</span
- >
+ <span v-if="driver.jre" class="rounded-full px-2 py-0.5 text-[11px]" :class="driver.jre !== '21' ? 'bg-blue-500/10 text-blue-600' : 'bg-muted text-muted-foreground'">JRE {{ driver.jre }}</span>
<template v-if="driver.installed">
- <span class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground"
- >v{{ driver.installed_version }}</span
- >
- <span
- v-if="driver.update_available"
- class="rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] text-amber-600"
- >→ v{{ driver.version }}</span
- >
+ <span class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">v{{ driver.installed_version }}</span>
+ <span v-if="driver.update_available" class="rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] text-amber-600">→ v{{ driver.version }}</span>
</template>
<template v-else>
- <span
- v-if="driver.version"
- class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground"
- >v{{ driver.version }}</span
- >
+ <span v-if="driver.version" class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">v{{ driver.version }}</span>
</template>
- <span
- v-if="formatSize(driver.size)"
- class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground"
- >{{ formatSize(driver.size) }}</span
- >
+ <span v-if="formatSize(driver.size)" class="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">{{ formatSize(driver.size) }}</span>
</div>
<div class="flex shrink-0 items-center gap-2">
- <Button
- v-if="!driver.installed && isDriverQueued(driver.db_type)"
- size="sm"
- variant="outline"
- class="h-7 rounded-full border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll"
- @click="removeQueuedDriverInstall(driver.db_type)"
- >
+ <Button v-if="!driver.installed && isDriverQueued(driver.db_type)" size="sm" variant="outline" class="h-7 rounded-full border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15" :disabled="upgradingAll" @click="removeQueuedDriverInstall(driver.db_type)">
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle
- v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)"
- :percent="progressNumber"
- :title="progressTitle(t('driverStore.installing'))"
- />
- <Button
- v-else-if="!driver.installed"
- size="sm"
- class="h-7 rounded-full text-xs"
- :disabled="upgradingAll"
- @click="installDriver(driver.db_type)"
- >
+ <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="progressNumber" :title="progressTitle(t('driverStore.installing'))" />
+ <Button v-else-if="!driver.installed" size="sm" class="h-7 rounded-full text-xs" :disabled="upgradingAll" @click="installDriver(driver.db_type)">
<Download class="h-3 w-3 mr-1" />
{{ t("driverStore.install") }}
</Button>
<Button
- v-if="
- !driver.installed && !isDriverProgressActive(driver.db_type) && !isDriverQueued(driver.db_type)
- "
+ v-if="!driver.installed && !isDriverProgressActive(driver.db_type) && !isDriverQueued(driver.db_type)"
size="sm"
variant="ghost"
class="h-7 w-7 rounded-full text-xs text-muted-foreground"
@@ -1123,10 +924,7 @@ watch(driverStoreTab, (tab) => {
<FileUp class="h-3.5 w-3.5" />
</Button>
<template v-else>
- <Check
- v-if="!(driver.update_available && isDriverProgressActive(driver.db_type))"
- class="h-4 w-4 text-green-600"
- />
+ <Check v-if="!(driver.update_available && isDriverProgressActive(driver.db_type))" class="h-4 w-4 text-green-600" />
<Button
v-if="driver.update_available && isDriverQueued(driver.db_type)"
size="sm"
@@ -1138,28 +936,11 @@ watch(driverStoreTab, (tab) => {
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle
- v-else-if="driver.update_available && isDriverProgressActive(driver.db_type)"
- :percent="progressNumber"
- :title="progressTitle(t('driverStore.updating'))"
- />
- <Button
- v-else-if="driver.update_available"
- size="sm"
- variant="outline"
- class="h-7 rounded-full text-xs"
- :disabled="upgradingAll"
- @click="installDriver(driver.db_type)"
- >
+ <DriverInstallProgressCircle v-else-if="driver.update_available && isDriverProgressActive(driver.db_type)" :percent="progressNumber" :title="progressTitle(t('driverStore.updating'))" />
+ <Button v-else-if="driver.update_available" size="sm" variant="outline" class="h-7 rounded-full text-xs" :disabled="upgradingAll" @click="installDriver(driver.db_type)">
{{ t("driverStore.update") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-7 rounded-full text-xs text-muted-foreground hover:text-destructive"
- :disabled="installing !== null || upgradingAll || isDriverQueued(driver.db_type)"
- @click="uninstallDriver(driver.db_type)"
- >
+ <Button variant="ghost" size="sm" class="h-7 rounded-full text-xs text-muted-foreground hover:text-destructive" :disabled="installing !== null || upgradingAll || isDriverQueued(driver.db_type)" @click="uninstallDriver(driver.db_type)">
{{ t("driverStore.uninstall") }}
</Button>
</template>
@@ -1180,11 +961,7 @@ watch(driverStoreTab, (tab) => {
</p>
</div>
<div class="flex shrink-0 items-center gap-3">
- <span
- v-if="jdbcPluginStatus?.installed"
- class="text-xs"
- :class="jdbcPluginStatus.compatible ? 'text-green-600' : 'text-destructive'"
- >
+ <span v-if="jdbcPluginStatus?.installed" class="text-xs" :class="jdbcPluginStatus.compatible ? 'text-green-600' : 'text-destructive'">
{{
jdbcPluginStatus.compatible
? t("settings.jdbcPluginInstalled", {
@@ -1193,49 +970,17 @@ watch(driverStoreTab, (tab) => {
: t("settings.jdbcPluginIncompatible")
}}
</span>
- <span
- v-if="jdbcPluginStatus?.installed && jdbcPluginStatus.update_available"
- class="rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] text-amber-600"
- >→ v{{ jdbcPluginStatus.latest_version }}</span
- >
- <Button
- v-if="jdbcPluginStatus?.installed && jdbcPluginStatus.update_available"
- type="button"
- variant="outline"
- class="rounded-full"
- :disabled="isInstallingJdbcPlugin"
- @click="installJdbcPlugin"
- >
+ <span v-if="jdbcPluginStatus?.installed && jdbcPluginStatus.update_available" class="rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] text-amber-600">→ v{{ jdbcPluginStatus.latest_version }}</span>
+ <Button v-if="jdbcPluginStatus?.installed && jdbcPluginStatus.update_available" type="button" variant="outline" class="rounded-full" :disabled="isInstallingJdbcPlugin" @click="installJdbcPlugin">
{{ isInstallingJdbcPlugin ? t("common.loading") : t("settings.jdbcPluginUpdate") }}
</Button>
- <Button
- v-if="jdbcPluginStatus?.installed"
- type="button"
- variant="outline"
- class="rounded-full"
- :disabled="isUninstallingJdbcPlugin"
- @click="uninstallJdbcPlugin"
- >
+ <Button v-if="jdbcPluginStatus?.installed" type="button" variant="outline" class="rounded-full" :disabled="isUninstallingJdbcPlugin" @click="uninstallJdbcPlugin">
{{ isUninstallingJdbcPlugin ? t("common.loading") : t("settings.jdbcPluginUninstall") }}
</Button>
- <Button
- v-else
- type="button"
- variant="default"
- class="rounded-full"
- :disabled="isInstallingJdbcPlugin"
- @click="installJdbcPlugin"
- >
+ <Button v-else type="button" variant="default" class="rounded-full" :disabled="isInstallingJdbcPlugin" @click="installJdbcPlugin">
{{ isInstallingJdbcPlugin ? t("common.loading") : t("settings.jdbcPluginInstall") }}
</Button>
- <Button
- v-if="!jdbcPluginStatus?.installed"
- type="button"
- variant="outline"
- class="rounded-full"
- :disabled="isInstallingJdbcPlugin"
- @click="installJdbcPluginLocal"
- >
+ <Button v-if="!jdbcPluginStatus?.installed" type="button" variant="outline" class="rounded-full" :disabled="isInstallingJdbcPlugin" @click="installJdbcPluginLocal">
<FolderOpen class="h-3.5 w-3.5 mr-1" />
{{ t("driverStore.localInstall") }}
</Button>
@@ -1250,25 +995,11 @@ watch(driverStoreTab, (tab) => {
</div>
<div class="relative">
<Search class="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- v-model="jdbcDriverSearch"
- class="h-8 pl-8 text-xs"
- :placeholder="t('driverStore.searchJdbcDrivers')"
- />
+ <Input v-model="jdbcDriverSearch" class="h-8 pl-8 text-xs" :placeholder="t('driverStore.searchJdbcDrivers')" />
</div>
<div class="flex items-center gap-2">
- <Input
- v-model="jdbcDriverPathInput"
- class="flex-1"
- :placeholder="t('settings.jdbcDriverPathPlaceholder')"
- @keydown.enter.prevent="importJdbcDriverPathInput"
- />
- <Button
- variant="outline"
- class="rounded-full"
- :disabled="!jdbcDriverPathInput.trim()"
- @click="importJdbcDriverPathInput"
- >
+ <Input v-model="jdbcDriverPathInput" class="flex-1" :placeholder="t('settings.jdbcDriverPathPlaceholder')" @keydown.enter.prevent="importJdbcDriverPathInput" />
+ <Button variant="outline" class="rounded-full" :disabled="!jdbcDriverPathInput.trim()" @click="importJdbcDriverPathInput">
{{ t("settings.jdbcImportPath") }}
</Button>
<Button class="shrink-0 rounded-full" @click="importJdbcDrivers">
@@ -1295,12 +1026,7 @@ watch(driverStoreTab, (tab) => {
<div class="truncate text-xs text-muted-foreground">{{ driver.path }}</div>
</div>
<div class="shrink-0 text-xs text-muted-foreground">{{ formatBytes(driver.size) }}</div>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8 shrink-0 rounded-full"
- @click="deleteJdbcDriver(driver.path)"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 rounded-full" @click="deleteJdbcDriver(driver.path)">
<Trash2 class="h-4 w-4" />
</Button>
</div>
@@ -1326,14 +1052,7 @@ watch(driverStoreTab, (tab) => {
</div>
</div>
</div>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8 shrink-0 rounded-full text-muted-foreground"
- :title="t('driverStore.refresh')"
- :disabled="runtimeLoading"
- @click="refreshDriverRuntime"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 rounded-full text-muted-foreground" :title="t('driverStore.refresh')" :disabled="runtimeLoading" @click="refreshDriverRuntime">
<RefreshCw class="h-4 w-4" :class="{ 'animate-spin': runtimeLoading }" />
</Button>
</div>
@@ -1342,9 +1061,7 @@ watch(driverStoreTab, (tab) => {
<div class="text-xs font-medium text-amber-700 dark:text-amber-300">
{{ t("driverStore.runtimeLastError") }}
</div>
- <pre class="mt-1 max-h-20 overflow-auto whitespace-pre-wrap text-[11px] text-muted-foreground">{{
- runtimeSummary.last_error
- }}</pre>
+ <pre class="mt-1 max-h-20 overflow-auto whitespace-pre-wrap text-[11px] text-muted-foreground">{{ runtimeSummary.last_error }}</pre>
</div>
<div v-if="runtimeLoading && !runtimeSummary" class="p-6 text-center text-sm text-muted-foreground">
@@ -1357,9 +1074,7 @@ watch(driverStoreTab, (tab) => {
{{ t("driverStore.runtimeEmpty") }}
</div>
<div v-else>
- <div
- class="hidden grid-cols-[minmax(0,1.6fr)_72px_56px_76px_58px_76px_72px] gap-2 border-b bg-muted/30 px-4 py-2 text-[11px] font-medium text-muted-foreground lg:grid"
- >
+ <div class="hidden grid-cols-[minmax(0,1.6fr)_72px_56px_76px_58px_76px_72px] gap-2 border-b bg-muted/30 px-4 py-2 text-[11px] font-medium text-muted-foreground lg:grid">
<div>{{ t("driverStore.runtimeDrivers") }}</div>
<div>{{ t("driverStore.runtimeHealth") }}</div>
<div>{{ t("driverStore.runtimePid") }}</div>
@@ -1369,21 +1084,12 @@ watch(driverStoreTab, (tab) => {
<div class="text-right">{{ t("driverStore.runtimeActions") }}</div>
</div>
<div class="divide-y">
- <div
- v-for="runtime in runtimeSummary.runtimes"
- :key="runtime.id"
- class="grid gap-2 px-4 py-3 transition hover:bg-muted/25 lg:grid-cols-[minmax(0,1.6fr)_72px_56px_76px_58px_76px_72px] lg:items-center"
- >
+ <div v-for="runtime in runtimeSummary.runtimes" :key="runtime.id" class="grid gap-2 px-4 py-3 transition hover:bg-muted/25 lg:grid-cols-[minmax(0,1.6fr)_72px_56px_76px_58px_76px_72px] lg:items-center">
<div class="min-w-0">
<div class="flex min-w-0 items-center gap-2">
<span class="h-2 w-2 shrink-0 rounded-full" :class="runtimeStatusDotClass(runtime.status)" />
<span class="truncate text-sm font-medium">{{ runtime.label }}</span>
- <span
- v-if="runtime.version"
- class="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground"
- >
- v{{ runtime.version }}
- </span>
+ <span v-if="runtime.version" class="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground"> v{{ runtime.version }} </span>
</div>
<div class="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
<span>{{ runtimeKindLabel(runtime) }}</span>
@@ -1393,9 +1099,7 @@ watch(driverStoreTab, (tab) => {
</div>
<div class="flex items-center gap-2 lg:block">
- <span class="lg:hidden text-[11px] text-muted-foreground">{{
- t("driverStore.runtimeHealth")
- }}</span>
+ <span class="lg:hidden text-[11px] text-muted-foreground">{{ t("driverStore.runtimeHealth") }}</span>
<span class="rounded-full px-2 py-0.5 text-[11px]" :class="runtimeStatusClass(runtime.status)">
{{ runtimeStatusLabel(runtime.status) }}
</span>
@@ -1416,41 +1120,19 @@ watch(driverStoreTab, (tab) => {
{{ formatRuntimeUptime(runtime.uptime_seconds) }}
</div>
<div class="flex min-w-0 items-center gap-1.5 lg:justify-end">
- <Button
- v-if="runtime.can_stop"
- variant="ghost"
- size="icon"
- class="h-7 w-7 rounded-full text-muted-foreground hover:text-destructive"
- :title="t('driverStore.runtimeStop')"
- :disabled="runtimeBusy === runtime.id"
- @click="stopRuntime(runtime)"
- >
+ <Button v-if="runtime.can_stop" variant="ghost" size="icon" class="h-7 w-7 rounded-full text-muted-foreground hover:text-destructive" :title="t('driverStore.runtimeStop')" :disabled="runtimeBusy === runtime.id" @click="stopRuntime(runtime)">
<Square class="h-3.5 w-3.5" />
</Button>
- <Button
- v-if="runtime.can_restart"
- variant="ghost"
- size="icon"
- class="h-7 w-7 rounded-full text-muted-foreground"
- :title="t('driverStore.runtimeRestart')"
- :disabled="runtimeBusy === runtime.id"
- @click="restartRuntime(runtime)"
- >
+ <Button v-if="runtime.can_restart" variant="ghost" size="icon" class="h-7 w-7 rounded-full text-muted-foreground" :title="t('driverStore.runtimeRestart')" :disabled="runtimeBusy === runtime.id" @click="restartRuntime(runtime)">
<RotateCcw class="h-3.5 w-3.5" :class="{ 'animate-spin': runtimeBusy === runtime.id }" />
</Button>
- <span
- v-if="!runtime.can_stop && !runtime.can_restart"
- class="min-w-0 truncate text-[11px] text-muted-foreground lg:text-right"
- :title="runtimeControlUnavailableReasonLabel(runtime.control_unavailable_reason)"
- >
+ <span v-if="!runtime.can_stop && !runtime.can_restart" class="min-w-0 truncate text-[11px] text-muted-foreground lg:text-right" :title="runtimeControlUnavailableReasonLabel(runtime.control_unavailable_reason)">
{{ runtimeControlUnavailableReasonLabel(runtime.control_unavailable_reason) }}
</span>
</div>
<div v-if="runtime.last_error" class="rounded-md bg-muted/60 p-2 lg:col-span-7">
- <pre class="max-h-16 overflow-auto whitespace-pre-wrap text-[11px] text-muted-foreground">{{
- runtime.last_error
- }}</pre>
+ <pre class="max-h-16 overflow-auto whitespace-pre-wrap text-[11px] text-muted-foreground">{{ runtime.last_error }}</pre>
</div>
</div>
</div>
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index ae4d812a20..19b9cad00a 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -10,14 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import type {
- ConnectionConfig,
- DatabaseType,
- JdbcDriverInfo,
- ProxyTunnelConfig,
- SshTunnelConfig,
- TransportLayerConfig,
-} from "@/types/database";
+import type { ConnectionConfig, DatabaseType, JdbcDriverInfo, ProxyTunnelConfig, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
@@ -27,51 +20,13 @@ import { isTauriRuntime } from "@/lib/tauriRuntime";
import { applyParsedConnectionUrl, normalizeMongoConnectionString, parseConnectionUrl } from "@/lib/connectionUrl";
import type { ConnectionDeepLinkDraft } from "@/lib/connectionDeepLink";
import { connectionUrlPlaceholder as getUrlPlaceholder } from "@/lib/connectionPresentation";
-import {
- h2ConnectionModeForConfig,
- h2FileJdbcUrl,
- h2FilePathFromJdbcUrl,
- type H2ConnectionMode,
-} from "@/lib/h2Connection";
+import { h2ConnectionModeForConfig, h2FileJdbcUrl, h2FilePathFromJdbcUrl, type H2ConnectionMode } from "@/lib/h2Connection";
import { mongodbAuthFailureHint, mongoUrlParam, setMongoUrlParam } from "@/lib/mongoConnectionOptions";
import { copyToClipboard } from "@/lib/clipboard";
import { showAgentDriverInstallHint, type AgentDriverInstallState } from "@/lib/agentDriverInstallHint";
-import {
- ArrowLeft,
- ArrowDown,
- ArrowUp,
- CheckSquare,
- ChevronRight,
- Copy,
- ExternalLink,
- FilePlus2,
- FolderOpen,
- GripVertical,
- Grid3X3,
- KeyRound,
- Link2,
- List,
- ListFilter,
- Loader2,
- Pipette,
- Plus,
- Search,
- ShieldCheck,
- Square,
- Trash2,
-} from "@lucide/vue";
-import {
- buildDraftVisibleDatabasesConnectionId,
- connectionCanChooseVisibleDatabases,
- initialVisibleDatabaseSelection,
- visibleDatabaseSelectionIsStale,
-} from "@/lib/connectionVisibleDatabases";
-import {
- canSaveVisibleDatabaseSelection,
- filterDatabaseNamesForConnection,
- isSystemDatabaseName,
- normalizeVisibleDatabaseSelection,
-} from "@/lib/visibleDatabases";
+import { ArrowLeft, ArrowDown, ArrowUp, CheckSquare, ChevronRight, Copy, ExternalLink, FilePlus2, FolderOpen, GripVertical, Grid3X3, KeyRound, Link2, List, ListFilter, Loader2, Pipette, Plus, Search, ShieldCheck, Square, Trash2 } from "@lucide/vue";
+import { buildDraftVisibleDatabasesConnectionId, connectionCanChooseVisibleDatabases, initialVisibleDatabaseSelection, visibleDatabaseSelectionIsStale } from "@/lib/connectionVisibleDatabases";
+import { canSaveVisibleDatabaseSelection, filterDatabaseNamesForConnection, isSystemDatabaseName, normalizeVisibleDatabaseSelection } from "@/lib/visibleDatabases";
type DbOption = { value: string; label: string };
type DbCategory = { key: string; title: string; options: DbOption[] };
@@ -259,14 +214,7 @@ function sshLayersForConfig(config: LegacyConnectionConfig): SshTunnelConfig[] {
if (config.ssh_tunnels?.length) {
return config.ssh_tunnels.map(normalizeSshTunnel);
}
- if (
- config.ssh_enabled ||
- config.ssh_host ||
- config.ssh_user ||
- config.ssh_password ||
- config.ssh_key_path ||
- config.ssh_key_passphrase
- ) {
+ if (config.ssh_enabled || config.ssh_host || config.ssh_user || config.ssh_password || config.ssh_key_path || config.ssh_key_passphrase) {
return [
normalizeSshTunnel({
id: "legacy",
@@ -510,9 +458,7 @@ function applyProfile(val: string, preserveConnectionFields = false) {
selectedType.value = val;
form.value.db_type = profile.type;
form.value.driver_profile = val;
- form.value.driver_label = isCustomCompatibleProfile()
- ? customDriverName.value.trim() || profile.label
- : profile.label;
+ form.value.driver_label = isCustomCompatibleProfile() ? customDriverName.value.trim() || profile.label : profile.label;
if (!preserveConnectionFields) {
form.value.port = profile.port;
@@ -639,9 +585,7 @@ watch(
},
);
-const databaseLabel = computed(() =>
- form.value.db_type === "oracle" ? t("connection.serviceName") : t("connection.database"),
-);
+const databaseLabel = computed(() => (form.value.db_type === "oracle" ? t("connection.serviceName") : t("connection.database")));
const databasePlaceholder = computed(() => {
const fallback = defaultDatabaseForProfile();
@@ -654,12 +598,8 @@ const selectedTransportLayer = computed(() => {
const layers = transportLayers.value;
return layers.find((layer) => layer.id === selectedTransportLayerId.value) || layers[0] || null;
});
-const selectedSshLayer = computed(() =>
- selectedTransportLayer.value?.type === "ssh" ? selectedTransportLayer.value : null,
-);
-const selectedProxyLayer = computed(() =>
- selectedTransportLayer.value?.type === "proxy" ? selectedTransportLayer.value : null,
-);
+const selectedSshLayer = computed(() => (selectedTransportLayer.value?.type === "ssh" ? selectedTransportLayer.value : null));
+const selectedProxyLayer = computed(() => (selectedTransportLayer.value?.type === "proxy" ? selectedTransportLayer.value : null));
const transportPathSegments = computed(() => {
const layers = transportLayers.value.filter((layer) => layer.enabled !== false);
return [
@@ -680,8 +620,7 @@ function defaultDatabaseForProfile() {
if (selectedType.value === "cockroachdb") return "defaultdb";
if (form.value.db_type === "highgo") return "highgo";
if (form.value.db_type === "yashandb") return "yasdb";
- if (form.value.db_type === "postgres" || form.value.db_type === "kingbase" || form.value.db_type === "vastbase")
- return "postgres";
+ if (form.value.db_type === "postgres" || form.value.db_type === "kingbase" || form.value.db_type === "vastbase") return "postgres";
if (form.value.db_type === "sqlserver") return "master";
if (form.value.db_type === "oracle") return "ORCL";
if (form.value.db_type === "h2" && h2ConnectionMode.value === "tcp") return "test";
@@ -700,8 +639,7 @@ function switchH2ConnectionMode(mode: H2ConnectionMode) {
form.value.host = h2FilePathFromJdbcUrl(form.value.connection_string) || "";
form.value.port = 0;
} else {
- form.value.host =
- form.value.host.trim() && !isH2FileJdbcUrlLikePath(form.value.host) ? form.value.host : "127.0.0.1";
+ form.value.host = form.value.host.trim() && !isH2FileJdbcUrlLikePath(form.value.host) ? form.value.host : "127.0.0.1";
form.value.port = form.value.port || 9092;
if (form.value.connection_string && h2FilePathFromJdbcUrl(form.value.connection_string)) {
form.value.connection_string = undefined;
@@ -868,13 +806,7 @@ const hasDbPickerResults = computed(() => filteredDbCategories.value.some((categ
const selectedDbIcon = computed(() => iconTypeMap[selectedType.value] || selectedProfile().icon || selectedType.value);
const isJdbcConnection = computed(() => form.value.db_type === "jdbc");
const isH2FileMode = computed(() => form.value.db_type === "h2" && h2ConnectionMode.value === "file");
-const usesLocalFilePathInput = computed(
- () =>
- form.value.db_type === "sqlite" ||
- form.value.db_type === "duckdb" ||
- form.value.db_type === "access" ||
- isH2FileMode.value,
-);
+const usesLocalFilePathInput = computed(() => form.value.db_type === "sqlite" || form.value.db_type === "duckdb" || form.value.db_type === "access" || isH2FileMode.value);
const connectionUrlPlaceholder = computed(() => getUrlPlaceholder(form.value.db_type));
const filePathPlaceholder = computed(() => {
@@ -890,24 +822,11 @@ const sqliteExtensionPaths = computed({
form.value.url_params = setSqliteExtensionPaths(form.value.url_params, value);
},
});
-const tlsCapableDatabaseTypes = new Set<DatabaseType>([
- "mysql",
- "postgres",
- "redshift",
- "gaussdb",
- "kwdb",
- "opengauss",
- "redis",
- "etcd",
- "clickhouse",
- "elasticsearch",
-]);
+const tlsCapableDatabaseTypes = new Set<DatabaseType>(["mysql", "postgres", "redshift", "gaussdb", "kwdb", "opengauss", "redis", "etcd", "clickhouse", "elasticsearch"]);
const supportsTlsToggle = computed(() => tlsCapableDatabaseTypes.has(form.value.db_type));
const supportsCaCertificatePath = computed(() => form.value.db_type === "clickhouse");
const bareMysqlProfiles = new Set(["doris", "starrocks", "selectdb", "oceanbase"]);
-const supportsMysqlTlsOptions = computed(
- () => form.value.db_type === "mysql" && !bareMysqlProfiles.has(selectedType.value),
-);
+const supportsMysqlTlsOptions = computed(() => form.value.db_type === "mysql" && !bareMysqlProfiles.has(selectedType.value));
const mysqlTlsMode = computed({
get: () => mysqlTlsModeFromParams(form.value.url_params, form.value.ssl),
set: (value: string) => {
@@ -972,12 +891,8 @@ const etcdEndpointsLines = computed({
form.value.etcd_endpoints = normalizeEndpointLines(value);
},
});
-const canUseTransportLayers = computed(
- () => form.value.db_type !== "sqlite" && form.value.db_type !== "access" && !isH2FileMode.value,
-);
-const shouldShowAgentDriverInstallHint = computed(() =>
- showAgentDriverInstallHint(form.value.db_type, agentDrivers.value, form.value.driver_profile),
-);
+const canUseTransportLayers = computed(() => form.value.db_type !== "sqlite" && form.value.db_type !== "access" && !isH2FileMode.value);
+const shouldShowAgentDriverInstallHint = computed(() => showAgentDriverInstallHint(form.value.db_type, agentDrivers.value, form.value.driver_profile));
const canChooseVisibleDatabases = computed(() => connectionCanChooseVisibleDatabases(form.value));
const hasVisibleDatabaseFilter = computed(() => Array.isArray(form.value.visible_databases));
const visibleDatabaseSummary = computed(() => {
@@ -1008,12 +923,7 @@ const testResultMessage = computed(() => {
});
const hasRequiredConnectionTarget = computed(() => {
if (isH2FileMode.value) return !!(form.value.host.trim() || h2FilePathFromJdbcUrl(form.value.connection_string));
- return !!(
- form.value.host ||
- (mongoUseUrl.value && form.value.connection_string) ||
- (form.value.db_type === "jdbc" && form.value.connection_string) ||
- connectionUrlInput.value.trim()
- );
+ return !!(form.value.host || (mongoUseUrl.value && form.value.connection_string) || (form.value.db_type === "jdbc" && form.value.connection_string) || connectionUrlInput.value.trim());
});
const mongoAuthDatabase = computed({
get: () => mongoUrlParam(form.value.url_params, "authSource"),
@@ -1242,10 +1152,7 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
delete legacy.proxy_port;
delete legacy.proxy_username;
delete legacy.proxy_password;
- config.visible_databases =
- Array.isArray(config.visible_databases) && config.visible_databases.length > 0
- ? config.visible_databases
- : undefined;
+ config.visible_databases = Array.isArray(config.visible_databases) && config.visible_databases.length > 0 ? config.visible_databases : undefined;
return config as ConnectionConfig;
}
@@ -1264,10 +1171,7 @@ function getUrlParam(params: string | undefined, key: string): string {
function sqliteExtensionPathsFromParams(params: string | undefined): string {
const parsed = new URLSearchParams((params || "").trim().replace(/^\?/, ""));
- return [
- ...parsed.getAll("sqlite_extension"),
- ...parsed.getAll("sqlite_extensions").flatMap((value) => value.split(/\r?\n/)),
- ]
+ return [...parsed.getAll("sqlite_extension"), ...parsed.getAll("sqlite_extensions").flatMap((value) => value.split(/\r?\n/))]
.map((value) => value.trim())
.filter(Boolean)
.join("\n");
@@ -1495,9 +1399,7 @@ async function openVisibleDatabasesPicker() {
visibleDatabaseNames.value = names;
const initialSelection = initialVisibleDatabaseSelection(names, form.value.visible_databases, draftConfig);
visibleDatabaseSelection.value = new Set(initialSelection);
- visibleDatabaseShowSystem.value = initialSelection.some((database) =>
- isSystemDatabaseName(draftConfig.db_type, database),
- );
+ visibleDatabaseShowSystem.value = initialSelection.some((database) => isSystemDatabaseName(draftConfig.db_type, database));
showVisibleDatabasesDialog.value = true;
} catch (e: any) {
visibleDatabaseNames.value = [];
@@ -1547,10 +1449,7 @@ function showAllVisibleDatabases() {
function saveVisibleDatabaseSelection() {
if (!visibleDatabaseCanSave.value) return;
- form.value.visible_databases = normalizeVisibleDatabaseSelection(
- [...visibleDatabaseSelection.value],
- visibleDatabaseNames.value,
- );
+ form.value.visible_databases = normalizeVisibleDatabaseSelection([...visibleDatabaseSelection.value], visibleDatabaseNames.value);
showVisibleDatabasesDialog.value = false;
}
@@ -1593,22 +1492,7 @@ function resetForm() {
const submittedOneTimePrefillKey = ref<string | null>(null);
function oneTimePrefillKey(draft: ConnectionDeepLinkDraft) {
- return JSON.stringify([
- draft.name,
- draft.dbType,
- draft.driverProfile,
- draft.driverLabel,
- draft.host,
- draft.port,
- draft.username,
- draft.password,
- draft.database,
- draft.urlParams,
- draft.ssl,
- draft.connectionString,
- draft.oracleConnectionType,
- draft.useMongoUrl,
- ]);
+ return JSON.stringify([draft.name, draft.dbType, draft.driverProfile, draft.driverLabel, draft.host, draft.port, draft.username, draft.password, draft.database, draft.urlParams, draft.ssl, draft.connectionString, draft.oracleConnectionType, draft.useMongoUrl]);
}
function submitOneTimePrefill(draft: ConnectionDeepLinkDraft) {
@@ -1704,9 +1588,7 @@ watch(
watch(visibleDatabaseShowSystem, (show) => {
if (show) return;
const connection = connectionConfigSnapshotForVisibleDatabases();
- visibleDatabaseSelection.value = new Set(
- [...visibleDatabaseSelection.value].filter((database) => !isSystemDatabaseName(connection.db_type, database)),
- );
+ visibleDatabaseSelection.value = new Set([...visibleDatabaseSelection.value].filter((database) => !isSystemDatabaseName(connection.db_type, database)));
});
watch(canUseTransportLayers, (value) => {
@@ -1722,10 +1604,7 @@ watch(supportsTlsToggle, (value) => {
});
function ensureSelectedTransportLayer() {
- if (
- !selectedTransportLayerId.value ||
- !transportLayers.value.some((layer) => layer.id === selectedTransportLayerId.value)
- ) {
+ if (!selectedTransportLayerId.value || !transportLayers.value.some((layer) => layer.id === selectedTransportLayerId.value)) {
selectedTransportLayerId.value = transportLayers.value[0]?.id || null;
}
}
@@ -1786,10 +1665,7 @@ function dropTransportLayer(targetId: string) {
function changeSelectedTransportLayerType(type: "ssh" | "proxy") {
const selected = selectedTransportLayer.value;
if (!selected || selected.type === type) return;
- const replacement: TransportLayerConfig =
- type === "proxy"
- ? { type: "proxy", ...defaultProxyTunnel(), id: selected.id, name: selected.name }
- : { type: "ssh", ...defaultSshTunnel(), id: selected.id, name: selected.name };
+ const replacement: TransportLayerConfig = type === "proxy" ? { type: "proxy", ...defaultProxyTunnel(), id: selected.id, name: selected.name } : { type: "ssh", ...defaultSshTunnel(), id: selected.id, name: selected.name };
form.value.transport_layers = transportLayers.value.map((layer) => (layer.id === selected.id ? replacement : layer));
resetTestState();
}
@@ -1922,12 +1798,7 @@ async function browsePostgresTlsFile(target: "root" | "cert" | "key") {
if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog");
const selected = await open({
- title:
- target === "root"
- ? t("connection.postgresRootCertBrowse")
- : target === "cert"
- ? t("connection.postgresClientCertBrowse")
- : t("connection.postgresClientKeyBrowse"),
+ title: target === "root" ? t("connection.postgresRootCertBrowse") : target === "cert" ? t("connection.postgresClientCertBrowse") : t("connection.postgresClientKeyBrowse"),
multiple: false,
filters: [
{ name: "PEM", extensions: ["pem", "crt", "cer", "key"] },
@@ -1950,12 +1821,7 @@ async function browseEtcdTlsFile(target: "ca" | "cert" | "key") {
if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog");
const selected = await open({
- title:
- target === "ca"
- ? t("connection.etcdCaCertBrowse")
- : target === "cert"
- ? t("connection.etcdClientCertBrowse")
- : t("connection.etcdClientKeyBrowse"),
+ title: target === "ca" ? t("connection.etcdCaCertBrowse") : target === "cert" ? t("connection.etcdClientCertBrowse") : t("connection.etcdClientKeyBrowse"),
multiple: false,
filters: [
{ name: "PEM", extensions: ["pem", "crt", "cer", "key"] },
@@ -2007,11 +1873,7 @@ async function browseSqliteExtensionPath() {
{ name: "All Files", extensions: ["*"] },
],
});
- const selectedPaths = Array.isArray(selected)
- ? selected
- : selected && typeof selected === "string"
- ? [selected]
- : [];
+ const selectedPaths = Array.isArray(selected) ? selected : selected && typeof selected === "string" ? [selected] : [];
if (selectedPaths.length) {
const existing = sqliteExtensionPaths.value
.split(/\r?\n/)
@@ -2055,9 +1917,7 @@ async function browseJdbcDriverPaths() {
.split(/\r?\n/)
.map((path) => path.trim())
.filter(Boolean);
- const merged = Array.from(
- new Set([...existing, ...paths.filter((path): path is string => typeof path === "string")]),
- );
+ const merged = Array.from(new Set([...existing, ...paths.filter((path): path is string => typeof path === "string")]));
jdbcDriverPathsInput.value = merged.join("\n");
}
@@ -2122,34 +1982,16 @@ function openExternalUrl(url: string) {
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end">
<div class="flex items-center gap-2">
<div class="flex shrink-0 rounded-lg border bg-muted/40 p-0.5">
- <Button
- type="button"
- size="icon-sm"
- :variant="dbPickerView === 'icon' ? 'secondary' : 'ghost'"
- :title="t('connection.iconView')"
- :aria-label="t('connection.iconView')"
- @click="dbPickerView = 'icon'"
- >
+ <Button type="button" size="icon-sm" :variant="dbPickerView === 'icon' ? 'secondary' : 'ghost'" :title="t('connection.iconView')" :aria-label="t('connection.iconView')" @click="dbPickerView = 'icon'">
<Grid3X3 class="h-3.5 w-3.5" />
</Button>
- <Button
- type="button"
- size="icon-sm"
- :variant="dbPickerView === 'list' ? 'secondary' : 'ghost'"
- :title="t('connection.listView')"
- :aria-label="t('connection.listView')"
- @click="dbPickerView = 'list'"
- >
+ <Button type="button" size="icon-sm" :variant="dbPickerView === 'list' ? 'secondary' : 'ghost'" :title="t('connection.listView')" :aria-label="t('connection.listView')" @click="dbPickerView = 'list'">
<List class="h-3.5 w-3.5" />
</Button>
</div>
<div class="relative w-full sm:w-64">
<Search class="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- v-model="dbSearchQuery"
- class="h-9 pl-8"
- :placeholder="t('connection.searchDatabasePlaceholder')"
- />
+ <Input v-model="dbSearchQuery" class="h-9 pl-8" :placeholder="t('connection.searchDatabasePlaceholder')" />
</div>
</div>
</div>
@@ -2166,18 +2008,12 @@ function openExternalUrl(url: string) {
:key="opt.value"
type="button"
class="group flex min-h-24 flex-col items-center justify-center gap-2 rounded-xl border bg-background/70 p-3 text-center transition hover:-translate-y-0.5 hover:border-primary/40 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- :class="
- selectedType === opt.value
- ? 'border-primary bg-primary/10 shadow-sm ring-1 ring-primary/30'
- : 'border-border'
- "
+ :class="selectedType === opt.value ? 'border-primary bg-primary/10 shadow-sm ring-1 ring-primary/30' : 'border-border'"
:aria-pressed="selectedType === opt.value"
@click="onDbTypeChange(opt.value)"
@dblclick="goToConnectionStep(opt.value)"
>
- <span
- class="flex h-10 w-10 items-center justify-center rounded-xl bg-muted/60 transition group-hover:bg-background"
- >
+ <span class="flex h-10 w-10 items-center justify-center rounded-xl bg-muted/60 transition group-hover:bg-background">
<DatabaseIcon :db-type="iconTypeMap[opt.value]" class="h-6 w-6" />
</span>
<span class="max-w-full truncate text-sm font-medium">{{ opt.label }}</span>
@@ -2190,9 +2026,7 @@ function openExternalUrl(url: string) {
:key="opt.value"
type="button"
class="flex items-center gap-3 rounded-lg border bg-background px-3 py-2 text-left transition hover:border-primary/40 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- :class="
- selectedType === opt.value ? 'border-primary bg-primary/10 ring-1 ring-primary/30' : 'border-border'
- "
+ :class="selectedType === opt.value ? 'border-primary bg-primary/10 ring-1 ring-primary/30' : 'border-border'"
:aria-pressed="selectedType === opt.value"
@click="onDbTypeChange(opt.value)"
@dblclick="goToConnectionStep(opt.value)"
@@ -2204,10 +2038,7 @@ function openExternalUrl(url: string) {
</div>
</section>
- <div
- v-if="!hasDbPickerResults"
- class="rounded-xl border border-dashed py-12 text-center text-sm text-muted-foreground"
- >
+ <div v-if="!hasDbPickerResults" class="rounded-xl border border-dashed py-12 text-center text-sm text-muted-foreground">
{{ t("connection.noDatabaseMatches") }}
</div>
</div>
@@ -2232,9 +2063,7 @@ function openExternalUrl(url: string) {
<TabsList>
<TabsTrigger value="connection">{{ t("connection.basicTab") }}</TabsTrigger>
<TabsTrigger v-if="supportsTlsToggle" value="tls">{{ t("connection.tlsTab") }}</TabsTrigger>
- <TabsTrigger v-if="canUseTransportLayers" value="transport">{{
- t("connection.sshTunnel")
- }}</TabsTrigger>
+ <TabsTrigger v-if="canUseTransportLayers" value="transport">{{ t("connection.sshTunnel") }}</TabsTrigger>
<TabsTrigger value="advanced">{{ t("connection.advancedTab") }}</TabsTrigger>
</TabsList>
</div>
@@ -2244,22 +2073,10 @@ function openExternalUrl(url: string) {
<div v-if="!isJdbcConnection" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.connectionUrlOptional") }}</Label>
<div class="col-span-3 flex items-center gap-1">
- <Input
- v-model="connectionUrlInput"
- class="flex-1"
- :placeholder="connectionUrlPlaceholder"
- @keydown.enter.prevent="applyConnectionUrl"
- />
+ <Input v-model="connectionUrlInput" class="flex-1" :placeholder="connectionUrlPlaceholder" @keydown.enter.prevent="applyConnectionUrl" />
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="!connectionUrlInput.trim()"
- :aria-label="t('connection.parseConnectionUrl')"
- @click="applyConnectionUrl"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="!connectionUrlInput.trim()" :aria-label="t('connection.parseConnectionUrl')" @click="applyConnectionUrl">
<Link2 class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -2275,11 +2092,7 @@ function openExternalUrl(url: string) {
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.type") }}</Label>
- <button
- type="button"
- class="col-span-3 flex items-center gap-2 rounded-md border bg-muted/20 px-3 py-2 hover:bg-muted/40 cursor-pointer transition"
- @click="backToDatabasePicker()"
- >
+ <button type="button" class="col-span-3 flex items-center gap-2 rounded-md border bg-muted/20 px-3 py-2 hover:bg-muted/40 cursor-pointer transition" @click="backToDatabasePicker()">
<DatabaseIcon :db-type="selectedDbIcon" class="h-4 w-4 shrink-0" />
<span class="min-w-0 flex-1 truncate text-sm text-left">{{ selectedProfile().label }}</span>
<Pencil class="h-3 w-3 text-muted-foreground" />
@@ -2290,18 +2103,10 @@ function openExternalUrl(url: string) {
<div v-if="selectedType === 'oceanbase'" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.mode") }}</Label>
<div class="col-span-3 flex gap-2">
- <Button
- size="sm"
- :variant="oceanbaseSubMode === 'mysql' ? 'default' : 'outline'"
- @click="switchOceanbaseMode('mysql')"
- >
+ <Button size="sm" :variant="oceanbaseSubMode === 'mysql' ? 'default' : 'outline'" @click="switchOceanbaseMode('mysql')">
{{ t("connection.oceanbaseMySQLMode") }}
</Button>
- <Button
- size="sm"
- :variant="oceanbaseSubMode === 'oracle' ? 'default' : 'outline'"
- @click="switchOceanbaseMode('oracle')"
- >
+ <Button size="sm" :variant="oceanbaseSubMode === 'oracle' ? 'default' : 'outline'" @click="switchOceanbaseMode('oracle')">
{{ t("connection.oceanbaseOracleMode") }}
</Button>
</div>
@@ -2310,30 +2115,14 @@ function openExternalUrl(url: string) {
<div v-if="selectedType === 'gbase'" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.version") }}</Label>
<div class="col-span-3 flex gap-2">
- <Button
- size="sm"
- :variant="form.driver_profile === 'gbase8s' ? 'outline' : 'default'"
- @click="switchGbaseProfile('gbase')"
- >
- GBase
- </Button>
- <Button
- size="sm"
- :variant="form.driver_profile === 'gbase8s' ? 'default' : 'outline'"
- @click="switchGbaseProfile('gbase8s')"
- >
- GBase 8s
- </Button>
+ <Button size="sm" :variant="form.driver_profile === 'gbase8s' ? 'outline' : 'default'" @click="switchGbaseProfile('gbase')"> GBase </Button>
+ <Button size="sm" :variant="form.driver_profile === 'gbase8s' ? 'default' : 'outline'" @click="switchGbaseProfile('gbase8s')"> GBase 8s </Button>
</div>
</div>
<div v-if="isCustomCompatibleProfile()" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.driverName") }}</Label>
- <Input
- v-model="customDriverName"
- class="col-span-3"
- :placeholder="t('connection.driverNamePlaceholder')"
- />
+ <Input v-model="customDriverName" class="col-span-3" :placeholder="t('connection.driverNamePlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
@@ -2344,10 +2133,7 @@ function openExternalUrl(url: string) {
:key="color.value || 'none'"
type="button"
class="h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105"
- :class="[
- color.class,
- form.color === color.value ? 'ring-2 ring-ring ring-offset-2' : 'border-border',
- ]"
+ :class="[color.class, form.color === color.value ? 'ring-2 ring-ring ring-offset-2' : 'border-border']"
:title="t(color.labelKey)"
@click="handlePresetClick(color.value)"
/>
@@ -2356,35 +2142,17 @@ function openExternalUrl(url: string) {
<button
type="button"
class="h-6 w-6 rounded-full border flex items-center justify-center hover:scale-105 transition"
- :class="[
- !isPresetColor(form.color) && form.color
- ? 'border-border ring-2 ring-ring ring-offset-2'
- : 'border-dashed border-border',
- ]"
+ :class="[!isPresetColor(form.color) && form.color ? 'border-border ring-2 ring-ring ring-offset-2' : 'border-dashed border-border']"
:style="!isPresetColor(form.color) && form.color ? { backgroundColor: form.color } : {}"
:title="t('connection.colorCustom')"
>
- <Pipette
- class="h-3.5 w-3.5"
- :class="!isPresetColor(form.color) && form.color ? 'text-white' : 'text-muted-foreground'"
- />
+ <Pipette class="h-3.5 w-3.5" :class="!isPresetColor(form.color) && form.color ? 'text-white' : 'text-muted-foreground'" />
</button>
</PopoverTrigger>
<PopoverContent class="w-auto p-2">
<div class="flex items-center gap-2">
- <input
- type="color"
- :value="form.color"
- @input="handleCustomColorPicked(($event.target as HTMLInputElement).value)"
- class="h-6 w-6 cursor-pointer rounded border-0 p-0"
- />
- <Input
- type="text"
- :value="customColorInput || form.color"
- @input="handleCustomColorInput(($event.target as HTMLInputElement).value)"
- class="w-28 h-7 text-xs font-mono"
- :placeholder="'#ff0000 或 rgba(…)'"
- />
+ <input type="color" :value="form.color" @input="handleCustomColorPicked(($event.target as HTMLInputElement).value)" class="h-6 w-6 cursor-pointer rounded border-0 p-0" />
+ <Input type="text" :value="customColorInput || form.color" @input="handleCustomColorInput(($event.target as HTMLInputElement).value)" class="w-28 h-7 text-xs font-mono" :placeholder="'#ff0000 或 rgba(…)'" />
</div>
</PopoverContent>
</Popover>
@@ -2394,18 +2162,10 @@ function openExternalUrl(url: string) {
<div v-if="form.db_type === 'h2'" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.mode") }}</Label>
<div class="col-span-3 flex gap-2">
- <Button
- size="sm"
- :variant="h2ConnectionMode === 'file' ? 'default' : 'outline'"
- @click="switchH2ConnectionMode('file')"
- >
+ <Button size="sm" :variant="h2ConnectionMode === 'file' ? 'default' : 'outline'" @click="switchH2ConnectionMode('file')">
{{ t("connection.h2FileMode") }}
</Button>
- <Button
- size="sm"
- :variant="h2ConnectionMode === 'tcp' ? 'default' : 'outline'"
- @click="switchH2ConnectionMode('tcp')"
- >
+ <Button size="sm" :variant="h2ConnectionMode === 'tcp' ? 'default' : 'outline'" @click="switchH2ConnectionMode('tcp')">
{{ t("connection.h2TcpMode") }}
</Button>
</div>
@@ -2415,11 +2175,7 @@ function openExternalUrl(url: string) {
<template v-if="form.db_type === 'jdbc'">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.jdbcUrl") }}</Label>
- <Input
- v-model="form.connection_string"
- class="col-span-3"
- :placeholder="t('connection.jdbcUrlPlaceholder')"
- />
+ <Input v-model="form.connection_string" class="col-span-3" :placeholder="t('connection.jdbcUrlPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.user") }}</Label>
@@ -2431,20 +2187,12 @@ function openExternalUrl(url: string) {
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.jdbcDriverClass") }}</Label>
- <Input
- v-model="form.jdbc_driver_class"
- class="col-span-3"
- :placeholder="t('connection.jdbcDriverClassPlaceholder')"
- />
+ <Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-start gap-4">
<Label class="text-right mt-2">{{ t("connection.jdbcDriverPaths") }}</Label>
<div class="col-span-3 space-y-2">
- <Select
- v-if="jdbcDrivers.length > 0"
- :model-value="selectedJdbcDriverPath"
- @update:model-value="onJdbcDriverSelect"
- >
+ <Select v-if="jdbcDrivers.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
<SelectTrigger>
<SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
</SelectTrigger>
@@ -2462,13 +2210,7 @@ function openExternalUrl(url: string) {
/>
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- type="button"
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- @click="browseJdbcDriverPaths"
- >
+ <Button type="button" variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseJdbcDriverPaths">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -2510,12 +2252,7 @@ function openExternalUrl(url: string) {
</Tooltip>
<Tooltip v-if="isDesktop && form.db_type === 'duckdb'">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- @click="createDuckDbFilePath"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="createDuckDbFilePath">
<FilePlus2 class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -2539,12 +2276,7 @@ function openExternalUrl(url: string) {
/>
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- @click="browseSqliteExtensionPath"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseSqliteExtensionPath">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -2558,15 +2290,11 @@ function openExternalUrl(url: string) {
</div>
<template v-if="form.db_type === 'h2' || form.db_type === 'access'">
<div class="grid grid-cols-4 items-center gap-4">
- <Label class="text-right">{{ t("connection.user") }}</Label>
- <Input
- v-model="form.username"
- class="col-span-3"
- :placeholder="form.db_type === 'access' ? '' : 'sa'"
- />
+ <Label class="text-right">{{ t("connection.user") }}{{ form.db_type === "access" ? "(可选)" : "" }}</Label>
+ <Input v-model="form.username" class="col-span-3" :placeholder="form.db_type === 'access' ? '' : 'sa'" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label class="text-right">{{ t("connection.password") }}</Label>
+ <Label class="text-right">{{ t("connection.password") }}{{ form.db_type === "access" ? "(可选)" : "" }}</Label>
<Input v-model="form.password" type="password" class="col-span-3" />
</div>
</template>
@@ -2577,37 +2305,19 @@ function openExternalUrl(url: string) {
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.mode") }}</Label>
<div class="col-span-3 flex gap-2">
- <Button
- size="sm"
- :variant="form.redis_connection_mode === 'standalone' ? 'default' : 'outline'"
- @click="form.redis_connection_mode = 'standalone'"
- >
+ <Button size="sm" :variant="form.redis_connection_mode === 'standalone' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'standalone'">
{{ t("connection.redisStandaloneMode") }}
</Button>
- <Button
- size="sm"
- :variant="form.redis_connection_mode === 'sentinel' ? 'default' : 'outline'"
- @click="form.redis_connection_mode = 'sentinel'"
- >
+ <Button size="sm" :variant="form.redis_connection_mode === 'sentinel' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'sentinel'">
{{ t("connection.redisSentinelMode") }}
</Button>
- <Button
- size="sm"
- :variant="form.redis_connection_mode === 'cluster' ? 'default' : 'outline'"
- @click="form.redis_connection_mode = 'cluster'"
- >
+ <Button size="sm" :variant="form.redis_connection_mode === 'cluster' ? 'default' : 'outline'" @click="form.redis_connection_mode = 'cluster'">
{{ t("connection.redisClusterMode") }}
</Button>
</div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
- <Label class="text-right">{{
- form.redis_connection_mode === "sentinel"
- ? t("connection.redisFirstSentinel")
- : form.redis_connection_mode === "cluster"
- ? t("connection.redisFirstClusterNode")
- : t("connection.host")
- }}</Label>
+ <Label class="text-right">{{ form.redis_connection_mode === "sentinel" ? t("connection.redisFirstSentinel") : form.redis_connection_mode === "cluster" ? t("connection.redisFirstClusterNode") : t("connection.host") }}</Label>
<Input v-model="form.host" class="col-span-2" />
<Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
@@ -2658,12 +2368,7 @@ function openExternalUrl(url: string) {
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.password") }}</Label>
- <Input
- v-model="form.password"
- type="password"
- class="col-span-3"
- :placeholder="t('connection.databasePlaceholder')"
- />
+ <Input v-model="form.password" type="password" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
</div>
</template>
@@ -2703,12 +2408,8 @@ function openExternalUrl(url: string) {
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.mode") }}</Label>
<div class="col-span-3 flex gap-2">
- <Button size="sm" :variant="mongoUseUrl ? 'outline' : 'default'" @click="mongoUseUrl = false">{{
- t("connection.modeForm")
- }}</Button>
- <Button size="sm" :variant="mongoUseUrl ? 'default' : 'outline'" @click="mongoUseUrl = true"
- >URL</Button
- >
+ <Button size="sm" :variant="mongoUseUrl ? 'outline' : 'default'" @click="mongoUseUrl = false">{{ t("connection.modeForm") }}</Button>
+ <Button size="sm" :variant="mongoUseUrl ? 'default' : 'outline'" @click="mongoUseUrl = true">URL</Button>
</div>
</div>
<template v-if="mongoUseUrl">
@@ -2744,19 +2445,11 @@ function openExternalUrl(url: string) {
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.defaultDatabase") }}</Label>
- <Input
- v-model="form.database"
- class="col-span-3"
- :placeholder="t('connection.databasePlaceholder')"
- />
+ <Input v-model="form.database" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.authDatabase") }}</Label>
- <Input
- v-model="mongoAuthDatabase"
- class="col-span-3"
- :placeholder="t('connection.authDatabasePlaceholder')"
- />
+ <Input v-model="mongoAuthDatabase" class="col-span-3" :placeholder="t('connection.authDatabasePlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.authMechanism") }}</Label>
@@ -2773,11 +2466,7 @@ function openExternalUrl(url: string) {
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right">{{ t("connection.urlParams") }}</Label>
- <Input
- v-model="form.url_params"
- class="col-span-3"
- placeholder="authSource=admin&authMechanism=SCRAM-SHA-1"
- />
+ <Input v-model="form.url_params" class="col-span-3" placeholder="authSource=admin&authMechanism=SCRAM-SHA-1" />
</div>
<div class="grid grid-cols-4 items-start gap-4">
<span />
@@ -2813,17 +2502,11 @@ function openExternalUrl(url: string) {
<div v-if="form.db_type === 'oracle'" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.mode") }}</Label>
- <div
- class="col-span-3 grid h-8 grid-cols-2 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5"
- >
+ <div class="col-span-3 grid h-8 grid-cols-2 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
<button
type="button"
class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="
- form.oracle_connection_type !== 'sid'
- ? 'bg-background text-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground'
- "
+ :class="form.oracle_connection_type !== 'sid' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
:aria-pressed="form.oracle_connection_type !== 'sid'"
@click="form.oracle_connection_type = 'service_name'"
>
@@ -2832,11 +2515,7 @@ function openExternalUrl(url: string) {
<button
type="button"
class="h-7 rounded-sm px-3 text-sm transition-colors"
- :class="
- form.oracle_connection_type === 'sid'
- ? 'bg-background text-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground'
- "
+ :class="form.oracle_connection_type === 'sid' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
:aria-pressed="form.oracle_connection_type === 'sid'"
@click="form.oracle_connection_type = 'sid'"
>
@@ -2848,23 +2527,14 @@ function openExternalUrl(url: string) {
<div v-if="shouldShowAgentDriverInstallHint" class="grid grid-cols-4 items-center gap-4">
<span />
<p class="col-span-3 text-xs text-muted-foreground">
- {{ t("connection.driverInstallHintPrefix")
- }}<a
- class="underline cursor-pointer text-primary hover:text-primary/80"
- @click="emit('openDriverStore')"
- >{{ t("toolbar.driverManager") }}</a
+ {{ t("connection.driverInstallHintPrefix") }}<a class="underline cursor-pointer text-primary hover:text-primary/80" @click="emit('openDriverStore')">{{ t("toolbar.driverManager") }}</a
>{{ t("connection.driverInstallHintSuffix") }}
</p>
</div>
<div v-if="form.db_type === 'oracle'" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.version") }}</Label>
- <Select
- :model-value="
- selectedType === 'oracle-legacy' || selectedType === 'oracle-10g' ? selectedType : 'oracle'
- "
- @update:model-value="(val) => applyProfile(String(val), true)"
- >
+ <Select :model-value="selectedType === 'oracle-legacy' || selectedType === 'oracle-10g' ? selectedType : 'oracle'" @update:model-value="(val) => applyProfile(String(val), true)">
<SelectTrigger class="col-span-3 h-8 text-sm">
<SelectValue />
</SelectTrigger>
@@ -2910,10 +2580,7 @@ function openExternalUrl(url: string) {
<TabsContent v-if="supportsTlsToggle" value="tls" class="m-0">
<div class="grid gap-4 py-4 pr-2 max-h-[65vh] overflow-y-auto">
- <div
- v-if="!supportsPostgresTlsOptions && !supportsMysqlTlsOptions"
- class="grid grid-cols-4 items-center gap-4"
- >
+ <div v-if="!supportsPostgresTlsOptions && !supportsMysqlTlsOptions" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">SSL/TLS</Label>
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="form.ssl" class="mr-0" />
@@ -2941,19 +2608,10 @@ function openExternalUrl(url: string) {
</Label>
<div class="col-span-3 space-y-2">
<div class="flex items-center gap-1">
- <Input
- v-model="form.ca_cert_path"
- class="flex-1"
- :placeholder="t('connection.etcdCaCertPlaceholder')"
- />
+ <Input v-model="form.ca_cert_path" class="flex-1" :placeholder="t('connection.etcdCaCertPlaceholder')" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- @click="browseEtcdTlsFile('ca')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseEtcdTlsFile('ca')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -2972,19 +2630,10 @@ function openExternalUrl(url: string) {
</Label>
<div class="col-span-3 grid gap-2">
<div class="flex items-center gap-1">
- <Input
- v-model="form.client_cert_path"
- class="flex-1"
- :placeholder="t('connection.etcdClientCertPlaceholder')"
- />
+ <Input v-model="form.client_cert_path" class="flex-1" :placeholder="t('connection.etcdClientCertPlaceholder')" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- @click="browseEtcdTlsFile('cert')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseEtcdTlsFile('cert')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -2992,19 +2641,10 @@ function openExternalUrl(url: string) {
</Tooltip>
</div>
<div class="flex items-center gap-1">
- <Input
- v-model="form.client_key_path"
- class="flex-1"
- :placeholder="t('connection.etcdClientKeyPlaceholder')"
- />
+ <Input v-model="form.client_key_path" class="flex-1" :placeholder="t('connection.etcdClientKeyPlaceholder')" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- @click="browseEtcdTlsFile('key')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="browseEtcdTlsFile('key')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3030,9 +2670,7 @@ function openExternalUrl(url: string) {
<SelectItem value="disabled">{{ t("connection.mysqlTlsModeDisabled") }}</SelectItem>
<SelectItem value="required">{{ t("connection.mysqlTlsModeRequired") }}</SelectItem>
<SelectItem value="verify_ca">{{ t("connection.mysqlTlsModeVerifyCa") }}</SelectItem>
- <SelectItem value="verify_identity">{{
- t("connection.mysqlTlsModeVerifyIdentity")
- }}</SelectItem>
+ <SelectItem value="verify_identity">{{ t("connection.mysqlTlsModeVerifyIdentity") }}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -3046,21 +2684,10 @@ function openExternalUrl(url: string) {
</Label>
<div class="col-span-3 space-y-2">
<div class="flex items-center gap-1">
- <Input
- v-model="form.ca_cert_path"
- class="flex-1"
- :placeholder="t('connection.caCertPathPlaceholder')"
- :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'"
- />
+ <Input v-model="form.ca_cert_path" class="flex-1" :placeholder="t('connection.caCertPathPlaceholder')" :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'"
- @click="browseCaCertPath"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'" @click="browseCaCertPath">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3082,21 +2709,10 @@ function openExternalUrl(url: string) {
</Label>
<div class="col-span-3 grid gap-2">
<div class="flex items-center gap-1">
- <Input
- v-model="mysqlClientCertPath"
- class="flex-1"
- :placeholder="t('connection.mysqlClientCertPlaceholder')"
- :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'"
- />
+ <Input v-model="mysqlClientCertPath" class="flex-1" :placeholder="t('connection.mysqlClientCertPlaceholder')" :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'"
- @click="browseMysqlTlsFile('cert')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'" @click="browseMysqlTlsFile('cert')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3104,21 +2720,10 @@ function openExternalUrl(url: string) {
</Tooltip>
</div>
<div class="flex items-center gap-1">
- <Input
- v-model="mysqlClientKeyPath"
- class="flex-1"
- :placeholder="t('connection.mysqlClientKeyPlaceholder')"
- :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'"
- />
+ <Input v-model="mysqlClientKeyPath" class="flex-1" :placeholder="t('connection.mysqlClientKeyPlaceholder')" :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'"
- @click="browseMysqlTlsFile('key')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="mysqlTlsMode === 'preferred' || mysqlTlsMode === 'disabled'" @click="browseMysqlTlsFile('key')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3158,21 +2763,10 @@ function openExternalUrl(url: string) {
</Label>
<div class="col-span-3 space-y-2">
<div class="flex items-center gap-1">
- <Input
- v-model="postgresRootCertPath"
- class="flex-1"
- :placeholder="t('connection.postgresRootCertPlaceholder')"
- :disabled="postgresTlsMode === 'disable'"
- />
+ <Input v-model="postgresRootCertPath" class="flex-1" :placeholder="t('connection.postgresRootCertPlaceholder')" :disabled="postgresTlsMode === 'disable'" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="postgresTlsMode === 'disable'"
- @click="browsePostgresTlsFile('root')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="postgresTlsMode === 'disable'" @click="browsePostgresTlsFile('root')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3194,21 +2788,10 @@ function openExternalUrl(url: string) {
</Label>
<div class="col-span-3 grid gap-2">
<div class="flex items-center gap-1">
- <Input
- v-model="postgresClientCertPath"
- class="flex-1"
- :placeholder="t('connection.postgresClientCertPlaceholder')"
- :disabled="postgresTlsMode === 'disable'"
- />
+ <Input v-model="postgresClientCertPath" class="flex-1" :placeholder="t('connection.postgresClientCertPlaceholder')" :disabled="postgresTlsMode === 'disable'" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="postgresTlsMode === 'disable'"
- @click="browsePostgresTlsFile('cert')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="postgresTlsMode === 'disable'" @click="browsePostgresTlsFile('cert')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3216,21 +2799,10 @@ function openExternalUrl(url: string) {
</Tooltip>
</div>
<div class="flex items-center gap-1">
- <Input
- v-model="postgresClientKeyPath"
- class="flex-1"
- :placeholder="t('connection.postgresClientKeyPlaceholder')"
- :disabled="postgresTlsMode === 'disable'"
- />
+ <Input v-model="postgresClientKeyPath" class="flex-1" :placeholder="t('connection.postgresClientKeyPlaceholder')" :disabled="postgresTlsMode === 'disable'" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="postgresTlsMode === 'disable'"
- @click="browsePostgresTlsFile('key')"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="postgresTlsMode === 'disable'" @click="browsePostgresTlsFile('key')">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3247,21 +2819,10 @@ function openExternalUrl(url: string) {
<div v-if="supportsCaCertificatePath" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.caCertPath") }}</Label>
<div class="col-span-3 flex items-center gap-1">
- <Input
- v-model="form.ca_cert_path"
- class="flex-1"
- :placeholder="t('connection.caCertPathPlaceholder')"
- :disabled="!form.ssl"
- />
+ <Input v-model="form.ca_cert_path" class="flex-1" :placeholder="t('connection.caCertPathPlaceholder')" :disabled="!form.ssl" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="!form.ssl"
- @click="browseCaCertPath"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="!form.ssl" @click="browseCaCertPath">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3276,36 +2837,15 @@ function openExternalUrl(url: string) {
<div class="grid gap-4 py-4 pr-2 max-h-[65vh] overflow-y-auto">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.connectTimeout") }}</Label>
- <Input
- v-model.number="form.connect_timeout_secs"
- type="number"
- min="1"
- max="300"
- step="1"
- class="col-span-3"
- />
+ <Input v-model.number="form.connect_timeout_secs" type="number" min="1" max="300" step="1" class="col-span-3" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.queryTimeout") }}</Label>
- <Input
- v-model.number="form.query_timeout_secs"
- type="number"
- min="0"
- max="300"
- step="1"
- class="col-span-3"
- />
+ <Input v-model.number="form.query_timeout_secs" type="number" min="0" max="300" step="1" class="col-span-3" />
</div>
<div v-show="form.db_type === 'mongodb'" class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.idleTimeout") }}</Label>
- <Input
- v-model.number="form.idle_timeout_secs"
- type="number"
- min="0"
- max="600"
- step="1"
- class="col-span-3"
- />
+ <Input v-model.number="form.idle_timeout_secs" type="number" min="0" max="600" step="1" class="col-span-3" />
</div>
</div>
</TabsContent>
@@ -3328,9 +2868,7 @@ function openExternalUrl(url: string) {
type="button"
draggable="true"
class="flex min-h-10 items-center gap-2 rounded-md border px-2 text-left text-xs transition-colors"
- :class="
- hop.id === selectedTransportLayer?.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'
- "
+ :class="hop.id === selectedTransportLayer?.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'"
@click="selectedTransportLayerId = hop.id"
@dragstart="draggedTransportLayerId = hop.id"
@dragover.prevent
@@ -3340,23 +2878,11 @@ function openExternalUrl(url: string) {
<span class="w-5 shrink-0 text-muted-foreground">{{ index + 1 }}</span>
<input v-model="hop.enabled" type="checkbox" class="mr-0" @click.stop />
<span class="min-w-0 flex-1 truncate">
- {{
- hop.name ||
- hop.host ||
- (hop.type === "proxy"
- ? `Proxy ${index + 1}`
- : t("connection.sshHopDefaultName", { index: index + 1 }))
- }}
+ {{ hop.name || hop.host || (hop.type === "proxy" ? `Proxy ${index + 1}` : t("connection.sshHopDefaultName", { index: index + 1 })) }}
</span>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7"
- :disabled="index === 0"
- @click.stop="moveTransportLayer(hop.id, -1)"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="index === 0" @click.stop="moveTransportLayer(hop.id, -1)">
<ArrowUp class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
@@ -3364,13 +2890,7 @@ function openExternalUrl(url: string) {
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7"
- :disabled="index === transportLayers.length - 1"
- @click.stop="moveTransportLayer(hop.id, 1)"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="index === transportLayers.length - 1" @click.stop="moveTransportLayer(hop.id, 1)">
<ArrowDown class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
@@ -3387,23 +2907,11 @@ function openExternalUrl(url: string) {
<Plus class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.proxy") }}
</Button>
- <Button
- v-if="selectedTransportLayer"
- type="button"
- variant="outline"
- size="sm"
- @click="duplicateTransportLayer(selectedTransportLayer)"
- >
+ <Button v-if="selectedTransportLayer" type="button" variant="outline" size="sm" @click="duplicateTransportLayer(selectedTransportLayer)">
<Copy class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.sshHopDuplicate") }}
</Button>
- <Button
- v-if="selectedTransportLayer"
- type="button"
- variant="outline"
- size="sm"
- @click="removeTransportLayer(selectedTransportLayer.id)"
- >
+ <Button v-if="selectedTransportLayer" type="button" variant="outline" size="sm" @click="removeTransportLayer(selectedTransportLayer.id)">
<Trash2 class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.sshHopDelete") }}
</Button>
@@ -3414,18 +2922,11 @@ function openExternalUrl(url: string) {
<template v-if="selectedTransportLayer">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshHopName") }}</Label>
- <Input
- v-model="selectedTransportLayer.name"
- class="col-span-3"
- :placeholder="t('connection.sshHopNamePlaceholder')"
- />
+ <Input v-model="selectedTransportLayer.name" class="col-span-3" :placeholder="t('connection.sshHopNamePlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">Type</Label>
- <Select
- :model-value="selectedTransportLayer.type"
- @update:model-value="(value: any) => changeSelectedTransportLayerType(value)"
- >
+ <Select :model-value="selectedTransportLayer.type" @update:model-value="(value: any) => changeSelectedTransportLayerType(value)">
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
@@ -3438,58 +2939,24 @@ function openExternalUrl(url: string) {
<template v-if="selectedSshLayer">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshHost") }}</Label>
- <Input
- v-model="selectedSshLayer.host"
- class="col-span-2"
- placeholder="ssh.example.com"
- :disabled="selectedSshLayer.enabled === false"
- />
- <Input
- v-model.number="selectedSshLayer.port"
- type="number"
- min="1"
- max="65535"
- class="col-span-1"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <Input v-model="selectedSshLayer.host" class="col-span-2" placeholder="ssh.example.com" :disabled="selectedSshLayer.enabled === false" />
+ <Input v-model.number="selectedSshLayer.port" type="number" min="1" max="65535" class="col-span-1" :disabled="selectedSshLayer.enabled === false" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshUser") }}</Label>
- <Input
- v-model="selectedSshLayer.user"
- class="col-span-3"
- placeholder="root"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <Input v-model="selectedSshLayer.user" class="col-span-3" placeholder="root" :disabled="selectedSshLayer.enabled === false" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshPassword") }}</Label>
- <Input
- v-model="selectedSshLayer.password"
- type="password"
- class="col-span-3"
- :placeholder="t('connection.sshPasswordPlaceholder')"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <Input v-model="selectedSshLayer.password" type="password" class="col-span-3" :placeholder="t('connection.sshPasswordPlaceholder')" :disabled="selectedSshLayer.enabled === false" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshKeyPath") }}</Label>
<div class="col-span-3 flex items-center gap-1">
- <Input
- v-model="selectedSshLayer.key_path"
- class="flex-1"
- placeholder="~/.ssh/id_rsa"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <Input v-model="selectedSshLayer.key_path" class="flex-1" placeholder="~/.ssh/id_rsa" :disabled="selectedSshLayer.enabled === false" />
<Tooltip v-if="isDesktop">
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-9 w-9 shrink-0"
- :disabled="selectedSshLayer.enabled === false"
- @click="browseSshKeyPath(selectedSshLayer)"
- >
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="selectedSshLayer.enabled === false" @click="browseSshKeyPath(selectedSshLayer)">
<FolderOpen class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -3499,47 +2966,24 @@ function openExternalUrl(url: string) {
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshKeyPassphrase") }}</Label>
- <Input
- v-model="selectedSshLayer.key_passphrase"
- type="password"
- class="col-span-3"
- :placeholder="t('connection.sshKeyPassphrasePlaceholder')"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <Input v-model="selectedSshLayer.key_passphrase" type="password" class="col-span-3" :placeholder="t('connection.sshKeyPassphrasePlaceholder')" :disabled="selectedSshLayer.enabled === false" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- v-model="selectedSshLayer.expose_lan"
- class="mr-0"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <input type="checkbox" v-model="selectedSshLayer.expose_lan" class="mr-0" :disabled="selectedSshLayer.enabled === false" />
<span class="text-xs text-muted-foreground">{{ t("connection.sshExposeLan") }}</span>
</label>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.sshConnectTimeout") }}</Label>
- <Input
- v-model.number="selectedSshLayer.connect_timeout_secs"
- type="number"
- min="1"
- max="300"
- step="1"
- class="col-span-3"
- :disabled="selectedSshLayer.enabled === false"
- />
+ <Input v-model.number="selectedSshLayer.connect_timeout_secs" type="number" min="1" max="300" step="1" class="col-span-3" :disabled="selectedSshLayer.enabled === false" />
</div>
</template>
<template v-else-if="selectedProxyLayer">
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyType") }}</Label>
- <Select
- :model-value="selectedProxyLayer.proxy_type || 'socks5'"
- :disabled="selectedProxyLayer.enabled === false"
- @update:model-value="updateSelectedProxyType"
- >
+ <Select :model-value="selectedProxyLayer.proxy_type || 'socks5'" :disabled="selectedProxyLayer.enabled === false" @update:model-value="updateSelectedProxyType">
<SelectTrigger class="col-span-3 h-9">
<SelectValue />
</SelectTrigger>
@@ -3551,37 +2995,16 @@ function openExternalUrl(url: string) {
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyHost") }}</Label>
- <Input
- v-model="selectedProxyLayer.host"
- class="col-span-2"
- placeholder="127.0.0.1"
- :disabled="selectedProxyLayer.enabled === false"
- />
- <Input
- v-model.number="selectedProxyLayer.port"
- type="number"
- class="col-span-1"
- :disabled="selectedProxyLayer.enabled === false"
- />
+ <Input v-model="selectedProxyLayer.host" class="col-span-2" placeholder="127.0.0.1" :disabled="selectedProxyLayer.enabled === false" />
+ <Input v-model.number="selectedProxyLayer.port" type="number" class="col-span-1" :disabled="selectedProxyLayer.enabled === false" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyUsername") }}</Label>
- <Input
- v-model="selectedProxyLayer.username"
- class="col-span-3"
- :placeholder="t('connection.proxyUsernamePlaceholder')"
- :disabled="selectedProxyLayer.enabled === false"
- />
+ <Input v-model="selectedProxyLayer.username" class="col-span-3" :placeholder="t('connection.proxyUsernamePlaceholder')" :disabled="selectedProxyLayer.enabled === false" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.proxyPassword") }}</Label>
- <Input
- v-model="selectedProxyLayer.password"
- type="password"
- class="col-span-3"
- :placeholder="t('connection.proxyPasswordPlaceholder')"
- :disabled="selectedProxyLayer.enabled === false"
- />
+ <Input v-model="selectedProxyLayer.password" type="password" class="col-span-3" :placeholder="t('connection.proxyPasswordPlaceholder')" :disabled="selectedProxyLayer.enabled === false" />
</div>
</template>
</template>
@@ -3592,45 +3015,20 @@ function openExternalUrl(url: string) {
<DialogFooter class="flex min-w-0 items-center gap-2 sm:flex-nowrap">
<div class="mr-auto flex min-w-0 flex-1 basis-0 items-center gap-2 overflow-hidden">
- <Button
- v-if="!editingId"
- variant="outline"
- class="shrink-0"
- :disabled="isSaving"
- @click="backToDatabasePicker"
- >
+ <Button v-if="!editingId" variant="outline" class="shrink-0" :disabled="isSaving" @click="backToDatabasePicker">
<ArrowLeft class="h-4 w-4" />
{{ t("connection.back") }}
</Button>
<template v-if="testResult">
- <span
- class="block min-w-0 flex-1 basis-0 truncate text-xs"
- :class="testResult.ok ? 'text-green-600' : 'text-red-600'"
- :title="testResultMessage"
- role="status"
- aria-live="polite"
- >
+ <span class="block min-w-0 flex-1 basis-0 truncate text-xs" :class="testResult.ok ? 'text-green-600' : 'text-red-600'" :title="testResultMessage" role="status" aria-live="polite">
{{ testResultMessage }}
</span>
- <Button
- variant="ghost"
- size="icon-xs"
- class="h-5 w-5 shrink-0"
- :title="t('connection.copyTestResult')"
- :aria-label="t('connection.copyTestResult')"
- @click="copyTestResult"
- >
+ <Button variant="ghost" size="icon-xs" class="h-5 w-5 shrink-0" :title="t('connection.copyTestResult')" :aria-label="t('connection.copyTestResult')" @click="copyTestResult">
<Copy class="h-3 w-3" />
</Button>
</template>
</div>
- <Button
- v-if="canChooseVisibleDatabases"
- variant="outline"
- class="shrink-0"
- :disabled="isTesting || isSaving || isLoadingVisibleDatabases || !hasRequiredConnectionTarget"
- @click="openVisibleDatabasesPicker"
- >
+ <Button v-if="canChooseVisibleDatabases" variant="outline" class="shrink-0" :disabled="isTesting || isSaving || isLoadingVisibleDatabases || !hasRequiredConnectionTarget" @click="openVisibleDatabasesPicker">
<Loader2 v-if="isLoadingVisibleDatabases" class="mr-1.5 h-4 w-4 animate-spin" />
<ListFilter v-else class="mr-1.5 h-4 w-4" />
{{ hasVisibleDatabaseFilter ? visibleDatabaseSummary : t("contextMenu.selectVisibleDatabases") }}
@@ -3639,13 +3037,7 @@ function openExternalUrl(url: string) {
{{ isTesting ? t("connection.testing") : t("connection.test") }}
</Button>
<Button class="shrink-0" @click="save" :disabled="isSaving || !hasRequiredConnectionTarget">
- {{
- isSaving
- ? t("common.loading")
- : editingId || isJdbcConnection
- ? t("connection.save")
- : t("connection.saveAndConnect")
- }}
+ {{ isSaving ? t("common.loading") : editingId || isJdbcConnection ? t("connection.save") : t("connection.saveAndConnect") }}
</Button>
</DialogFooter>
</template>
@@ -3663,12 +3055,7 @@ function openExternalUrl(url: string) {
<div class="flex items-center gap-2 rounded-md border bg-background px-2">
<Search class="h-4 w-4 shrink-0 text-muted-foreground" />
- <Input
- v-model="visibleDatabaseSearchText"
- :placeholder="t('visibleDatabases.searchPlaceholder')"
- class="h-8 border-0 px-0 shadow-none focus-visible:ring-0"
- :disabled="isLoadingVisibleDatabases || !!visibleDatabaseError"
- />
+ <Input v-model="visibleDatabaseSearchText" :placeholder="t('visibleDatabases.searchPlaceholder')" class="h-8 border-0 px-0 shadow-none focus-visible:ring-0" :disabled="isLoadingVisibleDatabases || !!visibleDatabaseError" />
</div>
<div class="flex items-center justify-between text-xs text-muted-foreground">
@@ -3681,54 +3068,28 @@ function openExternalUrl(url: string) {
}}
</span>
<div class="flex items-center gap-2">
- <button
- class="hover:text-foreground disabled:opacity-50"
- :disabled="isLoadingVisibleDatabases"
- @click="selectAllVisibleDatabases"
- >
+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoadingVisibleDatabases" @click="selectAllVisibleDatabases">
{{ t("visibleDatabases.selectAll") }}
</button>
- <button
- class="hover:text-foreground disabled:opacity-50"
- :disabled="isLoadingVisibleDatabases"
- @click="clearVisibleDatabaseSelection"
- >
+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoadingVisibleDatabases" @click="clearVisibleDatabaseSelection">
{{ t("visibleDatabases.clear") }}
</button>
- <button
- class="hover:text-foreground disabled:opacity-50"
- :disabled="isLoadingVisibleDatabases"
- @click="showAllVisibleDatabases"
- >
+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoadingVisibleDatabases" @click="showAllVisibleDatabases">
{{ t("visibleDatabases.showAll") }}
</button>
</div>
</div>
- <p
- v-if="!isLoadingVisibleDatabases && !visibleDatabaseError && !visibleDatabaseCanSave"
- class="text-xs text-destructive"
- >
+ <p v-if="!isLoadingVisibleDatabases && !visibleDatabaseError && !visibleDatabaseCanSave" class="text-xs text-destructive">
{{ t("visibleDatabases.emptySelection") }}
</p>
- <label
- v-if="visibleDatabaseHasSystemDatabases"
- class="flex h-8 items-center gap-2 rounded-md px-1 text-xs text-muted-foreground"
- >
- <input
- v-model="visibleDatabaseShowSystem"
- type="checkbox"
- class="h-3.5 w-3.5 accent-primary"
- :disabled="isLoadingVisibleDatabases || !!visibleDatabaseError"
- />
+ <label v-if="visibleDatabaseHasSystemDatabases" class="flex h-8 items-center gap-2 rounded-md px-1 text-xs text-muted-foreground">
+ <input v-model="visibleDatabaseShowSystem" type="checkbox" class="h-3.5 w-3.5 accent-primary" :disabled="isLoadingVisibleDatabases || !!visibleDatabaseError" />
<span>{{ t("visibleDatabases.showSystemDatabases") }}</span>
</label>
<div class="h-72 overflow-y-auto rounded-md border bg-background/50 p-1">
- <div
- v-if="isLoadingVisibleDatabases"
- class="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground"
- >
+ <div v-if="isLoadingVisibleDatabases" class="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
<Loader2 class="h-4 w-4 animate-spin" />
{{ t("common.loading") }}
</div>
@@ -3755,10 +3116,7 @@ function openExternalUrl(url: string) {
<DialogFooter>
<Button variant="outline" @click="showVisibleDatabasesDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button
- :disabled="isLoadingVisibleDatabases || !!visibleDatabaseError || !visibleDatabaseCanSave"
- @click="saveVisibleDatabaseSelection"
- >
+ <Button :disabled="isLoadingVisibleDatabases || !!visibleDatabaseError || !visibleDatabaseCanSave" @click="saveVisibleDatabaseSelection">
{{ t("visibleDatabases.save") }}
</Button>
</DialogFooter>
diff --git a/apps/desktop/src/components/connection/ConnectionErrorIndicator.vue b/apps/desktop/src/components/connection/ConnectionErrorIndicator.vue
index 34b5a9b0c1..4dc825e893 100644
--- a/apps/desktop/src/components/connection/ConnectionErrorIndicator.vue
+++ b/apps/desktop/src/components/connection/ConnectionErrorIndicator.vue
@@ -29,13 +29,7 @@ function clearError() {
<template>
<Popover v-if="errorMessage">
<PopoverTrigger as-child>
- <button
- type="button"
- class="inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-amber-500 hover:bg-amber-500/10 hover:text-amber-600 focus:outline-none focus:ring-1 focus:ring-amber-500/40"
- :class="triggerClass"
- :title="t('connection.lastError')"
- @click.stop
- >
+ <button type="button" class="inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-amber-500 hover:bg-amber-500/10 hover:text-amber-600 focus:outline-none focus:ring-1 focus:ring-amber-500/40" :class="triggerClass" :title="t('connection.lastError')" @click.stop>
<AlertTriangle class="h-3.5 w-3.5" />
</button>
</PopoverTrigger>
@@ -49,12 +43,7 @@ function clearError() {
{{ errorMessage }}
</div>
</div>
- <button
- type="button"
- class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"
- :title="t('connection.clearError')"
- @click="clearError"
- >
+ <button type="button" class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground" :title="t('connection.clearError')" @click="clearError">
<X class="h-3.5 w-3.5" />
</button>
</div>
diff --git a/apps/desktop/src/components/diagram/SchemaDiagramDialog.vue b/apps/desktop/src/components/diagram/SchemaDiagramDialog.vue
index 827cc057c6..10e16ac343 100644
--- a/apps/desktop/src/components/diagram/SchemaDiagramDialog.vue
+++ b/apps/desktop/src/components/diagram/SchemaDiagramDialog.vue
@@ -11,30 +11,11 @@ import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import * as api from "@/lib/api";
import { DIAGRAM_SQL_TYPES, isSchemaAware as isSchemaAwareDatabase } from "@/lib/databaseCapabilities";
import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions";
-import {
- buildDiagramRelationships,
- filterDiagramTables,
- layoutDiagramTables,
- type DiagramPosition,
- type DiagramRelationship,
- type DiagramTable,
-} from "@/lib/erDiagram";
+import { buildDiagramRelationships, filterDiagramTables, layoutDiagramTables, type DiagramPosition, type DiagramRelationship, type DiagramTable } from "@/lib/erDiagram";
import { buildEngineeringDiagram } from "@/lib/engineeringDiagram";
import { buildEngineeringDiagramSvg, buildTableDiagramSvg, diagramSvgFileName } from "@/lib/diagramSvgExport";
import { clampDiagramZoom, zoomFromGestureScale, zoomFromWheelDelta } from "@/lib/diagramZoom";
-import {
- Download,
- KeyRound,
- Link2,
- Loader2,
- Maximize2,
- Network,
- RefreshCw,
- Search,
- Table2,
- ZoomIn,
- ZoomOut,
-} from "@lucide/vue";
+import { Download, KeyRound, Link2, Loader2, Maximize2, Network, RefreshCw, Search, Table2, ZoomIn, ZoomOut } from "@lucide/vue";
import { useToast } from "@/composables/useToast";
import { isTauriRuntime } from "@/lib/tauriRuntime";
@@ -86,9 +67,7 @@ const dragging = ref<{
originY: number;
} | null>(null);
-const sqlConnections = computed(() =>
- store.connections.filter((connection) => DIAGRAM_SQL_TYPES.has(connection.db_type)),
-);
+const sqlConnections = computed(() => store.connections.filter((connection) => DIAGRAM_SQL_TYPES.has(connection.db_type)));
const selectedConnection = computed(() => (connectionId.value ? store.getConfig(connectionId.value) : undefined));
@@ -120,15 +99,9 @@ const visibleTableMap = computed(() => new Map(visibleTables.value.map((table) =
const visibleRelationships = computed(() => buildDiagramRelationships(visibleTables.value));
-const diagramReady = computed(
- () => !!connectionId.value && !!database.value && (!isSchemaAware.value || !!schema.value),
-);
+const diagramReady = computed(() => !!connectionId.value && !!database.value && (!isSchemaAware.value || !!schema.value));
-const loadingText = computed(() =>
- totalTableCount.value > 0
- ? t("diagram.loadingProgress", { loaded: loadedTableCount.value, total: totalTableCount.value })
- : t("diagram.loading"),
-);
+const loadingText = computed(() => (totalTableCount.value > 0 ? t("diagram.loadingProgress", { loaded: loadedTableCount.value, total: totalTableCount.value }) : t("diagram.loading")));
function connectionIconType(id: string) {
const config = store.getConfig(id);
@@ -153,13 +126,9 @@ const canvasSize = computed(() => {
return { width, height };
});
-const engineeringDiagram = computed(() =>
- buildEngineeringDiagram(visibleTables.value, visibleRelationships.value, positions.value),
-);
+const engineeringDiagram = computed(() => buildEngineeringDiagram(visibleTables.value, visibleRelationships.value, positions.value));
-const activeCanvasSize = computed(() =>
- diagramMode.value === "engineering" ? engineeringDiagram.value.canvas : canvasSize.value,
-);
+const activeCanvasSize = computed(() => (diagramMode.value === "engineering" ? engineeringDiagram.value.canvas : canvasSize.value));
function resetLayout() {
const count = visibleTables.value.length;
@@ -237,33 +206,19 @@ function routeSideX(rect: TableRect, routeX: number, offset = 0): number {
}
function tableRects(): TableRect[] {
- return visibleTables.value
- .map((table) => getTableRect(table.name))
- .filter((rect): rect is TableRect => rect !== null);
+ return visibleTables.value.map((table) => getTableRect(table.name)).filter((rect): rect is TableRect => rect !== null);
}
function isVerticalRouteBlocked(routeX: number, y1: number, y2: number, ignoredTables: Set<string>): boolean {
const top = Math.min(y1, y2);
const bottom = Math.max(y1, y2);
- return tableRects().some(
- (rect) =>
- !ignoredTables.has(rect.name) &&
- routeX >= rect.x - ROUTE_BLOCK_MARGIN &&
- routeX <= rect.x + rect.width + ROUTE_BLOCK_MARGIN &&
- rangesOverlap(top, bottom, rect.y - ROUTE_BLOCK_MARGIN, rect.y + rect.height + ROUTE_BLOCK_MARGIN),
- );
+ return tableRects().some((rect) => !ignoredTables.has(rect.name) && routeX >= rect.x - ROUTE_BLOCK_MARGIN && routeX <= rect.x + rect.width + ROUTE_BLOCK_MARGIN && rangesOverlap(top, bottom, rect.y - ROUTE_BLOCK_MARGIN, rect.y + rect.height + ROUTE_BLOCK_MARGIN));
}
function isHorizontalRouteBlocked(y: number, x1: number, x2: number, ignoredTables: Set<string>): boolean {
const left = Math.min(x1, x2);
const right = Math.max(x1, x2);
- return tableRects().some(
- (rect) =>
- !ignoredTables.has(rect.name) &&
- y >= rect.y - ROUTE_BLOCK_MARGIN &&
- y <= rect.y + rect.height + ROUTE_BLOCK_MARGIN &&
- rangesOverlap(left, right, rect.x - ROUTE_BLOCK_MARGIN, rect.x + rect.width + ROUTE_BLOCK_MARGIN),
- );
+ return tableRects().some((rect) => !ignoredTables.has(rect.name) && y >= rect.y - ROUTE_BLOCK_MARGIN && y <= rect.y + rect.height + ROUTE_BLOCK_MARGIN && rangesOverlap(left, right, rect.x - ROUTE_BLOCK_MARGIN, rect.x + rect.width + ROUTE_BLOCK_MARGIN));
}
function candidateRouteXs(source: TableRect, target: TableRect): number[] {
@@ -297,11 +252,7 @@ function candidateRouteXs(source: TableRect, target: TableRect): number[] {
const leftTargetX = routeSideX(target, left);
const rightSourceX = routeSideX(source, right);
const rightTargetX = routeSideX(target, right);
- return (
- Math.abs(left - leftSourceX) +
- Math.abs(left - leftTargetX) -
- (Math.abs(right - rightSourceX) + Math.abs(right - rightTargetX))
- );
+ return Math.abs(left - leftSourceX) + Math.abs(left - leftTargetX) - (Math.abs(right - rightSourceX) + Math.abs(right - rightTargetX));
});
}
@@ -319,11 +270,7 @@ function relationshipPath(relationship: DiagramRelationship): string {
candidates.find((candidate) => {
const x1 = routeSideX(source, candidate);
const x2 = routeSideX(target, candidate);
- return (
- !isVerticalRouteBlocked(candidate, y1, y2, ignoredTables) &&
- !isHorizontalRouteBlocked(y1, x1, candidate, ignoredTables) &&
- !isHorizontalRouteBlocked(y2, candidate, x2, ignoredTables)
- );
+ return !isVerticalRouteBlocked(candidate, y1, y2, ignoredTables) && !isHorizontalRouteBlocked(y1, x1, candidate, ignoredTables) && !isHorizontalRouteBlocked(y2, candidate, x2, ignoredTables);
}) ??
candidates[0] ??
Math.max(source.x + source.width, target.x + target.width) + ROUTE_PADDING;
@@ -338,21 +285,11 @@ function engineeringEntityCenter(tableName: string): DiagramPosition {
return entity ? { x: entity.x + entity.width / 2, y: entity.y + entity.height / 2 } : { x: 0, y: 0 };
}
-function engineeringAttributeCenter(attribute: {
- x: number;
- y: number;
- width: number;
- height: number;
-}): DiagramPosition {
+function engineeringAttributeCenter(attribute: { x: number; y: number; width: number; height: number }): DiagramPosition {
return { x: attribute.x + attribute.width / 2, y: attribute.y + attribute.height / 2 };
}
-function engineeringRelationshipCenter(relationship: {
- x: number;
- y: number;
- width: number;
- height: number;
-}): DiagramPosition {
+function engineeringRelationshipCenter(relationship: { x: number; y: number; width: number; height: number }): DiagramPosition {
return {
x: relationship.x + relationship.width / 2,
y: relationship.y + relationship.height / 2,
@@ -397,12 +334,7 @@ async function loadSchemas() {
try {
const names = await api.listSchemas(connectionId.value, database.value);
schemas.value = names;
- schema.value =
- props.prefillSchema && names.includes(props.prefillSchema)
- ? props.prefillSchema
- : names.includes("public")
- ? "public"
- : (names[0] ?? "");
+ schema.value = props.prefillSchema && names.includes(props.prefillSchema) ? props.prefillSchema : names.includes("public") ? "public" : (names[0] ?? "");
} catch (e: any) {
toast(e?.message || String(e), 5000);
} finally {
@@ -439,10 +371,7 @@ async function setSchema(value: string) {
async function loadTableDiagramData(tableName: string, querySchema: string): Promise<DiagramTable> {
try {
- const [columns, foreignKeys] = await Promise.all([
- api.getColumns(connectionId.value, database.value, querySchema, tableName),
- api.listForeignKeys(connectionId.value, database.value, querySchema, tableName).catch(() => []),
- ]);
+ const [columns, foreignKeys] = await Promise.all([api.getColumns(connectionId.value, database.value, querySchema, tableName), api.listForeignKeys(connectionId.value, database.value, querySchema, tableName).catch(() => [])]);
return { name: tableName, columns, foreignKeys };
} catch (e) {
failedTableCount.value += 1;
@@ -464,9 +393,7 @@ async function loadDiagram() {
await store.ensureConnected(connectionId.value);
const querySchema = schema.value || database.value;
const tableInfos = await api.listTables(connectionId.value, database.value, querySchema);
- const baseTables = tableInfos
- .filter((table) => table.table_type !== "VIEW")
- .sort((a, b) => a.name.localeCompare(b.name));
+ const baseTables = tableInfos.filter((table) => table.table_type !== "VIEW").sort((a, b) => a.name.localeCompare(b.name));
totalTableCount.value = baseTables.length;
const loadedTables: DiagramTable[] = [];
@@ -510,10 +437,7 @@ async function initialize() {
if (props.prefillConnectionId) {
connectionId.value = props.prefillConnectionId;
await loadDatabases(props.prefillConnectionId);
- const initialDatabase =
- props.prefillDatabase && databases.value.includes(props.prefillDatabase)
- ? props.prefillDatabase
- : props.prefillDatabase || databases.value[0] || "";
+ const initialDatabase = props.prefillDatabase && databases.value.includes(props.prefillDatabase) ? props.prefillDatabase : props.prefillDatabase || databases.value[0] || "";
if (initialDatabase) await setDatabase(initialDatabase);
return;
}
@@ -558,9 +482,7 @@ function resetZoomAndLayout() {
}
function tableRelationshipPaths(): Record<string, string> {
- return Object.fromEntries(
- visibleRelationships.value.map((relationship) => [relationship.id, relationshipPath(relationship)]),
- );
+ return Object.fromEntries(visibleRelationships.value.map((relationship) => [relationship.id, relationshipPath(relationship)]));
}
function currentDiagramSvg(): string {
@@ -590,10 +512,7 @@ async function exportSvg() {
const svgContent = currentDiagramSvg();
if (isTauriRuntime()) {
- const [{ save }, { writeTextFile }] = await Promise.all([
- import("@tauri-apps/plugin-dialog"),
- import("@tauri-apps/plugin-fs"),
- ]);
+ const [{ save }, { writeTextFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
const path = await save({
defaultPath,
filters: [{ name: "SVG", extensions: ["svg"] }],
@@ -685,9 +604,7 @@ onUnmounted(stopDrag);
<template>
<Dialog v-model:open="open">
- <DialogContent
- class="w-[94vw] max-w-[94vw] sm:max-w-[94vw] md:max-w-[94vw] lg:max-w-[94vw] xl:max-w-[94vw] h-[86vh] max-h-[86vh] gap-0 p-0 overflow-hidden flex flex-col"
- >
+ <DialogContent class="w-[94vw] max-w-[94vw] sm:max-w-[94vw] md:max-w-[94vw] lg:max-w-[94vw] xl:max-w-[94vw] h-[86vh] max-h-[86vh] gap-0 p-0 overflow-hidden flex flex-col">
<DialogHeader class="px-4 py-3 border-b">
<DialogTitle class="flex items-center gap-2">
<Network class="w-4 h-4" />
@@ -714,11 +631,7 @@ onUnmounted(stopDrag);
</SelectContent>
</Select>
- <Select
- :model-value="database"
- :disabled="!databases.length || loadingDatabases"
- @update:model-value="(value: any) => setDatabase(String(value))"
- >
+ <Select :model-value="database" :disabled="!databases.length || loadingDatabases" @update:model-value="(value: any) => setDatabase(String(value))">
<SelectTrigger class="h-8 w-44 text-xs">
<SelectValue :placeholder="loadingDatabases ? t('common.loading') : t('diagram.selectDatabase')" />
</SelectTrigger>
@@ -727,12 +640,7 @@ onUnmounted(stopDrag);
</SelectContent>
</Select>
- <Select
- v-if="isSchemaAware"
- :model-value="schema"
- :disabled="!schemas.length || loadingSchemas"
- @update:model-value="(value: any) => setSchema(String(value))"
- >
+ <Select v-if="isSchemaAware" :model-value="schema" :disabled="!schemas.length || loadingSchemas" @update:model-value="(value: any) => setSchema(String(value))">
<SelectTrigger class="h-8 w-40 text-xs">
<SelectValue :placeholder="loadingSchemas ? t('common.loading') : t('diagram.selectSchema')" />
</SelectTrigger>
@@ -747,35 +655,17 @@ onUnmounted(stopDrag);
</div>
<div class="flex h-8 shrink-0 items-center overflow-hidden rounded-md border bg-background">
- <Button
- variant="ghost"
- size="sm"
- class="h-8 rounded-none px-2 text-xs"
- :class="diagramMode === 'table' ? 'bg-accent' : ''"
- @click="diagramMode = 'table'"
- >
+ <Button variant="ghost" size="sm" class="h-8 rounded-none px-2 text-xs" :class="diagramMode === 'table' ? 'bg-accent' : ''" @click="diagramMode = 'table'">
<Table2 class="mr-1 h-3.5 w-3.5" />
{{ t("diagram.tableMode") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 rounded-none border-l px-2 text-xs"
- :class="diagramMode === 'engineering' ? 'bg-accent' : ''"
- @click="diagramMode = 'engineering'"
- >
+ <Button variant="ghost" size="sm" class="h-8 rounded-none border-l px-2 text-xs" :class="diagramMode === 'engineering' ? 'bg-accent' : ''" @click="diagramMode = 'engineering'">
<Network class="mr-1 h-3.5 w-3.5" />
{{ t("diagram.engineeringMode") }}
</Button>
</div>
- <Button
- v-if="focusTableName && tables.length > 0"
- variant="outline"
- size="sm"
- class="h-8 px-2 text-xs"
- @click="showAllTables = !showAllTables"
- >
+ <Button v-if="focusTableName && tables.length > 0" variant="outline" size="sm" class="h-8 px-2 text-xs" @click="showAllTables = !showAllTables">
{{ showAllTables ? t("diagram.relatedTables") : t("diagram.allTables") }}
</Button>
@@ -786,24 +676,10 @@ onUnmounted(stopDrag);
{{ t("diagram.relationshipsCount", { count: visibleRelationships.length }) }}
</Badge>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8"
- :disabled="loadingDiagram || visibleTables.length === 0"
- :title="t('diagram.exportSvg')"
- @click="exportSvg"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8" :disabled="loadingDiagram || visibleTables.length === 0" :title="t('diagram.exportSvg')" @click="exportSvg">
<Download class="h-4 w-4" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8"
- :disabled="!diagramReady || loadingDiagram"
- :title="t('diagram.refresh')"
- @click="loadDiagram"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8" :disabled="!diagramReady || loadingDiagram" :title="t('diagram.refresh')" @click="loadDiagram">
<Loader2 v-if="loadingDiagram" class="h-4 w-4 animate-spin" />
<RefreshCw v-else class="h-4 w-4" />
</Button>
@@ -813,13 +689,7 @@ onUnmounted(stopDrag);
<Button variant="ghost" size="icon" class="h-8 w-8" :title="t('diagram.zoomIn')" @click="zoomIn">
<ZoomIn class="h-4 w-4" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8"
- :title="t('diagram.resetLayout')"
- @click="resetZoomAndLayout"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8" :title="t('diagram.resetLayout')" @click="resetZoomAndLayout">
<Maximize2 class="h-4 w-4" />
</Button>
</div>
@@ -832,26 +702,13 @@ onUnmounted(stopDrag);
<div v-else-if="!diagramReady" class="h-full flex items-center justify-center text-sm text-muted-foreground">
{{ t("diagram.selectTarget") }}
</div>
- <div
- v-else-if="tables.length === 0"
- class="h-full flex items-center justify-center text-sm text-muted-foreground"
- >
+ <div v-else-if="tables.length === 0" class="h-full flex items-center justify-center text-sm text-muted-foreground">
{{ t("diagram.empty") }}
</div>
- <div
- v-else-if="visibleTables.length === 0"
- class="h-full flex items-center justify-center text-sm text-muted-foreground"
- >
+ <div v-else-if="visibleTables.length === 0" class="h-full flex items-center justify-center text-sm text-muted-foreground">
{{ t("diagram.noMatches") }}
</div>
- <div
- v-else
- ref="diagramViewport"
- class="h-full overflow-auto"
- @wheel="onDiagramWheel"
- @gesturestart="onDiagramGestureStart"
- @gesturechange="onDiagramGestureChange"
- >
+ <div v-else ref="diagramViewport" class="h-full overflow-auto" @wheel="onDiagramWheel" @gesturestart="onDiagramGestureStart" @gesturechange="onDiagramGestureChange">
<div
class="relative"
:style="{
@@ -870,26 +727,11 @@ onUnmounted(stopDrag);
<template v-if="diagramMode === 'table'">
<svg class="absolute inset-0 h-full w-full overflow-visible pointer-events-none">
<defs>
- <marker
- id="diagram-arrow"
- markerWidth="8"
- markerHeight="8"
- refX="7"
- refY="4"
- orient="auto"
- markerUnits="strokeWidth"
- >
+ <marker id="diagram-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto" markerUnits="strokeWidth">
<path d="M 0 0 L 8 4 L 0 8 z" class="fill-primary/70" />
</marker>
</defs>
- <path
- v-for="relationship in visibleRelationships"
- :key="relationship.id"
- :d="relationshipPath(relationship)"
- class="fill-none stroke-primary/55"
- stroke-width="1.6"
- marker-end="url(#diagram-arrow)"
- >
+ <path v-for="relationship in visibleRelationships" :key="relationship.id" :d="relationshipPath(relationship)" class="fill-none stroke-primary/55" stroke-width="1.6" marker-end="url(#diagram-arrow)">
<title>{{ relationshipTitle(relationship) }}</title>
</path>
</svg>
@@ -904,20 +746,13 @@ onUnmounted(stopDrag);
transform: `translate(${positions[table.name]?.x ?? 0}px, ${positions[table.name]?.y ?? 0}px)`,
}"
>
- <div
- class="flex h-11 cursor-grab items-center gap-2 border-b bg-muted/40 px-3 active:cursor-grabbing"
- @mousedown="startDrag(table.name, $event)"
- >
+ <div class="flex h-11 cursor-grab items-center gap-2 border-b bg-muted/40 px-3 active:cursor-grabbing" @mousedown="startDrag(table.name, $event)">
<Table2 class="h-4 w-4 shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate text-sm font-medium">{{ table.name }}</span>
<Badge variant="outline" class="h-5 px-1.5 text-[10px]">{{ table.columns.length }}</Badge>
</div>
<div>
- <div
- v-for="column in visibleColumns(table)"
- :key="column.name"
- class="flex h-6 items-center gap-1.5 border-b border-border/40 px-3 text-xs last:border-b-0"
- >
+ <div v-for="column in visibleColumns(table)" :key="column.name" class="flex h-6 items-center gap-1.5 border-b border-border/40 px-3 text-xs last:border-b-0">
<KeyRound v-if="column.is_primary_key" class="h-3 w-3 shrink-0 text-amber-500" />
<Link2 v-else-if="isForeignKeyColumn(table, column.name)" class="h-3 w-3 shrink-0 text-primary" />
<span v-else class="h-3 w-3 shrink-0" />
@@ -944,51 +779,19 @@ onUnmounted(stopDrag);
stroke-width="1.2"
/>
<template v-for="relationship in engineeringDiagram.relationships" :key="relationship.id">
- <line
- :x1="engineeringEntityCenter(relationship.sourceTable).x"
- :y1="engineeringEntityCenter(relationship.sourceTable).y"
- :x2="engineeringRelationshipCenter(relationship).x"
- :y2="engineeringRelationshipCenter(relationship).y"
- stroke-width="1.4"
- />
- <line
- :x1="engineeringRelationshipCenter(relationship).x"
- :y1="engineeringRelationshipCenter(relationship).y"
- :x2="engineeringEntityCenter(relationship.targetTable).x"
- :y2="engineeringEntityCenter(relationship.targetTable).y"
- stroke-width="1.4"
- />
+ <line :x1="engineeringEntityCenter(relationship.sourceTable).x" :y1="engineeringEntityCenter(relationship.sourceTable).y" :x2="engineeringRelationshipCenter(relationship).x" :y2="engineeringRelationshipCenter(relationship).y" stroke-width="1.4" />
+ <line :x1="engineeringRelationshipCenter(relationship).x" :y1="engineeringRelationshipCenter(relationship).y" :x2="engineeringEntityCenter(relationship.targetTable).x" :y2="engineeringEntityCenter(relationship.targetTable).y" stroke-width="1.4" />
<text
class="fill-foreground text-[13px] font-semibold"
- :x="
- engineeringCardinalityPoint(
- engineeringRelationshipCenter(relationship),
- engineeringEntityCenter(relationship.sourceTable),
- ).x
- "
- :y="
- engineeringCardinalityPoint(
- engineeringRelationshipCenter(relationship),
- engineeringEntityCenter(relationship.sourceTable),
- ).y
- "
+ :x="engineeringCardinalityPoint(engineeringRelationshipCenter(relationship), engineeringEntityCenter(relationship.sourceTable)).x"
+ :y="engineeringCardinalityPoint(engineeringRelationshipCenter(relationship), engineeringEntityCenter(relationship.sourceTable)).y"
>
{{ relationship.sourceCardinality }}
</text>
<text
class="fill-foreground text-[13px] font-semibold"
- :x="
- engineeringCardinalityPoint(
- engineeringRelationshipCenter(relationship),
- engineeringEntityCenter(relationship.targetTable),
- ).x
- "
- :y="
- engineeringCardinalityPoint(
- engineeringRelationshipCenter(relationship),
- engineeringEntityCenter(relationship.targetTable),
- ).y
- "
+ :x="engineeringCardinalityPoint(engineeringRelationshipCenter(relationship), engineeringEntityCenter(relationship.targetTable)).x"
+ :y="engineeringCardinalityPoint(engineeringRelationshipCenter(relationship), engineeringEntityCenter(relationship.targetTable)).y"
>
{{ relationship.targetCardinality }}
</text>
@@ -1022,10 +825,7 @@ onUnmounted(stopDrag);
}"
:title="`${relationship.sourceTable} -> ${relationship.targetTable}`"
>
- <div
- class="absolute inset-0 border border-red-500/70 bg-red-100/80 dark:bg-red-950/35"
- style="clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%)"
- />
+ <div class="absolute inset-0 border border-red-500/70 bg-red-100/80 dark:bg-red-950/35" style="clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%)" />
<span class="relative max-w-[70px] truncate">{{ relationship.label }}</span>
</div>
diff --git a/apps/desktop/src/components/diff/DataCompareDialog.vue b/apps/desktop/src/components/diff/DataCompareDialog.vue
index 7b9eb1f4c2..d3a1063b43 100644
--- a/apps/desktop/src/components/diff/DataCompareDialog.vue
+++ b/apps/desktop/src/components/diff/DataCompareDialog.vue
@@ -11,28 +11,11 @@ import { useToast } from "@/composables/useToast";
import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions";
import { isSchemaAware } from "@/lib/databaseCapabilities";
import { copyToClipboard } from "@/lib/clipboard";
-import type {
- DataCompareCellValue,
- DataCompareModifiedRow,
- DataCompareResult,
- DataCompareRow,
- DataCompareSyncPlan,
- DataCompareSyncPlanTableOptions,
-} from "@/lib/dataCompare";
+import type { DataCompareCellValue, DataCompareModifiedRow, DataCompareResult, DataCompareRow, DataCompareSyncPlan, DataCompareSyncPlanTableOptions } from "@/lib/dataCompare";
import type { ColumnInfo, DatabaseType } from "@/types/database";
import * as api from "@/lib/api";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
-import {
- ArrowLeftRight,
- CheckSquare,
- ChevronDown,
- ChevronRight,
- Copy,
- GitCompareArrows,
- Loader2,
- Play,
- Square,
-} from "@lucide/vue";
+import { ArrowLeftRight, CheckSquare, ChevronDown, ChevronRight, Copy, GitCompareArrows, Loader2, Play, Square } from "@lucide/vue";
type CompareColumn = ColumnInfo;
@@ -131,23 +114,15 @@ const showModified = ref(true);
let syncPlanRequestId = 0;
-const sqlConnections = computed(() =>
- store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(connection.db_type)),
-);
-const selectedSourceTableNames = computed(() =>
- sourceTables.value.filter((table) => selectedSourceTables.value.has(table)),
-);
+const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(connection.db_type)));
+const selectedSourceTableNames = computed(() => sourceTables.value.filter((table) => selectedSourceTables.value.has(table)));
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
const filteredSourceTables = computed(() => {
const query = sourceTableSearch.value.trim().toLowerCase();
if (!query) return sourceTables.value;
return sourceTables.value.filter((table) => table.toLowerCase().includes(query));
});
-const allFilteredTablesSelected = computed(
- () =>
- filteredSourceTables.value.length > 0 &&
- filteredSourceTables.value.every((table) => selectedSourceTables.value.has(table)),
-);
+const allFilteredTablesSelected = computed(() => filteredSourceTables.value.length > 0 && filteredSourceTables.value.every((table) => selectedSourceTables.value.has(table)));
const compareTasksPreview = computed(() =>
selectedSourceTableNames.value.map((table) => {
const target = isBatchCompare.value ? table : targetTable.value || table;
@@ -160,19 +135,8 @@ const compareTasksPreview = computed(() =>
}),
);
const matchedTaskCount = computed(() => compareTasksPreview.value.filter((task) => task.matched).length);
-const missingTargetTables = computed(() =>
- compareTasksPreview.value.filter((task) => !task.matched).map((task) => task.targetTable || task.sourceTable),
-);
-const canCompare = computed(
- () =>
- sourceConnectionId.value &&
- sourceDatabase.value &&
- sourceSchema.value &&
- selectedSourceTableNames.value.length > 0 &&
- targetConnectionId.value &&
- targetDatabase.value &&
- targetSchema.value,
-);
+const missingTargetTables = computed(() => compareTasksPreview.value.filter((task) => !task.matched).map((task) => task.targetTable || task.sourceTable));
+const canCompare = computed(() => sourceConnectionId.value && sourceDatabase.value && sourceSchema.value && selectedSourceTableNames.value.length > 0 && targetConnectionId.value && targetDatabase.value && targetSchema.value);
const keyColumns = computed(() =>
keyColumnsText.value
.split(",")
@@ -188,11 +152,7 @@ const totalAdded = computed(() => batchResults.value.reduce((sum, item) => sum +
const totalRemoved = computed(() => batchResults.value.reduce((sum, item) => sum + item.removed, 0));
const totalModified = computed(() => batchResults.value.reduce((sum, item) => sum + item.modified, 0));
const hasResults = computed(() => batchResults.value.length > 0);
-const visibleKinds = computed(() => [
- ...(showAdded.value ? (["added"] as DiffKind[]) : []),
- ...(showRemoved.value ? (["removed"] as DiffKind[]) : []),
- ...(showModified.value ? (["modified"] as DiffKind[]) : []),
-]);
+const visibleKinds = computed(() => [...(showAdded.value ? (["added"] as DiffKind[]) : []), ...(showRemoved.value ? (["removed"] as DiffKind[]) : []), ...(showModified.value ? (["modified"] as DiffKind[]) : [])]);
const selectedAddedCount = computed(() => selectedDiffCount("added"));
const selectedRemovedCount = computed(() => selectedDiffCount("removed"));
const selectedModifiedCount = computed(() => selectedDiffCount("modified"));
@@ -300,8 +260,7 @@ function clearResult() {
function swapSourceTarget() {
const previousSelectedTables = [...selectedSourceTableNames.value];
const nextSingleTarget = previousSelectedTables.length === 1 ? (previousSelectedTables[0] ?? "") : "";
- const nextSourceSelection =
- previousSelectedTables.length <= 1 ? [targetTable.value].filter(Boolean) : previousSelectedTables;
+ const nextSourceSelection = previousSelectedTables.length <= 1 ? [targetTable.value].filter(Boolean) : previousSelectedTables;
const tmpConnId = sourceConnectionId.value;
const tmpDb = sourceDatabase.value;
@@ -358,12 +317,7 @@ async function loadSchemas(side: "source" | "target", preferredSchema = "") {
}
const schemas = await api.listSchemas(connectionId, database);
- const schema =
- preferredSchema && schemas.includes(preferredSchema)
- ? preferredSchema
- : schemas.includes("public")
- ? "public"
- : (schemas[0] ?? "");
+ const schema = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
if (side === "source") {
sourceSchemas.value = schemas;
sourceSchema.value = schema;
@@ -402,19 +356,11 @@ async function loadTables(side: "source" | "target") {
const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
if (!connectionId || !database) return;
- const schema =
- side === "source"
- ? sourceSchema.value || (await resolveSchema(connectionId, database, props.prefillSchema))
- : targetSchema.value || (await resolveSchema(connectionId, database));
- const tables = (await api.listTables(connectionId, database, schema))
- .filter((table) => table.table_type !== "VIEW")
- .map((table) => table.name);
+ const schema = side === "source" ? sourceSchema.value || (await resolveSchema(connectionId, database, props.prefillSchema)) : targetSchema.value || (await resolveSchema(connectionId, database));
+ const tables = (await api.listTables(connectionId, database, schema)).filter((table) => table.table_type !== "VIEW").map((table) => table.name);
if (side === "source") {
- const preferredSelection =
- props.prefillTable && tables.includes(props.prefillTable)
- ? [props.prefillTable]
- : [...selectedSourceTables.value].filter((table) => tables.includes(table));
+ const preferredSelection = props.prefillTable && tables.includes(props.prefillTable) ? [props.prefillTable] : [...selectedSourceTables.value].filter((table) => tables.includes(table));
sourceSchema.value = schema;
sourceTables.value = tables;
resetSelectedSourceTables(preferredSelection);
@@ -423,23 +369,12 @@ async function loadTables(side: "source" | "target") {
targetSchema.value = schema;
targetTables.value = tables;
const singleSourceTable = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
- const preferred =
- targetTable.value && tables.includes(targetTable.value)
- ? targetTable.value
- : singleSourceTable && tables.includes(singleSourceTable)
- ? singleSourceTable
- : "";
+ const preferred = targetTable.value && tables.includes(targetTable.value) ? targetTable.value : singleSourceTable && tables.includes(singleSourceTable) ? singleSourceTable : "";
targetTable.value = preferred;
}
}
-async function loadColumnsWithCache(
- cache: Map<string, CompareColumn[]>,
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<CompareColumn[]> {
+async function loadColumnsWithCache(cache: Map<string, CompareColumn[]>, connectionId: string, database: string, schema: string, table: string): Promise<CompareColumn[]> {
const key = `${connectionId}:${database}:${schema}:${table}`;
const cached = cache.get(key);
if (cached) return cached;
@@ -448,25 +383,9 @@ async function loadColumnsWithCache(
return columns;
}
-async function inferKeyColumnsForTable(
- table: string,
- sourceColumnCache?: Map<string, CompareColumn[]>,
-): Promise<string[]> {
+async function inferKeyColumnsForTable(table: string, sourceColumnCache?: Map<string, CompareColumn[]>): Promise<string[]> {
if (!sourceConnectionId.value || !sourceDatabase.value || !sourceSchema.value || !table) return [];
- const columns = sourceColumnCache
- ? await loadColumnsWithCache(
- sourceColumnCache,
- sourceConnectionId.value,
- sourceDatabase.value,
- sourceSchema.value,
- table,
- )
- : (((await api.getColumns(
- sourceConnectionId.value,
- sourceDatabase.value,
- sourceSchema.value,
- table,
- )) as CompareColumn[]) ?? []);
+ const columns = sourceColumnCache ? await loadColumnsWithCache(sourceColumnCache, sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table) : (((await api.getColumns(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table)) as CompareColumn[]) ?? []);
const primaryKeys = columns.filter((column) => column.is_primary_key).map((column) => column.name);
if (primaryKeys.length > 0) return primaryKeys;
return columns.slice(0, 1).map((column) => column.name);
@@ -591,13 +510,7 @@ function buildSyncPlanTables(): DataCompareSyncPlanTableOptions[] {
databaseType: table.databaseType,
preSyncStatements: table.preSyncStatements ?? [],
}))
- .filter(
- (table) =>
- table.preSyncStatements.length > 0 ||
- table.diff.added.length > 0 ||
- table.diff.removed.length > 0 ||
- table.diff.modified.length > 0,
- );
+ .filter((table) => table.preSyncStatements.length > 0 || table.diff.added.length > 0 || table.diff.removed.length > 0 || table.diff.modified.length > 0);
}
async function rebuildSyncPlan() {
@@ -640,10 +553,7 @@ async function startCompare() {
const currentTargetDatabaseType = targetDatabaseType();
try {
- await Promise.all([
- store.ensureConnected(sourceConnectionId.value),
- store.ensureConnected(targetConnectionId.value),
- ]);
+ await Promise.all([store.ensureConnected(sourceConnectionId.value), store.ensureConnected(targetConnectionId.value)]);
for (const [index, task] of tasks.entries()) {
compareProgressCurrent.value = index + 1;
@@ -651,13 +561,7 @@ async function startCompare() {
try {
if (!targetTables.value.includes(task.targetTable)) {
- const sourceColumns = await loadColumnsWithCache(
- sourceColumnCache,
- sourceConnectionId.value,
- sourceDatabase.value,
- sourceSchema.value,
- task.sourceTable,
- );
+ const sourceColumns = await loadColumnsWithCache(sourceColumnCache, sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, task.sourceTable);
const resolvedKeys = keyColumns.value.length > 0 ? keyColumns.value : [];
const preparation = await api.prepareDataCompareMissingTarget({
sourceConnectionId: sourceConnectionId.value,
@@ -697,34 +601,15 @@ async function startCompare() {
continue;
}
- const resolvedKeys =
- keyColumns.value.length > 0
- ? keyColumns.value
- : await inferKeyColumnsForTable(task.sourceTable, sourceColumnCache);
+ const resolvedKeys = keyColumns.value.length > 0 ? keyColumns.value : await inferKeyColumnsForTable(task.sourceTable, sourceColumnCache);
if (resolvedKeys.length === 0) {
throw new Error(t("dataCompare.noKeyColumns"));
}
- const sourceColumns = await loadColumnsWithCache(
- sourceColumnCache,
- sourceConnectionId.value,
- sourceDatabase.value,
- sourceSchema.value,
- task.sourceTable,
- );
- const targetColumns = await loadColumnsWithCache(
- targetColumnCache,
- targetConnectionId.value,
- targetDatabase.value,
- targetSchema.value,
- task.targetTable,
- );
- const columns = sourceColumns
- .map((column) => column.name)
- .filter((column) => targetColumns.some((target) => target.name === column));
- const columnInfo = columns
- .map((column) => targetColumns.find((target) => target.name === column))
- .filter((column): column is CompareColumn => !!column);
+ const sourceColumns = await loadColumnsWithCache(sourceColumnCache, sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, task.sourceTable);
+ const targetColumns = await loadColumnsWithCache(targetColumnCache, targetConnectionId.value, targetDatabase.value, targetSchema.value, task.targetTable);
+ const columns = sourceColumns.map((column) => column.name).filter((column) => targetColumns.some((target) => target.name === column));
+ const columnInfo = columns.map((column) => targetColumns.find((target) => target.name === column)).filter((column): column is CompareColumn => !!column);
const missingKeys = resolvedKeys.filter((column) => !columns.includes(column));
if (missingKeys.length > 0) {
throw new Error(t("dataCompare.missingKeyColumns", { columns: missingKeys.join(", ") }));
@@ -883,12 +768,7 @@ function formatRowValues(values: Record<string, DataCompareCellValue>): string {
}
function formatModifiedSummary(row: SelectableDataCompareModifiedRow): string {
- return truncateText(
- row.changes
- .map((change) => `${change.column}: ${formatValue(change.target)} -> ${formatValue(change.source)}`)
- .join(", "),
- 220,
- );
+ return truncateText(row.changes.map((change) => `${change.column}: ${formatValue(change.target)} -> ${formatValue(change.source)}`).join(", "), 220);
}
watch(sourceConnectionId, (id) => {
@@ -999,17 +879,10 @@ watch(
<div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
<div class="space-y-2">
<Label class="text-xs font-medium">{{ t("diff.source") }}</Label>
- <Select
- :model-value="sourceConnectionId"
- @update:model-value="(v: any) => (sourceConnectionId = String(v))"
- >
+ <Select :model-value="sourceConnectionId" @update:model-value="(v: any) => (sourceConnectionId = String(v))">
<SelectTrigger class="h-8 text-xs">
<div class="flex items-center gap-2">
- <DatabaseIcon
- v-if="sourceConnectionId"
- :db-type="connectionIconType(sourceConnectionId)"
- class="w-3.5 h-3.5"
- />
+ <DatabaseIcon v-if="sourceConnectionId" :db-type="connectionIconType(sourceConnectionId)" class="w-3.5 h-3.5" />
<SelectValue :placeholder="t('diff.selectConnection')" />
</div>
</SelectTrigger>
@@ -1022,16 +895,10 @@ watch(
<Select :model-value="sourceDatabase" @update:model-value="(v: any) => (sourceDatabase = String(v))">
<SelectTrigger class="h-8 text-xs"><SelectValue :placeholder="t('diff.selectDatabase')" /></SelectTrigger>
<SelectContent>
- <SelectItem v-for="database in sourceDatabases" :key="database" :value="database">{{
- database
- }}</SelectItem>
+ <SelectItem v-for="database in sourceDatabases" :key="database" :value="database">{{ database }}</SelectItem>
</SelectContent>
</Select>
- <Select
- v-if="sourceSchemas.length"
- :model-value="sourceSchema"
- @update:model-value="(v: any) => (sourceSchema = String(v))"
- >
+ <Select v-if="sourceSchemas.length" :model-value="sourceSchema" @update:model-value="(v: any) => (sourceSchema = String(v))">
<SelectTrigger class="h-8 text-xs"><SelectValue :placeholder="t('diff.selectSchema')" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="schema in sourceSchemas" :key="schema" :value="schema">{{ schema }}</SelectItem>
@@ -1051,24 +918,11 @@ watch(
</div>
</div>
- <Input
- v-if="sourceTables.length > 5"
- v-model="sourceTableSearch"
- class="h-7 text-xs"
- :placeholder="t('dataCompare.searchTables')"
- />
+ <Input v-if="sourceTables.length > 5" v-model="sourceTableSearch" class="h-7 text-xs" :placeholder="t('dataCompare.searchTables')" />
<div class="flex items-center gap-2">
- <Button
- v-if="sourceTables.length"
- variant="outline"
- size="sm"
- class="h-7 px-2 text-xs"
- @click="toggleSelectAllSourceTables"
- >
- {{
- allFilteredTablesSelected ? t("dataCompare.deselectAllTables") : t("dataCompare.selectAllTables")
- }}
+ <Button v-if="sourceTables.length" variant="outline" size="sm" class="h-7 px-2 text-xs" @click="toggleSelectAllSourceTables">
+ {{ allFilteredTablesSelected ? t("dataCompare.deselectAllTables") : t("dataCompare.selectAllTables") }}
</Button>
</div>
@@ -1079,13 +933,7 @@ watch(
{{ t("dataCompare.noTables") }}
</div>
<div v-else class="max-h-40 overflow-auto rounded border">
- <button
- v-for="table in filteredSourceTables"
- :key="table"
- type="button"
- class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs hover:bg-muted/50"
- @click="toggleSourceTable(table)"
- >
+ <button v-for="table in filteredSourceTables" :key="table" type="button" class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs hover:bg-muted/50" @click="toggleSourceTable(table)">
<CheckSquare v-if="selectedSourceTables.has(table)" class="w-3.5 h-3.5 text-primary shrink-0" />
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
<span class="truncate">{{ table }}</span>
@@ -1102,17 +950,10 @@ watch(
<div class="space-y-2">
<Label class="text-xs font-medium">{{ t("diff.target") }}</Label>
- <Select
- :model-value="targetConnectionId"
- @update:model-value="(v: any) => (targetConnectionId = String(v))"
- >
+ <Select :model-value="targetConnectionId" @update:model-value="(v: any) => (targetConnectionId = String(v))">
<SelectTrigger class="h-8 text-xs">
<div class="flex items-center gap-2">
- <DatabaseIcon
- v-if="targetConnectionId"
- :db-type="connectionIconType(targetConnectionId)"
- class="w-3.5 h-3.5"
- />
+ <DatabaseIcon v-if="targetConnectionId" :db-type="connectionIconType(targetConnectionId)" class="w-3.5 h-3.5" />
<SelectValue :placeholder="t('diff.selectConnection')" />
</div>
</SelectTrigger>
@@ -1125,16 +966,10 @@ watch(
<Select :model-value="targetDatabase" @update:model-value="(v: any) => (targetDatabase = String(v))">
<SelectTrigger class="h-8 text-xs"><SelectValue :placeholder="t('diff.selectDatabase')" /></SelectTrigger>
<SelectContent>
- <SelectItem v-for="database in targetDatabases" :key="database" :value="database">{{
- database
- }}</SelectItem>
+ <SelectItem v-for="database in targetDatabases" :key="database" :value="database">{{ database }}</SelectItem>
</SelectContent>
</Select>
- <Select
- v-if="targetSchemas.length"
- :model-value="targetSchema"
- @update:model-value="(v: any) => (targetSchema = String(v))"
- >
+ <Select v-if="targetSchemas.length" :model-value="targetSchema" @update:model-value="(v: any) => (targetSchema = String(v))">
<SelectTrigger class="h-8 text-xs"><SelectValue :placeholder="t('diff.selectSchema')" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="schema in targetSchemas" :key="schema" :value="schema">{{ schema }}</SelectItem>
@@ -1155,19 +990,13 @@ watch(
<div v-else class="space-y-2 rounded-lg border p-3 text-xs">
<div class="font-medium">{{ t("dataCompare.autoMatchHint") }}</div>
<div class="text-muted-foreground">
- {{
- t("dataCompare.matchedTables", { matched: matchedTaskCount, total: selectedSourceTableNames.length })
- }}
+ {{ t("dataCompare.matchedTables", { matched: matchedTaskCount, total: selectedSourceTableNames.length }) }}
</div>
<div v-if="missingTargetTables.length" class="text-destructive">
{{ t("dataCompare.missingTargetTables", { tables: missingTargetTables.join(", ") }) }}
</div>
<div v-if="compareTasksPreview.length" class="max-h-36 overflow-auto rounded border bg-muted/20">
- <div
- v-for="task in compareTasksPreview"
- :key="`${task.sourceTable}:${task.targetTable}`"
- class="flex items-center justify-between gap-2 border-b px-2 py-1 last:border-b-0"
- >
+ <div v-for="task in compareTasksPreview" :key="`${task.sourceTable}:${task.targetTable}`" class="flex items-center justify-between gap-2 border-b px-2 py-1 last:border-b-0">
<span class="truncate font-mono">{{ task.sourceTable }}</span>
<span class="text-muted-foreground">→</span>
<span class="truncate font-mono" :class="task.matched ? '' : 'text-destructive'">
@@ -1195,33 +1024,9 @@ watch(
<div class="rounded-lg border p-3 space-y-3">
<div class="flex flex-wrap items-center gap-2">
- <Button
- size="sm"
- variant="outline"
- class="h-7 text-xs"
- :class="showAdded ? 'border-primary' : ''"
- @click="showAdded = !showAdded"
- >
- {{ t("diff.added") }} · {{ totalAdded }}
- </Button>
- <Button
- size="sm"
- variant="outline"
- class="h-7 text-xs"
- :class="showRemoved ? 'border-primary' : ''"
- @click="showRemoved = !showRemoved"
- >
- {{ t("diff.removed") }} · {{ totalRemoved }}
- </Button>
- <Button
- size="sm"
- variant="outline"
- class="h-7 text-xs"
- :class="showModified ? 'border-primary' : ''"
- @click="showModified = !showModified"
- >
- {{ t("diff.modified") }} · {{ totalModified }}
- </Button>
+ <Button size="sm" variant="outline" class="h-7 text-xs" :class="showAdded ? 'border-primary' : ''" @click="showAdded = !showAdded"> {{ t("diff.added") }} · {{ totalAdded }} </Button>
+ <Button size="sm" variant="outline" class="h-7 text-xs" :class="showRemoved ? 'border-primary' : ''" @click="showRemoved = !showRemoved"> {{ t("diff.removed") }} · {{ totalRemoved }} </Button>
+ <Button size="sm" variant="outline" class="h-7 text-xs" :class="showModified ? 'border-primary' : ''" @click="showModified = !showModified"> {{ t("diff.modified") }} · {{ totalModified }} </Button>
<span class="flex-1" />
<Select v-model="detailPreviewLimit">
<SelectTrigger class="h-7 w-32 text-xs">
@@ -1297,10 +1102,7 @@ watch(
<div v-if="item.status === 'different'" class="mt-1">
{{
t("dataCompare.selectedInline", {
- selected:
- selectedRows(item, "added") +
- selectedRows(item, "removed") +
- selectedRows(item, "modified"),
+ selected: selectedRows(item, "added") + selectedRows(item, "removed") + selectedRows(item, "modified"),
total: item.added + item.removed + item.modified,
})
}}
@@ -1314,16 +1116,8 @@ watch(
</div>
<div class="space-y-3">
- <div
- v-for="item in batchResults.filter((entry) => entry.status === 'different')"
- :key="`details-${item.sourceTable}:${item.targetTable}`"
- class="rounded-lg border overflow-hidden"
- >
- <button
- type="button"
- class="flex w-full items-center gap-2 border-b bg-muted/30 px-3 py-2 text-left text-sm font-medium"
- @click="toggleTableExpanded(item)"
- >
+ <div v-for="item in batchResults.filter((entry) => entry.status === 'different')" :key="`details-${item.sourceTable}:${item.targetTable}`" class="rounded-lg border overflow-hidden">
+ <button type="button" class="flex w-full items-center gap-2 border-b bg-muted/30 px-3 py-2 text-left text-sm font-medium" @click="toggleTableExpanded(item)">
<ChevronDown v-if="item.expanded" class="h-4 w-4 shrink-0" />
<ChevronRight v-else class="h-4 w-4 shrink-0" />
<span class="font-mono">{{ item.sourceTable }}</span>
@@ -1332,76 +1126,36 @@ watch(
</button>
<div v-if="item.expanded" class="space-y-3 p-3">
- <div
- v-for="kind in visibleKinds"
- :key="`${item.sourceTable}:${kind}`"
- class="rounded-lg border"
- v-show="hasDiffRows(item, kind)"
- >
+ <div v-for="kind in visibleKinds" :key="`${item.sourceTable}:${kind}`" class="rounded-lg border" v-show="hasDiffRows(item, kind)">
<div class="flex flex-wrap items-center gap-2 border-b bg-muted/20 px-3 py-2 text-xs">
<span class="font-medium">{{ t(`diff.${kind}`) }}</span>
- <span class="text-muted-foreground"
- >{{ selectedRows(item, kind) }}/{{ item.diff[kind].length }}</span
- >
+ <span class="text-muted-foreground">{{ selectedRows(item, kind) }}/{{ item.diff[kind].length }}</span>
<span class="flex-1" />
- <Button
- size="sm"
- variant="ghost"
- class="h-6 px-2 text-xs"
- @click="setTableDiffSelection(item, kind, true)"
- >
+ <Button size="sm" variant="ghost" class="h-6 px-2 text-xs" @click="setTableDiffSelection(item, kind, true)">
{{ t("dataCompare.selectAllKind", { kind: t(`diff.${kind}`) }) }}
</Button>
- <Button
- size="sm"
- variant="ghost"
- class="h-6 px-2 text-xs"
- @click="setTableDiffSelection(item, kind, false)"
- >
+ <Button size="sm" variant="ghost" class="h-6 px-2 text-xs" @click="setTableDiffSelection(item, kind, false)">
{{ t("dataCompare.clearKind", { kind: t(`diff.${kind}`) }) }}
</Button>
- <Button
- v-if="item.diff[kind].length > detailPreviewLimitNumber"
- size="sm"
- variant="ghost"
- class="h-6 px-2 text-xs"
- @click="toggleShowAll(item, kind)"
- >
- {{
- item.showAll[kind]
- ? t("dataCompare.showLessRows")
- : t("dataCompare.showAllRows", { count: item.diff[kind].length })
- }}
+ <Button v-if="item.diff[kind].length > detailPreviewLimitNumber" size="sm" variant="ghost" class="h-6 px-2 text-xs" @click="toggleShowAll(item, kind)">
+ {{ item.showAll[kind] ? t("dataCompare.showLessRows") : t("dataCompare.showAllRows", { count: item.diff[kind].length }) }}
</Button>
</div>
<div class="max-h-72 overflow-auto divide-y">
- <button
- v-for="row in rowsForDisplay(item, kind)"
- :key="`${item.sourceTable}:${kind}:${row.key}`"
- type="button"
- class="flex w-full items-start gap-3 px-3 py-2 text-left text-xs hover:bg-muted/40"
- @click="toggleRowSelection(row)"
- >
+ <button v-for="row in rowsForDisplay(item, kind)" :key="`${item.sourceTable}:${kind}:${row.key}`" type="button" class="flex w-full items-start gap-3 px-3 py-2 text-left text-xs hover:bg-muted/40" @click="toggleRowSelection(row)">
<CheckSquare v-if="row.selected" class="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
<Square v-else class="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/40" />
<div class="min-w-0 flex-1">
<div class="font-mono">{{ formatKeyValues(row.keyValues) }}</div>
<div class="mt-1 text-muted-foreground break-words">
- {{
- kind === "modified"
- ? formatModifiedSummary(row as SelectableDataCompareModifiedRow)
- : formatRowValues((row as SelectableDataCompareRow).values)
- }}
+ {{ kind === "modified" ? formatModifiedSummary(row as SelectableDataCompareModifiedRow) : formatRowValues((row as SelectableDataCompareRow).values) }}
</div>
</div>
</button>
</div>
- <div
- v-if="remainingRows(item, kind) > 0 && !item.showAll[kind]"
- class="border-t px-3 py-2 text-xs text-muted-foreground"
- >
+ <div v-if="remainingRows(item, kind) > 0 && !item.showAll[kind]" class="border-t px-3 py-2 text-xs text-muted-foreground">
{{ t("dataCompare.remainingRows", { count: remainingRows(item, kind) }) }}
</div>
</div>
@@ -1414,11 +1168,7 @@ watch(
</div>
<div v-else-if="syncPlan.syncSql.trim()" class="space-y-1">
<Label class="text-xs font-medium">{{ t("diff.generatedSql") }}</Label>
- <textarea
- :value="syncPlan.syncSql"
- readonly
- class="w-full h-48 rounded-lg border bg-muted/20 p-3 font-mono text-xs resize-none focus:outline-none focus:ring-1 focus:ring-ring"
- />
+ <textarea :value="syncPlan.syncSql" readonly class="w-full h-48 rounded-lg border bg-muted/20 p-3 font-mono text-xs resize-none focus:outline-none focus:ring-1 focus:ring-ring" />
</div>
<div v-else-if="differentTableCount === 0 && failedTableCount === 0" class="text-sm text-muted-foreground">
{{ t("dataCompare.noDifferences") }}
@@ -1435,9 +1185,7 @@ watch(
<div class="max-h-32 overflow-auto border rounded-lg bg-destructive/5 p-2 space-y-1">
<div v-for="(err, i) in syncErrors" :key="i" class="text-xs font-mono">
<span class="text-destructive">{{ err.error }}</span>
- <span class="text-muted-foreground ml-1"
- >— {{ err.sql.slice(0, 80) }}{{ err.sql.length > 80 ? "..." : "" }}</span
- >
+ <span class="text-muted-foreground ml-1">— {{ err.sql.slice(0, 80) }}{{ err.sql.length > 80 ? "..." : "" }}</span>
</div>
</div>
</div>
@@ -1445,9 +1193,7 @@ watch(
<DialogFooter v-if="!hasResults">
<Button variant="outline" @click="open = false">{{ t("common.close") }}</Button>
- <span v-if="compareProgressLabel" class="text-xs text-muted-foreground self-center">{{
- compareProgressLabel
- }}</span>
+ <span v-if="compareProgressLabel" class="text-xs text-muted-foreground self-center">{{ compareProgressLabel }}</span>
<Button size="sm" :disabled="!canCompare || comparing" @click="startCompare">
<Loader2 v-if="comparing" class="w-3.5 h-3.5 animate-spin mr-1" />
<GitCompareArrows v-else class="w-3.5 h-3.5 mr-1" />
@@ -1473,9 +1219,7 @@ watch(
})
}}
</span>
- <Button variant="outline" size="sm" :disabled="!syncPlan.syncSql.trim()" @click="copySql">
- <Copy class="w-3 h-3 mr-1" /> {{ t("diff.copySql") }}
- </Button>
+ <Button variant="outline" size="sm" :disabled="!syncPlan.syncSql.trim()" @click="copySql"> <Copy class="w-3 h-3 mr-1" /> {{ t("diff.copySql") }} </Button>
<Button size="sm" :disabled="planningSync || executing || syncPlan.statementCount === 0" @click="executeSql">
<Loader2 v-if="executing" class="w-3 h-3 animate-spin mr-1" />
<Play v-else class="w-3 h-3 mr-1" />
diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
index 46b66466a1..f05c937ef9 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
@@ -67,19 +67,9 @@ function toggleAll() {
refreshSelectedSyncSql().catch((e) => toast(e?.message || String(e), 5000));
}
-const sqlConnections = computed(() =>
- store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)),
-);
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)));
-const canCompare = computed(
- () =>
- sourceConnectionId.value &&
- sourceDatabase.value &&
- sourceSchema.value &&
- targetConnectionId.value &&
- targetDatabase.value &&
- targetSchema.value,
-);
+const canCompare = computed(() => sourceConnectionId.value && sourceDatabase.value && sourceSchema.value && targetConnectionId.value && targetDatabase.value && targetSchema.value);
function connectionIconType(connectionId: string) {
const config = store.getConfig(connectionId);
@@ -151,12 +141,7 @@ async function loadSchemas(side: "source" | "target", preferredSchema = "") {
}
const schemas = await api.listSchemas(connectionId, database);
- const selected =
- preferredSchema && schemas.includes(preferredSchema)
- ? preferredSchema
- : schemas.includes("public")
- ? "public"
- : (schemas[0] ?? "");
+ const selected = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
if (side === "source") {
sourceSchemas.value = schemas;
sourceSchema.value = selected;
@@ -177,10 +162,7 @@ async function startCompare() {
await store.ensureConnected(targetConnectionId.value);
const targetConfig = store.getConfig(targetConnectionId.value);
- const [srcTables, tgtTables] = await Promise.all([
- api.listTables(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value),
- api.listTables(targetConnectionId.value, targetDatabase.value, targetSchema.value),
- ]);
+ const [srcTables, tgtTables] = await Promise.all([api.listTables(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value), api.listTables(targetConnectionId.value, targetDatabase.value, targetSchema.value)]);
const { sourceDetails, targetDetails } = await loadSchemaDiffDetails(srcTables, tgtTables);
const result = await api.prepareSchemaDiff({
@@ -379,10 +361,7 @@ watch(
<template>
<Dialog v-model:open="open">
- <DialogContent
- class="min-w-[min(720px,calc(100vw-2rem))] resize-x sm:max-w-5xl max-h-[80vh] flex flex-col overflow-hidden"
- @interact-outside.prevent
- >
+ <DialogContent class="min-w-[min(720px,calc(100vw-2rem))] resize-x sm:max-w-5xl max-h-[80vh] flex flex-col overflow-hidden" @interact-outside.prevent>
<DialogHeader>
<DialogTitle class="flex items-center gap-2">
<GitCompareArrows class="w-4 h-4" />
@@ -395,17 +374,10 @@ watch(
<div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
<div class="space-y-2">
<Label class="text-xs font-medium">{{ t("diff.source") }}</Label>
- <Select
- :model-value="sourceConnectionId"
- @update:model-value="(v: any) => (sourceConnectionId = String(v))"
- >
+ <Select :model-value="sourceConnectionId" @update:model-value="(v: any) => (sourceConnectionId = String(v))">
<SelectTrigger class="h-8 text-xs">
<div class="flex items-center gap-2">
- <DatabaseIcon
- v-if="sourceConnectionId"
- :db-type="connectionIconType(sourceConnectionId)"
- class="w-3.5 h-3.5"
- />
+ <DatabaseIcon v-if="sourceConnectionId" :db-type="connectionIconType(sourceConnectionId)" class="w-3.5 h-3.5" />
<SelectValue :placeholder="t('diff.selectConnection')" />
</div>
</SelectTrigger>
@@ -418,11 +390,7 @@ watch(
</SelectItem>
</SelectContent>
</Select>
- <Select
- v-if="sourceDatabases.length"
- :model-value="sourceDatabase"
- @update:model-value="(v: any) => (sourceDatabase = String(v))"
- >
+ <Select v-if="sourceDatabases.length" :model-value="sourceDatabase" @update:model-value="(v: any) => (sourceDatabase = String(v))">
<SelectTrigger class="h-8 text-xs">
<SelectValue :placeholder="t('diff.selectDatabase')" />
</SelectTrigger>
@@ -430,11 +398,7 @@ watch(
<SelectItem v-for="db in sourceDatabases" :key="db" :value="db">{{ db }}</SelectItem>
</SelectContent>
</Select>
- <Select
- v-if="sourceSchemas.length"
- :model-value="sourceSchema"
- @update:model-value="(v: any) => (sourceSchema = String(v))"
- >
+ <Select v-if="sourceSchemas.length" :model-value="sourceSchema" @update:model-value="(v: any) => (sourceSchema = String(v))">
<SelectTrigger class="h-8 text-xs">
<SelectValue :placeholder="t('diff.selectSchema')" />
</SelectTrigger>
@@ -452,17 +416,10 @@ watch(
<div class="space-y-2">
<Label class="text-xs font-medium">{{ t("diff.target") }}</Label>
- <Select
- :model-value="targetConnectionId"
- @update:model-value="(v: any) => (targetConnectionId = String(v))"
- >
+ <Select :model-value="targetConnectionId" @update:model-value="(v: any) => (targetConnectionId = String(v))">
<SelectTrigger class="h-8 text-xs">
<div class="flex items-center gap-2">
- <DatabaseIcon
- v-if="targetConnectionId"
- :db-type="connectionIconType(targetConnectionId)"
- class="w-3.5 h-3.5"
- />
+ <DatabaseIcon v-if="targetConnectionId" :db-type="connectionIconType(targetConnectionId)" class="w-3.5 h-3.5" />
<SelectValue :placeholder="t('diff.selectConnection')" />
</div>
</SelectTrigger>
@@ -475,11 +432,7 @@ watch(
</SelectItem>
</SelectContent>
</Select>
- <Select
- v-if="targetDatabases.length"
- :model-value="targetDatabase"
- @update:model-value="(v: any) => (targetDatabase = String(v))"
- >
+ <Select v-if="targetDatabases.length" :model-value="targetDatabase" @update:model-value="(v: any) => (targetDatabase = String(v))">
<SelectTrigger class="h-8 text-xs">
<SelectValue :placeholder="t('diff.selectDatabase')" />
</SelectTrigger>
@@ -487,11 +440,7 @@ watch(
<SelectItem v-for="db in targetDatabases" :key="db" :value="db">{{ db }}</SelectItem>
</SelectContent>
</Select>
- <Select
- v-if="targetSchemas.length"
- :model-value="targetSchema"
- @update:model-value="(v: any) => (targetSchema = String(v))"
- >
+ <Select v-if="targetSchemas.length" :model-value="targetSchema" @update:model-value="(v: any) => (targetSchema = String(v))">
<SelectTrigger class="h-8 text-xs">
<SelectValue :placeholder="t('diff.selectSchema')" />
</SelectTrigger>
@@ -529,13 +478,7 @@ watch(
<thead class="bg-muted sticky top-0 z-10">
<tr>
<th class="px-2 py-2 w-8">
- <input
- type="checkbox"
- class="accent-primary"
- :checked="allSelected"
- :indeterminate="someSelected"
- @change="toggleAll"
- />
+ <input type="checkbox" class="accent-primary" :checked="allSelected" :indeterminate="someSelected" @change="toggleAll" />
</th>
<th class="text-left px-3 py-2 font-medium w-1/4">{{ t("diff.table") }}</th>
<th class="text-left px-3 py-2 font-medium w-16">{{ t("diff.status") }}</th>
@@ -545,12 +488,7 @@ watch(
<tbody>
<tr v-for="d in diffs" :key="d.name" class="border-t border-border/50 hover:bg-accent/30">
<td class="px-2 py-1.5">
- <input
- v-model="d.selected"
- type="checkbox"
- class="accent-primary"
- @change="onDiffSelectionChange"
- />
+ <input v-model="d.selected" type="checkbox" class="accent-primary" @change="onDiffSelectionChange" />
</td>
<td class="px-3 py-1.5 font-mono truncate">{{ d.name }}</td>
<td class="px-3 py-1.5">
@@ -612,17 +550,13 @@ watch(
'text-red-500': trigger.type === 'removed',
'text-yellow-500': trigger.type === 'modified',
}"
- >{{ trigger.type === "added" ? "+" : trigger.type === "removed" ? "-" : "~"
- }}{{ trigger.name }}</span
+ >{{ trigger.type === "added" ? "+" : trigger.type === "removed" ? "-" : "~" }}{{ trigger.name }}</span
>
<span v-if="ti < d.triggers!.length - 1">, </span>
</span>
</template>
<template v-if="d.type === 'modified' && d.sourceTableComment !== undefined">
- <span
- v-if="d.columns?.length || d.indexes?.length || d.foreignKeys?.length || d.triggers?.length"
- >;
- </span>
+ <span v-if="d.columns?.length || d.indexes?.length || d.foreignKeys?.length || d.triggers?.length">; </span>
<span>{{ t("diff.comments") }}</span>
</template>
<span v-else-if="d.type === 'added'" class="text-green-500">{{ t("diff.newTable") }}</span>
@@ -637,10 +571,7 @@ watch(
<!-- SQL Preview -->
<div class="space-y-1">
<Label class="text-xs font-medium">{{ t("diff.generatedSql") }}</Label>
- <pre
- class="w-full h-48 overflow-auto rounded-lg border bg-muted/20 p-3 font-mono text-xs whitespace-pre"
- v-html="highlightedSyncSql"
- ></pre>
+ <pre class="w-full h-48 overflow-auto rounded-lg border bg-muted/20 p-3 font-mono text-xs whitespace-pre" v-html="highlightedSyncSql"></pre>
</div>
<!-- Sync Errors -->
@@ -651,9 +582,7 @@ watch(
<div class="max-h-32 overflow-auto border rounded-lg bg-destructive/5 p-2 space-y-1">
<div v-for="(err, i) in syncErrors" :key="i" class="text-xs font-mono">
<span class="text-destructive">{{ err.error }}</span>
- <span class="text-muted-foreground ml-1"
- >— {{ err.sql.slice(0, 80) }}{{ err.sql.length > 80 ? "..." : "" }}</span
- >
+ <span class="text-muted-foreground ml-1">— {{ err.sql.slice(0, 80) }}{{ err.sql.length > 80 ? "..." : "" }}</span>
</div>
</div>
</div>
@@ -674,9 +603,7 @@ watch(
<span v-if="executing" class="text-xs text-muted-foreground mr-auto">
{{ t("diff.syncProgress", { current: executedCount, total: executeTotal }) }}
</span>
- <Button variant="outline" size="sm" @click="copySql">
- <Copy class="w-3 h-3 mr-1" /> {{ t("diff.copySql") }}
- </Button>
+ <Button variant="outline" size="sm" @click="copySql"> <Copy class="w-3 h-3 mr-1" /> {{ t("diff.copySql") }} </Button>
<Button size="sm" :disabled="!syncSql.trim() || executing" @click="executeSql">
<Loader2 v-if="executing" class="w-3 h-3 animate-spin mr-1" />
<Play v-else class="w-3 h-3 mr-1" />
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vue
index bc755fa72b..6ae3a452ea 100644
--- a/apps/desktop/src/components/editor/AiAssistant.vue
+++ b/apps/desktop/src/components/editor/AiAssistant.vue
@@ -3,34 +3,7 @@ import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";
import { uuid } from "@/lib/utils";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
-import {
- ArrowUp,
- ArrowRightLeft,
- AlertTriangle,
- Bot,
- Check,
- ChevronRight,
- CircleSlash,
- Copy,
- Database,
- HelpCircle,
- History,
- Loader2,
- MessageSquarePlus,
- Replace,
- Server,
- ShieldCheck,
- Table2,
- Play,
- Square,
- Trash2,
- Terminal,
- Wand2,
- Wrench,
- X,
- Zap,
- TestTube,
-} from "@lucide/vue";
+import { ArrowUp, ArrowRightLeft, AlertTriangle, Bot, Check, ChevronRight, CircleSlash, Copy, Database, HelpCircle, History, Loader2, MessageSquarePlus, Replace, Server, ShieldCheck, Table2, Play, Square, Trash2, Terminal, Wand2, Wrench, X, Zap, TestTube } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -49,24 +22,11 @@ import { buildAiAgentStepItems, type AiAgentStepItem, type AiAgentStepTone } fro
import { createAiShikiCodeHighlighter, type AiCodeHighlighter } from "@/lib/aiCodeHighlighter";
import { createAiMessageRenderer } from "@/lib/aiMessageRender";
import { Marked } from "marked";
-import {
- aiCancelStream,
- saveAiConversation,
- loadAiConversations,
- deleteAiConversation,
- listSchemas,
- listTables,
- type AiConversation,
-} from "@/lib/api";
+import { aiCancelStream, saveAiConversation, loadAiConversations, deleteAiConversation, listSchemas, listTables, type AiConversation } from "@/lib/api";
import type { AiMessage } from "@/lib/api";
import type { ConnectionConfig, QueryTab, TableInfo } from "@/types/database";
import { useDatabaseOptions } from "@/composables/useDatabaseOptions";
-import {
- decodeSelectableDatabaseValue,
- encodeSelectableDatabaseValue,
- formatDatabaseLabel,
- resolveDefaultDatabase,
-} from "@/lib/defaultDatabase";
+import { decodeSelectableDatabaseValue, encodeSelectableDatabaseValue, formatDatabaseLabel, resolveDefaultDatabase } from "@/lib/defaultDatabase";
import { isSchemaAware } from "@/lib/databaseCapabilities";
import { copyToClipboard } from "@/lib/clipboard";
import { formatAiTableMention, parseAiTableMentions, type AiTableMention } from "@/lib/aiTableMentions";
@@ -162,9 +122,7 @@ const isWaitingForFirstDelta = computed(() => {
return isGenerating.value && last?.role === "assistant" && !last.content && !last.reasoning;
});
-const activePlaceholder = computed(
- () => `${t(`ai.placeholders.${activeAction.value}`)} ${t("ai.tableMentionPlaceholderHint")}`,
-);
+const activePlaceholder = computed(() => `${t(`ai.placeholders.${activeAction.value}`)} ${t("ai.tableMentionPlaceholderHint")}`);
const activeModeHint = computed(() => t(`ai.modeHints.${assistantMode.value}`));
const assistantModeItems = computed(() => [
{
@@ -209,9 +167,7 @@ const dbSelectOptions = computed(() => {
}));
});
-const selectedDatabaseSelectValue = computed(() =>
- props.connection ? encodeSelectableDatabaseValue(props.connection.db_type, props.tab?.database || "") : "",
-);
+const selectedDatabaseSelectValue = computed(() => (props.connection ? encodeSelectableDatabaseValue(props.connection.db_type, props.tab?.database || "") : ""));
const selectedDatabaseLabel = computed(() => {
if (!props.connection) return t("editor.selectDatabase");
@@ -373,18 +329,10 @@ async function loadMentionCandidates(query: string) {
let candidates: AiMentionCandidate[] = [];
if (isSchemaAware(props.connection.db_type)) {
const schemas = mentionSchemaOrder(await listSchemas(props.tab.connectionId, props.tab.database));
- const filteredSchemas = schemaPrefix
- ? schemas.filter((schema) => schema.toLowerCase().includes(schemaPrefix.toLowerCase()))
- : schemas;
+ const filteredSchemas = schemaPrefix ? schemas.filter((schema) => schema.toLowerCase().includes(schemaPrefix.toLowerCase())) : schemas;
const results = await Promise.all(
filteredSchemas.slice(0, 8).map(async (schema) => {
- const tables = await listTables(
- props.tab!.connectionId,
- props.tab!.database,
- schema,
- tableFilter || undefined,
- 20,
- );
+ const tables = await listTables(props.tab!.connectionId, props.tab!.database, schema, tableFilter || undefined, 20);
return filterMentionCandidates(
tables.map((table) => mentionCandidateFromTable(table, schema)),
tableFilter,
@@ -432,8 +380,7 @@ function removeMentionChip(mention: AiTableMention) {
function addSelectedMention(candidate: AiMentionCandidate) {
const raw = formatAiTableMention(candidate.schema, candidate.name);
const key = `${candidate.schema || ""}.${candidate.name}`.toLowerCase();
- if (selectedMentions.value.some((mention) => `${mention.schema || ""}.${mention.table}`.toLowerCase() === key))
- return;
+ if (selectedMentions.value.some((mention) => `${mention.schema || ""}.${mention.table}`.toLowerCase() === key)) return;
selectedMentions.value.push({ raw, schema: candidate.schema, table: candidate.name });
}
@@ -445,15 +392,9 @@ function formatMentionTableType(tableType: string) {
return t("ai.tableMentionTypes.table");
}
-function filterMentionCandidates(
- candidates: AiMentionCandidate[],
- tableFilter: string,
- limit: number,
-): AiMentionCandidate[] {
+function filterMentionCandidates(candidates: AiMentionCandidate[], tableFilter: string, limit: number): AiMentionCandidate[] {
const normalizedFilter = tableFilter.toLowerCase();
- return candidates
- .filter((candidate) => !normalizedFilter || candidate.name.toLowerCase().includes(normalizedFilter))
- .slice(0, limit);
+ return candidates.filter((candidate) => !normalizedFilter || candidate.name.toLowerCase().includes(normalizedFilter)).slice(0, limit);
}
function refreshMentionState() {
@@ -492,10 +433,7 @@ function onPromptKeydown(event: KeyboardEvent) {
if (mentionOpen.value) {
if (event.key === "ArrowDown") {
event.preventDefault();
- mentionSelectedIndex.value = Math.min(
- mentionSelectedIndex.value + 1,
- Math.max(mentionCandidates.value.length - 1, 0),
- );
+ mentionSelectedIndex.value = Math.min(mentionSelectedIndex.value + 1, Math.max(mentionCandidates.value.length - 1, 0));
return;
}
if (event.key === "ArrowUp") {
@@ -718,10 +656,7 @@ const messageRenderer = computed(() => {
<template>
<div class="flex h-full min-h-0 flex-col overflow-hidden">
- <div
- class="flex items-center gap-2 border-b px-3 shrink-0"
- :class="settings.editorSettings.appLayout === 'classic' ? 'h-9' : 'h-10'"
- >
+ <div class="flex items-center gap-2 border-b px-3 shrink-0" :class="settings.editorSettings.appLayout === 'classic' ? 'h-9' : 'h-10'">
<span class="flex flex-1 self-stretch items-center truncate text-xs font-medium" data-tauri-drag-region>
{{ chatTitle }}
</span>
@@ -730,13 +665,7 @@ const messageRenderer = computed(() => {
</Button>
<Popover :open="showConversationList" @update:open="setConversationListOpen">
<PopoverTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :class="{ 'bg-accent': showConversationList }"
- :title="t('history.title')"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6" :class="{ 'bg-accent': showConversationList }" :title="t('history.title')">
<History class="h-3.5 w-3.5" />
</Button>
</PopoverTrigger>
@@ -751,18 +680,9 @@ const messageRenderer = computed(() => {
{{ t("history.empty") }}
</div>
<div v-else class="max-h-64 overflow-auto p-1">
- <div
- v-for="conv in conversations"
- :key="conv.id"
- class="flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-muted"
- :class="{ 'bg-muted': conv.id === conversationId }"
- @click="selectConversation(conv)"
- >
+ <div v-for="conv in conversations" :key="conv.id" class="flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-muted" :class="{ 'bg-muted': conv.id === conversationId }" @click="selectConversation(conv)">
<span class="min-w-0 flex-1 truncate">{{ conv.title }}</span>
- <button
- class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-background hover:text-destructive"
- @click.stop="deleteConversation(conv.id)"
- >
+ <button class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-background hover:text-destructive" @click.stop="deleteConversation(conv.id)">
<X class="h-3 w-3" />
</button>
</div>
@@ -777,10 +697,7 @@ const messageRenderer = computed(() => {
</Button>
</div>
- <div
- v-if="messages.length === 0"
- class="flex-1 min-h-0 flex flex-col items-center justify-center text-center text-muted-foreground"
- >
+ <div v-if="messages.length === 0" class="flex-1 min-h-0 flex flex-col items-center justify-center text-center text-muted-foreground">
<Bot class="h-10 w-10 mb-3 opacity-30" />
<p class="text-sm">{{ t("ai.welcome") }}</p>
</div>
@@ -796,14 +713,8 @@ const messageRenderer = computed(() => {
<div v-else-if="msg.content || msg.reasoning || msg.isThinking" class="flex">
<div class="max-w-[95%] rounded-lg bg-muted px-3 py-2 text-xs leading-relaxed">
<div v-if="msg.reasoning || msg.isThinking" class="mb-2">
- <button
- class="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors"
- @click="toggleReasoning(i)"
- >
- <ChevronRight
- class="h-3 w-3 transition-transform duration-200"
- :class="{ 'rotate-90': expandedReasoning.has(i) || msg.isThinking }"
- />
+ <button class="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors" @click="toggleReasoning(i)">
+ <ChevronRight class="h-3 w-3 transition-transform duration-200" :class="{ 'rotate-90': expandedReasoning.has(i) || msg.isThinking }" />
<Loader2 v-if="msg.isThinking" class="h-3 w-3 animate-spin" />
<span>{{ t("ai.reasoningProcess") }}</span>
</button>
@@ -814,21 +725,13 @@ const messageRenderer = computed(() => {
opacity: expandedReasoning.has(i) || msg.isThinking ? '1' : '0',
}"
>
- <div
- class="mt-1.5 pl-4 border-l-2 border-muted-foreground/20 text-[11px] text-muted-foreground whitespace-pre-wrap"
- >
+ <div class="mt-1.5 pl-4 border-l-2 border-muted-foreground/20 text-[11px] text-muted-foreground whitespace-pre-wrap">
{{ msg.reasoning }}
</div>
</div>
</div>
<div v-if="msg.agentSteps?.length" class="mb-2 flex flex-wrap gap-1.5">
- <span
- v-for="step in msg.agentSteps"
- :key="step.key"
- class="inline-flex h-5 max-w-full items-center gap-1 rounded-full border px-1.5 text-[10px] font-medium"
- :class="agentStepClass(step.tone)"
- :title="agentStepTitle(step)"
- >
+ <span v-for="step in msg.agentSteps" :key="step.key" class="inline-flex h-5 max-w-full items-center gap-1 rounded-full border px-1.5 text-[10px] font-medium" :class="agentStepClass(step.tone)" :title="agentStepTitle(step)">
<component :is="agentStepIcon(step.tone)" class="h-3 w-3 shrink-0" />
<span class="truncate">{{ t(step.labelKey) }}</span>
</span>
@@ -837,38 +740,21 @@ const messageRenderer = computed(() => {
<div v-if="seg.type === 'text'" class="ai-markdown whitespace-normal">
<div v-html="seg.html" />
</div>
- <div
- v-else
- class="my-2 overflow-hidden rounded-md border border-zinc-200 bg-zinc-50 dark:border-zinc-700/50 dark:bg-zinc-900"
- >
- <div
- class="flex items-center border-b border-zinc-200 px-3 py-1.5 text-[10px] font-medium text-zinc-600 dark:border-zinc-700/50 dark:text-zinc-400"
- >
+ <div v-else class="my-2 overflow-hidden rounded-md border border-zinc-200 bg-zinc-50 dark:border-zinc-700/50 dark:bg-zinc-900">
+ <div class="flex items-center border-b border-zinc-200 px-3 py-1.5 text-[10px] font-medium text-zinc-600 dark:border-zinc-700/50 dark:text-zinc-400">
<component :is="seg.isSql ? Database : Terminal" class="h-3 w-3 mr-1.5" />
<span>{{ seg.lang }}</span>
<span class="flex-1" />
<div class="flex items-center gap-1.5">
- <button
- v-if="seg.isSql"
- class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200"
- :title="t('ai.executeSql')"
- @click="executeSql(seg.content)"
- >
+ <button v-if="seg.isSql" class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200" :title="t('ai.executeSql')" @click="executeSql(seg.content)">
<Play class="h-3.5 w-3.5" />
</button>
- <button
- v-if="seg.isSql"
- class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200"
- :title="t('ai.apply')"
- @click="applySql(seg.content)"
- >
+ <button v-if="seg.isSql" class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200" :title="t('ai.apply')" @click="applySql(seg.content)">
<Replace class="h-3.5 w-3.5" />
</button>
<button
class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200"
- :title="
- copiedIndex === `${i}-${j}` ? t('ai.copied') : t(seg.isSql ? 'ai.copySql' : 'ai.copyCode')
- "
+ :title="copiedIndex === `${i}-${j}` ? t('ai.copied') : t(seg.isSql ? 'ai.copySql' : 'ai.copyCode')"
@click="copyCode(seg.content, `${i}-${j}`)"
>
<Check v-if="copiedIndex === `${i}-${j}`" class="h-3.5 w-3.5 text-green-400" />
@@ -876,9 +762,7 @@ const messageRenderer = computed(() => {
</button>
</div>
</div>
- <pre
- class="ai-code-block whitespace-pre-wrap break-words p-3 text-xs leading-relaxed text-zinc-900 dark:text-zinc-100"
- ><code v-html="seg.html"></code></pre>
+ <pre class="ai-code-block whitespace-pre-wrap break-words p-3 text-xs leading-relaxed text-zinc-900 dark:text-zinc-100"><code v-html="seg.html"></code></pre>
</div>
</template>
</div>
@@ -898,12 +782,8 @@ const messageRenderer = computed(() => {
<DatabaseIcon v-if="connection" :db-type="connectionIconType(connection)" class="h-3 w-3 shrink-0" />
<Server v-else class="h-3 w-3 shrink-0" />
<Select :model-value="connection?.id || ''" @update:model-value="(v: any) => changeConnection(v)">
- <SelectTrigger
- class="h-5 w-auto border-0 rounded-md bg-transparent dark:bg-transparent p-0 px-1 text-xs text-foreground/80 shadow-none focus:ring-0 focus-visible:ring-0 [&_svg]:size-3"
- >
- <SelectValue :placeholder="t('editor.selectConnection')">{{
- connection?.name || t("editor.selectConnection")
- }}</SelectValue>
+ <SelectTrigger class="h-5 w-auto border-0 rounded-md bg-transparent dark:bg-transparent p-0 px-1 text-xs text-foreground/80 shadow-none focus:ring-0 focus-visible:ring-0 [&_svg]:size-3">
+ <SelectValue :placeholder="t('editor.selectConnection')">{{ connection?.name || t("editor.selectConnection") }}</SelectValue>
</SelectTrigger>
<SelectContent class="min-w-48">
<SelectItem v-for="conn in connectionStore.connections" :key="conn.id" :value="conn.id">
@@ -925,26 +805,17 @@ const messageRenderer = computed(() => {
}
"
>
- <SelectTrigger
- class="h-5 w-auto border-0 rounded-md bg-transparent dark:bg-transparent p-0 px-1 text-xs text-foreground/80 shadow-none focus:ring-0 focus-visible:ring-0 [&_svg]:size-3"
- >
+ <SelectTrigger class="h-5 w-auto border-0 rounded-md bg-transparent dark:bg-transparent p-0 px-1 text-xs text-foreground/80 shadow-none focus:ring-0 focus-visible:ring-0 [&_svg]:size-3">
<SelectValue :placeholder="t('editor.selectDatabase')">{{ selectedDatabaseLabel }}</SelectValue>
</SelectTrigger>
<SelectContent>
- <SelectItem v-for="option in dbSelectOptions" :key="option.value" :value="option.value">{{
- option.label
- }}</SelectItem>
- <SelectItem v-if="!dbSelectOptions.length && connection && tab" :value="selectedDatabaseSelectValue">{{
- selectedDatabaseLabel
- }}</SelectItem>
+ <SelectItem v-for="option in dbSelectOptions" :key="option.value" :value="option.value">{{ option.label }}</SelectItem>
+ <SelectItem v-if="!dbSelectOptions.length && connection && tab" :value="selectedDatabaseSelectValue">{{ selectedDatabaseLabel }}</SelectItem>
</SelectContent>
</Select>
</template>
</div>
- <div
- v-if="mentionOpen"
- class="absolute bottom-full left-2 right-2 z-20 mb-1 max-h-56 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md"
- >
+ <div v-if="mentionOpen" class="absolute bottom-full left-2 right-2 z-20 mb-1 max-h-56 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md">
<div v-if="mentionLoading" class="flex items-center gap-2 px-2 py-2 text-xs text-muted-foreground">
<Loader2 class="h-3.5 w-3.5 animate-spin" />
<span>{{ t("common.loading") }}</span>
@@ -969,9 +840,7 @@ const messageRenderer = computed(() => {
<span class="min-w-0 flex-1 truncate">
<template v-if="candidate.schema">{{ candidate.schema }}.</template>{{ candidate.name }}
</span>
- <span class="shrink-0 text-[10px] text-muted-foreground">{{
- formatMentionTableType(candidate.tableType)
- }}</span>
+ <span class="shrink-0 text-[10px] text-muted-foreground">{{ formatMentionTableType(candidate.tableType) }}</span>
</button>
</div>
</div>
@@ -1004,34 +873,13 @@ const messageRenderer = computed(() => {
@keydown="onPromptKeydown"
/>
<div class="flex items-center gap-1.5">
- <LightDropdown
- v-model="assistantMode"
- :items="assistantModeItems"
- :aria-label="activeModeHint"
- item-class="text-xs px-2"
- />
- <LightDropdown
- :model-value="activeAction"
- :items="actionMenuItems"
- content-class="w-max min-w-0"
- item-class="text-xs px-2"
- @update:model-value="(value) => selectAction(value as AiAction)"
- />
+ <LightDropdown v-model="assistantMode" :items="assistantModeItems" :aria-label="activeModeHint" item-class="text-xs px-2" />
+ <LightDropdown :model-value="activeAction" :items="actionMenuItems" content-class="w-max min-w-0" item-class="text-xs px-2" @update:model-value="(value) => selectAction(value as AiAction)" />
<span class="flex-1" />
- <button
- v-if="isGenerating"
- class="h-7 w-7 shrink-0 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center"
- :title="t('ai.stopGenerating')"
- @click="cancelStream"
- >
+ <button v-if="isGenerating" class="h-7 w-7 shrink-0 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center" :title="t('ai.stopGenerating')" @click="cancelStream">
<Square class="h-3.5 w-3.5" />
</button>
- <button
- v-else
- class="h-7 w-7 shrink-0 rounded-full bg-foreground text-background flex items-center justify-center disabled:opacity-30"
- :disabled="!prompt.trim() || !props.tab?.database"
- @click="send"
- >
+ <button v-else class="h-7 w-7 shrink-0 rounded-full bg-foreground text-background flex items-center justify-center disabled:opacity-30" :disabled="!prompt.trim() || !props.tab?.database" @click="send">
<ArrowUp class="h-4 w-4" />
</button>
</div>
diff --git a/apps/desktop/src/components/editor/ColumnInfoPanel.vue b/apps/desktop/src/components/editor/ColumnInfoPanel.vue
index e0ce2dc00b..a26ae77fe1 100644
--- a/apps/desktop/src/components/editor/ColumnInfoPanel.vue
+++ b/apps/desktop/src/components/editor/ColumnInfoPanel.vue
@@ -67,13 +67,7 @@ async function copyText(text: string) {
<div class="flex items-center justify-between">
<div class="flex items-center gap-1.5">
<span class="font-semibold text-sm text-foreground">{{ col.name }}</span>
- <Badge
- v-if="col.isPrimaryKey"
- variant="outline"
- class="h-4 px-1 text-[10px] border-primary/40 text-primary"
- >
- PK
- </Badge>
+ <Badge v-if="col.isPrimaryKey" variant="outline" class="h-4 px-1 text-[10px] border-primary/40 text-primary"> PK </Badge>
</div>
<Button variant="ghost" size="sm" class="h-5 w-5 p-0" @click="copyText(col.name)">
<Copy class="h-3 w-3" />
diff --git a/apps/desktop/src/components/editor/DangerConfirmDialog.vue b/apps/desktop/src/components/editor/DangerConfirmDialog.vue
index 7800a6dd86..3a349df2f4 100644
--- a/apps/desktop/src/components/editor/DangerConfirmDialog.vue
+++ b/apps/desktop/src/components/editor/DangerConfirmDialog.vue
@@ -60,18 +60,9 @@ function onConfirm() {
<div class="py-4 min-w-0">
<p class="text-sm text-muted-foreground mb-3">{{ message || t("dangerDialog.message") }}</p>
- <pre
- v-if="code"
- class="text-xs bg-muted p-3 rounded overflow-auto max-h-40 min-w-0 font-mono whitespace-pre"
- v-html="highlightedCode"
- />
- <div
- v-if="showSuppressToggle"
- class="mt-3 flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"
- >
- <Label for="danger-confirm-suppress" class="text-sm leading-5">{{
- suppressToggleLabel || t("dangerDialog.suppressFuturePrompts")
- }}</Label>
+ <pre v-if="code" class="text-xs bg-muted p-3 rounded overflow-auto max-h-40 min-w-0 font-mono whitespace-pre" v-html="highlightedCode" />
+ <div v-if="showSuppressToggle" class="mt-3 flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
+ <Label for="danger-confirm-suppress" class="text-sm leading-5">{{ suppressToggleLabel || t("dangerDialog.suppressFuturePrompts") }}</Label>
<Switch id="danger-confirm-suppress" v-model="suppressFuturePrompts" />
</div>
</div>
diff --git a/apps/desktop/src/components/editor/EditorSearchPanel.vue b/apps/desktop/src/components/editor/EditorSearchPanel.vue
index 7803bf5228..539ad0ebc8 100644
--- a/apps/desktop/src/components/editor/EditorSearchPanel.vue
+++ b/apps/desktop/src/components/editor/EditorSearchPanel.vue
@@ -3,15 +3,7 @@ import { ref, nextTick, onBeforeUnmount, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { EditorView } from "@codemirror/view";
import { EditorSelection } from "@codemirror/state";
-import {
- SearchQuery,
- setSearchQuery,
- openSearchPanel as cmOpenSearchPanel,
- findNext as cmFindNext,
- findPrevious as cmFindPrevious,
- replaceNext as cmReplaceNext,
- replaceAll as cmReplaceAll,
-} from "@codemirror/search";
+import { SearchQuery, setSearchQuery, openSearchPanel as cmOpenSearchPanel, findNext as cmFindNext, findPrevious as cmFindPrevious, replaceNext as cmReplaceNext, replaceAll as cmReplaceAll } from "@codemirror/search";
import { ChevronUp, ChevronDown, ChevronRight, X } from "@lucide/vue";
const props = defineProps<{
@@ -221,22 +213,10 @@ defineExpose({ openSearch, openReplace, closeSearch });
</script>
<template>
- <Transition
- enter-active-class="transition-all duration-150"
- leave-active-class="transition-all duration-100"
- enter-from-class="opacity-0 -translate-y-1"
- leave-to-class="opacity-0 -translate-y-1"
- >
- <div
- v-if="searchVisible"
- class="absolute top-1 right-4 z-[9999] isolate flex flex-col gap-1 rounded-md border bg-popover p-1.5 text-popover-foreground shadow-lg"
- >
+ <Transition enter-active-class="transition-all duration-150" leave-active-class="transition-all duration-100" enter-from-class="opacity-0 -translate-y-1" leave-to-class="opacity-0 -translate-y-1">
+ <div v-if="searchVisible" class="absolute top-1 right-4 z-[9999] isolate flex flex-col gap-1 rounded-md border bg-popover p-1.5 text-popover-foreground shadow-lg">
<div class="flex items-center gap-0.5">
- <button
- class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
- :title="showReplace ? t('editor.search.collapseReplace') : t('editor.search.expandReplace')"
- @click="showReplace = !showReplace"
- >
+ <button class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" :title="showReplace ? t('editor.search.collapseReplace') : t('editor.search.expandReplace')" @click="showReplace = !showReplace">
<ChevronRight class="w-3 h-3 transition-transform" :class="showReplace && 'rotate-90'" />
</button>
<input
@@ -249,48 +229,18 @@ defineExpose({ openSearch, openReplace, closeSearch });
:placeholder="t('editor.search.find')"
@keydown="onSearchKeydown"
/>
- <button
- class="w-6 h-6 flex items-center justify-center rounded text-xs font-mono hover:bg-accent"
- :class="caseSensitive ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'"
- :title="t('editor.search.caseSensitive')"
- @click="caseSensitive = !caseSensitive"
- >
- Aa
- </button>
- <button
- class="w-6 h-6 flex items-center justify-center rounded text-xs font-mono hover:bg-accent"
- :class="useRegex ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'"
- :title="t('editor.search.regex')"
- @click="useRegex = !useRegex"
- >
- .*
- </button>
+ <button class="w-6 h-6 flex items-center justify-center rounded text-xs font-mono hover:bg-accent" :class="caseSensitive ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'" :title="t('editor.search.caseSensitive')" @click="caseSensitive = !caseSensitive">Aa</button>
+ <button class="w-6 h-6 flex items-center justify-center rounded text-xs font-mono hover:bg-accent" :class="useRegex ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'" :title="t('editor.search.regex')" @click="useRegex = !useRegex">.*</button>
<span class="text-xs text-muted-foreground min-w-[3rem] text-center shrink-0">
- {{
- searchText && matchCount > 0
- ? `${currentMatchIndex}/${matchCount}${matchCountLimited ? "+" : ""}`
- : t("editor.search.noResults")
- }}
+ {{ searchText && matchCount > 0 ? `${currentMatchIndex}/${matchCount}${matchCountLimited ? "+" : ""}` : t("editor.search.noResults") }}
</span>
- <button
- class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
- :title="t('editor.search.prevMatch')"
- @click="prevMatch"
- >
+ <button class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('editor.search.prevMatch')" @click="prevMatch">
<ChevronUp class="w-3.5 h-3.5" />
</button>
- <button
- class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
- :title="t('editor.search.nextMatch')"
- @click="nextMatch"
- >
+ <button class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('editor.search.nextMatch')" @click="nextMatch">
<ChevronDown class="w-3.5 h-3.5" />
</button>
- <button
- class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
- :title="t('editor.search.close')"
- @click="closeSearch"
- >
+ <button class="w-5 h-5 flex items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('editor.search.close')" @click="closeSearch">
<X class="w-3.5 h-3.5" />
</button>
</div>
@@ -307,18 +257,10 @@ defineExpose({ openSearch, openReplace, closeSearch });
@keydown.enter.prevent="doReplace"
@keydown.escape.prevent="closeSearch"
/>
- <button
- class="h-6 px-1.5 flex items-center justify-center rounded text-xs text-muted-foreground hover:bg-accent hover:text-foreground border"
- :title="t('editor.search.replace')"
- @click="doReplace"
- >
+ <button class="h-6 px-1.5 flex items-center justify-center rounded text-xs text-muted-foreground hover:bg-accent hover:text-foreground border" :title="t('editor.search.replace')" @click="doReplace">
{{ t("editor.search.replace") }}
</button>
- <button
- class="h-6 px-1.5 flex items-center justify-center rounded text-xs text-muted-foreground hover:bg-accent hover:text-foreground border"
- :title="t('editor.search.replaceAll')"
- @click="doReplaceAll"
- >
+ <button class="h-6 px-1.5 flex items-center justify-center rounded text-xs text-muted-foreground hover:bg-accent hover:text-foreground border" :title="t('editor.search.replaceAll')" @click="doReplaceAll">
{{ t("editor.search.replaceAll") }}
</button>
</div>
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 283a1b0306..2d1eb23a6d 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -2,25 +2,7 @@
import { ref, watch, shallowRef, computed, onMounted } from "vue";
import type { EditorView as EditorViewType } from "@codemirror/view";
import { useI18n } from "vue-i18n";
-import {
- AlertTriangle,
- CheckCircle2,
- CircleHelp,
- Cloud,
- Copy,
- Download,
- ExternalLink,
- Loader2,
- PackageSearch,
- Pencil,
- RefreshCw,
- RotateCcw,
- Settings,
- Terminal,
- Trash2,
- Upload,
- X,
-} from "@lucide/vue";
+import { AlertTriangle, CheckCircle2, CircleHelp, Cloud, Copy, Download, ExternalLink, Loader2, PackageSearch, Pencil, RefreshCw, RotateCcw, Settings, Terminal, Trash2, Upload, X } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -54,28 +36,9 @@ import { isTauriRuntime } from "@/lib/tauriRuntime";
import { useTheme } from "@/composables/useTheme";
import { copyToClipboard } from "@/lib/clipboard";
import { clearDebugLogs as clearStoredDebugLogs, downloadDebugLogs, getDebugLogBundleText } from "@/lib/debugLog";
-import {
- aiListModels,
- aiTestConnection,
- checkMcpServerStatus,
- forgetWebdavSavedPassword,
- listSystemFonts,
- saveWebdavSavedPassword,
- webdavPasswordStatus,
- webdavSyncDownload,
- webdavSyncTest,
- webdavSyncUpload,
- type AiModelInfo,
- type McpServerStatus,
- type WebDavConfig,
-} from "@/lib/api";
+import { aiListModels, aiTestConnection, checkMcpServerStatus, forgetWebdavSavedPassword, listSystemFonts, saveWebdavSavedPassword, webdavPasswordStatus, webdavSyncDownload, webdavSyncTest, webdavSyncUpload, type AiModelInfo, type McpServerStatus, type WebDavConfig } from "@/lib/api";
import { eventToShortcut } from "@/lib/keyboardShortcuts";
-import {
- SHORTCUT_DEFINITIONS,
- findShortcutConflict,
- normalizeShortcutSettings,
- type ShortcutActionId,
-} from "@/lib/shortcutRegistry";
+import { SHORTCUT_DEFINITIONS, findShortcutConflict, normalizeShortcutSettings, type ShortcutActionId } from "@/lib/shortcutRegistry";
import { normalizeSidebarHiddenTablePrefixes } from "@/lib/sidebarTableNameDisplay";
import { normalizeSqlFormatterSettings, type SqlFormatterSettings } from "@/lib/sqlFormatterConfig";
import type { SqlSnippet } from "@/types/database";
@@ -126,18 +89,14 @@ const editShowColumnTypesInHeader = ref(settingsStore.editorSettings.showColumnT
const editCompactColumnHeaderActions = ref(settingsStore.editorSettings.compactColumnHeaderActions);
const editRedisScanPageSize = ref(settingsStore.editorSettings.redisScanPageSize);
const editShortcuts = ref(normalizeShortcutSettings(settingsStore.editorSettings.shortcuts));
-const editSqlFormatter = ref<SqlFormatterSettings>(
- normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter),
-);
+const editSqlFormatter = ref<SqlFormatterSettings>(normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter));
const sqlFormatterConfigValid = ref(true);
const editingShortcutId = ref<ShortcutActionId | null>(null);
const editSidebarActivation = ref(settingsStore.editorSettings.sidebarActivation);
const editSidebarObjectDisplay = ref(settingsStore.editorSettings.sidebarObjectDisplay);
const sidebarObjectDisplayHelp = ref<"grouped" | "simple" | null>(null);
const editAutoSelectActiveSidebarNode = ref(settingsStore.editorSettings.autoSelectActiveSidebarNode);
-const editDisconnectTabHandlingMode = ref<DisconnectTabHandlingMode>(
- settingsStore.editorSettings.disconnectTabHandlingMode,
-);
+const editDisconnectTabHandlingMode = ref<DisconnectTabHandlingMode>(settingsStore.editorSettings.disconnectTabHandlingMode);
const editReuseDataTab = ref(settingsStore.editorSettings.reuseDataTab);
const editUpdateNotificationsEnabled = ref(settingsStore.editorSettings.updateNotificationsEnabled);
const editSidebarHiddenTablePrefixes = ref(settingsStore.editorSettings.sidebarHiddenTablePrefixes.join("\n"));
@@ -317,13 +276,9 @@ const shortcutConflicts = computed(() =>
}),
);
const hasShortcutConflicts = computed(() => shortcutConflicts.value.length > 0);
-const shortcutsChanged = computed(
- () => JSON.stringify(editShortcuts.value) !== JSON.stringify(settingsStore.editorSettings.shortcuts),
-);
+const shortcutsChanged = computed(() => JSON.stringify(editShortcuts.value) !== JSON.stringify(settingsStore.editorSettings.shortcuts));
const hasBlockingShortcutConflicts = computed(() => shortcutsChanged.value && hasShortcutConflicts.value);
-const hasBlockingFormatterConfig = computed(
- () => activeSettingsTab.value === "formatter" && !sqlFormatterConfigValid.value,
-);
+const hasBlockingFormatterConfig = computed(() => activeSettingsTab.value === "formatter" && !sqlFormatterConfigValid.value);
const hasApplyBlocker = computed(() => hasBlockingShortcutConflicts.value || hasBlockingFormatterConfig.value);
function hasChanges(): boolean {
@@ -346,8 +301,7 @@ function hasChanges(): boolean {
editCompactColumnHeaderActions.value !== settingsStore.editorSettings.compactColumnHeaderActions ||
editRedisScanPageSize.value !== settingsStore.editorSettings.redisScanPageSize ||
JSON.stringify(editShortcuts.value) !== JSON.stringify(settingsStore.editorSettings.shortcuts) ||
- JSON.stringify(editSqlFormatter.value) !==
- JSON.stringify(normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter)) ||
+ JSON.stringify(editSqlFormatter.value) !== JSON.stringify(normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter)) ||
editSidebarActivation.value !== settingsStore.editorSettings.sidebarActivation ||
editSidebarObjectDisplay.value !== settingsStore.editorSettings.sidebarObjectDisplay ||
editAutoSelectActiveSidebarNode.value !== settingsStore.editorSettings.autoSelectActiveSidebarNode ||
@@ -357,16 +311,14 @@ function hasChanges(): boolean {
editSidebarHideTableComments.value !== settingsStore.editorSettings.sidebarHideTableComments ||
editSidebarAllowHorizontalScroll.value !== settingsStore.editorSettings.sidebarAllowHorizontalScroll ||
editExportBatchSize.value !== settingsStore.editorSettings.exportBatchSize ||
- JSON.stringify(normalizeSidebarHiddenTablePrefixes(editSidebarHiddenTablePrefixes.value)) !==
- JSON.stringify(settingsStore.editorSettings.sidebarHiddenTablePrefixes) ||
+ JSON.stringify(normalizeSidebarHiddenTablePrefixes(editSidebarHiddenTablePrefixes.value)) !== JSON.stringify(settingsStore.editorSettings.sidebarHiddenTablePrefixes) ||
JSON.stringify(editSnippets.value) !== JSON.stringify(settingsStore.editorSettings.snippets)
);
}
async function persistSettings() {
if (hasApplyBlocker.value) return;
- const sidebarObjectDisplayChanged =
- editSidebarObjectDisplay.value !== settingsStore.editorSettings.sidebarObjectDisplay;
+ const sidebarObjectDisplayChanged = editSidebarObjectDisplay.value !== settingsStore.editorSettings.sidebarObjectDisplay;
settingsStore.updateEditorSettings({
fontFamily: editFontFamily.value,
fontSize: editFontSize.value,
@@ -598,20 +550,7 @@ function setSidebarActivation(value: "single" | "double") {
const activeSettingsTab = ref("editor");
const isWeb = !isTauriRuntime();
const displayedAppVersion = computed(() => (props.appVersion ? `v${props.appVersion}` : ""));
-type SettingsCategory =
- | "editor"
- | "formatter"
- | "appearance"
- | "navigation"
- | "data"
- | "redis"
- | "shortcuts"
- | "snippets"
- | "sync"
- | "ai"
- | "mcp"
- | "security"
- | "about";
+type SettingsCategory = "editor" | "formatter" | "appearance" | "navigation" | "data" | "redis" | "shortcuts" | "snippets" | "sync" | "ai" | "mcp" | "security" | "about";
const settingsCategoryNav = computed<{ value: SettingsCategory; label: string }[]>(() => [
{ value: "editor", label: t("settings.editorTab") },
{ value: "formatter", label: t("settings.sqlFormatterTab") },
@@ -627,28 +566,14 @@ const settingsCategoryNav = computed<{ value: SettingsCategory; label: string }[
...(isWeb ? [{ value: "security" as const, label: t("settings.securityTab") }] : []),
{ value: "about", label: t("settings.aboutTab") },
]);
-const settingsTabsWithApplyFooter = new Set<SettingsCategory>([
- "editor",
- "formatter",
- "appearance",
- "navigation",
- "data",
- "redis",
- "shortcuts",
- "snippets",
-]);
+const settingsTabsWithApplyFooter = new Set<SettingsCategory>(["editor", "formatter", "appearance", "navigation", "data", "redis", "shortcuts", "snippets"]);
function hasSettingsApplyFooter(value: SettingsCategory): boolean {
return settingsTabsWithApplyFooter.has(value);
}
function settingsCategoryButton(value: SettingsCategory): string {
- return [
- "w-full rounded-md px-3 py-2 text-left text-sm transition-colors",
- value === activeSettingsTab.value
- ? "bg-primary text-primary-foreground shadow-sm"
- : "text-muted-foreground hover:bg-muted hover:text-foreground",
- ].join(" ");
+ return ["w-full rounded-md px-3 py-2 text-left text-sm transition-colors", value === activeSettingsTab.value ? "bg-primary text-primary-foreground shadow-sm" : "text-muted-foreground hover:bg-muted hover:text-foreground"].join(" ");
}
function openExternalUrl(url: string) {
@@ -792,12 +717,7 @@ const webdavBusy = ref<"" | "test" | "upload" | "download">("");
const webdavMessage = ref("");
const webdavError = ref(false);
-const webdavReady = computed(
- () =>
- !!webdavEndpoint.value.trim() &&
- !webdavBusy.value &&
- (!webdavSyncSecrets.value || !!webdavSecretsPassphrase.value.trim()),
-);
+const webdavReady = computed(() => !!webdavEndpoint.value.trim() && !webdavBusy.value && (!webdavSyncSecrets.value || !!webdavSecretsPassphrase.value.trim()));
function currentWebDavConfig(): WebDavConfig {
return {
@@ -876,11 +796,7 @@ async function testWebDav() {
async function uploadWebDavSnapshot() {
await runWebDavAction("upload", async () => {
- const summary = await webdavSyncUpload(
- currentWebDavConfig(),
- settingsStore.editorSettings,
- webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined,
- );
+ const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined);
return t("settings.syncUploadSuccess", { bytes: summary.bytes, path: summary.remotePath });
});
}
@@ -888,10 +804,7 @@ async function uploadWebDavSnapshot() {
async function downloadWebDavSnapshot() {
if (!window.confirm(t("settings.syncDownloadConfirm"))) return;
await runWebDavAction("download", async () => {
- const result = await webdavSyncDownload(
- currentWebDavConfig(),
- webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined,
- );
+ const result = await webdavSyncDownload(currentWebDavConfig(), webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined);
if (result.editorSettings && typeof result.editorSettings === "object") {
settingsStore.updateEditorSettings(result.editorSettings as any);
}
@@ -1016,19 +929,9 @@ const aiTesting = ref(false);
const aiTestResult = ref<"" | "success" | "error">("");
const aiTestError = ref("");
const aiRequiresApiKey = computed(() => AI_PROVIDER_PRESETS[aiEditProvider.value].requiresApiKey);
-const aiSupportsApiStyle = computed(
- () =>
- aiEditProvider.value === "openai" ||
- aiEditProvider.value === "openai-compatible" ||
- aiEditProvider.value === "custom",
-);
+const aiSupportsApiStyle = computed(() => aiEditProvider.value === "openai" || aiEditProvider.value === "openai-compatible" || aiEditProvider.value === "custom");
const aiModelListSupported = computed(() => aiEditProvider.value !== "gemini");
-const aiCanListModels = computed(
- () =>
- aiModelListSupported.value &&
- !!aiEditEndpoint.value.trim() &&
- (!aiRequiresApiKey.value || !!aiEditApiKey.value.trim()),
-);
+const aiCanListModels = computed(() => aiModelListSupported.value && !!aiEditEndpoint.value.trim() && (!aiRequiresApiKey.value || !!aiEditApiKey.value.trim()));
const aiModelOptionIds = computed(() => aiModelOptions.value.map((model) => model.id));
const aiModelEmptyText = computed(() => {
if (aiModelError.value) return aiModelError.value;
@@ -1118,12 +1021,7 @@ async function aiRefreshModels() {
}
function onAiModelListOpen(open: boolean) {
- if (
- open &&
- aiCanListModels.value &&
- !aiModelLoading.value &&
- (!aiModelOptions.value.length || aiModelLoadedSignature.value !== aiModelConfigSignature())
- ) {
+ if (open && aiCanListModels.value && !aiModelLoading.value && (!aiModelOptions.value.length || aiModelLoadedSignature.value !== aiModelConfigSignature())) {
void aiRefreshModels();
}
}
@@ -1173,12 +1071,7 @@ function aiApplySettings() {
}
async function aiTestConn() {
- if (
- (aiRequiresApiKey.value && !aiEditApiKey.value.trim()) ||
- !aiEditEndpoint.value.trim() ||
- !aiEditModel.value.trim()
- )
- return;
+ if ((aiRequiresApiKey.value && !aiEditApiKey.value.trim()) || !aiEditEndpoint.value.trim() || !aiEditModel.value.trim()) return;
aiTesting.value = true;
aiTestResult.value = "";
aiTestError.value = "";
@@ -1232,10 +1125,7 @@ watch(
const themeExt = await loadEditorTheme(ss.theme, ss.appAppearance, ss.customColors);
previewView.value.dispatch({
- effects: [
- themeComp.reconfigure(themeExt),
- fontThemeComp.reconfigure(editorFontTheme(editorViewModule.EditorView, ss.fontSize, ss.fontFamily)),
- ],
+ effects: [themeComp.reconfigure(themeExt), fontThemeComp.reconfigure(editorFontTheme(editorViewModule.EditorView, ss.fontSize, ss.fontFamily))],
});
},
{ deep: true },
@@ -1259,12 +1149,7 @@ watch(previewRef, async (el) => {
previewInitialized = true;
if (previewView.value) return;
- const [{ EditorView }, { EditorState, Compartment }, { sql, MySQL }, { basicSetup }] = await Promise.all([
- import("@codemirror/view"),
- import("@codemirror/state"),
- import("@codemirror/lang-sql"),
- import("codemirror"),
- ]);
+ const [{ EditorView }, { EditorState, Compartment }, { sql, MySQL }, { basicSetup }] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("codemirror")]);
editorViewModule = { EditorView } as typeof import("@codemirror/view");
fontThemeComp = new Compartment();
@@ -1275,12 +1160,7 @@ watch(previewRef, async (el) => {
const state = EditorState.create({
doc: previewSql,
- extensions: [
- basicSetup,
- sql({ dialect: MySQL }),
- themeComp.of(themeExt),
- fontThemeComp.of(editorFontTheme(EditorView, ss.fontSize, ss.fontFamily)),
- ],
+ extensions: [basicSetup, sql({ dialect: MySQL }), themeComp.of(themeExt), fontThemeComp.of(editorFontTheme(EditorView, ss.fontSize, ss.fontFamily))],
});
previewView.value = new EditorView({ state, parent: previewRef.value });
@@ -1312,16 +1192,8 @@ watch(
</DialogHeader>
<div class="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden sm:flex-row">
- <nav
- class="settingsCategoryNav flex min-h-0 shrink-0 gap-1 overflow-x-auto border-b pb-3 sm:w-40 sm:flex-col sm:overflow-x-hidden sm:overflow-y-auto sm:border-b-0 sm:border-r sm:pb-0 sm:pr-3"
- >
- <button
- v-for="category in settingsCategoryNav"
- :key="category.value"
- type="button"
- :class="settingsCategoryButton(category.value)"
- @click="activeSettingsTab = category.value"
- >
+ <nav class="settingsCategoryNav flex min-h-0 shrink-0 gap-1 overflow-x-auto border-b pb-3 sm:w-40 sm:flex-col sm:overflow-x-hidden sm:overflow-y-auto sm:border-b-0 sm:border-r sm:pb-0 sm:pr-3">
+ <button v-for="category in settingsCategoryNav" :key="category.value" type="button" :class="settingsCategoryButton(category.value)" @click="activeSettingsTab = category.value">
{{ category.label }}
</button>
</nav>
@@ -1376,26 +1248,14 @@ watch(
<SelectContent>
<SelectItem v-for="theme in themeSelectOptions" :key="theme.value" :value="theme.value">
<div class="flex items-center gap-2">
- <span
- class="h-3 w-3 rounded-full border"
- :class="
- theme.dark
- ? 'bg-foreground border-foreground/20'
- : 'bg-muted-foreground/30 border-muted-foreground/40'
- "
- />
+ <span class="h-3 w-3 rounded-full border" :class="theme.dark ? 'bg-foreground border-foreground/20' : 'bg-muted-foreground/30 border-muted-foreground/40'" />
{{ theme.label }}
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
- <Button
- v-if="editTheme === 'custom'"
- variant="outline"
- class="h-9 w-auto px-4"
- @click="showThemeCustomizer = true"
- >
+ <Button v-if="editTheme === 'custom'" variant="outline" class="h-9 w-auto px-4" @click="showThemeCustomizer = true">
<Settings class="mr-2 h-4 w-4" />
{{ t("settings.customThemeConfigure") }}
</Button>
@@ -1408,15 +1268,7 @@ watch(
<Label>{{ t("settings.fontSize") }}</Label>
<span class="text-xs text-muted-foreground tabular-nums">{{ editFontSize }}px</span>
</div>
- <input
- type="range"
- min="10"
- max="24"
- step="1"
- :value="editFontSize"
- @input="editFontSize = Number(($event.target as HTMLInputElement).value)"
- class="w-full accent-primary"
- />
+ <input type="range" min="10" max="24" step="1" :value="editFontSize" @input="editFontSize = Number(($event.target as HTMLInputElement).value)" class="w-full accent-primary" />
<div class="flex items-center gap-2 text-xs text-muted-foreground">
<span>10px</span>
<span class="flex-1 border-b border-dashed border-muted-foreground/30" />
@@ -1464,24 +1316,14 @@ watch(
<!-- Live Preview -->
<div class="space-y-2">
<Label>{{ t("settings.preview") }}</Label>
- <div
- class="rounded-md border overflow-auto max-w-full"
- :class="
- editTheme === 'vscode-light' || editTheme === 'duotone-light' || editTheme === 'xcode'
- ? 'border-border'
- : 'border-border/50'
- "
- >
+ <div class="rounded-md border overflow-auto max-w-full" :class="editTheme === 'vscode-light' || editTheme === 'duotone-light' || editTheme === 'xcode' ? 'border-border' : 'border-border/50'">
<div ref="previewRef" style="min-width: 100%" />
</div>
</div>
</section>
<section v-else-if="activeSettingsTab === 'formatter'" class="flex flex-col gap-5 py-2">
- <SqlFormatterSettingsPanel
- v-model="editSqlFormatter"
- @validity-change="(value: boolean) => (sqlFormatterConfigValid = value)"
- />
+ <SqlFormatterSettingsPanel v-model="editSqlFormatter" @validity-change="(value: boolean) => (sqlFormatterConfigValid = value)" />
</section>
<section v-else-if="activeSettingsTab === 'appearance'" class="flex flex-col gap-5 py-2">
@@ -1494,9 +1336,7 @@ watch(
<SelectContent>
<SelectItem v-for="locale in LOCALE_OPTIONS" :key="locale.value" :value="locale.value">
<div class="flex items-center gap-2">
- <span
- class="inline-flex h-5 w-6 shrink-0 items-center justify-center text-sm font-medium leading-none"
- >
+ <span class="inline-flex h-5 w-6 shrink-0 items-center justify-center text-sm font-medium leading-none">
{{ locale.flag }}
</span>
<span>{{ locale.label }}</span>
@@ -1523,9 +1363,7 @@ watch(
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem v-for="scale in uiScaleOptions" :key="scale" :value="String(scale)">
- {{ Math.round(scale * 100) }}%
- </SelectItem>
+ <SelectItem v-for="scale in uiScaleOptions" :key="scale" :value="String(scale)"> {{ Math.round(scale * 100) }}% </SelectItem>
</SelectContent>
</Select>
<p class="text-xs text-muted-foreground">{{ t("settings.uiScaleDescription") }}</p>
@@ -1536,25 +1374,13 @@ watch(
<div class="space-y-2">
<Label>{{ t("settings.appLayout") }}</Label>
<div class="grid grid-cols-2 gap-2">
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editAppLayout === 'separated' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setAppLayout('separated')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editAppLayout === 'separated' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setAppLayout('separated')">
<div class="text-left">
<div class="text-sm font-medium">{{ t("settings.appLayoutSeparated") }}</div>
<div class="text-xs text-muted-foreground">{{ t("settings.appLayoutSeparatedDescription") }}</div>
</div>
</Button>
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editAppLayout === 'classic' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setAppLayout('classic')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editAppLayout === 'classic' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setAppLayout('classic')">
<div class="text-left">
<div class="text-sm font-medium">{{ t("settings.appLayoutClassic") }}</div>
<div class="text-xs text-muted-foreground">{{ t("settings.appLayoutClassicDescription") }}</div>
@@ -1566,13 +1392,7 @@ watch(
<div v-if="!isWeb" class="space-y-2">
<Label>{{ t("settings.iconTheme") }}</Label>
<div class="grid grid-cols-2 gap-2">
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editIconTheme === 'default' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setIconTheme('default')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editIconTheme === 'default' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setIconTheme('default')">
<div class="flex items-center gap-3 text-left">
<img src="/logo.png" alt="DBX" class="h-8 w-8 rounded-md" />
<div>
@@ -1581,13 +1401,7 @@ watch(
</div>
</div>
</Button>
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editIconTheme === 'black' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setIconTheme('black')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editIconTheme === 'black' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setIconTheme('black')">
<div class="flex items-center gap-3 text-left">
<img src="/logo-black.png" alt="DBX" class="h-8 w-8 dark:invert" />
<div>
@@ -1599,10 +1413,7 @@ watch(
</div>
</div>
- <div
- v-if="!isWeb"
- class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"
- >
+ <div v-if="!isWeb" class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
<div class="space-y-1">
<Label for="show-tray-icon">{{ t("settings.showTrayIcon") }}</Label>
<p class="text-xs text-muted-foreground">{{ t("settings.showTrayIconDescription") }}</p>
@@ -1687,13 +1498,7 @@ watch(
<div class="space-y-2">
<Label>{{ t("settings.sidebarActivation") }}</Label>
<div class="grid grid-cols-2 gap-2">
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editSidebarActivation === 'single' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setSidebarActivation('single')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editSidebarActivation === 'single' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setSidebarActivation('single')">
<div class="text-left">
<div class="text-sm font-medium">{{ t("settings.sidebarActivationSingle") }}</div>
<div class="text-xs text-muted-foreground">
@@ -1701,13 +1506,7 @@ watch(
</div>
</div>
</Button>
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editSidebarActivation === 'double' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setSidebarActivation('double')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editSidebarActivation === 'double' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setSidebarActivation('double')">
<div class="text-left">
<div class="text-sm font-medium">{{ t("settings.sidebarActivationDouble") }}</div>
<div class="text-xs text-muted-foreground">
@@ -1734,68 +1533,34 @@ watch(
<div class="space-y-2">
<Label>{{ t("settings.sidebarObjectDisplay") }}</Label>
<div class="grid grid-cols-2 gap-2">
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editSidebarObjectDisplay === 'grouped' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setSidebarObjectDisplay('grouped')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editSidebarObjectDisplay === 'grouped' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setSidebarObjectDisplay('grouped')">
<div class="text-left">
<div class="flex items-center gap-2">
<div class="text-sm font-medium">{{ t("settings.sidebarObjectDisplayGrouped") }}</div>
<Tooltip :open="sidebarObjectDisplayHelp === 'grouped'">
<TooltipTrigger as-child>
- <span
- class="inline-flex shrink-0 cursor-help text-muted-foreground hover:text-foreground"
- @click.stop
- @pointerdown.stop
- @mouseenter="sidebarObjectDisplayHelp = 'grouped'"
- @mouseleave="sidebarObjectDisplayHelp = null"
- >
+ <span class="inline-flex shrink-0 cursor-help text-muted-foreground hover:text-foreground" @click.stop @pointerdown.stop @mouseenter="sidebarObjectDisplayHelp = 'grouped'" @mouseleave="sidebarObjectDisplayHelp = null">
<CircleHelp class="h-3.5 w-3.5" />
</span>
</TooltipTrigger>
- <TooltipContent
- class="max-w-[320px] text-xs leading-relaxed"
- side="top"
- align="center"
- :side-offset="8"
- >
+ <TooltipContent class="max-w-[320px] text-xs leading-relaxed" side="top" align="center" :side-offset="8">
{{ t("settings.sidebarObjectDisplayGroupedDescription") }}
</TooltipContent>
</Tooltip>
</div>
</div>
</Button>
- <Button
- type="button"
- variant="outline"
- class="h-auto justify-start border p-3"
- :class="editSidebarObjectDisplay === 'simple' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="setSidebarObjectDisplay('simple')"
- >
+ <Button type="button" variant="outline" class="h-auto justify-start border p-3" :class="editSidebarObjectDisplay === 'simple' ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="setSidebarObjectDisplay('simple')">
<div class="text-left">
<div class="flex items-center gap-2">
<div class="text-sm font-medium">{{ t("settings.sidebarObjectDisplaySimple") }}</div>
<Tooltip :open="sidebarObjectDisplayHelp === 'simple'">
<TooltipTrigger as-child>
- <span
- class="inline-flex shrink-0 cursor-help text-muted-foreground hover:text-foreground"
- @click.stop
- @pointerdown.stop
- @mouseenter="sidebarObjectDisplayHelp = 'simple'"
- @mouseleave="sidebarObjectDisplayHelp = null"
- >
+ <span class="inline-flex shrink-0 cursor-help text-muted-foreground hover:text-foreground" @click.stop @pointerdown.stop @mouseenter="sidebarObjectDisplayHelp = 'simple'" @mouseleave="sidebarObjectDisplayHelp = null">
<CircleHelp class="h-3.5 w-3.5" />
</span>
</TooltipTrigger>
- <TooltipContent
- class="max-w-[320px] text-xs leading-relaxed"
- side="top"
- align="center"
- :side-offset="8"
- >
+ <TooltipContent class="max-w-[320px] text-xs leading-relaxed" side="top" align="center" :side-offset="8">
{{ t("settings.sidebarObjectDisplaySimpleDescription") }}
</TooltipContent>
</Tooltip>
@@ -1830,10 +1595,7 @@ watch(
</TooltipContent>
</Tooltip>
</div>
- <Select
- :model-value="editDisconnectTabHandlingMode"
- @update:model-value="onDisconnectTabHandlingModeChange"
- >
+ <Select :model-value="editDisconnectTabHandlingMode" @update:model-value="onDisconnectTabHandlingModeChange">
<SelectTrigger id="disconnect-tab-handling-mode" class="w-full">
<SelectValue />
</SelectTrigger>
@@ -1902,15 +1664,7 @@ watch(
<div class="space-y-2">
<Label>{{ t("settings.exportBatchSize") }}</Label>
<div class="flex items-center gap-3">
- <Input
- type="number"
- list="export-batch-sizes"
- min="100"
- max="100000"
- step="100"
- v-model.number="editExportBatchSize"
- class="h-9 w-28 [&::-webkit-inner-spin-button]:appearance-none"
- />
+ <Input type="number" list="export-batch-sizes" min="100" max="100000" step="100" v-model.number="editExportBatchSize" class="h-9 w-28 [&::-webkit-inner-spin-button]:appearance-none" />
<datalist id="export-batch-sizes">
<option value="500" />
<option value="1000" />
@@ -1943,21 +1697,12 @@ watch(
<section v-else-if="activeSettingsTab === 'shortcuts'" class="flex flex-col gap-2 py-2">
<div class="overflow-hidden rounded-md border border-border/70 bg-background">
- <div
- v-for="definition in SHORTCUT_DEFINITIONS"
- :key="definition.id"
- class="group -mt-px grid gap-2 border-t border-border/70 px-3 py-2 transition-colors first:mt-0 first:border-t-0 hover:bg-muted/40 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center"
- >
+ <div v-for="definition in SHORTCUT_DEFINITIONS" :key="definition.id" class="group -mt-px grid gap-2 border-t border-border/70 px-3 py-2 transition-colors first:mt-0 first:border-t-0 hover:bg-muted/40 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center">
<div class="min-w-0">
<div class="flex min-w-0 items-center gap-2">
<Label class="min-w-0 truncate leading-none">{{ t(definition.labelKey) }}</Label>
- <Badge
- variant="outline"
- class="h-5 shrink-0 rounded-md border-border/60 px-1.5 text-[11px] font-normal text-muted-foreground"
- >
- {{
- t(`settings.shortcutScope${definition.scope[0].toUpperCase()}${definition.scope.slice(1)}`)
- }}
+ <Badge variant="outline" class="h-5 shrink-0 rounded-md border-border/60 px-1.5 text-[11px] font-normal text-muted-foreground">
+ {{ t(`settings.shortcutScope${definition.scope[0].toUpperCase()}${definition.scope.slice(1)}`) }}
</Badge>
</div>
</div>
@@ -1965,24 +1710,15 @@ watch(
<div class="flex items-center justify-end gap-1.5">
<input
:data-shortcut-input="definition.id"
- :value="
- editingShortcutId === definition.id ? '' : formatShortcutPill(editShortcuts[definition.id])
- "
+ :value="editingShortcutId === definition.id ? '' : formatShortcutPill(editShortcuts[definition.id])"
:style="{
- width:
- editingShortcutId === definition.id
- ? shortcutPressShortcutInputWidth
- : `${Math.max(4, formatShortcutPill(editShortcuts[definition.id]).length + 3)}ch`,
+ width: editingShortcutId === definition.id ? shortcutPressShortcutInputWidth : `${Math.max(4, formatShortcutPill(editShortcuts[definition.id]).length + 3)}ch`,
}"
readonly
:aria-invalid="shortcutConflicts.includes(definition.id)"
:placeholder="t('settings.shortcutPressShortcut')"
class="h-7 w-auto min-w-12 max-w-32 shrink-0 cursor-default rounded-full border border-transparent bg-muted px-2.5 text-center font-mono text-[13px] font-semibold text-foreground/75 shadow-inner outline-none selection:bg-transparent placeholder:text-muted-foreground aria-invalid:border-destructive/70 aria-invalid:text-destructive aria-invalid:ring-destructive/20"
- :class="
- editingShortcutId === definition.id
- ? 'max-w-44 cursor-text border-border/80 bg-background text-left text-foreground shadow-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/35'
- : ''
- "
+ :class="editingShortcutId === definition.id ? 'max-w-44 cursor-text border-border/80 bg-background text-left text-foreground shadow-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/35' : ''"
@keydown="(event: KeyboardEvent) => onShortcutKeydown(definition.id, event)"
/>
<Button
@@ -1996,14 +1732,7 @@ watch(
>
<Pencil class="h-4 w-4" />
</Button>
- <Button
- v-else
- type="button"
- variant="ghost"
- size="sm"
- class="h-7 shrink-0 px-2 text-sm font-medium text-muted-foreground hover:text-foreground"
- @click="cancelShortcutEdit"
- >
+ <Button v-else type="button" variant="ghost" size="sm" class="h-7 shrink-0 px-2 text-sm font-medium text-muted-foreground hover:text-foreground" @click="cancelShortcutEdit">
{{ t("settings.cancel") }}
</Button>
<Button
@@ -2052,17 +1781,10 @@ watch(
</tr>
</thead>
<tbody>
- <tr
- v-for="snippet in editSnippets"
- :key="snippet.id"
- class="border-b last:border-b-0 hover:bg-muted/30"
- >
+ <tr v-for="snippet in editSnippets" :key="snippet.id" class="border-b last:border-b-0 hover:bg-muted/30">
<td class="px-3 py-2">{{ snippet.label }}</td>
<td class="px-3 py-2">
- <Badge
- variant="outline"
- class="h-5 rounded-md px-1.5 text-[11px] font-mono text-muted-foreground"
- >
+ <Badge variant="outline" class="h-5 rounded-md px-1.5 text-[11px] font-mono text-muted-foreground">
{{ snippet.prefix }}
</Badge>
</td>
@@ -2097,12 +1819,7 @@ watch(
<div class="grid gap-4 md:grid-cols-2">
<div class="space-y-2 md:col-span-2">
<Label for="webdav-endpoint">{{ t("settings.syncEndpoint") }}</Label>
- <Input
- id="webdav-endpoint"
- v-model="webdavEndpoint"
- autocomplete="off"
- placeholder="https://example.com/remote.php/dav/files/user/"
- />
+ <Input id="webdav-endpoint" v-model="webdavEndpoint" autocomplete="off" placeholder="https://example.com/remote.php/dav/files/user/" />
</div>
<div class="space-y-2">
<Label for="webdav-username">{{ t("settings.syncUsername") }}</Label>
@@ -2111,14 +1828,7 @@ watch(
<div class="space-y-2">
<Label for="webdav-password">{{ t("settings.syncPassword") }}</Label>
<div class="relative">
- <Input
- id="webdav-password"
- v-model="webdavPassword"
- type="password"
- :placeholder="webdavHasSavedPassword ? '••••••••' : t('settings.syncPasswordPlaceholder')"
- :disabled="webdavHasSavedPassword"
- autocomplete="current-password"
- />
+ <Input id="webdav-password" v-model="webdavPassword" type="password" :placeholder="webdavHasSavedPassword ? '••••••••' : t('settings.syncPasswordPlaceholder')" :disabled="webdavHasSavedPassword" autocomplete="current-password" />
<Button
v-if="webdavHasSavedPassword"
variant="ghost"
@@ -2172,12 +1882,7 @@ watch(
</div>
<div v-if="webdavSyncSecrets" class="space-y-2">
<Label for="webdav-secrets-passphrase">{{ t("settings.syncSecretsPassphrase") }}</Label>
- <Input
- id="webdav-secrets-passphrase"
- v-model="webdavSecretsPassphrase"
- type="password"
- autocomplete="new-password"
- />
+ <Input id="webdav-secrets-passphrase" v-model="webdavSecretsPassphrase" type="password" autocomplete="new-password" />
<p class="text-xs text-muted-foreground">{{ t("settings.syncSecretsPassphraseDescription") }}</p>
</div>
</div>
@@ -2192,27 +1897,15 @@ watch(
<SelectTrigger class="col-span-2 h-8 text-xs">
<SelectValue>
<span class="flex items-center gap-2">
- <AiProviderLogo
- :provider="selectedAiProviderPreset.provider"
- :label="selectedAiProviderPreset.label"
- :icon-slug="selectedAiProviderPreset.iconSlug"
- />
+ <AiProviderLogo :provider="selectedAiProviderPreset.provider" :label="selectedAiProviderPreset.label" :icon-slug="selectedAiProviderPreset.iconSlug" />
<span>{{ selectedAiProviderPreset.label }}</span>
</span>
</SelectValue>
</SelectTrigger>
<SelectContent>
- <SelectItem
- v-for="provider in aiProviderOptions"
- :key="provider.provider"
- :value="provider.provider"
- >
+ <SelectItem v-for="provider in aiProviderOptions" :key="provider.provider" :value="provider.provider">
<span class="flex items-center gap-2">
- <AiProviderLogo
- :provider="provider.provider"
- :label="provider.label"
- :icon-slug="provider.iconSlug"
- />
+ <AiProviderLogo :provider="provider.provider" :label="provider.label" :icon-slug="provider.iconSlug" />
<span>{{ provider.label }}</span>
</span>
</SelectItem>
@@ -2222,23 +1915,12 @@ watch(
<div class="grid grid-cols-3 items-center gap-3">
<Label class="text-right text-xs">API Key</Label>
- <Input
- v-model="aiEditApiKey"
- type="password"
- autocomplete="off"
- class="col-span-2 h-8 text-xs"
- :placeholder="aiRequiresApiKey ? '' : 'Optional'"
- />
+ <Input v-model="aiEditApiKey" type="password" autocomplete="off" class="col-span-2 h-8 text-xs" :placeholder="aiRequiresApiKey ? '' : 'Optional'" />
</div>
<div class="grid grid-cols-3 items-center gap-3">
<Label class="text-right text-xs">Endpoint</Label>
- <Input
- v-model="aiEditEndpoint"
- placeholder="https://api.openai.com/v1"
- autocomplete="off"
- class="col-span-2 h-8 text-xs"
- />
+ <Input v-model="aiEditEndpoint" placeholder="https://api.openai.com/v1" autocomplete="off" class="col-span-2 h-8 text-xs" />
</div>
<div class="grid grid-cols-3 items-start gap-3">
@@ -2266,22 +1948,11 @@ watch(
<template #option-label="{ option, label }">
<span class="flex min-w-0 flex-col">
<span class="truncate">{{ label }}</span>
- <span v-if="label !== option" class="truncate text-[11px] text-muted-foreground">{{
- option
- }}</span>
+ <span v-if="label !== option" class="truncate text-[11px] text-muted-foreground">{{ option }}</span>
</span>
</template>
</SearchableSelect>
- <Button
- type="button"
- size="icon"
- variant="outline"
- class="shrink-0"
- :disabled="aiModelLoading || !aiModelListSupported"
- :title="t('ai.refreshModels')"
- :aria-label="t('ai.refreshModels')"
- @click="aiRefreshModels"
- >
+ <Button type="button" size="icon" variant="outline" class="shrink-0" :disabled="aiModelLoading || !aiModelListSupported" :title="t('ai.refreshModels')" :aria-label="t('ai.refreshModels')" @click="aiRefreshModels">
<Loader2 v-if="aiModelLoading" class="h-3.5 w-3.5 animate-spin" />
<RefreshCw v-else class="h-3.5 w-3.5" />
</Button>
@@ -2296,22 +1967,8 @@ watch(
<div v-if="aiSupportsApiStyle" class="grid grid-cols-3 items-center gap-3">
<Label class="text-right text-xs">API</Label>
<div class="col-span-2 flex gap-2">
- <Button
- size="sm"
- variant="outline"
- class="h-8 flex-1 text-xs"
- :class="{ 'border-blue-300 border-2 ring-2 ring-blue-300/50': aiEditApiStyle === 'completions' }"
- @click="aiEditApiStyle = 'completions'"
- >/chat/completions</Button
- >
- <Button
- size="sm"
- variant="outline"
- class="h-8 flex-1 text-xs"
- :class="{ 'border-blue-300 border-2 ring-2 ring-blue-300/50': aiEditApiStyle === 'responses' }"
- @click="aiEditApiStyle = 'responses'"
- >/responses</Button
- >
+ <Button size="sm" variant="outline" class="h-8 flex-1 text-xs" :class="{ 'border-blue-300 border-2 ring-2 ring-blue-300/50': aiEditApiStyle === 'completions' }" @click="aiEditApiStyle = 'completions'">/chat/completions</Button>
+ <Button size="sm" variant="outline" class="h-8 flex-1 text-xs" :class="{ 'border-blue-300 border-2 ring-2 ring-blue-300/50': aiEditApiStyle === 'responses' }" @click="aiEditApiStyle = 'responses'">/responses</Button>
</div>
</div>
@@ -2319,12 +1976,7 @@ watch(
<Label class="text-right text-xs">{{ t("ai.enableThinking") }}</Label>
<div class="col-span-2 flex items-center gap-2">
<label class="flex items-center gap-2 text-xs text-muted-foreground">
- <input
- v-model="aiEditEnableThinking"
- type="checkbox"
- class="h-4 w-4 shrink-0 accent-primary"
- :disabled="!aiCompletionsMode || aiEditProvider === 'gemini'"
- />
+ <input v-model="aiEditEnableThinking" type="checkbox" class="h-4 w-4 shrink-0 accent-primary" :disabled="!aiCompletionsMode || aiEditProvider === 'gemini'" />
{{ aiEditEnableThinking ? t("ai.enableThinkingOn") : t("ai.enableThinkingOff") }}
</label>
<Popover>
@@ -2348,13 +2000,7 @@ watch(
<div class="grid grid-cols-3 items-center gap-3">
<Label class="text-right text-xs">{{ t("ai.proxyUrl") }}</Label>
- <Input
- v-model="aiEditProxyUrl"
- autocomplete="off"
- class="col-span-2 h-8 text-xs"
- placeholder="socks5://127.0.0.1:7890"
- :disabled="!aiEditProxyEnabled"
- />
+ <Input v-model="aiEditProxyUrl" autocomplete="off" class="col-span-2 h-8 text-xs" placeholder="socks5://127.0.0.1:7890" :disabled="!aiEditProxyEnabled" />
</div>
</div>
</section>
@@ -2376,17 +2022,7 @@ watch(
</Tooltip>
</div>
</div>
- <Badge
- variant="outline"
- class="shrink-0 rounded-md"
- :class="
- mcpStatusTone === 'ok'
- ? 'border-green-500/40 text-green-600 dark:text-green-400'
- : mcpStatusTone === 'warning'
- ? 'border-amber-500/40 text-amber-600 dark:text-amber-400'
- : 'text-muted-foreground'
- "
- >
+ <Badge variant="outline" class="shrink-0 rounded-md" :class="mcpStatusTone === 'ok' ? 'border-green-500/40 text-green-600 dark:text-green-400' : mcpStatusTone === 'warning' ? 'border-amber-500/40 text-amber-600 dark:text-amber-400' : 'text-muted-foreground'">
<Loader2 v-if="mcpStatusLoading" class="mr-1 h-3 w-3 animate-spin" />
<CheckCircle2 v-else-if="mcpStatusTone === 'ok'" class="mr-1 h-3 w-3" />
<AlertTriangle v-else-if="mcpStatusTone === 'warning'" class="mr-1 h-3 w-3" />
@@ -2430,22 +2066,12 @@ watch(
</div>
<div class="space-y-2">
- <Label>{{
- mcpStatus?.installed ? t("settings.mcpUpdateCommand") : t("settings.mcpInstallCommand")
- }}</Label>
+ <Label>{{ mcpStatus?.installed ? t("settings.mcpUpdateCommand") : t("settings.mcpInstallCommand") }}</Label>
<div class="flex min-w-0 items-center gap-2">
- <div
- class="min-w-0 flex-1 overflow-x-auto rounded-md border bg-background px-3 py-2 font-mono text-xs whitespace-nowrap"
- >
+ <div class="min-w-0 flex-1 overflow-x-auto rounded-md border bg-background px-3 py-2 font-mono text-xs whitespace-nowrap">
{{ mcpCommand }}
</div>
- <Button
- type="button"
- variant="outline"
- size="icon"
- :title="t('common.copy')"
- @click="copyMcpText('install', mcpCommand)"
- >
+ <Button type="button" variant="outline" size="icon" :title="t('common.copy')" @click="copyMcpText('install', mcpCommand)">
<CheckCircle2 v-if="mcpCopied === 'install'" class="h-4 w-4 text-green-500" />
<Copy v-else class="h-4 w-4" />
</Button>
@@ -2482,17 +2108,8 @@ watch(
<TabsContent value="claude" class="m-0">
<div class="relative rounded-md border bg-background p-3">
- <pre
- class="overflow-x-auto whitespace-pre text-xs leading-relaxed"
- ><code>{{ mcpClaudeRecommendedConfig }}</code></pre>
- <Button
- type="button"
- variant="outline"
- size="icon"
- class="absolute right-2 top-2 h-7 w-7"
- :title="t('common.copy')"
- @click="copyMcpText('claude-config', mcpClaudeRecommendedConfig)"
- >
+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpClaudeRecommendedConfig }}</code></pre>
+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('claude-config', mcpClaudeRecommendedConfig)">
<CheckCircle2 v-if="mcpCopied === 'claude-config'" class="h-3.5 w-3.5 text-green-500" />
<Copy v-else class="h-3.5 w-3.5" />
</Button>
@@ -2505,17 +2122,8 @@ watch(
{{ t("settings.mcpCodexConfigPath") }}
</div>
<div class="relative rounded-md border bg-background p-3">
- <pre
- class="overflow-x-auto whitespace-pre text-xs leading-relaxed"
- ><code>{{ mcpCodexRecommendedConfig }}</code></pre>
- <Button
- type="button"
- variant="outline"
- size="icon"
- class="absolute right-2 top-2 h-7 w-7"
- :title="t('common.copy')"
- @click="copyMcpText('codex-config', mcpCodexRecommendedConfig)"
- >
+ <pre class="overflow-x-auto whitespace-pre text-xs leading-relaxed"><code>{{ mcpCodexRecommendedConfig }}</code></pre>
+ <Button type="button" variant="outline" size="icon" class="absolute right-2 top-2 h-7 w-7" :title="t('common.copy')" @click="copyMcpText('codex-config', mcpCodexRecommendedConfig)">
<CheckCircle2 v-if="mcpCopied === 'codex-config'" class="h-3.5 w-3.5 text-green-500" />
<Copy v-else class="h-3.5 w-3.5" />
</Button>
@@ -2525,10 +2133,7 @@ watch(
</Tabs>
</div>
- <div
- v-if="mcpStatus?.error || mcpStatusError"
- class="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300"
- >
+ <div v-if="mcpStatus?.error || mcpStatusError" class="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
{{ mcpStatusError || mcpStatus?.error }}
</div>
@@ -2542,32 +2147,10 @@ watch(
<div class="space-y-3">
<Label class="text-base">{{ t("auth.changePassword") }}</Label>
<p class="text-sm text-muted-foreground">{{ t("auth.changePasswordDescription") }}</p>
- <Input
- v-model="oldPassword"
- type="password"
- :placeholder="t('auth.oldPassword')"
- class="h-9"
- autocomplete="off"
- />
- <Input
- v-model="newPassword"
- type="password"
- :placeholder="t('auth.newPassword')"
- class="h-9"
- autocomplete="off"
- />
- <Input
- v-model="confirmNewPassword"
- type="password"
- :placeholder="t('auth.confirmPassword')"
- class="h-9"
- autocomplete="off"
- />
- <p
- v-if="passwordMessage"
- class="text-xs"
- :class="passwordError ? 'text-destructive' : 'text-green-500'"
- >
+ <Input v-model="oldPassword" type="password" :placeholder="t('auth.oldPassword')" class="h-9" autocomplete="off" />
+ <Input v-model="newPassword" type="password" :placeholder="t('auth.newPassword')" class="h-9" autocomplete="off" />
+ <Input v-model="confirmNewPassword" type="password" :placeholder="t('auth.confirmPassword')" class="h-9" autocomplete="off" />
+ <p v-if="passwordMessage" class="text-xs" :class="passwordError ? 'text-destructive' : 'text-green-500'">
{{ passwordMessage }}
</p>
</div>
@@ -2580,21 +2163,14 @@ watch(
<div class="text-lg font-semibold">DBX</div>
<p class="text-sm text-muted-foreground">{{ t("settings.aboutDescription") }}</p>
</div>
- <div
- v-if="displayedAppVersion"
- class="rounded-md border bg-background px-2 py-1 text-xs text-muted-foreground"
- >
+ <div v-if="displayedAppVersion" class="rounded-md border bg-background px-2 py-1 text-xs text-muted-foreground">
{{ displayedAppVersion }}
</div>
</div>
</div>
<div class="grid gap-3 sm:grid-cols-2">
- <button
- type="button"
- class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- @click="openExternalUrl('https://qm.qq.com/cgi-bin/qm/qr?k=&group_code=1087880322')"
- >
+ <button type="button" class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click="openExternalUrl('https://qm.qq.com/cgi-bin/qm/qr?k=&group_code=1087880322')">
<div class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{{ t("settings.community") }}
</div>
@@ -2609,30 +2185,18 @@ watch(
</div>
<div class="mt-1 font-mono text-base">1087880322</div>
</button>
- <button
- type="button"
- class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- @click="openExternalUrl('https://discord.gg/W7NyVDRt6a')"
- >
+ <button type="button" class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click="openExternalUrl('https://discord.gg/W7NyVDRt6a')">
<div class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{{ t("settings.community") }}
</div>
<div class="mt-3 flex items-center gap-2 text-sm font-medium">
- <img
- src="https://cdn.simpleicons.org/discord/5865F2"
- alt="Discord"
- class="h-7 w-7 rounded-md bg-white p-1"
- />
+ <img src="https://cdn.simpleicons.org/discord/5865F2" alt="Discord" class="h-7 w-7 rounded-md bg-white p-1" />
Discord
<ExternalLink class="ml-auto h-3.5 w-3.5 text-muted-foreground" />
</div>
<div class="mt-1 text-sm text-primary">discord.gg/W7NyVDRt6a</div>
</button>
- <button
- type="button"
- class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- @click="openExternalUrl('https://docs.qq.com/doc/DVVhMY0h1ekJqc0tz')"
- >
+ <button type="button" class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click="openExternalUrl('https://docs.qq.com/doc/DVVhMY0h1ekJqc0tz')">
<div class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{{ t("settings.community") }}
</div>
@@ -2649,30 +2213,18 @@ watch(
</div>
<div class="mt-1 text-sm text-primary">{{ t("settings.wechatGroupInvite") }}</div>
</button>
- <button
- type="button"
- class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- @click="openExternalUrl('https://github.com/t8y2/dbx')"
- >
+ <button type="button" class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click="openExternalUrl('https://github.com/t8y2/dbx')">
<div class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{{ t("settings.project") }}
</div>
<div class="mt-3 flex items-center gap-2 text-sm font-medium">
- <img
- src="https://cdn.simpleicons.org/github/181717"
- alt="GitHub"
- class="h-7 w-7 rounded-md bg-white p-1"
- />
+ <img src="https://cdn.simpleicons.org/github/181717" alt="GitHub" class="h-7 w-7 rounded-md bg-white p-1" />
{{ t("settings.openSource") }}
<ExternalLink class="ml-auto h-3.5 w-3.5 text-muted-foreground" />
</div>
<div class="mt-1 text-sm text-primary">github.com/t8y2/dbx</div>
</button>
- <button
- type="button"
- class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- @click="openExternalUrl('https://dbxio.com')"
- >
+ <button type="button" class="rounded-lg border p-4 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click="openExternalUrl('https://dbxio.com')">
<div class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{{ t("settings.project") }}
</div>
@@ -2687,10 +2239,7 @@ watch(
</section>
</div>
- <DialogFooter
- v-if="hasSettingsApplyFooter(activeSettingsTab as SettingsCategory)"
- class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 gap-3 sm:gap-3"
- >
+ <DialogFooter v-if="hasSettingsApplyFooter(activeSettingsTab as SettingsCategory)" class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 gap-3 sm:gap-3">
<Button variant="outline" @click="resetDefaults">
{{ t("settings.resetDefaults") }}
</Button>
@@ -2706,33 +2255,16 @@ watch(
</Button>
</DialogFooter>
- <DialogFooter
- v-else-if="activeSettingsTab === 'ai'"
- class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 gap-3 sm:gap-3"
- >
+ <DialogFooter v-else-if="activeSettingsTab === 'ai'" class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 gap-3 sm:gap-3">
<div class="flex flex-1 items-center gap-2">
- <Button
- size="sm"
- variant="outline"
- :disabled="
- aiTesting ||
- (aiRequiresApiKey && !aiEditApiKey?.trim()) ||
- !aiEditEndpoint?.trim() ||
- !aiEditModel?.trim()
- "
- @click="aiTestConn"
- >
+ <Button size="sm" variant="outline" :disabled="aiTesting || (aiRequiresApiKey && !aiEditApiKey?.trim()) || !aiEditEndpoint?.trim() || !aiEditModel?.trim()" @click="aiTestConn">
<Loader2 v-if="aiTesting" class="h-3 w-3 animate-spin mr-1" />
{{ t("connection.test") }}
</Button>
<span v-if="aiTestResult === 'success'" class="text-xs text-green-500">
{{ t("connection.testSuccess") }}
</span>
- <span
- v-else-if="aiTestResult === 'error'"
- class="text-xs text-destructive truncate max-w-[200px]"
- :title="aiTestError"
- >
+ <span v-else-if="aiTestResult === 'error'" class="text-xs text-destructive truncate max-w-[200px]" :title="aiTestError">
{{ aiTestError }}
</span>
</div>
@@ -2740,18 +2272,11 @@ watch(
<Button :disabled="!aiHasChanges()" @click="aiApplySettings">{{ t("settings.apply") }}</Button>
</DialogFooter>
- <DialogFooter
- v-else-if="activeSettingsTab === 'sync'"
- class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 gap-3 sm:gap-3"
- >
+ <DialogFooter v-else-if="activeSettingsTab === 'sync'" class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 gap-3 sm:gap-3">
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
- <p
- v-if="webdavMessage"
- class="text-xs self-center truncate max-w-[280px]"
- :class="webdavError ? 'text-destructive' : 'text-green-500'"
- >
+ <p v-if="webdavMessage" class="text-xs self-center truncate max-w-[280px]" :class="webdavError ? 'text-destructive' : 'text-green-500'">
{{ webdavMessage }}
</p>
<div class="flex-1" />
@@ -2771,10 +2296,7 @@ watch(
</Button>
</DialogFooter>
- <DialogFooter
- v-else-if="activeSettingsTab === 'mcp' && !isWeb"
- class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3"
- >
+ <DialogFooter v-else-if="activeSettingsTab === 'mcp' && !isWeb" class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3">
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
@@ -2790,25 +2312,16 @@ watch(
</Button>
</DialogFooter>
- <DialogFooter
- v-else-if="activeSettingsTab === 'security' && isWeb"
- class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3"
- >
+ <DialogFooter v-else-if="activeSettingsTab === 'security' && isWeb" class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3">
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
- <Button
- :disabled="changingPassword || !oldPassword || !newPassword || !confirmNewPassword"
- @click="changePassword"
- >
+ <Button :disabled="changingPassword || !oldPassword || !newPassword || !confirmNewPassword" @click="changePassword">
{{ t("auth.changePassword") }}
</Button>
</DialogFooter>
- <DialogFooter
- v-else-if="activeSettingsTab === 'about'"
- class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3"
- >
+ <DialogFooter v-else-if="activeSettingsTab === 'about'" class="mx-0 mb-0 shrink-0 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3">
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
@@ -2818,12 +2331,7 @@ watch(
</DialogContent>
<!-- Theme Customizer Dialog -->
- <ThemeCustomizerDialog
- v-model:open="showThemeCustomizer"
- :themes="editCustomThemes"
- :active-theme-id="editActiveCustomThemeId"
- @save="handleThemeSave"
- />
+ <ThemeCustomizerDialog v-model:open="showThemeCustomizer" :themes="editCustomThemes" :active-theme-id="editActiveCustomThemeId" @save="handleThemeSave" />
<!-- Snippet Add/Edit Dialog -->
<Dialog :open="snippetDialogOpen" @update:open="snippetDialogOpen = $event">
@@ -2836,19 +2344,11 @@ watch(
<div class="flex flex-col gap-4 py-2">
<div class="flex flex-col gap-1.5">
<Label for="snippet-label">{{ t("settings.snippetsLabel") }}</Label>
- <Input
- id="snippet-label"
- v-model="snippetForm.label"
- :placeholder="t('settings.snippetsLabelPlaceholder')"
- />
+ <Input id="snippet-label" v-model="snippetForm.label" :placeholder="t('settings.snippetsLabelPlaceholder')" />
</div>
<div class="flex flex-col gap-1.5">
<Label for="snippet-prefix">{{ t("settings.snippetsPrefix") }}</Label>
- <Input
- id="snippet-prefix"
- v-model="snippetForm.prefix"
- :placeholder="t('settings.snippetsPrefixPlaceholder')"
- />
+ <Input id="snippet-prefix" v-model="snippetForm.prefix" :placeholder="t('settings.snippetsPrefixPlaceholder')" />
<p v-if="snippetFormPrefixError" class="text-xs text-destructive">{{ snippetFormPrefixError }}</p>
</div>
<div class="flex flex-col gap-1.5">
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 046f6b66c5..4e297b3e7d 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -1,15 +1,5 @@
<script setup lang="ts">
-import {
- ref,
- onMounted,
- onBeforeUnmount,
- onActivated,
- onDeactivated,
- watch,
- shallowRef,
- computed,
- nextTick,
-} from "vue";
+import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated, watch, shallowRef, computed, nextTick } from "vue";
import { Play, Copy, TextSelect } from "@lucide/vue";
import { useI18n } from "vue-i18n";
import type { CompletionContext } from "@codemirror/autocomplete";
@@ -24,23 +14,8 @@ import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useTheme } from "@/composables/useTheme";
import { useToast } from "@/composables/useToast";
-import {
- buildSqlCompletionItemsFromContext,
- getSqlFunctionSignatureHelp,
- getSqlCompletionContext,
- getSqlCompletionResultValidFor,
- isSqlLikeCompletionStatement,
- recordCompletionSelection,
- shouldAutoOpenSqlCompletion,
- extractCteDefinitions,
-} from "@/lib/sqlCompletion";
-import {
- buildElasticsearchCompletionItemsFromContext,
- getElasticsearchCompletionContext,
- getElasticsearchCompletionResultValidFor,
- shouldAutoOpenElasticsearchCompletion,
- type ElasticsearchCompletionItem,
-} from "@/lib/elasticsearchCompletion";
+import { buildSqlCompletionItemsFromContext, getSqlFunctionSignatureHelp, getSqlCompletionContext, getSqlCompletionResultValidFor, isSqlLikeCompletionStatement, recordCompletionSelection, shouldAutoOpenSqlCompletion, extractCteDefinitions } from "@/lib/sqlCompletion";
+import { buildElasticsearchCompletionItemsFromContext, getElasticsearchCompletionContext, getElasticsearchCompletionResultValidFor, shouldAutoOpenElasticsearchCompletion, type ElasticsearchCompletionItem } from "@/lib/elasticsearchCompletion";
import { extractIdentifierAt, isSqlKeyword, matchTable } from "@/lib/sqlNavigation";
import { lineColumnToOffset, parseSqlErrorLocation } from "@/lib/sqlDiagnostics";
import {
@@ -54,43 +29,15 @@ import {
type QueryEditorTableReferenceDropDetail,
type QueryEditorTableReferencePayload,
} from "@/lib/queryEditorTableDrop";
-import {
- EDITOR_FONT_FAMILY_CSS_VAR,
- EDITOR_FONT_SIZE_CSS_VAR,
- loadEditorTheme,
- editorFontTheme,
- sqlCompletionTheme,
-} from "@/lib/editorThemes";
-import {
- clampEditorFontSize,
- createEditorZoomCommitScheduler,
- fontSizeFromGestureScale,
- fontSizeFromWheelDelta,
-} from "@/lib/editorZoom";
+import { EDITOR_FONT_FAMILY_CSS_VAR, EDITOR_FONT_SIZE_CSS_VAR, loadEditorTheme, editorFontTheme, sqlCompletionTheme } from "@/lib/editorThemes";
+import { clampEditorFontSize, createEditorZoomCommitScheduler, fontSizeFromGestureScale, fontSizeFromWheelDelta } from "@/lib/editorZoom";
import { shortcutToCodeMirrorKey } from "@/lib/shortcutRegistry";
import { trimmedSelectionLayer } from "@/lib/codemirrorTrimmedSelectionLayer";
import { selectionMatchOccurrences } from "@/lib/codemirrorSelectionMatches";
import * as api from "@/lib/api";
-import {
- areSqlSemanticDiagnosticsEqual,
- buildSqlParserErrorDiagnostic,
- buildSqlSemanticDiagnostics,
- shouldRunSqlSemanticDiagnostics,
- type SqlSemanticDiagnostic,
-} from "@/lib/sqlSemanticDiagnostics";
-import type {
- SqlCompletionColumn,
- SqlCompletionForeignKey,
- SqlCompletionItem,
- SqlCompletionObject,
-} from "@/lib/sqlCompletion";
-import type {
- DatabaseType,
- ForeignKeyInfo,
- SqlReferenceAnalysis,
- SqlTableReference,
- SqlTextSpan,
-} from "@/types/database";
+import { areSqlSemanticDiagnosticsEqual, buildSqlParserErrorDiagnostic, buildSqlSemanticDiagnostics, shouldRunSqlSemanticDiagnostics, type SqlSemanticDiagnostic } from "@/lib/sqlSemanticDiagnostics";
+import type { SqlCompletionColumn, SqlCompletionForeignKey, SqlCompletionItem, SqlCompletionObject } from "@/lib/sqlCompletion";
+import type { DatabaseType, ForeignKeyInfo, SqlReferenceAnalysis, SqlTableReference, SqlTextSpan } from "@/types/database";
const props = defineProps<{
modelValue: string;
@@ -180,9 +127,7 @@ const completionTranslations = computed(() => ({
numericLiteral: t("editor.completion.numericLiteral"),
booleanValue: t("editor.completion.booleanValue"),
starExpansionColumns: t("editor.completion.starExpansionColumns"),
- functionDescriptions: Object.fromEntries(
- SQL_FUNCTION_NAMES.map((name) => [name, t(`editor.completion.functionDescriptions.${name}`)]),
- ) as Record<string, string>,
+ functionDescriptions: Object.fromEntries(SQL_FUNCTION_NAMES.map((name) => [name, t(`editor.completion.functionDescriptions.${name}`)])) as Record<string, string>,
}));
const MAX_COMPLETION_TABLES = 200;
const liveFontSize = ref(settingsStore.editorSettings.fontSize);
@@ -196,9 +141,7 @@ const executableSql = ref("");
const hasSelectedSql = computed(() => selectedSql.value.trim().length > 0);
const canCopySelectedSql = computed(() => selectedSql.value.length > 0);
const canExecuteContextSql = computed(() => executableSql.value.trim().length > 0);
-const executeContextMenuLabel = computed(() =>
- t(hasSelectedSql.value ? "editor.contextMenu.executeSelection" : "editor.contextMenu.executeCurrent"),
-);
+const executeContextMenuLabel = computed(() => t(hasSelectedSql.value ? "editor.contextMenu.executeSelection" : "editor.contextMenu.executeCurrent"));
interface EditorGestureEvent extends Event {
scale?: number;
@@ -366,11 +309,7 @@ function selectAllSqlFromContextMenu() {
focusEditor();
}
-function selectSqlLineFromGutter(
- currentView: EditorViewType,
- line: { from: number; to: number },
- event: Event,
-): boolean {
+function selectSqlLineFromGutter(currentView: EditorViewType, line: { from: number; to: number }, event: Event): boolean {
if (!(event instanceof MouseEvent) || event.button !== 0) return false;
event.preventDefault();
currentView.dispatch({
@@ -480,12 +419,7 @@ function completionCacheKey(table: { name: string; schema?: string | null }) {
async function ensureColumnsForTable(table: { name: string; schema?: string | null }) {
const cacheKey = completionCacheKey(table);
if (cachedColumnsByTable.has(cacheKey) || !props.connectionId || props.database == null) return;
- const columns = await connectionStore.listCompletionColumns(
- props.connectionId,
- props.database,
- table.name,
- table.schema ?? props.schema,
- );
+ const columns = await connectionStore.listCompletionColumns(props.connectionId, props.database, table.name, table.schema ?? props.schema);
if (columns.length === 0) return;
cachedColumnsByTable.set(cacheKey, columns);
}
@@ -557,8 +491,7 @@ function createSignatureDom(signature: ReturnType<typeof getSqlFunctionSignature
signatureNode.appendChild(comma);
}
const parameterNode = document.createElement("span");
- parameterNode.className =
- index === signature.activeParameter ? "font-semibold text-foreground" : "text-muted-foreground";
+ parameterNode.className = index === signature.activeParameter ? "font-semibold text-foreground" : "text-muted-foreground";
parameterNode.textContent = parameter;
signatureNode.appendChild(parameterNode);
});
@@ -586,24 +519,12 @@ async function resolveSqlHoverTooltip(currentView: EditorViewType, pos: number)
try {
if (cachedTables.length === 0) {
- cachedTables = await connectionStore.listCompletionTables(
- props.connectionId,
- props.database,
- name,
- MAX_COMPLETION_TABLES,
- props.schema,
- );
+ cachedTables = await connectionStore.listCompletionTables(props.connectionId, props.database, name, MAX_COMPLETION_TABLES, props.schema);
}
let table = matchTable(identifier, cachedTables) ?? matchTable(name, cachedTables);
if (!table) {
- const hoverTables = await connectionStore.listCompletionTables(
- props.connectionId,
- props.database,
- name,
- MAX_COMPLETION_TABLES,
- props.schema,
- );
+ const hoverTables = await connectionStore.listCompletionTables(props.connectionId, props.database, name, MAX_COMPLETION_TABLES, props.schema);
cachedTables = [...cachedTables, ...hoverTables];
table = matchTable(identifier, hoverTables) ?? matchTable(name, hoverTables);
}
@@ -618,12 +539,7 @@ async function resolveSqlHoverTooltip(currentView: EditorViewType, pos: number)
}
const context = getSqlCompletionContext(sql, pos);
- const candidates = qualifier
- ? context.referencedTables.filter(
- (rt) =>
- rt.alias?.toLowerCase() === qualifier.toLowerCase() || rt.name.toLowerCase() === qualifier.toLowerCase(),
- )
- : context.referencedTables;
+ const candidates = qualifier ? context.referencedTables.filter((rt) => rt.alias?.toLowerCase() === qualifier.toLowerCase() || rt.name.toLowerCase() === qualifier.toLowerCase()) : context.referencedTables;
for (const refTable of candidates) {
await ensureColumnsForTable(refTable);
@@ -634,10 +550,7 @@ async function resolveSqlHoverTooltip(currentView: EditorViewType, pos: number)
pos: range.from,
end: range.to,
create: () => ({
- dom: createHoverDom(column.name, column.dataType || "column", [
- column.schema ? `${column.schema}.${column.table}` : column.table,
- ...(column.comment?.trim() ? [column.comment.trim()] : []),
- ]),
+ dom: createHoverDom(column.name, column.dataType || "column", [column.schema ? `${column.schema}.${column.table}` : column.table, ...(column.comment?.trim() ? [column.comment.trim()] : [])]),
}),
};
}
@@ -719,13 +632,7 @@ async function enrichSemanticDiagnosticTables(tables: SqlTableReference[]) {
continue;
}
try {
- const matches = await connectionStore.listCompletionTables(
- props.connectionId,
- props.database,
- table.name,
- MAX_COMPLETION_TABLES,
- props.schema,
- );
+ const matches = await connectionStore.listCompletionTables(props.connectionId, props.database, table.name, MAX_COMPLETION_TABLES, props.schema);
cachedTables = [...cachedTables, ...matches];
const match = matches.find((item) => item.name.toLowerCase() === table.name.toLowerCase());
enriched.push(match?.schema ? { ...table, schema: match.schema } : table);
@@ -753,9 +660,7 @@ async function refreshSemanticDiagnostics() {
setSemanticDiagnostics([]);
return;
}
- if (
- !shouldRunSqlSemanticDiagnostics(sql, currentView.state.selection.main.head, { databaseType: props.databaseType })
- ) {
+ if (!shouldRunSqlSemanticDiagnostics(sql, currentView.state.selection.main.head, { databaseType: props.databaseType })) {
scheduleSemanticDiagnostics(1200);
return;
}
@@ -809,24 +714,14 @@ async function formatCurrentSql() {
if (!source.trim()) return;
try {
- const formatted = await formatSqlText(
- source,
- props.formatDialect ?? props.dialect ?? "generic",
- settingsStore.editorSettings.sqlFormatter,
- );
- if (
- view.value !== currentView ||
- currentView.state !== originalState ||
- currentView.state.sliceDoc(from, to) !== source
- ) {
+ const formatted = await formatSqlText(source, props.formatDialect ?? props.dialect ?? "generic", settingsStore.editorSettings.sqlFormatter);
+ if (view.value !== currentView || currentView.state !== originalState || currentView.state.sliceDoc(from, to) !== source) {
return;
}
if (formatted === source) return;
currentView.dispatch({
changes: { from, to, insert: formatted },
- selection: formatsSelection
- ? { anchor: from, head: from + formatted.length }
- : { anchor: from + formatted.length },
+ selection: formatsSelection ? { anchor: from, head: from + formatted.length } : { anchor: from + formatted.length },
});
} catch (e: any) {
emit("formatError", String(e?.message || e));
@@ -834,21 +729,14 @@ async function formatCurrentSql() {
}
function droppedTableReference(event: DragEvent) {
- return (
- activeTableReferencePayloadValue() ??
- parseTableReferencePayload(event.dataTransfer?.getData(DBX_TABLE_REFERENCE_MIME))
- );
+ return activeTableReferencePayloadValue() ?? parseTableReferencePayload(event.dataTransfer?.getData(DBX_TABLE_REFERENCE_MIME));
}
function hasDroppedTableReference(event: DragEvent) {
return !!activeTableReferencePayloadValue() || hasTableReferencePayloadType(event.dataTransfer?.types);
}
-function insertTableReferencePayload(
- currentView: EditorViewType,
- payload: QueryEditorTableReferencePayload,
- coords?: { clientX: number; clientY: number },
-): boolean {
+function insertTableReferencePayload(currentView: EditorViewType, payload: QueryEditorTableReferencePayload, coords?: { clientX: number; clientY: number }): boolean {
if (props.readOnly) return false;
const insertText = tableReferenceInsertText(payload, props.databaseType);
const dropPos = coords ? currentView.posAtCoords({ x: coords.clientX, y: coords.clientY }) : null;
@@ -951,11 +839,7 @@ function completionOptionForItem(item: QueryCompletionItem) {
};
}
-async function provideElasticsearchCompletions(
- currentState: import("@codemirror/state").EditorState,
- position: number,
- explicit: boolean,
-) {
+async function provideElasticsearchCompletions(currentState: import("@codemirror/state").EditorState, position: number, explicit: boolean) {
if (!props.connectionId) return null;
const epoch = ++completionEpoch;
const fullDoc = currentState.doc.toString();
@@ -976,11 +860,7 @@ async function provideElasticsearchCompletions(
return buildCompletionResult(items, completionContext.from, getElasticsearchCompletionResultValidFor());
}
-async function provideSqlCompletions(
- currentState: import("@codemirror/state").EditorState,
- position: number,
- explicit: boolean,
-) {
+async function provideSqlCompletions(currentState: import("@codemirror/state").EditorState, position: number, explicit: boolean) {
if (!props.connectionId) return null;
const fullDoc = currentState.doc.toString();
if (props.databaseType === "elasticsearch") {
@@ -1008,21 +888,11 @@ async function provideSqlCompletions(
dialect: props.dialect,
databaseType: props.databaseType,
});
- return buildCompletionResult(
- items,
- position - completionContext.prefix.length,
- getSqlCompletionResultValidFor(fullDoc, position),
- );
+ return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
}
const needsAsyncData =
- completionContext.suggestTables ||
- completionContext.suggestRoutines ||
- completionContext.exclusiveRoutineSuggestions ||
- !!completionContext.qualifier ||
- !!completionContext.insertTable ||
- completionContext.exclusiveColumnSuggestions ||
- completionContext.referencedTables.length > 0;
+ completionContext.suggestTables || completionContext.suggestRoutines || completionContext.exclusiveRoutineSuggestions || !!completionContext.qualifier || !!completionContext.insertTable || completionContext.exclusiveColumnSuggestions || completionContext.referencedTables.length > 0;
if (!needsAsyncData) {
const items = buildSqlCompletionItemsFromContext(completionContext, {
@@ -1035,11 +905,7 @@ async function provideSqlCompletions(
dialect: props.dialect,
databaseType: props.databaseType,
});
- return buildCompletionResult(
- items,
- position - completionContext.prefix.length,
- getSqlCompletionResultValidFor(fullDoc, position),
- );
+ return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
}
const localResult = buildLocalSqlCompletionResult(completionContext, fullDoc, position);
@@ -1081,71 +947,26 @@ async function provideSqlCompletions(
}
}
-function buildLocalSqlCompletionResult(
- completionContext: ReturnType<typeof getSqlCompletionContext>,
- fullDoc: string,
- position: number,
-) {
+function buildLocalSqlCompletionResult(completionContext: ReturnType<typeof getSqlCompletionContext>, fullDoc: string, position: number) {
if (!props.connectionId || props.database == null) return null;
- const shouldLoadTables =
- completionContext.suggestTables ||
- (!!completionContext.qualifier && !isReferencedTableQualifier(completionContext));
- const tableLookupSchema =
- completionContext.qualifier && completionContext.suggestTables ? completionContext.qualifier : props.schema;
- const tableLookupFilter =
- completionContext.qualifier && completionContext.suggestTables
- ? completionContext.prefix
- : completionContext.qualifier || completionContext.prefix;
- const tables = shouldLoadTables
- ? connectionStore.lookupLocalCompletionTables(
- props.connectionId,
- props.database,
- tableLookupFilter,
- MAX_COMPLETION_TABLES,
- tableLookupSchema,
- )
- : cachedTables;
-
- const shouldLoadObjects =
- completionContext.suggestRoutines ||
- completionContext.exclusiveRoutineSuggestions ||
- (!!completionContext.qualifier && !completionContext.exclusiveColumnSuggestions);
+ const shouldLoadTables = completionContext.suggestTables || (!!completionContext.qualifier && !isReferencedTableQualifier(completionContext));
+ const tableLookupSchema = completionContext.qualifier && completionContext.suggestTables ? completionContext.qualifier : props.schema;
+ const tableLookupFilter = completionContext.qualifier && completionContext.suggestTables ? completionContext.prefix : completionContext.qualifier || completionContext.prefix;
+ const tables = shouldLoadTables ? connectionStore.lookupLocalCompletionTables(props.connectionId, props.database, tableLookupFilter, MAX_COMPLETION_TABLES, tableLookupSchema) : cachedTables;
+
+ const shouldLoadObjects = completionContext.suggestRoutines || completionContext.exclusiveRoutineSuggestions || (!!completionContext.qualifier && !completionContext.exclusiveColumnSuggestions);
const completionObjects = shouldLoadObjects
- ? connectionStore.lookupLocalCompletionObjects(
- props.connectionId,
- props.database,
- completionContext.qualifier || completionContext.prefix,
- MAX_COMPLETION_TABLES,
- completionContext.qualifier && !completionContext.exclusiveColumnSuggestions
- ? completionContext.qualifier
- : props.schema,
- )
+ ? connectionStore.lookupLocalCompletionObjects(props.connectionId, props.database, completionContext.qualifier || completionContext.prefix, MAX_COMPLETION_TABLES, completionContext.qualifier && !completionContext.exclusiveColumnSuggestions ? completionContext.qualifier : props.schema)
: cachedCompletionObjects;
- const schemaNames =
- completionContext.suggestTables && !completionContext.qualifier && !completionContext.insertTable
- ? connectionStore.lookupLocalCompletionSchemas(
- props.connectionId,
- props.database,
- completionContext.prefix,
- MAX_COMPLETION_TABLES,
- )
- : [];
+ const schemaNames = completionContext.suggestTables && !completionContext.qualifier && !completionContext.insertTable ? connectionStore.lookupLocalCompletionSchemas(props.connectionId, props.database, completionContext.prefix, MAX_COMPLETION_TABLES) : [];
const columnsByTable = new Map<string, SqlCompletionColumn[]>();
if (completionContext.insertTable) {
const insertSchema = completionContext.insertSchema ?? props.schema;
- const insertColumns = connectionStore.lookupLocalCompletionColumns(
- props.connectionId,
- props.database,
- completionContext.insertTable,
- insertSchema,
- );
+ const insertColumns = connectionStore.lookupLocalCompletionColumns(props.connectionId, props.database, completionContext.insertTable, insertSchema);
if (insertColumns.length > 0) {
- columnsByTable.set(
- insertSchema ? `${insertSchema}.${completionContext.insertTable}` : completionContext.insertTable,
- insertColumns,
- );
+ columnsByTable.set(insertSchema ? `${insertSchema}.${completionContext.insertTable}` : completionContext.insertTable, insertColumns);
}
}
@@ -1165,26 +986,13 @@ function buildLocalSqlCompletionResult(
columnsByTable.set(cacheKey, cached);
continue;
}
- const localColumns = connectionStore.lookupLocalCompletionColumns(
- props.connectionId,
- props.database,
- refTable.name,
- refTable.schema ?? props.schema,
- );
+ const localColumns = connectionStore.lookupLocalCompletionColumns(props.connectionId, props.database, refTable.name, refTable.schema ?? props.schema);
if (localColumns.length > 0) {
columnsByTable.set(cacheKey, localColumns);
}
}
- if (
- tables.length === 0 &&
- completionObjects.length === 0 &&
- schemaNames.length === 0 &&
- columnsByTable.size === 0 &&
- (completionContext.exclusiveTableSuggestions ||
- completionContext.exclusiveColumnSuggestions ||
- completionContext.exclusiveRoutineSuggestions)
- ) {
+ if (tables.length === 0 && completionObjects.length === 0 && schemaNames.length === 0 && columnsByTable.size === 0 && (completionContext.exclusiveTableSuggestions || completionContext.exclusiveColumnSuggestions || completionContext.exclusiveRoutineSuggestions)) {
return null;
}
@@ -1200,41 +1008,23 @@ function buildLocalSqlCompletionResult(
databaseType: props.databaseType,
});
- return buildCompletionResult(
- items,
- position - completionContext.prefix.length,
- getSqlCompletionResultValidFor(fullDoc, position),
- );
+ return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
}
function scheduleCompletionMetadataRefresh(completionContext: ReturnType<typeof getSqlCompletionContext>) {
if (!props.connectionId || props.database == null) return;
const connectionId = props.connectionId;
const database = props.database;
- const schema =
- completionContext.qualifier && completionContext.suggestTables ? completionContext.qualifier : props.schema;
- if (
- completionContext.suggestTables ||
- (!!completionContext.qualifier && !isReferencedTableQualifier(completionContext))
- ) {
+ const schema = completionContext.qualifier && completionContext.suggestTables ? completionContext.qualifier : props.schema;
+ if (completionContext.suggestTables || (!!completionContext.qualifier && !isReferencedTableQualifier(completionContext))) {
void connectionStore
- .refreshCompletionTables(
- connectionId,
- database,
- completionContext.qualifier && !schema ? completionContext.qualifier : completionContext.prefix,
- MAX_COMPLETION_TABLES,
- schema,
- )
+ .refreshCompletionTables(connectionId, database, completionContext.qualifier && !schema ? completionContext.qualifier : completionContext.prefix, MAX_COMPLETION_TABLES, schema)
.then((tables) => {
cachedTables = mergeCompletionTables(cachedTables, tables);
})
.catch(() => {});
}
- if (
- completionContext.suggestRoutines ||
- completionContext.exclusiveRoutineSuggestions ||
- (!!completionContext.qualifier && !completionContext.exclusiveColumnSuggestions)
- ) {
+ if (completionContext.suggestRoutines || completionContext.exclusiveRoutineSuggestions || (!!completionContext.qualifier && !completionContext.exclusiveColumnSuggestions)) {
void connectionStore
.refreshCompletionObjects(connectionId, database, completionContext.prefix, MAX_COMPLETION_TABLES, props.schema)
.then((objects) => {
@@ -1268,10 +1058,7 @@ function scheduleCompletionMetadataRefresh(completionContext: ReturnType<typeof
}
}
-function mergeCompletionTables(
- existing: Array<{ name: string; schema?: string; type?: "table" | "view" }>,
- incoming: Array<{ name: string; schema?: string; type?: "table" | "view" }>,
-) {
+function mergeCompletionTables(existing: Array<{ name: string; schema?: string; type?: "table" | "view" }>, incoming: Array<{ name: string; schema?: string; type?: "table" | "view" }>) {
const merged = [...existing];
const seen = new Set(existing.map((table) => `${table.schema ?? ""}.${table.name}`.toLowerCase()));
for (const table of incoming) {
@@ -1283,28 +1070,16 @@ function mergeCompletionTables(
return merged;
}
-async function performAsyncCompletionWithResult(
- epoch: number,
- completionContext: ReturnType<typeof getSqlCompletionContext>,
- fullDoc: string,
- position: number,
-) {
+async function performAsyncCompletionWithResult(epoch: number, completionContext: ReturnType<typeof getSqlCompletionContext>, fullDoc: string, position: number) {
// Handle INSERT column list: fetch columns for the target table
let insertColumnsByTable = new Map<string, SqlCompletionColumn[]>();
if (completionContext.insertTable) {
try {
- const insertCols = await connectionStore.listCompletionColumns(
- props.connectionId!,
- props.database!,
- completionContext.insertTable,
- completionContext.insertSchema ?? props.schema,
- );
+ const insertCols = await connectionStore.listCompletionColumns(props.connectionId!, props.database!, completionContext.insertTable, completionContext.insertSchema ?? props.schema);
if (epoch !== completionEpoch) return null;
if (insertCols.length > 0) {
const insertSchema = completionContext.insertSchema ?? props.schema;
- const insertKey = insertSchema
- ? `${insertSchema}.${completionContext.insertTable}`
- : completionContext.insertTable;
+ const insertKey = insertSchema ? `${insertSchema}.${completionContext.insertTable}` : completionContext.insertTable;
insertColumnsByTable.set(insertKey, insertCols);
}
} catch {
@@ -1312,43 +1087,16 @@ async function performAsyncCompletionWithResult(
}
}
- const shouldLoadTables =
- completionContext.suggestTables ||
- (!!completionContext.qualifier && !isReferencedTableQualifier(completionContext));
- let tables = shouldLoadTables
- ? await connectionStore.listCompletionTables(
- props.connectionId!,
- props.database!,
- completionContext.qualifier || completionContext.prefix,
- MAX_COMPLETION_TABLES,
- props.schema,
- )
- : cachedTables;
+ const shouldLoadTables = completionContext.suggestTables || (!!completionContext.qualifier && !isReferencedTableQualifier(completionContext));
+ let tables = shouldLoadTables ? await connectionStore.listCompletionTables(props.connectionId!, props.database!, completionContext.qualifier || completionContext.prefix, MAX_COMPLETION_TABLES, props.schema) : cachedTables;
if (epoch !== completionEpoch) return null;
- const shouldLoadObjects =
- completionContext.suggestRoutines ||
- completionContext.exclusiveRoutineSuggestions ||
- (!!completionContext.qualifier && !completionContext.exclusiveColumnSuggestions);
- let completionObjects = shouldLoadObjects
- ? await connectionStore.listCompletionObjects(
- props.connectionId!,
- props.database!,
- completionContext.qualifier || completionContext.prefix,
- MAX_COMPLETION_TABLES,
- props.schema,
- )
- : cachedCompletionObjects;
+ const shouldLoadObjects = completionContext.suggestRoutines || completionContext.exclusiveRoutineSuggestions || (!!completionContext.qualifier && !completionContext.exclusiveColumnSuggestions);
+ let completionObjects = shouldLoadObjects ? await connectionStore.listCompletionObjects(props.connectionId!, props.database!, completionContext.qualifier || completionContext.prefix, MAX_COMPLETION_TABLES, props.schema) : cachedCompletionObjects;
if (epoch !== completionEpoch) return null;
if (completionContext.qualifier && completionObjects.length === 0) {
- const schemaObjects = await connectionStore.listCompletionObjects(
- props.connectionId!,
- props.database!,
- completionContext.prefix,
- MAX_COMPLETION_TABLES,
- completionContext.qualifier,
- );
+ const schemaObjects = await connectionStore.listCompletionObjects(props.connectionId!, props.database!, completionContext.prefix, MAX_COMPLETION_TABLES, completionContext.qualifier);
if (schemaObjects.length > 0) {
completionObjects = schemaObjects;
}
@@ -1369,18 +1117,8 @@ async function performAsyncCompletionWithResult(
// If qualifier didn't match any table names, try it as a schema name
let qualifierIsSchema = false;
- if (
- completionContext.qualifier &&
- tables.length === 0 &&
- (completionContext.suggestTables || completionContext.exclusiveColumnSuggestions)
- ) {
- const schemaTables = await connectionStore.listCompletionTables(
- props.connectionId!,
- props.database!,
- completionContext.prefix,
- MAX_COMPLETION_TABLES,
- completionContext.qualifier,
- );
+ if (completionContext.qualifier && tables.length === 0 && (completionContext.suggestTables || completionContext.exclusiveColumnSuggestions)) {
+ const schemaTables = await connectionStore.listCompletionTables(props.connectionId!, props.database!, completionContext.prefix, MAX_COMPLETION_TABLES, completionContext.qualifier);
if (schemaTables.length > 0) {
tables = schemaTables;
qualifierIsSchema = true;
@@ -1400,11 +1138,7 @@ async function performAsyncCompletionWithResult(
});
const unresolvedRefs = refs.filter((rt) => !rt.schema && !rt.columns);
if (unresolvedRefs.length > 0) {
- const lookupGroups = await Promise.all(
- unresolvedRefs.map((rt) =>
- connectionStore.listCompletionTables(props.connectionId!, props.database!, rt.name, 20, props.schema),
- ),
- );
+ const lookupGroups = await Promise.all(unresolvedRefs.map((rt) => connectionStore.listCompletionTables(props.connectionId!, props.database!, rt.name, 20, props.schema)));
if (epoch !== completionEpoch) return null;
const lookupTables = lookupGroups.flat();
refs = refs.map((rt) => {
@@ -1437,12 +1171,7 @@ async function performAsyncCompletionWithResult(
const cacheKey = refTable.schema ? `${refTable.schema}.${refTable.name}` : refTable.name;
if (cachedColumnsByTable.has(cacheKey)) return;
try {
- const columns = await connectionStore.listCompletionColumns(
- props.connectionId!,
- props.database!,
- refTable.name,
- refTable.schema ?? props.schema,
- );
+ const columns = await connectionStore.listCompletionColumns(props.connectionId!, props.database!, refTable.name, refTable.schema ?? props.schema);
if (epoch !== completionEpoch) return;
if (columns.length === 0) return;
cachedColumnsByTable.set(cacheKey, columns);
@@ -1518,28 +1247,18 @@ async function performAsyncCompletionWithResult(
databaseType: props.databaseType,
});
- return buildCompletionResult(
- items,
- position - completionContext.prefix.length,
- getSqlCompletionResultValidFor(fullDoc, position),
- );
+ return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
}
function isReferencedTableQualifier(completionContext: ReturnType<typeof getSqlCompletionContext>): boolean {
if (!completionContext.qualifier) return false;
const qualifier = completionContext.qualifier.toLowerCase();
- return completionContext.referencedTables.some(
- (table) => table.alias?.toLowerCase() === qualifier || table.name.toLowerCase() === qualifier,
- );
+ return completionContext.referencedTables.some((table) => table.alias?.toLowerCase() === qualifier || table.name.toLowerCase() === qualifier);
}
function mergeCompletionObjects(existing: SqlCompletionObject[], incoming: SqlCompletionObject[]) {
const merged = [...existing];
- const seen = new Set(
- existing.map((object) =>
- `${object.type}:${object.schema ?? ""}:${object.name}:${object.parentName ?? ""}`.toLowerCase(),
- ),
- );
+ const seen = new Set(existing.map((object) => `${object.type}:${object.schema ?? ""}:${object.name}:${object.parentName ?? ""}`.toLowerCase()));
for (const object of incoming) {
const key = `${object.type}:${object.schema ?? ""}:${object.name}:${object.parentName ?? ""}`.toLowerCase();
if (seen.has(key)) continue;
@@ -1560,46 +1279,14 @@ onMounted(async () => {
if (!editorRef.value) return;
const [
- {
- EditorView,
- keymap,
- rectangularSelection,
- hoverTooltip,
- showTooltip,
- Decoration,
- tooltips,
- lineNumbers,
- highlightActiveLineGutter,
- highlightSpecialChars,
- drawSelection,
- dropCursor,
- crosshairCursor,
- ViewPlugin,
- },
+ { EditorView, keymap, rectangularSelection, hoverTooltip, showTooltip, Decoration, tooltips, lineNumbers, highlightActiveLineGutter, highlightSpecialChars, drawSelection, dropCursor, crosshairCursor, ViewPlugin },
{ EditorState, Compartment, Prec, StateEffect, StateField },
{ sql, MSSQL, MySQL, PostgreSQL, SQLDialect },
- {
- autocompletion,
- startCompletion,
- acceptCompletion,
- closeBrackets,
- closeBracketsKeymap,
- snippetCompletion,
- completionStatus,
- completionKeymap,
- },
+ { autocompletion, startCompletion, acceptCompletion, closeBrackets, closeBracketsKeymap, snippetCompletion, completionStatus, completionKeymap },
{ indentMore, insertNewlineKeepIndent, history, defaultKeymap, historyKeymap },
{ bracketMatching, foldGutter, indentOnInput, syntaxHighlighting, defaultHighlightStyle, foldKeymap },
{ searchKeymap },
- ] = await Promise.all([
- import("@codemirror/view"),
- import("@codemirror/state"),
- import("@codemirror/lang-sql"),
- import("@codemirror/autocomplete"),
- import("@codemirror/commands"),
- import("@codemirror/language"),
- import("@codemirror/search"),
- ]);
+ ] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("@codemirror/autocomplete"), import("@codemirror/commands"), import("@codemirror/language"), import("@codemirror/search")]);
editorViewModule = { EditorView, keymap, rectangularSelection } as typeof import("@codemirror/view");
codeMirrorPrec = Prec;
codeMirrorSnippetCompletion = snippetCompletion;
@@ -1649,8 +1336,7 @@ onMounted(async () => {
const field = StateField.define({
create: buildDecorations,
update(value, transaction) {
- const diagnosticsChanged =
- !!diagnosticEffect && transaction.effects.some((effect) => effect.is(diagnosticEffect));
+ const diagnosticsChanged = !!diagnosticEffect && transaction.effects.some((effect) => effect.is(diagnosticEffect));
return transaction.docChanged || diagnosticsChanged ? buildDecorations(transaction.state) : value;
},
provide: (field) => EditorView.decorations.from(field),
@@ -1674,22 +1360,17 @@ onMounted(async () => {
buildSqlCompletionExtension = () =>
autocompletion({
activateOnTyping: true,
- override: [
- async (context: CompletionContext) => provideSqlCompletions(context.state, context.pos, context.explicit),
- ],
+ override: [async (context: CompletionContext) => provideSqlCompletions(context.state, context.pos, context.explicit)],
});
const baseDialect = props.dialect === "postgres" ? PostgreSQL : props.dialect === "sqlserver" ? MSSQL : MySQL;
- const extraKeywords =
- "PIVOT UNPIVOT EXCLUDE REPLACE QUALIFY ASOF POSITIONAL ANTI SEMI SAMPLE TABLESAMPLE STRUCT MAP LIST ARRAY LAMBDA UNNEST LATERAL FILTER RECURSIVE SUMMARIZE PRAGMA READ_CSV READ_PARQUET READ_JSON DESCRIBE SHOW COPY EXPORT IMPORT";
+ const extraKeywords = "PIVOT UNPIVOT EXCLUDE REPLACE QUALIFY ASOF POSITIONAL ANTI SEMI SAMPLE TABLESAMPLE STRUCT MAP LIST ARRAY LAMBDA UNNEST LATERAL FILTER RECURSIVE SUMMARIZE PRAGMA READ_CSV READ_PARQUET READ_JSON DESCRIBE SHOW COPY EXPORT IMPORT";
// PL/pgSQL extension: add procedural language keywords and built-in variables for PostgreSQL function/procedure bodies
const isPostgres = props.dialect === "postgres";
const plpgsqlKeywords = isPostgres ? "PERFORM" : "";
const plpgsqlTypes = isPostgres ? " RECORD JSON JSONB" : "";
- const plpgsqlBuiltin = isPostgres
- ? "SQLERRM TG_NAME TG_WHEN TG_LEVEL TG_OP TG_RELID TG_RELNAME TG_TABLE_NAME TG_TABLE_SCHEMA TG_NARGS TG_ARGV"
- : "";
+ const plpgsqlBuiltin = isPostgres ? "SQLERRM TG_NAME TG_WHEN TG_LEVEL TG_OP TG_RELID TG_RELNAME TG_TABLE_NAME TG_TABLE_SCHEMA TG_NARGS TG_ARGV" : "";
const dialect = SQLDialect.define({
...baseDialect.spec,
@@ -1873,22 +1554,13 @@ onMounted(async () => {
try {
// Ensure table cache is populated
if (cachedTables.length === 0) {
- cachedTables = await connectionStore.listCompletionTables(
- props.connectionId!,
- props.database!,
- identifier,
- MAX_COMPLETION_TABLES,
- props.schema,
- );
+ cachedTables = await connectionStore.listCompletionTables(props.connectionId!, props.database!, identifier, MAX_COMPLETION_TABLES, props.schema);
}
// 1. Check if it's a table name
const matchedTable = matchTable(identifier, cachedTables);
if (matchedTable) {
- emit(
- "clickTable",
- matchedTable.schema ? `${matchedTable.schema}.${matchedTable.name}` : matchedTable.name,
- );
+ emit("clickTable", matchedTable.schema ? `${matchedTable.schema}.${matchedTable.name}` : matchedTable.name);
return;
}
@@ -1914,13 +1586,7 @@ onMounted(async () => {
return;
}
// 3. Fetch columns — if qualifier, only check matching table; otherwise check all
- const tablesToCheck = qualifier
- ? referencedTables.filter(
- (rt) =>
- rt.alias?.toLowerCase() === qualifier.toLowerCase() ||
- rt.name.toLowerCase() === qualifier.toLowerCase(),
- )
- : referencedTables;
+ const tablesToCheck = qualifier ? referencedTables.filter((rt) => rt.alias?.toLowerCase() === qualifier.toLowerCase() || rt.name.toLowerCase() === qualifier.toLowerCase()) : referencedTables;
if (tablesToCheck.length === 0 && qualifier) {
return;
@@ -1935,12 +1601,7 @@ onMounted(async () => {
let cols = cachedColumnsByTable.get(cacheKey);
if (!cols) {
try {
- cols = await connectionStore.listCompletionColumns(
- props.connectionId!,
- props.database!,
- refTable.name,
- refTable.schema ?? props.schema,
- );
+ cols = await connectionStore.listCompletionColumns(props.connectionId!, props.database!, refTable.name, refTable.schema ?? props.schema);
cachedColumnsByTable.set(cacheKey, cols);
} catch {
continue;
@@ -2059,9 +1720,7 @@ watch(
function getCurrentCustomThemeColors() {
const settings = settingsStore.editorSettings;
if (settings.theme !== "custom") return settings.customThemeColors;
- const activeTheme =
- settings.customThemes?.find((t: { id: string }) => t.id === settings.activeCustomThemeId) ||
- settings.customThemes?.[0];
+ const activeTheme = settings.customThemes?.find((t: { id: string }) => t.id === settings.activeCustomThemeId) || settings.customThemes?.[0];
return activeTheme?.colors ?? settings.customThemeColors;
}
@@ -2079,11 +1738,7 @@ watch(
const themeColors = getCurrentCustomThemeColors();
const themeExt = await loadEditorTheme(ss.theme, editorThemeAppearance(), themeColors);
view.value.dispatch({
- effects: [
- codeMirrorTheme.reconfigure(themeExt),
- wordWrapComp.reconfigure(props.forceWordWrap || ss.wordWrap ? editorViewModule.EditorView.lineWrapping : []),
- runKeymapComp.reconfigure(runKeymapExtension(editorViewModule.keymap)),
- ],
+ effects: [codeMirrorTheme.reconfigure(themeExt), wordWrapComp.reconfigure(props.forceWordWrap || ss.wordWrap ? editorViewModule.EditorView.lineWrapping : []), runKeymapComp.reconfigure(runKeymapExtension(editorViewModule.keymap))],
});
},
{ deep: true },
@@ -2266,12 +1921,7 @@ defineExpose({ openSearch, openReplace, scrollCursorIntoView });
</script>
<template>
- <div
- class="h-full w-full overflow-hidden relative"
- @gesturestart="onEditorGestureStart"
- @gesturechange="onEditorGestureChange"
- @gestureend="onEditorGestureEnd"
- >
+ <div class="h-full w-full overflow-hidden relative" @gesturestart="onEditorGestureStart" @gesturechange="onEditorGestureChange" @gestureend="onEditorGestureEnd">
<CustomContextMenu :items="contextMenuItems" v-slot="{ onContextMenu }">
<div
ref="editorRef"
diff --git a/apps/desktop/src/components/editor/QueryHistory.vue b/apps/desktop/src/components/editor/QueryHistory.vue
index ec8d40036a..e9203e8c7f 100644
--- a/apps/desktop/src/components/editor/QueryHistory.vue
+++ b/apps/desktop/src/components/editor/QueryHistory.vue
@@ -47,9 +47,7 @@ const filtered = computed(() => {
return false;
}
if (!q) return true;
- return [entry.sql, entry.connection_name, entry.database, entry.operation, entry.target]
- .filter(Boolean)
- .some((value) => String(value).toLowerCase().includes(q));
+ return [entry.sql, entry.connection_name, entry.database, entry.operation, entry.target].filter(Boolean).some((value) => String(value).toLowerCase().includes(q));
});
});
@@ -142,10 +140,7 @@ function detailsRows(entry: HistoryEntry) {
[t("history.detail.time"), formatFullTime(entry.executed_at)],
[t("history.detail.duration"), `${entry.execution_time_ms}ms`],
[t("history.detail.affectedRows"), entry.affected_rows ?? "-"],
- [
- t("history.detail.rollback"),
- canRollbackHistoryEntry(entry) ? t("history.rollbackAvailable") : t("history.rollbackUnavailable"),
- ],
+ [t("history.detail.rollback"), canRollbackHistoryEntry(entry) ? t("history.rollbackAvailable") : t("history.rollbackUnavailable")],
[t("history.detail.status"), entry.success ? t("history.success") : t("history.failed")],
];
if (entry.error) rows.push([t("history.detail.error"), entry.error]);
@@ -218,51 +213,23 @@ onMounted(() => store.load());
<div class="border-b shrink-0">
<div class="flex gap-1 overflow-x-auto px-2 pt-2">
- <button
- v-for="filter in filters"
- :key="filter"
- type="button"
- class="h-6 shrink-0 rounded border px-2 text-xs"
- :class="activeFilter === filter ? 'border-primary bg-primary text-primary-foreground' : 'bg-background'"
- @click="activeFilter = filter"
- >
+ <button v-for="filter in filters" :key="filter" type="button" class="h-6 shrink-0 rounded border px-2 text-xs" :class="activeFilter === filter ? 'border-primary bg-primary text-primary-foreground' : 'bg-background'" @click="activeFilter = filter">
{{ filterLabel(filter) }}
</button>
</div>
<div class="relative flex items-center px-2 py-1">
<Search class="absolute left-3 w-3 h-3 text-muted-foreground pointer-events-none" />
- <input
- v-model="searchText"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="flex-1 h-5 text-xs bg-transparent border rounded pl-5 pr-1 outline-none placeholder:text-muted-foreground"
- :placeholder="t('history.search')"
- />
+ <input v-model="searchText" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 text-xs bg-transparent border rounded pl-5 pr-1 outline-none placeholder:text-muted-foreground" :placeholder="t('history.search')" />
</div>
</div>
<div class="min-h-0 flex-1">
- <RecycleScroller
- v-if="shouldVirtualizeHistory(filtered.length)"
- class="h-full"
- :items="filtered"
- :item-size="HISTORY_ROW_HEIGHT"
- :buffer="HISTORY_SCROLL_BUFFER"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller v-if="shouldVirtualizeHistory(filtered.length)" class="h-full" :items="filtered" :item-size="HISTORY_ROW_HEIGHT" :buffer="HISTORY_SCROLL_BUFFER" :skip-hover="true" key-field="id">
<template #default="{ item: entry }">
<CustomContextMenu :items="getHistoryMenuItems(entry)" v-slot="{ onContextMenu }">
- <div
- class="h-[72px] cursor-pointer border-b border-border/50 px-3 py-2 text-xs hover:bg-accent/50"
- @click="selectedEntry = entry"
- @contextmenu="onContextMenu"
- >
+ <div class="h-[72px] cursor-pointer border-b border-border/50 px-3 py-2 text-xs hover:bg-accent/50" @click="selectedEntry = entry" @contextmenu="onContextMenu">
<div class="mb-0.5 flex items-center gap-1">
- <span
- class="inline-flex h-5 w-9 shrink-0 items-center justify-center rounded border px-1 text-[10px] leading-none text-muted-foreground"
- >
+ <span class="inline-flex h-5 w-9 shrink-0 items-center justify-center rounded border px-1 text-[10px] leading-none text-muted-foreground">
{{ kindShortLabel(entry) }}
</span>
<span class="truncate font-medium">{{ entryTitle(entry) }}</span>
@@ -310,10 +277,7 @@ onMounted(() => store.load());
{{ t("history.copy") }}
</Button>
</div>
- <pre
- class="max-h-48 overflow-auto rounded border bg-muted/30 p-3 text-xs"
- v-html="highlight(selectedEntry.sql)"
- ></pre>
+ <pre class="max-h-48 overflow-auto rounded border bg-muted/30 p-3 text-xs" v-html="highlight(selectedEntry.sql)"></pre>
</div>
<div v-if="selectedEntry.rollback_sql">
<div class="mb-1 flex items-center justify-between">
@@ -323,10 +287,7 @@ onMounted(() => store.load());
{{ t("history.copy") }}
</Button>
</div>
- <pre
- class="max-h-40 overflow-auto rounded border bg-muted/30 p-3 text-xs"
- v-html="highlight(selectedEntry.rollback_sql || '')"
- ></pre>
+ <pre class="max-h-40 overflow-auto rounded border bg-muted/30 p-3 text-xs" v-html="highlight(selectedEntry.rollback_sql || '')"></pre>
</div>
</div>
<DialogFooter>
@@ -335,11 +296,7 @@ onMounted(() => store.load());
{{ t("history.analyzeWithAi") }}
</Button>
<Button variant="outline" @click="selectedEntry && restore(selectedEntry)">{{ t("history.restore") }}</Button>
- <Button
- v-if="selectedEntry && canRollbackHistoryEntry(selectedEntry)"
- :disabled="isRollingBack"
- @click="rollback(selectedEntry)"
- >
+ <Button v-if="selectedEntry && canRollbackHistoryEntry(selectedEntry)" :disabled="isRollingBack" @click="rollback(selectedEntry)">
<RotateCcw class="h-4 w-4" />
{{ isRollingBack ? t("common.loading") : t("history.rollback") }}
</Button>
diff --git a/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue b/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
index 4c67758308..0c5d097d6c 100644
--- a/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
+++ b/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
@@ -247,13 +247,7 @@ function formatJsonDraft(): boolean {
async function loadCodeMirrorModules(): Promise<CodeMirrorModules> {
if (cmModules) return cmModules;
- const [view, state, langJson, commands, search] = await Promise.all([
- import("@codemirror/view"),
- import("@codemirror/state"),
- import("@codemirror/lang-json"),
- import("@codemirror/commands"),
- import("@codemirror/search"),
- ]);
+ const [view, state, langJson, commands, search] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-json"), import("@codemirror/commands"), import("@codemirror/search")]);
cmModules = { view, state, langJson, commands, search };
return cmModules;
}
@@ -349,10 +343,7 @@ watch(
(value) => {
if (activeMode.value === "json") {
const currentDraft = parseSqlFormatterConfig(jsonDraft.value);
- if (
- currentDraft.ok &&
- serializeSqlFormatterConfig(currentDraft.settings) === serializeSqlFormatterConfig(value)
- ) {
+ if (currentDraft.ok && serializeSqlFormatterConfig(currentDraft.settings) === serializeSqlFormatterConfig(value)) {
validateJsonDraft(jsonDraft.value);
return;
}
@@ -403,10 +394,7 @@ onBeforeUnmount(() => {
</Button>
</div>
- <p
- v-if="importError"
- class="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
- >
+ <p v-if="importError" class="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{{ importError }}
</p>
@@ -420,10 +408,7 @@ onBeforeUnmount(() => {
<div class="grid gap-4 md:grid-cols-3">
<div class="space-y-2">
<Label>{{ t("settings.sqlFormatterKeywordCase") }}</Label>
- <Select
- :model-value="settings.keywordCase"
- @update:model-value="(value: any) => onCaseOption('keywordCase', value)"
- >
+ <Select :model-value="settings.keywordCase" @update:model-value="(value: any) => onCaseOption('keywordCase', value)">
<SelectTrigger class="w-full">
<SelectValue />
</SelectTrigger>
@@ -437,10 +422,7 @@ onBeforeUnmount(() => {
<div class="space-y-2">
<Label>{{ t("settings.sqlFormatterFunctionCase") }}</Label>
- <Select
- :model-value="settings.functionCase"
- @update:model-value="(value: any) => onCaseOption('functionCase', value)"
- >
+ <Select :model-value="settings.functionCase" @update:model-value="(value: any) => onCaseOption('functionCase', value)">
<SelectTrigger class="w-full">
<SelectValue />
</SelectTrigger>
@@ -454,10 +436,7 @@ onBeforeUnmount(() => {
<div class="space-y-2">
<Label>{{ t("settings.sqlFormatterDataTypeCase") }}</Label>
- <Select
- :model-value="settings.dataTypeCase"
- @update:model-value="(value: any) => onCaseOption('dataTypeCase', value)"
- >
+ <Select :model-value="settings.dataTypeCase" @update:model-value="(value: any) => onCaseOption('dataTypeCase', value)">
<SelectTrigger class="w-full">
<SelectValue />
</SelectTrigger>
@@ -474,22 +453,10 @@ onBeforeUnmount(() => {
<div class="space-y-2">
<Label>{{ t("settings.sqlFormatterIndent") }}</Label>
<div class="grid grid-cols-2 gap-2">
- <Button
- type="button"
- variant="outline"
- class="justify-center"
- :class="!settings.useTabs ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="updateOption('useTabs', false)"
- >
+ <Button type="button" variant="outline" class="justify-center" :class="!settings.useTabs ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="updateOption('useTabs', false)">
{{ t("settings.sqlFormatterIndentSpaces") }}
</Button>
- <Button
- type="button"
- variant="outline"
- class="justify-center"
- :class="settings.useTabs ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
- @click="updateOption('useTabs', true)"
- >
+ <Button type="button" variant="outline" class="justify-center" :class="settings.useTabs ? 'border-blue-300 ring-2 ring-blue-300/50' : ''" @click="updateOption('useTabs', true)">
{{ t("settings.sqlFormatterIndentTabs") }}
</Button>
</div>
@@ -557,22 +524,14 @@ onBeforeUnmount(() => {
<div class="grid gap-3 md:grid-cols-2">
<div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
<Label for="sql-formatter-dense-operators">{{ t("settings.sqlFormatterDenseOperators") }}</Label>
- <Switch
- id="sql-formatter-dense-operators"
- :model-value="settings.denseOperators"
- @update:model-value="(value: boolean) => updateOption('denseOperators', value)"
- />
+ <Switch id="sql-formatter-dense-operators" :model-value="settings.denseOperators" @update:model-value="(value: boolean) => updateOption('denseOperators', value)" />
</div>
<div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
<Label for="sql-formatter-newline-before-semicolon">
{{ t("settings.sqlFormatterNewlineBeforeSemicolon") }}
</Label>
- <Switch
- id="sql-formatter-newline-before-semicolon"
- :model-value="settings.newlineBeforeSemicolon"
- @update:model-value="(value: boolean) => updateOption('newlineBeforeSemicolon', value)"
- />
+ <Switch id="sql-formatter-newline-before-semicolon" :model-value="settings.newlineBeforeSemicolon" @update:model-value="(value: boolean) => updateOption('newlineBeforeSemicolon', value)" />
</div>
</div>
</TabsContent>
@@ -592,19 +551,12 @@ onBeforeUnmount(() => {
<div ref="jsonEditorRef" class="min-h-[260px]" />
- <p
- v-if="jsonValidationMessage"
- class="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
- >
+ <p v-if="jsonValidationMessage" class="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{{ jsonValidationMessage }}
</p>
<div class="grid gap-1 rounded-md border border-border/70 bg-muted/20 p-2 sm:grid-cols-2">
- <div
- v-for="row in shortcutRows"
- :key="row.id"
- class="flex min-w-0 items-center justify-between gap-2 rounded px-1.5 py-1 text-xs"
- >
+ <div v-for="row in shortcutRows" :key="row.id" class="flex min-w-0 items-center justify-between gap-2 rounded px-1.5 py-1 text-xs">
<span class="truncate text-muted-foreground">{{ t(row.labelKey) }}</span>
<span class="shrink-0 rounded border bg-background px-1.5 py-0.5 font-mono text-[11px]">
{{ row.shortcut }}
diff --git a/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue b/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue
index 6cee27209d..bdaa4903e2 100644
--- a/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue
+++ b/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue
@@ -449,23 +449,10 @@ function handleImport() {
<div class="w-48 shrink-0 flex flex-col gap-2">
<div class="text-sm font-medium px-1">{{ t("settings.customThemeMyThemes") }}</div>
<div class="flex-1 overflow-y-auto space-y-1 pr-1">
- <div
- v-for="theme in localThemes"
- :key="theme.id"
- class="group flex items-center gap-2 rounded-md px-2 py-1.5 cursor-pointer text-sm"
- :class="activeEditId === theme.id ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'"
- @click="activeEditId = theme.id"
- >
+ <div v-for="theme in localThemes" :key="theme.id" class="group flex items-center gap-2 rounded-md px-2 py-1.5 cursor-pointer text-sm" :class="activeEditId === theme.id ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'" @click="activeEditId = theme.id">
<div class="flex-1 min-w-0">
<div v-if="renamingId === theme.id" class="flex items-center gap-1" @click.stop>
- <Input
- v-model="renamingName"
- class="h-6 text-xs px-1 py-0"
- @keydown.enter="confirmRename"
- @keydown.esc="cancelRename"
- @blur="confirmRename"
- autofocus
- />
+ <Input v-model="renamingName" class="h-6 text-xs px-1 py-0" @keydown.enter="confirmRename" @keydown.esc="cancelRename" @blur="confirmRename" autofocus />
</div>
<div v-else class="truncate">{{ theme.name }}</div>
</div>
@@ -505,9 +492,7 @@ function handleImport() {
{{ token.text }}<sup v-if="token.num" class="text-xl opacity-60">{{ token.num }}</sup>
</span>
</div>
- <div class="mt-2 text-lg" :style="{ color: localColors.comment }">
- <sup class="text-xl">⑥</sup> -- {{ t("settings.customThemePreviewExample") }}
- </div>
+ <div class="mt-2 text-lg" :style="{ color: localColors.comment }"><sup class="text-xl">⑥</sup> -- {{ t("settings.customThemePreviewExample") }}</div>
</div>
<!-- Preset color schemes -->
@@ -532,11 +517,7 @@ function handleImport() {
<!-- Color configuration list -->
<div class="grid grid-cols-2 gap-3">
- <div
- v-for="item in colorItems"
- :key="item.key"
- class="relative flex items-center gap-3 rounded-lg border p-3"
- >
+ <div v-for="item in colorItems" :key="item.key" class="relative flex items-center gap-3 rounded-lg border p-3">
<span class="text-xl font-bold w-8 text-center shrink-0">{{ item.num }}</span>
<div class="flex-1 min-w-0">
<div class="font-medium text-sm">{{ item.label }}</div>
@@ -545,45 +526,20 @@ function handleImport() {
<div class="flex items-center gap-2 shrink-0">
<!-- Color square + dropdown arrow -->
<div class="relative">
- <button
- type="button"
- class="flex items-center gap-0.5 rounded border p-0.5 hover:bg-muted transition-colors"
- @click.stop="togglePalette(item.key)"
- >
+ <button type="button" class="flex items-center gap-0.5 rounded border p-0.5 hover:bg-muted transition-colors" @click.stop="togglePalette(item.key)">
<div class="h-6 w-6 rounded-sm" :style="{ backgroundColor: localColors[item.key] }" />
<ChevronDown class="h-3 w-3 text-muted-foreground pointer-events-none" />
</button>
<!-- Palette popup -->
- <div
- v-if="expandedPalette === item.key"
- class="absolute right-0 top-full z-50 mt-1 rounded-lg border bg-popover p-2 shadow-lg"
- @click.stop
- >
+ <div v-if="expandedPalette === item.key" class="absolute right-0 top-full z-50 mt-1 rounded-lg border bg-popover p-2 shadow-lg" @click.stop>
<div class="space-y-1">
<div v-for="(row, rowIndex) in basicColors" :key="rowIndex" class="flex gap-1">
- <button
- v-for="color in row"
- :key="color"
- type="button"
- class="h-5 w-5 rounded-sm border border-border/50 hover:scale-110 transition-transform"
- :style="{ backgroundColor: color }"
- @click="applyBasicColor(item.key, color)"
- />
+ <button v-for="color in row" :key="color" type="button" class="h-5 w-5 rounded-sm border border-border/50 hover:scale-110 transition-transform" :style="{ backgroundColor: color }" @click="applyBasicColor(item.key, color)" />
</div>
</div>
<div class="mt-2 pt-2 border-t flex items-center gap-2">
- <input
- type="color"
- :value="localColors[item.key]"
- @input="handleColorChange(item.key, ($event.target as HTMLInputElement).value)"
- class="h-6 w-6 cursor-pointer rounded border-0 p-0"
- />
- <input
- type="text"
- :value="localColors[item.key]"
- @input="handleColorChange(item.key, ($event.target as HTMLInputElement).value)"
- class="w-20 rounded border px-2 py-0.5 text-xs font-mono"
- />
+ <input type="color" :value="localColors[item.key]" @input="handleColorChange(item.key, ($event.target as HTMLInputElement).value)" class="h-6 w-6 cursor-pointer rounded border-0 p-0" />
+ <input type="text" :value="localColors[item.key]" @input="handleColorChange(item.key, ($event.target as HTMLInputElement).value)" class="w-20 rounded border px-2 py-0.5 text-xs font-mono" />
</div>
</div>
</div>
@@ -593,19 +549,10 @@ function handleImport() {
</TabsContent>
<TabsContent value="json" class="space-y-4 flex-1 min-h-0 flex flex-col">
- <textarea
- v-model="jsonText"
- @blur="handleJsonChange"
- class="flex-1 w-full rounded-lg border bg-black/50 p-4 font-mono text-sm min-h-[360px]"
- spellcheck="false"
- />
+ <textarea v-model="jsonText" @blur="handleJsonChange" class="flex-1 w-full rounded-lg border bg-black/50 p-4 font-mono text-sm min-h-[360px]" spellcheck="false" />
<div class="flex gap-2">
- <Button variant="outline" size="sm" @click="handleImport">{{
- t("settings.customThemePasteImport")
- }}</Button>
- <Button variant="outline" size="sm" @click="handleExport">{{
- t("settings.customThemeExportJson")
- }}</Button>
+ <Button variant="outline" size="sm" @click="handleImport">{{ t("settings.customThemePasteImport") }}</Button>
+ <Button variant="outline" size="sm" @click="handleExport">{{ t("settings.customThemeExportJson") }}</Button>
</div>
</TabsContent>
</Tabs>
diff --git a/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue b/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue
index b5f39fdba8..e1a262d866 100644
--- a/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue
+++ b/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue
@@ -1,18 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import {
- ChevronDown,
- ChevronRight,
- FolderClosed,
- FolderOpen,
- KeyRound,
- Loader2,
- Plus,
- RefreshCw,
- Search,
- Trash2,
-} from "@lucide/vue";
+import { ChevronDown, ChevronRight, FolderClosed, FolderOpen, KeyRound, Loader2, Plus, RefreshCw, Search, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
@@ -20,12 +9,7 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import * as api from "@/lib/api";
import type { KvGetResponse, KvKeySummary, KvValue } from "@/lib/api";
-import {
- buildEtcdKeyTree,
- collectEtcdGroupIds,
- flattenVisibleEtcdKeyTree,
- type EtcdKeyTreeNode,
-} from "@/lib/etcdKeyTree";
+import { buildEtcdKeyTree, collectEtcdGroupIds, flattenVisibleEtcdKeyTree, type EtcdKeyTreeNode } from "@/lib/etcdKeyTree";
import { useToast } from "@/composables/useToast";
const props = defineProps<{ connectionId: string }>();
@@ -54,9 +38,7 @@ const pageSize = 200;
const tree = computed(() => buildEtcdKeyTree(keys.value));
const visibleRows = computed(() => flattenVisibleEtcdKeyTree(tree.value, expandedGroupIds.value));
-const selectedMetadata = computed(
- () => selectedValue.value?.metadata ?? keys.value.find((key) => key.key === selectedKey.value),
-);
+const selectedMetadata = computed(() => selectedValue.value?.metadata ?? keys.value.find((key) => key.key === selectedKey.value));
const selectedTextValue = computed(() => {
const value = selectedValue.value?.value;
if (!value) return "";
@@ -84,12 +66,7 @@ async function loadKeys(reset = true) {
loadingMore.value = true;
}
try {
- const result = await api.etcdListPrefix(
- props.connectionId,
- prefix.value.trim(),
- pageSize,
- reset ? null : continuation.value,
- );
+ const result = await api.etcdListPrefix(props.connectionId, prefix.value.trim(), pageSize, reset ? null : continuation.value);
const existing = new Set(keys.value.map((key) => key.key));
const merged = reset ? result.keys : [...keys.value, ...result.keys.filter((key) => !existing.has(key.key))];
keys.value = merged;
@@ -204,13 +181,7 @@ defineExpose({ focusSearch });
<div class="flex shrink-0 items-center gap-2 border-b px-3 py-2">
<div class="relative min-w-0 flex-1">
<Search class="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- ref="searchInputRef"
- v-model="prefix"
- class="h-8 pl-8"
- :placeholder="t('etcd.prefixPlaceholder')"
- @keyup.enter="loadKeys(true)"
- />
+ <Input ref="searchInputRef" v-model="prefix" class="h-8 pl-8" :placeholder="t('etcd.prefixPlaceholder')" @keyup.enter="loadKeys(true)" />
</div>
<Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="loading" @click="loadKeys(true)">
<Loader2 v-if="loading" class="h-3.5 w-3.5 animate-spin" />
@@ -229,10 +200,7 @@ defineExpose({ focusSearch });
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
{{ t("etcd.loadingKeys") }}
</div>
- <div
- v-else-if="visibleRows.length === 0"
- class="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
+ <div v-else-if="visibleRows.length === 0" class="flex h-full items-center justify-center text-sm text-muted-foreground">
{{ t("etcd.empty") }}
</div>
<div v-else class="h-full overflow-auto py-1 text-sm">
@@ -258,13 +226,7 @@ defineExpose({ focusSearch });
<span class="truncate">{{ row.node.label }}</span>
</button>
<div v-if="continuation" class="border-t p-2">
- <Button
- size="sm"
- variant="outline"
- class="h-8 w-full gap-1.5"
- :disabled="loadingMore"
- @click="loadKeys(false)"
- >
+ <Button size="sm" variant="outline" class="h-8 w-full gap-1.5" :disabled="loadingMore" @click="loadKeys(false)">
<Loader2 v-if="loadingMore" class="h-3.5 w-3.5 animate-spin" />
{{ t("etcd.loadMore") }}
</Button>
@@ -305,11 +267,7 @@ defineExpose({ focusSearch });
<div v-else-if="selectedValue && !selectedValue.found" class="p-4 text-sm text-muted-foreground">
{{ t("etcd.notFound") }}
</div>
- <pre
- v-else
- class="dbx-editor-font-family m-0 flex-1 overflow-auto whitespace-pre-wrap break-words p-4 text-sm"
- >{{ selectedTextValue }}</pre
- >
+ <pre v-else class="dbx-editor-font-family m-0 flex-1 overflow-auto whitespace-pre-wrap break-words p-4 text-sm">{{ selectedTextValue }}</pre>
</div>
</div>
</div>
@@ -321,11 +279,7 @@ defineExpose({ focusSearch });
</DialogHeader>
<div class="grid gap-3 py-2">
<Input v-model="editKey" :placeholder="t('etcd.keyPlaceholder')" />
- <textarea
- v-model="editValue"
- class="min-h-52 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- spellcheck="false"
- />
+ <textarea v-model="editValue" class="min-h-52 rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" spellcheck="false" />
<div v-if="editError" class="text-sm text-destructive">{{ editError }}</div>
</div>
<DialogFooter>
@@ -338,12 +292,6 @@ defineExpose({ focusSearch });
</DialogContent>
</Dialog>
- <DangerConfirmDialog
- v-model:open="showDeleteConfirm"
- :title="t('etcd.deleteTitle')"
- :details="selectedKey || ''"
- :confirm-label="t('etcd.delete')"
- @confirm="deleteSelectedKey"
- />
+ <DangerConfirmDialog v-model:open="showDeleteConfirm" :title="t('etcd.deleteTitle')" :details="selectedKey || ''" :confirm-label="t('etcd.delete')" @confirm="deleteSelectedKey" />
</div>
</template>
diff --git a/apps/desktop/src/components/explain/ExplainPlanNodeTree.vue b/apps/desktop/src/components/explain/ExplainPlanNodeTree.vue
index bab313852c..27f4e68e74 100644
--- a/apps/desktop/src/components/explain/ExplainPlanNodeTree.vue
+++ b/apps/desktop/src/components/explain/ExplainPlanNodeTree.vue
@@ -32,36 +32,21 @@ const rowDiffers = hasActualStats && actualRows !== props.node.rows;
<template>
<div>
<!-- Single line: collapse icon + title + badges all in one row -->
- <div
- class="flex cursor-pointer items-center gap-1 rounded border bg-background px-2 py-1 text-xs hover:bg-muted/30"
- :class="{ 'border-green-300 dark:border-green-700': hasActualStats }"
- @click="toggle"
- >
+ <div class="flex cursor-pointer items-center gap-1 rounded border bg-background px-2 py-1 text-xs hover:bg-muted/30" :class="{ 'border-green-300 dark:border-green-700': hasActualStats }" @click="toggle">
<ChevronRight v-if="node.children.length > 0 && collapsed" class="h-3 w-3 shrink-0 text-muted-foreground" />
<ChevronDown v-else-if="node.children.length > 0" class="h-3 w-3 shrink-0 text-muted-foreground" />
<span class="shrink-0 rounded bg-muted px-1 py-0.5 font-medium">{{ node.nodeType }}</span>
- <span v-if="node.relation" class="shrink-0 truncate max-w-[120px] text-blue-600 dark:text-blue-400">{{
- node.relation
- }}</span>
+ <span v-if="node.relation" class="shrink-0 truncate max-w-[120px] text-blue-600 dark:text-blue-400">{{ node.relation }}</span>
<span v-if="node.index" class="shrink-0 text-emerald-600 dark:text-emerald-400">[{{ node.index }}]</span>
<span v-if="node.cost" class="shrink-0 tabular-nums text-muted-foreground">c:{{ node.cost }}</span>
<span v-if="node.rows" class="shrink-0 tabular-nums text-amber-600 dark:text-amber-400">e:{{ node.rows }}</span>
- <span
- v-if="hasActualStats"
- class="shrink-0 tabular-nums font-semibold"
- :class="rowDiffers ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'"
- >a:{{ actualRows
- }}<span v-if="rowDiffers">({{ Math.round((Number(actualRows) / Number(node.rows)) * 100) }}%)</span></span
+ <span v-if="hasActualStats" class="shrink-0 tabular-nums font-semibold" :class="rowDiffers ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'"
+ >a:{{ actualRows }}<span v-if="rowDiffers">({{ Math.round((Number(actualRows) / Number(node.rows)) * 100) }}%)</span></span
>
<!-- Details collapsed into tooltip on hover -->
- <span
- v-if="node.details.length"
- class="ml-auto shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground/40"
- :title="node.details.join('\n')"
- >{{ node.details.join(" ") }}</span
- >
+ <span v-if="node.details.length" class="ml-auto shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground/40" :title="node.details.join('\n')">{{ node.details.join(" ") }}</span>
</div>
<!-- Children (collapsible) -->
diff --git a/apps/desktop/src/components/explain/ExplainPlanViewer.vue b/apps/desktop/src/components/explain/ExplainPlanViewer.vue
index 52726953ae..54722c4e3e 100644
--- a/apps/desktop/src/components/explain/ExplainPlanViewer.vue
+++ b/apps/desktop/src/components/explain/ExplainPlanViewer.vue
@@ -47,41 +47,19 @@ const nodeCount = computed(() => (props.plan ? flattenExplainPlanNodes(props.pla
<GitBranch class="h-3.5 w-3.5" />
{{ t("explain.title") }}
</span>
- <span v-if="plan" class="text-muted-foreground"
- >{{ plan.databaseType.toUpperCase() }} · {{ t("explain.nodeCount", { count: nodeCount }) }}</span
- >
- <span
- v-if="plan?.databaseType === 'dameng' && isRawString && rawContent.includes('->')"
- class="ml-1 inline-flex items-center gap-1 rounded bg-green-100 px-1.5 py-0.5 font-semibold text-green-700 dark:bg-green-900/30 dark:text-green-300"
- style="font-size: 10px"
- >A-TRACE</span
- >
+ <span v-if="plan" class="text-muted-foreground">{{ plan.databaseType.toUpperCase() }} · {{ t("explain.nodeCount", { count: nodeCount }) }}</span>
+ <span v-if="plan?.databaseType === 'dameng' && isRawString && rawContent.includes('->')" class="ml-1 inline-flex items-center gap-1 rounded bg-green-100 px-1.5 py-0.5 font-semibold text-green-700 dark:bg-green-900/30 dark:text-green-300" style="font-size: 10px">A-TRACE</span>
<span class="flex-1" />
<div v-if="plan" class="inline-flex rounded-md border bg-muted/40 p-0.5">
- <Button
- size="sm"
- :variant="activeView === 'tree' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs gap-1"
- @click="activeView = 'tree'"
- >
+ <Button size="sm" :variant="activeView === 'tree' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" @click="activeView = 'tree'">
<GitBranch class="h-3.5 w-3.5" />
{{ t("explain.tree") }}
</Button>
- <Button
- size="sm"
- :variant="activeView === 'summary' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs gap-1"
- @click="activeView = 'summary'"
- >
+ <Button size="sm" :variant="activeView === 'summary' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" @click="activeView = 'summary'">
<Table2 class="h-3.5 w-3.5" />
{{ t("explain.summary") }}
</Button>
- <Button
- size="sm"
- :variant="activeView === 'raw' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs gap-1"
- @click="activeView = 'raw'"
- >
+ <Button size="sm" :variant="activeView === 'raw' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" @click="activeView = 'raw'">
<FileText v-if="isRawString" class="h-3.5 w-3.5" />
<Braces v-else class="h-3.5 w-3.5" />
{{ isRawString ? "TEXT" : "JSON" }}
@@ -94,9 +72,7 @@ const nodeCount = computed(() => (props.plan ? flattenExplainPlanNodes(props.pla
</div>
<div v-else-if="error" class="flex-1 min-h-0 flex items-center justify-center">
- <div
- class="flex max-w-xl items-start gap-2 rounded border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive"
- >
+ <div class="flex max-w-xl items-start gap-2 rounded border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
<AlertCircle class="mt-0.5 h-4 w-4 shrink-0" />
<span>{{ error }}</span>
</div>
@@ -142,11 +118,7 @@ const nodeCount = computed(() => (props.plan ? flattenExplainPlanNodes(props.pla
</div>
</div>
- <pre
- v-else
- class="m-3 overflow-auto whitespace-pre rounded border bg-muted/30 p-3 font-mono text-xs leading-relaxed"
- >{{ rawContent }}</pre
- >
+ <pre v-else class="m-3 overflow-auto whitespace-pre rounded border bg-muted/30 p-3 font-mono text-xs leading-relaxed">{{ rawContent }}</pre>
</div>
</div>
</template>
diff --git a/apps/desktop/src/components/export/DatabaseExportDialog.vue b/apps/desktop/src/components/export/DatabaseExportDialog.vue
index ac6b17bfac..18885a0e4d 100644
--- a/apps/desktop/src/components/export/DatabaseExportDialog.vue
+++ b/apps/desktop/src/components/export/DatabaseExportDialog.vue
@@ -65,21 +65,9 @@ const exportCancelled = ref(false);
const pendingPrefillTable = ref("");
const pendingPrefillTables = ref<string[]>([]);
-const sqlConnections = computed(() =>
- store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)),
-);
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)));
-const canExport = computed(
- () =>
- connectionId.value &&
- database.value &&
- schema.value &&
- !loadingTables.value &&
- !tableError.value &&
- (tables.value.length === 0 || selectedTables.value.length > 0) &&
- (includeStructure.value || includeData.value || includeObjects.value) &&
- !isExporting.value,
-);
+const canExport = computed(() => connectionId.value && database.value && schema.value && !loadingTables.value && !tableError.value && (tables.value.length === 0 || selectedTables.value.length > 0) && (includeStructure.value || includeData.value || includeObjects.value) && !isExporting.value);
const selectedTableSet = computed(() => new Set(selectedTables.value));
@@ -121,12 +109,7 @@ async function loadSchemas(preferredSchema = "") {
}
const schemaList = await api.listSchemas(connectionId.value, database.value);
- const selected =
- preferredSchema && schemaList.includes(preferredSchema)
- ? preferredSchema
- : schemaList.includes("public")
- ? "public"
- : (schemaList[0] ?? "");
+ const selected = preferredSchema && schemaList.includes(preferredSchema) ? preferredSchema : schemaList.includes("public") ? "public" : (schemaList[0] ?? "");
schemas.value = schemaList;
schema.value = selected;
}
@@ -142,12 +125,7 @@ async function loadTables(preferredTable = "", preferredTables: string[] = []) {
const names = tableInfos.map((table) => table.name);
tables.value = names;
const preferredSet = new Set(preferredTables.filter((name) => names.includes(name)));
- selectedTables.value =
- preferredSet.size > 0
- ? names.filter((name) => preferredSet.has(name))
- : preferredTable && names.includes(preferredTable)
- ? [preferredTable]
- : [...names];
+ selectedTables.value = preferredSet.size > 0 ? names.filter((name) => preferredSet.has(name)) : preferredTable && names.includes(preferredTable) ? [preferredTable] : [...names];
} catch (e: any) {
tableError.value = e?.message || String(e);
} finally {
@@ -425,13 +403,7 @@ watch(
</Button>
</div>
<div class="max-h-40 overflow-auto space-y-1 pr-1">
- <button
- v-for="table in filteredTables"
- :key="table"
- type="button"
- class="flex w-full min-w-0 items-center gap-2 rounded px-1.5 py-1 text-left text-xs hover:bg-muted"
- @click="toggleTable(table)"
- >
+ <button v-for="table in filteredTables" :key="table" type="button" class="flex w-full min-w-0 items-center gap-2 rounded px-1.5 py-1 text-left text-xs hover:bg-muted" @click="toggleTable(table)">
<CheckSquare v-if="selectedTableSet.has(table)" class="w-3.5 h-3.5 text-primary shrink-0" />
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
<span class="truncate">{{ table }}</span>
@@ -453,11 +425,7 @@ watch(
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
{{ t("databaseExport.includeStructure") }}
</div>
- <div
- class="flex items-center gap-2 text-xs"
- :class="includeStructure ? 'cursor-pointer' : 'cursor-not-allowed text-muted-foreground/50'"
- @click="includeStructure && (dropTableIfExists = !dropTableIfExists)"
- >
+ <div class="flex items-center gap-2 text-xs" :class="includeStructure ? 'cursor-pointer' : 'cursor-not-allowed text-muted-foreground/50'" @click="includeStructure && (dropTableIfExists = !dropTableIfExists)">
<CheckSquare v-if="dropTableIfExists && includeStructure" class="w-3.5 h-3.5 text-primary shrink-0" />
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
{{ t("databaseExport.dropTableIfExists") }}
@@ -489,11 +457,7 @@ watch(
</div>
<div class="w-full bg-muted rounded-full h-2 overflow-hidden">
- <div
- class="h-full rounded-full transition-all duration-300"
- :class="exportError ? 'bg-destructive' : exportCancelled ? 'bg-yellow-500' : 'bg-primary'"
- :style="{ width: `${progressPercent}%` }"
- />
+ <div class="h-full rounded-full transition-all duration-300" :class="exportError ? 'bg-destructive' : exportCancelled ? 'bg-yellow-500' : 'bg-primary'" :style="{ width: `${progressPercent}%` }" />
</div>
<div class="text-xs text-muted-foreground">
diff --git a/apps/desktop/src/components/export/ExportProgressDialog.vue b/apps/desktop/src/components/export/ExportProgressDialog.vue
index ddf1c7c028..f9d5e5c14e 100644
--- a/apps/desktop/src/components/export/ExportProgressDialog.vue
+++ b/apps/desktop/src/components/export/ExportProgressDialog.vue
@@ -61,12 +61,7 @@ const rowsText = computed(() => {
<!-- Progress bar -->
<div class="w-full bg-muted rounded-full h-2 overflow-hidden">
- <div
- v-if="status === 'Running' || status === 'Writing'"
- class="h-full bg-primary rounded-full transition-all duration-300"
- :class="{ 'animate-pulse': !totalRows }"
- :style="{ width: totalRows ? `${progressPercent}%` : '50%' }"
- />
+ <div v-if="status === 'Running' || status === 'Writing'" class="h-full bg-primary rounded-full transition-all duration-300" :class="{ 'animate-pulse': !totalRows }" :style="{ width: totalRows ? `${progressPercent}%` : '50%' }" />
<div v-else-if="status === 'Done'" class="h-full bg-green-500 rounded-full" style="width: 100%" />
</div>
diff --git a/apps/desktop/src/components/export/ExportProgressPopover.vue b/apps/desktop/src/components/export/ExportProgressPopover.vue
index 3c0cc624cc..0e829f23ee 100644
--- a/apps/desktop/src/components/export/ExportProgressPopover.vue
+++ b/apps/desktop/src/components/export/ExportProgressPopover.vue
@@ -79,18 +79,9 @@ function toggleShowAll() {
<template>
<Popover v-if="tasks.length > 0" v-model:open="open">
<PopoverTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="relative h-8 w-8"
- :title="t('exportProgress.tooltip')"
- :class="{ 'bg-accent text-primary': hasActive }"
- >
+ <Button variant="ghost" size="icon" class="relative h-8 w-8" :title="t('exportProgress.tooltip')" :class="{ 'bg-accent text-primary': hasActive }">
<FileDown class="h-4 w-4" />
- <span
- v-if="hasActive"
- class="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium leading-none text-primary-foreground"
- >
+ <span v-if="hasActive" class="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium leading-none text-primary-foreground">
{{ activeCount > 9 ? "9+" : activeCount }}
</span>
</Button>
@@ -102,28 +93,16 @@ function toggleShowAll() {
</div>
<div class="max-h-80 overflow-y-auto">
- <div
- v-for="task in visibleTasks"
- :key="task.exportId"
- class="flex items-center gap-2 border-b px-3 py-2.5 text-xs last:border-b-0"
- >
+ <div v-for="task in visibleTasks" :key="task.exportId" class="flex items-center gap-2 border-b px-3 py-2.5 text-xs last:border-b-0">
<div class="flex-1 min-w-0 flex flex-col gap-1">
<div class="flex items-center gap-1.5">
- <component
- :is="statusIcon(task.status)"
- :class="[statusColor(task.status), isActive(task.status) ? 'animate-spin' : '']"
- class="h-3.5 w-3.5 shrink-0"
- />
+ <component :is="statusIcon(task.status)" :class="[statusColor(task.status), isActive(task.status) ? 'animate-spin' : '']" class="h-3.5 w-3.5 shrink-0" />
<span class="truncate font-medium">{{ task.tableName }}.{{ task.format }}</span>
</div>
<!-- Progress bar -->
<div v-if="isActive(task.status)" class="w-full bg-muted rounded-full h-1.5 overflow-hidden">
- <div
- class="h-full bg-primary rounded-full transition-all duration-300"
- :class="{ 'animate-pulse': !task.totalRows }"
- :style="{ width: task.totalRows ? `${progressPercent(task.totalRows, task.rowsExported)}%` : '50%' }"
- />
+ <div class="h-full bg-primary rounded-full transition-all duration-300" :class="{ 'animate-pulse': !task.totalRows }" :style="{ width: task.totalRows ? `${progressPercent(task.totalRows, task.rowsExported)}%` : '50%' }" />
</div>
<div v-else-if="task.status === 'Done'" class="w-full bg-muted rounded-full h-1.5 overflow-hidden">
<div class="h-full bg-green-500 rounded-full" style="width: 100%" />
@@ -131,11 +110,7 @@ function toggleShowAll() {
<div class="flex items-center justify-between text-muted-foreground">
<span class="tabular-nums">{{ rowsText(task) }}</span>
- <span
- v-if="task.status === 'Error' && task.errorMessage"
- class="truncate ml-2 text-destructive"
- :title="task.errorMessage"
- >
+ <span v-if="task.status === 'Error' && task.errorMessage" class="truncate ml-2 text-destructive" :title="task.errorMessage">
{{ task.errorMessage }}
</span>
</div>
@@ -143,20 +118,10 @@ function toggleShowAll() {
<!-- Actions: stop/cancel for active, delete for finished -->
<div class="flex shrink-0 self-center">
- <button
- v-if="isActive(task.status)"
- class="flex h-6 w-6 items-center justify-center rounded hover:bg-muted"
- :title="t('exportProgress.cancel')"
- @click="cancelTask(task.exportId)"
- >
+ <button v-if="isActive(task.status)" class="flex h-6 w-6 items-center justify-center rounded hover:bg-muted" :title="t('exportProgress.cancel')" @click="cancelTask(task.exportId)">
<X class="h-3.5 w-3.5 text-muted-foreground hover:text-destructive" />
</button>
- <button
- v-else
- class="flex h-6 w-6 items-center justify-center rounded hover:bg-muted"
- :title="t('exportProgress.delete')"
- @click="removeTask(task.exportId)"
- >
+ <button v-else class="flex h-6 w-6 items-center justify-center rounded hover:bg-muted" :title="t('exportProgress.delete')" @click="removeTask(task.exportId)">
<X class="h-3.5 w-3.5 text-muted-foreground hover:text-foreground" />
</button>
</div>
@@ -165,9 +130,7 @@ function toggleShowAll() {
<div v-if="hasMore" class="border-t bg-muted/30 px-3 py-1.5">
<button class="w-full text-center text-xs text-muted-foreground hover:text-foreground" @click="toggleShowAll">
- {{
- showAll ? t("exportProgress.showLess") : t("exportProgress.showMore", { count: tasks.length - MAX_VISIBLE })
- }}
+ {{ showAll ? t("exportProgress.showLess") : t("exportProgress.showMore", { count: tasks.length - MAX_VISIBLE }) }}
</button>
</div>
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index 0ca8289f8c..a2ec89efc7 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -4,17 +4,7 @@ const globalDdlOpen = ref(false);
</script>
<script setup lang="ts">
-import {
- computed,
- nextTick,
- onMounted,
- onUnmounted,
- onActivated,
- onDeactivated,
- useSlots,
- watch,
- type Component,
-} from "vue";
+import { computed, nextTick, onMounted, onUnmounted, onActivated, onDeactivated, useSlots, watch, type Component } from "vue";
import { useI18n } from "vue-i18n";
import {
ArrowUp,
@@ -60,12 +50,7 @@ import {
} from "@lucide/vue";
import { Button } from "@/components/ui/button";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import LightTooltip from "@/components/ui/LightTooltip.vue";
import LightDropdown from "@/components/ui/LightDropdown.vue";
@@ -85,19 +70,8 @@ import type { BuildSingleColumnAlterSqlOptions } from "@/lib/tableStructureEdito
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/tableSelectSql";
import { uuid } from "@/lib/utils";
import { resolveHeaderColumnType } from "@/lib/dataGridColumnType";
-import {
- canEditExistingTableRows,
- hiveTablePropertiesIndicateTransactional,
- isHiddenGridColumn,
- isTdengineExistingRowReadonlyColumn,
- usesSyntheticRowIdKey,
-} from "@/lib/tableEditing";
-import {
- buildDataGridContextFilterCondition,
- buildDataGridCountSql,
- buildHiveTablePropertiesSql,
- type DataGridContextFilterMode,
-} from "@/lib/dataGridSql";
+import { canEditExistingTableRows, hiveTablePropertiesIndicateTransactional, isHiddenGridColumn, isTdengineExistingRowReadonlyColumn, usesSyntheticRowIdKey } from "@/lib/tableEditing";
+import { buildDataGridContextFilterCondition, buildDataGridCountSql, buildHiveTablePropertiesSql, type DataGridContextFilterMode } from "@/lib/dataGridSql";
import {
buildVisibleTransposeRows,
nextAppendedTransposeState,
@@ -114,82 +88,21 @@ import { matchesRowStatusFilter, type RowStatus, type RowStatusFilter } from "@/
import { displayCellValue, type CellValue } from "@/lib/cellValue";
import { getApplicablePreviewActions } from "@/lib/resultPreviewRegistry";
import "@/lib/previewHandlers/geometryMapPreview";
-import {
- BINARY_CELL_DOWNLOAD_MODES,
- binaryCellDisplayText,
- binaryCellDownloadFileName,
- binaryCellDownloadPayload,
- canDownloadBinaryCellValue,
- downloadBinaryCellPayload,
- type BinaryCellDownloadMode,
-} from "@/lib/binaryCellDownload";
-import {
- canFormatCellDetailJson,
- cellDetailEditorText,
- defaultCellDetailTab,
- formatJsonText,
- isGeometryColumnType,
- linkedCellDetailTarget,
- valueEditorActions,
- visibleCellDetailTabs,
- type CellDetailTab,
-} from "@/lib/cellDetailPresentation";
+import { BINARY_CELL_DOWNLOAD_MODES, binaryCellDisplayText, binaryCellDownloadFileName, binaryCellDownloadPayload, canDownloadBinaryCellValue, downloadBinaryCellPayload, type BinaryCellDownloadMode } from "@/lib/binaryCellDownload";
+import { canFormatCellDetailJson, cellDetailEditorText, defaultCellDetailTab, formatJsonText, isGeometryColumnType, linkedCellDetailTarget, valueEditorActions, visibleCellDetailTabs, type CellDetailTab } from "@/lib/cellDetailPresentation";
import { renderWktOnCanvas, isHexGeometry } from "@/lib/geometryPreview";
-import {
- buildDataGridCellDetail,
- buildDataGridColumnDetail,
- buildDataGridRowDetail,
- dataGridColumnDetailJson,
- dataGridColumnDetailTsv,
- dataGridRowDetailJson,
- dataGridRowDetailTsv,
- filterDataGridDetailFields,
- type DataGridCellDetail,
-} from "@/lib/dataGridDetail";
-import {
- applyColumnFormatter,
- buildColumnFormatterKey,
- normalizeColumnFormatter,
- resolveColumnFormatter,
- type ColumnFormatterConfig,
- type DateTimeFormatterUnit,
-} from "@/lib/columnFormatter";
+import { buildDataGridCellDetail, buildDataGridColumnDetail, buildDataGridRowDetail, dataGridColumnDetailJson, dataGridColumnDetailTsv, dataGridRowDetailJson, dataGridRowDetailTsv, filterDataGridDetailFields, type DataGridCellDetail } from "@/lib/dataGridDetail";
+import { applyColumnFormatter, buildColumnFormatterKey, normalizeColumnFormatter, resolveColumnFormatter, type ColumnFormatterConfig, type DateTimeFormatterUnit } from "@/lib/columnFormatter";
import { temporalCellEditorKind, type TemporalCellEditorKind } from "@/lib/dataGridTemporalEditor";
-import {
- isCancelSearchShortcut,
- isCopyCurrentRowShortcut,
- isDeleteCurrentRowShortcut,
- isFocusSearchShortcut,
- isModRShortcut,
- isToggleTransposeShortcut,
-} from "@/lib/keyboardShortcuts";
+import { isCancelSearchShortcut, isCopyCurrentRowShortcut, isDeleteCurrentRowShortcut, isFocusSearchShortcut, isModRShortcut, isToggleTransposeShortcut } from "@/lib/keyboardShortcuts";
import { dataGridHeaderContentWidth, scrollbarGutterWidth } from "@/lib/dataGridScrollGutter";
import { canGoNextDataGridPage } from "@/lib/dataGridPagination";
import { CANVAS_DATA_GRID_ROW_HEIGHT, drawCanvasDataGrid } from "@/lib/canvasDataGridRenderer";
import { dataGridSaveActionMode, dataGridSaveToolbarState } from "@/lib/dataGridSaveUi";
-import {
- appendColumnValueFilterCondition,
- buildColumnValueFilterCondition,
- combineWhereInputs,
- filterModeNeedsValue,
- parseFilterValue,
-} from "@/lib/dataGridColumnFilter";
+import { appendColumnValueFilterCondition, buildColumnValueFilterCondition, combineWhereInputs, filterModeNeedsValue, parseFilterValue } from "@/lib/dataGridColumnFilter";
import { clampSearchSplitWidth } from "@/lib/dataGridSearchSplit";
-import {
- MAX_RESULT_PAGE_SIZE,
- MIN_RESULT_PAGE_SIZE,
- normalizeResultPageSize,
- resultPageSizeMenuOptions,
-} from "@/lib/paginationPageSize";
-import {
- allNullColumnIndexes,
- filterColumnVisibilityOptions,
- hiddenColumnIndexesWithAllNullColumns,
- invertedHiddenColumnIndexes,
- nextHiddenColumnIndexes,
- removeAutoHiddenColumnIndexes,
- visibleColumnIndexesForFilter,
-} from "@/lib/dataGridColumnVisibility";
+import { MAX_RESULT_PAGE_SIZE, MIN_RESULT_PAGE_SIZE, normalizeResultPageSize, resultPageSizeMenuOptions } from "@/lib/paginationPageSize";
+import { allNullColumnIndexes, filterColumnVisibilityOptions, hiddenColumnIndexesWithAllNullColumns, invertedHiddenColumnIndexes, nextHiddenColumnIndexes, removeAutoHiddenColumnIndexes, visibleColumnIndexesForFilter } from "@/lib/dataGridColumnVisibility";
import { parseClipboardTable } from "@/lib/gridSelection";
import { useToast } from "@/composables/useToast";
@@ -249,13 +162,7 @@ const props = defineProps<{
cacheKey?: string;
onExecuteSql?: (sql: string) => Promise<void>;
fullExportResult?: () => Promise<QueryResult | undefined>;
- customSave?: (changes: {
- dirtyRows: Map<number, Map<number, CellValue>>;
- newRows: CellValue[][];
- deletedRows: Set<number>;
- columns: string[];
- rows: CellValue[][];
- }) => Promise<void>;
+ customSave?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<void>;
}>();
const dataGridTraceId = uuid().slice(0, 8);
@@ -389,45 +296,11 @@ function headerColumnSortable(actualColIdx: number): boolean {
function typeColorClass(t: string): string {
// Strip precision/scale suffix like (20,6)
const base = t.replace(/\(.*\)$/, "").toLowerCase();
- if (
- [
- "int",
- "int2",
- "int4",
- "int8",
- "smallint",
- "bigint",
- "integer",
- "serial",
- "bigserial",
- "tinyint",
- "mediumint",
- ].includes(base)
- )
- return "text-blue-500";
- if (["float4", "float8", "double", "decimal", "numeric", "real", "float", "money"].includes(base))
- return "text-cyan-500";
- if (
- [
- "varchar",
- "text",
- "char",
- "character varying",
- "character",
- "string",
- "nvarchar",
- "nchar",
- "ntext",
- "longtext",
- "mediumtext",
- "tinytext",
- "clob",
- ].includes(base)
- )
- return "text-green-500";
+ if (["int", "int2", "int4", "int8", "smallint", "bigint", "integer", "serial", "bigserial", "tinyint", "mediumint"].includes(base)) return "text-blue-500";
+ if (["float4", "float8", "double", "decimal", "numeric", "real", "float", "money"].includes(base)) return "text-cyan-500";
+ if (["varchar", "text", "char", "character varying", "character", "string", "nvarchar", "nchar", "ntext", "longtext", "mediumtext", "tinytext", "clob"].includes(base)) return "text-green-500";
if (["bool", "boolean", "bit"].includes(base)) return "text-orange-500";
- if (["timestamp", "timestamptz", "datetime", "date", "time", "timetz", "datetime2", "smalldatetime"].includes(base))
- return "text-purple-500";
+ if (["timestamp", "timestamptz", "datetime", "date", "time", "timetz", "datetime2", "smalldatetime"].includes(base)) return "text-purple-500";
if (["json", "jsonb", "xml", "array"].includes(base)) return "text-pink-500";
if (["uuid", "uniqueidentifier"].includes(base)) return "text-amber-500";
if (["bytea", "blob", "binary", "varbinary", "image"].includes(base)) return "text-red-400";
@@ -563,12 +436,7 @@ const filterModeOptions: Array<{ value: FilterMode; labelKey: string }> = [
];
const filterBuilderColumns = computed(() => props.tableMeta?.columns ?? []);
const filterBuilderColumnOptions = computed(() => filterBuilderColumns.value.map((column) => column.name));
-const structuredFilterCount = computed(
- () =>
- structuredFilterRules.value.filter(
- (rule) => !!rule.columnName && (!filterModeNeedsValue(rule.mode) || rule.rawValue.trim().length > 0),
- ).length,
-);
+const structuredFilterCount = computed(() => structuredFilterRules.value.filter((rule) => !!rule.columnName && (!filterModeNeedsValue(rule.mode) || rule.rawValue.trim().length > 0)).length);
const hasStructuredFilters = computed(() => !!combineWhereInputs(undefined, appliedStructuredWhereInput.value));
const formatterOpenColumn = ref<number | null>(null);
type FormatterDraftKind = Exclude<ColumnFormatterConfig["kind"], "custom-ref">;
@@ -583,9 +451,7 @@ const formatterCustomName = ref("");
const formatterCustomTemplate = ref("${value}");
const savedCustomFormatters = computed(() => {
- return Object.values(settingsStore.editorSettings.customColumnFormatters).sort((a, b) =>
- a.name.localeCompare(b.name),
- );
+ return Object.values(settingsStore.editorSettings.customColumnFormatters).sort((a, b) => a.name.localeCompare(b.name));
});
function localFilterKey(value: CellValue): string {
@@ -626,9 +492,7 @@ const localFilterSummaries = computed(() =>
function rowMatchesLocalColumnFilters(data: CellValue[]): boolean {
const activeEntries = Object.entries(localColumnFilters.value).filter(([, selected]) => selected.size > 0);
if (activeEntries.length === 0) return true;
- return activeEntries.every(([columnIndex, selected]) =>
- selected.has(localFilterKey(data[Number(columnIndex)] ?? null)),
- );
+ return activeEntries.every(([columnIndex, selected]) => selected.has(localFilterKey(data[Number(columnIndex)] ?? null)));
}
const localFilteredRows = computed(() => {
@@ -680,9 +544,7 @@ const localFilterAllOptions = computed(() => {
const localFilterOptions = computed(() => {
const query = localFilterSearch.value.trim().toLowerCase();
- return localFilterAllOptions.value
- .filter((option) => !query || option.label.toLowerCase().includes(query))
- .slice(0, 500);
+ return localFilterAllOptions.value.filter((option) => !query || option.label.toLowerCase().includes(query)).slice(0, 500);
});
const localFilterAllVisibleSelected = computed(() => {
@@ -723,9 +585,7 @@ function guardHeaderPanelDismiss() {
}
function shouldIgnoreHeaderPanelClose(columnIndex: number, openColumn: number | null): boolean {
- return (
- compactColumnHeaderActions.value && openColumn === columnIndex && Date.now() < headerPanelDismissGuardUntil.value
- );
+ return compactColumnHeaderActions.value && openColumn === columnIndex && Date.now() < headerPanelDismissGuardUntil.value;
}
function openCompactLocalFilter(colIdx: number) {
@@ -768,12 +628,7 @@ function columnFormatter(columnIndex: number): ColumnFormatterConfig | undefined
const column = props.result.columns[columnIndex];
if (!column) return undefined;
const key = formatterKeyForColumn(column);
- return key
- ? resolveColumnFormatter(
- settingsStore.editorSettings.columnFormatters[key],
- settingsStore.editorSettings.customColumnFormatters,
- )
- : undefined;
+ return key ? resolveColumnFormatter(settingsStore.editorSettings.columnFormatters[key], settingsStore.editorSettings.customColumnFormatters) : undefined;
}
function savedColumnFormatter(columnIndex: number): ColumnFormatterConfig | undefined {
@@ -902,10 +757,7 @@ function createCustomFormatterId(): string {
}
function formatterPreviewRows(columnIndex: number) {
- const formatter = resolveColumnFormatter(
- currentFormatterDraft(),
- settingsStore.editorSettings.customColumnFormatters,
- );
+ const formatter = resolveColumnFormatter(currentFormatterDraft(), settingsStore.editorSettings.customColumnFormatters);
return displayRowRefs.value.slice(0, 5).map((_, index) => {
const item = displayItemAt(index);
const value = item?.data[columnIndex] ?? null;
@@ -942,11 +794,7 @@ function toggleAllLocalFilterOptions() {
async function applyLocalFilter() {
const draft = localFilterDraft.value;
if (!draft) return;
- if (
- canApplyTypedLocalFilterValue.value &&
- localFilterDraftIsAllSelected.value &&
- localFilterOptions.value.length === 0
- ) {
+ if (canApplyTypedLocalFilterValue.value && localFilterDraftIsAllSelected.value && localFilterOptions.value.length === 0) {
await applyTypedLocalFilterValue();
return;
}
@@ -1126,9 +974,7 @@ watch(
structuredFilterRules.value = [defaultStructuredFilterRule()];
return;
}
- structuredFilterRules.value = structuredFilterRules.value.map((rule) =>
- columns.includes(rule.columnName) ? rule : { ...rule, columnName: columns[0] ?? "" },
- );
+ structuredFilterRules.value = structuredFilterRules.value.map((rule) => (columns.includes(rule.columnName) ? rule : { ...rule, columnName: columns[0] ?? "" }));
},
{ immediate: true },
);
@@ -1316,10 +1162,7 @@ function dismissWhereSuggestions() {
function navigateWhereSuggestion(delta: number) {
if (whereSuggestions.value.length === 0) return;
- whereSuggestionIndex.value = Math.min(
- Math.max(whereSuggestionIndex.value + delta, 0),
- whereSuggestions.value.length - 1,
- );
+ whereSuggestionIndex.value = Math.min(Math.max(whereSuggestionIndex.value + delta, 0), whereSuggestions.value.length - 1);
}
watch(whereFilterInput, (val) => {
@@ -1349,8 +1192,7 @@ function onWhereFilterKeydown(e: KeyboardEvent) {
if (start !== end) {
e.preventDefault();
const selected = whereFilterInput.value.slice(start, end);
- whereFilterInput.value =
- whereFilterInput.value.slice(0, start) + e.key + selected + close + whereFilterInput.value.slice(end);
+ whereFilterInput.value = whereFilterInput.value.slice(0, start) + e.key + selected + close + whereFilterInput.value.slice(end);
nextTick(() => {
input.setSelectionRange(start + 1 + selected.length, start + 1 + selected.length);
});
@@ -1441,10 +1283,7 @@ function dismissOrderBySuggestions() {
function navigateOrderBySuggestion(delta: number) {
if (orderBySuggestions.value.length === 0) return;
- orderBySuggestionIndex.value = Math.min(
- Math.max(orderBySuggestionIndex.value + delta, 0),
- orderBySuggestions.value.length - 1,
- );
+ orderBySuggestionIndex.value = Math.min(Math.max(orderBySuggestionIndex.value + delta, 0), orderBySuggestions.value.length - 1);
}
watch(orderByInput, (val) => {
@@ -1514,9 +1353,7 @@ const displayableColumnIndexes = computed(() =>
.filter(({ column }) => !isHiddenGridColumn(props.databaseType, column, props.tableMeta?.primaryKeys ?? []))
.map(({ index }) => index),
);
-const visibleColumnIndexes = computed(() =>
- visibleColumnIndexesForFilter(displayableColumnIndexes.value, hiddenColumnIndexes.value),
-);
+const visibleColumnIndexes = computed(() => visibleColumnIndexesForFilter(displayableColumnIndexes.value, hiddenColumnIndexes.value));
const visibleColumns = computed(() => visibleColumnIndexes.value.map((index) => props.result.columns[index]));
const visibleSourceColumns = computed(() => {
if (!props.sourceColumns || props.sourceColumns.length !== props.result.columns.length) return undefined;
@@ -1533,10 +1370,7 @@ const visibleColumnTypes = computed(() =>
visibleColumnIndexes.value.map((index) => {
const resultColumn = props.result.columns[index]?.toLocaleLowerCase();
const sourceColumn = props.sourceColumns?.[index]?.toLocaleLowerCase();
- return (
- (sourceColumn ? tableColumnTypesByName.value.get(sourceColumn) : undefined) ||
- (resultColumn ? tableColumnTypesByName.value.get(resultColumn) : undefined)
- );
+ return (sourceColumn ? tableColumnTypesByName.value.get(sourceColumn) : undefined) || (resultColumn ? tableColumnTypesByName.value.get(resultColumn) : undefined);
}),
);
const visibleColumnCount = computed(() => visibleColumnIndexes.value.length);
@@ -1548,13 +1382,9 @@ const previewActions = computed(() => {
});
const displayableColumnCount = computed(() => displayableColumnIndexes.value.length);
const hiddenColumnCount = computed(() => displayableColumnCount.value - visibleColumnCount.value);
-const allNullColumnIndexesForResult = computed(() =>
- allNullColumnIndexes(props.result.rows, displayableColumnIndexes.value),
-);
+const allNullColumnIndexesForResult = computed(() => allNullColumnIndexes(props.result.rows, displayableColumnIndexes.value));
const allNullColumnCount = computed(() => allNullColumnIndexesForResult.value.length);
-const canToggleAllNullColumns = computed(
- () => nullColumnsHidden.value || (allNullColumnCount.value > 0 && displayableColumnCount.value > 1),
-);
+const canToggleAllNullColumns = computed(() => nullColumnsHidden.value || (allNullColumnCount.value > 0 && displayableColumnCount.value > 1));
function filteredColumnVisibilityOptions(query: string) {
const displayable = new Set(displayableColumnIndexes.value);
return filterColumnVisibilityOptions(props.result.columns, query).filter((option) => displayable.has(option.index));
@@ -1576,10 +1406,7 @@ function invertColumnVisibility() {
hiddenColumnIndexes.value = invertedHiddenColumnIndexes(displayableColumnIndexes.value, hiddenColumnIndexes.value);
}
function showAllNullColumns() {
- hiddenColumnIndexes.value = removeAutoHiddenColumnIndexes(
- hiddenColumnIndexes.value,
- autoHiddenNullColumnIndexes.value,
- );
+ hiddenColumnIndexes.value = removeAutoHiddenColumnIndexes(hiddenColumnIndexes.value, autoHiddenNullColumnIndexes.value);
autoHiddenNullColumnIndexes.value = new Set();
nullColumnsHidden.value = false;
}
@@ -1602,10 +1429,7 @@ function toggleAllNullColumns() {
}
watch(allNullColumnIndexesForResult, () => {
if (!nullColumnsHidden.value) return;
- hiddenColumnIndexes.value = removeAutoHiddenColumnIndexes(
- hiddenColumnIndexes.value,
- autoHiddenNullColumnIndexes.value,
- );
+ hiddenColumnIndexes.value = removeAutoHiddenColumnIndexes(hiddenColumnIndexes.value, autoHiddenNullColumnIndexes.value);
autoHiddenNullColumnIndexes.value = new Set();
hideAllNullColumns();
});
@@ -1618,9 +1442,7 @@ function matchesTableInfoColumn(resultColumn: string, sourceColumn: string | und
return resultColumn.toLocaleLowerCase() === target || sourceColumn?.toLocaleLowerCase() === target;
}
function scrollToTableInfoColumn(columnName: string) {
- const columnIndex = props.result.columns.findIndex((column, index) =>
- matchesTableInfoColumn(column, props.sourceColumns?.[index], columnName),
- );
+ const columnIndex = props.result.columns.findIndex((column, index) => matchesTableInfoColumn(column, props.sourceColumns?.[index], columnName));
if (columnIndex < 0 || !displayableColumnIndexes.value.includes(columnIndex)) return;
if (hiddenColumnIndexes.value.has(columnIndex)) {
@@ -1639,12 +1461,7 @@ function scrollToTableInfoColumn(columnName: string) {
const scroller = gridRef.value?.querySelector<HTMLElement>(".data-grid-scroller");
if (visibleColIdx < 0 || !scroller) return;
- const targetLeft = Math.max(
- 0,
- columnContentOffsetLeft(visibleColIdx) -
- scroller.clientWidth / 2 +
- (renderedColumnWidths.value[visibleColIdx] ?? 0) / 2,
- );
+ const targetLeft = Math.max(0, columnContentOffsetLeft(visibleColIdx) - scroller.clientWidth / 2 + (renderedColumnWidths.value[visibleColIdx] ?? 0) / 2);
scroller.scrollLeft = targetLeft;
updateGridHorizontalViewport(scroller);
if (headerRef.value) {
@@ -1654,14 +1471,13 @@ function scrollToTableInfoColumn(columnName: string) {
}
// --- Column resize composable ---
-const { initColumnWidths, onResizeStart, autoFitColumn, renderedColumnWidths, totalWidth, columnVars, getIsResizing } =
- useDataGridColumnResize({
- columns: visibleColumns,
- sourceRows: computed(() => props.result.rows),
- columnIndexes: visibleColumnIndexes,
- gridRef,
- scrollbarGutter: gridScrollbarGutter,
- });
+const { initColumnWidths, onResizeStart, autoFitColumn, renderedColumnWidths, totalWidth, columnVars, getIsResizing } = useDataGridColumnResize({
+ columns: visibleColumns,
+ sourceRows: computed(() => props.result.rows),
+ columnIndexes: visibleColumnIndexes,
+ gridRef,
+ scrollbarGutter: gridScrollbarGutter,
+});
const gridStyle = computed(() => ({
...columnVars.value,
"--header-total-w": dataGridHeaderContentWidth("var(--total-w)", gridScrollbarGutter.value),
@@ -1730,14 +1546,8 @@ function getHorizontalColumnWindow(): HorizontalColumnWindow {
return { start: 0, end: 0, beforeWidth: 0, afterWidth: 0 };
}
- const viewportStart = Math.max(
- 0,
- gridHorizontalScrollLeft.value - DATA_GRID_ROW_NUM_WIDTH - HORIZONTAL_COLUMN_BUFFER_PX,
- );
- const viewportEnd =
- Math.max(gridViewportWidth.value, 1) +
- Math.max(0, gridHorizontalScrollLeft.value - DATA_GRID_ROW_NUM_WIDTH) +
- HORIZONTAL_COLUMN_BUFFER_PX;
+ const viewportStart = Math.max(0, gridHorizontalScrollLeft.value - DATA_GRID_ROW_NUM_WIDTH - HORIZONTAL_COLUMN_BUFFER_PX);
+ const viewportEnd = Math.max(gridViewportWidth.value, 1) + Math.max(0, gridHorizontalScrollLeft.value - DATA_GRID_ROW_NUM_WIDTH) + HORIZONTAL_COLUMN_BUFFER_PX;
let low = 0;
let high = totalColumns - 1;
while (low < high) {
@@ -1871,9 +1681,7 @@ watch(
);
const manualTotalRowCount = ref<number | undefined>(undefined);
const manualTotalRowCountLoading = ref(false);
-const showTruncationWarning = computed(
- () => props.result.truncated === true && typeof props.pageLimit !== "number" && props.result.has_more !== true,
-);
+const showTruncationWarning = computed(() => props.result.truncated === true && typeof props.pageLimit !== "number" && props.result.has_more !== true);
const isResultsContext = computed(() => props.context === "results");
// affected_rows reported by the backend can be larger than the rows we
// actually have in memory — e.g. ES auto-pages SELECT * on a big index and
@@ -1891,9 +1699,7 @@ const serverKnownTotalRowCount = computed(() => props.totalRowCount ?? manualTot
const displayedTotalRowCount = computed(() => serverKnownTotalRowCount.value ?? inferredBackendTotalRowCount.value);
// Only a server-confirmed total drives pagination — an inferred total means
// rows exist that we never fetched, so navigation must stay inside rows.length.
-const hasKnownTotalRowCount = computed(
- () => typeof serverKnownTotalRowCount.value === "number" && serverKnownTotalRowCount.value >= 0,
-);
+const hasKnownTotalRowCount = computed(() => typeof serverKnownTotalRowCount.value === "number" && serverKnownTotalRowCount.value >= 0);
// When context=results and the caller hasn't configured server-side
// pagination (no pageLimit), the backend handed us every row up-front and
// rowCount IS the total. Without this hint, the "page is full → assume more"
@@ -1910,27 +1716,15 @@ const canGoNextPage = computed(() => {
allRowsLoaded: allRowsLoaded.value,
});
});
-const canJumpLastPage = computed(
- () =>
- canGoNextPage.value &&
- (hasKnownTotalRowCount.value || allRowsLoaded.value || !!props.tableMeta || !!props.countSql),
-);
+const canJumpLastPage = computed(() => canGoNextPage.value && (hasKnownTotalRowCount.value || allRowsLoaded.value || !!props.tableMeta || !!props.countSql));
const totalRowCountBusy = computed(() => props.totalRowCountLoading === true || manualTotalRowCountLoading.value);
-const canCalculateTotalRowCount = computed(
- () => !isResultsContext.value && !!props.connectionId && (!!props.tableMeta || !!props.countSql),
-);
-const showQueryEditReadyBadge = computed(
- () => isResultsContext.value && hasData.value && !!props.editable && !!props.tableMeta,
-);
+const canCalculateTotalRowCount = computed(() => !isResultsContext.value && !!props.connectionId && (!!props.tableMeta || !!props.countSql));
+const showQueryEditReadyBadge = computed(() => isResultsContext.value && hasData.value && !!props.editable && !!props.tableMeta);
const canShowWhereSearch = computed(() => !!props.onExecuteSql && !isResultsContext.value);
const canUseWhereSearch = computed(() => !!props.tableMeta && !!props.onExecuteSql && !isResultsContext.value);
type DataGridTableMeta = NonNullable<typeof props.tableMeta>;
const hiveTableTransactional = ref<boolean | undefined>(undefined);
-const canEditExistingRows = computed(
- () =>
- !!props.customSave ||
- canEditExistingTableRows(props.databaseType, hiveTableTransactional.value, props.tableMeta?.primaryKeys ?? []),
-);
+const canEditExistingRows = computed(() => !!props.customSave || canEditExistingTableRows(props.databaseType, hiveTableTransactional.value, props.tableMeta?.primaryKeys ?? []));
watch(
() => [props.databaseType, props.connectionId, props.database, props.tableMeta?.schema, props.tableMeta?.tableName],
async () => {
@@ -1970,22 +1764,11 @@ function currentWhereInput(): string | undefined {
}
function currentOrderBy(): string | undefined {
- return (
- orderByInput.value.trim() ||
- (sortCol.value ? `${queryColumnRef(sortCol.value)} ${sortDir.value.toUpperCase()}` : undefined)
- );
+ return orderByInput.value.trim() || (sortCol.value ? `${queryColumnRef(sortCol.value)} ${sortDir.value.toUpperCase()}` : undefined);
}
watch(
- () => [
- props.countSql ?? "",
- props.tableMeta?.schema ?? "",
- props.tableMeta?.tableName ?? "",
- currentWhereInput() ?? "",
- props.database ?? "",
- props.connectionId ?? "",
- props.result,
- ],
+ () => [props.countSql ?? "", props.tableMeta?.schema ?? "", props.tableMeta?.tableName ?? "", currentWhereInput() ?? "", props.database ?? "", props.connectionId ?? "", props.result],
() => {
manualTotalRowCount.value = undefined;
},
@@ -2103,12 +1886,7 @@ async function calculateTotalRowCount() {
try {
const countTarget = await buildCurrentCountTarget();
if (!countTarget?.sql) return;
- const result = await api.executeQuery(
- props.connectionId,
- props.database ?? "",
- countTarget.sql,
- countTarget.schema,
- );
+ const result = await api.executeQuery(props.connectionId, props.database ?? "", countTarget.sql, countTarget.schema);
const total = Number(result.rows?.[0]?.[0] ?? 0);
if (Number.isFinite(total) && total >= 0) {
manualTotalRowCount.value = total;
@@ -2288,15 +2066,7 @@ async function onToolbarRefresh() {
discardChanges();
}
preserveTransposeOnNextResult.value = showTranspose.value;
- emit(
- "reload",
- props.sql,
- searchText.value,
- currentWhereInput(),
- currentOrderBy(),
- pageSize.value,
- (currentPage.value - 1) * pageSize.value,
- );
+ emit("reload", props.sql, searchText.value, currentWhereInput(), currentOrderBy(), pageSize.value, (currentPage.value - 1) * pageSize.value);
}
async function onToolbarCommit() {
@@ -2306,15 +2076,7 @@ async function onToolbarCommit() {
function onToolbarRollback() {
preserveTransposeOnNextResult.value = showTranspose.value;
discardChanges();
- emit(
- "reload",
- props.sql,
- searchText.value,
- currentWhereInput(),
- currentOrderBy(),
- pageSize.value,
- (currentPage.value - 1) * pageSize.value,
- );
+ emit("reload", props.sql, searchText.value, currentWhereInput(), currentOrderBy(), pageSize.value, (currentPage.value - 1) * pageSize.value);
}
function addRow() {
@@ -2329,9 +2091,7 @@ const sortedRows = computed(() => {
const rows = props.result.rows;
indices = indices.filter((sourceIndex) => {
const data = rows[sourceIndex];
- return data.some(
- (cell, columnIndex) => cell !== null && formatCellCached(cell, columnIndex).toLowerCase().includes(q),
- );
+ return data.some((cell, columnIndex) => cell !== null && formatCellCached(cell, columnIndex).toLowerCase().includes(q));
});
}
return indices;
@@ -2508,10 +2268,7 @@ function scrollToCurrentMatch() {
if (useCanvasGridRows.value) {
const scroller = canvasScrollerElement();
if (!scroller) return;
- const targetTop = Math.max(
- 0,
- match.displayRow * CANVAS_DATA_GRID_ROW_HEIGHT - (scroller.clientHeight - CANVAS_DATA_GRID_ROW_HEIGHT) / 2,
- );
+ const targetTop = Math.max(0, match.displayRow * CANVAS_DATA_GRID_ROW_HEIGHT - (scroller.clientHeight - CANVAS_DATA_GRID_ROW_HEIGHT) / 2);
scroller.scrollTop = targetTop;
syncCanvasViewport();
return;
@@ -2546,20 +2303,12 @@ const exportContextCell = computed(() => {
return { ...contextCell.value, col: visibleCol };
});
-const deleteRowDetails = computed(() =>
- props.tableMeta?.tableName
- ? t("dangerDialog.deleteRowDetails", { table: props.tableMeta.tableName })
- : t("dangerDialog.deleteRowDetailsNoTable"),
-);
+const deleteRowDetails = computed(() => (props.tableMeta?.tableName ? t("dangerDialog.deleteRowDetails", { table: props.tableMeta.tableName }) : t("dangerDialog.deleteRowDetailsNoTable")));
const hasVisibleRows = computed(() => displayRowCount.value > 0);
-const hasActiveFilter = computed(
- () => !!deferredClientSearchText.value || rowStatusFilter.value !== "all" || hasLocalColumnFilters.value,
-);
+const hasActiveFilter = computed(() => !!deferredClientSearchText.value || rowStatusFilter.value !== "all" || hasLocalColumnFilters.value);
const emptyTitle = computed(() => (hasActiveFilter.value ? t("grid.noFilteredRows") : t("grid.noRows")));
-const emptyDescription = computed(() =>
- hasActiveFilter.value ? t("grid.noFilteredRowsDescription") : t("grid.noRowsDescription"),
-);
+const emptyDescription = computed(() => (hasActiveFilter.value ? t("grid.noFilteredRowsDescription") : t("grid.noRowsDescription")));
watch(
() => [hasVisibleRows.value, props.result.columns.length] as const,
() => {
@@ -2567,9 +2316,7 @@ watch(
},
{ immediate: true },
);
-const isErrorResult = computed(
- () => props.result.columns.length === 1 && props.result.columns[0] === "Error" && props.result.rows.length > 0,
-);
+const isErrorResult = computed(() => props.result.columns.length === 1 && props.result.columns[0] === "Error" && props.result.rows.length > 0);
const errorMessage = computed(() => (isErrorResult.value ? String(props.result.rows[0]?.[0] ?? "") : ""));
// --- Selection composable ---
const selection = useDataGridSelection({
@@ -2651,11 +2398,7 @@ function handleQuickDownloadMenuOpenChange(open: boolean, rowIndex: number, actu
function cellDetailButtonVisible(rowIndex: number, actualColIdx: number) {
if (isScrolling.value) return false;
- return (
- (hoveredDetailCell.value?.rowIndex === rowIndex && hoveredDetailCell.value.col === actualColIdx) ||
- quickDownloadMenuOpenFor(rowIndex, actualColIdx) ||
- (showCellDetail.value && detailCell.value?.rowIndex === rowIndex && detailCell.value.col === actualColIdx)
- );
+ return (hoveredDetailCell.value?.rowIndex === rowIndex && hoveredDetailCell.value.col === actualColIdx) || quickDownloadMenuOpenFor(rowIndex, actualColIdx) || (showCellDetail.value && detailCell.value?.rowIndex === rowIndex && detailCell.value.col === actualColIdx);
}
function affectedRowIds(): number[] {
@@ -2787,13 +2530,9 @@ const columnDetail = computed(() => {
});
});
-const filteredRowDetailFields = computed(() =>
- rowDetail.value ? filterDataGridDetailFields(rowDetail.value.fields, rowDetailSearch.value) : [],
-);
+const filteredRowDetailFields = computed(() => (rowDetail.value ? filterDataGridDetailFields(rowDetail.value.fields, rowDetailSearch.value) : []));
-const filteredColumnDetailFields = computed(() =>
- columnDetail.value ? filterDataGridDetailFields(columnDetail.value.fields, columnDetailSearch.value) : [],
-);
+const filteredColumnDetailFields = computed(() => (columnDetail.value ? filterDataGridDetailFields(columnDetail.value.fields, columnDetailSearch.value) : []));
watch(cellDetailDialogOpen, (open) => {
if (open) cellDetailJsonView.value = false;
@@ -3045,11 +2784,7 @@ function commitDetailEdit() {
if (item.isNew && item.newIndex !== undefined) {
const oldVal = newRows.value[item.newIndex]?.[detail.colIndex];
- newRows.value[item.newIndex][detail.colIndex] = coerceDetailCellValue(
- detailEditValue.value,
- oldVal,
- detail.colIndex,
- );
+ newRows.value[item.newIndex][detail.colIndex] = coerceDetailCellValue(detailEditValue.value, oldVal, detail.colIndex);
return;
}
@@ -3177,11 +2912,7 @@ function toggleSort(colName: string, colIdx: number) {
if (getIsResizing()) return;
currentPage.value = 1;
resetGridVerticalScroll(true);
- const next = nextDataGridSortState(
- { column: sortCol.value, columnIndex: sortColIndex.value, direction: sortDir.value },
- colName,
- colIdx,
- );
+ const next = nextDataGridSortState({ column: sortCol.value, columnIndex: sortColIndex.value, direction: sortDir.value }, colName, colIdx);
sortCol.value = next.column;
sortColIndex.value = next.columnIndex;
sortDir.value = next.direction;
@@ -3301,9 +3032,7 @@ async function applyWhereFilter() {
tableName: tableMeta.tableName,
columns: tableMeta.columns.map((column) => column.name),
primaryKeys: tableMeta.primaryKeys,
- orderBy:
- orderByInput.value.trim() ||
- (sortCol.value ? `${queryColumnRef(sortCol.value)} ${sortDir.value.toUpperCase()}` : undefined),
+ orderBy: orderByInput.value.trim() || (sortCol.value ? `${queryColumnRef(sortCol.value)} ${sortDir.value.toUpperCase()}` : undefined),
limit: pageSize.value,
whereInput: currentWhereInput(),
includeRowId: usesSyntheticRowIdKey(props.databaseType, tableMeta.primaryKeys),
@@ -3320,9 +3049,7 @@ const CELL_DISPLAY_MAX_LENGTH = 256;
const CELL_FORMAT_CACHE_LIMIT = 20_000;
const CELL_FORMAT_CACHE_PRUNE_COUNT = 5_000;
-const resolvedColumnFormatters = computed(() =>
- props.result.columns.map((_, columnIndex) => columnFormatter(columnIndex)),
-);
+const resolvedColumnFormatters = computed(() => props.result.columns.map((_, columnIndex) => columnFormatter(columnIndex)));
const columnFormatterSignatures = computed(() => resolvedColumnFormatters.value.map(formatterSignature));
const primitiveCellFormatCache = new Map<string, string>();
let objectCellFormatCache = new WeakMap<object, Map<number, string>>();
@@ -3357,16 +3084,9 @@ function formatCell(value: CellValue, columnIndex?: number): string {
const formatter = columnIndex === undefined ? undefined : resolvedColumnFormatters.value[columnIndex];
const columnName = columnIndex === undefined ? undefined : props.result.columns[columnIndex];
const columnInfo = columnIndex === undefined ? undefined : tableColumnForGridColumn(columnIndex);
- const arrayDisplay = formatter
- ? undefined
- : dataGridCellDisplayText({ value, databaseType: props.databaseType, columnInfo });
+ const arrayDisplay = formatter ? undefined : dataGridCellDisplayText({ value, databaseType: props.databaseType, columnInfo });
if (arrayDisplay !== undefined) return arrayDisplay;
- const binaryDisplay = formatter
- ? null
- : binaryCellDisplayText(
- value,
- columnInfo?.data_type ?? (columnName ? columnTypeMap.value.get(columnName) : undefined),
- );
+ const binaryDisplay = formatter ? null : binaryCellDisplayText(value, columnInfo?.data_type ?? (columnName ? columnTypeMap.value.get(columnName) : undefined));
if (binaryDisplay) return binaryDisplay;
const s = applyColumnFormatter(value, formatter);
return s.length > CELL_DISPLAY_MAX_LENGTH ? s.slice(0, CELL_DISPLAY_MAX_LENGTH) : s;
@@ -3395,10 +3115,7 @@ function formatCellCached(value: CellValue, columnIndex?: number): string {
return rememberPrimitiveCellFormat(key, formatCell(value, columnIndex));
}
-watch(
- () => [props.result.columns.join("\u0000"), columnFormatterSignatures.value.join("\u0000")],
- clearCellFormatCache,
-);
+watch(() => [props.result.columns.join("\u0000"), columnFormatterSignatures.value.join("\u0000")], clearCellFormatCache);
function quoteIdent(name: string): string {
return quoteTableIdentifier(props.databaseType, name);
@@ -3437,15 +3154,10 @@ const canvasViewportHeight = ref(0);
const canvasScrollTop = ref(0);
const canvasHoverCell = ref<{ rowIndex: number; visibleColIdx: number } | null>(null);
const canvasDevicePixelRatio = ref(typeof window === "undefined" ? 1 : window.devicePixelRatio || 1);
-const canvasBackingPixelRatio = computed(() =>
- Math.min(4, Math.max(1, canvasDevicePixelRatio.value * settingsStore.editorSettings.uiScale)),
-);
+const canvasBackingPixelRatio = computed(() => Math.min(4, Math.max(1, canvasDevicePixelRatio.value * settingsStore.editorSettings.uiScale)));
const useCanvasGridRows = computed(() => dataGridRenderMode.value === "canvas");
const canvasContentHeight = computed(() => Math.max(1, displayRowCount.value * CANVAS_DATA_GRID_ROW_HEIGHT));
-const canvasRenderStyleKey = computed(
- () =>
- `${settingsStore.editorSettings.theme}:${settingsStore.editorSettings.uiScale}:${canvasBackingPixelRatio.value}:${isDark.value}`,
-);
+const canvasRenderStyleKey = computed(() => `${settingsStore.editorSettings.theme}:${settingsStore.editorSettings.uiScale}:${canvasBackingPixelRatio.value}:${isDark.value}`);
const CANVAS_MOUSE_WHEEL_SCROLL_MULTIPLIER = 1.5;
const CANVAS_TRACKPAD_DELTA_THRESHOLD = 40;
let canvasResizeObserver: ResizeObserver | null = null;
@@ -3609,10 +3321,7 @@ function canvasWheelDeltaToPixels(delta: number, deltaMode: number, pageSize: nu
function shouldAccelerateCanvasWheel(event: WheelEvent): boolean {
if (event.ctrlKey || event.metaKey) return false;
if (event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL) return true;
- return (
- Math.abs(event.deltaY) >= CANVAS_TRACKPAD_DELTA_THRESHOLD ||
- Math.abs(event.deltaX) >= CANVAS_TRACKPAD_DELTA_THRESHOLD
- );
+ return Math.abs(event.deltaY) >= CANVAS_TRACKPAD_DELTA_THRESHOLD || Math.abs(event.deltaX) >= CANVAS_TRACKPAD_DELTA_THRESHOLD;
}
function onCanvasWheel(event: WheelEvent) {
@@ -3622,25 +3331,9 @@ function onCanvasWheel(event: WheelEvent) {
const verticalDelta = canvasWheelDeltaToPixels(event.deltaY, event.deltaMode, scroller.clientHeight);
const horizontalDelta = canvasWheelDeltaToPixels(event.deltaX, event.deltaMode, scroller.clientWidth);
- const shiftedHorizontalDelta =
- event.shiftKey && Math.abs(verticalDelta) > Math.abs(horizontalDelta) ? verticalDelta : 0;
- const nextTop =
- shiftedHorizontalDelta === 0
- ? Math.max(
- 0,
- Math.min(
- scroller.scrollHeight - scroller.clientHeight,
- scroller.scrollTop + verticalDelta * CANVAS_MOUSE_WHEEL_SCROLL_MULTIPLIER,
- ),
- )
- : scroller.scrollTop;
- const nextLeft = Math.max(
- 0,
- Math.min(
- scroller.scrollWidth - scroller.clientWidth,
- scroller.scrollLeft + (horizontalDelta + shiftedHorizontalDelta) * CANVAS_MOUSE_WHEEL_SCROLL_MULTIPLIER,
- ),
- );
+ const shiftedHorizontalDelta = event.shiftKey && Math.abs(verticalDelta) > Math.abs(horizontalDelta) ? verticalDelta : 0;
+ const nextTop = shiftedHorizontalDelta === 0 ? Math.max(0, Math.min(scroller.scrollHeight - scroller.clientHeight, scroller.scrollTop + verticalDelta * CANVAS_MOUSE_WHEEL_SCROLL_MULTIPLIER)) : scroller.scrollTop;
+ const nextLeft = Math.max(0, Math.min(scroller.scrollWidth - scroller.clientWidth, scroller.scrollLeft + (horizontalDelta + shiftedHorizontalDelta) * CANVAS_MOUSE_WHEEL_SCROLL_MULTIPLIER));
if (nextTop === scroller.scrollTop && nextLeft === scroller.scrollLeft) return;
event.preventDefault();
@@ -3652,20 +3345,12 @@ function onCanvasWheel(event: WheelEvent) {
function onCanvasMouseMove(event: MouseEvent) {
const hit = canvasHitTest(event);
const hitItem = hit ? displayItemAt(hit.rowIndex) : undefined;
- const next =
- hit && hitItem ? { rowIndex: hitItem.displayIndex, visibleColIdx: hit.rowNumber ? -1 : hit.visibleColIdx } : null;
+ const next = hit && hitItem ? { rowIndex: hitItem.displayIndex, visibleColIdx: hit.rowNumber ? -1 : hit.visibleColIdx } : null;
const actualColIdx = next ? visibleColumnIndexes.value[next.visibleColIdx] : undefined;
if (canvasRef.value) {
- canvasRef.value.style.cursor = hit?.rowNumber
- ? "default"
- : hitItem && actualColIdx !== undefined && canEditCellItem(hitItem, actualColIdx)
- ? "text"
- : "cell";
- }
- if (
- next?.rowIndex === canvasHoverCell.value?.rowIndex &&
- next?.visibleColIdx === canvasHoverCell.value?.visibleColIdx
- ) {
+ canvasRef.value.style.cursor = hit?.rowNumber ? "default" : hitItem && actualColIdx !== undefined && canEditCellItem(hitItem, actualColIdx) ? "text" : "cell";
+ }
+ if (next?.rowIndex === canvasHoverCell.value?.rowIndex && next?.visibleColIdx === canvasHoverCell.value?.visibleColIdx) {
return;
}
const previous = canvasHoverCell.value;
@@ -3700,10 +3385,7 @@ function keepCanvasDetailHover() {
function clearCanvasDetailHover(event?: MouseEvent) {
const relatedTarget = event?.relatedTarget;
- if (
- relatedTarget instanceof Node &&
- (canvasOverlayRef.value?.contains(relatedTarget) || canvasRef.value?.contains(relatedTarget))
- ) {
+ if (relatedTarget instanceof Node && (canvasOverlayRef.value?.contains(relatedTarget) || canvasRef.value?.contains(relatedTarget))) {
return;
}
onCanvasMouseLeave();
@@ -3758,8 +3440,7 @@ function canvasCellViewportRect(rowIndex: number, visibleColIdx: number) {
const widths = renderedColumnWidths.value;
const colWidth = widths[visibleColIdx];
if (colWidth === undefined) return null;
- const left =
- DATA_GRID_ROW_NUM_WIDTH + (renderedColumnOffsets.value[visibleColIdx] ?? 0) - gridHorizontalScrollLeft.value;
+ const left = DATA_GRID_ROW_NUM_WIDTH + (renderedColumnOffsets.value[visibleColIdx] ?? 0) - gridHorizontalScrollLeft.value;
return {
left,
top: rowIndex * CANVAS_DATA_GRID_ROW_HEIGHT - canvasScrollTop.value,
@@ -3829,8 +3510,7 @@ const canvasEditingCellStyle = computed(() => {
const canvasDetailButtonCell = computed(() => {
if (!useCanvasGridRows.value || isScrolling.value) return null;
- const target =
- hoveredDetailCell.value ?? quickDownloadMenuCell.value ?? (showCellDetail.value ? detailCell.value : null);
+ const target = hoveredDetailCell.value ?? quickDownloadMenuCell.value ?? (showCellDetail.value ? detailCell.value : null);
if (!target || !cellDetailButtonVisible(target.rowIndex, target.col)) return null;
const visibleColIdx = visibleColumnIndexes.value.indexOf(target.col);
if (visibleColIdx < 0) return null;
@@ -4281,9 +3961,7 @@ function pasteStartCell() {
}
function selectedVisibleColumnIndexes(): number[] {
- return [...selectedColumnIndexes.value]
- .filter((index) => index >= 0 && index < visibleColumns.value.length)
- .sort((a, b) => a - b);
+ return [...selectedColumnIndexes.value].filter((index) => index >= 0 && index < visibleColumns.value.length).sort((a, b) => a - b);
}
function applyVisibleCellValue(item: RowItem, visibleCol: number, value: string | null): boolean {
@@ -4476,8 +4154,7 @@ function toggleKeyboardTranspose(): boolean {
function moveSelectedCell(rowDelta: number, colDelta: number): boolean {
const position = currentSelectedCellPosition();
- if (!position || editingCell.value || displayRowCount.value === 0 || visibleColumnIndexes.value.length === 0)
- return false;
+ if (!position || editingCell.value || displayRowCount.value === 0 || visibleColumnIndexes.value.length === 0) return false;
const rowIndex = Math.max(0, Math.min(displayRowCount.value - 1, position.rowIndex + rowDelta));
const colIndex = Math.max(0, Math.min(visibleColumnIndexes.value.length - 1, position.colIndex + colDelta));
selectSingleCell(rowIndex, colIndex);
@@ -4626,9 +4303,7 @@ async function onGridKeydown(event: KeyboardEvent) {
const keydownAt = Date.now();
window.setTimeout(() => {
if (lastPasteEventAt >= keydownAt) return;
- pasteClipboardIntoSelection().catch((e) =>
- toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000),
- );
+ pasteClipboardIntoSelection().catch((e) => toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000));
}, 50);
return;
}
@@ -4826,9 +4501,7 @@ watch(
(count) => ensureTransposeRecordWidths(count),
);
const transposePinnedWidthOverride = ref<number | null>(null);
-const transposePinnedWidth = computed(
- () => transposePinnedWidthOverride.value ?? transposeFieldWidth(visibleColumns.value),
-);
+const transposePinnedWidth = computed(() => transposePinnedWidthOverride.value ?? transposeFieldWidth(visibleColumns.value));
const transposeRecordWindow = computed(() =>
visibleTransposeRecordWindow({
@@ -4852,12 +4525,8 @@ const activeTransposeRecordIndexes = computed(() =>
visibleRecordIndexes: visibleTransposeRecordIndexes.value,
}),
);
-const transposeBeforeSpacerWidth = computed(() =>
- multiRowTranspose.value ? transposeRecordWindow.value.beforeWidth : 0,
-);
-const transposeAfterSpacerWidth = computed(() =>
- multiRowTranspose.value ? transposeRecordWindow.value.afterWidth : 0,
-);
+const transposeBeforeSpacerWidth = computed(() => (multiRowTranspose.value ? transposeRecordWindow.value.beforeWidth : 0));
+const transposeAfterSpacerWidth = computed(() => (multiRowTranspose.value ? transposeRecordWindow.value.afterWidth : 0));
const transposeRows = computed(() => {
return buildVisibleTransposeRows({
columns: visibleColumns.value,
@@ -4870,9 +4539,7 @@ const transposeRows = computed(() => {
});
const isTransposeMode = computed(() => showTranspose.value && transposeRows.value.length > 0);
const transposeTotalWidth = computed(() => {
- const recordIndexes = multiRowTranspose.value
- ? Array.from({ length: displayRowCount.value }, (_, i) => i)
- : activeTransposeRecordIndexes.value;
+ const recordIndexes = multiRowTranspose.value ? Array.from({ length: displayRowCount.value }, (_, i) => i) : activeTransposeRecordIndexes.value;
return transposePinnedWidth.value + recordIndexes.reduce((sum, i) => sum + getTransposeRecordWidth(i), 0);
});
@@ -5106,9 +4773,7 @@ watch(
closeCellDetails();
closeDetailDialogs();
if (shouldPreserveTranspose) {
- applyTransposeState(
- nextTransposeStateForRecordCount(showTranspose.value, transposeRowIndex.value, displayRowCount.value),
- );
+ applyTransposeState(nextTransposeStateForRecordCount(showTranspose.value, transposeRowIndex.value, displayRowCount.value));
} else {
closeTranspose(false);
}
@@ -5291,11 +4956,7 @@ const ddlDrawerStyle = computed(() => ({
width: `${ddlWidth.value}px`,
}));
-const detailPanelStyle = computed(() =>
- cellDetailPanelIsBottom.value
- ? { height: `${detailPanelHeight.value}px`, maxHeight: `min(70vh, ${CELL_DETAIL_PANEL_MAX_HEIGHT}px)` }
- : { width: `${detailPanelHeight.value}px` },
-);
+const detailPanelStyle = computed(() => (cellDetailPanelIsBottom.value ? { height: `${detailPanelHeight.value}px`, maxHeight: `min(70vh, ${CELL_DETAIL_PANEL_MAX_HEIGHT}px)` } : { width: `${detailPanelHeight.value}px` }));
const contentGridStyle = computed(() =>
cellDetailPanelIsBottom.value
@@ -5362,12 +5023,7 @@ async function fetchDdl() {
showTableInfo.value = true;
ddlLoading.value = true;
try {
- ddlContent.value = await api.getTableDdl(
- props.connectionId,
- props.database || "",
- props.tableMeta.schema || props.database || "",
- props.tableMeta.tableName,
- );
+ ddlContent.value = await api.getTableDdl(props.connectionId, props.database || "", props.tableMeta.schema || props.database || "", props.tableMeta.tableName);
} catch (e: any) {
ddlContent.value = `-- Error: ${e}`;
} finally {
@@ -5380,12 +5036,7 @@ async function fetchIndexes() {
indexesLoading.value = true;
indexesError.value = "";
try {
- indexes.value = await api.listIndexes(
- props.connectionId,
- props.database || "",
- props.tableMeta.schema || props.database || "",
- props.tableMeta.tableName,
- );
+ indexes.value = await api.listIndexes(props.connectionId, props.database || "", props.tableMeta.schema || props.database || "", props.tableMeta.tableName);
indexesLoaded.value = true;
} catch (e: any) {
indexesError.value = String(e?.message || e);
@@ -5399,12 +5050,7 @@ async function fetchForeignKeys() {
foreignKeysLoading.value = true;
foreignKeysError.value = "";
try {
- foreignKeys.value = await api.listForeignKeys(
- props.connectionId,
- props.database || "",
- props.tableMeta.schema || props.database || "",
- props.tableMeta.tableName,
- );
+ foreignKeys.value = await api.listForeignKeys(props.connectionId, props.database || "", props.tableMeta.schema || props.database || "", props.tableMeta.tableName);
foreignKeysLoaded.value = true;
} catch (e: any) {
foreignKeysError.value = String(e?.message || e);
@@ -5418,12 +5064,7 @@ async function fetchTriggers() {
triggersLoading.value = true;
triggersError.value = "";
try {
- triggers.value = await api.listTriggers(
- props.connectionId,
- props.database || "",
- props.tableMeta.schema || props.database || "",
- props.tableMeta.tableName,
- );
+ triggers.value = await api.listTriggers(props.connectionId, props.database || "", props.tableMeta.schema || props.database || "", props.tableMeta.tableName);
triggersLoaded.value = true;
} catch (e: any) {
triggersError.value = String(e?.message || e);
@@ -5616,29 +5257,19 @@ onUnmounted(() => {
const filteredColumns = computed(() => {
if (!searchQuery.value) return props.tableMeta?.columns ?? [];
const q = searchQuery.value.toLowerCase();
- return (props.tableMeta?.columns ?? []).filter(
- (c) => c.name.toLowerCase().includes(q) || c.data_type.toLowerCase().includes(q),
- );
+ return (props.tableMeta?.columns ?? []).filter((c) => c.name.toLowerCase().includes(q) || c.data_type.toLowerCase().includes(q));
});
const filteredIndexes = computed(() => {
if (!searchQuery.value) return indexes.value;
const q = searchQuery.value.toLowerCase();
- return indexes.value.filter(
- (i) => i.name.toLowerCase().includes(q) || i.columns.some((c) => c.toLowerCase().includes(q)),
- );
+ return indexes.value.filter((i) => i.name.toLowerCase().includes(q) || i.columns.some((c) => c.toLowerCase().includes(q)));
});
const filteredForeignKeys = computed(() => {
if (!searchQuery.value) return foreignKeys.value;
const q = searchQuery.value.toLowerCase();
- return foreignKeys.value.filter(
- (fk) =>
- fk.name.toLowerCase().includes(q) ||
- fk.column.toLowerCase().includes(q) ||
- fk.ref_table.toLowerCase().includes(q) ||
- fk.ref_column.toLowerCase().includes(q),
- );
+ return foreignKeys.value.filter((fk) => fk.name.toLowerCase().includes(q) || fk.column.toLowerCase().includes(q) || fk.ref_table.toLowerCase().includes(q) || fk.ref_column.toLowerCase().includes(q));
});
const filteredTriggers = computed(() => {
@@ -5705,9 +5336,7 @@ function copyRowLabels() {
return {
row: isMultiRow.value ? t("grid.copyRows", { count }) : t("grid.copyRow"),
insert: isMultiRow.value ? t("grid.copyRowsInsert", { count }) : t("grid.copyRowInsert"),
- insertNoPk: isMultiRow.value
- ? t("grid.copyRowsInsertWithoutPrimaryKeys", { count })
- : t("grid.copyRowInsertWithoutPrimaryKeys"),
+ insertNoPk: isMultiRow.value ? t("grid.copyRowsInsertWithoutPrimaryKeys", { count }) : t("grid.copyRowInsertWithoutPrimaryKeys"),
update: isMultiRow.value ? t("grid.copyRowsUpdate", { count }) : t("grid.copyRowUpdate"),
};
}
@@ -5808,10 +5437,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
// 2. Column sort & filter
if (contextColumn.value) {
- items.push(
- { label: t("grid.sortAscending"), action: () => applyContextSort("asc"), icon: ArrowUp },
- { label: t("grid.sortDescending"), action: () => applyContextSort("desc"), icon: ArrowDown },
- );
+ items.push({ label: t("grid.sortAscending"), action: () => applyContextSort("asc"), icon: ArrowUp }, { label: t("grid.sortDescending"), action: () => applyContextSort("desc"), icon: ArrowDown });
if (sortCol.value) {
items.push({ label: t("grid.clearSort"), action: () => applyContextSort(null), icon: ArrowUpDown });
}
@@ -5880,8 +5506,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
} else if (canDeleteRowItem(contextRowItem.value)) {
items.push({
label: labels.delete,
- action: () =>
- isMultiRow.value ? requestDeleteRows(affectedRowIds()) : requestDeleteRow(contextRowItem.value!.id),
+ action: () => (isMultiRow.value ? requestDeleteRows(affectedRowIds()) : requestDeleteRow(contextRowItem.value!.id)),
icon: Trash2,
variant: "destructive" as const,
});
@@ -5915,21 +5540,9 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</script>
<template>
- <div
- ref="gridRef"
- data-grid-root
- class="h-full flex flex-col overflow-hidden outline-none"
- :style="gridStyle"
- tabindex="0"
- @keydown="onGridKeydown"
- @paste="onGridPaste"
- >
+ <div ref="gridRef" data-grid-root class="h-full flex flex-col overflow-hidden outline-none" :style="gridStyle" tabindex="0" @keydown="onGridKeydown" @paste="onGridPaste">
<CustomContextMenu :items="gridContextMenuItems" v-slot="{ onContextMenu }">
- <div
- v-if="hasData || canShowWhereSearch"
- class="flex-1 flex flex-col overflow-hidden"
- @contextmenu="onContextMenu"
- >
+ <div v-if="hasData || canShowWhereSearch" class="flex-1 flex flex-col overflow-hidden" @contextmenu="onContextMenu">
<!-- Search bar -->
<div
v-if="showDataGridTopbar"
@@ -5940,17 +5553,9 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
"
>
<div class="data-grid-topbar flex items-stretch relative">
- <div
- v-if="useTransaction && editable && (tableMeta || customSave)"
- class="flex items-center px-2 py-0.5 border-r shrink-0"
- >
- <Select
- :model-value="rowStatusFilter"
- @update:model-value="(value: any) => setRowStatusFilter(String(value))"
- >
- <SelectTrigger
- class="h-5 max-w-28 border-0 bg-transparent px-0 py-0 text-xs font-medium text-foreground/70 shadow-none focus-visible:ring-0 data-[state=open]:text-foreground [&_svg]:size-3"
- >
+ <div v-if="useTransaction && editable && (tableMeta || customSave)" class="flex items-center px-2 py-0.5 border-r shrink-0">
+ <Select :model-value="rowStatusFilter" @update:model-value="(value: any) => setRowStatusFilter(String(value))">
+ <SelectTrigger class="h-5 max-w-28 border-0 bg-transparent px-0 py-0 text-xs font-medium text-foreground/70 shadow-none focus-visible:ring-0 data-[state=open]:text-foreground [&_svg]:size-3">
<SelectValue :placeholder="t('grid.filterRows')" />
</SelectTrigger>
<SelectContent position="popper">
@@ -5964,12 +5569,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<template v-if="hasLocalColumnFilters && !canShowWhereSearch && !hasSearchBarSlot">
<div class="flex items-center gap-1 px-2 py-0.5 min-w-0">
- <button
- type="button"
- class="flex shrink-0 items-center gap-1 rounded border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/15"
- :title="t('grid.clearLocalFilters')"
- @click="clearLocalFilter()"
- >
+ <button type="button" class="flex shrink-0 items-center gap-1 rounded border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/15" :title="t('grid.clearLocalFilters')" @click="clearLocalFilter()">
<Filter class="h-3 w-3" />
{{ localFilterCount }}
<X class="h-3 w-3" />
@@ -5978,29 +5578,18 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</template>
<template v-if="canShowWhereSearch">
<div ref="searchSplitContainerRef" class="flex flex-1 min-w-0">
- <div
- class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0 relative"
- :class="{ 'border-l': useTransaction && editable && (tableMeta || customSave) }"
- :style="whereSearchPaneStyle"
- >
+ <div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0 relative" :class="{ 'border-l': useTransaction && editable && (tableMeta || customSave) }" :style="whereSearchPaneStyle">
<Popover v-model:open="filterBuilderOpen">
<PopoverTrigger as-child>
<button
type="button"
class="relative flex h-5 w-5 shrink-0 items-center justify-center rounded border text-[11px] font-medium transition-colors"
- :class="
- filterButtonActive
- ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15'
- : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'
- "
+ :class="filterButtonActive ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"
:disabled="!canUseWhereSearch"
@click="ensureStructuredFilterRule"
>
<Filter class="h-3 w-3" />
- <span
- v-if="filterButtonCount"
- class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground"
- >
+ <span v-if="filterButtonCount" class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground">
{{ filterButtonCount }}
</span>
</button>
@@ -6014,33 +5603,19 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</Button>
</div>
- <div
- v-if="hasLocalColumnFilters"
- class="space-y-2 rounded-md border border-primary/20 bg-primary/5 px-2.5 py-2"
- >
+ <div v-if="hasLocalColumnFilters" class="space-y-2 rounded-md border border-primary/20 bg-primary/5 px-2.5 py-2">
<div class="flex items-center justify-between gap-3">
<div class="flex min-w-0 items-center gap-2 text-xs font-medium text-primary">
<Filter class="h-3.5 w-3.5 shrink-0" />
- <span class="truncate">{{
- t("grid.localFiltersActive", { count: localFilterCount })
- }}</span>
+ <span class="truncate">{{ t("grid.localFiltersActive", { count: localFilterCount }) }}</span>
</div>
- <Button
- variant="ghost"
- size="sm"
- class="h-7 shrink-0 px-2 text-xs"
- @click="clearLocalFilter()"
- >
+ <Button variant="ghost" size="sm" class="h-7 shrink-0 px-2 text-xs" @click="clearLocalFilter()">
<X class="mr-1 h-3.5 w-3.5" />
{{ t("grid.clearLocalFiltersShort") }}
</Button>
</div>
<div class="space-y-1">
- <div
- v-for="summary in localFilterSummaries"
- :key="summary.columnIndex"
- class="grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.6fr)_auto] items-center gap-2 rounded border border-primary/10 bg-background/70 px-2 py-1 text-xs"
- >
+ <div v-for="summary in localFilterSummaries" :key="summary.columnIndex" class="grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.6fr)_auto] items-center gap-2 rounded border border-primary/10 bg-background/70 px-2 py-1 text-xs">
<span class="truncate font-medium text-foreground" :title="summary.columnName">
{{ summary.columnName }}
</span>
@@ -6053,13 +5628,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ t("grid.localFilterMoreValues", { count: summary.hiddenValueCount }) }}
</span>
</span>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6 text-muted-foreground hover:text-destructive"
- :title="t('grid.clearFilter')"
- @click="clearLocalFilter(summary.columnIndex)"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:text-destructive" :title="t('grid.clearFilter')" @click="clearLocalFilter(summary.columnIndex)">
<X class="h-3.5 w-3.5" />
</Button>
</div>
@@ -6082,48 +5651,24 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ rule.conjunction }}
</Button>
</div>
- <div
- class="grid grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1.2fr)_auto] items-center gap-2"
- >
- <Select
- :model-value="rule.columnName"
- @update:model-value="
- (value: any) => updateStructuredFilterRule(rule.id, { columnName: String(value) })
- "
- >
- <SelectTrigger
- class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate"
- >
+ <div class="grid grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1.2fr)_auto] items-center gap-2">
+ <Select :model-value="rule.columnName" @update:model-value="(value: any) => updateStructuredFilterRule(rule.id, { columnName: String(value) })">
+ <SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate">
<SelectValue :placeholder="t('grid.filterBuilderColumn')" />
</SelectTrigger>
<SelectContent position="popper">
- <SelectItem
- v-for="columnName in filterBuilderColumnOptions"
- :key="columnName"
- :value="columnName"
- >
+ <SelectItem v-for="columnName in filterBuilderColumnOptions" :key="columnName" :value="columnName">
{{ columnName }}
</SelectItem>
</SelectContent>
</Select>
- <Select
- :model-value="rule.mode"
- @update:model-value="
- (value: any) => updateStructuredFilterRule(rule.id, { mode: value as FilterMode })
- "
- >
- <SelectTrigger
- class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate"
- >
+ <Select :model-value="rule.mode" @update:model-value="(value: any) => updateStructuredFilterRule(rule.id, { mode: value as FilterMode })">
+ <SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
- <SelectItem
- v-for="option in filterModeOptions"
- :key="option.value"
- :value="option.value"
- >
+ <SelectItem v-for="option in filterModeOptions" :key="option.value" :value="option.value">
{{ t(option.labelKey) }}
</SelectItem>
</SelectContent>
@@ -6134,35 +5679,21 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
:model-value="rule.rawValue"
class="h-8 min-w-0 text-xs"
:placeholder="t('grid.filterBuilderValue')"
- @update:model-value="
- (value) => updateStructuredFilterRule(rule.id, { rawValue: String(value ?? '') })
- "
+ @update:model-value="(value) => updateStructuredFilterRule(rule.id, { rawValue: String(value ?? '') })"
@keydown.enter.prevent="applyStructuredFilters"
/>
- <div
- v-else
- class="flex h-8 min-w-0 items-center overflow-hidden rounded-md border border-dashed px-2 text-xs text-muted-foreground"
- >
+ <div v-else class="flex h-8 min-w-0 items-center overflow-hidden rounded-md border border-dashed px-2 text-xs text-muted-foreground">
<span class="truncate">{{ t("grid.filterBuilderNoValue") }}</span>
</div>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
- :disabled="structuredFilterRules.length === 1"
- @click="removeStructuredFilterRule(rule.id)"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :disabled="structuredFilterRules.length === 1" @click="removeStructuredFilterRule(rule.id)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</div>
</template>
</div>
- <div
- v-else
- class="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground"
- >
+ <div v-else class="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
{{ t("grid.filterBuilderEmpty") }}
</div>
@@ -6194,25 +5725,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@click="updateWhereSuggestionPosition"
@blur="dismissWhereSuggestions"
/>
- <span
- ref="whereMeasureRef"
- class="invisible absolute left-0 top-0 text-xs whitespace-pre pointer-events-none"
- aria-hidden="true"
- />
+ <span ref="whereMeasureRef" class="invisible absolute left-0 top-0 text-xs whitespace-pre pointer-events-none" aria-hidden="true" />
<!-- WHERE suggestion dropdown -->
<Teleport to="body">
- <div
- v-if="whereSuggestions.length > 0"
- class="fixed z-50 min-w-[180px] rounded-md border bg-popover text-popover-foreground shadow-md"
- :style="whereSuggestionStyle"
- >
+ <div v-if="whereSuggestions.length > 0" class="fixed z-50 min-w-[180px] rounded-md border bg-popover text-popover-foreground shadow-md" :style="whereSuggestionStyle">
<div
v-for="(sug, idx) in whereSuggestions"
:key="sug"
class="flex items-center px-3 py-1.5 text-xs cursor-pointer"
- :class="
- idx === whereSuggestionIndex ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50'
- "
+ :class="idx === whereSuggestionIndex ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50'"
@mousedown.prevent="
whereSuggestionIndex = idx;
acceptWhereSuggestion();
@@ -6245,9 +5766,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<span class="h-5 w-px bg-border group-hover:bg-primary/60" />
</button>
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 border-r min-w-0 relative">
- <span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0"
- >ORDER BY</span
- >
+ <span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0">ORDER BY</span>
<input
ref="orderByInputRef"
v-model="orderByInput"
@@ -6260,25 +5779,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@click="updateOrderBySuggestionPosition"
@blur="dismissOrderBySuggestions"
/>
- <span
- ref="orderByMeasureRef"
- class="invisible absolute left-0 top-0 text-xs whitespace-pre pointer-events-none"
- aria-hidden="true"
- />
+ <span ref="orderByMeasureRef" class="invisible absolute left-0 top-0 text-xs whitespace-pre pointer-events-none" aria-hidden="true" />
<!-- ORDER BY suggestion dropdown -->
<Teleport to="body">
- <div
- v-if="orderBySuggestions.length > 0"
- class="fixed z-50 min-w-[180px] rounded-md border bg-popover text-popover-foreground shadow-md"
- :style="orderBySuggestionStyle"
- >
+ <div v-if="orderBySuggestions.length > 0" class="fixed z-50 min-w-[180px] rounded-md border bg-popover text-popover-foreground shadow-md" :style="orderBySuggestionStyle">
<div
v-for="(sug, idx) in orderBySuggestions"
:key="sug"
class="flex items-center px-3 py-1.5 text-xs cursor-pointer"
- :class="
- idx === orderBySuggestionIndex ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50'
- "
+ :class="idx === orderBySuggestionIndex ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50'"
@mousedown.prevent="
orderBySuggestionIndex = idx;
acceptOrderBySuggestion();
@@ -6304,20 +5813,12 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
</template>
- <slot
- name="search-bar"
- :local-filter-count="localFilterCount"
- :has-local-column-filters="hasLocalColumnFilters"
- :local-filter-summaries="localFilterSummaries"
- :clear-local-filter="clearLocalFilter"
- />
+ <slot name="search-bar" :local-filter-count="localFilterCount" :has-local-column-filters="hasLocalColumnFilters" :local-filter-summaries="localFilterSummaries" :clear-local-filter="clearLocalFilter" />
<div class="flex shrink-0 items-center gap-1 px-1 ml-auto">
<Tooltip v-if="showQueryEditReadyBadge">
<TooltipTrigger as-child>
- <div
- class="flex h-5 items-center gap-1 rounded border border-emerald-500/30 bg-emerald-500/10 px-1.5 text-xs font-medium text-emerald-700 dark:text-emerald-300"
- >
+ <div class="flex h-5 items-center gap-1 rounded border border-emerald-500/30 bg-emerald-500/10 px-1.5 text-xs font-medium text-emerald-700 dark:text-emerald-300">
{{ t("grid.queryEditReady") }}
</div>
</TooltipTrigger>
@@ -6325,27 +5826,14 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ t("grid.queryEditReadyHint", { table: tableMeta?.tableName }) }}
</TooltipContent>
</Tooltip>
- <Button
- v-if="props.context !== 'results'"
- variant="ghost"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- :disabled="isSaving"
- @click="onToolbarRefresh"
- >
+ <Button v-if="props.context !== 'results'" variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" :disabled="isSaving" @click="onToolbarRefresh">
<Loader2 v-if="loading" class="w-3 h-3 mr-1 animate-spin" />
<RefreshCcw v-else class="w-3 h-3 mr-1" />
{{ t("grid.refresh") }}
</Button>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- :class="dataGridRenderMode === 'canvas' ? 'text-primary bg-primary/10' : ''"
- @click="toggleDataGridRenderMode"
- >
+ <Button variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" :class="dataGridRenderMode === 'canvas' ? 'text-primary bg-primary/10' : ''" @click="toggleDataGridRenderMode">
<SquareDashed class="w-3 h-3 mr-1" />
{{ dataGridRenderMode === "canvas" ? t("grid.canvasRenderMode") : t("grid.domRenderMode") }}
</Button>
@@ -6354,30 +5842,13 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ t("grid.renderModeHint") }}
</TooltipContent>
</Tooltip>
- <Button
- v-if="editable && (tableMeta || customSave)"
- variant="ghost"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- @click="addRow"
- >
- <Plus class="w-3 h-3 mr-1" /> {{ t("grid.addRow") }}
- </Button>
+ <Button v-if="editable && (tableMeta || customSave)" variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" @click="addRow"> <Plus class="w-3 h-3 mr-1" /> {{ t("grid.addRow") }} </Button>
<template v-if="saveToolbarState.showActions">
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="default"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- :disabled="saveToolbarState.actionsDisabled"
- @click="onToolbarCommit"
- >
+ <Button variant="default" size="sm" class="h-5 text-xs px-1.5 shrink-0" :disabled="saveToolbarState.actionsDisabled" @click="onToolbarCommit">
<Loader2 v-if="isSaving" class="w-3 h-3 mr-1 animate-spin" />
- <span
- v-else-if="pendingChangeCount > 0"
- class="mr-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-300 px-1 text-[9px] font-semibold leading-none text-amber-950 shadow-[0_0_0_1px_rgba(120,53,15,0.16)] dark:bg-amber-400 dark:text-amber-950"
- >
+ <span v-else-if="pendingChangeCount > 0" class="mr-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-300 px-1 text-[9px] font-semibold leading-none text-amber-950 shadow-[0_0_0_1px_rgba(120,53,15,0.16)] dark:bg-amber-400 dark:text-amber-950">
{{ pendingChangeCount }}
</span>
<Save v-else class="w-3 h-3 mr-1" />
@@ -6388,13 +5859,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ t(saveActionMode.tooltipKey, { count: pendingChangeCount }) }}
</TooltipContent>
</Tooltip>
- <Button
- variant="outline"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- :disabled="saveToolbarState.actionsDisabled"
- @click="useTransaction ? onToolbarRollback() : discardChanges()"
- >
+ <Button variant="outline" size="sm" class="h-5 text-xs px-1.5 shrink-0" :disabled="saveToolbarState.actionsDisabled" @click="useTransaction ? onToolbarRollback() : discardChanges()">
<RotateCcw class="w-3 h-3 mr-1" />
{{ t(saveActionMode.secondaryActionKey) }}
</Button>
@@ -6403,26 +5868,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
</div>
<!-- Truncation warning banner -->
- <div
- v-if="showTruncationWarning"
- class="shrink-0 px-3 py-1 bg-amber-500/10 border-b border-amber-500/20 text-xs text-amber-600 dark:text-amber-400 flex items-center gap-1.5"
- >
+ <div v-if="showTruncationWarning" class="shrink-0 px-3 py-1 bg-amber-500/10 border-b border-amber-500/20 text-xs text-amber-600 dark:text-amber-400 flex items-center gap-1.5">
<span>{{ t("grid.truncatedHint", { count: pageSize }) }}</span>
</div>
<!-- Content area: table + side/bottom detail panes -->
<div class="flex-1 grid min-h-0 overflow-hidden" :style="contentGridStyle">
<div class="col-start-1 row-start-1 flex flex-col min-w-0 overflow-hidden relative">
<!-- Search overlay (Ctrl+F) -->
- <Transition
- enter-active-class="transition-opacity duration-150"
- leave-active-class="transition-opacity duration-100"
- enter-from-class="opacity-0"
- leave-to-class="opacity-0"
- >
- <div
- v-if="searchOverlayVisible"
- class="absolute top-1 right-2 z-20 flex items-center gap-1 px-2 py-1 bg-background border rounded-md shadow-md"
- >
+ <Transition enter-active-class="transition-opacity duration-150" leave-active-class="transition-opacity duration-100" enter-from-class="opacity-0" leave-to-class="opacity-0">
+ <div v-if="searchOverlayVisible" class="absolute top-1 right-2 z-20 flex items-center gap-1 px-2 py-1 bg-background border rounded-md shadow-md">
<Search class="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<input
ref="searchInputRef"
@@ -6435,15 +5889,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@keydown="onSearchKeydown"
@click="updateSuggestionPosition"
/>
- <span
- ref="measureRef"
- class="invisible absolute left-0 top-0 text-xs whitespace-pre pointer-events-none"
- aria-hidden="true"
- />
- <div
- v-if="searchSuggestions.length > 0"
- class="absolute top-full right-0 mt-0.5 z-50 min-w-[180px] rounded-md border bg-popover text-popover-foreground shadow-md"
- >
+ <span ref="measureRef" class="invisible absolute left-0 top-0 text-xs whitespace-pre pointer-events-none" aria-hidden="true" />
+ <div v-if="searchSuggestions.length > 0" class="absolute top-full right-0 mt-0.5 z-50 min-w-[180px] rounded-md border bg-popover text-popover-foreground shadow-md">
<div
v-for="(sug, idx) in searchSuggestions"
:key="sug"
@@ -6459,19 +5906,14 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<span>{{ sug }}</span>
</div>
</div>
- <span v-if="searchMatches.length > 0" class="text-xs text-muted-foreground shrink-0">
- {{ currentMatchIndex + 1 }}/{{ searchMatches.length }}
- </span>
+ <span v-if="searchMatches.length > 0" class="text-xs text-muted-foreground shrink-0"> {{ currentMatchIndex + 1 }}/{{ searchMatches.length }} </span>
<span v-else-if="deferredClientSearchText" class="text-xs text-muted-foreground shrink-0"> 0 </span>
<button class="text-muted-foreground hover:text-foreground shrink-0" @click="closeSearch">
<X class="w-3.5 h-3.5" />
</button>
</div>
</Transition>
- <div
- v-if="isErrorResult"
- class="flex-1 flex flex-col items-center justify-center gap-2 px-6 text-center text-destructive"
- >
+ <div v-if="isErrorResult" class="flex-1 flex flex-col items-center justify-center gap-2 px-6 text-center text-destructive">
<TriangleAlert class="h-8 w-8 text-destructive/50" aria-hidden="true" />
<div class="space-y-1">
<div class="text-sm font-medium">{{ t("grid.queryError") }}</div>
@@ -6483,31 +5925,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="h-8 flex items-center gap-2 px-3 border-y shrink-0 bg-muted/20">
<Rows3 class="w-3.5 h-3.5 text-muted-foreground" />
<span class="text-xs font-medium">{{ t("grid.transpose") }}</span>
- <span class="text-xs text-muted-foreground">
- {{ t("grid.rowNumber") }} {{ (transposeRowIndex ?? 0) + 1 }}
- </span>
- <span
- class="rounded border border-border bg-background px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground"
- >
+ <span class="text-xs text-muted-foreground"> {{ t("grid.rowNumber") }} {{ (transposeRowIndex ?? 0) + 1 }} </span>
+ <span class="rounded border border-border bg-background px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
{{ multiRowTranspose ? t("grid.transposeMultiRow") : t("grid.transposeSingleRow") }}
</span>
<span class="flex-1" />
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :disabled="transposeRowIndex === 0"
- @click="transposeNav(-1)"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="transposeRowIndex === 0" @click="transposeNav(-1)">
<ChevronLeft class="w-3 h-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :disabled="transposeRowIndex === displayItems.length - 1"
- @click="transposeNav(1)"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="transposeRowIndex === displayItems.length - 1" @click="transposeNav(1)">
<ChevronRight class="w-3 h-3" />
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="closeTranspose">
@@ -6529,19 +5955,10 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@scroll="onTransposeScroll"
>
<template #before>
- <div
- class="sticky top-0 z-20 flex h-7 border-b border-border bg-[rgb(239_239_239)] text-xs font-semibold text-muted-foreground dark:bg-muted"
- :style="{ width: `${transposeTotalWidth}px` }"
- >
- <div
- class="sticky left-0 z-30 shrink-0 border-r border-border px-3 py-1.5 bg-[rgb(239_239_239)] truncate dark:bg-muted relative"
- :style="{ width: `${transposePinnedWidth}px` }"
- >
+ <div class="sticky top-0 z-20 flex h-7 border-b border-border bg-[rgb(239_239_239)] text-xs font-semibold text-muted-foreground dark:bg-muted" :style="{ width: `${transposeTotalWidth}px` }">
+ <div class="sticky left-0 z-30 shrink-0 border-r border-border px-3 py-1.5 bg-[rgb(239_239_239)] truncate dark:bg-muted relative" :style="{ width: `${transposePinnedWidth}px` }">
{{ t("grid.columnName") }}
- <div
- class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30"
- @mousedown.stop="onTransposePinnedResizeStart"
- />
+ <div class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30" @mousedown.stop="onTransposePinnedResizeStart" />
</div>
<div class="shrink-0" :style="{ width: `${transposeBeforeSpacerWidth}px` }" />
<div
@@ -6549,39 +5966,23 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
:key="`transpose-head-${recordIndex}`"
class="shrink-0 border-r border-border px-2 py-1.5 text-center tabular-nums relative"
:class="{
- 'transpose-record-header-selected text-primary font-semibold':
- transposeRecordUsesFramedHeader(recordIndex),
- 'transpose-record-header-active text-primary':
- transposeRecordUsesActiveHighlight(recordIndex) &&
- !transposeRecordUsesFramedHeader(recordIndex),
- 'bg-[rgb(239_239_239)] dark:bg-muted':
- !transposeRecordUsesActiveHighlight(recordIndex) &&
- !transposeRecordUsesFramedHeader(recordIndex),
+ 'transpose-record-header-selected text-primary font-semibold': transposeRecordUsesFramedHeader(recordIndex),
+ 'transpose-record-header-active text-primary': transposeRecordUsesActiveHighlight(recordIndex) && !transposeRecordUsesFramedHeader(recordIndex),
+ 'bg-[rgb(239_239_239)] dark:bg-muted': !transposeRecordUsesActiveHighlight(recordIndex) && !transposeRecordUsesFramedHeader(recordIndex),
}"
:style="{ width: `${getTransposeRecordWidth(recordIndex)}px` }"
@click="selectTransposeRecord(recordIndex, $event)"
@contextmenu="selectTransposeRecord(recordIndex, $event)"
>
{{ recordIndex + 1 }}
- <div
- class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30"
- @mousedown.stop="onTransposeRecordResizeStart(recordIndex, $event)"
- @dblclick.stop="autoFitTransposeRecord(recordIndex)"
- />
+ <div class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30" @mousedown.stop="onTransposeRecordResizeStart(recordIndex, $event)" @dblclick.stop="autoFitTransposeRecord(recordIndex)" />
</div>
<div class="shrink-0" :style="{ width: `${transposeAfterSpacerWidth}px` }" />
</div>
</template>
<template #default="{ item }">
- <div
- class="flex border-b border-border/60 text-xs"
- :style="{ height: '30px', width: `${transposeTotalWidth}px` }"
- >
- <div
- class="sticky left-0 z-10 flex shrink-0 items-center border-r border-border bg-background px-3 py-0 font-medium truncate"
- :style="{ width: `${transposePinnedWidth}px` }"
- :title="item.column"
- >
+ <div class="flex border-b border-border/60 text-xs" :style="{ height: '30px', width: `${transposeTotalWidth}px` }">
+ <div class="sticky left-0 z-10 flex shrink-0 items-center border-r border-border bg-background px-3 py-0 font-medium truncate" :style="{ width: `${transposePinnedWidth}px` }" :title="item.column">
{{ item.column }}
</div>
<div class="shrink-0" :style="{ width: `${transposeBeforeSpacerWidth}px` }" />
@@ -6591,33 +5992,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
class="relative flex shrink-0 items-center border-r border-border/70 px-2 py-0 font-mono truncate"
:class="{
'text-muted-foreground italic': cell.isNull,
- 'cell-selected':
- transposeCellIsSelected(cell.recordIndex, cell.valueIndex) &&
- !displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
- 'cell-selected-dirty':
- transposeCellIsSelected(cell.recordIndex, cell.valueIndex) &&
- displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
- 'row-cell-selected':
- transposeRecordUsesSelectionVisual(cell.recordIndex) &&
- !transposeCellIsSelected(cell.recordIndex, cell.valueIndex) &&
- !displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
- 'row-cell-selected-dirty':
- transposeRecordUsesSelectionVisual(cell.recordIndex) &&
- !transposeCellIsSelected(cell.recordIndex, cell.valueIndex) &&
- displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
- 'bg-primary/15':
- transposeRecordUsesActiveHighlight(cell.recordIndex) &&
- !transposeRecordUsesSelectionVisual(cell.recordIndex) &&
- !displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex] &&
- !transposeCellIsSelected(cell.recordIndex, cell.valueIndex),
+ 'cell-selected': transposeCellIsSelected(cell.recordIndex, cell.valueIndex) && !displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
+ 'cell-selected-dirty': transposeCellIsSelected(cell.recordIndex, cell.valueIndex) && displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
+ 'row-cell-selected': transposeRecordUsesSelectionVisual(cell.recordIndex) && !transposeCellIsSelected(cell.recordIndex, cell.valueIndex) && !displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
+ 'row-cell-selected-dirty': transposeRecordUsesSelectionVisual(cell.recordIndex) && !transposeCellIsSelected(cell.recordIndex, cell.valueIndex) && displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
+ 'bg-primary/15': transposeRecordUsesActiveHighlight(cell.recordIndex) && !transposeRecordUsesSelectionVisual(cell.recordIndex) && !displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex] && !transposeCellIsSelected(cell.recordIndex, cell.valueIndex),
'bg-yellow-500/10 cell-dirty': displayItems[cell.recordIndex]?.isDirtyCol[cell.valueIndex],
'cursor-text': !isScrolling && canEditCellItem(displayItems[cell.recordIndex], cell.valueIndex),
'hover:bg-accent/50':
- !isScrolling &&
- canEditCellItem(displayItems[cell.recordIndex], cell.valueIndex) &&
- !transposeRecordUsesSelectionVisual(cell.recordIndex) &&
- !transposeRecordUsesActiveHighlight(cell.recordIndex) &&
- !transposeCellIsSelected(cell.recordIndex, cell.valueIndex),
+ !isScrolling && canEditCellItem(displayItems[cell.recordIndex], cell.valueIndex) && !transposeRecordUsesSelectionVisual(cell.recordIndex) && !transposeRecordUsesActiveHighlight(cell.recordIndex) && !transposeCellIsSelected(cell.recordIndex, cell.valueIndex),
}"
:style="{ width: `${getTransposeRecordWidth(cell.recordIndex)}px` }"
:title="cell.display"
@@ -6625,25 +6008,10 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@mouseenter="onTransposeCellMouseenter(cell.recordIndex, cell.valueIndex)"
@mouseleave="onCellMouseleave(cell.recordIndex, cell.valueIndex)"
@contextmenu="onTransposeCellContext(cell.recordIndex, cell.valueIndex, $event)"
- @dblclick.stop="
- canEditCellItem(displayItems[cell.recordIndex], cell.valueIndex) &&
- startEdit(displayItems[cell.recordIndex].id, cell.valueIndex)
- "
+ @dblclick.stop="canEditCellItem(displayItems[cell.recordIndex], cell.valueIndex) && startEdit(displayItems[cell.recordIndex].id, cell.valueIndex)"
>
- <template
- v-if="
- editingCell?.rowId === displayItems[cell.recordIndex]?.id &&
- editingCell?.col === cell.valueIndex
- "
- >
- <TemporalCellEditor
- v-if="temporalEditorKindForColumn(cell.valueIndex)"
- v-model="editValue"
- :kind="temporalEditorKindForColumn(cell.valueIndex)!"
- cell-layout="transpose"
- @cancel="cancelEdit"
- @commit="commitGridEdit"
- />
+ <template v-if="editingCell?.rowId === displayItems[cell.recordIndex]?.id && editingCell?.col === cell.valueIndex">
+ <TemporalCellEditor v-if="temporalEditorKindForColumn(cell.valueIndex)" v-model="editValue" :kind="temporalEditorKindForColumn(cell.valueIndex)!" cell-layout="transpose" @cancel="cancelEdit" @commit="commitGridEdit" />
<input
v-else
v-model="editValue"
@@ -6659,34 +6027,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</template>
<template v-else>
{{ cell.display }}
- <div
- v-if="cellDetailButtonVisible(cell.recordIndex, cell.valueIndex)"
- class="absolute right-0.5 top-0.5 flex items-center gap-1"
- >
- <DropdownMenu
- v-if="canQuickDownloadCellValue(cell.recordIndex, cell.valueIndex)"
- :open="quickDownloadMenuOpenFor(cell.recordIndex, cell.valueIndex)"
- @update:open="
- (value: boolean) =>
- handleQuickDownloadMenuOpenChange(value, cell.recordIndex, cell.valueIndex)
- "
- >
+ <div v-if="cellDetailButtonVisible(cell.recordIndex, cell.valueIndex)" class="absolute right-0.5 top-0.5 flex items-center gap-1">
+ <DropdownMenu v-if="canQuickDownloadCellValue(cell.recordIndex, cell.valueIndex)" :open="quickDownloadMenuOpenFor(cell.recordIndex, cell.valueIndex)" @update:open="(value: boolean) => handleQuickDownloadMenuOpenChange(value, cell.recordIndex, cell.valueIndex)">
<DropdownMenuTrigger as-child>
- <button
- class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground"
- :title="t('grid.downloadBinaryValue')"
- @mousedown.stop
- @click.stop
- >
+ <button class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground" :title="t('grid.downloadBinaryValue')" @mousedown.stop @click.stop>
<Download class="h-3 w-3" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-44">
- <DropdownMenuItem
- v-for="mode in BINARY_CELL_DOWNLOAD_MODES"
- :key="mode"
- @click="downloadCellBinaryValue(cell.recordIndex, cell.valueIndex, mode)"
- >
+ <DropdownMenuItem v-for="mode in BINARY_CELL_DOWNLOAD_MODES" :key="mode" @click="downloadCellBinaryValue(cell.recordIndex, cell.valueIndex, mode)">
{{ t(`grid.binaryDownload.${mode}`) }}
</DropdownMenuItem>
</DropdownMenuContent>
@@ -6709,31 +6058,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<template v-else>
<!-- Sticky header -->
- <div
- ref="headerRef"
- class="shrink-0 bg-[rgb(239_239_239)] dark:bg-muted/60 z-10 border-y border-border overflow-hidden"
- >
+ <div ref="headerRef" class="shrink-0 bg-[rgb(239_239_239)] dark:bg-muted/60 z-10 border-y border-border overflow-hidden">
<div class="flex text-xs font-semibold text-foreground" :style="{ width: 'var(--header-total-w)' }">
- <div
- class="shrink-0 px-2 py-1.5 border-r border-border text-center text-muted-foreground select-none cursor-pointer hover:bg-accent/60 sticky left-0 z-20 bg-[rgb(239_239_239)] dark:bg-muted"
- :style="{ width: 'var(--row-num-w)' }"
- @click="selectAllCells"
- >
- #
- </div>
+ <div class="shrink-0 px-2 py-1.5 border-r border-border text-center text-muted-foreground select-none cursor-pointer hover:bg-accent/60 sticky left-0 z-20 bg-[rgb(239_239_239)] dark:bg-muted" :style="{ width: 'var(--row-num-w)' }" @click="selectAllCells">#</div>
<div class="shrink-0" :style="{ width: `${horizontalColumnWindow.beforeWidth}px` }" />
- <LightTooltip
- v-for="col in renderedGridColumns"
- :key="`${col.name}-${col.actualColIdx}`"
- :text="col.name"
- side="bottom"
- :side-offset="4"
- >
+ <LightTooltip v-for="col in renderedGridColumns" :key="`${col.name}-${col.actualColIdx}`" :text="col.name" side="bottom" :side-offset="4">
<div
class="shrink-0 px-2 py-1.5 border-r border-border whitespace-nowrap hover:bg-accent/60 select-none relative overflow-hidden"
:class="{
- 'bg-primary/15 ring-1 ring-inset ring-primary/40':
- highlightedColumnIndex === col.actualColIdx || columnIsSelected(col.visibleColIdx),
+ 'bg-primary/15 ring-1 ring-inset ring-primary/40': highlightedColumnIndex === col.actualColIdx || columnIsSelected(col.visibleColIdx),
}"
:style="renderedColumnStyle(col.visibleColIdx)"
:data-grid-column-index="col.actualColIdx"
@@ -6745,19 +6078,10 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<span class="min-w-0 truncate leading-4">
{{ col.name }}
</span>
- <span
- v-if="headerColumnType(col.name, col.actualColIdx)"
- class="min-w-0 truncate text-[10px] font-normal leading-3"
- :class="typeColorClass(headerColumnType(col.name, col.actualColIdx))"
- :title="headerColumnType(col.name, col.actualColIdx)"
- >
+ <span v-if="headerColumnType(col.name, col.actualColIdx)" class="min-w-0 truncate text-[10px] font-normal leading-3" :class="typeColorClass(headerColumnType(col.name, col.actualColIdx))" :title="headerColumnType(col.name, col.actualColIdx)">
{{ headerColumnType(col.name, col.actualColIdx) }}
</span>
- <span
- v-if="headerColumnComment(col.name)"
- class="min-w-0 truncate text-[10px] font-normal leading-3 text-muted-foreground"
- :title="headerColumnComment(col.name)"
- >
+ <span v-if="headerColumnComment(col.name)" class="min-w-0 truncate text-[10px] font-normal leading-3 text-muted-foreground" :title="headerColumnComment(col.name)">
{{ headerColumnComment(col.name) }}
</span>
</span>
@@ -6765,73 +6089,38 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
v-if="headerColumnSortable(col.actualColIdx)"
type="button"
class="flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
- :class="
- sortCol === col.name && sortColIndex === col.actualColIdx
- ? 'text-primary opacity-100'
- : 'opacity-80'
- "
+ :class="sortCol === col.name && sortColIndex === col.actualColIdx ? 'text-primary opacity-100' : 'opacity-80'"
:title="t('grid.sort')"
@click.stop="toggleSort(col.name, col.actualColIdx)"
>
- <ArrowUp
- v-if="sortCol === col.name && sortColIndex === col.actualColIdx && sortDir === 'asc'"
- class="h-3 w-3 shrink-0"
- />
- <ArrowDown
- v-else-if="sortCol === col.name && sortColIndex === col.actualColIdx && sortDir === 'desc'"
- class="h-3 w-3 shrink-0"
- />
+ <ArrowUp v-if="sortCol === col.name && sortColIndex === col.actualColIdx && sortDir === 'asc'" class="h-3 w-3 shrink-0" />
+ <ArrowDown v-else-if="sortCol === col.name && sortColIndex === col.actualColIdx && sortDir === 'desc'" class="h-3 w-3 shrink-0" />
<ArrowUpDown v-else class="h-3 w-3 shrink-0" />
</button>
- <DropdownMenu
- v-if="compactColumnHeaderActions"
- :open="headerActionMenuOpenColumn === col.actualColIdx"
- @update:open="
- (value: boolean) => (headerActionMenuOpenColumn = value ? col.actualColIdx : null)
- "
- >
+ <DropdownMenu v-if="compactColumnHeaderActions" :open="headerActionMenuOpenColumn === col.actualColIdx" @update:open="(value: boolean) => (headerActionMenuOpenColumn = value ? col.actualColIdx : null)">
<DropdownMenuTrigger as-child>
<button
type="button"
class="flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
- :class="
- columnHasFormatter(col.actualColIdx) || localFilterActive(col.actualColIdx)
- ? 'text-primary opacity-90'
- : 'opacity-80'
- "
+ :class="columnHasFormatter(col.actualColIdx) || localFilterActive(col.actualColIdx) ? 'text-primary opacity-90' : 'opacity-80'"
:title="t('grid.columnActions')"
@click.stop
>
<ChevronDown class="h-3 w-3" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- class="w-max min-w-28 max-w-48 p-0.5"
- @click.stop
- @keydown.stop
- >
- <DropdownMenuItem
- class="gap-1 px-1.5 py-0.5 text-xs"
- :disabled="!formatterKeyForColumn(col.name)"
- @select.prevent="openCompactColumnFormatter(col.actualColIdx)"
- >
+ <DropdownMenuContent align="end" class="w-max min-w-28 max-w-48 p-0.5" @click.stop @keydown.stop>
+ <DropdownMenuItem class="gap-1 px-1.5 py-0.5 text-xs" :disabled="!formatterKeyForColumn(col.name)" @select.prevent="openCompactColumnFormatter(col.actualColIdx)">
<Code2 class="h-3 w-3" />
{{ t("grid.columnFormatter") }}
</DropdownMenuItem>
- <DropdownMenuItem
- class="gap-1 px-1.5 py-0.5 text-xs"
- @select.prevent="openCompactLocalFilter(col.actualColIdx)"
- >
+ <DropdownMenuItem class="gap-1 px-1.5 py-0.5 text-xs" @select.prevent="openCompactLocalFilter(col.actualColIdx)">
<Filter class="h-3 w-3" />
{{ t("grid.localFilter") }}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <Popover
- :open="formatterOpenColumn === col.actualColIdx"
- @update:open="(value: boolean) => handleColumnFormatterOpenChange(value, col.actualColIdx)"
- >
+ <Popover :open="formatterOpenColumn === col.actualColIdx" @update:open="(value: boolean) => handleColumnFormatterOpenChange(value, col.actualColIdx)">
<PopoverAnchor v-if="compactColumnHeaderActions" as-child>
<span class="pointer-events-none absolute right-3 top-1/2 h-px w-px -translate-y-1/2" />
</PopoverAnchor>
@@ -6847,13 +6136,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Code2 class="h-3.5 w-3.5" />
</button>
</PopoverTrigger>
- <PopoverContent
- align="start"
- side="bottom"
- class="w-[380px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="start" side="bottom" class="w-[380px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-3 py-2">
<div class="text-sm font-semibold">
{{ t("grid.columnFormatterFor", { column: col.name }) }}
@@ -6867,10 +6150,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterType") }}
</div>
- <Select
- :model-value="formatterKind"
- @update:model-value="(value: any) => (formatterKind = value)"
- >
+ <Select :model-value="formatterKind" @update:model-value="(value: any) => (formatterKind = value)">
<SelectTrigger class="h-8 text-xs">
<SelectValue />
</SelectTrigger>
@@ -6878,9 +6158,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<SelectItem value="datetime">{{ t("grid.formatterDatetime") }}</SelectItem>
<SelectItem value="json-path">{{ t("grid.formatterJsonPath") }}</SelectItem>
<SelectItem value="mask">{{ t("grid.formatterMask") }}</SelectItem>
- <SelectItem value="custom-template">{{
- t("grid.formatterCustomTemplate")
- }}</SelectItem>
+ <SelectItem value="custom-template">{{ t("grid.formatterCustomTemplate") }}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -6889,19 +6167,14 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterTimestampUnit") }}
</div>
- <Select
- :model-value="formatterDateUnit"
- @update:model-value="(value: any) => (formatterDateUnit = value)"
- >
+ <Select :model-value="formatterDateUnit" @update:model-value="(value: any) => (formatterDateUnit = value)">
<SelectTrigger class="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">{{ t("grid.formatterUnitAuto") }}</SelectItem>
<SelectItem value="seconds">{{ t("grid.formatterUnitSeconds") }}</SelectItem>
- <SelectItem value="milliseconds">{{
- t("grid.formatterUnitMilliseconds")
- }}</SelectItem>
+ <SelectItem value="milliseconds">{{ t("grid.formatterUnitMilliseconds") }}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -6910,14 +6183,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterJsonPathInput") }}
</div>
- <input
- v-model="formatterJsonPath"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="h-8 w-full rounded border bg-background px-2 font-mono text-xs outline-none focus:border-primary"
- placeholder="$.user.name"
- />
+ <input v-model="formatterJsonPath" autocapitalize="off" autocorrect="off" spellcheck="false" class="h-8 w-full rounded border bg-background px-2 font-mono text-xs outline-none focus:border-primary" placeholder="$.user.name" />
</div>
<div v-else-if="formatterKind === 'mask'" class="grid grid-cols-2 gap-2">
@@ -6925,23 +6191,13 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<span class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterMaskPrefix") }}
</span>
- <input
- v-model.number="formatterMaskPrefix"
- type="number"
- min="0"
- class="h-8 w-full rounded border bg-background px-2 text-xs outline-none focus:border-primary"
- />
+ <input v-model.number="formatterMaskPrefix" type="number" min="0" class="h-8 w-full rounded border bg-background px-2 text-xs outline-none focus:border-primary" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterMaskSuffix") }}
</span>
- <input
- v-model.number="formatterMaskSuffix"
- type="number"
- min="0"
- class="h-8 w-full rounded border bg-background px-2 text-xs outline-none focus:border-primary"
- />
+ <input v-model.number="formatterMaskSuffix" type="number" min="0" class="h-8 w-full rounded border bg-background px-2 text-xs outline-none focus:border-primary" />
</label>
</div>
@@ -6950,22 +6206,13 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterSavedCustom") }}
</div>
- <Select
- :model-value="formatterCustomId"
- @update:model-value="(value: any) => selectCustomFormatter(String(value))"
- >
+ <Select :model-value="formatterCustomId" @update:model-value="(value: any) => selectCustomFormatter(String(value))">
<SelectTrigger class="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem :value="CUSTOM_FORMATTER_NEW">{{
- t("grid.formatterNewCustom")
- }}</SelectItem>
- <SelectItem
- v-for="formatter in savedCustomFormatters"
- :key="formatter.id"
- :value="formatter.id"
- >
+ <SelectItem :value="CUSTOM_FORMATTER_NEW">{{ t("grid.formatterNewCustom") }}</SelectItem>
+ <SelectItem v-for="formatter in savedCustomFormatters" :key="formatter.id" :value="formatter.id">
{{ formatter.name }}
</SelectItem>
</SelectContent>
@@ -6975,24 +6222,13 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<span class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterCustomName") }}
</span>
- <input
- v-model="formatterCustomName"
- class="h-8 w-full rounded border bg-background px-2 text-xs outline-none focus:border-primary"
- :placeholder="t('grid.formatterCustomNamePlaceholder')"
- />
+ <input v-model="formatterCustomName" class="h-8 w-full rounded border bg-background px-2 text-xs outline-none focus:border-primary" :placeholder="t('grid.formatterCustomNamePlaceholder')" />
</label>
<label class="block space-y-1.5">
<span class="text-xs font-medium text-muted-foreground">
{{ t("grid.formatterCustomTemplateInput") }}
</span>
- <input
- v-model="formatterCustomTemplate"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="h-8 w-full rounded border bg-background px-2 font-mono text-xs outline-none focus:border-primary"
- placeholder="ID-${value}"
- />
+ <input v-model="formatterCustomTemplate" autocapitalize="off" autocorrect="off" spellcheck="false" class="h-8 w-full rounded border bg-background px-2 font-mono text-xs outline-none focus:border-primary" placeholder="ID-${value}" />
</label>
<div class="text-[11px] leading-4 text-muted-foreground">
{{ t("grid.formatterCustomTemplateHint") }}
@@ -7004,11 +6240,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ t("grid.formatterPreview") }}
</div>
<div class="max-h-40 overflow-auto rounded border bg-muted/20">
- <div
- v-for="row in formatterPreviewRows(col.actualColIdx)"
- :key="row.index"
- class="grid grid-cols-[2rem_minmax(0,1fr)_minmax(0,1fr)] gap-2 border-b px-2 py-1.5 text-[11px] last:border-b-0"
- >
+ <div v-for="row in formatterPreviewRows(col.actualColIdx)" :key="row.index" class="grid grid-cols-[2rem_minmax(0,1fr)_minmax(0,1fr)] gap-2 border-b px-2 py-1.5 text-[11px] last:border-b-0">
<span class="text-muted-foreground">{{ row.index }}</span>
<span class="truncate font-mono text-muted-foreground">{{ row.raw }}</span>
<span class="truncate font-mono">{{ row.formatted }}</span>
@@ -7018,40 +6250,21 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<div class="flex items-center justify-between gap-2 border-t bg-muted/30 px-3 py-2">
- <Button
- variant="ghost"
- size="sm"
- class="h-7 px-2 text-xs"
- :disabled="!columnHasFormatter(col.actualColIdx)"
- @click="clearColumnFormatter(col.actualColIdx)"
- >
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="!columnHasFormatter(col.actualColIdx)" @click="clearColumnFormatter(col.actualColIdx)">
{{ t("grid.clearFormatter") }}
</Button>
<div class="flex items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- class="h-7 px-2 text-xs"
- @click="closeColumnFormatter"
- >
+ <Button variant="outline" size="sm" class="h-7 px-2 text-xs" @click="closeColumnFormatter">
{{ t("dangerDialog.cancel") }}
</Button>
- <Button
- size="sm"
- class="h-7 px-2 text-xs"
- :disabled="!formatterDraftIsSavable()"
- @click="saveColumnFormatter(col.actualColIdx)"
- >
+ <Button size="sm" class="h-7 px-2 text-xs" :disabled="!formatterDraftIsSavable()" @click="saveColumnFormatter(col.actualColIdx)">
{{ t("grid.saveFormatter") }}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
- <Popover
- :open="localFilterOpenColumn === col.actualColIdx"
- @update:open="(value: boolean) => handleLocalFilterOpenChange(value, col.actualColIdx)"
- >
+ <Popover :open="localFilterOpenColumn === col.actualColIdx" @update:open="(value: boolean) => handleLocalFilterOpenChange(value, col.actualColIdx)">
<PopoverAnchor v-if="compactColumnHeaderActions" as-child>
<span class="pointer-events-none absolute right-3 top-1/2 h-px w-px -translate-y-1/2" />
</PopoverAnchor>
@@ -7066,108 +6279,50 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Filter class="h-3.5 w-3.5" />
</button>
</PopoverTrigger>
- <PopoverContent
- align="start"
- side="bottom"
- class="w-[300px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="start" side="bottom" class="w-[300px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-2 py-1.5 text-center text-xs font-semibold">
{{ t("grid.localFilterFor", { column: col.name }) }}
</div>
<div class="flex items-center gap-1.5 border-b px-2 py-1.5">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <input
- v-model="localFilterSearch"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="h-7 min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground"
- :placeholder="t('grid.searchValues')"
- />
+ <input v-model="localFilterSearch" autocapitalize="off" autocorrect="off" spellcheck="false" class="h-7 min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground" :placeholder="t('grid.searchValues')" />
</div>
- <div
- class="grid grid-cols-[1.75rem_minmax(0,1fr)_3.5rem] border-b bg-muted/40 px-2 py-1 text-xs font-medium text-muted-foreground"
- >
- <button
- type="button"
- class="flex h-4 w-4 items-center justify-center rounded border"
- :class="
- localFilterAllVisibleSelected
- ? 'border-blue-600 bg-blue-600 text-white'
- : 'border-border bg-background text-foreground/70'
- "
- @click="toggleAllLocalFilterOptions"
- >
+ <div class="grid grid-cols-[1.75rem_minmax(0,1fr)_3.5rem] border-b bg-muted/40 px-2 py-1 text-xs font-medium text-muted-foreground">
+ <button type="button" class="flex h-4 w-4 items-center justify-center rounded border" :class="localFilterAllVisibleSelected ? 'border-blue-600 bg-blue-600 text-white' : 'border-border bg-background text-foreground/70'" @click="toggleAllLocalFilterOptions">
<Check v-if="localFilterAllVisibleSelected" class="h-3 w-3 stroke-[3]" />
</button>
<span>{{ t("grid.value") }}</span>
<span class="text-right">{{ t("grid.count") }}</span>
</div>
<div class="max-h-72 overflow-auto py-0.5">
- <button
- v-for="option in localFilterOptions"
- :key="option.key"
- type="button"
- class="grid w-full grid-cols-[1.75rem_minmax(0,1fr)_3.5rem] items-center px-2 py-1 text-left text-xs hover:bg-accent"
- @click="toggleLocalFilterValue(option.key)"
- >
- <span
- class="flex h-4 w-4 items-center justify-center rounded border"
- :class="
- localFilterDraft?.values.has(option.key)
- ? 'border-blue-600 bg-blue-600 text-white'
- : 'border-border bg-background text-foreground/70'
- "
- >
+ <button v-for="option in localFilterOptions" :key="option.key" type="button" class="grid w-full grid-cols-[1.75rem_minmax(0,1fr)_3.5rem] items-center px-2 py-1 text-left text-xs hover:bg-accent" @click="toggleLocalFilterValue(option.key)">
+ <span class="flex h-4 w-4 items-center justify-center rounded border" :class="localFilterDraft?.values.has(option.key) ? 'border-blue-600 bg-blue-600 text-white' : 'border-border bg-background text-foreground/70'">
<Check v-if="localFilterDraft?.values.has(option.key)" class="h-3 w-3 stroke-[3]" />
</span>
- <span
- class="truncate font-mono"
- :class="{ 'italic text-muted-foreground': option.value === null }"
- >
+ <span class="truncate font-mono" :class="{ 'italic text-muted-foreground': option.value === null }">
{{ option.label }}
</span>
- <span class="text-right tabular-nums text-muted-foreground text-xs">{{
- option.count
- }}</span>
+ <span class="text-right tabular-nums text-muted-foreground text-xs">{{ option.count }}</span>
</button>
- <div
- v-if="localFilterAllOptions.length > localFilterOptions.length"
- class="px-2 py-0.5 text-center text-[10px] text-muted-foreground"
- >
+ <div v-if="localFilterAllOptions.length > localFilterOptions.length" class="px-2 py-0.5 text-center text-[10px] text-muted-foreground">
{{
t("grid.moreValues", {
count: localFilterAllOptions.length - localFilterOptions.length,
})
}}
</div>
- <button
- v-if="canApplyTypedLocalFilterValue"
- type="button"
- class="grid w-full grid-cols-[1.75rem_minmax(0,1fr)] items-center px-2 py-1 text-left text-xs text-primary hover:bg-accent"
- @click="applyTypedLocalFilterValue"
- >
+ <button v-if="canApplyTypedLocalFilterValue" type="button" class="grid w-full grid-cols-[1.75rem_minmax(0,1fr)] items-center px-2 py-1 text-left text-xs text-primary hover:bg-accent" @click="applyTypedLocalFilterValue">
<Search class="h-3.5 w-3.5" />
<span class="truncate font-mono">
{{ t("grid.filterTypedValue", { value: localFilterTypedValue }) }}
</span>
</button>
- <div
- v-if="localFilterOptions.length === 0 && !canApplyTypedLocalFilterValue"
- class="px-2 py-6 text-center text-xs text-muted-foreground"
- >
+ <div v-if="localFilterOptions.length === 0 && !canApplyTypedLocalFilterValue" class="px-2 py-6 text-center text-xs text-muted-foreground">
{{ t("grid.noSearchResults") }}
</div>
</div>
<div class="flex items-center justify-between gap-2 border-t bg-muted/40 px-2 py-1.5">
- <Button
- variant="ghost"
- size="sm"
- class="h-7 px-2 text-xs"
- @click="clearLocalFilter(col.actualColIdx)"
- >
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="clearLocalFilter(col.actualColIdx)">
{{ t("grid.clearFilter") }}
</Button>
<div class="flex items-center gap-2">
@@ -7182,31 +6337,20 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</PopoverContent>
</Popover>
</span>
- <div
- class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30"
- @mousedown.stop="onResizeStart(col.visibleColIdx, $event)"
- @dblclick.stop="autoFitColumn(col.visibleColIdx)"
- />
+ <div class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30" @mousedown.stop="onResizeStart(col.visibleColIdx, $event)" @dblclick.stop="autoFitColumn(col.visibleColIdx)" />
</div>
<template #content>
<div class="grid min-w-56 grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-1 px-3 py-2">
<span class="text-background/70">{{ t("grid.columnName") }}</span>
<span class="flex min-w-0 items-center gap-2">
<span class="min-w-0 flex-1 truncate font-mono">{{ col.name }}</span>
- <button
- type="button"
- class="flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-background/10"
- :title="t('grid.copyColumnName')"
- @click.stop="copyText(col.name)"
- >
+ <button type="button" class="flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-background/10" :title="t('grid.copyColumnName')" @click.stop="copyText(col.name)">
<Copy class="h-3 w-3" />
</button>
</span>
<template v-if="columnTypeMap.get(col.name)">
<span class="text-background/70">{{ t("grid.columnType") }}</span>
- <span :class="typeColorClass(columnTypeMap.get(col.name)!)">{{
- columnTypeMap.get(col.name)
- }}</span>
+ <span :class="typeColorClass(columnTypeMap.get(col.name)!)">{{ columnTypeMap.get(col.name) }}</span>
</template>
<template v-if="columnCommentMap.get(col.name)">
<span class="text-background/70">{{ t("grid.columnComment") }}</span>
@@ -7216,30 +6360,16 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</template>
</LightTooltip>
<div class="shrink-0" :style="{ width: `${horizontalColumnWindow.afterWidth}px` }" />
- <div
- v-if="gridScrollbarGutter > 0"
- class="shrink-0 border-l border-border"
- :style="{ width: 'var(--grid-scrollbar-gutter)' }"
- />
+ <div v-if="gridScrollbarGutter > 0" class="shrink-0 border-l border-border" :style="{ width: 'var(--grid-scrollbar-gutter)' }" />
</div>
</div>
<div v-if="!hasVisibleRows" class="relative min-h-0 flex-1">
- <div
- class="data-grid-scroller h-full overflow-x-auto overflow-y-hidden overscroll-none"
- :class="{ 'is-scrolling': isScrolling }"
- @scroll="onScrollerScroll"
- >
+ <div class="data-grid-scroller h-full overflow-x-auto overflow-y-hidden overscroll-none" :class="{ 'is-scrolling': isScrolling }" @scroll="onScrollerScroll">
<div class="h-full min-h-[220px]" :style="{ width: 'max(100%, var(--total-w))' }" />
</div>
- <div
- class="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 px-6 text-center text-muted-foreground"
- >
- <component
- :is="hasActiveFilter ? SearchX : Inbox"
- class="h-8 w-8 text-muted-foreground/50"
- aria-hidden="true"
- />
+ <div class="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 px-6 text-center text-muted-foreground">
+ <component :is="hasActiveFilter ? SearchX : Inbox" class="h-8 w-8 text-muted-foreground/50" aria-hidden="true" />
<div class="space-y-1">
<div class="text-sm font-medium text-foreground">{{ emptyTitle }}</div>
<div class="text-xs">{{ emptyDescription }}</div>
@@ -7247,14 +6377,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
</div>
- <div
- v-else-if="useCanvasGridRows"
- ref="scrollerRef"
- class="data-grid-scroller canvas-grid-scroller flex-1 overflow-auto overscroll-none bg-background"
- :class="{ 'is-scrolling': isScrolling }"
- @scroll="onCanvasScroll"
- @wheel="onCanvasWheel"
- >
+ <div v-else-if="useCanvasGridRows" ref="scrollerRef" class="data-grid-scroller canvas-grid-scroller flex-1 overflow-auto overscroll-none bg-background" :class="{ 'is-scrolling': isScrolling }" @scroll="onCanvasScroll" @wheel="onCanvasWheel">
<div class="relative" :style="{ width: `${totalWidth}px`, height: `${canvasContentHeight}px` }">
<canvas
ref="canvasRef"
@@ -7275,21 +6398,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
marginTop: `-${canvasViewportHeight}px`,
}"
>
- <div
- v-if="canvasEditingCell"
- class="absolute pointer-events-auto z-20"
- :class="{ 'tabular-nums': canvasEditingCellIsNumeric }"
- :style="canvasEditingCellStyle"
- @mousedown.stop
- @click.stop
- >
- <TemporalCellEditor
- v-if="temporalEditorKindForColumn(canvasEditingCell.actualColIdx)"
- v-model="editValue"
- :kind="temporalEditorKindForColumn(canvasEditingCell.actualColIdx)!"
- @cancel="cancelEdit"
- @commit="commitGridEdit"
- />
+ <div v-if="canvasEditingCell" class="absolute pointer-events-auto z-20" :class="{ 'tabular-nums': canvasEditingCellIsNumeric }" :style="canvasEditingCellStyle" @mousedown.stop @click.stop>
+ <TemporalCellEditor v-if="temporalEditorKindForColumn(canvasEditingCell.actualColIdx)" v-model="editValue" :kind="temporalEditorKindForColumn(canvasEditingCell.actualColIdx)!" @cancel="cancelEdit" @commit="commitGridEdit" />
<input
v-else
v-model="editValue"
@@ -7303,49 +6413,19 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@paste.stop
/>
</div>
- <div
- v-if="canvasDetailButtonCell"
- class="absolute pointer-events-auto z-20 flex items-center gap-1"
- :style="canvasDetailButtonStyle"
- @mouseenter="keepCanvasDetailHover"
- @mouseleave="clearCanvasDetailHover"
- >
+ <div v-if="canvasDetailButtonCell" class="absolute pointer-events-auto z-20 flex items-center gap-1" :style="canvasDetailButtonStyle" @mouseenter="keepCanvasDetailHover" @mouseleave="clearCanvasDetailHover">
<DropdownMenu
v-if="canvasDetailButtonCell.canQuickDownload"
- :open="
- quickDownloadMenuOpenFor(canvasDetailButtonCell.rowIndex, canvasDetailButtonCell.actualColIdx)
- "
- @update:open="
- (value: boolean) =>
- handleQuickDownloadMenuOpenChange(
- value,
- canvasDetailButtonCell!.rowIndex,
- canvasDetailButtonCell!.actualColIdx,
- )
- "
+ :open="quickDownloadMenuOpenFor(canvasDetailButtonCell.rowIndex, canvasDetailButtonCell.actualColIdx)"
+ @update:open="(value: boolean) => handleQuickDownloadMenuOpenChange(value, canvasDetailButtonCell!.rowIndex, canvasDetailButtonCell!.actualColIdx)"
>
<DropdownMenuTrigger as-child>
- <button
- class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground"
- :title="t('grid.downloadBinaryValue')"
- @mousedown.stop
- @click.stop
- >
+ <button class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground" :title="t('grid.downloadBinaryValue')" @mousedown.stop @click.stop>
<Download class="h-3 w-3" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-44">
- <DropdownMenuItem
- v-for="mode in BINARY_CELL_DOWNLOAD_MODES"
- :key="mode"
- @click="
- downloadCellBinaryValue(
- canvasDetailButtonCell.rowIndex,
- canvasDetailButtonCell.actualColIdx,
- mode,
- )
- "
- >
+ <DropdownMenuItem v-for="mode in BINARY_CELL_DOWNLOAD_MODES" :key="mode" @click="downloadCellBinaryValue(canvasDetailButtonCell.rowIndex, canvasDetailButtonCell.actualColIdx, mode)">
{{ t(`grid.binaryDownload.${mode}`) }}
</DropdownMenuItem>
</DropdownMenuContent>
@@ -7354,13 +6434,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground"
:title="t('grid.cellDetails')"
@mousedown.stop
- @click.stop="
- showCellDetailsForVisibleCell(
- canvasDetailButtonCell.rowIndex,
- canvasDetailButtonCell.visibleColIdx,
- canvasDetailButtonCell.actualColIdx,
- )
- "
+ @click.stop="showCellDetailsForVisibleCell(canvasDetailButtonCell.rowIndex, canvasDetailButtonCell.visibleColIdx, canvasDetailButtonCell.actualColIdx)"
>
<Info class="h-3 w-3" />
</button>
@@ -7370,29 +6444,14 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<!-- Virtual scrolled rows -->
- <RecycleScroller
- v-else-if="hasVisibleRows"
- ref="scrollerRef"
- class="data-grid-scroller flex-1 overflow-x-auto overscroll-none"
- :class="{ 'is-scrolling': isScrolling }"
- :items="displayItems"
- :item-size="26"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- @scroll="onScrollerScroll"
- >
+ <RecycleScroller v-else-if="hasVisibleRows" ref="scrollerRef" class="data-grid-scroller flex-1 overflow-x-auto overscroll-none" :class="{ 'is-scrolling': isScrolling }" :items="displayItems" :item-size="26" :buffer="600" :skip-hover="true" key-field="id" @scroll="onScrollerScroll">
<template #default="{ item }">
<div
class="flex text-xs border-b border-border"
:class="{
'bg-destructive/5 opacity-70': item.isDeleted,
'bg-primary/5': item.isNew && !isRowActive(item.displayIndex),
- 'bg-muted/30':
- !item.isNew &&
- !item.isDeleted &&
- !isRowActive(item.displayIndex) &&
- item.displayIndex % 2 === 1,
+ 'bg-muted/30': !item.isNew && !item.isDeleted && !isRowActive(item.displayIndex) && item.displayIndex % 2 === 1,
'active-row': isRowActive(item.displayIndex) && !item.isDeleted,
}"
:style="{ height: '26px', width: 'var(--total-w)' }"
@@ -7403,11 +6462,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
:class="[
rowNumberStatusClass(item),
{
- 'text-primary font-semibold !bg-primary/25':
- isRowSelected(item.id) &&
- item.status !== 'new' &&
- item.status !== 'edited' &&
- item.status !== 'deleted',
+ 'text-primary font-semibold !bg-primary/25': isRowSelected(item.id) && item.status !== 'new' && item.status !== 'edited' && item.status !== 'deleted',
},
]"
:style="{ width: 'var(--row-num-w)' }"
@@ -7426,26 +6481,12 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
:class="{
'text-muted-foreground italic': isNull(item.data[col.actualColIdx]),
'bg-yellow-500/10 cell-dirty': item.isDirtyCol[col.actualColIdx],
- 'cell-selected':
- cellIsSelected(item.displayIndex, col.visibleColIdx) && !item.isDirtyCol[col.actualColIdx],
- 'cell-selected-dirty':
- cellIsSelected(item.displayIndex, col.visibleColIdx) && item.isDirtyCol[col.actualColIdx],
- 'row-cell-selected':
- rowCellsUseSelectionVisual(item.id) &&
- !cellIsSelected(item.displayIndex, col.visibleColIdx) &&
- !item.isDirtyCol[col.actualColIdx],
- 'row-cell-selected-dirty':
- rowCellsUseSelectionVisual(item.id) &&
- !cellIsSelected(item.displayIndex, col.visibleColIdx) &&
- item.isDirtyCol[col.actualColIdx],
- 'bg-yellow-200/60 dark:bg-yellow-500/20': cellIsSearchMatch(
- item.displayIndex,
- col.actualColIdx,
- ),
- 'ring-2 ring-inset ring-yellow-500 bg-yellow-300/60 dark:bg-yellow-500/40': cellIsCurrentMatch(
- item.displayIndex,
- col.actualColIdx,
- ),
+ 'cell-selected': cellIsSelected(item.displayIndex, col.visibleColIdx) && !item.isDirtyCol[col.actualColIdx],
+ 'cell-selected-dirty': cellIsSelected(item.displayIndex, col.visibleColIdx) && item.isDirtyCol[col.actualColIdx],
+ 'row-cell-selected': rowCellsUseSelectionVisual(item.id) && !cellIsSelected(item.displayIndex, col.visibleColIdx) && !item.isDirtyCol[col.actualColIdx],
+ 'row-cell-selected-dirty': rowCellsUseSelectionVisual(item.id) && !cellIsSelected(item.displayIndex, col.visibleColIdx) && item.isDirtyCol[col.actualColIdx],
+ 'bg-yellow-200/60 dark:bg-yellow-500/20': cellIsSearchMatch(item.displayIndex, col.actualColIdx),
+ 'ring-2 ring-inset ring-yellow-500 bg-yellow-300/60 dark:bg-yellow-500/40': cellIsCurrentMatch(item.displayIndex, col.actualColIdx),
'tabular-nums': typeof item.data[col.actualColIdx] === 'number',
'cursor-text hover:bg-accent/50': !isScrolling && canEditCellItem(item, col.actualColIdx),
'line-through': item.isDeleted,
@@ -7458,13 +6499,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
@contextmenu="onCellContext(item.id, item.displayIndex, col.actualColIdx, col.visibleColIdx)"
>
<template v-if="editingCell?.rowId === item.id && editingCell?.col === col.actualColIdx">
- <TemporalCellEditor
- v-if="temporalEditorKindForColumn(col.actualColIdx)"
- v-model="editValue"
- :kind="temporalEditorKindForColumn(col.actualColIdx)!"
- @cancel="cancelEdit"
- @commit="commitGridEdit"
- />
+ <TemporalCellEditor v-if="temporalEditorKindForColumn(col.actualColIdx)" v-model="editValue" :kind="temporalEditorKindForColumn(col.actualColIdx)!" @cancel="cancelEdit" @commit="commitGridEdit" />
<input
v-else
v-model="editValue"
@@ -7480,34 +6515,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</template>
<template v-else>
{{ formatCellCached(item.data[col.actualColIdx], col.actualColIdx) }}
- <div
- v-if="cellDetailButtonVisible(item.displayIndex, col.actualColIdx)"
- class="absolute right-0.5 top-0.5 flex items-center gap-1"
- >
- <DropdownMenu
- v-if="canQuickDownloadCellValue(item.displayIndex, col.actualColIdx)"
- :open="quickDownloadMenuOpenFor(item.displayIndex, col.actualColIdx)"
- @update:open="
- (value: boolean) =>
- handleQuickDownloadMenuOpenChange(value, item.displayIndex, col.actualColIdx)
- "
- >
+ <div v-if="cellDetailButtonVisible(item.displayIndex, col.actualColIdx)" class="absolute right-0.5 top-0.5 flex items-center gap-1">
+ <DropdownMenu v-if="canQuickDownloadCellValue(item.displayIndex, col.actualColIdx)" :open="quickDownloadMenuOpenFor(item.displayIndex, col.actualColIdx)" @update:open="(value: boolean) => handleQuickDownloadMenuOpenChange(value, item.displayIndex, col.actualColIdx)">
<DropdownMenuTrigger as-child>
- <button
- class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground"
- :title="t('grid.downloadBinaryValue')"
- @mousedown.stop
- @click.stop
- >
+ <button class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground" :title="t('grid.downloadBinaryValue')" @mousedown.stop @click.stop>
<Download class="h-3 w-3" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-44">
- <DropdownMenuItem
- v-for="mode in BINARY_CELL_DOWNLOAD_MODES"
- :key="mode"
- @click="downloadCellBinaryValue(item.displayIndex, col.actualColIdx, mode)"
- >
+ <DropdownMenuItem v-for="mode in BINARY_CELL_DOWNLOAD_MODES" :key="mode" @click="downloadCellBinaryValue(item.displayIndex, col.actualColIdx, mode)">
{{ t(`grid.binaryDownload.${mode}`) }}
</DropdownMenuItem>
</DropdownMenuContent>
@@ -7516,9 +6532,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
class="flex h-5 w-5 items-center justify-center rounded bg-background/90 text-muted-foreground shadow-sm ring-1 ring-border hover:text-foreground"
:title="t('grid.cellDetails')"
@mousedown.stop
- @click.stop="
- showCellDetailsForVisibleCell(item.displayIndex, col.visibleColIdx, col.actualColIdx)
- "
+ @click.stop="showCellDetailsForVisibleCell(item.displayIndex, col.visibleColIdx, col.actualColIdx)"
>
<Info class="h-3 w-3" />
</button>
@@ -7530,9 +6544,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</template>
</RecycleScroller>
<div v-if="loading" class="absolute inset-0 z-20 bg-background/50 flex items-center justify-center">
- <div
- class="flex items-center gap-2 px-3 py-1.5 rounded-md bg-background border shadow-sm text-xs text-muted-foreground"
- >
+ <div class="flex items-center gap-2 px-3 py-1.5 rounded-md bg-background border shadow-sm text-xs text-muted-foreground">
<Loader2 class="w-3.5 h-3.5 animate-spin" />
<span>{{ (loadingElapsed / 1000).toFixed(1) }}s</span>
</div>
@@ -7540,39 +6552,16 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</template>
</div>
<!-- Table Info Drawer -->
- <div
- v-if="showTableInfo"
- class="relative col-start-2 row-start-1 border-l flex flex-col bg-background min-w-0"
- :class="[{ 'row-span-2': cellDetailPanelIsBottom }, { 'ddl-drawer-resizing': isResizingDdl }]"
- :style="ddlDrawerStyle"
- >
- <div
- class="absolute left-0 top-0 bottom-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize hover:bg-primary/30"
- @mousedown.prevent="onDdlResizeStart"
- />
+ <div v-if="showTableInfo" class="relative col-start-2 row-start-1 border-l flex flex-col bg-background min-w-0" :class="[{ 'row-span-2': cellDetailPanelIsBottom }, { 'ddl-drawer-resizing': isResizingDdl }]" :style="ddlDrawerStyle">
+ <div class="absolute left-0 top-0 bottom-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize hover:bg-primary/30" @mousedown.prevent="onDdlResizeStart" />
<div class="flex items-center gap-2 px-3 py-1.5 border-b shrink-0 bg-muted/20">
<TableProperties class="w-3.5 h-3.5 text-muted-foreground" />
<span class="text-xs font-medium flex-1 min-w-0 truncate">{{ tableMeta?.tableName }}</span>
- <Button
- v-if="activeTableInfoTab === 'ddl'"
- variant="ghost"
- size="sm"
- class="h-6 px-2 text-xs"
- :title="t('grid.copyDdl')"
- :aria-label="t('grid.copyDdl')"
- @click="copyDdl"
- >
+ <Button v-if="activeTableInfoTab === 'ddl'" variant="ghost" size="sm" class="h-6 px-2 text-xs" :title="t('grid.copyDdl')" :aria-label="t('grid.copyDdl')" @click="copyDdl">
<Copy class="w-3 h-3" />
<span>{{ t("grid.copyDdl") }}</span>
</Button>
- <Button
- v-if="activeTableInfoTab === 'ddl'"
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :class="{ 'bg-accent': ddlWrap }"
- @click="toggleDdlWrap"
- >
+ <Button v-if="activeTableInfoTab === 'ddl'" variant="ghost" size="icon" class="h-5 w-5" :class="{ 'bg-accent': ddlWrap }" @click="toggleDdlWrap">
<WrapText class="w-3 h-3" />
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="showTableInfo = false">
@@ -7596,27 +6585,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="px-2 py-1.5 border-b shrink-0 bg-background">
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
- <input
- v-model="searchQuery"
- :placeholder="t('grid.tableInfoSearch')"
- class="w-full h-7 pl-7 pr-6 text-xs bg-muted/50 rounded border border-border focus:outline-none focus:border-primary/50"
- @keydown.escape="searchQuery = ''"
- />
- <button
- v-if="searchQuery"
- class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- @click="searchQuery = ''"
- >
+ <input v-model="searchQuery" :placeholder="t('grid.tableInfoSearch')" class="w-full h-7 pl-7 pr-6 text-xs bg-muted/50 rounded border border-border focus:outline-none focus:border-primary/50" @keydown.escape="searchQuery = ''" />
+ <button v-if="searchQuery" class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground" @click="searchQuery = ''">
<X class="w-3 h-3" />
</button>
</div>
</div>
<div v-if="activeTableInfoTab === 'columns'" class="flex-1 min-h-0 overflow-auto">
- <div
- v-if="searchQuery && filteredColumns.length === 0"
- class="p-6 text-center text-xs text-muted-foreground"
- >
+ <div v-if="searchQuery && filteredColumns.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<table v-else class="w-full text-xs">
@@ -7660,10 +6637,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="indexesError" class="p-3 text-xs text-destructive">{{ indexesError }}</div>
- <div
- v-else-if="searchQuery && filteredIndexes.length === 0"
- class="p-6 text-center text-xs text-muted-foreground"
- >
+ <div v-else-if="searchQuery && filteredIndexes.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<div v-else-if="indexes.length === 0" class="p-6 text-center text-xs text-muted-foreground">
@@ -7674,12 +6648,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="font-medium truncate">{{ index.name }}</div>
<div class="mt-1 flex flex-wrap gap-1">
<span v-if="index.is_primary" class="rounded bg-amber-500/10 px-1.5 py-0.5 text-amber-600">PK</span>
- <span v-if="index.is_unique" class="rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-600"
- >UNIQUE</span
- >
- <span v-if="index.index_type" class="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">{{
- index.index_type
- }}</span>
+ <span v-if="index.is_unique" class="rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-600">UNIQUE</span>
+ <span v-if="index.index_type" class="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">{{ index.index_type }}</span>
</div>
<div class="mt-2 font-mono text-[11px] text-muted-foreground break-all">
{{ index.columns.join(", ") }}
@@ -7693,10 +6663,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="foreignKeysError" class="p-3 text-xs text-destructive">{{ foreignKeysError }}</div>
- <div
- v-else-if="searchQuery && filteredForeignKeys.length === 0"
- class="p-6 text-center text-xs text-muted-foreground"
- >
+ <div v-else-if="searchQuery && filteredForeignKeys.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<div v-else-if="foreignKeys.length === 0" class="p-6 text-center text-xs text-muted-foreground">
@@ -7705,9 +6672,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div v-else class="divide-y">
<div v-for="fk in filteredForeignKeys" :key="`${fk.name}:${fk.column}`" class="p-3 text-xs">
<div class="font-medium truncate">{{ fk.name }}</div>
- <div class="mt-1 font-mono text-[11px] text-muted-foreground break-all">
- {{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}
- </div>
+ <div class="mt-1 font-mono text-[11px] text-muted-foreground break-all">{{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}</div>
</div>
</div>
</div>
@@ -7717,10 +6682,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="triggersError" class="p-3 text-xs text-destructive">{{ triggersError }}</div>
- <div
- v-else-if="searchQuery && filteredTriggers.length === 0"
- class="p-6 text-center text-xs text-muted-foreground"
- >
+ <div v-else-if="searchQuery && filteredTriggers.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<div v-else-if="triggers.length === 0" class="p-6 text-center text-xs text-muted-foreground">
@@ -7734,75 +6696,29 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
</div>
- <pre
- v-else-if="activeTableInfoTab === 'ddl' && !ddlLoading"
- data-native-clipboard
- class="flex-1 min-w-0 text-xs font-mono p-3 overflow-auto ddl-code leading-5 select-text"
- :class="ddlWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"
- v-html="filteredDdlContent"
- ></pre>
+ <pre v-else-if="activeTableInfoTab === 'ddl' && !ddlLoading" data-native-clipboard class="flex-1 min-w-0 text-xs font-mono p-3 overflow-auto ddl-code leading-5 select-text" :class="ddlWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'" v-html="filteredDdlContent"></pre>
<div v-else class="flex-1 flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
</div>
<!-- Cell Detail Drawer -->
- <div
- v-if="showCellDetail && activeCellDetail"
- class="relative flex flex-col bg-background min-w-0"
- :class="[
- cellDetailPanelIsBottom ? 'col-start-1 row-start-2 border-t' : 'col-start-3 row-start-1 border-l',
- { 'detail-drawer-resizing': isResizingDetail },
- ]"
- :style="detailPanelStyle"
- >
- <div
- v-if="!cellDetailPanelIsBottom"
- class="absolute left-0 top-0 bottom-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize hover:bg-primary/30"
- @mousedown.prevent="onDetailResizeStart"
- />
- <div
- v-else
- class="absolute left-0 right-0 top-0 z-20 h-1.5 -translate-y-1/2 cursor-row-resize hover:bg-primary/30"
- @mousedown.prevent="onDetailResizeStart"
- />
+ <div v-if="showCellDetail && activeCellDetail" class="relative flex flex-col bg-background min-w-0" :class="[cellDetailPanelIsBottom ? 'col-start-1 row-start-2 border-t' : 'col-start-3 row-start-1 border-l', { 'detail-drawer-resizing': isResizingDetail }]" :style="detailPanelStyle">
+ <div v-if="!cellDetailPanelIsBottom" class="absolute left-0 top-0 bottom-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize hover:bg-primary/30" @mousedown.prevent="onDetailResizeStart" />
+ <div v-else class="absolute left-0 right-0 top-0 z-20 h-1.5 -translate-y-1/2 cursor-row-resize hover:bg-primary/30" @mousedown.prevent="onDetailResizeStart" />
<div class="h-9 flex items-center gap-2 px-3 border-b shrink-0 bg-muted/20">
<Info class="w-3.5 h-3.5 text-muted-foreground" />
<span class="text-xs font-medium flex-1 min-w-0 truncate">{{ t("grid.cellDetails") }}</span>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :title="cellDetailPanelIsBottom ? t('grid.cellDetailLayoutRight') : t('grid.cellDetailLayoutBottom')"
- @click="toggleCellDetailPanelLayout"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :title="cellDetailPanelIsBottom ? t('grid.cellDetailLayoutRight') : t('grid.cellDetailLayoutBottom')" @click="toggleCellDetailPanelLayout">
<PanelRight v-if="cellDetailPanelIsBottom" class="w-3 h-3" />
<PanelBottom v-else class="w-3 h-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :title="t('grid.openCellDetailsDialog')"
- @click="openActiveCellDetailDialog"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :title="t('grid.openCellDetailsDialog')" @click="openActiveCellDetailDialog">
<Maximize2 class="w-3 h-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :title="t('grid.openRowDetailsDialog')"
- @click="openActiveRowDetailDialog"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :title="t('grid.openRowDetailsDialog')" @click="openActiveRowDetailDialog">
<ListTree class="w-3 h-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :title="t('grid.openColumnDetailsDialog')"
- @click="openActiveColumnDetailDialog"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :title="t('grid.openColumnDetailsDialog')" @click="openActiveColumnDetailDialog">
<TableProperties class="w-3 h-3" />
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="closeCellDetails">
@@ -7812,16 +6728,9 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Tabs v-model="activeCellDetailTab" class="flex-1 min-h-0 gap-0">
<div class="shrink-0 border-b px-3 py-2">
- <TabsList
- class="grid h-7 w-full p-0.5"
- :class="activeCellDetailTabs.length > 1 ? 'grid-cols-2' : 'grid-cols-1'"
- >
+ <TabsList class="grid h-7 w-full p-0.5" :class="activeCellDetailTabs.length > 1 ? 'grid-cols-2' : 'grid-cols-1'">
<TabsTrigger value="details" class="h-6 text-xs">{{ t("grid.cellDetails") }}</TabsTrigger>
- <TabsTrigger
- v-if="activeCellDetailTabs.includes('valueEditor')"
- value="valueEditor"
- class="h-6 text-xs"
- >
+ <TabsTrigger v-if="activeCellDetailTabs.includes('valueEditor')" value="valueEditor" class="h-6 text-xs">
{{ t("grid.valueEditor") }}
</TabsTrigger>
</TabsList>
@@ -7829,10 +6738,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<TabsContent value="details" class="m-0 min-h-0 flex-1 flex flex-col">
<div data-native-clipboard class="flex-1 min-h-0 overflow-auto p-3 text-xs space-y-3">
- <div
- v-if="cellDetailPanelIsBottom"
- class="grid grid-cols-[minmax(180px,1.6fr)_repeat(4,minmax(74px,0.55fr))_minmax(160px,1fr)] gap-3 rounded border bg-muted/20 p-2"
- >
+ <div v-if="cellDetailPanelIsBottom" class="grid grid-cols-[minmax(180px,1.6fr)_repeat(4,minmax(74px,0.55fr))_minmax(160px,1fr)] gap-3 rounded border bg-muted/20 p-2">
<div class="min-w-0 space-y-1">
<div class="text-muted-foreground">{{ t("grid.columnName") }}</div>
<div class="truncate font-medium" :title="activeCellDetail.column">
@@ -7845,11 +6751,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<div class="min-w-0 space-y-1">
<div class="text-muted-foreground">{{ t("grid.columnType") }}</div>
- <div
- class="truncate"
- :class="activeCellDetail.type ? typeColorClass(activeCellDetail.type) : 'text-muted-foreground'"
- :title="activeCellDetail.type || '-'"
- >
+ <div class="truncate" :class="activeCellDetail.type ? typeColorClass(activeCellDetail.type) : 'text-muted-foreground'" :title="activeCellDetail.type || '-'">
{{ activeCellDetail.type || "-" }}
</div>
</div>
@@ -7880,11 +6782,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<div class="space-y-1">
<div class="text-muted-foreground">{{ t("grid.columnType") }}</div>
- <div
- :class="
- activeCellDetail.type ? typeColorClass(activeCellDetail.type) : 'text-muted-foreground'
- "
- >
+ <div :class="activeCellDetail.type ? typeColorClass(activeCellDetail.type) : 'text-muted-foreground'">
{{ activeCellDetail.type || "-" }}
</div>
</div>
@@ -7908,34 +6806,14 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="flex items-center justify-between gap-2">
<div class="text-muted-foreground">{{ t("grid.cellValue") }}</div>
<div v-if="!isEditingDetail" class="flex items-center gap-1">
- <Button
- v-if="activeCellDetail.formattedJson"
- :variant="sideDetailJsonView ? 'secondary' : 'ghost'"
- size="sm"
- class="h-6 gap-1 px-2 text-xs"
- :title="t('grid.formattedJson')"
- @click="sideDetailJsonView = !sideDetailJsonView"
- >
+ <Button v-if="activeCellDetail.formattedJson" :variant="sideDetailJsonView ? 'secondary' : 'ghost'" size="sm" class="h-6 gap-1 px-2 text-xs" :title="t('grid.formattedJson')" @click="sideDetailJsonView = !sideDetailJsonView">
<Code2 class="h-3 w-3" />
{{ t("grid.formattedJson") }}
</Button>
- <Button
- v-if="activeCellDetail.isEditable"
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('grid.editValue')"
- @click="startDetailEdit"
- >
+ <Button v-if="activeCellDetail.isEditable" variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.editValue')" @click="startDetailEdit">
<Pencil class="h-3 w-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('grid.copyValue')"
- @click="copyDetailCurrentValue"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.copyValue')" @click="copyDetailCurrentValue">
<Copy class="h-3 w-3" />
</Button>
<DropdownMenu v-if="canDownloadDetailBinaryValue(activeCellDetail)">
@@ -7945,77 +6823,33 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-44">
- <DropdownMenuItem
- v-for="mode in BINARY_CELL_DOWNLOAD_MODES"
- :key="mode"
- @click="downloadDetailBinaryValue(activeCellDetail, mode)"
- >
+ <DropdownMenuItem v-for="mode in BINARY_CELL_DOWNLOAD_MODES" :key="mode" @click="downloadDetailBinaryValue(activeCellDetail, mode)">
{{ t(`grid.binaryDownload.${mode}`) }}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<!-- Skip hex fallback from backend (unsupported geometry types like TIN/Triangle) -->
- <Popover
- v-if="
- isGeometryColumnType(activeCellDetail.type) &&
- activeCellDetail.value !== null &&
- !isEditingDetail &&
- !isHexGeometry(activeCellDetail.value as string)
- "
- v-model:open="sideGeometryPreviewOpen"
- >
+ <Popover v-if="isGeometryColumnType(activeCellDetail.type) && activeCellDetail.value !== null && !isEditingDetail && !isHexGeometry(activeCellDetail.value as string)" v-model:open="sideGeometryPreviewOpen">
<PopoverTrigger as-child>
<Button variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.geometryPreview')">
<Eye class="h-3 w-3" />
</Button>
</PopoverTrigger>
<PopoverContent class="w-auto p-1.5" align="end">
- <canvas
- v-show="sideGeometryPreviewOpen"
- ref="sideGeometryCanvas"
- width="400"
- height="280"
- class="block rounded"
- />
+ <canvas v-show="sideGeometryPreviewOpen" ref="sideGeometryCanvas" width="400" height="280" class="block rounded" />
</PopoverContent>
</Popover>
</div>
</div>
<div v-if="activeCellDetail.imagePreviewUrl && !isEditingDetail" class="space-y-1.5">
<div class="text-muted-foreground">{{ t("grid.imagePreview") }}</div>
- <a
- :href="activeCellDetail.imagePreviewUrl"
- role="button"
- class="block overflow-hidden rounded border bg-muted/20"
- @click.prevent="openImagePreview(activeCellDetail.imagePreviewUrl, activeCellDetail.column)"
- >
- <img
- :src="activeCellDetail.imagePreviewUrl"
- :alt="activeCellDetail.column"
- loading="lazy"
- decoding="async"
- referrerpolicy="no-referrer"
- class="max-h-72 w-full object-contain"
- />
+ <a :href="activeCellDetail.imagePreviewUrl" role="button" class="block overflow-hidden rounded border bg-muted/20" @click.prevent="openImagePreview(activeCellDetail.imagePreviewUrl, activeCellDetail.column)">
+ <img :src="activeCellDetail.imagePreviewUrl" :alt="activeCellDetail.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="max-h-72 w-full object-contain" />
</a>
</div>
<template v-if="isEditingDetail">
- <TemporalCellEditor
- v-if="detailTemporalEditorKind"
- v-model="detailEditValue"
- :kind="detailTemporalEditorKind"
- variant="inline"
- :commit-on-close="false"
- @cancel="cancelDetailEdit"
- @commit="commitDetailEdit"
- />
- <div
- v-else
- ref="detailsEditorContainer"
- data-cell-detail-editor-root
- class="w-full rounded border overflow-hidden"
- :class="cellDetailPanelIsBottom ? 'h-28' : 'h-40'"
- />
+ <TemporalCellEditor v-if="detailTemporalEditorKind" v-model="detailEditValue" :kind="detailTemporalEditorKind" variant="inline" :commit-on-close="false" @cancel="cancelDetailEdit" @commit="commitDetailEdit" />
+ <div v-else ref="detailsEditorContainer" data-cell-detail-editor-root class="w-full rounded border overflow-hidden" :class="cellDetailPanelIsBottom ? 'h-28' : 'h-40'" />
<div class="flex gap-1 mt-1">
<Button size="sm" class="h-6 text-xs" @click="commitDetailEdit">
{{ t("dangerDialog.confirm") }}
@@ -8025,21 +6859,10 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</Button>
</div>
</template>
- <pre
- v-else
- class="overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words cursor-pointer hover:border-primary/50"
- :class="{ 'cursor-text': activeCellDetail.isEditable }"
- @dblclick="startDetailEdit"
- >{{
- sideDetailJsonView && activeCellDetail.formattedJson
- ? activeCellDetail.formattedJson
- : activeCellDetail.rawValuePreview
- }}</pre
- >
- <div
- v-if="activeCellDetail.isValuePreviewTruncated && !sideDetailJsonView"
- class="text-[11px] text-muted-foreground"
- >
+ <pre v-else class="overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words cursor-pointer hover:border-primary/50" :class="{ 'cursor-text': activeCellDetail.isEditable }" @dblclick="startDetailEdit">{{
+ sideDetailJsonView && activeCellDetail.formattedJson ? activeCellDetail.formattedJson : activeCellDetail.rawValuePreview
+ }}</pre>
+ <div v-if="activeCellDetail.isValuePreviewTruncated && !sideDetailJsonView" class="text-[11px] text-muted-foreground">
{{
t("grid.largeValuePreviewHint", {
count: activeCellDetail.rawValuePreview.length,
@@ -8049,85 +6872,26 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
</div>
- <div
- class="border-t p-2 grid gap-1"
- :class="cellDetailPanelIsBottom ? 'grid-cols-[repeat(3,max-content)] justify-end' : 'grid-cols-1'"
- >
- <Button
- v-if="activeCellDetail.isEditable && activeCellDetail.value !== null"
- variant="ghost"
- size="sm"
- class="h-7 justify-start text-xs"
- @click="setDetailNull"
- >
- <X class="w-3 h-3 mr-2" /> {{ t("grid.setNull") }}
- </Button>
- <Button variant="ghost" size="sm" class="h-7 justify-start text-xs" @click="copyDetailColumnName">
- <Copy class="w-3 h-3 mr-2" /> {{ t("grid.copyColumnName") }}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-7 justify-start text-xs"
- :disabled="!canCopyPreparedDetailSqlCondition()"
- @click="copyDetailSqlCondition"
- >
- <Code2 class="w-3 h-3 mr-2" /> {{ t("grid.copySqlCondition") }}
- </Button>
+ <div class="border-t p-2 grid gap-1" :class="cellDetailPanelIsBottom ? 'grid-cols-[repeat(3,max-content)] justify-end' : 'grid-cols-1'">
+ <Button v-if="activeCellDetail.isEditable && activeCellDetail.value !== null" variant="ghost" size="sm" class="h-7 justify-start text-xs" @click="setDetailNull"> <X class="w-3 h-3 mr-2" /> {{ t("grid.setNull") }} </Button>
+ <Button variant="ghost" size="sm" class="h-7 justify-start text-xs" @click="copyDetailColumnName"> <Copy class="w-3 h-3 mr-2" /> {{ t("grid.copyColumnName") }} </Button>
+ <Button variant="ghost" size="sm" class="h-7 justify-start text-xs" :disabled="!canCopyPreparedDetailSqlCondition()" @click="copyDetailSqlCondition"> <Code2 class="w-3 h-3 mr-2" /> {{ t("grid.copySqlCondition") }} </Button>
</div>
</TabsContent>
- <TabsContent
- v-if="activeCellDetailTabs.includes('valueEditor')"
- value="valueEditor"
- class="m-0 min-h-0 flex-1 flex flex-col p-3 text-xs"
- >
+ <TabsContent v-if="activeCellDetailTabs.includes('valueEditor')" value="valueEditor" class="m-0 min-h-0 flex-1 flex flex-col p-3 text-xs">
<div class="flex min-h-0 flex-1 flex-col">
- <TemporalCellEditor
- v-if="detailTemporalEditorKind"
- v-model="detailEditValue"
- :kind="detailTemporalEditorKind"
- variant="inline"
- :commit-on-close="false"
- @cancel="cancelValueEditorEdit"
- @commit="commitValueEditorEdit"
- />
- <div
- v-else
- ref="valueEditorContainer"
- data-cell-detail-editor-root
- class="min-h-0 flex-1 w-full rounded border overflow-auto"
- />
+ <TemporalCellEditor v-if="detailTemporalEditorKind" v-model="detailEditValue" :kind="detailTemporalEditorKind" variant="inline" :commit-on-close="false" @cancel="cancelValueEditorEdit" @commit="commitValueEditorEdit" />
+ <div v-else ref="valueEditorContainer" data-cell-detail-editor-root class="min-h-0 flex-1 w-full rounded border overflow-auto" />
</div>
<div class="flex gap-1 mt-2 shrink-0">
- <Button
- v-if="activeValueEditorActions.includes('formatJson')"
- variant="outline"
- size="sm"
- class="h-6 text-xs"
- @mousedown.prevent
- @click="formatValueEditorJson"
- >
+ <Button v-if="activeValueEditorActions.includes('formatJson')" variant="outline" size="sm" class="h-6 text-xs" @mousedown.prevent @click="formatValueEditorJson">
{{ t("grid.formatJson") }}
</Button>
- <Button
- v-if="activeValueEditorActions.includes('setNull')"
- variant="outline"
- size="sm"
- class="h-6 text-xs"
- @mousedown.prevent
- @click="setValueEditorNull"
- >
+ <Button v-if="activeValueEditorActions.includes('setNull')" variant="outline" size="sm" class="h-6 text-xs" @mousedown.prevent @click="setValueEditorNull">
{{ t("grid.setNull") }}
</Button>
- <Button
- v-if="activeValueEditorActions.includes('restoreOriginal')"
- variant="outline"
- size="sm"
- class="h-6 text-xs"
- @mousedown.prevent
- @click="restoreDetailOriginalValue"
- >
+ <Button v-if="activeValueEditorActions.includes('restoreOriginal')" variant="outline" size="sm" class="h-6 text-xs" @mousedown.prevent @click="restoreDetailOriginalValue">
{{ t("grid.restoreOriginalValue") }}
</Button>
</div>
@@ -8142,37 +6906,21 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</div>
<!-- Error bar -->
- <div
- v-if="saveError"
- class="px-3 py-1.5 border-t bg-destructive/10 text-destructive text-xs shrink-0 flex items-center gap-2"
- >
+ <div v-if="saveError" class="px-3 py-1.5 border-t bg-destructive/10 text-destructive text-xs shrink-0 flex items-center gap-2">
<span class="flex-1">{{ saveError }}</span>
<button class="hover:underline" @click="saveError = ''">{{ t("grid.dismiss") }}</button>
</div>
<!-- Bottom status bar -->
- <div
- v-if="!isErrorResult"
- class="grid grid-cols-[minmax(0,1fr)_minmax(0,38%)_minmax(0,1fr)] items-center gap-2 px-3 py-1 border-t text-xs text-muted-foreground bg-muted/30 shrink-0"
- >
+ <div v-if="!isErrorResult" class="grid grid-cols-[minmax(0,1fr)_minmax(0,38%)_minmax(0,1fr)] items-center gap-2 px-3 py-1 border-t text-xs text-muted-foreground bg-muted/30 shrink-0">
<div class="flex min-w-0 items-center gap-2 overflow-hidden">
<span v-if="hasData" class="shrink-0">
{{ t("grid.totalRows", { count: result.rows.length }) }}
- <span
- v-if="typeof displayedTotalRowCount === 'number' && displayedTotalRowCount >= 0"
- class="text-muted-foreground/70"
- >{{ t("grid.totalRowCount", { count: displayedTotalRowCount }) }}</span
- >
+ <span v-if="typeof displayedTotalRowCount === 'number' && displayedTotalRowCount >= 0" class="text-muted-foreground/70">{{ t("grid.totalRowCount", { count: displayedTotalRowCount }) }}</span>
<span v-else-if="totalRowCountBusy" class="text-muted-foreground/70">
{{ t("grid.totalRowCountLoading") }}
</span>
- <button
- v-else-if="canCalculateTotalRowCount"
- type="button"
- class="text-muted-foreground/70 hover:text-foreground hover:underline underline-offset-2 disabled:pointer-events-none"
- :disabled="manualTotalRowCountLoading"
- @click="calculateTotalRowCount"
- >
+ <button v-else-if="canCalculateTotalRowCount" type="button" class="text-muted-foreground/70 hover:text-foreground hover:underline underline-offset-2 disabled:pointer-events-none" :disabled="manualTotalRowCountLoading" @click="calculateTotalRowCount">
{{ t("grid.calculateTotalRowsInline") }}
</button>
</span>
@@ -8192,10 +6940,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Tooltip v-if="sqlOneLiner">
<TooltipTrigger as-child>
- <span
- class="min-w-0 max-w-full justify-self-center truncate opacity-60 cursor-pointer hover:opacity-100"
- @click="copySql"
- >
+ <span class="min-w-0 max-w-full justify-self-center truncate opacity-60 cursor-pointer hover:opacity-100" @click="copySql">
{{ sqlOneLiner }}
</span>
</TooltipTrigger>
@@ -8232,13 +6977,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
/>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="outline"
- size="icon"
- class="h-6 w-6 shrink-0"
- :aria-label="t('grid.applyPageSize')"
- @click.stop="applyCustomPageSize"
- >
+ <Button variant="outline" size="icon" class="h-6 w-6 shrink-0" :aria-label="t('grid.applyPageSize')" @click.stop="applyCustomPageSize">
<Check class="h-3 w-3" />
</Button>
</TooltipTrigger>
@@ -8318,34 +7057,14 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="flex items-center justify-between gap-2">
<div class="text-muted-foreground">{{ t("grid.cellValue") }}</div>
<div class="flex items-center gap-1">
- <Button
- v-if="dialogCellDetail.formattedJson"
- :variant="cellDetailJsonView ? 'secondary' : 'ghost'"
- size="sm"
- class="h-6 gap-1 px-2 text-xs"
- :title="t('grid.formattedJson')"
- @click="cellDetailJsonView = !cellDetailJsonView"
- >
+ <Button v-if="dialogCellDetail.formattedJson" :variant="cellDetailJsonView ? 'secondary' : 'ghost'" size="sm" class="h-6 gap-1 px-2 text-xs" :title="t('grid.formattedJson')" @click="cellDetailJsonView = !cellDetailJsonView">
<Code2 class="h-3 w-3" />
{{ t("grid.formattedJson") }}
</Button>
- <Button
- v-if="dialogCellDetail.isEditable"
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('grid.editValue')"
- @click="openDialogCellInSidePanel"
- >
+ <Button v-if="dialogCellDetail.isEditable" variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.editValue')" @click="openDialogCellInSidePanel">
<Pencil class="h-3 w-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('grid.copyValue')"
- @click="copyDialogCellCurrentValue"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.copyValue')" @click="copyDialogCellCurrentValue">
<Copy class="h-3 w-3" />
</Button>
<DropdownMenu v-if="canDownloadDetailBinaryValue(dialogCellDetail)">
@@ -8355,70 +7074,31 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-44">
- <DropdownMenuItem
- v-for="mode in BINARY_CELL_DOWNLOAD_MODES"
- :key="mode"
- @click="downloadDetailBinaryValue(dialogCellDetail, mode)"
- >
+ <DropdownMenuItem v-for="mode in BINARY_CELL_DOWNLOAD_MODES" :key="mode" @click="downloadDetailBinaryValue(dialogCellDetail, mode)">
{{ t(`grid.binaryDownload.${mode}`) }}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<!-- Skip hex fallback from backend (unsupported geometry types like TIN/Triangle) -->
- <Popover
- v-if="
- isGeometryColumnType(dialogCellDetail.type) &&
- dialogCellDetail.value !== null &&
- !isHexGeometry(dialogCellDetail.value as string)
- "
- v-model:open="dialogGeometryPreviewOpen"
- >
+ <Popover v-if="isGeometryColumnType(dialogCellDetail.type) && dialogCellDetail.value !== null && !isHexGeometry(dialogCellDetail.value as string)" v-model:open="dialogGeometryPreviewOpen">
<PopoverTrigger as-child>
<Button variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.geometryPreview')">
<Eye class="h-3 w-3" />
</Button>
</PopoverTrigger>
<PopoverContent class="w-auto p-1.5" align="end">
- <canvas
- v-show="dialogGeometryPreviewOpen"
- ref="dialogGeometryCanvas"
- width="400"
- height="280"
- class="block rounded"
- />
+ <canvas v-show="dialogGeometryPreviewOpen" ref="dialogGeometryCanvas" width="400" height="280" class="block rounded" />
</PopoverContent>
</Popover>
</div>
</div>
- <a
- v-if="dialogCellDetail.imagePreviewUrl"
- :href="dialogCellDetail.imagePreviewUrl"
- role="button"
- class="block max-h-72 overflow-hidden rounded border bg-muted/20"
- @click.prevent="openImagePreview(dialogCellDetail.imagePreviewUrl, dialogCellDetail.column)"
- >
- <img
- :src="dialogCellDetail.imagePreviewUrl"
- :alt="dialogCellDetail.column"
- loading="lazy"
- decoding="async"
- referrerpolicy="no-referrer"
- class="max-h-72 w-full object-contain"
- />
+ <a v-if="dialogCellDetail.imagePreviewUrl" :href="dialogCellDetail.imagePreviewUrl" role="button" class="block max-h-72 overflow-hidden rounded border bg-muted/20" @click.prevent="openImagePreview(dialogCellDetail.imagePreviewUrl, dialogCellDetail.column)">
+ <img :src="dialogCellDetail.imagePreviewUrl" :alt="dialogCellDetail.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="max-h-72 w-full object-contain" />
</a>
- <pre
- class="max-h-[44vh] overflow-auto rounded border bg-muted/20 p-3 font-mono text-xs whitespace-pre-wrap break-words"
- :class="{ 'italic text-muted-foreground': dialogCellDetail.value === null }"
- >{{
- cellDetailJsonView && dialogCellDetail.formattedJson
- ? dialogCellDetail.formattedJson
- : dialogCellDetail.rawValuePreview
- }}</pre
- >
- <div
- v-if="dialogCellDetail.isValuePreviewTruncated && !cellDetailJsonView"
- class="text-[11px] text-muted-foreground"
- >
+ <pre class="max-h-[44vh] overflow-auto rounded border bg-muted/20 p-3 font-mono text-xs whitespace-pre-wrap break-words" :class="{ 'italic text-muted-foreground': dialogCellDetail.value === null }">{{
+ cellDetailJsonView && dialogCellDetail.formattedJson ? dialogCellDetail.formattedJson : dialogCellDetail.rawValuePreview
+ }}</pre>
+ <div v-if="dialogCellDetail.isValuePreviewTruncated && !cellDetailJsonView" class="text-[11px] text-muted-foreground">
{{ t("grid.largeValuePreviewHint", { count: dialogCellDetail.rawValuePreview.length }) }}
</div>
</div>
@@ -8426,9 +7106,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<DialogFooter class="shrink-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div class="flex flex-wrap gap-2"></div>
- <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyDialogCellColumnName">
- <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnName") }}
- </Button>
+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyDialogCellColumnName"> <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnName") }} </Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -8445,14 +7123,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
<span class="whitespace-nowrap">{{ t("grid.columnsCount", { count: rowDetail.fields.length }) }}</span>
<div class="relative ml-auto w-56 max-w-full">
- <Search
- class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
- />
- <Input
- v-model="rowDetailSearch"
- :placeholder="t('grid.detailSearchPlaceholder')"
- class="h-7 pl-7 text-xs"
- />
+ <Search class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="rowDetailSearch" :placeholder="t('grid.detailSearchPlaceholder')" class="h-7 pl-7 text-xs" />
</div>
</div>
@@ -8467,18 +7139,11 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</tr>
</thead>
<tbody>
- <tr
- v-for="(field, fieldIndex) in filteredRowDetailFields"
- :key="`${field.colIndex}:${field.column}`"
- class="border-b align-top last:border-b-0"
- >
+ <tr v-for="(field, fieldIndex) in filteredRowDetailFields" :key="`${field.colIndex}:${field.column}`" class="border-b align-top last:border-b-0">
<td class="px-3 py-2 text-muted-foreground tabular-nums">{{ fieldIndex + 1 }}</td>
<td class="px-3 py-2">
<div class="font-medium break-words">{{ field.column }}</div>
- <div
- :class="field.type ? typeColorClass(field.type) : 'text-muted-foreground'"
- class="mt-1 text-[11px]"
- >
+ <div :class="field.type ? typeColorClass(field.type) : 'text-muted-foreground'" class="mt-1 text-[11px]">
{{ field.type || "-" }}
</div>
<div v-if="field.comment" class="mt-1 text-[11px] text-muted-foreground whitespace-pre-wrap">
@@ -8490,68 +7155,35 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
{{ field.value === null ? t("grid.nullValue") : t("grid.valueLength") }}:
{{ field.value === null ? "true" : field.length }}
</div>
- <a
- v-if="field.imagePreviewUrl"
- :href="field.imagePreviewUrl"
- role="button"
- class="mb-2 block max-h-48 overflow-hidden rounded border bg-muted/20"
- @click.prevent="openImagePreview(field.imagePreviewUrl, field.column)"
- >
- <img
- :src="field.imagePreviewUrl"
- :alt="field.column"
- loading="lazy"
- decoding="async"
- referrerpolicy="no-referrer"
- class="max-h-48 w-full object-contain"
- />
+ <a v-if="field.imagePreviewUrl" :href="field.imagePreviewUrl" role="button" class="mb-2 block max-h-48 overflow-hidden rounded border bg-muted/20" @click.prevent="openImagePreview(field.imagePreviewUrl, field.column)">
+ <img :src="field.imagePreviewUrl" :alt="field.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="max-h-48 w-full object-contain" />
</a>
- <pre
- class="max-h-44 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words"
- :class="{ 'italic text-muted-foreground': field.value === null }"
- >{{ field.rawValuePreview }}</pre
- >
+ <pre class="max-h-44 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words" :class="{ 'italic text-muted-foreground': field.value === null }">{{ field.rawValuePreview }}</pre>
<div v-if="field.isValuePreviewTruncated" class="mt-1 text-[11px] text-muted-foreground">
{{ t("grid.largeValuePreviewHint", { count: field.rawValuePreview.length }) }}
</div>
<div v-if="field.formattedJson" class="mt-2 space-y-1">
<div class="text-muted-foreground">{{ t("grid.formattedJson") }}</div>
- <pre
- class="max-h-44 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words"
- >{{ field.formattedJson }}</pre
- >
+ <pre class="max-h-44 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words">{{ field.formattedJson }}</pre>
</div>
</td>
<td class="px-2 py-2">
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('grid.copyValue')"
- @click="copyRowDetailFieldValue(field)"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.copyValue')" @click="copyRowDetailFieldValue(field)">
<Copy class="h-3 w-3" />
</Button>
</td>
</tr>
</tbody>
</table>
- <div
- v-if="rowDetailSearch && !filteredRowDetailFields.length"
- class="px-3 py-6 text-center text-xs text-muted-foreground"
- >
+ <div v-if="rowDetailSearch && !filteredRowDetailFields.length" class="px-3 py-6 text-center text-xs text-muted-foreground">
{{ t("grid.detailSearchNoMatch") }}
</div>
</div>
<DialogFooter class="shrink-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div class="flex flex-wrap gap-2">
- <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyRowDetailJson">
- <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyRow") }}
- </Button>
- <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyRowDetailTsv">
- <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyRowTsv") }}
- </Button>
+ <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyRowDetailJson"> <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyRow") }} </Button>
+ <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyRowDetailTsv"> <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyRowTsv") }} </Button>
</div>
</DialogFooter>
</DialogContent>
@@ -8592,14 +7224,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<div class="flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
<span class="whitespace-nowrap">{{ t("grid.rowCount") }}: {{ columnDetail.fields.length }}</span>
<div class="relative ml-auto w-56 max-w-full">
- <Search
- class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
- />
- <Input
- v-model="columnDetailSearch"
- :placeholder="t('grid.detailSearchPlaceholder')"
- class="h-7 pl-7 text-xs"
- />
+ <Search class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="columnDetailSearch" :placeholder="t('grid.detailSearchPlaceholder')" class="h-7 pl-7 text-xs" />
</div>
</div>
@@ -8613,83 +7239,44 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
</tr>
</thead>
<tbody>
- <tr
- v-for="field in filteredColumnDetailFields"
- :key="`${field.rowId}:${field.colIndex}`"
- class="border-b align-top last:border-b-0"
- >
+ <tr v-for="field in filteredColumnDetailFields" :key="`${field.rowId}:${field.colIndex}`" class="border-b align-top last:border-b-0">
<td class="px-3 py-2 tabular-nums">{{ field.rowNumber }}</td>
<td class="w-full max-w-0 px-3 py-2">
<div class="mb-1 text-[11px] text-muted-foreground">
{{ field.value === null ? t("grid.nullValue") : t("grid.valueLength") }}:
{{ field.value === null ? "true" : field.length }}
</div>
- <a
- v-if="field.imagePreviewUrl"
- :href="field.imagePreviewUrl"
- role="button"
- class="mb-2 block max-h-40 overflow-hidden rounded border bg-muted/20"
- @click.prevent="openImagePreview(field.imagePreviewUrl, field.column)"
- >
- <img
- :src="field.imagePreviewUrl"
- :alt="field.column"
- loading="lazy"
- decoding="async"
- referrerpolicy="no-referrer"
- class="max-h-40 w-full object-contain"
- />
+ <a v-if="field.imagePreviewUrl" :href="field.imagePreviewUrl" role="button" class="mb-2 block max-h-40 overflow-hidden rounded border bg-muted/20" @click.prevent="openImagePreview(field.imagePreviewUrl, field.column)">
+ <img :src="field.imagePreviewUrl" :alt="field.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="max-h-40 w-full object-contain" />
</a>
- <pre
- class="max-h-36 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words"
- :class="{ 'italic text-muted-foreground': field.value === null }"
- >{{ field.rawValuePreview }}</pre
- >
+ <pre class="max-h-36 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words" :class="{ 'italic text-muted-foreground': field.value === null }">{{ field.rawValuePreview }}</pre>
<div v-if="field.isValuePreviewTruncated" class="mt-1 text-[11px] text-muted-foreground">
{{ t("grid.largeValuePreviewHint", { count: field.rawValuePreview.length }) }}
</div>
<div v-if="field.formattedJson" class="mt-2 space-y-1">
<div class="text-muted-foreground">{{ t("grid.formattedJson") }}</div>
- <pre
- class="max-h-36 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words"
- >{{ field.formattedJson }}</pre
- >
+ <pre class="max-h-36 overflow-auto rounded border bg-muted/20 p-2 font-mono text-xs whitespace-pre-wrap break-words">{{ field.formattedJson }}</pre>
</div>
</td>
<td class="px-2 py-2">
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('grid.copyValue')"
- @click="copyColumnDetailFieldValue(field)"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6" :title="t('grid.copyValue')" @click="copyColumnDetailFieldValue(field)">
<Copy class="h-3 w-3" />
</Button>
</td>
</tr>
</tbody>
</table>
- <div
- v-if="columnDetailSearch && !filteredColumnDetailFields.length"
- class="px-3 py-6 text-center text-xs text-muted-foreground"
- >
+ <div v-if="columnDetailSearch && !filteredColumnDetailFields.length" class="px-3 py-6 text-center text-xs text-muted-foreground">
{{ t("grid.detailSearchNoMatch") }}
</div>
</div>
<DialogFooter class="shrink-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div class="flex flex-wrap gap-2">
- <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyColumnDetailJson">
- <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnValues") }}
- </Button>
- <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyColumnDetailTsv">
- <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnTsv") }}
- </Button>
+ <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyColumnDetailJson"> <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnValues") }} </Button>
+ <Button variant="outline" size="sm" class="h-7 text-xs" @click="copyColumnDetailTsv"> <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnTsv") }} </Button>
</div>
- <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyColumnDetailColumnName">
- <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnName") }}
- </Button>
+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyColumnDetailColumnName"> <Copy class="mr-1.5 h-3 w-3" /> {{ t("grid.copyColumnName") }} </Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -8703,11 +7290,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<p class="text-sm text-muted-foreground">
{{ t("grid.bulkEditDescription", { count: selectedCellCount }) }}
</p>
- <Input
- v-model="bulkEditValue"
- :placeholder="t('grid.bulkEditValuePlaceholder')"
- @keydown.enter.prevent="applyBulkEditValue"
- />
+ <Input v-model="bulkEditValue" :placeholder="t('grid.bulkEditValuePlaceholder')" @keydown.enter.prevent="applyBulkEditValue" />
</div>
<DialogFooter>
<Button variant="outline" @click="bulkEditDialogOpen = false">{{ t("dangerDialog.cancel") }}</Button>
@@ -8718,26 +7301,13 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<DangerConfirmDialog
v-model:open="showDeleteRowConfirm"
- :message="
- pendingDeleteRowIds.length > 1
- ? t('dangerDialog.deleteRowsMessage', { count: pendingDeleteRowIds.length })
- : t('dangerDialog.deleteRowMessage')
- "
+ :message="pendingDeleteRowIds.length > 1 ? t('dangerDialog.deleteRowsMessage', { count: pendingDeleteRowIds.length }) : t('dangerDialog.deleteRowMessage')"
:details="deleteRowDetails"
- :confirm-label="
- pendingDeleteRowIds.length > 1
- ? t('grid.deleteRows', { count: pendingDeleteRowIds.length })
- : t('grid.deleteRow')
- "
+ :confirm-label="pendingDeleteRowIds.length > 1 ? t('grid.deleteRows', { count: pendingDeleteRowIds.length }) : t('grid.deleteRow')"
@confirm="confirmDeleteRow"
/>
<ImagePreviewDialog v-model:open="imagePreviewOpen" :src="imagePreviewSrc" :title="imagePreviewTitle" />
- <component
- v-if="previewDialogOpen && previewDialogConfig"
- :is="previewDialogConfig.component"
- v-model:open="previewDialogOpen"
- v-bind="previewDialogConfig.props"
- />
+ <component v-if="previewDialogOpen && previewDialogConfig" :is="previewDialogConfig.component" v-model:open="previewDialogOpen" v-bind="previewDialogConfig.props" />
<ExportProgressDialog v-model:open="exportProgressDialog" v-bind="exportProgressState" disable-cancel />
</div>
</template>
@@ -8793,11 +7363,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
--data-grid-cell-active-bg: color-mix(in oklab, var(--primary) 15%, transparent);
--data-grid-cell-dirty-bg: color-mix(in oklab, rgb(240 177 0) 10%, transparent);
--data-grid-cell-selected-bg: color-mix(in oklab, var(--primary) 25%, transparent);
- --data-grid-cell-selected-dirty-bg: color-mix(
- in oklab,
- rgb(234 181 50) 30%,
- color-mix(in oklab, var(--primary) 18%, transparent)
- );
+ --data-grid-cell-selected-dirty-bg: color-mix(in oklab, rgb(234 181 50) 30%, color-mix(in oklab, var(--primary) 18%, transparent));
--data-grid-cell-selected-border: color-mix(in oklab, var(--primary) 70%, transparent);
--data-grid-cell-hover-bg: color-mix(in oklab, var(--accent) 50%, transparent);
--data-grid-row-number-new-bg: color-mix(in oklab, rgb(16 185 129) 15%, var(--background));
diff --git a/apps/desktop/src/components/grid/ImagePreviewDialog.vue b/apps/desktop/src/components/grid/ImagePreviewDialog.vue
index 0782b7d466..5ec67f24c9 100644
--- a/apps/desktop/src/components/grid/ImagePreviewDialog.vue
+++ b/apps/desktop/src/components/grid/ImagePreviewDialog.vue
@@ -143,81 +143,37 @@ watch(
<template>
<Dialog :open="open" @update:open="(value) => emit('update:open', value)">
- <DialogContent
- :show-close-button="false"
- class="image-preview-dialog h-[min(86vh,920px)] w-[min(92vw,1280px)] max-w-none gap-0 overflow-hidden rounded-xl border-white/10 bg-[#090b0f] p-0 text-white shadow-2xl"
- @escape-key-down="close"
- >
+ <DialogContent :show-close-button="false" class="image-preview-dialog h-[min(86vh,920px)] w-[min(92vw,1280px)] max-w-none gap-0 overflow-hidden rounded-xl border-white/10 bg-[#090b0f] p-0 text-white shadow-2xl" @escape-key-down="close">
<div class="flex h-12 shrink-0 items-center gap-3 border-b border-white/10 bg-white/[0.035] px-4">
<div class="min-w-0 flex-1">
<DialogTitle class="truncate text-sm font-semibold text-white">{{ imageTitle }}</DialogTitle>
<div class="truncate text-[11px] text-white/45">{{ hostLabel || src }}</div>
</div>
<div class="flex items-center gap-1 rounded-md border border-white/10 bg-black/20 p-1">
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white"
- :title="t('grid.zoomOut')"
- @click="zoomOut"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white" :title="t('grid.zoomOut')" @click="zoomOut">
<ZoomOut class="h-3.5 w-3.5" />
</Button>
<div class="w-12 text-center text-[11px] tabular-nums text-white/65">{{ zoomLabel }}</div>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white"
- :title="t('grid.zoomIn')"
- @click="zoomIn"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white" :title="t('grid.zoomIn')" @click="zoomIn">
<ZoomIn class="h-3.5 w-3.5" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white"
- :title="t('grid.fitImage')"
- @click="fitImage"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white" :title="t('grid.fitImage')" @click="fitImage">
<Maximize2 class="h-3.5 w-3.5" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white"
- :title="t('grid.openImage')"
- @click="openExternal"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 text-white/75 hover:bg-white/10 hover:text-white" :title="t('grid.openImage')" @click="openExternal">
<ExternalLink class="h-3.5 w-3.5" />
</Button>
</div>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8 text-white/70 hover:bg-white/10 hover:text-white"
- :title="t('dangerDialog.cancel')"
- @click="close"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8 text-white/70 hover:bg-white/10 hover:text-white" :title="t('dangerDialog.cancel')" @click="close">
<X class="h-4 w-4" />
</Button>
</div>
- <div
- ref="stageRef"
- class="image-preview-stage relative min-h-0 flex-1 overflow-hidden"
- :class="{ 'cursor-grabbing': dragStart, 'cursor-grab': !dragStart && imageLoaded && !imageError }"
- @wheel="onWheel"
- >
+ <div ref="stageRef" class="image-preview-stage relative min-h-0 flex-1 overflow-hidden" :class="{ 'cursor-grabbing': dragStart, 'cursor-grab': !dragStart && imageLoaded && !imageError }" @wheel="onWheel">
<div v-if="!imageLoaded && !imageError" class="absolute inset-0 flex items-center justify-center">
- <div
- class="h-16 w-16 animate-pulse rounded-full border border-white/10 bg-white/10 shadow-[0_0_80px_rgba(255,255,255,0.12)]"
- />
+ <div class="h-16 w-16 animate-pulse rounded-full border border-white/10 bg-white/10 shadow-[0_0_80px_rgba(255,255,255,0.12)]" />
</div>
- <div
- v-if="imageError"
- class="absolute inset-0 flex items-center justify-center px-8 text-center text-sm text-white/55"
- >
+ <div v-if="imageError" class="absolute inset-0 flex items-center justify-center px-8 text-center text-sm text-white/55">
{{ t("grid.imageLoadFailed") }}
</div>
<img
@@ -247,10 +203,7 @@ watch(
.image-preview-stage {
background-color: #07090d;
background-image:
- linear-gradient(45deg, rgba(255, 255, 255, 0.055) 25%, transparent 25%),
- linear-gradient(-45deg, rgba(255, 255, 255, 0.055) 25%, transparent 25%),
- linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, 0.055) 75%),
- linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, 0.055) 75%),
+ linear-gradient(45deg, rgba(255, 255, 255, 0.055) 25%, transparent 25%), linear-gradient(-45deg, rgba(255, 255, 255, 0.055) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, 0.055) 75%), linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, 0.055) 75%),
radial-gradient(circle at 50% 30%, rgba(255, 255, 255, 0.08), transparent 42%);
background-position:
0 0,
diff --git a/apps/desktop/src/components/grid/LayerPreviewDialog.vue b/apps/desktop/src/components/grid/LayerPreviewDialog.vue
index 707f4e4656..0e665ee36f 100644
--- a/apps/desktop/src/components/grid/LayerPreviewDialog.vue
+++ b/apps/desktop/src/components/grid/LayerPreviewDialog.vue
@@ -436,12 +436,7 @@ onBeforeUnmount(() => cleanupMap());
<template>
<Dialog :open="open" @update:open="(value) => emit('update:open', value)">
- <DialogContent
- :show-close-button="false"
- :style="contentStyle"
- class="layer-preview-dialog flex w-[96vw] max-w-[1800px] h-[88vh] max-h-[960px] min-w-[640px] min-h-[400px] flex-col gap-0 overflow-hidden rounded-xl border p-0 shadow-2xl"
- @escape-key-down="close"
- >
+ <DialogContent :show-close-button="false" :style="contentStyle" class="layer-preview-dialog flex w-[96vw] max-w-[1800px] h-[88vh] max-h-[960px] min-w-[640px] min-h-[400px] flex-col gap-0 overflow-hidden rounded-xl border p-0 shadow-2xl" @escape-key-down="close">
<!-- Header -->
<div class="flex h-12 shrink-0 items-center gap-2 border-b bg-muted/20 px-3">
<div class="flex min-w-0 shrink-0 items-center gap-2">
@@ -450,12 +445,7 @@ onBeforeUnmount(() => cleanupMap());
</div>
<!-- Label property selector -->
- <select
- v-if="labelProperties.length"
- v-model="labelProperty"
- class="h-6 shrink-0 rounded border bg-background px-1.5 text-[11px] outline-none"
- @change="onLabelPropertyChange"
- >
+ <select v-if="labelProperties.length" v-model="labelProperty" class="h-6 shrink-0 rounded border bg-background px-1.5 text-[11px] outline-none" @change="onLabelPropertyChange">
<option value="">— 标签 —</option>
<option v-for="p in labelProperties" :key="p" :value="p">
{{ p }}
@@ -465,94 +455,43 @@ onBeforeUnmount(() => cleanupMap());
<div class="flex flex-1" />
<!-- Basemap selector -->
- <select
- v-model="selectedBasemapId"
- class="h-6 shrink-0 rounded border bg-background px-1.5 text-[11px] outline-none"
- >
+ <select v-model="selectedBasemapId" class="h-6 shrink-0 rounded border bg-background px-1.5 text-[11px] outline-none">
<option v-for="bm in basemaps" :key="bm.id" :value="bm.id">
{{ bm.label }}
</option>
</select>
<!-- Save as image -->
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
- title="导出图片"
- :disabled="isExporting"
- @click="saveAsImage"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground" title="导出图片" :disabled="isExporting" @click="saveAsImage">
<Camera v-if="!isExporting" class="h-3.5 w-3.5" />
<Loader2 v-else class="h-3.5 w-3.5 animate-spin" />
</Button>
<!-- Maximise -->
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
- :title="isMaximized ? '还原' : '最大化'"
- @click="toggleMaximize"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground" :title="isMaximized ? '还原' : '最大化'" @click="toggleMaximize">
<Maximize2 v-if="!isMaximized" class="h-3.5 w-3.5" />
<Minimize2 v-else class="h-3.5 w-3.5" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
- :title="t('dangerDialog.cancel')"
- @click="close"
- >
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground" :title="t('dangerDialog.cancel')" @click="close">
<X class="h-3.5 w-3.5" />
</Button>
</div>
<!-- Map -->
<div ref="mapContainer" class="relative w-full flex-1" style="min-height: 200px" data-map-container>
- <div
- class="absolute inset-0 z-10 flex items-center justify-center text-xs text-muted-foreground pointer-events-none"
- data-map-placeholder
- >
- Loading map…
- </div>
+ <div class="absolute inset-0 z-10 flex items-center justify-center text-xs text-muted-foreground pointer-events-none" data-map-placeholder>Loading map…</div>
</div>
- <div
- v-if="mapError"
- class="absolute inset-0 flex items-center justify-center bg-background/80 p-4 text-sm text-destructive"
- >
+ <div v-if="mapError" class="absolute inset-0 flex items-center justify-center bg-background/80 p-4 text-sm text-destructive">
{{ mapError }}
</div>
<!-- Resize handles -->
- <div
- class="absolute bottom-0 right-0 z-50 h-5 w-5 cursor-se-resize"
- @pointerdown.prevent="onResizePointerDown($event, 'se')"
- @pointermove="onResizePointerMove"
- @pointerup="onResizePointerUp"
- @pointercancel="onResizePointerUp"
- >
- <div
- class="absolute bottom-0.5 right-0.5 h-2.5 w-2.5"
- style="border-right: 2px solid; border-bottom: 2px solid; opacity: 0.3"
- />
+ <div class="absolute bottom-0 right-0 z-50 h-5 w-5 cursor-se-resize" @pointerdown.prevent="onResizePointerDown($event, 'se')" @pointermove="onResizePointerMove" @pointerup="onResizePointerUp" @pointercancel="onResizePointerUp">
+ <div class="absolute bottom-0.5 right-0.5 h-2.5 w-2.5" style="border-right: 2px solid; border-bottom: 2px solid; opacity: 0.3" />
</div>
- <div
- class="absolute bottom-0 left-2 right-6 z-50 h-2 cursor-s-resize opacity-0 hover:opacity-25"
- @pointerdown.prevent="onResizePointerDown($event, 's')"
- @pointermove="onResizePointerMove"
- @pointerup="onResizePointerUp"
- @pointercancel="onResizePointerUp"
- />
- <div
- class="absolute right-0 top-2 bottom-6 z-50 w-2 cursor-e-resize opacity-0 hover:opacity-25"
- @pointerdown.prevent="onResizePointerDown($event, 'e')"
- @pointermove="onResizePointerMove"
- @pointerup="onResizePointerUp"
- @pointercancel="onResizePointerUp"
- />
+ <div class="absolute bottom-0 left-2 right-6 z-50 h-2 cursor-s-resize opacity-0 hover:opacity-25" @pointerdown.prevent="onResizePointerDown($event, 's')" @pointermove="onResizePointerMove" @pointerup="onResizePointerUp" @pointercancel="onResizePointerUp" />
+ <div class="absolute right-0 top-2 bottom-6 z-50 w-2 cursor-e-resize opacity-0 hover:opacity-25" @pointerdown.prevent="onResizePointerDown($event, 'e')" @pointermove="onResizePointerMove" @pointerup="onResizePointerUp" @pointercancel="onResizePointerUp" />
</DialogContent>
</Dialog>
</template>
diff --git a/apps/desktop/src/components/grid/TemporalCellEditor.vue b/apps/desktop/src/components/grid/TemporalCellEditor.vue
index a2e2ae8307..97b1a94659 100644
--- a/apps/desktop/src/components/grid/TemporalCellEditor.vue
+++ b/apps/desktop/src/components/grid/TemporalCellEditor.vue
@@ -37,10 +37,7 @@ const displayValue = computed(() => props.modelValue || "NULL");
const triggerClass = computed(() =>
props.variant === "inline"
? "cell-edit-input flex h-9 w-full items-center gap-2 rounded border bg-background px-2 text-left text-xs outline-none hover:border-primary/60 focus:border-primary"
- : [
- "cell-edit-input absolute inset-0 z-10 flex items-center gap-1 border-2 border-primary bg-background py-0 text-left text-xs outline-none",
- props.cellLayout === "transpose" ? "px-1.5" : "px-2.5",
- ],
+ : ["cell-edit-input absolute inset-0 z-10 flex items-center gap-1 border-2 border-primary bg-background py-0 text-left text-xs outline-none", props.cellLayout === "transpose" ? "px-1.5" : "px-2.5"],
);
const dateParts = computed(() => {
const text = formatTemporalInputValue(props.modelValue, "date");
@@ -131,16 +128,8 @@ function setNull() {
function setNow() {
const now = new Date();
- const dateText = [
- String(now.getFullYear()).padStart(4, "0"),
- String(now.getMonth() + 1).padStart(2, "0"),
- String(now.getDate()).padStart(2, "0"),
- ].join("-");
- const nextTime = [
- String(now.getHours()).padStart(2, "0"),
- String(now.getMinutes()).padStart(2, "0"),
- String(now.getSeconds()).padStart(2, "0"),
- ].join(":");
+ const dateText = [String(now.getFullYear()).padStart(4, "0"), String(now.getMonth() + 1).padStart(2, "0"), String(now.getDate()).padStart(2, "0")].join("-");
+ const nextTime = [String(now.getHours()).padStart(2, "0"), String(now.getMinutes()).padStart(2, "0"), String(now.getSeconds()).padStart(2, "0")].join(":");
if (props.kind === "date") setModelValue(dateText);
else if (props.kind === "time") setModelValue(nextTime);
else setModelValue(`${dateText} ${nextTime}`);
@@ -186,9 +175,7 @@ function normalizeTimePart(value: string | number, max: number): string {
}
function setDateTimeValue(year: number, month: number, day: number, time: string) {
- const dateText = [String(year).padStart(4, "0"), String(month).padStart(2, "0"), String(day).padStart(2, "0")].join(
- "-",
- );
+ const dateText = [String(year).padStart(4, "0"), String(month).padStart(2, "0"), String(day).padStart(2, "0")].join("-");
if (props.kind === "date") setModelValue(dateText);
else setModelValue(`${dateText} ${time}`);
}
@@ -210,82 +197,39 @@ function twoDigit(value: string | number): string {
<span class="min-w-0 flex-1 truncate">{{ displayValue }}</span>
</button>
</PopoverTrigger>
- <PopoverContent
- align="start"
- side="bottom"
- class="w-auto gap-1.5 rounded-md p-1.5"
- @click.stop
- @keydown.stop="onKeydown"
- @interact-outside="onPopoverInteractOutside"
- >
+ <PopoverContent align="start" side="bottom" class="w-auto gap-1.5 rounded-md p-1.5" @click.stop @keydown.stop="onKeydown" @interact-outside="onPopoverInteractOutside">
<div v-if="hasDate" class="grid grid-cols-[4.5rem_4.5rem_4.5rem] gap-1.5">
- <div
- class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background"
- >
- <input
- :value="dateParts.year"
- data-temporal-part="year"
- inputmode="numeric"
- class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none"
- @change="updateDateFromInput('year', $event)"
- />
+ <div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
+ <input :value="dateParts.year" data-temporal-part="year" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateDateFromInput('year', $event)" />
<div class="grid border-l">
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepDate('year', 1)">
<ChevronUp class="h-3 w-3" />
</button>
- <button
- type="button"
- class="flex items-center justify-center border-t hover:bg-muted"
- @click="stepDate('year', -1)"
- >
+ <button type="button" class="flex items-center justify-center border-t hover:bg-muted" @click="stepDate('year', -1)">
<ChevronDown class="h-3 w-3" />
</button>
</div>
</div>
- <div
- class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background"
- >
- <input
- :value="twoDigit(dateParts.month)"
- data-temporal-part="month"
- inputmode="numeric"
- class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none"
- @change="updateDateFromInput('month', $event)"
- />
+ <div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
+ <input :value="twoDigit(dateParts.month)" data-temporal-part="month" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateDateFromInput('month', $event)" />
<div class="grid border-l">
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepDate('month', 1)">
<ChevronUp class="h-3 w-3" />
</button>
- <button
- type="button"
- class="flex items-center justify-center border-t hover:bg-muted"
- @click="stepDate('month', -1)"
- >
+ <button type="button" class="flex items-center justify-center border-t hover:bg-muted" @click="stepDate('month', -1)">
<ChevronDown class="h-3 w-3" />
</button>
</div>
</div>
- <div
- class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background"
- >
- <input
- :value="twoDigit(dateParts.day)"
- data-temporal-part="day"
- inputmode="numeric"
- class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none"
- @change="updateDateFromInput('day', $event)"
- />
+ <div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
+ <input :value="twoDigit(dateParts.day)" data-temporal-part="day" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateDateFromInput('day', $event)" />
<div class="grid border-l">
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepDate('day', 1)">
<ChevronUp class="h-3 w-3" />
</button>
- <button
- type="button"
- class="flex items-center justify-center border-t hover:bg-muted"
- @click="stepDate('day', -1)"
- >
+ <button type="button" class="flex items-center justify-center border-t hover:bg-muted" @click="stepDate('day', -1)">
<ChevronDown class="h-3 w-3" />
</button>
</div>
@@ -293,81 +237,37 @@ function twoDigit(value: string | number): string {
</div>
<div v-if="hasTime" class="grid grid-cols-[3.5rem_0.5rem_3.5rem_0.5rem_3.5rem] items-center gap-1.5">
- <div
- class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background"
- >
- <input
- :value="twoDigit(timeParts.hour)"
- data-temporal-part="hour"
- inputmode="numeric"
- class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none"
- @change="updateTimeFromInput('hour', $event)"
- />
+ <div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
+ <input :value="twoDigit(timeParts.hour)" data-temporal-part="hour" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateTimeFromInput('hour', $event)" />
<div class="grid border-l">
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepTime('hour', 1)">
<ChevronUp class="h-3 w-3" />
</button>
- <button
- type="button"
- class="flex items-center justify-center border-t hover:bg-muted"
- @click="stepTime('hour', -1)"
- >
+ <button type="button" class="flex items-center justify-center border-t hover:bg-muted" @click="stepTime('hour', -1)">
<ChevronDown class="h-3 w-3" />
</button>
</div>
</div>
<span class="text-center text-xs text-muted-foreground">:</span>
- <div
- class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background"
- >
- <input
- :value="twoDigit(timeParts.minute)"
- data-temporal-part="minute"
- inputmode="numeric"
- class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none"
- @change="updateTimeFromInput('minute', $event)"
- />
+ <div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
+ <input :value="twoDigit(timeParts.minute)" data-temporal-part="minute" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateTimeFromInput('minute', $event)" />
<div class="grid border-l">
- <button
- type="button"
- class="flex items-center justify-center hover:bg-muted"
- @click="stepTime('minute', 1)"
- >
+ <button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepTime('minute', 1)">
<ChevronUp class="h-3 w-3" />
</button>
- <button
- type="button"
- class="flex items-center justify-center border-t hover:bg-muted"
- @click="stepTime('minute', -1)"
- >
+ <button type="button" class="flex items-center justify-center border-t hover:bg-muted" @click="stepTime('minute', -1)">
<ChevronDown class="h-3 w-3" />
</button>
</div>
</div>
<span class="text-center text-xs text-muted-foreground">:</span>
- <div
- class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background"
- >
- <input
- :value="twoDigit(timeParts.second)"
- data-temporal-part="second"
- inputmode="numeric"
- class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none"
- @change="updateTimeFromInput('second', $event)"
- />
+ <div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
+ <input :value="twoDigit(timeParts.second)" data-temporal-part="second" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateTimeFromInput('second', $event)" />
<div class="grid border-l">
- <button
- type="button"
- class="flex items-center justify-center hover:bg-muted"
- @click="stepTime('second', 1)"
- >
+ <button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepTime('second', 1)">
<ChevronUp class="h-3 w-3" />
</button>
- <button
- type="button"
- class="flex items-center justify-center border-t hover:bg-muted"
- @click="stepTime('second', -1)"
- >
+ <button type="button" class="flex items-center justify-center border-t hover:bg-muted" @click="stepTime('second', -1)">
<ChevronDown class="h-3 w-3" />
</button>
</div>
diff --git a/apps/desktop/src/components/icons/AiProviderLogo.vue b/apps/desktop/src/components/icons/AiProviderLogo.vue
index d2c9bf62c6..f9fb05f378 100644
--- a/apps/desktop/src/components/icons/AiProviderLogo.vue
+++ b/apps/desktop/src/components/icons/AiProviderLogo.vue
@@ -20,13 +20,7 @@ watch(
},
);
-const usesWhiteDarkIcon = computed(
- () =>
- props.provider === "claude" ||
- props.provider === "ollama" ||
- props.provider === "openai" ||
- props.provider === "openai-compatible",
-);
+const usesWhiteDarkIcon = computed(() => props.provider === "claude" || props.provider === "ollama" || props.provider === "openai" || props.provider === "openai-compatible");
const localIconUrl = computed(() => {
if (props.provider === "openai-compatible") return "/icons/ai/openai.svg";
return props.iconSlug ? `/icons/ai/${props.iconSlug}.svg` : "";
@@ -40,14 +34,7 @@ const fallbackText = computed(() => {
<template>
<span class="flex h-4 w-4 shrink-0 items-center justify-center overflow-hidden rounded-sm">
<Settings2 v-if="provider === 'custom'" class="h-4 w-4 text-muted-foreground" />
- <img
- v-else-if="localIconUrl && !failed"
- :src="localIconUrl"
- :alt="label"
- class="h-4 w-4 object-contain"
- :class="{ 'dark:invert': isDark && usesWhiteDarkIcon }"
- @error="failed = true"
- />
+ <img v-else-if="localIconUrl && !failed" :src="localIconUrl" :alt="label" class="h-4 w-4 object-contain" :class="{ 'dark:invert': isDark && usesWhiteDarkIcon }" @error="failed = true" />
<span v-else class="flex h-4 w-4 items-center justify-center rounded-sm bg-muted text-[8px] font-semibold">
{{ fallbackText }}
</span>
diff --git a/apps/desktop/src/components/icons/DatabaseIcon.vue b/apps/desktop/src/components/icons/DatabaseIcon.vue
index f90708b65b..bb83db01c8 100644
--- a/apps/desktop/src/components/icons/DatabaseIcon.vue
+++ b/apps/desktop/src/components/icons/DatabaseIcon.vue
@@ -81,9 +81,7 @@ const normalizedType = computed(() => props.dbType.toLowerCase().replace(/[\s-]+
const assetName = computed(() => assetIcons[normalizedType.value]);
const assetSrc = computed(() => {
if (!assetName.value) return "";
- return assetName.value.includes(".")
- ? `/icons/database/${assetName.value}`
- : `/icons/database/${assetName.value}.svg`;
+ return assetName.value.includes(".") ? `/icons/database/${assetName.value}` : `/icons/database/${assetName.value}.svg`;
});
const letter = computed(() => letterIcons[normalizedType.value]);
</script>
@@ -92,15 +90,7 @@ const letter = computed(() => letterIcons[normalizedType.value]);
<img v-if="assetName" :src="assetSrc" alt="" class="database-logo object-contain" aria-hidden="true" />
<svg v-else-if="letter" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="12" :fill="letter.color" />
- <text
- x="12"
- y="16.5"
- text-anchor="middle"
- fill="white"
- font-size="14"
- font-weight="bold"
- font-family="system-ui, sans-serif"
- >
+ <text x="12" y="16.5" text-anchor="middle" fill="white" font-size="14" font-weight="bold" font-family="system-ui, sans-serif">
{{ letter.letter }}
</text>
</svg>
diff --git a/apps/desktop/src/components/import/TableImportDialog.vue b/apps/desktop/src/components/import/TableImportDialog.vue
index 452acee8e0..9ec0243c52 100644
--- a/apps/desktop/src/components/import/TableImportDialog.vue
+++ b/apps/desktop/src/components/import/TableImportDialog.vue
@@ -42,9 +42,7 @@ const progress = ref<api.TableImportProgress | null>(null);
const errorMessage = ref("");
const fileInput = ref<HTMLInputElement | null>(null);
-const selectedConnection = computed(() =>
- props.prefillConnectionId ? store.getConfig(props.prefillConnectionId) : undefined,
-);
+const selectedConnection = computed(() => (props.prefillConnectionId ? store.getConfig(props.prefillConnectionId) : undefined));
const targetColumnNames = computed(() => targetColumns.value.map((column) => column.name));
const mappedColumns = computed<api.TableImportColumnMapping[]>(() => {
const currentPreview = preview.value;
@@ -57,26 +55,14 @@ const mappedColumns = computed<api.TableImportColumnMapping[]>(() => {
.filter((mapping) => mapping.targetColumn);
});
const mappedCount = computed(() => mappedColumns.value.length);
-const canImport = computed(
- () =>
- !!preview.value &&
- !!props.prefillConnectionId &&
- !!props.prefillTable &&
- mappedColumns.value.length > 0 &&
- !running.value,
-);
+const canImport = computed(() => !!preview.value && !!props.prefillConnectionId && !!props.prefillTable && mappedColumns.value.length > 0 && !running.value);
const progressPercent = computed(() => {
const p = progress.value;
if (!p || p.totalRows <= 0) return 0;
return Math.min(100, Math.round((p.rowsImported / p.totalRows) * 100));
});
const targetLabel = computed(() => {
- const pieces = [
- selectedConnection.value?.name,
- props.prefillDatabase,
- props.prefillSchema,
- props.prefillTable,
- ].filter(Boolean);
+ const pieces = [selectedConnection.value?.name, props.prefillDatabase, props.prefillSchema, props.prefillTable].filter(Boolean);
return pieces.join(" / ");
});
@@ -105,12 +91,7 @@ async function loadTargetColumns() {
errorMessage.value = "";
try {
await store.ensureConnected(props.prefillConnectionId);
- targetColumns.value = await api.getColumns(
- props.prefillConnectionId,
- props.prefillDatabase,
- props.prefillSchema || props.prefillDatabase,
- props.prefillTable,
- );
+ targetColumns.value = await api.getColumns(props.prefillConnectionId, props.prefillDatabase, props.prefillSchema || props.prefillDatabase, props.prefillTable);
applyAutoMapping();
} catch (e: any) {
errorMessage.value = String(e?.message || e);
@@ -255,13 +236,7 @@ watch(
<div class="space-y-4 py-2">
<div class="grid grid-cols-[1fr_auto] gap-2">
- <input
- ref="fileInput"
- type="file"
- accept=".csv,.tsv,.json,.xlsx,.xlsm,.xls"
- class="hidden"
- @change="handleFileInputChange"
- />
+ <input ref="fileInput" type="file" accept=".csv,.tsv,.json,.xlsx,.xlsm,.xls" class="hidden" @change="handleFileInputChange" />
<div class="min-w-0 rounded-md border bg-muted/20 px-3 py-2">
<div class="truncate text-xs text-muted-foreground">{{ t("tableImport.target") }}</div>
<div class="truncate text-sm font-medium">
@@ -294,18 +269,11 @@ watch(
<div class="rounded-md border">
<div class="border-b px-3 py-2 text-xs font-medium">{{ t("tableImport.mapping") }}</div>
<div class="max-h-[280px] overflow-auto p-2">
- <div
- v-for="sourceColumn in preview.columns"
- :key="sourceColumn"
- class="grid grid-cols-[1fr_1fr] items-center gap-2 py-1"
- >
+ <div v-for="sourceColumn in preview.columns" :key="sourceColumn" class="grid grid-cols-[1fr_1fr] items-center gap-2 py-1">
<div class="truncate font-mono text-xs" :title="sourceColumn">
{{ sourceColumn }}
</div>
- <Select
- :model-value="columnMapping[sourceColumn] || SKIP_VALUE"
- @update:model-value="(value: any) => updateMapping(sourceColumn, value)"
- >
+ <Select :model-value="columnMapping[sourceColumn] || SKIP_VALUE" @update:model-value="(value: any) => updateMapping(sourceColumn, value)">
<SelectTrigger class="h-7 text-xs">
<SelectValue />
</SelectTrigger>
@@ -326,23 +294,14 @@ watch(
<table class="min-w-full border-separate border-spacing-0 text-xs">
<thead class="sticky top-0 bg-background">
<tr>
- <th
- v-for="column in preview.columns"
- :key="column"
- class="border-b border-r px-2 py-1.5 text-left font-medium"
- >
+ <th v-for="column in preview.columns" :key="column" class="border-b border-r px-2 py-1.5 text-left font-medium">
<span class="block max-w-[140px] truncate">{{ column }}</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in preview.rows" :key="rowIndex">
- <td
- v-for="(cell, colIndex) in row"
- :key="colIndex"
- class="max-w-[180px] border-b border-r px-2 py-1.5 font-mono"
- :class="{ 'text-muted-foreground': cell === null }"
- >
+ <td v-for="(cell, colIndex) in row" :key="colIndex" class="max-w-[180px] border-b border-r px-2 py-1.5 font-mono" :class="{ 'text-muted-foreground': cell === null }">
<span class="block truncate">{{ formatCell(cell) }}</span>
</td>
</tr>
@@ -375,10 +334,7 @@ watch(
<Loader2 v-if="running && !cancelling" class="h-3.5 w-3.5 animate-spin text-primary" />
<Square v-else-if="cancelling" class="h-3.5 w-3.5 fill-current text-destructive" />
<Check v-else class="h-3.5 w-3.5 text-emerald-600" />
- <span class="truncate">
- {{ progress?.rowsImported ?? 0 }} / {{ progress?.totalRows ?? preview.totalRows }} ·
- {{ progressPercent }}%
- </span>
+ <span class="truncate"> {{ progress?.rowsImported ?? 0 }} / {{ progress?.totalRows ?? preview.totalRows }} · {{ progressPercent }}% </span>
</div>
</div>
</div>
@@ -387,10 +343,7 @@ watch(
<Loader2 class="h-3.5 w-3.5 animate-spin" />
{{ t("common.loading") }}
</div>
- <div
- v-if="errorMessage"
- class="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive"
- >
+ <div v-if="errorMessage" class="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{{ errorMessage }}
</div>
</div>
diff --git a/apps/desktop/src/components/layout/AppDialogs.vue b/apps/desktop/src/components/layout/AppDialogs.vue
index 544d1ed5d1..331bc83a16 100644
--- a/apps/desktop/src/components/layout/AppDialogs.vue
+++ b/apps/desktop/src/components/layout/AppDialogs.vue
@@ -106,13 +106,7 @@ watch(
@connect-failed="emit('connectFailed', $event)"
@open-driver-store="emit('openDriverStore')"
/>
- <EditorSettingsDialog
- v-if="showSettingsDialog"
- :open="showSettingsDialog"
- :initial-tab="settingsInitialTab || 'editor'"
- :app-version="appVersion"
- @update:open="emit('update:showSettingsDialog', $event)"
- />
+ <EditorSettingsDialog v-if="showSettingsDialog" :open="showSettingsDialog" :initial-tab="settingsInitialTab || 'editor'" :app-version="appVersion" @update:open="emit('update:showSettingsDialog', $event)" />
<DangerConfirmDialog
v-if="showDangerDialog"
:open="showDangerDialog"
@@ -123,19 +117,8 @@ watch(
@update:suppress-future-prompts="emit('update:suppressDangerConfirm', $event)"
@confirm="emit('dangerConfirm')"
/>
- <DataTransferDialog
- v-if="dialogs.showTransferDialog.value"
- v-model:open="dialogs.showTransferDialog.value"
- :prefill-connection-id="dialogs.transferPrefillConnectionId.value"
- :prefill-database="dialogs.transferPrefillDatabase.value"
- />
- <SchemaDiffDialog
- v-if="dialogs.showSchemaDiffDialog.value"
- v-model:open="dialogs.showSchemaDiffDialog.value"
- :prefill-connection-id="dialogs.schemaDiffPrefillConnectionId.value"
- :prefill-database="dialogs.schemaDiffPrefillDatabase.value"
- :prefill-schema="dialogs.schemaDiffPrefillSchema.value"
- />
+ <DataTransferDialog v-if="dialogs.showTransferDialog.value" v-model:open="dialogs.showTransferDialog.value" :prefill-connection-id="dialogs.transferPrefillConnectionId.value" :prefill-database="dialogs.transferPrefillDatabase.value" />
+ <SchemaDiffDialog v-if="dialogs.showSchemaDiffDialog.value" v-model:open="dialogs.showSchemaDiffDialog.value" :prefill-connection-id="dialogs.schemaDiffPrefillConnectionId.value" :prefill-database="dialogs.schemaDiffPrefillDatabase.value" :prefill-schema="dialogs.schemaDiffPrefillSchema.value" />
<DataCompareDialog
v-if="dialogs.showDataCompareDialog.value"
v-model:open="dialogs.showDataCompareDialog.value"
@@ -144,12 +127,7 @@ watch(
:prefill-schema="dialogs.dataComparePrefillSchema.value"
:prefill-table="dialogs.dataComparePrefillTable.value"
/>
- <SqlFileExecutionDialog
- v-if="dialogs.showSqlFileDialog.value"
- v-model:open="dialogs.showSqlFileDialog.value"
- :prefill-connection-id="dialogs.sqlFilePrefillConnectionId.value"
- :prefill-database="dialogs.sqlFilePrefillDatabase.value"
- />
+ <SqlFileExecutionDialog v-if="dialogs.showSqlFileDialog.value" v-model:open="dialogs.showSqlFileDialog.value" :prefill-connection-id="dialogs.sqlFilePrefillConnectionId.value" :prefill-database="dialogs.sqlFilePrefillDatabase.value" />
<SchemaDiagramDialog
v-if="dialogs.showDiagramDialog.value"
v-model:open="dialogs.showDiagramDialog.value"
@@ -198,11 +176,7 @@ watch(
v-model:open="dialogs.showConfigPassphraseDialog.value"
:mode="dialogs.configPassphraseMode.value"
:external-error="dialogs.configPassphraseError.value"
- @confirm="
- dialogs.configPassphraseMode.value === 'export'
- ? dialogs.onExportConfirm($event)
- : dialogs.onImportConfirm($event)
- "
+ @confirm="dialogs.configPassphraseMode.value === 'export' ? dialogs.onExportConfirm($event) : dialogs.onImportConfirm($event)"
/>
<Dialog v-model:open="dialogs.showImportLayoutConfirm.value">
<DialogContent class="sm:max-w-[400px]">
@@ -211,9 +185,7 @@ watch(
</DialogHeader>
<p class="text-sm text-muted-foreground">{{ t("configExport.importLayoutConfirm") }}</p>
<DialogFooter>
- <Button variant="outline" @click="dialogs.showImportLayoutConfirm.value = false">{{
- t("dangerDialog.cancel")
- }}</Button>
+ <Button variant="outline" @click="dialogs.showImportLayoutConfirm.value = false">{{ t("dangerDialog.cancel") }}</Button>
<Button
@click="
dialogs.showImportLayoutConfirm.value = false;
diff --git a/apps/desktop/src/components/layout/AppSidebar.vue b/apps/desktop/src/components/layout/AppSidebar.vue
index 5041a80f5c..cb451307a2 100644
--- a/apps/desktop/src/components/layout/AppSidebar.vue
+++ b/apps/desktop/src/components/layout/AppSidebar.vue
@@ -53,19 +53,10 @@ defineExpose({ focusSearch });
</script>
<template>
- <div
- class="h-full shrink-0 relative select-none"
- :class="classicLayout ? '' : 'rounded-md border border-border/80 bg-background'"
- :style="{ width: sidebarWidth + 'px' }"
- >
+ <div class="h-full shrink-0 relative select-none" :class="classicLayout ? '' : 'rounded-md border border-border/80 bg-background'" :style="{ width: sidebarWidth + 'px' }">
<div class="h-full flex flex-col overflow-hidden">
- <div
- class="flex items-center gap-px px-3 text-xs font-medium text-muted-foreground border-b bg-muted/20"
- :class="classicLayout ? 'h-9' : 'h-10'"
- >
- <span class="flex self-stretch items-center truncate" data-tauri-drag-region>{{
- t("sidebar.connections")
- }}</span>
+ <div class="flex items-center gap-px px-3 text-xs font-medium text-muted-foreground border-b bg-muted/20" :class="classicLayout ? 'h-9' : 'h-10'">
+ <span class="flex self-stretch items-center truncate" data-tauri-drag-region>{{ t("sidebar.connections") }}</span>
<span class="flex-1 self-stretch" data-tauri-drag-region />
<Tooltip>
<TooltipTrigger as-child>
diff --git a/apps/desktop/src/components/layout/AppTabBar.vue b/apps/desktop/src/components/layout/AppTabBar.vue
index 9b378b9b52..7ce6a9b6cf 100644
--- a/apps/desktop/src/components/layout/AppTabBar.vue
+++ b/apps/desktop/src/components/layout/AppTabBar.vue
@@ -2,19 +2,7 @@
import { computed, ref, watch, nextTick } from "vue";
import type { CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
-import {
- X,
- Pin,
- ChevronDown,
- Table2,
- Code2,
- TableProperties,
- PencilRuler,
- KeyRound,
- Pencil,
- Package,
- Check,
-} from "@lucide/vue";
+import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Check } from "@lucide/vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import LightDropdown from "@/components/ui/LightDropdown.vue";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
@@ -120,15 +108,7 @@ function getTabMenuItems(tab: QueryTab): ContextMenuItem[] {
}
const tabsContainerRef = ref<HTMLElement | null>(null);
-const {
- hasTabOverflow,
- scrollThumbLeftPercent,
- scrollThumbWidthPercent,
- isScrollbarDragging,
- updateScrollButtons,
- onTabsWheel,
- startScrollbarDrag,
-} = useTabScroll(tabsContainerRef);
+const { hasTabOverflow, scrollThumbLeftPercent, scrollThumbWidthPercent, isScrollbarDragging, updateScrollButtons, onTabsWheel, startScrollbarDrag } = useTabScroll(tabsContainerRef);
const tabScrollBehavior = ref<ScrollBehavior>("smooth");
watch(
@@ -199,8 +179,7 @@ function tabColorStyle(tab: QueryTab) {
}
function tabIconClass(tab: QueryTab) {
- if (tab.mode === "data" || tab.mode === "objects" || tab.mode === "structure")
- return "text-emerald-600 dark:text-emerald-400";
+ if (tab.mode === "data" || tab.mode === "objects" || tab.mode === "structure") return "text-emerald-600 dark:text-emerald-400";
return "text-blue-600 dark:text-blue-400";
}
@@ -259,9 +238,7 @@ const tabScrollbarThumbStyle = computed<CSSProperties>(() => ({
width: `${scrollThumbWidthPercent.value}%`,
}));
-const tabTailDragRegionClass = computed(() =>
- showTabOverflowControls.value ? "w-0 flex-none self-stretch" : "min-w-8 flex-1 self-stretch",
-);
+const tabTailDragRegionClass = computed(() => (showTabOverflowControls.value ? "w-0 flex-none self-stretch" : "min-w-8 flex-1 self-stretch"));
const tabOverflowControlClass = computed(() =>
settingsStore.editorSettings.appLayout === "classic"
@@ -271,9 +248,7 @@ const tabOverflowControlClass = computed(() =>
function dispatchBeforeTabSwitch(tabId: string) {
if (tabId === queryStore.activeTabId) return;
- window.dispatchEvent(
- new CustomEvent("dbx:before-tab-switch", { detail: { tabId, fromTabId: queryStore.activeTabId } }),
- );
+ window.dispatchEvent(new CustomEvent("dbx:before-tab-switch", { detail: { tabId, fromTabId: queryStore.activeTabId } }));
}
function activateTab(tabId: string) {
@@ -285,62 +260,22 @@ function activateTab(tabId: string) {
</script>
<template>
- <div
- v-if="queryStore.tabs.length > 0 || showDriverStore"
- class="relative flex border-b shrink-0"
- :class="
- settingsStore.editorSettings.appLayout === 'classic'
- ? 'h-9 items-stretch bg-muted'
- : 'h-10 items-center bg-background px-2'
- "
- >
+ <div v-if="queryStore.tabs.length > 0 || showDriverStore" class="relative flex border-b shrink-0" :class="settingsStore.editorSettings.appLayout === 'classic' ? 'h-9 items-stretch bg-muted' : 'h-10 items-center bg-background px-2'">
<div class="relative h-full min-w-0 flex-1">
- <div
- v-if="showTabOverflowControls"
- class="app-tab-scrollbar"
- :class="{ 'app-tab-scrollbar--dragging': isScrollbarDragging }"
- @pointerdown="startScrollbarDrag"
- >
+ <div v-if="showTabOverflowControls" class="app-tab-scrollbar" :class="{ 'app-tab-scrollbar--dragging': isScrollbarDragging }" @pointerdown="startScrollbarDrag">
<div class="app-tab-scrollbar__thumb" :style="tabScrollbarThumbStyle" />
</div>
- <div
- ref="tabsContainerRef"
- class="app-tab-scroll flex min-w-0 flex-1 items-center overflow-x-auto"
- :class="settingsStore.editorSettings.appLayout === 'classic' ? 'h-full' : 'h-10 gap-1.5 py-1.5'"
- :style="tabsContainerStyle"
- @scroll="updateScrollButtons"
- @wheel="onTabsWheel"
- >
- <CustomContextMenu
- v-for="tab in queryStore.tabs"
- :key="tab.id"
- :items="getTabMenuItems(tab)"
- v-slot="{ onContextMenu }"
- >
- <div
- :class="settingsStore.editorSettings.appLayout === 'classic' ? 'h-full' : ''"
- @contextmenu="onContextMenu"
- >
+ <div ref="tabsContainerRef" class="app-tab-scroll flex min-w-0 flex-1 items-center overflow-x-auto" :class="settingsStore.editorSettings.appLayout === 'classic' ? 'h-full' : 'h-10 gap-1.5 py-1.5'" :style="tabsContainerStyle" @scroll="updateScrollButtons" @wheel="onTabsWheel">
+ <CustomContextMenu v-for="tab in queryStore.tabs" :key="tab.id" :items="getTabMenuItems(tab)" v-slot="{ onContextMenu }">
+ <div :class="settingsStore.editorSettings.appLayout === 'classic' ? 'h-full' : ''" @contextmenu="onContextMenu">
<Tooltip>
<TooltipTrigger as-child>
<div
class="group flex items-center gap-1 px-2 text-xs cursor-pointer transition-colors whitespace-nowrap select-none"
:class="
settingsStore.editorSettings.appLayout === 'classic'
- ? [
- compactTabTitle ? 'min-w-24' : 'min-w-38',
- 'h-full border-r border-border/80 font-medium dark:border-border/45',
- tab.id === queryStore.activeTabId && !showDriverStore
- ? 'bg-background text-foreground'
- : 'text-foreground/70 hover:text-foreground/90',
- ]
- : [
- compactTabTitle ? 'min-w-24' : 'min-w-38',
- 'h-7 rounded-md border',
- tab.id === queryStore.activeTabId && !showDriverStore
- ? 'text-foreground font-medium'
- : 'border-border/60 text-foreground/70 hover:border-border hover:text-foreground/90',
- ]
+ ? [compactTabTitle ? 'min-w-24' : 'min-w-38', 'h-full border-r border-border/80 font-medium dark:border-border/45', tab.id === queryStore.activeTabId && !showDriverStore ? 'bg-background text-foreground' : 'text-foreground/70 hover:text-foreground/90']
+ : [compactTabTitle ? 'min-w-24' : 'min-w-38', 'h-7 rounded-md border', tab.id === queryStore.activeTabId && !showDriverStore ? 'text-foreground font-medium' : 'border-border/60 text-foreground/70 hover:border-border hover:text-foreground/90']
"
:style="[tabColorStyle(tab), tabDropStyle(tab.id)]"
:data-active-tab="tab.id === queryStore.activeTabId && !showDriverStore"
@@ -374,20 +309,13 @@ function activateTab(tabId: string) {
<span v-else class="min-w-0 truncate flex-1">{{ tabDisplayTitle(tab, t) }}</span>
<Tooltip>
<TooltipTrigger as-child>
- <button
- class="inline-flex rounded p-0.5 text-muted-foreground hover:bg-muted-foreground/20 hover:text-foreground focus:opacity-100"
- :class="tab.pinned ? 'visible text-primary' : 'invisible group-hover:visible'"
- @click.stop="queryStore.togglePinnedTab(tab.id)"
- >
+ <button class="inline-flex rounded p-0.5 text-muted-foreground hover:bg-muted-foreground/20 hover:text-foreground focus:opacity-100" :class="tab.pinned ? 'visible text-primary' : 'invisible group-hover:visible'" @click.stop="queryStore.togglePinnedTab(tab.id)">
<Pin class="h-3 w-3" :class="{ 'fill-current': tab.pinned }" />
</button>
</TooltipTrigger>
<TooltipContent>{{ tab.pinned ? t("contextMenu.unpin") : t("contextMenu.pin") }}</TooltipContent>
</Tooltip>
- <button
- class="rounded hover:bg-muted-foreground/20 p-0.5 shrink-0"
- @click.stop="queryStore.closeTab(tab.id)"
- >
+ <button class="rounded hover:bg-muted-foreground/20 p-0.5 shrink-0" @click.stop="queryStore.closeTab(tab.id)">
<X class="h-3 w-3" />
</button>
</div>
@@ -407,27 +335,15 @@ function activateTab(tabId: string) {
v-if="showDriverStore"
data-driver-store-tab
class="group flex min-w-38 items-center gap-1 px-2 text-xs cursor-pointer transition-colors whitespace-nowrap"
- :class="
- settingsStore.editorSettings.appLayout === 'classic'
- ? ['h-full border-r border-border/80 dark:border-border/45 bg-background text-foreground font-medium']
- : ['h-7 rounded-md border text-foreground font-medium', 'border-ring']
- "
- :style="
- settingsStore.editorSettings.appLayout === 'classic'
- ? { boxShadow: '0 1px 0 0 var(--color-background)' }
- : {}
- "
+ :class="settingsStore.editorSettings.appLayout === 'classic' ? ['h-full border-r border-border/80 dark:border-border/45 bg-background text-foreground font-medium'] : ['h-7 rounded-md border text-foreground font-medium', 'border-ring']"
+ :style="settingsStore.editorSettings.appLayout === 'classic' ? { boxShadow: '0 1px 0 0 var(--color-background)' } : {}"
@click="emit('toggle-driver-store')"
>
<span class="shrink-0 text-amber-600 dark:text-amber-400">
<Package class="h-3.5 w-3.5" />
</span>
<span class="min-w-0 truncate flex-1">{{ t("toolbar.driverManager") }}</span>
- <span
- v-if="(agentDriverUpdateCount ?? 0) > 0"
- class="inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium leading-none text-white"
- :aria-label="t('toolbar.updatableDriverCount')"
- >
+ <span v-if="(agentDriverUpdateCount ?? 0) > 0" class="inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium leading-none text-white" :aria-label="t('toolbar.updatableDriverCount')">
{{ (agentDriverUpdateCount ?? 0) > 99 ? "99+" : agentDriverUpdateCount }}
</span>
<button class="rounded hover:bg-muted-foreground/20 p-0.5 shrink-0" @click.stop="emit('close-driver-store')">
diff --git a/apps/desktop/src/components/layout/AppToolbar.vue b/apps/desktop/src/components/layout/AppToolbar.vue
index 133e089000..fd6f6ba7d2 100644
--- a/apps/desktop/src/components/layout/AppToolbar.vue
+++ b/apps/desktop/src/components/layout/AppToolbar.vue
@@ -1,26 +1,7 @@
<script setup lang="ts">
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n";
-import {
- DatabaseZap,
- FilePlus2,
- Loader2,
- Languages,
- Moon,
- Sun,
- SunMoon,
- History,
- Bot,
- ArrowLeftRight,
- FileCode,
- FileStack,
- GitCompareArrows,
- TableProperties,
- Settings,
- CloudDownload,
- Package,
- Ellipsis,
-} from "@lucide/vue";
+import { DatabaseZap, FilePlus2, Loader2, Languages, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, FileStack, GitCompareArrows, TableProperties, Settings, CloudDownload, Package, Ellipsis } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import LightDropdown from "@/components/ui/LightDropdown.vue";
@@ -63,8 +44,7 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
-const { isMac, isDesktop, showControls, isMaximized, isFullscreen, minimize, toggleMaximize, close } =
- useWindowControls();
+const { isMac, isDesktop, showControls, isMaximized, isFullscreen, minimize, toggleMaximize, close } = useWindowControls();
const themeItems = computed(() => [
{ value: "light", label: t("toolbar.themeLight"), icon: Sun },
@@ -142,10 +122,7 @@ const collapsedItems = computed(() => [
},
{
value: "driver-store",
- label:
- props.agentDriverUpdateCount > 0
- ? `${t("toolbar.driverManager")} (${props.agentDriverUpdateCount})`
- : t("toolbar.driverManager"),
+ label: props.agentDriverUpdateCount > 0 ? `${t("toolbar.driverManager")} (${props.agentDriverUpdateCount})` : t("toolbar.driverManager"),
icon: Package,
action: () => emit("open-driver-store"),
disabled: false,
@@ -154,88 +131,42 @@ const collapsedItems = computed(() => [
</script>
<template>
- <div
- ref="toolbarEl"
- class="h-10 flex items-center gap-1 px-2 border-b bg-muted/30 shrink-0 overflow-hidden"
- :class="{ 'pl-17.5': shouldReserveMacTrafficLightInset(isMac, isFullscreen, isDesktop) }"
- data-tauri-drag-region
- @dblclick="onToolbarDblClick"
- >
+ <div ref="toolbarEl" class="h-10 flex items-center gap-1 px-2 border-b bg-muted/30 shrink-0 overflow-hidden" :class="{ 'pl-17.5': shouldReserveMacTrafficLightInset(isMac, isFullscreen, isDesktop) }" data-tauri-drag-region @dblclick="onToolbarDblClick">
<Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" @click="emit('new-connection')">
<DatabaseZap class="h-3.5 w-3.5" />
{{ t("toolbar.newConnection") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs gap-1"
- @click="emit('new-query')"
- :disabled="!hasConnections"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" @click="emit('new-query')" :disabled="!hasConnections">
<FilePlus2 class="h-3.5 w-3.5" />
{{ t("toolbar.newQuery") }}
</Button>
<template v-if="!toolbarCollapsed">
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs gap-1"
- @click="emit('open-transfer')"
- :disabled="!hasConnections"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" @click="emit('open-transfer')" :disabled="!hasConnections">
<ArrowLeftRight class="h-3.5 w-3.5" />
{{ t("transfer.dataTransfer") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs gap-1"
- @click="emit('open-sql-file')"
- :disabled="!hasSqlFileConnections"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" @click="emit('open-sql-file')" :disabled="!hasSqlFileConnections">
<FileCode class="h-3.5 w-3.5" />
{{ t("sqlFile.title") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs gap-1"
- @click="emit('open-schema-diff')"
- :disabled="!hasConnections"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" @click="emit('open-schema-diff')" :disabled="!hasConnections">
<GitCompareArrows class="h-3.5 w-3.5" />
{{ t("diff.title") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs gap-1"
- @click="emit('open-data-compare')"
- :disabled="!hasConnections"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" @click="emit('open-data-compare')" :disabled="!hasConnections">
<TableProperties class="h-3.5 w-3.5" />
{{ t("dataCompare.title") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs gap-1"
- :class="{ 'bg-accent': showDriverStore }"
- @click="emit('open-driver-store')"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs gap-1" :class="{ 'bg-accent': showDriverStore }" @click="emit('open-driver-store')">
<Package class="h-3.5 w-3.5" />
{{ t("toolbar.driverManager") }}
- <span
- v-if="agentDriverUpdateCount > 0"
- class="ml-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium leading-none text-white"
- :aria-label="t('toolbar.updatableDriverCount')"
- >
+ <span v-if="agentDriverUpdateCount > 0" class="ml-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium leading-none text-white" :aria-label="t('toolbar.updatableDriverCount')">
{{ agentDriverUpdateCount > 99 ? "99+" : agentDriverUpdateCount }}
</span>
</Button>
@@ -266,19 +197,10 @@ const collapsedItems = computed(() => [
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="relative h-8 w-8"
- :disabled="checkingUpdates"
- @click="emit('check-updates')"
- >
+ <Button variant="ghost" size="icon" class="relative h-8 w-8" :disabled="checkingUpdates" @click="emit('check-updates')">
<Loader2 v-if="checkingUpdates" class="h-4 w-4 animate-spin" />
<CloudDownload v-else class="h-4 w-4" />
- <span
- v-if="hasUpdateAvailable"
- class="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background"
- />
+ <span v-if="hasUpdateAvailable" class="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background" />
</Button>
</TooltipTrigger>
<TooltipContent>{{ t("updates.check") }}</TooltipContent>
@@ -288,13 +210,7 @@ const collapsedItems = computed(() => [
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8"
- :class="{ 'bg-accent': showSqlLibrary }"
- @click="emit('toggle-sql-library')"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8" :class="{ 'bg-accent': showSqlLibrary }" @click="emit('toggle-sql-library')">
<FileStack class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -303,13 +219,7 @@ const collapsedItems = computed(() => [
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8"
- :class="{ 'bg-accent': showHistory }"
- @click="emit('toggle-history')"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8" :class="{ 'bg-accent': showHistory }" @click="emit('toggle-history')">
<History class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -318,13 +228,7 @@ const collapsedItems = computed(() => [
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8"
- :class="{ 'bg-accent': showAiPanel }"
- @click="emit('toggle-ai')"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8" :class="{ 'bg-accent': showAiPanel }" @click="emit('toggle-ai')">
<Bot class="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -396,12 +300,6 @@ const collapsedItems = computed(() => [
<TooltipContent>{{ t("settings.title") }}</TooltipContent>
</Tooltip>
- <WindowControls
- v-if="showControls"
- :is-maximized="isMaximized"
- @minimize="minimize"
- @toggle-maximize="toggleMaximize"
- @close="close"
- />
+ <WindowControls v-if="showControls" :is-maximized="isMaximized" @minimize="minimize" @toggle-maximize="toggleMaximize" @close="close" />
</div>
</template>
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 6ca42a14b4..afdd547cd2 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -1,24 +1,7 @@
<script setup lang="ts">
import { computed, ref, defineAsyncComponent, watch, nextTick, onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
-import {
- Check,
- Columns3,
- Loader2,
- Search,
- Square,
- Bot,
- Table2,
- GitBranch,
- BarChart3,
- TableProperties,
- ChevronDown,
- ChevronUp,
- Inbox,
- RefreshCcw,
- Wrench,
- ListChecks,
-} from "@lucide/vue";
+import { Check, Columns3, Loader2, Search, Square, Bot, Table2, GitBranch, BarChart3, TableProperties, ChevronDown, ChevronUp, Inbox, RefreshCcw, Wrench, ListChecks } from "@lucide/vue";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { Button } from "@/components/ui/button";
@@ -153,9 +136,7 @@ const columnInfoError = ref<string | undefined>(undefined);
const dataGridRef = ref<DataGridHandle>();
const queryEditorRef = ref<InstanceType<typeof QueryEditor>>();
const columnVisibilitySearch = ref("");
-const columnVisibilityOptions = computed(
- () => dataGridRef.value?.filteredColumnVisibilityOptions(columnVisibilitySearch.value) ?? [],
-);
+const columnVisibilityOptions = computed(() => dataGridRef.value?.filteredColumnVisibilityOptions(columnVisibilitySearch.value) ?? []);
const redisKeyBrowserRef = ref<SearchableBrowserHandle>();
const etcdKeyBrowserRef = ref<SearchableBrowserHandle>();
const objectBrowserRef = ref<SearchableBrowserHandle>();
@@ -182,8 +163,7 @@ const activeSqlFormatDialect = computed<SqlFormatDialect>(() => {
});
const editorDialect = computed<"mysql" | "postgres" | "sqlserver">(() => {
- if (activeEffectiveDatabaseType.value === "postgres" || activeEffectiveDatabaseType.value === "kwdb")
- return "postgres";
+ if (activeEffectiveDatabaseType.value === "postgres" || activeEffectiveDatabaseType.value === "kwdb") return "postgres";
if (activeEffectiveDatabaseType.value === "sqlserver") return "sqlserver";
return "mysql";
});
@@ -207,14 +187,7 @@ const activeQueryError = computed(() => {
if (!result?.columns.includes("Error")) return "";
return String(result.rows[0]?.[0] ?? "");
});
-const hasQueryOutput = computed(
- () =>
- !!props.activeTab.result ||
- !!props.activeTab.explainPlan ||
- !!props.activeTab.explainError ||
- props.activeTab.isExecuting === true ||
- props.activeTab.isExplaining === true,
-);
+const hasQueryOutput = computed(() => !!props.activeTab.result || !!props.activeTab.explainPlan || !!props.activeTab.explainError || props.activeTab.isExecuting === true || props.activeTab.isExplaining === true);
const tabularResults = computed(() => tabularResultItems(props.activeTab.results));
const summaryItems = computed(() => executionSummaryItems(props.activeTab));
const hasExecutionSummary = computed(() => summaryItems.value.length > 0 || props.activeTab.isExecuting);
@@ -245,11 +218,7 @@ function startQueryRunningElapsedTimer() {
const queryRunningElapsedSeconds = computed(() => (queryRunningElapsed.value / 1000).toFixed(1));
-watch(
- () => [props.activeTab.id, props.activeTab.isExecuting, props.activeTab.queryExecutionStartedAt] as const,
- startQueryRunningElapsedTimer,
- { immediate: true },
-);
+watch(() => [props.activeTab.id, props.activeTab.isExecuting, props.activeTab.queryExecutionStartedAt] as const, startQueryRunningElapsedTimer, { immediate: true });
onUnmounted(stopQueryRunningElapsedTimer);
@@ -329,10 +298,7 @@ watch(
);
// Column info panel handlers
-async function onHandleClickColumn(
- matchedCols: Array<{ name: string; table: string; schema?: string }>,
- errorMsg?: string,
-) {
+async function onHandleClickColumn(matchedCols: Array<{ name: string; table: string; schema?: string }>, errorMsg?: string) {
if (!props.activeTab.connectionId || !props.activeTab.database) return;
// If error or no columns, silently ignore — don't show the panel
@@ -349,12 +315,7 @@ async function onHandleClickColumn(
for (const matchedCol of matchedCols) {
const querySchema = matchedCol.schema || props.activeTab.database || "";
try {
- const fullColumns = await apiModule.getColumns(
- props.activeTab.connectionId,
- props.activeTab.database,
- querySchema,
- matchedCol.table,
- );
+ const fullColumns = await apiModule.getColumns(props.activeTab.connectionId, props.activeTab.database, querySchema, matchedCol.table);
for (const col of fullColumns) {
if (col.name === matchedCol.name) {
results.push({
@@ -462,20 +423,8 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
@click-column="onHandleClickColumn"
@close-column-panel="onHandleCloseColumnPanel"
/>
- <ColumnInfoPanel
- v-if="showColumnInfo"
- :columns="columnInfoColumns"
- :loading="columnInfoLoading"
- :error="columnInfoError"
- @close="closeColumnInfo"
- />
- <Button
- v-if="hasQueryOutput && !resultsPaneOpen"
- variant="secondary"
- size="sm"
- class="absolute bottom-3 right-3 z-20 h-7 gap-1.5 rounded-full border bg-background/95 px-3 text-xs shadow-lg backdrop-blur hover:bg-accent"
- @click="resultsPaneOpen = true"
- >
+ <ColumnInfoPanel v-if="showColumnInfo" :columns="columnInfoColumns" :loading="columnInfoLoading" :error="columnInfoError" @close="closeColumnInfo" />
+ <Button v-if="hasQueryOutput && !resultsPaneOpen" variant="secondary" size="sm" class="absolute bottom-3 right-3 z-20 h-7 gap-1.5 rounded-full border bg-background/95 px-3 text-xs shadow-lg backdrop-blur hover:bg-accent" @click="resultsPaneOpen = true">
<ChevronUp class="h-3.5 w-3.5" />
{{ t("editor.showResultsPane") }}
</Button>
@@ -483,18 +432,8 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
</Pane>
<Pane v-if="resultsPaneOpen" :size="60" :min-size="20">
<div class="h-full flex flex-col">
- <div
- v-if="hasQueryOutput"
- class="h-8 shrink-0 border-b bg-muted/20 px-2 flex items-center gap-1 overflow-x-auto"
- style="scrollbar-width: none; -ms-overflow-style: none; -webkit-overflow-scrolling: touch"
- >
- <Button
- size="sm"
- :variant="activeOutputView === 'result' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs"
- :disabled="!hasTabularResult && !activeTab.isExecuting"
- @click="emit('update:activeOutputView', 'result')"
- >
+ <div v-if="hasQueryOutput" class="h-8 shrink-0 border-b bg-muted/20 px-2 flex items-center gap-1 overflow-x-auto" style="scrollbar-width: none; -ms-overflow-style: none; -webkit-overflow-scrolling: touch">
+ <Button size="sm" :variant="activeOutputView === 'result' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs" :disabled="!hasTabularResult && !activeTab.isExecuting" @click="emit('update:activeOutputView', 'result')">
{{ t("tabs.tableData") }}
</Button>
<template v-if="tabularResults.length > 1">
@@ -503,9 +442,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
v-for="item in tabularResults"
:key="item.index"
size="sm"
- :variant="
- activeOutputView === 'result' && activeTab.activeResultIndex === item.index ? 'default' : 'ghost'
- "
+ :variant="activeOutputView === 'result' && activeTab.activeResultIndex === item.index ? 'default' : 'ghost'"
class="h-6 px-2 text-xs shrink-0"
@click="
queryStore.setActiveResultIndex(activeTab.id, item.index);
@@ -515,34 +452,16 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
{{ t("tabs.resultN", { n: item.n }) }}
</Button>
</template>
- <Button
- size="sm"
- :variant="activeOutputView === 'summary' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs gap-1"
- :disabled="!hasExecutionSummary"
- @click="emit('update:activeOutputView', 'summary')"
- >
+ <Button size="sm" :variant="activeOutputView === 'summary' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" :disabled="!hasExecutionSummary" @click="emit('update:activeOutputView', 'summary')">
<ListChecks class="h-3.5 w-3.5" />
{{ t("tabs.executionSummary") }}
</Button>
- <Button
- size="sm"
- :variant="activeOutputView === 'chart' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs gap-1"
- :disabled="!hasNumericData"
- @click="emit('update:activeOutputView', 'chart')"
- >
+ <Button size="sm" :variant="activeOutputView === 'chart' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" :disabled="!hasNumericData" @click="emit('update:activeOutputView', 'chart')">
<BarChart3 class="h-3.5 w-3.5" />
{{ t("chart.title") }}
</Button>
<span class="mx-1 h-4 w-px shrink-0 bg-border" />
- <Button
- size="sm"
- :variant="activeOutputView === 'explain' ? 'secondary' : 'ghost'"
- class="h-6 px-2 text-xs gap-1"
- :disabled="!activeTab.explainPlan && !activeTab.explainError && !activeTab.isExplaining"
- @click="emit('update:activeOutputView', 'explain')"
- >
+ <Button size="sm" :variant="activeOutputView === 'explain' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" :disabled="!activeTab.explainPlan && !activeTab.explainError && !activeTab.isExplaining" @click="emit('update:activeOutputView', 'explain')">
<GitBranch class="h-3.5 w-3.5" />
{{ t("explain.title") }}
</Button>
@@ -561,152 +480,70 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
<Wrench class="h-4 w-4" />
</Button>
</PopoverTrigger>
- <PopoverContent
- align="end"
- class="w-max min-w-44 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="end" class="w-max min-w-44 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-3 py-2">
<div class="text-xs font-semibold">{{ t("grid.viewOptions") }}</div>
</div>
- <LightTooltip
- :text="t('grid.transposeMultiRowHint')"
- side="left"
- :side-offset="6"
- :delay="0"
- :open-on-focus="false"
- >
- <label
- class="flex cursor-pointer items-center justify-between gap-3 px-3 py-2 text-xs hover:bg-accent"
- >
+ <LightTooltip :text="t('grid.transposeMultiRowHint')" side="left" :side-offset="6" :delay="0" :open-on-focus="false">
+ <label class="flex cursor-pointer items-center justify-between gap-3 px-3 py-2 text-xs hover:bg-accent">
<span class="min-w-0 flex items-center gap-1.5 font-medium">
{{ t("grid.transposeMultiRowToggle") }}
<span class="text-muted-foreground">
- {{
- dataGridRef?.multiRowTranspose ? t("grid.transposeMultiRow") : t("grid.transposeSingleRow")
- }}
+ {{ dataGridRef?.multiRowTranspose ? t("grid.transposeMultiRow") : t("grid.transposeSingleRow") }}
</span>
</span>
- <Switch
- size="sm"
- :model-value="!!dataGridRef?.multiRowTranspose"
- :aria-label="t('grid.transposeMultiRow')"
- @update:model-value="(value: boolean) => dataGridRef?.setMultiRowTranspose(value)"
- />
+ <Switch size="sm" :model-value="!!dataGridRef?.multiRowTranspose" :aria-label="t('grid.transposeMultiRow')" @update:model-value="(value: boolean) => dataGridRef?.setMultiRowTranspose(value)" />
</label>
</LightTooltip>
- <label
- class="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs hover:bg-accent"
- :class="{ 'cursor-not-allowed opacity-60': !dataGridRef?.canToggleAllNullColumns }"
- >
- <input
- type="checkbox"
- class="h-3.5 w-3.5 shrink-0 accent-primary"
- :checked="!!dataGridRef?.nullColumnsHidden"
- :disabled="!dataGridRef?.canToggleAllNullColumns"
- @change="dataGridRef?.toggleAllNullColumns()"
- />
+ <label class="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs hover:bg-accent" :class="{ 'cursor-not-allowed opacity-60': !dataGridRef?.canToggleAllNullColumns }">
+ <input type="checkbox" class="h-3.5 w-3.5 shrink-0 accent-primary" :checked="!!dataGridRef?.nullColumnsHidden" :disabled="!dataGridRef?.canToggleAllNullColumns" @change="dataGridRef?.toggleAllNullColumns()" />
<span class="min-w-0 flex items-center gap-1 font-medium">
{{ t("grid.hideNullColumns") }}
- <span
- v-if="(dataGridRef?.allNullColumnCount ?? 0) > 0"
- class="text-muted-foreground tabular-nums"
- >
- ({{ dataGridRef?.allNullColumnCount }})
- </span>
+ <span v-if="(dataGridRef?.allNullColumnCount ?? 0) > 0" class="text-muted-foreground tabular-nums"> ({{ dataGridRef?.allNullColumnCount }}) </span>
</span>
</label>
</PopoverContent>
</Popover>
- <Button
- v-if="activeOutputView === 'result' && hasTabularResult"
- variant="ghost"
- size="sm"
- class="h-6 shrink-0 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
- :disabled="activeTab.isExecuting"
- @click="refreshData"
- >
+ <Button v-if="activeOutputView === 'result' && hasTabularResult" variant="ghost" size="sm" class="h-6 shrink-0 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground" :disabled="activeTab.isExecuting" @click="refreshData">
<Loader2 v-if="activeTab.isExecuting" class="h-3.5 w-3.5 animate-spin" />
<RefreshCcw v-else class="h-3.5 w-3.5" />
{{ t("grid.refresh") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-6 shrink-0 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
- :class="{ 'ml-auto': activeOutputView !== 'result' || !hasTabularResult }"
- @click="resultsPaneOpen = false"
- >
+ <Button variant="ghost" size="sm" class="h-6 shrink-0 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground" :class="{ 'ml-auto': activeOutputView !== 'result' || !hasTabularResult }" @click="resultsPaneOpen = false">
<ChevronDown class="h-3.5 w-3.5" />
{{ t("editor.hideResultsPane") }}
</Button>
</div>
- <ExplainPlanViewer
- v-if="activeOutputView === 'explain'"
- class="flex-1 min-h-0"
- :plan="activeTab.explainPlan"
- :error="activeTab.explainError"
- :loading="activeTab.isExplaining"
- :source-sql="activeTab.lastExplainedSql"
- :explain-sql="activeTab.explainSql"
- />
+ <ExplainPlanViewer v-if="activeOutputView === 'explain'" class="flex-1 min-h-0" :plan="activeTab.explainPlan" :error="activeTab.explainError" :loading="activeTab.isExplaining" :source-sql="activeTab.lastExplainedSql" :explain-sql="activeTab.explainSql" />
- <QueryChart
- v-else-if="activeOutputView === 'chart' && activeTab.result"
- class="flex-1 min-h-0"
- :result="activeTab.result"
- />
+ <QueryChart v-else-if="activeOutputView === 'chart' && activeTab.result" class="flex-1 min-h-0" :result="activeTab.result" />
<div v-else-if="activeOutputView === 'summary'" class="flex-1 min-h-0 overflow-auto bg-background">
- <div
- v-if="activeTab.isExecuting"
- class="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
+ <div v-if="activeTab.isExecuting" class="flex h-full items-center justify-center text-sm text-muted-foreground">
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
{{ t("executionSummary.executing") }}
</div>
- <div
- v-else-if="summaryItems.length === 0"
- class="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
+ <div v-else-if="summaryItems.length === 0" class="flex h-full items-center justify-center text-sm text-muted-foreground">
{{ t("executionSummary.empty") }}
</div>
<div v-else>
<div class="overflow-hidden border-b">
- <div
- class="grid grid-cols-[4rem_1fr_8rem_8rem_7rem] border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground"
- >
+ <div class="grid grid-cols-[4rem_1fr_8rem_8rem_7rem] border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">
<div>{{ t("executionSummary.statement") }}</div>
<div>{{ t("executionSummary.type") }}</div>
<div class="text-right">{{ t("executionSummary.rows") }}</div>
<div class="text-right">{{ t("executionSummary.affected") }}</div>
<div class="text-right">{{ t("executionSummary.time") }}</div>
</div>
- <div
- v-for="item in summaryItems"
- :key="item.index"
- class="grid grid-cols-[4rem_1fr_8rem_8rem_7rem] items-center border-b px-3 py-2 text-xs last:border-b-0"
- >
+ <div v-for="item in summaryItems" :key="item.index" class="grid grid-cols-[4rem_1fr_8rem_8rem_7rem] items-center border-b px-3 py-2 text-xs last:border-b-0">
<div class="font-mono text-muted-foreground">#{{ item.index + 1 }}</div>
<div class="flex min-w-0 items-center gap-2">
- <span
- class="inline-flex h-5 items-center rounded-full border px-2 text-[10px]"
- :class="
- item.isError
- ? 'border-destructive/40 bg-destructive/10 text-destructive'
- : 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
- "
- >
+ <span class="inline-flex h-5 items-center rounded-full border px-2 text-[10px]" :class="item.isError ? 'border-destructive/40 bg-destructive/10 text-destructive' : 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'">
{{ item.isError ? t("executionSummary.error") : t("executionSummary.success") }}
</span>
<span class="truncate">
- {{
- item.hasTabularResult
- ? t("executionSummary.returnedTable", { count: item.returnedColumns })
- : t("executionSummary.noTable")
- }}
+ {{ item.hasTabularResult ? t("executionSummary.returnedTable", { count: item.returnedColumns }) : t("executionSummary.noTable") }}
</span>
</div>
<div class="text-right tabular-nums">{{ item.returnedRows.toLocaleString() }}</div>
@@ -747,51 +584,25 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
:on-execute-sql="async (sql: string) => emit('executeSql', sql)"
:full-export-result="() => queryStore.fetchTabResultForExport(activeTab.id)"
@update:order-by-input="(v: string) => (activeTab.orderByInput = v)"
- @reload="
- (
- sql?: string,
- searchText?: string,
- whereInput?: string,
- orderBy?: string,
- limit?: number,
- offset?: number,
- ) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset)
- "
- @paginate="
- (offset: number, limit: number, whereInput?: string, orderBy?: string) =>
- emit('paginate', offset, limit, whereInput, orderBy)
- "
- @sort="
- (column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string) =>
- emit('sort', column, columnIndex, direction, whereInput)
- "
+ @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset)"
+ @paginate="(offset: number, limit: number, whereInput?: string, orderBy?: string) => emit('paginate', offset, limit, whereInput, orderBy)"
+ @sort="(column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string) => emit('sort', column, columnIndex, direction, whereInput)"
>
<template v-if="activeTab.result?.columns.includes('Error')" #error-actions="{ errorMessage }">
- <Button
- variant="outline"
- size="sm"
- class="mt-2 h-7 gap-1.5 border-destructive/30 bg-background px-2.5 text-xs text-destructive hover:bg-destructive/10 hover:text-destructive"
- @click="emit('fixWithAi', String(errorMessage))"
- >
+ <Button variant="outline" size="sm" class="mt-2 h-7 gap-1.5 border-destructive/30 bg-background px-2.5 text-xs text-destructive hover:bg-destructive/10 hover:text-destructive" @click="emit('fixWithAi', String(errorMessage))">
<Bot class="h-3.5 w-3.5" />
{{ t("ai.fixWithAi") }}
</Button>
</template>
</DataGrid>
- <div
- v-else-if="!activeTab.result && activeTab.isExecuting"
- class="flex-1 min-h-0 flex flex-col items-center justify-center gap-3 text-muted-foreground text-sm"
- >
+ <div v-else-if="!activeTab.result && activeTab.isExecuting" class="flex-1 min-h-0 flex flex-col items-center justify-center gap-3 text-muted-foreground text-sm">
<div class="flex items-center">
<Loader2 class="h-5 w-5 animate-spin mr-2" />
{{ t(queryExecutionLabelKey(activeTab)) }}
<span class="ml-1 tabular-nums text-muted-foreground/80">· {{ queryRunningElapsedSeconds }}s</span>
</div>
</div>
- <div
- v-else-if="!activeTab.result"
- class="flex-1 min-h-0 flex flex-col items-center justify-center gap-1 text-muted-foreground text-sm"
- >
+ <div v-else-if="!activeTab.result" class="flex-1 min-h-0 flex flex-col items-center justify-center gap-1 text-muted-foreground text-sm">
<div>{{ t("editor.pressToExecute", { mod: shortcutModifier }) }}</div>
<div>{{ t("editor.pressToSaveSql", { mod: shortcutModifier }) }}</div>
</div>
@@ -805,128 +616,61 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
<template v-else-if="activeTab.mode === 'data'">
<div class="flex-1 min-h-0 flex flex-col">
<div class="h-9 shrink-0 border-b bg-background/80 px-3 flex items-center gap-2 text-xs">
- <span
- class="inline-flex items-center gap-1 rounded border border-emerald-200 bg-emerald-50 px-2 py-0.5 font-medium text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300"
- >
+ <span class="inline-flex items-center gap-1 rounded border border-emerald-200 bg-emerald-50 px-2 py-0.5 font-medium text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300">
<Table2 class="h-3.5 w-3.5" />
{{ t("tabs.tableData") }}
</span>
- <span
- class="inline-flex items-center rounded border border-border bg-muted/50 px-2 py-0.5 font-medium truncate"
- >
+ <span class="inline-flex items-center rounded border border-border bg-muted/50 px-2 py-0.5 font-medium truncate">
{{ activeTab.tableMeta?.tableName || activeTab.title }}
</span>
- <span
- class="inline-flex items-center rounded border border-border bg-muted/30 px-2 py-0.5 text-muted-foreground truncate"
- >
- <template v-if="activeTab.tableMeta?.schema">{{ activeTab.tableMeta.schema }}@</template
- >{{ databaseDisplayNameForTab(activeTab.connectionId, activeTab.database, t) }}
- </span>
- <span v-if="activeTab.tableMeta" class="ml-auto text-muted-foreground">
- {{ activeTab.tableMeta.columns.length }} {{ t("tree.columns") }}
+ <span class="inline-flex items-center rounded border border-border bg-muted/30 px-2 py-0.5 text-muted-foreground truncate">
+ <template v-if="activeTab.tableMeta?.schema">{{ activeTab.tableMeta.schema }}@</template>{{ databaseDisplayNameForTab(activeTab.connectionId, activeTab.database, t) }}
</span>
+ <span v-if="activeTab.tableMeta" class="ml-auto text-muted-foreground"> {{ activeTab.tableMeta.columns.length }} {{ t("tree.columns") }} </span>
<Popover v-if="activeTab.result?.columns.length">
<PopoverTrigger as-child>
- <Button
- variant="ghost"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- :class="{ 'bg-accent text-foreground': (dataGridRef?.hiddenColumnCount ?? 0) > 0 }"
- >
+ <Button variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" :class="{ 'bg-accent text-foreground': (dataGridRef?.hiddenColumnCount ?? 0) > 0 }">
<Columns3 class="h-3.5 w-3.5" />
{{ t("grid.columnVisibility") }}
- <span v-if="(dataGridRef?.hiddenColumnCount ?? 0) > 0" class="tabular-nums">
- {{ dataGridRef?.visibleColumnCount }}/{{ dataGridRef?.displayableColumnCount }}
- </span>
+ <span v-if="(dataGridRef?.hiddenColumnCount ?? 0) > 0" class="tabular-nums"> {{ dataGridRef?.visibleColumnCount }}/{{ dataGridRef?.displayableColumnCount }} </span>
</Button>
</PopoverTrigger>
- <PopoverContent
- align="end"
- class="w-64 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="end" class="w-64 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-2 py-1.5">
<div class="flex items-center justify-between gap-2">
<div class="text-xs font-semibold">{{ t("grid.columnVisibility") }}</div>
- <div class="text-[10px] text-muted-foreground tabular-nums">
- {{ dataGridRef?.visibleColumnCount ?? 0 }}/{{ dataGridRef?.displayableColumnCount ?? 0 }}
- </div>
+ <div class="text-[10px] text-muted-foreground tabular-nums">{{ dataGridRef?.visibleColumnCount ?? 0 }}/{{ dataGridRef?.displayableColumnCount ?? 0 }}</div>
</div>
</div>
<div class="flex items-center gap-1.5 border-b px-2 py-1.5">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <input
- v-model="columnVisibilitySearch"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="h-6 min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground"
- :placeholder="t('grid.searchColumns')"
- />
+ <input v-model="columnVisibilitySearch" autocapitalize="off" autocorrect="off" spellcheck="false" class="h-6 min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground" :placeholder="t('grid.searchColumns')" />
</div>
<div class="max-h-72 overflow-auto py-0.5">
- <button
- v-for="option in columnVisibilityOptions"
- :key="`${option.index}:${option.column}`"
- type="button"
- class="grid w-full grid-cols-[1.5rem_minmax(0,1fr)] items-center px-2 py-1 text-left text-xs hover:bg-accent"
- @click="dataGridRef?.toggleColumnVisibility(option.index)"
- >
- <span
- class="flex h-4 w-4 items-center justify-center rounded border"
- :class="
- dataGridRef?.isColumnVisible(option.index)
- ? 'border-primary bg-primary text-primary-foreground'
- : 'border-border bg-background text-transparent'
- "
- >
+ <button v-for="option in columnVisibilityOptions" :key="`${option.index}:${option.column}`" type="button" class="grid w-full grid-cols-[1.5rem_minmax(0,1fr)] items-center px-2 py-1 text-left text-xs hover:bg-accent" @click="dataGridRef?.toggleColumnVisibility(option.index)">
+ <span class="flex h-4 w-4 items-center justify-center rounded border" :class="dataGridRef?.isColumnVisible(option.index) ? 'border-primary bg-primary text-primary-foreground' : 'border-border bg-background text-transparent'">
<Check class="h-3 w-3 stroke-[3]" />
</span>
<span class="truncate font-mono text-xs" :title="option.column">{{ option.column }}</span>
</button>
- <div
- v-if="columnVisibilityOptions.length === 0"
- class="px-2 py-6 text-center text-xs text-muted-foreground"
- >
+ <div v-if="columnVisibilityOptions.length === 0" class="px-2 py-6 text-center text-xs text-muted-foreground">
{{ t("grid.noSearchResults") }}
</div>
</div>
<div class="flex items-center justify-between gap-2 border-t bg-muted/30 px-2 py-1.5">
<span class="text-[11px] text-muted-foreground">{{ t("grid.columnVisibilityHint") }}</span>
<div class="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- class="h-7 px-2 text-xs"
- :disabled="(dataGridRef?.displayableColumnCount ?? 0) <= 1"
- @click="dataGridRef?.invertColumnVisibility()"
- >
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="(dataGridRef?.displayableColumnCount ?? 0) <= 1" @click="dataGridRef?.invertColumnVisibility()">
{{ t("grid.invertColumnVisibility") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-7 px-2 text-xs"
- :disabled="(dataGridRef?.hiddenColumnCount ?? 0) === 0"
- @click="dataGridRef?.showAllColumns()"
- >
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="(dataGridRef?.hiddenColumnCount ?? 0) === 0" @click="dataGridRef?.showAllColumns()">
{{ t("grid.showAllColumns") }}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
- <Button
- v-if="activeTab.tableMeta && activeTab.connectionId"
- variant="ghost"
- size="sm"
- class="h-5 text-xs px-1.5 shrink-0"
- :class="{ 'bg-accent': dataGridRef?.showDdl }"
- @click="dataGridRef?.toggleDdl()"
- >
- <TableProperties class="h-3.5 w-3.5" /> {{ t("grid.tableInfo") }}
- </Button>
+ <Button v-if="activeTab.tableMeta && activeTab.connectionId" variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" :class="{ 'bg-accent': dataGridRef?.showDdl }" @click="dataGridRef?.toggleDdl()"> <TableProperties class="h-3.5 w-3.5" /> {{ t("grid.tableInfo") }} </Button>
<Popover v-if="activeTab.result?.columns.length">
<PopoverTrigger as-child>
<Button
@@ -942,22 +686,11 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
<Wrench class="h-4 w-4" />
</Button>
</PopoverTrigger>
- <PopoverContent
- align="end"
- class="w-max min-w-44 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="end" class="w-max min-w-44 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-3 py-2">
<div class="text-xs font-semibold">{{ t("grid.viewOptions") }}</div>
</div>
- <LightTooltip
- :text="t('grid.transposeMultiRowHint')"
- side="left"
- :side-offset="6"
- :delay="0"
- :open-on-focus="false"
- >
+ <LightTooltip :text="t('grid.transposeMultiRowHint')" side="left" :side-offset="6" :delay="0" :open-on-focus="false">
<label class="flex cursor-pointer items-center justify-between gap-3 px-3 py-2 text-xs hover:bg-accent">
<span class="min-w-0 flex items-center gap-1.5 font-medium">
{{ t("grid.transposeMultiRowToggle") }}
@@ -965,30 +698,14 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
{{ dataGridRef?.multiRowTranspose ? t("grid.transposeMultiRow") : t("grid.transposeSingleRow") }}
</span>
</span>
- <Switch
- size="sm"
- :model-value="!!dataGridRef?.multiRowTranspose"
- :aria-label="t('grid.transposeMultiRow')"
- @update:model-value="(value: boolean) => dataGridRef?.setMultiRowTranspose(value)"
- />
+ <Switch size="sm" :model-value="!!dataGridRef?.multiRowTranspose" :aria-label="t('grid.transposeMultiRow')" @update:model-value="(value: boolean) => dataGridRef?.setMultiRowTranspose(value)" />
</label>
</LightTooltip>
- <label
- class="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs hover:bg-accent"
- :class="{ 'cursor-not-allowed opacity-60': !dataGridRef?.canToggleAllNullColumns }"
- >
- <input
- type="checkbox"
- class="h-3.5 w-3.5 shrink-0 accent-primary"
- :checked="!!dataGridRef?.nullColumnsHidden"
- :disabled="!dataGridRef?.canToggleAllNullColumns"
- @change="dataGridRef?.toggleAllNullColumns()"
- />
+ <label class="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs hover:bg-accent" :class="{ 'cursor-not-allowed opacity-60': !dataGridRef?.canToggleAllNullColumns }">
+ <input type="checkbox" class="h-3.5 w-3.5 shrink-0 accent-primary" :checked="!!dataGridRef?.nullColumnsHidden" :disabled="!dataGridRef?.canToggleAllNullColumns" @change="dataGridRef?.toggleAllNullColumns()" />
<span class="min-w-0 flex items-center gap-1 font-medium">
{{ t("grid.hideNullColumns") }}
- <span v-if="(dataGridRef?.allNullColumnCount ?? 0) > 0" class="text-muted-foreground tabular-nums">
- ({{ dataGridRef?.allNullColumnCount }})
- </span>
+ <span v-if="(dataGridRef?.allNullColumnCount ?? 0) > 0" class="text-muted-foreground tabular-nums"> ({{ dataGridRef?.allNullColumnCount }}) </span>
</span>
</label>
</PopoverContent>
@@ -1020,41 +737,17 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
:full-export-result="() => queryStore.fetchTabResultForExport(activeTab.id)"
@update:where-input="(v: string) => (activeTab.whereInput = v)"
@update:order-by-input="(v: string) => (activeTab.orderByInput = v)"
- @reload="
- (
- sql?: string,
- searchText?: string,
- whereInput?: string,
- orderBy?: string,
- limit?: number,
- offset?: number,
- ) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset)
- "
- @paginate="
- (offset: number, limit: number, whereInput?: string, orderBy?: string) =>
- emit('paginate', offset, limit, whereInput, orderBy)
- "
- @sort="
- (column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string) =>
- emit('sort', column, columnIndex, direction, whereInput)
- "
+ @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset)"
+ @paginate="(offset: number, limit: number, whereInput?: string, orderBy?: string) => emit('paginate', offset, limit, whereInput, orderBy)"
+ @sort="(column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string) => emit('sort', column, columnIndex, direction, whereInput)"
/>
- <div
- v-else-if="activeTab.isExecuting"
- class="h-full flex flex-col items-center justify-center gap-3 text-muted-foreground text-sm"
- >
+ <div v-else-if="activeTab.isExecuting" class="h-full flex flex-col items-center justify-center gap-3 text-muted-foreground text-sm">
<div class="flex items-center">
<Loader2 class="h-5 w-5 animate-spin mr-2" />
{{ t(queryExecutionLabelKey(activeTab)) }}
<span class="ml-1 tabular-nums text-muted-foreground/80">· {{ queryRunningElapsedSeconds }}s</span>
</div>
- <Button
- variant="destructive"
- size="sm"
- class="h-7 gap-1.5"
- :disabled="!canCancelQueryExecution(activeTab)"
- @click="emit('cancel')"
- >
+ <Button variant="destructive" size="sm" class="h-7 gap-1.5" :disabled="!canCancelQueryExecution(activeTab)" @click="emit('cancel')">
<Loader2 v-if="activeTab.isCancelling" class="h-3.5 w-3.5 animate-spin" />
<Square v-else class="h-3.5 w-3.5 fill-current" />
{{ t("toolbar.stopQuery") }}
@@ -1065,12 +758,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
<div>{{ t("grid.dataUnavailable") }}</div>
<div class="text-xs text-muted-foreground/70 inline-flex items-center gap-1">
<span>{{ t("grid.dataUnavailableHintPrefix") }}</span>
- <kbd
- v-for="key in modRKeys"
- :key="key"
- class="min-w-5 rounded border border-border/60 bg-muted/50 px-1.5 py-0.5 text-center font-mono text-[12px] leading-none text-muted-foreground shadow-xs"
- >{{ key }}</kbd
- >
+ <kbd v-for="key in modRKeys" :key="key" class="min-w-5 rounded border border-border/60 bg-muted/50 px-1.5 py-0.5 text-center font-mono text-[12px] leading-none text-muted-foreground shadow-xs">{{ key }}</kbd>
<span>{{ t("grid.dataUnavailableHintSuffix") }}</span>
</div>
<Button variant="outline" size="sm" class="h-7 gap-1.5" @click="emit('reload')">
@@ -1084,12 +772,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
<!-- Redis mode: key browser -->
<template v-else-if="activeTab.mode === 'redis'">
<div class="flex-1 min-h-0">
- <RedisKeyBrowser
- ref="redisKeyBrowserRef"
- :key="activeTab.id"
- :connection-id="activeTab.connectionId"
- :db="Number(activeTab.database)"
- />
+ <RedisKeyBrowser ref="redisKeyBrowserRef" :key="activeTab.id" :connection-id="activeTab.connectionId" :db="Number(activeTab.database)" />
</div>
</template>
@@ -1103,12 +786,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
<!-- MongoDB mode: document browser -->
<template v-else-if="activeTab.mode === 'mongo'">
<div class="flex-1 min-h-0">
- <MongoDocBrowser
- :key="activeTab.id"
- :connection-id="activeTab.connectionId"
- :database="activeTab.database"
- :collection="activeTab.sql"
- />
+ <MongoDocBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :collection="activeTab.sql" />
</div>
</template>
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 20a3f1a2c2..4c874f5dc2 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -1,19 +1,7 @@
<script setup lang="ts">
import { computed, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
-import {
- Play,
- Loader2,
- Square,
- Database,
- Check,
- Table2,
- AlignLeft,
- GitBranch,
- Save,
- FolderOpen,
- Layers,
-} from "@lucide/vue";
+import { Play, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, Layers } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SearchableSelect } from "@/components/ui/searchable-select";
@@ -73,11 +61,7 @@ const saveTooltip = computed(() => (props.activeTab.objectSource ? t("objects.sa
const showSchemaSelector = computed(() => {
const connection = props.activeConnection;
- return (
- connection &&
- isSchemaAware(connection.id) &&
- (props.activeTab.database || isSingleDb.value || hasDefaultDatabaseOption.value)
- );
+ return connection && isSchemaAware(connection.id) && (props.activeTab.database || isSingleDb.value || hasDefaultDatabaseOption.value);
});
const activeSchemaOptions = computed(() => {
@@ -116,10 +100,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
</script>
<template>
- <div
- class="h-9 shrink-0 border-b bg-background/80 px-3 flex items-center gap-1 text-xs text-muted-foreground relative z-10"
- :style="toolbarStyle"
- >
+ <div class="h-9 shrink-0 border-b bg-background/80 px-3 flex items-center gap-1 text-xs text-muted-foreground relative z-10" :style="toolbarStyle">
<div class="flex items-center gap-0.5">
<Tooltip>
<TooltipTrigger as-child>
@@ -127,14 +108,8 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
:variant="activeTab.isExecuting ? 'destructive' : 'ghost'"
size="icon"
class="h-6 w-6"
- :class="
- activeTab.isExecuting
- ? ''
- : 'bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/20 hover:text-emerald-800 dark:text-emerald-300 dark:hover:text-emerald-200'
- "
- :disabled="
- activeTab.isCancelling || activeTab.isExplaining || (!activeTab.isExecuting && !executableSql.trim())
- "
+ :class="activeTab.isExecuting ? '' : 'bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/20 hover:text-emerald-800 dark:text-emerald-300 dark:hover:text-emerald-200'"
+ :disabled="activeTab.isCancelling || activeTab.isExplaining || (!activeTab.isExecuting && !executableSql.trim())"
@click="activeTab.isExecuting ? emit('cancel') : emit('execute')"
>
<Loader2 v-if="activeTab.isCancelling" class="h-3.5 w-3.5 animate-spin" />
@@ -142,9 +117,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
<Play v-else class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
- <TooltipContent>{{
- activeTab.isExecuting ? t("toolbar.stopQuery") : t("toolbar.executeShortcut")
- }}</TooltipContent>
+ <TooltipContent>{{ activeTab.isExecuting ? t("toolbar.stopQuery") : t("toolbar.executeShortcut") }}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
@@ -152,11 +125,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
:variant="activeTab.isExplaining ? 'destructive' : 'ghost'"
size="icon"
class="h-6 w-6"
- :class="
- activeTab.isExplaining
- ? ''
- : 'text-violet-600 hover:bg-violet-500/10 hover:text-violet-700 dark:text-violet-300 dark:hover:text-violet-200'
- "
+ :class="activeTab.isExplaining ? '' : 'text-violet-600 hover:bg-violet-500/10 hover:text-violet-700 dark:text-violet-300 dark:hover:text-violet-200'"
:disabled="activeTab.isExecuting || (!activeTab.isExplaining && !executableSql.trim())"
@click="activeTab.isExplaining ? emit('cancel') : emit('explain')"
>
@@ -164,9 +133,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
<GitBranch v-else class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
- <TooltipContent>{{
- activeTab.isExplaining ? t("toolbar.stopExplain") : t("toolbar.explainPlan")
- }}</TooltipContent>
+ <TooltipContent>{{ activeTab.isExplaining ? t("toolbar.stopExplain") : t("toolbar.explainPlan") }}</TooltipContent>
</Tooltip>
<!-- Autotrace toggle (only for DM) -->
<Button
@@ -174,11 +141,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
variant="ghost"
size="icon"
class="h-6 w-6"
- :class="
- props.explainMode === 'autotrace'
- ? 'text-green-600 bg-green-100 dark:text-green-300 dark:bg-green-900/30'
- : 'text-muted-foreground/50'
- "
+ :class="props.explainMode === 'autotrace' ? 'text-green-600 bg-green-100 dark:text-green-300 dark:bg-green-900/30' : 'text-muted-foreground/50'"
:disabled="activeTab.isExecuting"
@click="emit('update:explainMode', props.explainMode === 'autotrace' ? 'explain' : 'autotrace')"
>
@@ -186,13 +149,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
</Button>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6 text-amber-600 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-300 dark:hover:text-amber-200"
- :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()"
- @click="emit('formatSql')"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-amber-600 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-300 dark:hover:text-amber-200" :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()" @click="emit('formatSql')">
<AlignLeft class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
@@ -200,13 +157,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6 text-blue-600 hover:bg-blue-500/10 hover:text-blue-700 dark:text-blue-300 dark:hover:text-blue-200"
- :disabled="!activeTab.sql.trim()"
- @click="emit('saveSql')"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-blue-600 hover:bg-blue-500/10 hover:text-blue-700 dark:text-blue-300 dark:hover:text-blue-200" :disabled="!activeTab.sql.trim()" @click="emit('saveSql')">
<Save class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
@@ -214,12 +165,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6 text-sky-600 hover:bg-sky-500/10 hover:text-sky-700 dark:text-sky-300 dark:hover:text-sky-200"
- @click="emit('openSql')"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-sky-600 hover:bg-sky-500/10 hover:text-sky-700 dark:text-sky-300 dark:hover:text-sky-200" @click="emit('openSql')">
<FolderOpen class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
@@ -229,11 +175,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
<span class="flex-1 min-w-0" />
<div class="flex items-center gap-2 shrink-0">
<div class="flex items-center gap-1">
- <span
- v-if="activeConnection?.color"
- class="h-4 w-1 rounded-full shrink-0"
- :style="{ backgroundColor: activeConnection.color }"
- />
+ <span v-if="activeConnection?.color" class="h-4 w-1 rounded-full shrink-0" :style="{ backgroundColor: activeConnection.color }" />
<SearchableSelect
:model-value="activeConnectionValue"
:options="connectionOptionIds"
@@ -264,9 +206,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
<Database class="h-3.5 w-3.5 shrink-0" />
<SearchableSelect
:model-value="activeDatabaseValue"
- :options="
- activeDatabaseOptions.length ? activeDatabaseOptions : activeDatabaseValue ? [activeDatabaseValue] : []
- "
+ :options="activeDatabaseOptions.length ? activeDatabaseOptions : activeDatabaseValue ? [activeDatabaseValue] : []"
:placeholder="t('editor.selectDatabase')"
:search-placeholder="t('editor.searchDatabase')"
:empty-text="t('grid.noSearchResults')"
@@ -284,13 +224,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
<TruncatedTextTooltip :text="label" class="min-w-0 flex-1" side="left" :side-offset="8" />
</template>
</SearchableSelect>
- <Button
- v-if="activeDatabaseValue"
- variant="ghost"
- size="sm"
- class="h-6 px-2 text-[11px]"
- @click="isActiveDatabaseDefault ? emit('clearDefaultDatabase') : emit('setDefaultDatabase')"
- >
+ <Button v-if="activeDatabaseValue" variant="ghost" size="sm" class="h-6 px-2 text-[11px]" @click="isActiveDatabaseDefault ? emit('clearDefaultDatabase') : emit('setDefaultDatabase')">
<Check v-if="isActiveDatabaseDefault" class="h-3 w-3" />
{{ isActiveDatabaseDefault ? t("editor.defaultDatabase") : t("editor.setDefaultDatabase") }}
</Button>
@@ -307,13 +241,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
"
>
<SelectTrigger class="h-6 w-auto max-w-56 border-0 bg-transparent px-1 text-xs shadow-none focus:ring-0">
- <SelectValue
- :placeholder="
- activeConnection && isLoadingSchemas(activeConnection.id, schemaDatabaseKey)
- ? t('common.loading')
- : t('editor.selectSchema')
- "
- >
+ <SelectValue :placeholder="activeConnection && isLoadingSchemas(activeConnection.id, schemaDatabaseKey) ? t('common.loading') : t('editor.selectSchema')">
{{ activeSchemaValue || t("editor.selectSchema") }}
</SelectValue>
</SelectTrigger>
diff --git a/apps/desktop/src/components/layout/SqlLibraryPanel.vue b/apps/desktop/src/components/layout/SqlLibraryPanel.vue
index f63a128d24..547fa6c366 100644
--- a/apps/desktop/src/components/layout/SqlLibraryPanel.vue
+++ b/apps/desktop/src/components/layout/SqlLibraryPanel.vue
@@ -1,31 +1,9 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
-import {
- Download,
- FileInput,
- FileText,
- FolderCog,
- FolderClosed,
- FolderOpen,
- FolderPlus,
- Library,
- LocateFixed,
- Pencil,
- Search,
- Trash2,
- Upload,
- X,
-} from "@lucide/vue";
+import { Download, FileInput, FileText, FolderCog, FolderClosed, FolderOpen, FolderPlus, Library, LocateFixed, Pencil, Search, Trash2, Upload, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import CustomContextMenu, { type ContextMenuItem as CtxMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { useToast } from "@/composables/useToast";
import { isTauriRuntime } from "@/lib/tauriRuntime";
@@ -91,9 +69,7 @@ function stripSqlExtension(name: string) {
function relativeImportName(baseDir: string, filePath: string) {
const normalizedBase = baseDir.replace(/\\/g, "/").replace(/\/+$/, "");
const normalizedFile = filePath.replace(/\\/g, "/");
- const relative = normalizedFile.startsWith(`${normalizedBase}/`)
- ? normalizedFile.slice(normalizedBase.length + 1)
- : normalizedFile.split("/").pop() || "import.sql";
+ const relative = normalizedFile.startsWith(`${normalizedBase}/`) ? normalizedFile.slice(normalizedBase.length + 1) : normalizedFile.split("/").pop() || "import.sql";
const pretty = relative.replace(/\//g, " - ");
return ensureSqlExtension(pretty);
}
@@ -250,11 +226,7 @@ async function importDirectoryIntoLibrary(targetFolder?: SavedSqlFolder) {
return;
}
- const takenNames = new Set(
- (targetFolder ? savedSqlStore.filesInFolder(targetFolder.id) : savedSqlStore.filesWithoutFolder())
- .filter((file) => !orphanedIds.value.has(file.id))
- .map((file) => file.name),
- );
+ const takenNames = new Set((targetFolder ? savedSqlStore.filesInFolder(targetFolder.id) : savedSqlStore.filesWithoutFolder()).filter((file) => !orphanedIds.value.has(file.id)).map((file) => file.name));
for (const path of sqlPaths) {
const content = await readTextFile(path);
@@ -328,33 +300,26 @@ async function openSqlStorageDirectory() {
function fileMatchesQuery(file: SavedSqlFile) {
const q = searchQuery.value;
if (!q) return true;
- return [file.name, file.database, file.schema, file.sql, getConnectionLabel(file.connectionId)]
- .filter(Boolean)
- .some((value) => String(value).toLowerCase().includes(q));
+ return [file.name, file.database, file.schema, file.sql, getConnectionLabel(file.connectionId)].filter(Boolean).some((value) => String(value).toLowerCase().includes(q));
}
function folderMatchesQuery(folder: SavedSqlFolder) {
const q = searchQuery.value;
if (!q) return true;
if (folder.name.toLowerCase().includes(q)) return true;
- return savedSqlStore
- .filesInFolder(folder.id)
- .some((file) => !orphanedIds.value.has(file.id) && fileMatchesQuery(file));
+ return savedSqlStore.filesInFolder(folder.id).some((file) => !orphanedIds.value.has(file.id) && fileMatchesQuery(file));
}
function filesInFolder(folderId: string) {
const folder = savedSqlStore.allFolders.find((item) => item.id === folderId);
- const includeAllFilesForMatchedFolder =
- !!folder && !!searchQuery.value && folder.name.toLowerCase().includes(searchQuery.value);
+ const includeAllFilesForMatchedFolder = !!folder && !!searchQuery.value && folder.name.toLowerCase().includes(searchQuery.value);
return savedSqlStore
.filesInFolder(folderId)
.filter((file) => !orphanedIds.value.has(file.id))
.filter((file) => includeAllFilesForMatchedFolder || fileMatchesQuery(file));
}
-const visibleFolders = computed(() =>
- savedSqlStore.allFolders.filter((folder) => isConnectionVisible(folder.connectionId) && folderMatchesQuery(folder)),
-);
+const visibleFolders = computed(() => savedSqlStore.allFolders.filter((folder) => isConnectionVisible(folder.connectionId) && folderMatchesQuery(folder)));
const visibleFiles = computed(() =>
savedSqlStore
@@ -756,22 +721,10 @@ function showDropInside(targetId: string) {
<Button variant="ghost" size="icon" class="h-5 w-5" :title="t('savedSql.newFolder')" @click="openNewFolderInput">
<FolderPlus class="h-3 w-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :title="t('sqlLibrary.importDirectory')"
- @click="importDirectoryIntoLibrary()"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :title="t('sqlLibrary.importDirectory')" @click="importDirectoryIntoLibrary()">
<Upload class="h-3 w-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :title="t('sqlLibrary.exportLibrary')"
- @click="exportFolderContents()"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :title="t('sqlLibrary.exportLibrary')" @click="exportFolderContents()">
<Download class="h-3 w-3" />
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="emit('close')">
@@ -782,20 +735,8 @@ function showDropInside(targetId: string) {
<div class="border-b shrink-0 px-2 py-1">
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
- <input
- v-model="searchText"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="w-full h-6 pl-7 pr-6 text-xs rounded border border-border bg-background focus:outline-none focus:ring-1 focus:ring-ring"
- :placeholder="t('grid.search')"
- />
- <button
- v-if="searchText"
- type="button"
- class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- @click="searchText = ''"
- >
+ <input v-model="searchText" autocapitalize="off" autocorrect="off" spellcheck="false" class="w-full h-6 pl-7 pr-6 text-xs rounded border border-border bg-background focus:outline-none focus:ring-1 focus:ring-ring" :placeholder="t('grid.search')" />
+ <button v-if="searchText" type="button" class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground" @click="searchText = ''">
<X class="h-3 w-3" />
</button>
</div>
@@ -827,10 +768,7 @@ function showDropInside(targetId: string) {
<div v-for="folder in visibleFolders" :key="folder.id" class="mb-0.5">
<div
class="relative flex items-center gap-1 rounded px-2 py-1.5 text-xs cursor-pointer transition-colors group"
- :class="[
- showDropInside(folder.id) ? 'ring-1 ring-primary/50 bg-primary/5' : 'hover:bg-accent',
- isDraggingItem(folder.id) ? 'opacity-50' : '',
- ]"
+ :class="[showDropInside(folder.id) ? 'ring-1 ring-primary/50 bg-primary/5' : 'hover:bg-accent', isDraggingItem(folder.id) ? 'opacity-50' : '']"
@mousedown="handleDragMouseDown($event, folder.id, 'folder')"
@mousemove="updateDropTarget($event, folder.id, 'folder')"
@mouseleave="clearDropTarget(folder.id)"
@@ -841,14 +779,8 @@ function showDropInside(targetId: string) {
"
>
<div v-if="showDropBefore(folder.id)" class="absolute left-2 right-2 top-0 border-t-2 border-primary" />
- <div
- v-if="showDropAfter(folder.id)"
- class="absolute left-2 right-2 bottom-0 border-b-2 border-primary"
- />
- <component
- :is="isFolderExpanded(folder.id) ? FolderOpen : FolderClosed"
- class="h-4 w-4 text-amber-500 shrink-0"
- />
+ <div v-if="showDropAfter(folder.id)" class="absolute left-2 right-2 bottom-0 border-b-2 border-primary" />
+ <component :is="isFolderExpanded(folder.id) ? FolderOpen : FolderClosed" class="h-4 w-4 text-amber-500 shrink-0" />
<template v-if="renamingTarget?.type === 'folder' && renamingTarget.id === folder.id">
<input
:ref="setRenameInputRef"
@@ -883,10 +815,7 @@ function showDropInside(targetId: string) {
"
>
<div v-if="showDropBefore(file.id)" class="absolute left-2 right-2 top-0 border-t-2 border-primary" />
- <div
- v-if="showDropAfter(file.id)"
- class="absolute left-2 right-2 bottom-0 border-b-2 border-primary"
- />
+ <div v-if="showDropAfter(file.id)" class="absolute left-2 right-2 bottom-0 border-b-2 border-primary" />
<FileText class="h-3.5 w-3.5 text-blue-400 shrink-0" />
<template v-if="renamingTarget?.type === 'file' && renamingTarget.id === file.id">
<input
@@ -901,9 +830,7 @@ function showDropInside(targetId: string) {
/>
</template>
<span v-else class="dbx-sql-library-drag-label min-w-0 flex-1 truncate">{{ file.name }}</span>
- <span class="shrink-0 text-xs text-muted-foreground">
- [{{ getConnectionLabel(file.connectionId) }}]
- </span>
+ <span class="shrink-0 text-xs text-muted-foreground"> [{{ getConnectionLabel(file.connectionId) }}] </span>
</div>
<div v-if="filesInFolder(folder.id).length === 0" class="px-2 py-1 text-xs text-muted-foreground">
@@ -951,16 +878,11 @@ function showDropInside(targetId: string) {
/>
</template>
<span v-else class="dbx-sql-library-drag-label min-w-0 flex-1 truncate">{{ file.name }}</span>
- <span class="shrink-0 text-xs text-muted-foreground">
- [{{ getConnectionLabel(file.connectionId) }}]
- </span>
+ <span class="shrink-0 text-xs text-muted-foreground"> [{{ getConnectionLabel(file.connectionId) }}] </span>
</div>
</div>
- <div
- v-if="!hasAnyVisibleItem && !showNewFolderInput"
- class="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground"
- >
+ <div v-if="!hasAnyVisibleItem && !showNewFolderInput" class="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
<Library class="h-8 w-8 opacity-30" />
<p class="text-xs">{{ t("sqlLibrary.empty") }}</p>
</div>
diff --git a/apps/desktop/src/components/layout/UpdateDialog.vue b/apps/desktop/src/components/layout/UpdateDialog.vue
index 049d9ec882..04ba684708 100644
--- a/apps/desktop/src/components/layout/UpdateDialog.vue
+++ b/apps/desktop/src/components/layout/UpdateDialog.vue
@@ -99,17 +99,12 @@ watch(
<code class="bg-muted px-1 py-0.5 rounded text-[11px]">docker compose pull && docker compose up -d</code>
{{ t("updates.toUpdate") }}
</p>
- <p
- v-if="isDesktop && updateInfo?.update_available && updateInfo.portable_mode"
- class="text-xs text-muted-foreground"
- >
+ <p v-if="isDesktop && updateInfo?.update_available && updateInfo.portable_mode" class="text-xs text-muted-foreground">
{{ t("updates.portableManualUpdate") }}
</p>
</div>
<DialogFooter>
- <Button v-if="!isDownloadingUpdate && !updateReady" variant="outline" @click="open = false">{{
- t("dangerDialog.cancel")
- }}</Button>
+ <Button v-if="!isDownloadingUpdate && !updateReady" variant="outline" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>
<template v-if="updateInfo?.update_available">
<Button variant="outline" @click="emit('open-latest-release')">{{ t("updates.openRelease") }}</Button>
<template v-if="canDownloadAndInstallUpdate(updateInfo, isDesktop)">
@@ -124,9 +119,7 @@ watch(
<Button v-else @click="emit('download-and-install')">{{ t("updates.downloadAndInstall") }}</Button>
</template>
</template>
- <Button v-else-if="updateCheckMessage" @click="emit('open-latest-release')">{{
- t("updates.openRelease")
- }}</Button>
+ <Button v-else-if="updateCheckMessage" @click="emit('open-latest-release')">{{ t("updates.openRelease") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
diff --git a/apps/desktop/src/components/layout/WelcomeScreen.vue b/apps/desktop/src/components/layout/WelcomeScreen.vue
index f4a1d8bed9..47c53a1e05 100644
--- a/apps/desktop/src/components/layout/WelcomeScreen.vue
+++ b/apps/desktop/src/components/layout/WelcomeScreen.vue
@@ -2,12 +2,7 @@
import { useI18n } from "vue-i18n";
import { FilePlus2, Plus, History, Download, Database, Search, ShieldCheck, Sparkles } from "@lucide/vue";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
-import {
- connectionDriverLabel,
- connectionIconType,
- connectionRedactedNameLabel,
- connectionRedactedOptionSubtitle,
-} from "@/lib/connectionPresentation";
+import { connectionDriverLabel, connectionIconType, connectionRedactedNameLabel, connectionRedactedOptionSubtitle } from "@/lib/connectionPresentation";
import type { ConnectionConfig } from "@/types/database";
defineProps<{
@@ -35,21 +30,15 @@ const { t } = useI18n();
<div class="mx-auto flex min-h-full w-full min-w-0 max-w-5xl flex-col justify-center gap-6 px-8 py-10">
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div class="rounded-lg border bg-muted/20 px-4 py-3">
- <div class="flex items-center gap-2 text-xs text-muted-foreground">
- <Database class="h-3.5 w-3.5" /> {{ t("welcome.connections") }}
- </div>
+ <div class="flex items-center gap-2 text-xs text-muted-foreground"><Database class="h-3.5 w-3.5" /> {{ t("welcome.connections") }}</div>
<div class="mt-2 text-2xl font-semibold">{{ connectionStats.total }}</div>
</div>
<div class="rounded-lg border bg-muted/20 px-4 py-3">
- <div class="flex items-center gap-2 text-xs text-muted-foreground">
- <ShieldCheck class="h-3.5 w-3.5" /> {{ t("welcome.connected") }}
- </div>
+ <div class="flex items-center gap-2 text-xs text-muted-foreground"><ShieldCheck class="h-3.5 w-3.5" /> {{ t("welcome.connected") }}</div>
<div class="mt-2 text-2xl font-semibold">{{ connectionStats.connected }}</div>
</div>
<div class="rounded-lg border bg-muted/20 px-4 py-3">
- <div class="flex items-center gap-2 text-xs text-muted-foreground">
- <Sparkles class="h-3.5 w-3.5" /> {{ t("welcome.databaseTypes") }}
- </div>
+ <div class="flex items-center gap-2 text-xs text-muted-foreground"><Sparkles class="h-3.5 w-3.5" /> {{ t("welcome.databaseTypes") }}</div>
<div class="mt-2 text-2xl font-semibold">{{ connectionStats.types }}</div>
</div>
</div>
@@ -60,12 +49,7 @@ const { t } = useI18n();
<div class="text-sm font-medium">{{ t("welcome.quickConnections") }}</div>
</div>
<div class="divide-y">
- <button
- v-for="connection in recentConnections"
- :key="connection.id"
- class="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-muted/40"
- @click="emit('open-connection-query', connection.id)"
- >
+ <button v-for="connection in recentConnections" :key="connection.id" class="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-muted/40" @click="emit('open-connection-query', connection.id)">
<DatabaseIcon :db-type="connectionIconType(connection)" class="h-4 w-4" />
<span class="h-5 w-1 rounded-full shrink-0" :style="{ backgroundColor: connection.color || '#9ca3af' }" />
<div class="min-w-0 flex-1">
@@ -87,31 +71,10 @@ const { t } = useI18n();
<div class="text-sm font-medium">{{ t("welcome.shortcuts") }}</div>
</div>
<div class="grid gap-1 p-2">
- <button
- class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50"
- @click="emit('new-connection')"
- >
- <Plus class="h-4 w-4" /> {{ t("toolbar.newConnection") }}
- </button>
- <button
- class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50"
- :disabled="!hasConnections"
- @click="emit('new-query')"
- >
- <FilePlus2 class="h-4 w-4" /> {{ t("toolbar.newQuery") }}
- </button>
- <button
- class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50"
- @click="emit('show-history')"
- >
- <History class="h-4 w-4" /> {{ t("history.title") }}
- </button>
- <button
- class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50"
- @click="emit('import-config')"
- >
- <Download class="h-4 w-4" /> {{ t("sidebar.import") }}
- </button>
+ <button class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50" @click="emit('new-connection')"><Plus class="h-4 w-4" /> {{ t("toolbar.newConnection") }}</button>
+ <button class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50" :disabled="!hasConnections" @click="emit('new-query')"><FilePlus2 class="h-4 w-4" /> {{ t("toolbar.newQuery") }}</button>
+ <button class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50" @click="emit('show-history')"><History class="h-4 w-4" /> {{ t("history.title") }}</button>
+ <button class="flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted/50" @click="emit('import-config')"><Download class="h-4 w-4" /> {{ t("sidebar.import") }}</button>
<div class="mt-2 rounded-md bg-muted/30 px-3 py-2 text-xs leading-5 text-muted-foreground">
<Search class="mr-1 inline h-3.5 w-3.5" />
{{ t("welcome.tip") }}
@@ -130,12 +93,8 @@ const { t } = useI18n();
{{ t("welcome.mcpDescription") }}
</p>
<div class="mt-2 flex flex-wrap items-center gap-2">
- <code class="max-w-full break-all rounded bg-muted px-2 py-0.5 text-[11px] select-all"
- >npx @dbx-app/mcp-server</code
- >
- <a href="#" class="text-xs text-primary hover:underline" @click.prevent="emit('open-mcp-guide')">{{
- t("welcome.mcpLearnMore")
- }}</a>
+ <code class="max-w-full break-all rounded bg-muted px-2 py-0.5 text-[11px] select-all">npx @dbx-app/mcp-server</code>
+ <a href="#" class="text-xs text-primary hover:underline" @click.prevent="emit('open-mcp-guide')">{{ t("welcome.mcpLearnMore") }}</a>
</div>
</div>
</div>
diff --git a/apps/desktop/src/components/layout/WindowControls.vue b/apps/desktop/src/components/layout/WindowControls.vue
index 67595c9142..3205ea366f 100644
--- a/apps/desktop/src/components/layout/WindowControls.vue
+++ b/apps/desktop/src/components/layout/WindowControls.vue
@@ -14,23 +14,14 @@ const emit = defineEmits<{
<template>
<div class="flex items-stretch -mr-2 ml-1">
- <button
- class="inline-flex items-center justify-center w-11.5 h-10 hover:bg-foreground/10 transition-colors"
- @click="emit('minimize')"
- >
+ <button class="inline-flex items-center justify-center w-11.5 h-10 hover:bg-foreground/10 transition-colors" @click="emit('minimize')">
<Minus class="h-4 w-4" />
</button>
- <button
- class="inline-flex items-center justify-center w-11.5 h-10 hover:bg-foreground/10 transition-colors"
- @click="emit('toggle-maximize')"
- >
+ <button class="inline-flex items-center justify-center w-11.5 h-10 hover:bg-foreground/10 transition-colors" @click="emit('toggle-maximize')">
<Copy v-if="isMaximized" class="h-3.5 w-3.5" />
<Square v-else class="h-3.5 w-3.5" />
</button>
- <button
- class="inline-flex items-center justify-center w-11.5 h-10 hover:bg-red-500 hover:text-white transition-colors"
- @click="emit('close')"
- >
+ <button class="inline-flex items-center justify-center w-11.5 h-10 hover:bg-red-500 hover:text-white transition-colors" @click="emit('close')">
<X class="h-4 w-4" />
</button>
</div>
diff --git a/apps/desktop/src/components/lineage/FieldLineageDialog.vue b/apps/desktop/src/components/lineage/FieldLineageDialog.vue
index d5d584e75d..8a3008cb5b 100644
--- a/apps/desktop/src/components/lineage/FieldLineageDialog.vue
+++ b/apps/desktop/src/components/lineage/FieldLineageDialog.vue
@@ -2,21 +2,7 @@
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
-import {
- ArrowUpRight,
- Check,
- Columns3,
- Copy,
- Eye,
- Filter,
- History,
- Link,
- Loader2,
- RefreshCw,
- Search,
- SearchX,
- X,
-} from "@lucide/vue";
+import { ArrowUpRight, Check, Columns3, Copy, Eye, Filter, History, Link, Loader2, RefreshCw, Search, SearchX, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogFooter, DialogHeader, DialogScrollContent, DialogTitle } from "@/components/ui/dialog";
@@ -24,15 +10,7 @@ import { Input } from "@/components/ui/input";
import { useToast } from "@/composables/useToast";
import { useConnectionStore } from "@/stores/connectionStore";
import * as api from "@/lib/api";
-import {
- analyzeFieldLineage,
- summarizeLineageCounts,
- type FieldLineageConfidence,
- type FieldLineageItem,
- type FieldLineageResult,
- type FieldLineageTable,
- type FieldLineageView,
-} from "@/lib/fieldLineage";
+import { analyzeFieldLineage, summarizeLineageCounts, type FieldLineageConfidence, type FieldLineageItem, type FieldLineageResult, type FieldLineageTable, type FieldLineageView } from "@/lib/fieldLineage";
import { copyToClipboard } from "@/lib/clipboard";
const props = defineProps<{
@@ -88,14 +66,12 @@ const targetLabel = computed(() => {
const counts = computed(() => summarizeLineageCounts(result.value?.items ?? []));
-const confidenceOptions = computed<Array<{ value: "all" | FieldLineageConfidence; label: string; count: number }>>(
- () => [
- { value: "all", label: t("lineage.all"), count: result.value?.items.length ?? 0 },
- { value: "certain", label: t("lineage.certain"), count: counts.value.certain },
- { value: "likely", label: t("lineage.likely"), count: counts.value.likely },
- { value: "possible", label: t("lineage.possible"), count: counts.value.possible },
- ],
-);
+const confidenceOptions = computed<Array<{ value: "all" | FieldLineageConfidence; label: string; count: number }>>(() => [
+ { value: "all", label: t("lineage.all"), count: result.value?.items.length ?? 0 },
+ { value: "certain", label: t("lineage.certain"), count: counts.value.certain },
+ { value: "likely", label: t("lineage.likely"), count: counts.value.likely },
+ { value: "possible", label: t("lineage.possible"), count: counts.value.possible },
+]);
const filteredItems = computed(() => {
const query = searchText.value.trim().toLowerCase();
@@ -103,15 +79,7 @@ const filteredItems = computed(() => {
.filter((item) => confidenceFilter.value === "all" || item.confidence === confidenceFilter.value)
.filter((item) => {
if (!query) return true;
- return [
- item.title,
- item.schema,
- item.table,
- item.column,
- item.sqlSnippet,
- itemKindLabel(item),
- itemDescription(item),
- ].some((value) =>
+ return [item.title, item.schema, item.table, item.column, item.sqlSnippet, itemKindLabel(item), itemDescription(item)].some((value) =>
String(value ?? "")
.toLowerCase()
.includes(query),
@@ -157,13 +125,8 @@ async function loadLineage() {
if (isStale(currentRun)) return;
const schema = props.prefillSchema || props.prefillDatabase;
- const tableInfos = prioritizeTargetTable(
- await api.listTables(props.prefillConnectionId, props.prefillDatabase, schema),
- props.prefillTable,
- ).slice(0, MAX_TABLES);
- const viewInfos = tableInfos
- .filter((table) => table.table_type.toUpperCase().includes("VIEW"))
- .slice(0, MAX_VIEW_DDLS);
+ const tableInfos = prioritizeTargetTable(await api.listTables(props.prefillConnectionId, props.prefillDatabase, schema), props.prefillTable).slice(0, MAX_TABLES);
+ const viewInfos = tableInfos.filter((table) => table.table_type.toUpperCase().includes("VIEW")).slice(0, MAX_VIEW_DDLS);
progressTotal.value = tableInfos.length + viewInfos.length + 1;
const tables: FieldLineageTable[] = [];
@@ -174,12 +137,7 @@ async function loadLineage() {
batch.map(async (table) => {
try {
const columns = await api.getColumns(props.prefillConnectionId, props.prefillDatabase, schema, table.name);
- const foreignKeys = await api.listForeignKeys(
- props.prefillConnectionId,
- props.prefillDatabase,
- schema,
- table.name,
- );
+ const foreignKeys = await api.listForeignKeys(props.prefillConnectionId, props.prefillDatabase, schema, table.name);
return {
schema,
name: table.name,
@@ -208,9 +166,7 @@ async function loadLineage() {
}
}
- const histories = (await api.loadHistory(200, 0))
- .filter((entry) => !entry.database || entry.database === props.prefillDatabase)
- .map((entry) => ({ id: entry.id, sql: entry.sql, executed_at: entry.executed_at }));
+ const histories = (await api.loadHistory(200, 0)).filter((entry) => !entry.database || entry.database === props.prefillDatabase).map((entry) => ({ id: entry.id, sql: entry.sql, executed_at: entry.executed_at }));
progressDone.value++;
if (isStale(currentRun)) return;
@@ -258,8 +214,7 @@ function confidenceTone(confidence: FieldLineageItem["confidence"]) {
function itemRank(item: FieldLineageItem) {
const confidenceRank = item.confidence === "certain" ? 0 : item.confidence === "likely" ? 10 : 20;
- const kindRank =
- item.kind === "foreignKey" ? 0 : item.kind === "viewReference" ? 1 : item.kind === "historyReference" ? 2 : 3;
+ const kindRank = item.kind === "foreignKey" ? 0 : item.kind === "viewReference" ? 1 : item.kind === "historyReference" ? 2 : 3;
return confidenceRank + kindRank;
}
@@ -287,9 +242,7 @@ function itemDescription(item: FieldLineageItem) {
return item.confidence === "likely" ? t("lineage.description.viewLikely") : t("lineage.description.viewPossible");
}
if (item.kind === "historyReference") {
- return item.confidence === "likely"
- ? t("lineage.description.historyLikely")
- : t("lineage.description.historyPossible");
+ return item.confidence === "likely" ? t("lineage.description.historyLikely") : t("lineage.description.historyPossible");
}
return t("lineage.description.sameName");
}
@@ -322,9 +275,7 @@ function openItemTarget(item: FieldLineageItem) {
<template>
<Dialog v-model:open="dialogOpen">
- <DialogScrollContent
- class="h-[78vh] min-h-[560px] max-h-[780px] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden gap-0 p-0 sm:max-w-[980px]"
- >
+ <DialogScrollContent class="h-[78vh] min-h-[560px] max-h-[780px] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden gap-0 p-0 sm:max-w-[980px]">
<DialogHeader class="border-b px-6 py-4 pr-12">
<DialogTitle class="flex items-center gap-2 text-lg">
<Link class="h-5 w-5" />
@@ -357,16 +308,7 @@ function openItemTarget(item: FieldLineageItem) {
</div>
<div class="flex items-center gap-2 overflow-x-auto">
<Filter class="h-4 w-4 shrink-0 text-muted-foreground" />
- <Button
- v-for="option in confidenceOptions"
- :key="option.value"
- size="sm"
- :variant="confidenceFilter === option.value ? 'default' : 'outline'"
- class="h-8 shrink-0 px-3"
- @click="confidenceFilter = option.value"
- >
- {{ option.label }} {{ option.count }}
- </Button>
+ <Button v-for="option in confidenceOptions" :key="option.value" size="sm" :variant="confidenceFilter === option.value ? 'default' : 'outline'" class="h-8 shrink-0 px-3" @click="confidenceFilter = option.value"> {{ option.label }} {{ option.count }} </Button>
</div>
</div>
</div>
@@ -379,17 +321,11 @@ function openItemTarget(item: FieldLineageItem) {
</div>
</div>
- <div
- v-else-if="error"
- class="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"
- >
+ <div v-else-if="error" class="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
{{ error }}
</div>
- <div
- v-else-if="result && result.items.length === 0"
- class="flex flex-col items-center justify-center gap-2 rounded-md border py-12 text-sm text-muted-foreground"
- >
+ <div v-else-if="result && result.items.length === 0" class="flex flex-col items-center justify-center gap-2 rounded-md border py-12 text-sm text-muted-foreground">
<SearchX class="h-8 w-8" />
{{ t("lineage.empty") }}
</div>
@@ -398,33 +334,20 @@ function openItemTarget(item: FieldLineageItem) {
<div class="mb-3 flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span>{{ t("lineage.showing", { shown: filteredItems.length, total: result.items.length }) }}</span>
<span v-if="filteredItems.length">
- {{ t("lineage.certain") }} {{ filteredCounts.certain }} · {{ t("lineage.likely") }}
- {{ filteredCounts.likely }} · {{ t("lineage.possible") }}
+ {{ t("lineage.certain") }} {{ filteredCounts.certain }} · {{ t("lineage.likely") }} {{ filteredCounts.likely }} · {{ t("lineage.possible") }}
{{ filteredCounts.possible }}
</span>
</div>
- <div
- v-if="filteredItems.length === 0"
- class="flex flex-col items-center justify-center gap-2 rounded-md border py-12 text-sm text-muted-foreground"
- >
+ <div v-if="filteredItems.length === 0" class="flex flex-col items-center justify-center gap-2 rounded-md border py-12 text-sm text-muted-foreground">
<SearchX class="h-8 w-8" />
{{ t("lineage.noFiltered") }}
</div>
<div v-else class="space-y-2">
- <div
- v-for="item in filteredItems"
- :key="item.id"
- class="rounded-md border bg-background transition-colors hover:bg-muted/25"
- >
+ <div v-for="item in filteredItems" :key="item.id" class="rounded-md border bg-background transition-colors hover:bg-muted/25">
<div class="flex items-start gap-3 p-3">
- <div
- :class="[
- 'mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md border',
- confidenceTone(item.confidence),
- ]"
- >
+ <div :class="['mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md border', confidenceTone(item.confidence)]">
<component :is="itemIcon(item)" class="h-4 w-4" />
</div>
<div class="min-w-0 flex-1">
@@ -437,33 +360,19 @@ function openItemTarget(item: FieldLineageItem) {
@click="openItemTarget(item)"
>
<span class="truncate">{{ itemPrimaryLabel(item) }}</span>
- <ArrowUpRight
- class="h-3.5 w-3.5 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"
- />
+ <ArrowUpRight class="h-3.5 w-3.5 shrink-0 opacity-70 transition-opacity group-hover:opacity-100" />
</button>
<span v-else class="max-w-[560px] truncate font-medium">{{ itemPrimaryLabel(item) }}</span>
<Badge v-if="item.schema" variant="outline" class="text-[10px]">{{ item.schema }}</Badge>
<Badge variant="outline" class="text-[10px]">{{ itemKindLabel(item) }}</Badge>
- <Badge :variant="confidenceVariant(item.confidence)" class="text-[10px]">{{
- t(`lineage.${item.confidence}`)
- }}</Badge>
+ <Badge :variant="confidenceVariant(item.confidence)" class="text-[10px]">{{ t(`lineage.${item.confidence}`) }}</Badge>
</div>
<p class="mt-1 text-xs leading-5 text-muted-foreground">
{{ itemDescription(item) }}
</p>
- <pre
- v-if="item.sqlSnippet"
- class="mt-2 max-h-20 overflow-auto rounded-md bg-muted/40 p-2 text-xs whitespace-pre-wrap"
- v-html="highlight(item.sqlSnippet)"
- />
+ <pre v-if="item.sqlSnippet" class="mt-2 max-h-20 overflow-auto rounded-md bg-muted/40 p-2 text-xs whitespace-pre-wrap" v-html="highlight(item.sqlSnippet)" />
</div>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 w-8 shrink-0 p-0"
- :title="t('lineage.copy')"
- @click="copyItem(item)"
- >
+ <Button variant="ghost" size="sm" class="h-8 w-8 shrink-0 p-0" :title="t('lineage.copy')" @click="copyItem(item)">
<Check v-if="copiedId === item.id" class="h-4 w-4 text-emerald-600" />
<Copy v-else class="h-4 w-4" />
</Button>
diff --git a/apps/desktop/src/components/mongo/JsonEditNode.vue b/apps/desktop/src/components/mongo/JsonEditNode.vue
index 98d963cf10..a7746f9397 100644
--- a/apps/desktop/src/components/mongo/JsonEditNode.vue
+++ b/apps/desktop/src/components/mongo/JsonEditNode.vue
@@ -116,29 +116,13 @@ function confirmRemoveChild() {
</template>
<template v-else>
<span class="json-edit-quote">"</span>
- <input
- v-model="node.keyName"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="json-edit-key-input"
- :disabled="node.readonlyKey"
- :placeholder="t('mongo.fieldPlaceholder')"
- />
+ <input v-model="node.keyName" autocapitalize="off" autocorrect="off" spellcheck="false" class="json-edit-key-input" :disabled="node.readonlyKey" :placeholder="t('mongo.fieldPlaceholder')" />
<span class="json-edit-quote">"</span>
</template>
<span class="json-edit-colon">:</span>
</div>
- <textarea
- v-if="node.kind === 'value'"
- v-model="node.valueText"
- class="json-edit-value"
- :class="[fieldValueTone(node.valueText), { 'is-readonly': node.readonlyValue }]"
- :disabled="node.readonlyValue"
- :rows="fieldRows(node.valueText)"
- wrap="soft"
- />
+ <textarea v-if="node.kind === 'value'" v-model="node.valueText" class="json-edit-value" :class="[fieldValueTone(node.valueText), { 'is-readonly': node.readonlyValue }]" :disabled="node.readonlyValue" :rows="fieldRows(node.valueText)" wrap="soft" />
<div v-else class="json-edit-container-open">
<span>{{ node.kind === "array" ? "[" : "{" }}</span>
<span class="json-edit-count">{{ node.children.length }}</span>
@@ -146,43 +130,21 @@ function confirmRemoveChild() {
<span class="json-edit-comma">{{ node.kind === "value" ? "," : "" }}</span>
- <Button
- v-if="removable"
- variant="ghost"
- size="icon"
- class="json-edit-remove"
- :title="t('mongo.deleteField')"
- @click="emit('remove')"
- >
+ <Button v-if="removable" variant="ghost" size="icon" class="json-edit-remove" :title="t('mongo.deleteField')" @click="emit('remove')">
<Trash2 class="w-3 h-3" />
</Button>
<span v-else-if="node.readonlyValue" class="json-edit-lock">{{ t("mongo.readonlyId") }}</span>
</div>
<div v-if="isContainer" class="json-edit-children" :style="{ '--mongo-key-width': childKeyWidth }">
- <JsonEditNode
- v-for="(child, idx) in node.children"
- :key="child.key"
- :node="child"
- :parent-kind="node.kind"
- :removable="!child.readonlyValue || node.kind === 'array'"
- @remove="requestRemoveChild(idx)"
- />
-
- <Button variant="ghost" size="sm" class="json-edit-add" @click="addChild">
- <Plus class="w-3 h-3 mr-1" /> {{ t("mongo.addField") }}
- </Button>
+ <JsonEditNode v-for="(child, idx) in node.children" :key="child.key" :node="child" :parent-kind="node.kind" :removable="!child.readonlyValue || node.kind === 'array'" @remove="requestRemoveChild(idx)" />
+
+ <Button variant="ghost" size="sm" class="json-edit-add" @click="addChild"> <Plus class="w-3 h-3 mr-1" /> {{ t("mongo.addField") }} </Button>
<div class="json-edit-close">{{ node.kind === "array" ? "]" : "}" }}<span class="json-edit-comma">,</span></div>
</div>
- <DangerConfirmDialog
- v-model:open="showChildDeleteConfirm"
- :message="t('dangerDialog.deleteMessage')"
- :details="childDeleteDetails"
- :confirm-label="t('mongo.deleteField')"
- @confirm="confirmRemoveChild"
- />
+ <DangerConfirmDialog v-model:open="showChildDeleteConfirm" :message="t('dangerDialog.deleteMessage')" :details="childDeleteDetails" :confirm-label="t('mongo.deleteField')" @confirm="confirmRemoveChild" />
</div>
</template>
diff --git a/apps/desktop/src/components/mongo/MongoDocBrowser.vue b/apps/desktop/src/components/mongo/MongoDocBrowser.vue
index d05a4e6c8e..a89908af2f 100644
--- a/apps/desktop/src/components/mongo/MongoDocBrowser.vue
+++ b/apps/desktop/src/components/mongo/MongoDocBrowser.vue
@@ -2,24 +2,7 @@
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
import { uuid } from "@/lib/utils";
import { useI18n } from "vue-i18n";
-import {
- RefreshCw,
- RefreshCcw,
- Loader2,
- Trash2,
- Plus,
- Save,
- ChevronLeft,
- ChevronRight,
- Table2,
- Braces,
- X,
- Columns3,
- Check,
- Search,
- Wrench,
- Filter,
-} from "@lucide/vue";
+import { RefreshCw, RefreshCcw, Loader2, Trash2, Plus, Save, ChevronLeft, ChevronRight, Table2, Braces, X, Columns3, Check, Search, Wrench, Filter } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
@@ -70,9 +53,7 @@ const filterInput = ref("");
const sortInput = ref("");
const dataGridRef = ref<InstanceType<typeof DataGrid>>();
const columnVisibilitySearch = ref("");
-const columnVisibilityOptions = computed(
- () => dataGridRef.value?.filteredColumnVisibilityOptions(columnVisibilitySearch.value) ?? [],
-);
+const columnVisibilityOptions = computed(() => dataGridRef.value?.filteredColumnVisibilityOptions(columnVisibilitySearch.value) ?? []);
const tableSearchSplitContainerRef = ref<HTMLDivElement>();
const tableFindPaneWidth = ref<number | null>(null);
const isResizingTableSearchSplit = ref(false);
@@ -91,15 +72,7 @@ type LocalFilterSummary = {
values: string[];
hiddenValueCount: number;
};
-type MongoFilterMode =
- | "equals"
- | "not-equals"
- | "like"
- | "not-like"
- | "greater-than"
- | "less-than"
- | "is-null"
- | "is-not-null";
+type MongoFilterMode = "equals" | "not-equals" | "like" | "not-like" | "greater-than" | "less-than" | "is-null" | "is-not-null";
type MongoFilterRule = {
id: string;
fieldName: string;
@@ -260,10 +233,7 @@ function mongoConditionForRule(rule: MongoFilterRule): Record<string, unknown> |
}
}
-function combineMongoConditions(
- conditions: Record<string, unknown>[],
- rules: MongoFilterRule[],
-): Record<string, unknown> | null {
+function combineMongoConditions(conditions: Record<string, unknown>[], rules: MongoFilterRule[]): Record<string, unknown> | null {
if (conditions.length === 0) return null;
let result = conditions[0];
for (let i = 1; i < conditions.length; i++) {
@@ -302,9 +272,7 @@ const mongoQueryPreview = computed(() => {
});
async function applyMongoStructuredFilters() {
- const items = mongoFilterRules.value
- .map((rule) => ({ rule, condition: mongoConditionForRule(rule) }))
- .filter((item): item is { rule: MongoFilterRule; condition: Record<string, unknown> } => !!item.condition);
+ const items = mongoFilterRules.value.map((rule) => ({ rule, condition: mongoConditionForRule(rule) })).filter((item): item is { rule: MongoFilterRule; condition: Record<string, unknown> } => !!item.condition);
const structured = combineMongoConditions(
items.map((item) => item.condition),
items.map((item) => item.rule),
@@ -321,12 +289,7 @@ function clearMongoFilters(clearLocalFilter?: (columnIndex?: number) => void) {
applyFilter();
}
-async function gridSave(changes: {
- dirtyRows: Map<number, Map<number, string | number | boolean | null>>;
- deletedRows: Set<number>;
- columns: string[];
- rows: (string | number | boolean | null)[][];
-}) {
+async function gridSave(changes: { dirtyRows: Map<number, Map<number, string | number | boolean | null>>; deletedRows: Set<number>; columns: string[]; rows: (string | number | boolean | null)[][] }) {
const cols = changes.columns;
const idColIdx = cols.indexOf("_id");
if (idColIdx < 0) throw new Error("No _id column");
@@ -353,13 +316,7 @@ async function gridSave(changes: {
updated[col] = newVal;
}
}
- await api.mongoUpdateDocument(
- props.connectionId,
- props.database,
- props.collection,
- String(id),
- JSON.stringify(updated),
- );
+ await api.mongoUpdateDocument(props.connectionId, props.database, props.collection, String(id), JSON.stringify(updated));
}
for (const rowIdx of changes.deletedRows) {
@@ -378,15 +335,7 @@ async function load() {
try {
const filter = currentMongoFilter();
const sort = sortInput.value.trim() || undefined;
- const result = await api.mongoFindDocuments(
- props.connectionId,
- props.database,
- props.collection,
- page.value * pageSize.value,
- pageSize.value,
- filter,
- sort,
- );
+ const result = await api.mongoFindDocuments(props.connectionId, props.database, props.collection, page.value * pageSize.value, pageSize.value, filter, sort);
const nextDocuments = result.documents.map(asRecord);
documents.value = nextDocuments;
if (nextDocuments.length > 0) {
@@ -455,9 +404,7 @@ function startNew() {
function startEdit() {
const doc = selectedDoc.value;
if (!doc) return;
- editFields.value = Object.entries(doc).map(([name, value]) =>
- createEditNode(name, value, name === "_id", name === "_id"),
- );
+ editFields.value = Object.entries(doc).map(([name, value]) => createEditNode(name, value, name === "_id", name === "_id"));
isEditing.value = true;
isNew.value = false;
}
@@ -497,9 +444,7 @@ function createEditNode(keyName: string, value: unknown, readonlyKey: boolean, r
valueText: "",
readonlyKey,
readonlyValue,
- children: Object.entries(value as JsonRecord).map(([childName, child]) =>
- createEditNode(childName, child, readonlyValue, readonlyValue),
- ),
+ children: Object.entries(value as JsonRecord).map(([childName, child]) => createEditNode(childName, child, readonlyValue, readonlyValue)),
};
}
@@ -589,13 +534,7 @@ async function saveDoc() {
error.value = "No _id field";
return;
}
- await api.mongoUpdateDocument(
- props.connectionId,
- props.database,
- props.collection,
- String(id),
- JSON.stringify(doc),
- );
+ await api.mongoUpdateDocument(props.connectionId, props.database, props.collection, String(id), JSON.stringify(doc));
}
isEditing.value = false;
isNew.value = false;
@@ -666,16 +605,13 @@ function docPreview(doc: JsonRecord): string {
function highlightedJson(json: string): string {
const escaped = json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
- return escaped.replace(
- /("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g,
- (match) => {
- let cls = "json-number";
- if (match.startsWith('"')) cls = match.endsWith(":") ? "json-key" : "json-string";
- else if (match === "true" || match === "false") cls = "json-boolean";
- else if (match === "null") cls = "json-null";
- return `<span class="${cls}">${match}</span>`;
- },
- );
+ return escaped.replace(/("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g, (match) => {
+ let cls = "json-number";
+ if (match.startsWith('"')) cls = match.endsWith(":") ? "json-key" : "json-string";
+ else if (match === "true" || match === "false") cls = "json-boolean";
+ else if (match === "null") cls = "json-null";
+ return `<span class="${cls}">${match}</span>`;
+ });
}
onMounted(load);
@@ -731,49 +667,25 @@ function resetTableSearchSplitWidth() {
<!-- Top toolbar: view toggle + document count + pagination + actions -->
<div class="h-9 flex items-center gap-1 px-3 border-b shrink-0 text-xs text-muted-foreground">
<div class="flex items-center border rounded-md overflow-hidden mr-2">
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 rounded-none"
- :class="{ 'bg-accent': viewMode === 'document' }"
- :title="t('mongo.documentView')"
- @click="viewMode = 'document'"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5 rounded-none" :class="{ 'bg-accent': viewMode === 'document' }" :title="t('mongo.documentView')" @click="viewMode = 'document'">
<Braces class="h-3 w-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 rounded-none"
- :class="{ 'bg-accent': viewMode === 'table' }"
- :title="t('mongo.tableView')"
- @click="viewMode = 'table'"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5 rounded-none" :class="{ 'bg-accent': viewMode === 'table' }" :title="t('mongo.tableView')" @click="viewMode = 'table'">
<Table2 class="h-3 w-3" />
</Button>
</div>
<span class="shrink-0 ml-1">{{ t("mongo.documents", { count: total }) }}</span>
- <Button v-if="viewMode === 'document'" variant="ghost" size="icon" class="h-5 w-5" @click="startNew"
- ><Plus class="h-3 w-3"
- /></Button>
- <Button v-if="viewMode === 'document'" variant="ghost" size="icon" class="h-5 w-5" @click="load"
- ><RefreshCw class="h-3 w-3" :class="{ 'animate-spin': loading }"
- /></Button>
+ <Button v-if="viewMode === 'document'" variant="ghost" size="icon" class="h-5 w-5" @click="startNew"><Plus class="h-3 w-3" /></Button>
+ <Button v-if="viewMode === 'document'" variant="ghost" size="icon" class="h-5 w-5" @click="load"><RefreshCw class="h-3 w-3" :class="{ 'animate-spin': loading }" /></Button>
<div v-if="viewMode === 'document'" class="flex items-center gap-1 ml-1">
<Button variant="ghost" size="icon" class="h-5 w-5" :disabled="page <= 0" @click="prevPage">
<ChevronLeft class="h-3 w-3" />
</Button>
<span>{{ page + 1 }} / {{ Math.max(1, Math.ceil(total / pageSize)) }}</span>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :disabled="(page + 1) * pageSize >= total"
- @click="nextPage"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="(page + 1) * pageSize >= total" @click="nextPage">
<ChevronRight class="h-3 w-3" />
</Button>
</div>
@@ -782,92 +694,41 @@ function resetTableSearchSplitWidth() {
<Popover v-if="viewMode === 'table' && gridResult.columns.length">
<PopoverTrigger as-child>
- <Button
- variant="ghost"
- size="sm"
- class="h-5 shrink-0 gap-1 px-1.5 text-xs text-foreground hover:bg-accent"
- :class="{ 'bg-accent text-foreground': (dataGridRef?.hiddenColumnCount ?? 0) > 0 }"
- :title="t('grid.columnVisibility')"
- :aria-label="t('grid.columnVisibility')"
- >
+ <Button variant="ghost" size="sm" class="h-5 shrink-0 gap-1 px-1.5 text-xs text-foreground hover:bg-accent" :class="{ 'bg-accent text-foreground': (dataGridRef?.hiddenColumnCount ?? 0) > 0 }" :title="t('grid.columnVisibility')" :aria-label="t('grid.columnVisibility')">
<Columns3 class="h-3.5 w-3.5" />
{{ t("grid.columnVisibility") }}
- <span v-if="(dataGridRef?.hiddenColumnCount ?? 0) > 0" class="tabular-nums">
- {{ dataGridRef?.visibleColumnCount }}/{{ dataGridRef?.displayableColumnCount }}
- </span>
+ <span v-if="(dataGridRef?.hiddenColumnCount ?? 0) > 0" class="tabular-nums"> {{ dataGridRef?.visibleColumnCount }}/{{ dataGridRef?.displayableColumnCount }} </span>
</Button>
</PopoverTrigger>
- <PopoverContent
- align="end"
- class="w-64 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="end" class="w-64 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-2 py-1.5">
<div class="flex items-center justify-between gap-2">
<div class="text-xs font-semibold">{{ t("grid.columnVisibility") }}</div>
- <div class="text-[10px] text-muted-foreground tabular-nums">
- {{ dataGridRef?.visibleColumnCount ?? 0 }}/{{ dataGridRef?.displayableColumnCount ?? 0 }}
- </div>
+ <div class="text-[10px] text-muted-foreground tabular-nums">{{ dataGridRef?.visibleColumnCount ?? 0 }}/{{ dataGridRef?.displayableColumnCount ?? 0 }}</div>
</div>
</div>
<div class="flex items-center gap-1.5 border-b px-2 py-1.5">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <input
- v-model="columnVisibilitySearch"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="h-6 min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground"
- :placeholder="t('grid.searchColumns')"
- />
+ <input v-model="columnVisibilitySearch" autocapitalize="off" autocorrect="off" spellcheck="false" class="h-6 min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground" :placeholder="t('grid.searchColumns')" />
</div>
<div class="max-h-72 overflow-auto py-0.5">
- <button
- v-for="option in columnVisibilityOptions"
- :key="`${option.index}:${option.column}`"
- type="button"
- class="grid w-full grid-cols-[1.5rem_minmax(0,1fr)] items-center px-2 py-1 text-left text-xs hover:bg-accent"
- @click="dataGridRef?.toggleColumnVisibility(option.index)"
- >
- <span
- class="flex h-4 w-4 items-center justify-center rounded border"
- :class="
- dataGridRef?.isColumnVisible(option.index)
- ? 'border-primary bg-primary text-primary-foreground'
- : 'border-border bg-background text-transparent'
- "
- >
+ <button v-for="option in columnVisibilityOptions" :key="`${option.index}:${option.column}`" type="button" class="grid w-full grid-cols-[1.5rem_minmax(0,1fr)] items-center px-2 py-1 text-left text-xs hover:bg-accent" @click="dataGridRef?.toggleColumnVisibility(option.index)">
+ <span class="flex h-4 w-4 items-center justify-center rounded border" :class="dataGridRef?.isColumnVisible(option.index) ? 'border-primary bg-primary text-primary-foreground' : 'border-border bg-background text-transparent'">
<Check class="h-3 w-3 stroke-[3]" />
</span>
<span class="truncate font-mono text-xs" :title="option.column">{{ option.column }}</span>
</button>
- <div
- v-if="columnVisibilityOptions.length === 0"
- class="px-2 py-6 text-center text-xs text-muted-foreground"
- >
+ <div v-if="columnVisibilityOptions.length === 0" class="px-2 py-6 text-center text-xs text-muted-foreground">
{{ t("grid.noSearchResults") }}
</div>
</div>
<div class="flex items-center justify-between gap-2 border-t bg-muted/30 px-2 py-1.5">
<span class="text-[11px] text-muted-foreground">{{ t("grid.columnVisibilityHint") }}</span>
<div class="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- class="h-7 px-2 text-xs"
- :disabled="(dataGridRef?.displayableColumnCount ?? 0) <= 1"
- @click="dataGridRef?.invertColumnVisibility()"
- >
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="(dataGridRef?.displayableColumnCount ?? 0) <= 1" @click="dataGridRef?.invertColumnVisibility()">
{{ t("grid.invertColumnVisibility") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-7 px-2 text-xs"
- :disabled="(dataGridRef?.hiddenColumnCount ?? 0) === 0"
- @click="dataGridRef?.showAllColumns()"
- >
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="(dataGridRef?.hiddenColumnCount ?? 0) === 0" @click="dataGridRef?.showAllColumns()">
{{ t("grid.showAllColumns") }}
</Button>
</div>
@@ -877,42 +738,19 @@ function resetTableSearchSplitWidth() {
<Popover v-if="viewMode === 'table' && gridResult.columns.length">
<PopoverTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-7 shrink-0 text-foreground hover:bg-accent"
- :class="{ 'bg-accent text-foreground': dataGridRef?.nullColumnsHidden }"
- :title="t('grid.viewOptions')"
- :aria-label="t('grid.viewOptions')"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-7 shrink-0 text-foreground hover:bg-accent" :class="{ 'bg-accent text-foreground': dataGridRef?.nullColumnsHidden }" :title="t('grid.viewOptions')" :aria-label="t('grid.viewOptions')">
<Wrench class="h-4 w-4" />
</Button>
</PopoverTrigger>
- <PopoverContent
- align="end"
- class="w-max min-w-44 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl"
- @click.stop
- @keydown.stop
- >
+ <PopoverContent align="end" class="w-max min-w-44 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-xl border bg-popover p-0 text-popover-foreground shadow-xl" @click.stop @keydown.stop>
<div class="border-b bg-muted/40 px-3 py-2">
<div class="text-xs font-semibold">{{ t("grid.viewOptions") }}</div>
</div>
- <label
- class="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs hover:bg-accent"
- :class="{ 'cursor-not-allowed opacity-60': !dataGridRef?.canToggleAllNullColumns }"
- >
- <input
- type="checkbox"
- class="h-3.5 w-3.5 shrink-0 accent-primary"
- :checked="!!dataGridRef?.nullColumnsHidden"
- :disabled="!dataGridRef?.canToggleAllNullColumns"
- @change="dataGridRef?.toggleAllNullColumns()"
- />
+ <label class="flex cursor-pointer items-center gap-2 px-3 py-2 text-xs hover:bg-accent" :class="{ 'cursor-not-allowed opacity-60': !dataGridRef?.canToggleAllNullColumns }">
+ <input type="checkbox" class="h-3.5 w-3.5 shrink-0 accent-primary" :checked="!!dataGridRef?.nullColumnsHidden" :disabled="!dataGridRef?.canToggleAllNullColumns" @change="dataGridRef?.toggleAllNullColumns()" />
<span class="min-w-0 flex items-center gap-1 font-medium">
{{ t("grid.hideNullColumns") }}
- <span v-if="(dataGridRef?.allNullColumnCount ?? 0) > 0" class="text-muted-foreground tabular-nums">
- ({{ dataGridRef?.allNullColumnCount }})
- </span>
+ <span v-if="(dataGridRef?.allNullColumnCount ?? 0) > 0" class="text-muted-foreground tabular-nums"> ({{ dataGridRef?.allNullColumnCount }}) </span>
</span>
</label>
</PopoverContent>
@@ -937,19 +775,7 @@ function resetTableSearchSplitWidth() {
@reload="load"
@paginate="(offset: number, limit: number) => paginate(offset, limit)"
>
- <template
- #search-bar="{
- localFilterCount,
- hasLocalColumnFilters,
- localFilterSummaries,
- clearLocalFilter,
- }: {
- localFilterCount: number;
- hasLocalColumnFilters: boolean;
- localFilterSummaries: LocalFilterSummary[];
- clearLocalFilter: (columnIndex?: number) => void;
- }"
- >
+ <template #search-bar="{ localFilterCount, hasLocalColumnFilters, localFilterSummaries, clearLocalFilter }: { localFilterCount: number; hasLocalColumnFilters: boolean; localFilterSummaries: LocalFilterSummary[]; clearLocalFilter: (columnIndex?: number) => void }">
<div ref="tableSearchSplitContainerRef" class="flex flex-1 min-w-0">
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0" :style="tableFindPaneStyle">
<Popover v-model:open="mongoFilterBuilderOpen">
@@ -957,18 +783,11 @@ function resetTableSearchSplitWidth() {
<button
type="button"
class="relative flex h-5 w-5 shrink-0 items-center justify-center rounded border text-[11px] font-medium transition-colors"
- :class="
- hasLocalColumnFilters || appliedMongoFilter
- ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15'
- : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'
- "
+ :class="hasLocalColumnFilters || appliedMongoFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"
@click="ensureMongoFilterRule"
>
<Filter class="h-3 w-3" />
- <span
- v-if="localFilterCount + mongoStructuredFilterCount"
- class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground"
- >
+ <span v-if="localFilterCount + mongoStructuredFilterCount" class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground">
{{ localFilterCount + mongoStructuredFilterCount }}
</span>
</button>
@@ -981,10 +800,7 @@ function resetTableSearchSplitWidth() {
{{ t("grid.filterBuilderAddRule") }}
</Button>
</div>
- <div
- v-if="hasLocalColumnFilters"
- class="space-y-2 rounded-md border border-primary/20 bg-primary/5 px-2.5 py-2"
- >
+ <div v-if="hasLocalColumnFilters" class="space-y-2 rounded-md border border-primary/20 bg-primary/5 px-2.5 py-2">
<div class="flex items-center justify-between gap-3">
<div class="flex min-w-0 items-center gap-2 text-xs font-medium text-primary">
<Filter class="h-3.5 w-3.5 shrink-0" />
@@ -996,11 +812,7 @@ function resetTableSearchSplitWidth() {
</Button>
</div>
<div class="space-y-1">
- <div
- v-for="summary in localFilterSummaries"
- :key="summary.columnIndex"
- class="grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.6fr)_auto] items-center gap-2 rounded border border-primary/10 bg-background/70 px-2 py-1 text-xs"
- >
+ <div v-for="summary in localFilterSummaries" :key="summary.columnIndex" class="grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.6fr)_auto] items-center gap-2 rounded border border-primary/10 bg-background/70 px-2 py-1 text-xs">
<span class="truncate font-medium text-foreground" :title="summary.columnName">
{{ summary.columnName }}
</span>
@@ -1013,13 +825,7 @@ function resetTableSearchSplitWidth() {
{{ t("grid.localFilterMoreValues", { count: summary.hiddenValueCount }) }}
</span>
</span>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6 text-muted-foreground hover:text-destructive"
- :title="t('grid.clearFilter')"
- @click="clearLocalFilter(summary.columnIndex)"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:text-destructive" :title="t('grid.clearFilter')" @click="clearLocalFilter(summary.columnIndex)">
<X class="h-3.5 w-3.5" />
</Button>
</div>
@@ -1042,18 +848,9 @@ function resetTableSearchSplitWidth() {
{{ rule.conjunction }}
</Button>
</div>
- <div
- class="grid grid-cols-[minmax(0,1fr)_minmax(0,0.95fr)_minmax(0,1fr)_auto] items-center gap-1.5"
- >
- <Select
- :model-value="rule.fieldName"
- @update:model-value="
- (value: any) => updateMongoFilterRule(rule.id, { fieldName: String(value) })
- "
- >
- <SelectTrigger
- class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate"
- >
+ <div class="grid grid-cols-[minmax(0,1fr)_minmax(0,0.95fr)_minmax(0,1fr)_auto] items-center gap-1.5">
+ <Select :model-value="rule.fieldName" @update:model-value="(value: any) => updateMongoFilterRule(rule.id, { fieldName: String(value) })">
+ <SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate">
<SelectValue :placeholder="t('grid.filterBuilderColumn')" />
</SelectTrigger>
<SelectContent position="popper">
@@ -1063,23 +860,12 @@ function resetTableSearchSplitWidth() {
</SelectContent>
</Select>
- <Select
- :model-value="rule.mode"
- @update:model-value="
- (value: any) => updateMongoFilterRule(rule.id, { mode: value as MongoFilterMode })
- "
- >
- <SelectTrigger
- class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate"
- >
+ <Select :model-value="rule.mode" @update:model-value="(value: any) => updateMongoFilterRule(rule.id, { mode: value as MongoFilterMode })">
+ <SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
- <SelectItem
- v-for="option in mongoFilterModeOptions"
- :key="option.value"
- :value="option.value"
- >
+ <SelectItem v-for="option in mongoFilterModeOptions" :key="option.value" :value="option.value">
{{ t(option.labelKey) }}
</SelectItem>
</SelectContent>
@@ -1090,25 +876,14 @@ function resetTableSearchSplitWidth() {
:model-value="rule.rawValue"
class="h-8 min-w-0 text-xs"
:placeholder="t('grid.filterBuilderValue')"
- @update:model-value="
- (value) => updateMongoFilterRule(rule.id, { rawValue: String(value ?? '') })
- "
+ @update:model-value="(value) => updateMongoFilterRule(rule.id, { rawValue: String(value ?? '') })"
@keydown.enter.prevent="applyMongoStructuredFilters"
/>
- <div
- v-else
- class="flex h-8 min-w-0 items-center overflow-hidden rounded-md border border-dashed px-2 text-xs text-muted-foreground"
- >
+ <div v-else class="flex h-8 min-w-0 items-center overflow-hidden rounded-md border border-dashed px-2 text-xs text-muted-foreground">
<span class="truncate">{{ t("grid.filterBuilderNoValue") }}</span>
</div>
- <Button
- variant="ghost"
- size="icon"
- class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
- :disabled="mongoFilterRules.length === 1"
- @click="removeMongoFilterRule(rule.id)"
- >
+ <Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :disabled="mongoFilterRules.length === 1" @click="removeMongoFilterRule(rule.id)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</div>
@@ -1119,12 +894,7 @@ function resetTableSearchSplitWidth() {
</div>
<div class="flex items-center justify-between gap-2 pt-1">
- <Button
- variant="ghost"
- size="sm"
- class="h-8 px-2 text-xs"
- @click="clearMongoFilters(clearLocalFilter)"
- >
+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="clearMongoFilters(clearLocalFilter)">
{{ t("grid.clearFilter") }}
</Button>
<div class="flex items-center gap-2">
@@ -1139,15 +909,7 @@ function resetTableSearchSplitWidth() {
</PopoverContent>
</Popover>
<span class="text-blue-600 dark:text-blue-400 text-xs font-medium select-none shrink-0">find</span>
- <input
- v-model="filterInput"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono"
- placeholder="{}"
- @keydown.enter="applyFilter"
- />
+ <input v-model="filterInput" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono" placeholder="{}" @keydown.enter="applyFilter" />
<button
v-if="filterInput.trim()"
class="text-muted-foreground hover:text-foreground shrink-0"
@@ -1170,15 +932,7 @@ function resetTableSearchSplitWidth() {
</button>
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0">
<span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0">sort</span>
- <input
- v-model="sortInput"
- autocapitalize="off"
- autocorrect="off"
- spellcheck="false"
- class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono"
- placeholder="{}"
- @keydown.enter="applyFilter"
- />
+ <input v-model="sortInput" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono" placeholder="{}" @keydown.enter="applyFilter" />
<button
v-if="sortInput.trim()"
class="text-muted-foreground hover:text-foreground shrink-0"
@@ -1207,20 +961,9 @@ function resetTableSearchSplitWidth() {
<Pane :size="30" :min-size="15" :max-size="50">
<div class="h-full flex flex-col overflow-hidden">
<div class="flex-1 overflow-y-auto">
- <div
- v-for="(doc, idx) in documents"
- :key="idx"
- class="px-3 py-1.5 border-b text-xs font-mono cursor-pointer hover:bg-accent/50 flex items-center gap-2 group"
- :class="{ 'bg-accent': selectedIdx === idx }"
- @click="selectDoc(idx)"
- >
+ <div v-for="(doc, idx) in documents" :key="idx" class="px-3 py-1.5 border-b text-xs font-mono cursor-pointer hover:bg-accent/50 flex items-center gap-2 group" :class="{ 'bg-accent': selectedIdx === idx }" @click="selectDoc(idx)">
<span class="truncate flex-1">{{ docPreview(doc) }}</span>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive shrink-0"
- @click.stop="requestDeleteDoc(idx)"
- >
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive shrink-0" @click.stop="requestDeleteDoc(idx)">
<Trash2 class="w-3 h-3" />
</Button>
</div>
@@ -1238,51 +981,28 @@ function resetTableSearchSplitWidth() {
<div class="h-9 flex items-center gap-2 px-4 border-b bg-muted/30 shrink-0">
<Badge variant="secondary" class="text-xs">{{ isNew ? "New" : selectedDoc?._id }}</Badge>
<span class="flex-1" />
- <Button v-if="!isEditing" variant="ghost" size="sm" class="h-6 text-xs" @click="startEdit">{{
- t("mongo.edit")
- }}</Button>
+ <Button v-if="!isEditing" variant="ghost" size="sm" class="h-6 text-xs" @click="startEdit">{{ t("mongo.edit") }}</Button>
<template v-if="isEditing">
- <Button variant="ghost" size="sm" class="h-6 text-xs" @click="addField">
- <Plus class="w-3 h-3 mr-1" /> {{ t("mongo.addField") }}
- </Button>
- <Button variant="ghost" size="sm" class="h-6 text-xs" @click="cancelEdit">{{
- t("grid.discard")
- }}</Button>
- <Button size="sm" class="h-6 text-xs" @click="saveDoc"
- ><Save class="w-3 h-3 mr-1" />{{ t("grid.save") }}</Button
- >
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="addField"> <Plus class="w-3 h-3 mr-1" /> {{ t("mongo.addField") }} </Button>
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="cancelEdit">{{ t("grid.discard") }}</Button>
+ <Button size="sm" class="h-6 text-xs" @click="saveDoc"><Save class="w-3 h-3 mr-1" />{{ t("grid.save") }}</Button>
</template>
</div>
<div v-if="isEditing" class="flex-1 overflow-auto bg-muted/10">
- <div
- class="json-edit min-w-fit p-5 font-mono text-[13px] leading-6"
- :style="{ '--mongo-key-width': editKeyWidth }"
- >
+ <div class="json-edit min-w-fit p-5 font-mono text-[13px] leading-6" :style="{ '--mongo-key-width': editKeyWidth }">
<div class="json-edit-brace">{</div>
- <JsonEditNode
- v-for="(field, idx) in editFields"
- :key="field.key"
- :node="field"
- parent-kind="root"
- :removable="!field.readonlyValue"
- @remove="requestRemoveField(idx)"
- />
+ <JsonEditNode v-for="(field, idx) in editFields" :key="field.key" :node="field" parent-kind="root" :removable="!field.readonlyValue" @remove="requestRemoveField(idx)" />
- <Button variant="ghost" size="sm" class="json-edit-add" @click="addField">
- <Plus class="w-3 h-3 mr-1" /> {{ t("mongo.addField") }}
- </Button>
+ <Button variant="ghost" size="sm" class="json-edit-add" @click="addField"> <Plus class="w-3 h-3 mr-1" /> {{ t("mongo.addField") }} </Button>
<div class="json-edit-brace">}</div>
</div>
</div>
<div v-else class="flex-1 overflow-auto bg-muted/10">
- <pre
- class="json-viewer min-w-fit p-5 font-mono text-[13px] leading-6"
- v-html="highlightedJson(editJson)"
- />
+ <pre class="json-viewer min-w-fit p-5 font-mono text-[13px] leading-6" v-html="highlightedJson(editJson)" />
</div>
</template>
<div v-else class="h-full flex items-center justify-center text-muted-foreground text-sm">
@@ -1292,13 +1012,7 @@ function resetTableSearchSplitWidth() {
<div v-if="error" class="px-3 py-1.5 border-t bg-destructive/10 text-destructive text-xs shrink-0">
{{ error }}
</div>
- <DangerConfirmDialog
- v-model:open="showDeleteConfirm"
- :message="t('dangerDialog.deleteMessage')"
- :details="deleteDetails"
- :confirm-label="t('dangerDialog.deleteConfirm')"
- @confirm="confirmDelete"
- />
+ <DangerConfirmDialog v-model:open="showDeleteConfirm" :message="t('dangerDialog.deleteMessage')" :details="deleteDetails" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDelete" />
</div>
</Pane>
</Splitpanes>
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index f5631eb337..a1b89739e5 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -46,28 +46,12 @@ import ProcedureExecutionDialog from "@/components/objects/ProcedureExecutionDia
import * as api from "@/lib/api";
import type { ConnectionConfig, ObjectInfo, ObjectSourceKind } from "@/types/database";
import { isSchemaAware } from "@/lib/databaseCapabilities";
-import {
- supportsSchemaDiagram,
- supportsTableImport,
- supportsTableStructureEditing,
- supportsTableTruncate,
-} from "@/lib/databaseFeatureSupport";
+import { supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/databaseFeatureSupport";
import { connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
import { buildTableSelectSql } from "@/lib/tableSelectSql";
-import {
- buildDropObjectSql,
- buildDuplicateTableStructureSql,
- buildEmptyTableSql,
- buildTruncateTableSql,
- type TableAdminSqlOptions,
-} from "@/lib/dbAdminSql";
+import { buildDropObjectSql, buildDuplicateTableStructureSql, buildEmptyTableSql, buildTruncateTableSql, type TableAdminSqlOptions } from "@/lib/dbAdminSql";
import { useToast } from "@/composables/useToast";
-import {
- buildExecutableObjectSourceStatements,
- buildRoutineRenameObjectSourceStatements,
- objectSourceSaveExecutionMode,
- supportsSourceBackedRoutineRename,
-} from "@/lib/objectSourceEditor";
+import { buildExecutableObjectSourceStatements, buildRoutineRenameObjectSourceStatements, objectSourceSaveExecutionMode, supportsSourceBackedRoutineRename } from "@/lib/objectSourceEditor";
import { buildRenameObjectSql, supportsObjectRename } from "@/lib/objectRenameSql";
import { buildViewDdl } from "@/lib/viewDdl";
import { isTauriRuntime } from "@/lib/tauriRuntime";
@@ -83,16 +67,7 @@ import QueryEditor from "@/components/editor/QueryEditor.vue";
import type { SqlFormatDialect } from "@/lib/sqlFormatter";
import { isCancelSearchShortcut } from "@/lib/keyboardShortcuts";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import {
- buildObjectBrowserRows,
- filterObjectBrowserRows,
- formatObjectBrowserTimestamp,
- initialObjectBrowserSortDirection,
- sortObjectBrowserRows,
- type ObjectBrowserRow,
- type ObjectBrowserSortDirection,
- type ObjectBrowserSortKey,
-} from "@/lib/objectBrowserRows";
+import { buildObjectBrowserRows, filterObjectBrowserRows, formatObjectBrowserTimestamp, initialObjectBrowserSortDirection, sortObjectBrowserRows, type ObjectBrowserRow, type ObjectBrowserSortDirection, type ObjectBrowserSortKey } from "@/lib/objectBrowserRows";
type ObjectFilter = "all" | "tables" | "views" | "procedures" | "functions" | "sequences" | "packages";
@@ -130,9 +105,7 @@ const sourceContent = ref("");
const sourceError = ref("");
const sourceRow = ref<ObjectBrowserRow | null>(null);
const sourceEditing = ref(false);
-const effectiveDatabaseType = computed(
- () => effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type,
-);
+const effectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type);
const sourceDraft = ref("");
const sourceSaving = ref(false);
const sourceSaveError = ref("");
@@ -164,29 +137,19 @@ let loadId = 0;
// Export via background tracker
const { addTask: addExportTask } = useExportTracker();
-const needsSchema = computed(
- () => isSchemaAware(props.connection.db_type) && !connectionUsesDatabaseObjectTreeMode(props.connection),
-);
+const needsSchema = computed(() => isSchemaAware(props.connection.db_type) && !connectionUsesDatabaseObjectTreeMode(props.connection));
const tableCount = computed(() => rows.value.filter((row) => row.type === "TABLE").length);
const viewCount = computed(() => rows.value.filter((row) => row.type === "VIEW").length);
const procedureCount = computed(() => rows.value.filter((row) => row.type === "PROCEDURE").length);
const functionCount = computed(() => rows.value.filter((row) => row.type === "FUNCTION").length);
const sequenceCount = computed(() => rows.value.filter((row) => row.type === "SEQUENCE").length);
-const packageCount = computed(
- () => rows.value.filter((row) => row.type === "PACKAGE" || row.type === "PACKAGE_BODY").length,
-);
+const packageCount = computed(() => rows.value.filter((row) => row.type === "PACKAGE" || row.type === "PACKAGE_BODY").length);
const canOpenStructureEditor = computed(() => supportsTableStructureEditing(effectiveDatabaseType.value));
const canOpenDiagram = computed(() => !!props.database && supportsSchemaDiagram(effectiveDatabaseType.value));
const canOpenTableImport = computed(() => !!props.database && supportsTableImport(effectiveDatabaseType.value));
const supportsTruncateTable = computed(() => supportsTableTruncate(effectiveDatabaseType.value));
const sourceDialect = computed<"mysql" | "postgres" | "sqlserver">(() => {
- if (
- effectiveDatabaseType.value === "postgres" ||
- effectiveDatabaseType.value === "gaussdb" ||
- effectiveDatabaseType.value === "kwdb" ||
- effectiveDatabaseType.value === "opengauss"
- )
- return "postgres";
+ if (effectiveDatabaseType.value === "postgres" || effectiveDatabaseType.value === "gaussdb" || effectiveDatabaseType.value === "kwdb" || effectiveDatabaseType.value === "opengauss") return "postgres";
if (effectiveDatabaseType.value === "sqlserver") return "sqlserver";
return "mysql";
});
@@ -252,11 +215,7 @@ const selectedTableRows = computed(() => {
return selectableRows.value.filter((row) => ids.has(row.id));
});
const selectedTableCount = computed(() => selectedTableRows.value.length);
-const allVisibleTablesSelected = computed(
- () =>
- visibleSelectableRows.value.length > 0 &&
- visibleSelectableRows.value.every((row) => selectedTableIds.value.has(row.id)),
-);
+const allVisibleTablesSelected = computed(() => visibleSelectableRows.value.length > 0 && visibleSelectableRows.value.every((row) => selectedTableIds.value.has(row.id)));
function iconFor(row: ObjectBrowserRow) {
if (row.type === "VIEW") return Eye;
@@ -307,9 +266,7 @@ function groupedFilteredRows() {
const candidateIds = new Set(candidateRows.map((row) => row.id));
const matchingRows = filterObjectBrowserRows(candidateRows, query);
const matchingIds = new Set(matchingRows.map((row) => row.id));
- const parentIdsWithMatchingPartitions = new Set(
- matchingRows.flatMap((row) => (row.partitionParentId ? [row.partitionParentId] : [])),
- );
+ const parentIdsWithMatchingPartitions = new Set(matchingRows.flatMap((row) => (row.partitionParentId ? [row.partitionParentId] : [])));
const rootRows = candidateRows.filter((row) => {
if (row.partitionParentId) return false;
if (!query) return true;
@@ -325,8 +282,7 @@ function groupedFilteredRows() {
const parentMatches = matchingIds.has(row.id);
const shouldShowPartitions = expandedPartitionParentIds.value.has(row.id) || !!query;
if (!shouldShowPartitions) continue;
- const visiblePartitions =
- query && !parentMatches ? partitions.filter((partition) => matchingIds.has(partition.id)) : partitions;
+ const visiblePartitions = query && !parentMatches ? partitions.filter((partition) => matchingIds.has(partition.id)) : partitions;
result.push(...sortObjectBrowserRows(visiblePartitions, sortKey.value, sortDirection.value));
}
@@ -355,21 +311,11 @@ function togglePartitionParent(row: ObjectBrowserRow) {
}
function canOpenSource(row: ObjectBrowserRow) {
- return (
- row.type === "VIEW" ||
- row.type === "PROCEDURE" ||
- row.type === "FUNCTION" ||
- row.type === "SEQUENCE" ||
- row.type === "PACKAGE" ||
- row.type === "PACKAGE_BODY"
- );
+ return row.type === "VIEW" || row.type === "PROCEDURE" || row.type === "FUNCTION" || row.type === "SEQUENCE" || row.type === "PACKAGE" || row.type === "PACKAGE_BODY";
}
function canRename(row: ObjectBrowserRow) {
- return (
- supportsObjectRename(effectiveDatabaseType.value, row.type) ||
- supportsSourceBackedRoutineRename(effectiveDatabaseType.value, row.type as ObjectSourceKind)
- );
+ return supportsObjectRename(effectiveDatabaseType.value, row.type) || supportsSourceBackedRoutineRename(effectiveDatabaseType.value, row.type as ObjectSourceKind);
}
function sourceTitle(row: ObjectBrowserRow | null) {
@@ -405,13 +351,7 @@ async function openSource(row: ObjectBrowserRow) {
sourceSaveError.value = "";
sourceLoading.value = true;
try {
- const result = await api.getObjectSource(
- props.connection.id,
- props.database,
- row.schema || selectedSchema.value || props.database,
- row.name,
- row.type as ObjectSourceKind,
- );
+ const result = await api.getObjectSource(props.connection.id, props.database, row.schema || selectedSchema.value || props.database, row.name, row.type as ObjectSourceKind);
sourceContent.value = result.source;
sourceDraft.value = result.source;
sourceEditing.value = row.type !== "SEQUENCE";
@@ -425,13 +365,7 @@ async function openSource(row: ObjectBrowserRow) {
async function openViewDdl(row: ObjectBrowserRow) {
if (row.type !== "VIEW") return;
try {
- const result = await api.getObjectSource(
- props.connection.id,
- props.database,
- row.schema || selectedSchema.value || props.database,
- row.name,
- "VIEW",
- );
+ const result = await api.getObjectSource(props.connection.id, props.database, row.schema || selectedSchema.value || props.database, row.name, "VIEW");
const ddl = await buildViewDdl({
databaseType: effectiveDatabaseType.value,
schema: row.schema || selectedSchema.value || props.database,
@@ -534,13 +468,7 @@ async function confirmRename() {
try {
const schema = row.schema || selectedSchema.value || props.database;
if (supportsSourceBackedRoutineRename(effectiveDatabaseType.value, row.type as ObjectSourceKind)) {
- const source = await api.getObjectSource(
- props.connection.id,
- props.database,
- schema,
- row.name,
- row.type as ObjectSourceKind,
- );
+ const source = await api.getObjectSource(props.connection.id, props.database, schema, row.name, row.type as ObjectSourceKind);
const statements = await buildRoutineRenameObjectSourceStatements({
databaseType: effectiveDatabaseType.value,
objectType: row.type as ObjectSourceKind,
@@ -566,11 +494,7 @@ async function confirmRename() {
showRenameDialog.value = false;
if (sourceRow.value?.id === row.id) closeSource();
await reload();
- await connectionStore.refreshObjectListTreeNode(
- props.connection.id,
- props.database,
- row.schema || selectedSchema.value,
- );
+ await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, row.schema || selectedSchema.value);
} catch (e: any) {
renameError.value = e?.message || String(e);
}
@@ -587,21 +511,10 @@ async function confirmDrop() {
name: row.name,
});
await api.executeQuery(props.connection.id, props.database, sql);
- const successKey =
- row.type === "VIEW"
- ? "contextMenu.dropViewSuccess"
- : row.type === "PROCEDURE"
- ? "contextMenu.dropProcedureSuccess"
- : row.type === "FUNCTION"
- ? "contextMenu.dropFunctionSuccess"
- : "contextMenu.dropTableSuccess";
+ const successKey = row.type === "VIEW" ? "contextMenu.dropViewSuccess" : row.type === "PROCEDURE" ? "contextMenu.dropProcedureSuccess" : row.type === "FUNCTION" ? "contextMenu.dropFunctionSuccess" : "contextMenu.dropTableSuccess";
toast(t(successKey, { name: row.name }));
await reload();
- await connectionStore.refreshObjectListTreeNode(
- props.connection.id,
- props.database,
- row.schema || selectedSchema.value,
- );
+ await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, row.schema || selectedSchema.value);
} catch (e: any) {
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
@@ -798,17 +711,8 @@ async function exportStructure(row: ObjectBrowserRow) {
async function exportDataLegacy(row: ObjectBrowserRow, format: "json" | "sql") {
try {
const schema = row.schema || selectedSchema.value;
- const tableColumns =
- format === "sql"
- ? await api.getColumns(props.connection.id, props.database, schema || props.database, row.name)
- : undefined;
- const queryColumns =
- props.connection.db_type === "neo4j"
- ? (
- tableColumns ??
- (await api.getColumns(props.connection.id, props.database, schema || props.database, row.name))
- ).map((column) => column.name)
- : undefined;
+ const tableColumns = format === "sql" ? await api.getColumns(props.connection.id, props.database, schema || props.database, row.name) : undefined;
+ const queryColumns = props.connection.db_type === "neo4j" ? (tableColumns ?? (await api.getColumns(props.connection.id, props.database, schema || props.database, row.name))).map((column) => column.name) : undefined;
const result = await fetchTableDataForExport({
databaseType: effectiveDatabaseType.value,
schema,
@@ -848,10 +752,7 @@ async function exportDataLegacy(row: ObjectBrowserRow, format: "json" | "sql") {
}
}
-function columnTypesForResultColumns(
- columns: string[],
- tableColumns: Array<{ name: string; data_type: string }>,
-): Array<string | undefined> {
+function columnTypesForResultColumns(columns: string[], tableColumns: Array<{ name: string; data_type: string }>): Array<string | undefined> {
const typesByName = new Map(tableColumns.map((column) => [column.name.toLocaleLowerCase(), column.data_type]));
return columns.map((column) => typesByName.get(column.toLocaleLowerCase()));
}
@@ -896,12 +797,7 @@ async function exportTableData(row: ObjectBrowserRow, format: "csv" | "xlsx") {
let task: ExportTask | null = null;
try {
- const queryColumns =
- props.connection.db_type === "neo4j"
- ? (await api.getColumns(props.connection.id, props.database, schema || props.database, row.name)).map(
- (column) => column.name,
- )
- : undefined;
+ const queryColumns = props.connection.db_type === "neo4j" ? (await api.getColumns(props.connection.id, props.database, schema || props.database, row.name)).map((column) => column.name) : undefined;
task = addExportTask(row.name, format, filePath);
const currentTask = task;
@@ -1118,11 +1014,7 @@ async function loadObjects() {
});
const availableTableIds = new Set(rows.value.filter((row) => row.type === "TABLE").map((row) => row.id));
setSelectedTableIds(new Set([...selectedTableIds.value].filter((id) => availableTableIds.has(id))));
- expandedPartitionParentIds.value = new Set(
- [...expandedPartitionParentIds.value].filter((id) =>
- rows.value.some((row) => row.id === id && row.partitionCount),
- ),
- );
+ expandedPartitionParentIds.value = new Set([...expandedPartitionParentIds.value].filter((id) => rows.value.some((row) => row.id === id && row.partitionCount)));
} catch (e: any) {
if (id !== loadId) return;
error.value = e?.message || String(e);
@@ -1160,20 +1052,7 @@ function filterCount(filter: ObjectFilter) {
}
function filterLabel(filter: ObjectFilter) {
- const key =
- filter === "tables"
- ? "objects.tables"
- : filter === "views"
- ? "objects.views"
- : filter === "procedures"
- ? "objects.procedures"
- : filter === "functions"
- ? "objects.functions"
- : filter === "sequences"
- ? "objects.sequences"
- : filter === "packages"
- ? "objects.packages"
- : "objects.all";
+ const key = filter === "tables" ? "objects.tables" : filter === "views" ? "objects.views" : filter === "procedures" ? "objects.procedures" : filter === "functions" ? "objects.functions" : filter === "sequences" ? "objects.sequences" : filter === "packages" ? "objects.packages" : "objects.all";
return `${t(key)} ${filterCount(filter)}`;
}
@@ -1227,17 +1106,11 @@ function exportDataSubmenu(item: ObjectBrowserRow): ContextMenuItem {
function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
return [
{ label: t("contextMenu.viewData"), action: () => openRow(item), icon: Table2 },
- ...(canOpenStructureEditor.value
- ? [{ label: t("contextMenu.editStructure"), action: () => openStructureEditor(item), icon: PencilRuler }]
- : []),
- ...(canRename(item)
- ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }]
- : []),
+ ...(canOpenStructureEditor.value ? [{ label: t("contextMenu.editStructure"), action: () => openStructureEditor(item), icon: PencilRuler }] : []),
+ ...(canRename(item) ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }] : []),
{ label: t("contextMenu.newQuery"), action: () => openNewQuery(item), icon: TerminalSquare },
...(canOpenDiagram.value ? [{ label: t("diagram.open"), action: () => openDiagram(item), icon: Network }] : []),
- ...(canOpenTableImport.value
- ? [{ label: t("contextMenu.importData"), action: () => openTableImport(item), icon: Download }]
- : []),
+ ...(canOpenTableImport.value ? [{ label: t("contextMenu.importData"), action: () => openTableImport(item), icon: Download }] : []),
{ label: t("dataCompare.title"), action: () => openDataCompare(item), icon: ArrowRightLeft },
{ label: "", separator: true },
exportDataSubmenu(item),
@@ -1279,9 +1152,7 @@ function getViewMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
{ label: t("contextMenu.editView"), action: () => openSource(item), icon: PencilLine },
{ label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },
{ label: t("contextMenu.viewDdl"), action: () => openViewDdl(item), icon: ScrollText },
- ...(canRename(item)
- ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }]
- : []),
+ ...(canRename(item) ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }] : []),
{ label: t("contextMenu.newQuery"), action: () => openNewQuery(item), icon: TerminalSquare },
...(canOpenDiagram.value ? [{ label: t("diagram.open"), action: () => openDiagram(item), icon: Network }] : []),
{ label: "", separator: true },
@@ -1302,13 +1173,9 @@ function getViewMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
function getProcFuncMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
return [
- ...(item.type === "PROCEDURE"
- ? [{ label: t("contextMenu.executeProcedure"), action: () => openProcedureExecution(item), icon: Play }]
- : []),
+ ...(item.type === "PROCEDURE" ? [{ label: t("contextMenu.executeProcedure"), action: () => openProcedureExecution(item), icon: Play }] : []),
{ label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },
- ...(canRename(item)
- ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }]
- : []),
+ ...(canRename(item) ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }] : []),
{ label: "", separator: true },
{
label: item.type === "PROCEDURE" ? t("contextMenu.dropProcedure") : t("contextMenu.dropFunction"),
@@ -1346,19 +1213,11 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<div class="min-w-0 truncate text-sm font-medium">
{{ props.database }}<template v-if="selectedSchema"> / {{ selectedSchema }}</template>
</div>
- <div class="shrink-0 rounded border bg-muted/40 px-1.5 py-0.5 text-xs text-muted-foreground">
- {{ filteredRows.length }} / {{ rows.length }}
- </div>
+ <div class="shrink-0 rounded border bg-muted/40 px-1.5 py-0.5 text-xs text-muted-foreground">{{ filteredRows.length }} / {{ rows.length }}</div>
</div>
<div class="flex min-w-[240px] flex-1 items-center gap-2">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <Input
- v-model="search"
- data-object-search-input
- class="h-7 text-xs"
- :placeholder="t('objects.search')"
- @keydown="onSearchKeydown"
- />
+ <Input v-model="search" data-object-search-input class="h-7 text-xs" :placeholder="t('objects.search')" @keydown="onSearchKeydown" />
<div v-if="showObjectFilter" class="flex h-7 shrink-0 items-center rounded border bg-muted/20 p-0.5">
<button
v-for="filter in objectFilters"
@@ -1375,12 +1234,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
</button>
</div>
</div>
- <Select
- v-if="needsSchema"
- :model-value="selectedSchema"
- :disabled="loadingSchemas"
- @update:model-value="onSchemaChange"
- >
+ <Select v-if="needsSchema" :model-value="selectedSchema" :disabled="loadingSchemas" @update:model-value="onSchemaChange">
<SelectTrigger class="h-7 w-36 text-xs">
<SelectValue :placeholder="loadingSchemas ? t('objects.loadingSchemas') : t('objects.schema')" />
</SelectTrigger>
@@ -1417,23 +1271,12 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<div v-else-if="error" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-destructive">
{{ error }}
</div>
- <div
- v-else-if="filteredRows.length === 0"
- class="flex flex-1 items-center justify-center text-sm text-muted-foreground"
- >
+ <div v-else-if="filteredRows.length === 0" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">
{{ t("objects.empty") }}
</div>
<div v-else class="flex min-h-0 flex-1 flex-col">
- <div
- class="grid h-8 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground"
- :style="{ gridTemplateColumns }"
- >
- <button
- class="flex h-6 w-6 items-center justify-center rounded-sm hover:bg-accent"
- type="button"
- :disabled="visibleSelectableRows.length === 0"
- @click="toggleVisibleTableSelection"
- >
+ <div class="grid h-8 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground" :style="{ gridTemplateColumns }">
+ <button class="flex h-6 w-6 items-center justify-center rounded-sm hover:bg-accent" type="button" :disabled="visibleSelectableRows.length === 0" @click="toggleVisibleTableSelection">
<CheckSquare v-if="allVisibleTablesSelected" class="h-3.5 w-3.5 text-primary" />
<Square v-else class="h-3.5 w-3.5" />
</button>
@@ -1445,42 +1288,20 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<span class="truncate">{{ t("objects.type") }}</span>
<component :is="sortIconFor('type')" v-if="sortIconFor('type')" class="h-3 w-3 shrink-0" />
</button>
- <button
- v-if="hasCreatedAt"
- class="flex min-w-0 items-center gap-1 truncate text-left"
- type="button"
- @click="toggleSort('created_at')"
- >
+ <button v-if="hasCreatedAt" class="flex min-w-0 items-center gap-1 truncate text-left" type="button" @click="toggleSort('created_at')">
<span class="truncate">{{ t("objects.createdAt") }}</span>
<component :is="sortIconFor('created_at')" v-if="sortIconFor('created_at')" class="h-3 w-3 shrink-0" />
</button>
- <button
- v-if="hasUpdatedAt"
- class="flex min-w-0 items-center gap-1 truncate text-left"
- type="button"
- @click="toggleSort('updated_at')"
- >
+ <button v-if="hasUpdatedAt" class="flex min-w-0 items-center gap-1 truncate text-left" type="button" @click="toggleSort('updated_at')">
<span class="truncate">{{ t("objects.updatedAt") }}</span>
<component :is="sortIconFor('updated_at')" v-if="sortIconFor('updated_at')" class="h-3 w-3 shrink-0" />
</button>
- <button
- v-if="hasComments"
- class="flex min-w-0 items-center gap-1 truncate text-left"
- type="button"
- @click="toggleSort('comment')"
- >
+ <button v-if="hasComments" class="flex min-w-0 items-center gap-1 truncate text-left" type="button" @click="toggleSort('comment')">
<span class="truncate">{{ t("objects.comment") }}</span>
<component :is="sortIconFor('comment')" v-if="sortIconFor('comment')" class="h-3 w-3 shrink-0" />
</button>
</div>
- <RecycleScroller
- class="object-browser-scroller min-h-0 flex-1"
- :items="filteredRows"
- :item-size="38"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller class="object-browser-scroller min-h-0 flex-1" :items="filteredRows" :item-size="38" :buffer="600" :skip-hover="true" key-field="id">
<template #default="{ item }">
<CustomContextMenu :items="getObjectBrowserMenuItems(item)" v-slot="{ onContextMenu }">
<div
@@ -1493,12 +1314,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
@click="onRowClick(item, $event)"
@contextmenu="onContextMenu"
>
- <button
- class="flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
- type="button"
- :class="{ invisible: item.type !== 'TABLE' }"
- @click.stop="toggleTableSelection(item)"
- >
+ <button class="flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground" type="button" :class="{ invisible: item.type !== 'TABLE' }" @click.stop="toggleTableSelection(item)">
<CheckSquare v-if="selectedTableIds.has(item.id)" class="h-3.5 w-3.5 text-primary" />
<Square v-else class="h-3.5 w-3.5" />
</button>
@@ -1516,26 +1332,15 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<span v-else class="h-5 w-5 shrink-0" :class="{ 'ml-4': item.partitionParentId }" />
<component :is="iconFor(item)" class="h-3.5 w-3.5 shrink-0" :class="iconClass(item.type)" />
<span class="truncate text-[13px] font-medium text-foreground">{{ item.name }}</span>
- <span
- v-if="item.partitionCount"
- class="shrink-0 rounded border bg-muted/40 px-1.5 py-0.5 text-[10px] font-medium leading-none text-muted-foreground"
- >
+ <span v-if="item.partitionCount" class="shrink-0 rounded border bg-muted/40 px-1.5 py-0.5 text-[10px] font-medium leading-none text-muted-foreground">
{{ t("objects.partitions", { count: item.partitionCount }) }}
</span>
</div>
<div class="truncate text-xs text-muted-foreground">{{ typeLabel(item.type) }}</div>
- <div
- v-if="hasCreatedAt"
- class="truncate text-xs tabular-nums text-muted-foreground"
- :title="formatObjectBrowserTimestamp(item.created_at)"
- >
+ <div v-if="hasCreatedAt" class="truncate text-xs tabular-nums text-muted-foreground" :title="formatObjectBrowserTimestamp(item.created_at)">
{{ formatObjectBrowserTimestamp(item.created_at) }}
</div>
- <div
- v-if="hasUpdatedAt"
- class="truncate text-xs tabular-nums text-muted-foreground"
- :title="formatObjectBrowserTimestamp(item.updated_at)"
- >
+ <div v-if="hasUpdatedAt" class="truncate text-xs tabular-nums text-muted-foreground" :title="formatObjectBrowserTimestamp(item.updated_at)">
{{ formatObjectBrowserTimestamp(item.updated_at) }}
</div>
<div v-if="hasComments" class="truncate text-xs text-muted-foreground" :title="item.comment || ''">
@@ -1549,45 +1354,17 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<div class="flex h-8 shrink-0 items-center gap-2 border-b bg-muted/20 px-3">
<Code2 class="h-3.5 w-3.5 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate text-xs font-medium">{{ sourceTitle(sourceRow) }}</span>
- <Button
- v-if="sourceEditing"
- variant="ghost"
- size="sm"
- class="h-6 px-2 text-xs"
- :disabled="sourceSaving || !sourceDraft.trim()"
- @click="saveSource"
- >
+ <Button v-if="sourceEditing" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="sourceSaving || !sourceDraft.trim()" @click="saveSource">
<Loader2 v-if="sourceSaving" class="mr-1 h-3 w-3 animate-spin" />
{{ t("objects.saveSource") }}
</Button>
- <Button
- v-if="sourceEditing"
- variant="ghost"
- size="sm"
- class="h-6 px-2 text-xs"
- :disabled="sourceSaving"
- @click="cancelEditSource"
- >
+ <Button v-if="sourceEditing" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="sourceSaving" @click="cancelEditSource">
{{ t("objects.cancelEdit") }}
</Button>
- <Button
- v-if="!sourceEditing"
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :disabled="!sourceContent"
- @click="copySource"
- >
+ <Button v-if="!sourceEditing" variant="ghost" size="icon" class="h-5 w-5" :disabled="!sourceContent" @click="copySource">
<Copy class="h-3 w-3" />
</Button>
- <Button
- v-if="!sourceEditing"
- variant="ghost"
- size="icon"
- class="h-5 w-5"
- :disabled="!sourceContent"
- @click="editSource"
- >
+ <Button v-if="!sourceEditing" variant="ghost" size="icon" class="h-5 w-5" :disabled="!sourceContent" @click="editSource">
<PencilLine class="h-3 w-3" />
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="closeSource">
@@ -1601,18 +1378,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
{{ sourceError }}
</div>
<div v-else-if="sourceEditing" class="flex min-h-0 flex-1 flex-col" data-object-source-editor>
- <QueryEditor
- v-model="sourceDraft"
- class="min-h-0 flex-1"
- :connection-id="props.connection.id"
- :database="props.database"
- :schema="selectedSchema"
- :database-type="props.connection.db_type"
- :dialect="sourceDialect"
- :format-dialect="sourceFormatDialect"
- force-word-wrap
- @save="saveSource"
- />
+ <QueryEditor v-model="sourceDraft" class="min-h-0 flex-1" :connection-id="props.connection.id" :database="props.database" :schema="selectedSchema" :database-type="props.connection.db_type" :dialect="sourceDialect" :format-dialect="sourceFormatDialect" force-word-wrap @save="saveSource" />
<div v-if="sourceSaveError" class="shrink-0 border-t px-3 py-2 text-xs text-destructive">
{{ sourceSaveError }}
</div>
@@ -1636,22 +1402,9 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
</div>
</div>
- <DangerConfirmDialog
- v-model:open="showDropConfirm"
- :title="dropConfirmTitle()"
- :details="dropConfirmMessage()"
- :confirm-label="t('dangerDialog.deleteConfirm')"
- @confirm="confirmDrop"
- />
+ <DangerConfirmDialog v-model:open="showDropConfirm" :title="dropConfirmTitle()" :details="dropConfirmMessage()" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDrop" />
- <DangerConfirmDialog
- v-model:open="showBatchDropConfirm"
- :title="t('objects.confirmBatchDropTitle')"
- :message="t('objects.confirmBatchDropMessage', { count: selectedTableCount })"
- :sql="batchDropPreviewSql"
- :confirm-label="t('objects.dropSelected')"
- @confirm="confirmBatchDropTables"
- />
+ <DangerConfirmDialog v-model:open="showBatchDropConfirm" :title="t('objects.confirmBatchDropTitle')" :message="t('objects.confirmBatchDropMessage', { count: selectedTableCount })" :sql="batchDropPreviewSql" :confirm-label="t('objects.dropSelected')" @confirm="confirmBatchDropTables" />
<Dialog v-model:open="showRenameDialog">
<DialogContent class="sm:max-w-[420px]">
@@ -1659,16 +1412,8 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<DialogTitle>{{ t("contextMenu.renameObjectTitle") }}</DialogTitle>
</DialogHeader>
<div class="grid gap-3">
- <Input
- v-model="renameInput"
- :placeholder="t('contextMenu.renameObjectNamePlaceholder')"
- @keydown.enter.prevent="confirmRename"
- />
- <pre
- v-if="renamePreviewSqlText"
- class="max-h-32 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap"
- v-html="highlight(renamePreviewSqlText)"
- ></pre>
+ <Input v-model="renameInput" :placeholder="t('contextMenu.renameObjectNamePlaceholder')" @keydown.enter.prevent="confirmRename" />
+ <pre v-if="renamePreviewSqlText" class="max-h-32 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap" v-html="highlight(renamePreviewSqlText)"></pre>
<p v-if="renameError" class="text-sm text-destructive">{{ renameError }}</p>
</div>
<DialogFooter>
@@ -1689,14 +1434,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
@confirm="confirmTruncateTable"
/>
- <DangerConfirmDialog
- v-model:open="showEmptyConfirm"
- :title="t('contextMenu.confirmEmptyTableTitle')"
- :message="t('contextMenu.confirmEmptyTableMessage', { name: emptyTarget?.name ?? '' })"
- :sql="emptyPreviewSql"
- :confirm-label="t('contextMenu.emptyTable')"
- @confirm="confirmEmptyTable"
- />
+ <DangerConfirmDialog v-model:open="showEmptyConfirm" :title="t('contextMenu.confirmEmptyTableTitle')" :message="t('contextMenu.confirmEmptyTableMessage', { name: emptyTarget?.name ?? '' })" :sql="emptyPreviewSql" :confirm-label="t('contextMenu.emptyTable')" @confirm="confirmEmptyTable" />
<ProcedureExecutionDialog
v-if="procedureExecutionTarget"
@@ -1715,11 +1453,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<DialogHeader>
<DialogTitle>{{ t("contextMenu.duplicateNameTitle") }}</DialogTitle>
</DialogHeader>
- <Input
- v-model="duplicateTableName"
- :placeholder="t('contextMenu.duplicateNamePlaceholder')"
- @keydown.enter.prevent="confirmDuplicateStructure"
- />
+ <Input v-model="duplicateTableName" :placeholder="t('contextMenu.duplicateNamePlaceholder')" @keydown.enter.prevent="confirmDuplicateStructure" />
<DialogFooter>
<Button variant="outline" @click="showDuplicateDialog = false">{{ t("dangerDialog.cancel") }}</Button>
<Button :disabled="!duplicateTableName.trim()" @click="confirmDuplicateStructure">
diff --git a/apps/desktop/src/components/objects/ProcedureExecutionDialog.vue b/apps/desktop/src/components/objects/ProcedureExecutionDialog.vue
index bb8d28d61f..305b744ac2 100644
--- a/apps/desktop/src/components/objects/ProcedureExecutionDialog.vue
+++ b/apps/desktop/src/components/objects/ProcedureExecutionDialog.vue
@@ -8,12 +8,7 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "
import { Input } from "@/components/ui/input";
import LightTooltip from "@/components/ui/LightTooltip.vue";
import { loadRoutineParameters } from "@/lib/routineParameters";
-import {
- acceptsRoutineInput,
- buildProcedureExecutionSql,
- buildProcedureExecutionSqlFromValues,
- type RoutineParameterValue,
-} from "@/lib/routineExecutionSql";
+import { acceptsRoutineInput, buildProcedureExecutionSql, buildProcedureExecutionSqlFromValues, type RoutineParameterValue } from "@/lib/routineExecutionSql";
import type { DatabaseType } from "@/types/database";
const { t } = useI18n();
@@ -143,9 +138,7 @@ function canEditParameter(parameter: RoutineParameterValue): boolean {
<template>
<Dialog v-model:open="open">
- <DialogContent
- class="max-h-[86vh] border border-border !bg-background text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[780px]"
- >
+ <DialogContent class="max-h-[86vh] border border-border !bg-background text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[780px]">
<DialogHeader>
<DialogTitle>{{ t("contextMenu.confirmExecuteProcedureTitle") }}</DialogTitle>
</DialogHeader>
@@ -170,19 +163,14 @@ function canEditParameter(parameter: RoutineParameterValue): boolean {
</div>
</div>
- <div
- v-if="loading"
- class="flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm text-muted-foreground"
- >
+ <div v-if="loading" class="flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
<Loader2 class="h-4 w-4 animate-spin" />
{{ t("contextMenu.loadingProcedureParameters") }}
</div>
<div v-else-if="parameters.length" class="overflow-x-auto rounded-md border bg-background">
<div class="min-w-[650px]">
- <div
- class="grid grid-cols-[minmax(120px,1.2fr)_minmax(96px,1fr)_72px_minmax(160px,1.5fr)_64px_86px] border-b bg-muted px-3 py-2 text-xs font-medium text-muted-foreground"
- >
+ <div class="grid grid-cols-[minmax(120px,1.2fr)_minmax(96px,1fr)_72px_minmax(160px,1.5fr)_64px_86px] border-b bg-muted px-3 py-2 text-xs font-medium text-muted-foreground">
<div>{{ t("contextMenu.parameterName") }}</div>
<div>{{ t("contextMenu.parameterType") }}</div>
<div>{{ t("contextMenu.parameterMode") }}</div>
@@ -191,54 +179,24 @@ function canEditParameter(parameter: RoutineParameterValue): boolean {
<div class="flex items-center gap-1">
{{ t("contextMenu.parameterDefault") }}
<LightTooltip :text="t('contextMenu.parameterDefaultHint')" side="top" :delay="150">
- <button
- type="button"
- class="inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground hover:bg-background hover:text-foreground"
- :aria-label="t('contextMenu.parameterDefaultHint')"
- >
+ <button type="button" class="inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground hover:bg-background hover:text-foreground" :aria-label="t('contextMenu.parameterDefaultHint')">
<CircleHelp class="h-3.5 w-3.5" />
</button>
</LightTooltip>
</div>
</div>
- <div
- v-for="parameter in parameters"
- :key="`${parameter.ordinal}:${parameter.name}`"
- class="grid grid-cols-[minmax(120px,1.2fr)_minmax(96px,1fr)_72px_minmax(160px,1.5fr)_64px_86px] items-center gap-2 border-b px-3 py-2 text-sm last:border-b-0"
- >
+ <div v-for="parameter in parameters" :key="`${parameter.ordinal}:${parameter.name}`" class="grid grid-cols-[minmax(120px,1.2fr)_minmax(96px,1fr)_72px_minmax(160px,1.5fr)_64px_86px] items-center gap-2 border-b px-3 py-2 text-sm last:border-b-0">
<div class="min-w-0 truncate font-medium">{{ parameter.name }}</div>
<div class="min-w-0 truncate text-muted-foreground">{{ parameter.dataType || "-" }}</div>
<div class="text-xs text-muted-foreground">{{ parameter.mode }}</div>
- <Input
- v-model="parameter.value"
- class="h-8 bg-background font-mono text-xs"
- :disabled="!canEditParameter(parameter) || parameter.useNull || parameter.useDefault"
- :placeholder="
- canEditParameter(parameter) ? t('contextMenu.parameterValuePlaceholder') : t('contextMenu.outputOnly')
- "
- />
- <input
- type="checkbox"
- class="h-4 w-4 accent-primary"
- :checked="!!parameter.useNull"
- :disabled="!canEditParameter(parameter) || parameter.useDefault"
- @change="(event: Event) => (parameter.useNull = (event.target as HTMLInputElement).checked)"
- />
- <input
- type="checkbox"
- class="h-4 w-4 accent-primary"
- :checked="!!parameter.useDefault"
- :disabled="!canEditParameter(parameter) || !parameter.hasDefault || parameter.useNull"
- @change="(event: Event) => (parameter.useDefault = (event.target as HTMLInputElement).checked)"
- />
+ <Input v-model="parameter.value" class="h-8 bg-background font-mono text-xs" :disabled="!canEditParameter(parameter) || parameter.useNull || parameter.useDefault" :placeholder="canEditParameter(parameter) ? t('contextMenu.parameterValuePlaceholder') : t('contextMenu.outputOnly')" />
+ <input type="checkbox" class="h-4 w-4 accent-primary" :checked="!!parameter.useNull" :disabled="!canEditParameter(parameter) || parameter.useDefault" @change="(event: Event) => (parameter.useNull = (event.target as HTMLInputElement).checked)" />
+ <input type="checkbox" class="h-4 w-4 accent-primary" :checked="!!parameter.useDefault" :disabled="!canEditParameter(parameter) || !parameter.hasDefault || parameter.useNull" @change="(event: Event) => (parameter.useDefault = (event.target as HTMLInputElement).checked)" />
</div>
</div>
</div>
- <p
- v-else-if="loadError"
- class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800"
- >
+ <p v-else-if="loadError" class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
{{ t("contextMenu.procedureParametersUnavailable") }}
</p>
@@ -253,12 +211,7 @@ function canEditParameter(parameter: RoutineParameterValue): boolean {
{{ t("contextMenu.resetSqlPreview") }}
</Button>
</div>
- <textarea
- :value="sqlDraft"
- class="min-h-28 w-full resize-y rounded-md border border-input bg-background px-3 py-2 font-mono text-xs outline-none transition-colors focus:border-ring focus:ring-1 focus:ring-ring/40"
- spellcheck="false"
- @input="onSqlInput"
- ></textarea>
+ <textarea :value="sqlDraft" class="min-h-28 w-full resize-y rounded-md border border-input bg-background px-3 py-2 font-mono text-xs outline-none transition-colors focus:border-ring focus:ring-1 focus:ring-ring/40" spellcheck="false" @input="onSqlInput"></textarea>
</div>
</div>
diff --git a/apps/desktop/src/components/redis/RedisJsonTree.vue b/apps/desktop/src/components/redis/RedisJsonTree.vue
index 743697ef34..0aceaf7489 100644
--- a/apps/desktop/src/components/redis/RedisJsonTree.vue
+++ b/apps/desktop/src/components/redis/RedisJsonTree.vue
@@ -128,12 +128,7 @@ function renderJsonNode(node: JsonNode): VNodeChild {
}
if (node.parentKind !== "root") {
- rowChildren.push(
- node.parentKind === "array"
- ? h("span", { class: "redis-json-index" }, `[${node.label}]`)
- : highlightedJsonSpan("redis-json-key", JSON.stringify(node.label)),
- h("span", { class: "redis-json-colon" }, ":"),
- );
+ rowChildren.push(node.parentKind === "array" ? h("span", { class: "redis-json-index" }, `[${node.label}]`) : highlightedJsonSpan("redis-json-key", JSON.stringify(node.label)), h("span", { class: "redis-json-colon" }, ":"));
}
if (container) {
@@ -146,10 +141,7 @@ function renderJsonNode(node: JsonNode): VNodeChild {
rowChildren.push(highlightedJsonSpan(scalarClass(node.value), scalarText(node.value)));
}
- return h("div", { class: "redis-json-node" }, [
- h("div", { class: "redis-json-row", style: { paddingLeft: indent } }, rowChildren),
- container && !collapsed ? h("div", { class: "redis-json-children" }, children.map(renderJsonNode)) : null,
- ]);
+ return h("div", { class: "redis-json-node" }, [h("div", { class: "redis-json-row", style: { paddingLeft: indent } }, rowChildren), container && !collapsed ? h("div", { class: "redis-json-children" }, children.map(renderJsonNode)) : null]);
}
const JsonTreeNode = defineComponent({
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.vue b/apps/desktop/src/components/redis/RedisKeyBrowser.vue
index 14902c9f84..578e57a5d4 100644
--- a/apps/desktop/src/components/redis/RedisKeyBrowser.vue
+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.vue
@@ -1,21 +1,7 @@
<script setup lang="ts">
import { computed, nextTick, ref, onMounted, onUnmounted, onActivated, onDeactivated, watch } from "vue";
import { useI18n } from "vue-i18n";
-import {
- Search,
- RefreshCw,
- Loader2,
- ChevronRight,
- ChevronDown,
- FolderClosed,
- FolderOpen,
- Trash2,
- Plus,
- KeyRound,
- TerminalSquare,
- Asterisk,
- History,
-} from "@lucide/vue";
+import { Search, RefreshCw, Loader2, ChevronRight, ChevronDown, FolderClosed, FolderOpen, Trash2, Plus, KeyRound, TerminalSquare, Asterisk, History } from "@lucide/vue";
import { RecycleScroller } from "vue-virtual-scroller";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
import { Splitpanes, Pane } from "splitpanes";
@@ -34,14 +20,7 @@ import type { RedisKeyInfo, RedisScanResult, HistoryEntry } from "@/lib/api";
import { uuid } from "@/lib/utils";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
-import {
- buildRedisKeyTree,
- collectExpandedGroupIds,
- collectRedisGroupKeyRaws,
- flattenVisibleRedisKeyTree,
- mergeKeysIntoRedisKeyTree,
- type RedisKeyTreeNode,
-} from "@/lib/redisKeyTree";
+import { buildRedisKeyTree, collectExpandedGroupIds, collectRedisGroupKeyRaws, flattenVisibleRedisKeyTree, mergeKeysIntoRedisKeyTree, type RedisKeyTreeNode } from "@/lib/redisKeyTree";
import { classifyRedisCommandSafety } from "@/lib/redisCommandSafety";
import { isRedisClearScreenCommand, nextRedisCommandDb, redisKeyTextToRaw } from "@/lib/redisCommandSession";
import { formatRedisCommandResult, formatRedisStringValue } from "@/lib/redisValuePresentation";
@@ -94,9 +73,7 @@ const hasMore = ref(false);
const scanCursor = ref(0);
const expandedGroupIds = ref<Set<string>>(new Set());
const checkedKeys = ref<Set<string>>(new Set());
-const pendingDanger = ref<
- { kind: "delete-keys"; title: string; keyRaws: string[] } | { kind: "command"; command: string } | null
->(null);
+const pendingDanger = ref<{ kind: "delete-keys"; title: string; keyRaws: string[] } | { kind: "command"; command: string } | null>(null);
const showDangerConfirm = ref(false);
const commandText = ref("");
const commandRunning = ref(false);
@@ -123,22 +100,10 @@ let redisBrowserIsActive = true;
let redisDbFlushedListenerRegistered = false;
const valueQuery = computed(() => searchPattern.value.trim());
-const effectivePattern = computed(() =>
- searchMode.value === "key" ? redisKeySearchPattern(searchPattern.value, fuzzyKeySearch.value) : "*",
-);
-const isSearchMode = computed(() =>
- searchMode.value === "key" ? effectivePattern.value !== "*" : valueQuery.value !== "",
-);
-const searchPlaceholder = computed(() =>
- searchMode.value === "key"
- ? fuzzyKeySearch.value
- ? t("redis.fuzzyPattern")
- : t("redis.pattern")
- : t("redis.valueSearchPlaceholder"),
-);
-const loadingEmptyText = computed(() =>
- searchMode.value === "value" && valueQuery.value ? t("redis.searchingValues") : t("redis.loadingKeys"),
-);
+const effectivePattern = computed(() => (searchMode.value === "key" ? redisKeySearchPattern(searchPattern.value, fuzzyKeySearch.value) : "*"));
+const isSearchMode = computed(() => (searchMode.value === "key" ? effectivePattern.value !== "*" : valueQuery.value !== ""));
+const searchPlaceholder = computed(() => (searchMode.value === "key" ? (fuzzyKeySearch.value ? t("redis.fuzzyPattern") : t("redis.pattern")) : t("redis.valueSearchPlaceholder")));
+const loadingEmptyText = computed(() => (searchMode.value === "value" && valueQuery.value ? t("redis.searchingValues") : t("redis.loadingKeys")));
const lastTotalKeys = ref(0);
const fetchAllProgressText = computed(() => {
if (!isFetchingAll.value) return "";
@@ -223,9 +188,7 @@ function mergeTree(newKeys: RedisKeyInfo[]) {
async function fetchScanPage(): Promise<RedisScanResult> {
const pageSize = settingsStore.editorSettings.redisScanPageSize;
- return searchMode.value === "value"
- ? await api.redisScanValues(props.connectionId, props.db, scanCursor.value, "*", valueQuery.value, pageSize)
- : await api.redisScanKeys(props.connectionId, props.db, scanCursor.value, effectivePattern.value, pageSize);
+ return searchMode.value === "value" ? await api.redisScanValues(props.connectionId, props.db, scanCursor.value, "*", valueQuery.value, pageSize) : await api.redisScanKeys(props.connectionId, props.db, scanCursor.value, effectivePattern.value, pageSize);
}
function appendScanResult(result: RedisScanResult) {
@@ -265,12 +228,7 @@ async function streamValueSearch(requestId: number) {
async function fillInitialKeyBatch(requestId: number) {
const targetCount = Math.max(1, settingsStore.editorSettings.redisScanPageSize);
let rounds = 0;
- while (
- requestId === searchRequestId &&
- searchMode.value === "key" &&
- hasMore.value &&
- flatKeys.value.length < targetCount
- ) {
+ while (requestId === searchRequestId && searchMode.value === "key" && hasMore.value && flatKeys.value.length < targetCount) {
const beforeCount = flatKeys.value.length;
const applied = await scanNextPage(requestId);
if (!applied) return;
@@ -650,9 +608,7 @@ async function createRedisKey() {
}
}
} else if (createKeyType.value === "stream") {
- const fields: [string, string][] = createKeyEntries.value
- .filter((e) => e.field && e.field.trim())
- .map((e) => [e.field!.trim(), e.value]);
+ const fields: [string, string][] = createKeyEntries.value.filter((e) => e.field && e.field.trim()).map((e) => [e.field!.trim(), e.value]);
if (fields.length > 0) {
const entryId = createKeyEntryId.value.trim() || "*";
await api.redisStreamAdd(props.connectionId, props.db, keyRaw, entryId, fields, ttl);
@@ -883,49 +839,15 @@ defineExpose({ focusSearch });
<div class="h-9 flex items-center gap-1 px-2 border-b shrink-0">
<Search class="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<div class="h-6 flex rounded-md border bg-muted/30 p-0.5 shrink-0" role="group">
- <button
- type="button"
- class="h-5 px-2 text-xs rounded-sm transition-colors"
- :class="
- searchMode === 'key'
- ? 'bg-background text-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground'
- "
- @click="setSearchMode('key')"
- >
+ <button type="button" class="h-5 px-2 text-xs rounded-sm transition-colors" :class="searchMode === 'key' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'" @click="setSearchMode('key')">
{{ t("redis.searchByKey") }}
</button>
- <button
- type="button"
- class="h-5 px-2 text-xs rounded-sm transition-colors"
- :class="
- searchMode === 'value'
- ? 'bg-background text-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground'
- "
- @click="setSearchMode('value')"
- >
+ <button type="button" class="h-5 px-2 text-xs rounded-sm transition-colors" :class="searchMode === 'value' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'" @click="setSearchMode('value')">
{{ t("redis.searchByValue") }}
</button>
</div>
- <Input
- v-model="searchPattern"
- data-redis-search-input
- class="h-6 text-xs border-0 shadow-none focus-visible:ring-0"
- :placeholder="searchPlaceholder"
- @input="onSearchInput"
- @keydown="onSearchKeydown"
- />
- <Button
- v-if="searchMode === 'key'"
- variant="ghost"
- size="sm"
- class="h-6 shrink-0 px-2 text-xs"
- :class="fuzzyKeySearch ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'"
- :title="t('redis.fuzzyMatchTitle')"
- :aria-pressed="fuzzyKeySearch"
- @click="toggleFuzzyKeySearch"
- >
+ <Input v-model="searchPattern" data-redis-search-input class="h-6 text-xs border-0 shadow-none focus-visible:ring-0" :placeholder="searchPlaceholder" @input="onSearchInput" @keydown="onSearchKeydown" />
+ <Button v-if="searchMode === 'key'" variant="ghost" size="sm" class="h-6 shrink-0 px-2 text-xs" :class="fuzzyKeySearch ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'" :title="t('redis.fuzzyMatchTitle')" :aria-pressed="fuzzyKeySearch" @click="toggleFuzzyKeySearch">
<Asterisk class="h-3 w-3 mr-1" />
{{ t("redis.fuzzyMatch") }}
</Button>
@@ -933,108 +855,42 @@ defineExpose({ focusSearch });
<Loader2 v-if="loading" class="h-3 w-3 animate-spin" />
<RefreshCw v-else class="h-3 w-3" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-6 w-6 shrink-0"
- :title="t('redis.createKey')"
- @click="openCreateKeyDialog"
- >
+ <Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :title="t('redis.createKey')" @click="openCreateKeyDialog">
<Plus class="h-3 w-3" />
</Button>
- <span class="text-xs text-muted-foreground shrink-0 ml-1">{{
- loading && flatKeys.length === 0 ? loadingEmptyText : t("redis.keys", { count: flatKeys.length })
- }}</span>
- <Button
- v-if="checkedKeys.size > 0"
- variant="ghost"
- size="sm"
- class="h-6 text-xs text-destructive shrink-0 ml-1"
- @click="requestBatchDelete"
- >
- <Trash2 class="w-3 h-3 mr-1" />{{ checkedKeys.size }}
- </Button>
+ <span class="text-xs text-muted-foreground shrink-0 ml-1">{{ loading && flatKeys.length === 0 ? loadingEmptyText : t("redis.keys", { count: flatKeys.length }) }}</span>
+ <Button v-if="checkedKeys.size > 0" variant="ghost" size="sm" class="h-6 text-xs text-destructive shrink-0 ml-1" @click="requestBatchDelete"> <Trash2 class="w-3 h-3 mr-1" />{{ checkedKeys.size }} </Button>
</div>
- <div
- v-if="flatKeys.length === 0 && !loading"
- class="flex-1 flex items-center justify-center text-muted-foreground text-xs"
- >
+ <div v-if="flatKeys.length === 0 && !loading" class="flex-1 flex items-center justify-center text-muted-foreground text-xs">
{{ t("redis.noKeys") }}
</div>
- <div
- v-else-if="loading && flatKeys.length === 0"
- class="flex-1 flex items-center justify-center gap-2 text-muted-foreground text-xs"
- >
+ <div v-else-if="loading && flatKeys.length === 0" class="flex-1 flex items-center justify-center gap-2 text-muted-foreground text-xs">
<Loader2 class="w-3.5 h-3.5 animate-spin" />
<span>{{ loadingEmptyText }}</span>
</div>
- <RecycleScroller
- v-else
- class="redis-key-scroller flex-1"
- :items="visibleRows"
- :item-size="30"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller v-else class="redis-key-scroller flex-1" :items="visibleRows" :item-size="30" :buffer="600" :skip-hover="true" key-field="id">
<template #default="{ item: row }">
- <div
- class="flex items-center gap-2 border-b px-3 text-[13px] cursor-pointer hover:bg-accent/50 group"
- :class="{ 'bg-accent': row.node.kind === 'leaf' && selectedKeyRaw === row.node.keyRaw }"
- :style="{ height: '30px' }"
- @click="onRowClick(row.node)"
- >
- <div
- class="min-w-0 flex flex-1 items-center gap-1 overflow-hidden"
- :style="{ paddingLeft: `${12 + row.depth * 16}px` }"
- >
+ <div class="flex items-center gap-2 border-b px-3 text-[13px] cursor-pointer hover:bg-accent/50 group" :class="{ 'bg-accent': row.node.kind === 'leaf' && selectedKeyRaw === row.node.keyRaw }" :style="{ height: '30px' }" @click="onRowClick(row.node)">
+ <div class="min-w-0 flex flex-1 items-center gap-1 overflow-hidden" :style="{ paddingLeft: `${12 + row.depth * 16}px` }">
<template v-if="row.node.kind === 'group'">
- <component
- :is="expandedGroupIds.has(row.node.id) ? ChevronDown : ChevronRight"
- class="w-3 h-3 shrink-0 text-muted-foreground"
- />
- <component
- :is="expandedGroupIds.has(row.node.id) ? FolderOpen : FolderClosed"
- class="w-3 h-3 shrink-0 text-amber-500"
- />
+ <component :is="expandedGroupIds.has(row.node.id) ? ChevronDown : ChevronRight" class="w-3 h-3 shrink-0 text-muted-foreground" />
+ <component :is="expandedGroupIds.has(row.node.id) ? FolderOpen : FolderClosed" class="w-3 h-3 shrink-0 text-amber-500" />
<span class="dbx-editor-font-family truncate">{{ row.node.label }}</span>
<span class="text-muted-foreground ml-1">({{ countLeaves(row.node) }})</span>
</template>
<template v-else>
<span class="relative flex h-4 w-4 shrink-0 items-center justify-center">
- <KeyRound
- class="h-3.5 w-3.5 text-muted-foreground/70 transition-opacity group-hover:opacity-0"
- :class="{ 'opacity-0': checkedKeys.has(row.node.keyRaw) }"
- />
- <input
- type="checkbox"
- class="absolute h-3.5 w-3.5 accent-primary cursor-pointer opacity-0 group-hover:opacity-100"
- :class="{ 'opacity-100': checkedKeys.has(row.node.keyRaw) }"
- :checked="checkedKeys.has(row.node.keyRaw)"
- @click="toggleCheck(row.node.keyRaw, $event)"
- />
+ <KeyRound class="h-3.5 w-3.5 text-muted-foreground/70 transition-opacity group-hover:opacity-0" :class="{ 'opacity-0': checkedKeys.has(row.node.keyRaw) }" />
+ <input type="checkbox" class="absolute h-3.5 w-3.5 accent-primary cursor-pointer opacity-0 group-hover:opacity-100" :class="{ 'opacity-100': checkedKeys.has(row.node.keyRaw) }" :checked="checkedKeys.has(row.node.keyRaw)" @click="toggleCheck(row.node.keyRaw, $event)" />
</span>
<span class="dbx-editor-font-family truncate">{{ row.node.label }}</span>
</template>
</div>
<div class="flex shrink-0 items-center justify-end gap-1">
- <Badge
- v-if="row.node.kind === 'leaf'"
- variant="outline"
- class="text-xs px-1.5 py-0"
- :class="typeColor(row.node.keyType)"
- >{{ row.node.keyType }}</Badge
- >
- <Button
- v-if="row.node.kind === 'group'"
- variant="ghost"
- size="icon"
- class="h-5 w-5 shrink-0 text-destructive opacity-0 group-hover:opacity-100"
- :title="t('redis.deleteGroup')"
- @click="requestGroupDelete(row.node, $event)"
- >
+ <Badge v-if="row.node.kind === 'leaf'" variant="outline" class="text-xs px-1.5 py-0" :class="typeColor(row.node.keyType)">{{ row.node.keyType }}</Badge>
+ <Button v-if="row.node.kind === 'group'" variant="ghost" size="icon" class="h-5 w-5 shrink-0 text-destructive opacity-0 group-hover:opacity-100" :title="t('redis.deleteGroup')" @click="requestGroupDelete(row.node, $event)">
<Trash2 class="h-3 w-3" />
</Button>
</div>
@@ -1042,23 +898,11 @@ defineExpose({ focusSearch });
</template>
</RecycleScroller>
<div v-if="hasMore && !isFetchingAll" class="shrink-0 border-t px-2 py-1.5 flex items-center gap-1.5">
- <Button
- variant="outline"
- size="sm"
- class="h-7 text-xs flex-1"
- :disabled="loadingMore || loading"
- @click="loadMore"
- >
+ <Button variant="outline" size="sm" class="h-7 text-xs flex-1" :disabled="loadingMore || loading" @click="loadMore">
<Loader2 v-if="loadingMore" class="w-3 h-3 mr-1.5 animate-spin" />
{{ t("redis.loadMoreKeys") }}
</Button>
- <Button
- variant="outline"
- size="sm"
- class="h-7 text-xs flex-1"
- :disabled="loading || !hasMore"
- @click="fetchAll"
- >
+ <Button variant="outline" size="sm" class="h-7 text-xs flex-1" :disabled="loading || !hasMore" @click="fetchAll">
{{ t("redis.fetchAllKeys") }}
</Button>
</div>
@@ -1083,48 +927,25 @@ defineExpose({ focusSearch });
<KeyRound class="size-3.5" />
{{ t("redis.keyDetail") }}
</TabsTrigger>
- <TabsTrigger
- value="command"
- class="h-6 flex-none gap-1.5 rounded-md px-2 text-xs"
- @click="openCommandPanel"
- >
+ <TabsTrigger value="command" class="h-6 flex-none gap-1.5 rounded-md px-2 text-xs" @click="openCommandPanel">
<TerminalSquare class="size-3.5" />
{{ t("redis.commandLine") }}
</TabsTrigger>
</TabsList>
- <Button
- v-if="activeSidePanel === 'command'"
- variant="ghost"
- size="icon"
- class="h-6 w-6"
- :title="t('redis.clearHistory')"
- @click="clearPersistedRedisHistory"
- >
+ <Button v-if="activeSidePanel === 'command'" variant="ghost" size="icon" class="h-6 w-6" :title="t('redis.clearHistory')" @click="clearPersistedRedisHistory">
<History class="size-3.5" />
</Button>
</div>
<TabsContent value="detail" class="m-0 min-h-0 flex-1 flex flex-col">
- <RedisValueViewer
- v-if="selectedKey"
- :key="selectedKey.key_raw"
- :connection-id="connectionId"
- :db="db"
- :key-display="selectedKey.key_display"
- :key-raw="selectedKey.key_raw"
- :metadata="selectedKey"
- @deleted="onKeyDeleted"
- />
+ <RedisValueViewer v-if="selectedKey" :key="selectedKey.key_raw" :connection-id="connectionId" :db="db" :key-display="selectedKey.key_display" :key-raw="selectedKey.key_raw" :metadata="selectedKey" @deleted="onKeyDeleted" />
<div v-else class="flex-1 flex items-center justify-center text-xs text-muted-foreground">
{{ t("redis.selectKeyForDetail") }}
</div>
</TabsContent>
<TabsContent value="command" class="m-0 min-h-0 flex-1 flex flex-col">
- <div
- class="dbx-editor-font-family relative flex min-h-0 flex-1 flex-col bg-[#171b21] text-[13px] leading-5 text-slate-200"
- @click="getCommandInput()?.focus()"
- >
+ <div class="dbx-editor-font-family relative flex min-h-0 flex-1 flex-col bg-[#171b21] text-[13px] leading-5 text-slate-200" @click="getCommandInput()?.focus()">
<div ref="commandTerminalRef" class="min-h-0 flex-1 overflow-auto px-4 pb-3 pt-4">
<div class="mb-4 text-slate-400">
<span class="text-slate-200">{{ t("redis.commandWelcome") }}</span>
@@ -1135,19 +956,11 @@ defineExpose({ focusSearch });
<span class="shrink-0 text-[#d7ba7d]">{{ entry.prompt }}</span>
<span class="min-w-0 text-slate-200">{{ entry.command }}</span>
</div>
- <pre
- v-if="entry.output"
- class="ml-0 whitespace-pre-wrap break-words pl-0"
- :class="entry.error ? 'text-[#ff6b6b]' : 'text-slate-300'"
- >{{ entry.output }}</pre
- >
+ <pre v-if="entry.output" class="ml-0 whitespace-pre-wrap break-words pl-0" :class="entry.error ? 'text-[#ff6b6b]' : 'text-slate-300'">{{ entry.output }}</pre>
</div>
</div>
- <form
- class="flex shrink-0 items-center gap-2 border-t border-white/10 bg-[#171b21] px-4 py-2"
- @submit.prevent="executeCommand"
- >
+ <form class="flex shrink-0 items-center gap-2 border-t border-white/10 bg-[#171b21] px-4 py-2" @submit.prevent="executeCommand">
<span class="shrink-0 text-[#d7ba7d]">{{ commandPrompt }}</span>
<input
v-model="commandText"
@@ -1168,13 +981,7 @@ defineExpose({ focusSearch });
</Pane>
</Splitpanes>
- <DangerConfirmDialog
- v-model:open="showDangerConfirm"
- :message="t('dangerDialog.deleteMessage')"
- :details="dangerDetails"
- :confirm-label="dangerConfirmLabel"
- @confirm="applyDangerAction"
- />
+ <DangerConfirmDialog v-model:open="showDangerConfirm" :message="t('dangerDialog.deleteMessage')" :details="dangerDetails" :confirm-label="dangerConfirmLabel" @confirm="applyDangerAction" />
<Dialog v-model:open="showCreateKeyDialog">
<DialogContent class="sm:max-w-md" :style="editorFontFamilyStyle">
@@ -1185,12 +992,7 @@ defineExpose({ focusSearch });
<div class="grid gap-3">
<label class="grid gap-1.5 text-xs font-medium">
<span>{{ t("redis.createKeyName") }}</span>
- <Input
- v-model="createKeyName"
- class="dbx-editor-font-family h-8 text-xs"
- :placeholder="t('redis.createKeyNamePlaceholder')"
- @keydown.enter="createRedisKey"
- />
+ <Input v-model="createKeyName" class="dbx-editor-font-family h-8 text-xs" :placeholder="t('redis.createKeyNamePlaceholder')" @keydown.enter="createRedisKey" />
</label>
<label class="grid gap-1.5 text-xs font-medium">
@@ -1209,42 +1011,22 @@ defineExpose({ focusSearch });
<label v-if="createKeyType === 'hash' && createKeyRawMode" class="grid gap-1.5 text-xs font-medium">
<span>{{ t("redis.createField") }}</span>
- <Input
- v-model="createKeyField"
- class="dbx-editor-font-family h-8 text-xs"
- :placeholder="t('redis.createFieldPlaceholder')"
- @keydown.enter="createRedisKey"
- />
+ <Input v-model="createKeyField" class="dbx-editor-font-family h-8 text-xs" :placeholder="t('redis.createFieldPlaceholder')" @keydown.enter="createRedisKey" />
</label>
<label v-if="createKeyType === 'zset' && createKeyRawMode" class="grid gap-1.5 text-xs font-medium">
<span>{{ t("redis.createScore") }}</span>
- <Input
- v-model="createKeyScore"
- class="dbx-editor-font-family h-8 text-xs"
- placeholder="0"
- @keydown.enter="createRedisKey"
- />
+ <Input v-model="createKeyScore" class="dbx-editor-font-family h-8 text-xs" placeholder="0" @keydown.enter="createRedisKey" />
</label>
<!-- TTL input -- always visible -->
<label class="grid gap-1.5 text-xs font-medium">
<span>{{ t("redis.createKeyTtl") }}</span>
- <Input
- v-model="createKeyTtl"
- class="dbx-editor-font-family h-8 text-xs"
- type="number"
- min="0"
- :placeholder="t('redis.createKeyTtlPlaceholder')"
- @keydown.enter="createRedisKey"
- />
+ <Input v-model="createKeyTtl" class="dbx-editor-font-family h-8 text-xs" type="number" min="0" :placeholder="t('redis.createKeyTtlPlaceholder')" @keydown.enter="createRedisKey" />
</label>
<!-- Raw mode toggle (non-string, non-stream, non-json types) -->
- <div
- v-if="createKeyType !== 'string' && createKeyType !== 'stream' && createKeyType !== 'json'"
- class="flex items-center justify-end gap-1.5"
- >
+ <div v-if="createKeyType !== 'string' && createKeyType !== 'stream' && createKeyType !== 'json'" class="flex items-center justify-end gap-1.5">
<label class="flex items-center gap-1.5 text-xs text-muted-foreground">
<span>{{ t("redis.createKeyRawMode") }}</span>
<Switch size="sm" v-model="createKeyRawMode" />
@@ -1270,47 +1052,19 @@ defineExpose({ focusSearch });
<div v-for="(entry, idx) in createKeyEntries" :key="entry.id" class="flex items-start gap-2">
<!-- Hash / Stream: field + value -->
<template v-if="createKeyType === 'hash' || createKeyType === 'stream'">
- <Input
- v-model="entry.field"
- class="dbx-editor-font-family h-8 w-2/5 text-xs"
- :placeholder="t('redis.createFieldPlaceholder')"
- />
- <Input
- v-model="entry.value"
- class="dbx-editor-font-family h-8 flex-1 text-xs"
- :placeholder="t('redis.createValuePlaceholder')"
- />
+ <Input v-model="entry.field" class="dbx-editor-font-family h-8 w-2/5 text-xs" :placeholder="t('redis.createFieldPlaceholder')" />
+ <Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :placeholder="t('redis.createValuePlaceholder')" />
</template>
<!-- ZSet: score + member -->
<template v-else-if="createKeyType === 'zset'">
- <Input
- v-model="entry.score"
- class="dbx-editor-font-family h-8 w-20 text-xs"
- type="number"
- step="any"
- placeholder="0"
- />
- <Input
- v-model="entry.value"
- class="dbx-editor-font-family h-8 flex-1 text-xs"
- :placeholder="t('redis.createMember')"
- />
+ <Input v-model="entry.score" class="dbx-editor-font-family h-8 w-20 text-xs" type="number" step="any" placeholder="0" />
+ <Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :placeholder="t('redis.createMember')" />
</template>
<!-- List / Set: single value -->
<template v-else>
- <Input
- v-model="entry.value"
- class="dbx-editor-font-family h-8 flex-1 text-xs"
- :placeholder="t('redis.createValuePlaceholder')"
- />
+ <Input v-model="entry.value" class="dbx-editor-font-family h-8 flex-1 text-xs" :placeholder="t('redis.createValuePlaceholder')" />
</template>
- <Button
- variant="ghost"
- size="sm"
- class="h-8 w-8 shrink-0 p-0 text-muted-foreground hover:text-destructive"
- :disabled="createKeyEntries.length <= 1"
- @click="removeEntry(idx)"
- >
+ <Button variant="ghost" size="sm" class="h-8 w-8 shrink-0 p-0 text-muted-foreground hover:text-destructive" :disabled="createKeyEntries.length <= 1" @click="removeEntry(idx)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</div>
@@ -1318,19 +1072,9 @@ defineExpose({ focusSearch });
</template>
<!-- Raw value textarea (string, json, or raw mode for other types) -->
- <label
- v-if="createKeyType === 'string' || createKeyType === 'json' || createKeyRawMode"
- class="grid gap-1.5 text-xs font-medium"
- >
- <span>{{
- t(createKeyType === "set" || createKeyType === "zset" ? "redis.createMember" : "redis.createValue")
- }}</span>
- <textarea
- v-model="createKeyValue"
- class="dbx-editor-font-family min-h-28 resize-y rounded-md border bg-background p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring"
- spellcheck="false"
- :placeholder="t('redis.createValuePlaceholder')"
- />
+ <label v-if="createKeyType === 'string' || createKeyType === 'json' || createKeyRawMode" class="grid gap-1.5 text-xs font-medium">
+ <span>{{ t(createKeyType === "set" || createKeyType === "zset" ? "redis.createMember" : "redis.createValue") }}</span>
+ <textarea v-model="createKeyValue" class="dbx-editor-font-family min-h-28 resize-y rounded-md border bg-background p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring" spellcheck="false" :placeholder="t('redis.createValuePlaceholder')" />
</label>
<p v-if="createKeyError" class="text-xs text-destructive">{{ createKeyError }}</p>
@@ -1340,10 +1084,7 @@ defineExpose({ focusSearch });
<Button variant="ghost" :disabled="creatingKey" @click="showCreateKeyDialog = false">
{{ t("dangerDialog.cancel") }}
</Button>
- <Button
- :disabled="creatingKey || checkingJsonModule || (createKeyType === 'json' && jsonModuleAvailable !== true)"
- @click="createRedisKey"
- >
+ <Button :disabled="creatingKey || checkingJsonModule || (createKeyType === 'json' && jsonModuleAvailable !== true)" @click="createRedisKey">
<Loader2 v-if="creatingKey" class="h-4 w-4 animate-spin" />
<Plus v-else class="h-4 w-4" />
{{ t("redis.createKeySubmit") }}
diff --git a/apps/desktop/src/components/redis/RedisValueViewer.vue b/apps/desktop/src/components/redis/RedisValueViewer.vue
index a654cb0504..70b3e7a67b 100644
--- a/apps/desktop/src/components/redis/RedisValueViewer.vue
+++ b/apps/desktop/src/components/redis/RedisValueViewer.vue
@@ -2,22 +2,7 @@
import { computed, ref, onBeforeUnmount, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { DynamicScroller, DynamicScrollerItem, RecycleScroller } from "vue-virtual-scroller";
-import {
- Braces,
- Copy,
- Eye,
- FileText,
- Terminal,
- Trash2,
- Save,
- RefreshCw,
- Plus,
- Loader2,
- Pencil,
- WrapText,
- IndentIncrease,
- IndentDecrease,
-} from "@lucide/vue";
+import { Braces, Copy, Eye, FileText, Terminal, Trash2, Save, RefreshCw, Plus, Loader2, Pencil, WrapText, IndentIncrease, IndentDecrease } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
@@ -32,12 +17,7 @@ import { useTheme } from "@/composables/useTheme";
import { useEditorFontFamilyStyle } from "@/composables/useEditorFontFamilyStyle";
import { createRedisShikiJsonHighlighter, type RedisJsonHighlighter } from "@/lib/redisJsonHighlighter";
import { copyToClipboard } from "@/lib/clipboard";
-import {
- canEditRedisMemberDetail,
- clampRedisMemberDetailSheetWidth,
- formatRedisMemberDetail,
- getRedisMemberSelectionKey,
-} from "@/lib/redisValuePresentation";
+import { canEditRedisMemberDetail, clampRedisMemberDetailSheetWidth, formatRedisMemberDetail, getRedisMemberSelectionKey } from "@/lib/redisValuePresentation";
const { t } = useI18n();
const { toast } = useToast();
@@ -91,32 +71,21 @@ const redisJsonWordWrap = ref(readRedisJsonWordWrap());
const redisJsonHighlighter = ref<RedisJsonHighlighter>();
const selectedMemberDetail = computed(() => formatRedisMemberDetail(selectedMemberRaw.value));
const selectedMemberJsonDetail = computed(() => selectedMemberDetail.value.json ?? null);
-const stringValueDetail = computed(() =>
- data.value?.key_type === "string" ? formatRedisMemberDetail(data.value.value) : null,
-);
+const stringValueDetail = computed(() => (data.value?.key_type === "string" ? formatRedisMemberDetail(data.value.value) : null));
const stringJsonDetail = computed(() => stringValueDetail.value?.json ?? null);
const redisJsonAppearance = computed(() => (isDark.value ? "dark" : "light"));
-const memberRawJsonHtml = computed(() =>
- selectedMemberJsonDetail.value ? highlightRedisJson(selectedMemberJsonDetail.value.rawText) : "",
-);
+const memberRawJsonHtml = computed(() => (selectedMemberJsonDetail.value ? highlightRedisJson(selectedMemberJsonDetail.value.rawText) : ""));
const hashGridStyle = computed(() => ({
gridTemplateColumns: `${hashFieldWidth.value}px minmax(12rem, 1fr) 84px`,
}));
const zsetGridStyle = computed(() => ({
gridTemplateColumns: `${zsetScoreWidth.value}px minmax(0, 1fr) 84px`,
}));
-const selectedMemberCanEdit = computed(
- () => selectedMemberContext.value != null && canEditRedisMemberDetail(selectedMemberContext.value.kind),
-);
+const selectedMemberCanEdit = computed(() => selectedMemberContext.value != null && canEditRedisMemberDetail(selectedMemberContext.value.kind));
const REDIS_COLLECTION_ROW_HEIGHT = 32;
const REDIS_STREAM_MIN_ROW_HEIGHT = 96;
-type PendingDelete =
- | { kind: "key" }
- | { kind: "hash"; field: string }
- | { kind: "list"; index: number }
- | { kind: "set"; member: string }
- | { kind: "zset"; member: string };
+type PendingDelete = { kind: "key" } | { kind: "hash"; field: string } | { kind: "list"; index: number } | { kind: "set"; member: string } | { kind: "zset"; member: string };
const pendingDelete = ref<PendingDelete | null>(null);
@@ -127,12 +96,7 @@ let hashResizeStartWidth = 0;
let zsetResizeStartX = 0;
let zsetResizeStartWidth = 0;
-type RedisMemberContext =
- | { kind: "list"; index: number }
- | { kind: "set"; member: string }
- | { kind: "hash"; field: string }
- | { kind: "zset"; member: string; score: number }
- | { kind: "stream"; field: string };
+type RedisMemberContext = { kind: "list"; index: number } | { kind: "set"; member: string } | { kind: "hash"; field: string } | { kind: "zset"; member: string; score: number } | { kind: "stream"; field: string };
type RedisCollectionRow = {
id: string;
@@ -208,12 +172,9 @@ const deleteDetails = computed(() => {
const pending = pendingDelete.value;
if (!pending) return "";
if (pending.kind === "key") return t("dangerDialog.redisKeyDetails", { key: props.keyDisplay });
- if (pending.kind === "hash")
- return t("dangerDialog.redisHashFieldDetails", { key: props.keyDisplay, field: pending.field });
- if (pending.kind === "list")
- return t("dangerDialog.redisListItemDetails", { key: props.keyDisplay, index: pending.index });
- if (pending.kind === "zset")
- return t("dangerDialog.redisSetMemberDetails", { key: props.keyDisplay, member: pending.member });
+ if (pending.kind === "hash") return t("dangerDialog.redisHashFieldDetails", { key: props.keyDisplay, field: pending.field });
+ if (pending.kind === "list") return t("dangerDialog.redisListItemDetails", { key: props.keyDisplay, index: pending.index });
+ if (pending.kind === "zset") return t("dangerDialog.redisSetMemberDetails", { key: props.keyDisplay, member: pending.member });
return t("dangerDialog.redisSetMemberDetails", { key: props.keyDisplay, member: pending.member });
});
@@ -262,14 +223,7 @@ async function loadMore() {
if (!data.value || !hasMore.value || loadingMore.value) return;
loadingMore.value = true;
try {
- const result = await api.redisLoadMore(
- props.connectionId,
- props.db,
- props.keyRaw,
- data.value.key_type,
- scanCursor.value!,
- 200,
- );
+ const result = await api.redisLoadMore(props.connectionId, props.db, props.keyRaw, data.value.key_type, scanCursor.value!, 200);
const newItems = Array.isArray(result.value) ? result.value : [];
collectionItems.value = [...collectionItems.value, ...newItems];
scanCursor.value = result.scan_cursor ?? undefined;
@@ -420,9 +374,7 @@ function generateInsertStatements(): string | null {
break;
}
case "hash": {
- const pairs = collectionItems.value
- .map((v) => `${escapeRedisArg(String(v.field))} ${escapeRedisArg(String(v.value))}`)
- .join(" ");
+ const pairs = collectionItems.value.map((v) => `${escapeRedisArg(String(v.field))} ${escapeRedisArg(String(v.value))}`).join(" ");
commands.push(`HSET ${escapeRedisArg(key)} ${pairs}`);
break;
}
@@ -518,10 +470,7 @@ function stopResizeMemberSheet() {
function resizeMemberSheet(event: PointerEvent) {
if (!isResizingMemberSheet.value) return;
const delta = memberSheetResizeStartX - event.clientX;
- memberDetailSheetWidth.value = clampRedisMemberDetailSheetWidth(
- memberSheetResizeStartWidth + delta,
- window.innerWidth,
- );
+ memberDetailSheetWidth.value = clampRedisMemberDetailSheetWidth(memberSheetResizeStartWidth + delta, window.innerWidth);
}
function startResizeMemberSheet(event: PointerEvent) {
@@ -631,13 +580,7 @@ function selectDefaultMember(redisValue: RedisValue) {
clearSelectedMember();
return;
}
- selectMember(
- redisValue.key_type === "list" ? "#0" : t("redis.member"),
- collectionItems.value[0],
- redisValue.key_type === "list"
- ? { kind: "list", index: 0 }
- : { kind: "set", member: String(collectionItems.value[0]) },
- );
+ selectMember(redisValue.key_type === "list" ? "#0" : t("redis.member"), collectionItems.value[0], redisValue.key_type === "list" ? { kind: "list", index: 0 } : { kind: "set", member: String(collectionItems.value[0]) });
return;
}
@@ -826,58 +769,22 @@ onBeforeUnmount(() => {
<!-- Header -->
<div class="shrink-0 border-b bg-background">
<div class="flex h-9 items-center gap-2 px-4">
- <span class="dbx-editor-font-family min-w-0 flex-1 truncate text-sm font-semibold">{{
- data.key_display
- }}</span>
- <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="load"
- ><RefreshCw class="h-3.5 w-3.5"
- /></Button>
- <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="copyValue"
- ><Copy class="h-3.5 w-3.5"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-7 w-7 shrink-0"
- :title="t('redis.copyInsertStatement')"
- @click="copyInsertStatement"
- ><Terminal class="h-3.5 w-3.5"
- /></Button>
- <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-destructive" @click="requestDeleteKey"
- ><Trash2 class="h-3.5 w-3.5"
- /></Button>
+ <span class="dbx-editor-font-family min-w-0 flex-1 truncate text-sm font-semibold">{{ data.key_display }}</span>
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="load"><RefreshCw class="h-3.5 w-3.5" /></Button>
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="copyValue"><Copy class="h-3.5 w-3.5" /></Button>
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :title="t('redis.copyInsertStatement')" @click="copyInsertStatement"><Terminal class="h-3.5 w-3.5" /></Button>
+ <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-destructive" @click="requestDeleteKey"><Trash2 class="h-3.5 w-3.5" /></Button>
</div>
<div class="flex min-h-7 flex-wrap items-center gap-2 px-4 pb-1">
<Badge variant="secondary" class="dbx-editor-font-family text-xs uppercase">{{ data.key_type }}</Badge>
- <Badge v-if="metadataSizeLabel" variant="outline" class="text-xs text-muted-foreground">
- {{ t("redis.columnSize") }}: {{ metadataSizeLabel }}
- </Badge>
+ <Badge v-if="metadataSizeLabel" variant="outline" class="text-xs text-muted-foreground"> {{ t("redis.columnSize") }}: {{ metadataSizeLabel }} </Badge>
<template v-if="!editingTtl">
- <Badge
- v-if="data.ttl > 0"
- variant="outline"
- class="text-xs cursor-pointer text-muted-foreground hover:bg-accent"
- @click="startEditTtl"
- >TTL: {{ data.ttl }}s</Badge
- >
- <Badge
- v-else-if="data.ttl === -1"
- variant="outline"
- class="text-xs cursor-pointer text-muted-foreground hover:bg-accent"
- @click="startEditTtl"
- >{{ t("redis.noExpiry") }}</Badge
- >
+ <Badge v-if="data.ttl > 0" variant="outline" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent" @click="startEditTtl">TTL: {{ data.ttl }}s</Badge>
+ <Badge v-else-if="data.ttl === -1" variant="outline" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent" @click="startEditTtl">{{ t("redis.noExpiry") }}</Badge>
</template>
<div v-else class="flex items-center gap-1">
- <Input
- v-model="ttlInput"
- class="h-6 w-20 text-xs"
- placeholder="seconds (-1=no expiry)"
- autofocus
- @keydown.enter="saveTtl"
- @keydown.escape="cancelEditTtl"
- />
+ <Input v-model="ttlInput" class="h-6 w-20 text-xs" placeholder="seconds (-1=no expiry)" autofocus @keydown.enter="saveTtl" @keydown.escape="cancelEditTtl" />
<Button variant="ghost" size="icon" class="h-6 w-6" @click="saveTtl"><Save class="h-3 w-3" /></Button>
</div>
</div>
@@ -887,76 +794,32 @@ onBeforeUnmount(() => {
<div v-if="data.key_type === 'string'" class="flex-1 flex flex-col overflow-hidden">
<div v-if="stringJsonDetail" class="flex h-9 items-center gap-2 border-b px-4 text-xs shrink-0">
<div class="flex overflow-hidden rounded-md border bg-muted/20 p-0.5">
- <Button
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :class="{ 'bg-background shadow-sm': stringValueView === 'json' }"
- @click="stringValueView = 'json'"
- >
+ <Button variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': stringValueView === 'json' }" @click="stringValueView = 'json'">
<Braces class="h-3.5 w-3.5" />
{{ t("redis.jsonView") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :class="{ 'bg-background shadow-sm': stringValueView === 'raw' }"
- @click="stringValueView = 'raw'"
- >
+ <Button variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': stringValueView === 'raw' }" @click="stringValueView = 'raw'">
<FileText class="h-3.5 w-3.5" />
{{ t("redis.rawContent") }}
</Button>
</div>
<span class="flex-1" />
- <Button
- v-if="stringValueView === 'raw'"
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :title="t('redis.formatJson')"
- @click="handleFormatStringJson"
- >
+ <Button v-if="stringValueView === 'raw'" variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :title="t('redis.formatJson')" @click="handleFormatStringJson">
<IndentIncrease class="h-3.5 w-3.5" />
</Button>
- <Button
- v-if="stringValueView === 'raw'"
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :title="t('redis.compressJson')"
- @click="handleCompressStringJson"
- >
+ <Button v-if="stringValueView === 'raw'" variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :title="t('redis.compressJson')" @click="handleCompressStringJson">
<IndentDecrease class="h-3.5 w-3.5" />
</Button>
<label class="flex items-center gap-1.5 text-muted-foreground">
<WrapText class="h-3.5 w-3.5" />
{{ t("redis.wordWrap") }}
- <Switch
- size="sm"
- :model-value="redisJsonWordWrap"
- @update:model-value="setRedisJsonWordWrap(Boolean($event))"
- />
+ <Switch size="sm" :model-value="redisJsonWordWrap" @update:model-value="setRedisJsonWordWrap(Boolean($event))" />
</label>
</div>
- <div
- v-if="stringJsonDetail && stringValueView === 'json'"
- class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-4 text-sm leading-6"
- >
- <RedisJsonTree
- :value="stringJsonDetail.value"
- :word-wrap="redisJsonWordWrap"
- :highlight-json="highlightRedisJson"
- />
+ <div v-if="stringJsonDetail && stringValueView === 'json'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-4 text-sm leading-6">
+ <RedisJsonTree :value="stringJsonDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" />
</div>
- <textarea
- v-else
- v-model="editValue"
- class="dbx-editor-font-family flex-1 p-4 text-sm bg-background resize-none outline-none"
- :class="{ 'whitespace-pre': stringJsonDetail && !redisJsonWordWrap }"
- :readonly="isBinaryStringValue"
- @input="handleStringInput"
- />
+ <textarea v-else v-model="editValue" class="dbx-editor-font-family flex-1 p-4 text-sm bg-background resize-none outline-none" :class="{ 'whitespace-pre': stringJsonDetail && !redisJsonWordWrap }" :readonly="isBinaryStringValue" @input="handleStringInput" />
<div v-if="isBinaryStringValue" class="px-4 py-2 border-t text-xs text-muted-foreground shrink-0">
{{ t("redis.binaryStringReadonlyHint") }}
</div>
@@ -977,28 +840,17 @@ onBeforeUnmount(() => {
<!-- List -->
<div v-else-if="data.key_type === 'list'" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
- <span class="text-xs text-muted-foreground">{{
- collectionCountLabel("items", collectionItems.length, data.total)
- }}</span>
+ <span class="text-xs text-muted-foreground">{{ collectionCountLabel("items", collectionItems.length, data.total) }}</span>
<span class="flex-1" />
<Input v-model="newValue" class="h-6 w-40 text-xs" placeholder="value" @keydown.enter="listPush" />
- <Button variant="ghost" size="sm" class="h-6 text-xs" @click="listPush"
- ><Plus class="w-3 h-3 mr-1" />Push</Button
- >
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="listPush"><Plus class="w-3 h-3 mr-1" />Push</Button>
</div>
<div class="grid grid-cols-[60px_1fr_84px] border-b bg-muted/50 shrink-0">
<div class="px-3 py-1 text-xs font-medium text-muted-foreground border-r">#</div>
<div class="px-3 py-1 text-xs font-medium text-muted-foreground">Value</div>
<div />
</div>
- <RecycleScroller
- class="flex-1 overflow-y-auto"
- :items="collectionRows"
- :item-size="REDIS_COLLECTION_ROW_HEIGHT"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller class="flex-1 overflow-y-auto" :items="collectionRows" :item-size="REDIS_COLLECTION_ROW_HEIGHT" :buffer="600" :skip-hover="true" key-field="id">
<template #default="{ item: row }">
<div
data-redis-value-row
@@ -1010,29 +862,9 @@ onBeforeUnmount(() => {
<div class="px-3 py-1.5 text-xs text-muted-foreground border-r">{{ row.index }}</div>
<div class="px-3 py-1.5 truncate">{{ row.value }}</div>
<div class="flex items-center justify-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.viewMember')"
- @click.stop="viewMember(`#${row.index}`, row.value, { kind: 'list', index: row.index })"
- ><Eye class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.copyMember')"
- @click.stop="copyMember(row.value)"
- ><Copy class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive"
- @click.stop="requestListRemove(row.index)"
- ><Trash2 class="w-3 h-3"
- /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.viewMember')" @click.stop="viewMember(`#${row.index}`, row.value, { kind: 'list', index: row.index })"><Eye class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click.stop="copyMember(row.value)"><Copy class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" @click.stop="requestListRemove(row.index)"><Trash2 class="w-3 h-3" /></Button>
</div>
</div>
</template>
@@ -1050,27 +882,16 @@ onBeforeUnmount(() => {
<!-- Set -->
<div v-else-if="data.key_type === 'set'" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
- <span class="text-xs text-muted-foreground">{{
- collectionCountLabel("items", collectionItems.length, data.total)
- }}</span>
+ <span class="text-xs text-muted-foreground">{{ collectionCountLabel("items", collectionItems.length, data.total) }}</span>
<span class="flex-1" />
<Input v-model="newValue" class="h-6 w-40 text-xs" placeholder="member" @keydown.enter="setAdd" />
- <Button variant="ghost" size="sm" class="h-6 text-xs" @click="setAdd"
- ><Plus class="w-3 h-3 mr-1" />Add</Button
- >
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="setAdd"><Plus class="w-3 h-3 mr-1" />Add</Button>
</div>
<div class="grid grid-cols-[1fr_84px] border-b bg-muted/50 shrink-0">
<div class="px-3 py-1 text-xs font-medium text-muted-foreground">Member</div>
<div />
</div>
- <RecycleScroller
- class="flex-1 overflow-y-auto"
- :items="collectionRows"
- :item-size="REDIS_COLLECTION_ROW_HEIGHT"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller class="flex-1 overflow-y-auto" :items="collectionRows" :item-size="REDIS_COLLECTION_ROW_HEIGHT" :buffer="600" :skip-hover="true" key-field="id">
<template #default="{ item: row }">
<div
data-redis-value-row
@@ -1081,29 +902,9 @@ onBeforeUnmount(() => {
>
<div class="px-3 py-1.5 truncate">{{ row.value }}</div>
<div class="flex items-center justify-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.viewMember')"
- @click.stop="viewMember(t('redis.member'), row.value, { kind: 'set', member: String(row.value) })"
- ><Eye class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.copyMember')"
- @click.stop="copyMember(row.value)"
- ><Copy class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive"
- @click.stop="requestSetRemove(String(row.value))"
- ><Trash2 class="w-3 h-3"
- /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.viewMember')" @click.stop="viewMember(t('redis.member'), row.value, { kind: 'set', member: String(row.value) })"><Eye class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click.stop="copyMember(row.value)"><Copy class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" @click.stop="requestSetRemove(String(row.value))"><Trash2 class="w-3 h-3" /></Button>
</div>
</div>
</template>
@@ -1121,44 +922,28 @@ onBeforeUnmount(() => {
<!-- Hash -->
<div v-else-if="data.key_type === 'hash'" ref="hashTableRef" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
- <span class="text-xs text-muted-foreground">{{
- collectionCountLabel("fields", collectionItems.length, data.total)
- }}</span>
+ <span class="text-xs text-muted-foreground">{{ collectionCountLabel("fields", collectionItems.length, data.total) }}</span>
<span class="flex-1" />
<Input v-model="newField" class="h-6 w-24 text-xs" placeholder="field" />
<Input v-model="newValue" class="h-6 w-32 text-xs" placeholder="value" @keydown.enter="hashSet" />
- <Button variant="ghost" size="sm" class="h-6 text-xs" @click="hashSet"
- ><Plus class="w-3 h-3 mr-1" />Set</Button
- >
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="hashSet"><Plus class="w-3 h-3 mr-1" />Set</Button>
</div>
<div class="grid border-b bg-muted/50 shrink-0" :style="hashGridStyle">
<div class="relative px-3 py-1 text-xs font-medium text-muted-foreground border-r select-none">
Field
- <div
- class="absolute -right-1 top-0 h-full w-2 cursor-col-resize touch-none"
- @pointerdown.prevent="startResizeHashColumns"
- />
+ <div class="absolute -right-1 top-0 h-full w-2 cursor-col-resize touch-none" @pointerdown.prevent="startResizeHashColumns" />
</div>
<div class="px-3 py-1 text-xs font-medium text-muted-foreground">Value</div>
<div />
</div>
- <RecycleScroller
- class="flex-1 overflow-y-auto"
- :items="collectionRows"
- :item-size="REDIS_COLLECTION_ROW_HEIGHT"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller class="flex-1 overflow-y-auto" :items="collectionRows" :item-size="REDIS_COLLECTION_ROW_HEIGHT" :buffer="600" :skip-hover="true" key-field="id">
<template #default="{ item: row }">
<div
data-redis-value-row
class="dbx-editor-font-family grid border-b text-sm hover:bg-accent/50 group cursor-pointer"
:style="{ ...hashGridStyle, height: `${REDIS_COLLECTION_ROW_HEIGHT}px` }"
:class="{ 'bg-accent/60': isSelectedMember(String(row.value.field), row.value.value) }"
- @click="
- viewMember(String(row.value.field), row.value.value, { kind: 'hash', field: String(row.value.field) })
- "
+ @click="viewMember(String(row.value.field), row.value.value, { kind: 'hash', field: String(row.value.field) })"
>
<div class="px-3 py-1.5 text-blue-500 truncate border-r">{{ row.value.field }}</div>
<div class="px-3 py-1.5 truncate text-muted-foreground">{{ row.value.value }}</div>
@@ -1176,21 +961,8 @@ onBeforeUnmount(() => {
"
><Eye class="w-3 h-3"
/></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.copyMember')"
- @click.stop="copyMember(row.value.value)"
- ><Copy class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive"
- @click.stop="requestHashDel(String(row.value.field))"
- ><Trash2 class="w-3 h-3"
- /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click.stop="copyMember(row.value.value)"><Copy class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" @click.stop="requestHashDel(String(row.value.field))"><Trash2 class="w-3 h-3" /></Button>
</div>
</div>
</template>
@@ -1208,35 +980,21 @@ onBeforeUnmount(() => {
<!-- Sorted Set -->
<div v-else-if="data.key_type === 'zset'" ref="zsetTableRef" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
- <span class="text-xs text-muted-foreground">{{
- collectionCountLabel("members", collectionItems.length, data.total)
- }}</span>
+ <span class="text-xs text-muted-foreground">{{ collectionCountLabel("members", collectionItems.length, data.total) }}</span>
<span class="flex-1" />
<Input v-model="newScore" class="h-6 w-20 text-xs" placeholder="score" />
<Input v-model="newValue" class="h-6 w-32 text-xs" placeholder="member" @keydown.enter="zsetAdd" />
- <Button variant="ghost" size="sm" class="h-6 text-xs" @click="zsetAdd"
- ><Plus class="w-3 h-3 mr-1" />Add</Button
- >
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="zsetAdd"><Plus class="w-3 h-3 mr-1" />Add</Button>
</div>
<div class="grid border-b bg-muted/50 shrink-0" :style="zsetGridStyle">
<div class="relative px-3 py-1 text-xs font-medium text-muted-foreground border-r select-none">
Score
- <div
- class="absolute -right-1 top-0 h-full w-2 cursor-col-resize touch-none"
- @pointerdown.prevent="startResizeZsetColumns"
- />
+ <div class="absolute -right-1 top-0 h-full w-2 cursor-col-resize touch-none" @pointerdown.prevent="startResizeZsetColumns" />
</div>
<div class="px-3 py-1 text-xs font-medium text-muted-foreground min-w-0">Member</div>
<div />
</div>
- <RecycleScroller
- class="flex-1 overflow-y-auto"
- :items="collectionRows"
- :item-size="REDIS_COLLECTION_ROW_HEIGHT"
- :buffer="600"
- :skip-hover="true"
- key-field="id"
- >
+ <RecycleScroller class="flex-1 overflow-y-auto" :items="collectionRows" :item-size="REDIS_COLLECTION_ROW_HEIGHT" :buffer="600" :skip-hover="true" key-field="id">
<template #default="{ item: row }">
<div
data-redis-value-row
@@ -1251,10 +1009,7 @@ onBeforeUnmount(() => {
})
"
>
- <div
- class="px-3 py-1.5 text-muted-foreground text-xs border-r min-w-0 truncate"
- :title="String(row.value.score)"
- >
+ <div class="px-3 py-1.5 text-muted-foreground text-xs border-r min-w-0 truncate" :title="String(row.value.score)">
{{ row.value.score }}
</div>
<div class="px-3 py-1.5 min-w-0 truncate" :title="String(row.value.member)">
@@ -1275,21 +1030,8 @@ onBeforeUnmount(() => {
"
><Eye class="w-3 h-3"
/></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.copyMember')"
- @click.stop="copyMember(row.value.member)"
- ><Copy class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive"
- @click.stop="requestZsetRemove(String(row.value.member))"
- ><Trash2 class="w-3 h-3"
- /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click.stop="copyMember(row.value.member)"><Copy class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" @click.stop="requestZsetRemove(String(row.value.member))"><Trash2 class="w-3 h-3" /></Button>
</div>
</div>
</template>
@@ -1309,20 +1051,9 @@ onBeforeUnmount(() => {
<div class="px-4 py-1 text-xs text-muted-foreground border-b shrink-0">
{{ t("redis.entries", { count: streamRows.length }) }}
</div>
- <DynamicScroller
- class="flex-1 overflow-y-auto"
- :items="streamRows"
- :min-item-size="REDIS_STREAM_MIN_ROW_HEIGHT"
- :buffer="600"
- key-field="id"
- >
+ <DynamicScroller class="flex-1 overflow-y-auto" :items="streamRows" :min-item-size="REDIS_STREAM_MIN_ROW_HEIGHT" :buffer="600" key-field="id">
<template #default="{ item: row, active }">
- <DynamicScrollerItem
- :item="row"
- :active="active"
- :size-dependencies="[streamFieldCount(row)]"
- :data-index="row.index"
- >
+ <DynamicScrollerItem :item="row" :active="active" :size-dependencies="[streamFieldCount(row)]" :data-index="row.index">
<div data-redis-stream-entry class="dbx-editor-font-family px-4 py-2 border-b text-sm hover:bg-accent/50">
<div class="mb-1 text-xs text-muted-foreground">{{ row.entry.id }}</div>
<div
@@ -1335,22 +1066,8 @@ onBeforeUnmount(() => {
<span class="truncate text-blue-500">{{ field }}</span>
<span class="truncate text-muted-foreground">{{ val }}</span>
<span class="flex justify-end gap-1">
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.viewMember')"
- @click.stop="viewMember(String(field), val, { kind: 'stream', field: String(field) })"
- ><Eye class="w-3 h-3"
- /></Button>
- <Button
- variant="ghost"
- size="icon"
- class="h-5 w-5 opacity-0 group-hover:opacity-100"
- :title="t('redis.copyMember')"
- @click.stop="copyMember(val)"
- ><Copy class="w-3 h-3"
- /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.viewMember')" @click.stop="viewMember(String(field), val, { kind: 'stream', field: String(field) })"><Eye class="w-3 h-3" /></Button>
+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click.stop="copyMember(val)"><Copy class="w-3 h-3" /></Button>
</span>
</div>
</div>
@@ -1365,13 +1082,7 @@ onBeforeUnmount(() => {
</div>
</template>
- <DangerConfirmDialog
- v-model:open="showDeleteConfirm"
- :message="t('dangerDialog.deleteMessage')"
- :details="deleteDetails"
- :confirm-label="t('dangerDialog.deleteConfirm')"
- @confirm="confirmDelete"
- />
+ <DangerConfirmDialog v-model:open="showDeleteConfirm" :message="t('dangerDialog.deleteMessage')" :details="deleteDetails" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDelete" />
<Sheet :open="showMemberDetail" @update:open="handleMemberDetailOpenChange">
<SheetContent
@@ -1383,10 +1094,7 @@ onBeforeUnmount(() => {
@pointer-down-outside.prevent
@interact-outside.prevent
>
- <div
- class="absolute inset-y-0 left-0 z-10 w-2 -translate-x-1 cursor-col-resize border-l border-transparent hover:border-primary/60"
- @pointerdown.prevent="startResizeMemberSheet"
- />
+ <div class="absolute inset-y-0 left-0 z-10 w-2 -translate-x-1 cursor-col-resize border-l border-transparent hover:border-primary/60" @pointerdown.prevent="startResizeMemberSheet" />
<SheetHeader class="border-b px-5 py-4 pr-12">
<SheetTitle class="flex items-center gap-2">
<span class="truncate">{{ selectedMemberTitle || t("redis.memberDetail") }}</span>
@@ -1396,108 +1104,46 @@ onBeforeUnmount(() => {
<template v-if="isEditingMember">
<div v-if="selectedMemberJsonDetail" class="flex h-9 items-center gap-2 border-b px-5 text-xs shrink-0">
<span class="flex-1" />
- <Button
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :title="t('redis.formatJson')"
- @click="handleFormatMemberJson"
- >
+ <Button variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :title="t('redis.formatJson')" @click="handleFormatMemberJson">
<IndentIncrease class="h-3.5 w-3.5" />
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :title="t('redis.compressJson')"
- @click="handleCompressMemberJson"
- >
+ <Button variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :title="t('redis.compressJson')" @click="handleCompressMemberJson">
<IndentDecrease class="h-3.5 w-3.5" />
</Button>
</div>
- <textarea
- v-model="memberEditValue"
- class="dbx-editor-font-family min-h-0 flex-1 resize-none bg-background p-5 text-[13px] leading-6 outline-none"
- spellcheck="false"
- />
+ <textarea v-model="memberEditValue" class="dbx-editor-font-family min-h-0 flex-1 resize-none bg-background p-5 text-[13px] leading-6 outline-none" spellcheck="false" />
</template>
<template v-else-if="selectedMemberJsonDetail">
<div class="flex h-9 items-center gap-2 border-b px-5 text-xs">
<div class="flex overflow-hidden rounded-md border bg-muted/20 p-0.5">
- <Button
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :class="{ 'bg-background shadow-sm': memberValueView === 'json' }"
- @click="memberValueView = 'json'"
- >
+ <Button variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': memberValueView === 'json' }" @click="memberValueView = 'json'">
<Braces class="h-3.5 w-3.5" />
{{ t("redis.jsonView") }}
</Button>
- <Button
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :class="{ 'bg-background shadow-sm': memberValueView === 'raw' }"
- @click="memberValueView = 'raw'"
- >
+ <Button variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': memberValueView === 'raw' }" @click="memberValueView = 'raw'">
<FileText class="h-3.5 w-3.5" />
{{ t("redis.rawContent") }}
</Button>
</div>
<span class="flex-1" />
- <Button
- v-if="memberValueView === 'raw'"
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :title="t('redis.formatJson')"
- @click="handleFormatMemberJson"
- >
+ <Button v-if="memberValueView === 'raw'" variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :title="t('redis.formatJson')" @click="handleFormatMemberJson">
<IndentIncrease class="h-3.5 w-3.5" />
</Button>
- <Button
- v-if="memberValueView === 'raw'"
- variant="ghost"
- size="sm"
- class="h-6 rounded-[5px] px-2 text-xs"
- :title="t('redis.compressJson')"
- @click="handleCompressMemberJson"
- >
+ <Button v-if="memberValueView === 'raw'" variant="ghost" size="sm" class="h-6 rounded-[5px] px-2 text-xs" :title="t('redis.compressJson')" @click="handleCompressMemberJson">
<IndentDecrease class="h-3.5 w-3.5" />
</Button>
<label class="flex items-center gap-1.5 text-muted-foreground">
<WrapText class="h-3.5 w-3.5" />
{{ t("redis.wordWrap") }}
- <Switch
- size="sm"
- :model-value="redisJsonWordWrap"
- @update:model-value="setRedisJsonWordWrap(Boolean($event))"
- />
+ <Switch size="sm" :model-value="redisJsonWordWrap" @update:model-value="setRedisJsonWordWrap(Boolean($event))" />
</label>
</div>
- <div
- v-if="memberValueView === 'json'"
- class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6"
- >
- <RedisJsonTree
- :value="selectedMemberJsonDetail.value"
- :word-wrap="redisJsonWordWrap"
- :highlight-json="highlightRedisJson"
- />
+ <div v-if="memberValueView === 'json'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6">
+ <RedisJsonTree :value="selectedMemberJsonDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" />
</div>
- <pre
- v-else
- class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6"
- :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"
- v-html="memberRawJsonHtml"
- ></pre>
+ <pre v-else class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6" :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'" v-html="memberRawJsonHtml"></pre>
</template>
- <pre
- v-else
- class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6 whitespace-pre-wrap break-words"
- >{{ selectedMemberDetail.text }}</pre
- >
+ <pre v-else class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6 whitespace-pre-wrap break-words">{{ selectedMemberDetail.text }}</pre>
<SheetFooter class="shrink-0 border-t px-5 py-3">
<template v-if="isEditingMember">
<Button variant="ghost" :disabled="savingMember" @click="cancelEditMember">
diff --git a/apps/desktop/src/components/search/DatabaseSearchDialog.vue b/apps/desktop/src/components/search/DatabaseSearchDialog.vue
index eb23b80ddb..1328e951cf 100644
--- a/apps/desktop/src/components/search/DatabaseSearchDialog.vue
+++ b/apps/desktop/src/components/search/DatabaseSearchDialog.vue
@@ -55,17 +55,7 @@ type SearchTableTask = {
table: TableInfo;
};
-const SYSTEM_SCHEMAS = new Set([
- "information_schema",
- "pg_catalog",
- "sys",
- "system",
- "mysql",
- "performance_schema",
- "xdb",
- "outln",
- "dbsnmp",
-]);
+const SYSTEM_SCHEMAS = new Set(["information_schema", "pg_catalog", "sys", "system", "mysql", "performance_schema", "xdb", "outln", "dbsnmp"]);
const MAX_TABLES = 200;
const keyword = ref("");
@@ -82,18 +72,10 @@ const limitedTables = ref(false);
const currentExecutionId = ref("");
let runId = 0;
-const connection = computed(() =>
- props.prefillConnectionId ? connectionStore.getConfig(props.prefillConnectionId) : undefined,
-);
-const scopeLabel = computed(() =>
- [connection.value?.name, props.prefillDatabase, props.prefillSchema].filter(Boolean).join(" / "),
-);
-const canSearch = computed(() =>
- Boolean(props.prefillConnectionId && props.prefillDatabase && keyword.value.trim() && !running.value),
-);
-const progressLabel = computed(() =>
- t("databaseSearch.progress", { done: progressDone.value, total: progressTotal.value }),
-);
+const connection = computed(() => (props.prefillConnectionId ? connectionStore.getConfig(props.prefillConnectionId) : undefined));
+const scopeLabel = computed(() => [connection.value?.name, props.prefillDatabase, props.prefillSchema].filter(Boolean).join(" / "));
+const canSearch = computed(() => Boolean(props.prefillConnectionId && props.prefillDatabase && keyword.value.trim() && !running.value));
+const progressLabel = computed(() => t("databaseSearch.progress", { done: progressDone.value, total: progressTotal.value }));
watch(
dialogOpen,
@@ -160,11 +142,7 @@ function rowPreview(columns: string[], row: unknown[], matchedColumns: string[])
async function listSearchTables(): Promise<SearchTableTask[]> {
if (!connection.value || !props.prefillConnectionId || !props.prefillDatabase) return [];
const databaseType = connection.value.db_type;
- const schemaNames = props.prefillSchema
- ? [props.prefillSchema]
- : isSchemaAware(databaseType)
- ? filterSearchSchemas(await api.listSchemas(props.prefillConnectionId, props.prefillDatabase))
- : [props.prefillDatabase];
+ const schemaNames = props.prefillSchema ? [props.prefillSchema] : isSchemaAware(databaseType) ? filterSearchSchemas(await api.listSchemas(props.prefillConnectionId, props.prefillDatabase)) : [props.prefillDatabase];
const tasks: SearchTableTask[] = [];
for (const schema of schemaNames) {
@@ -228,13 +206,7 @@ async function searchTable(task: SearchTableTask, databaseType: DatabaseType, cu
const executionId = makeExecutionId();
currentExecutionId.value = executionId;
- const result = await api.executeQuery(
- props.prefillConnectionId,
- props.prefillDatabase,
- query.sql,
- undefined,
- executionId,
- );
+ const result = await api.executeQuery(props.prefillConnectionId, props.prefillDatabase, query.sql, undefined, executionId);
if (currentExecutionId.value === executionId) currentExecutionId.value = "";
if (currentRun !== runId || cancelled.value) return;
@@ -308,13 +280,7 @@ function openResult(item: SearchResultItem) {
<div class="grid gap-3 md:grid-cols-[1fr_9rem_auto]">
<div class="space-y-1.5">
<Label class="text-xs">{{ t("databaseSearch.keyword") }}</Label>
- <Input
- v-model="keyword"
- class="h-9"
- :placeholder="t('databaseSearch.keywordPlaceholder')"
- :disabled="running"
- @keydown.enter.prevent="startSearch"
- />
+ <Input v-model="keyword" class="h-9" :placeholder="t('databaseSearch.keywordPlaceholder')" :disabled="running" @keydown.enter.prevent="startSearch" />
</div>
<div class="space-y-1.5">
<Label class="text-xs">{{ t("databaseSearch.limitPerTable") }}</Label>
@@ -340,15 +306,10 @@ function openResult(item: SearchResultItem) {
<div v-if="running || progressTotal" class="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
<span>{{ loadingTables ? t("databaseSearch.loadingTables") : progressLabel }}</span>
<span>{{ t("databaseSearch.resultCount", { count: results.length }) }}</span>
- <span v-if="limitedTables" class="text-amber-600">{{
- t("databaseSearch.limitedTables", { count: 200 })
- }}</span>
+ <span v-if="limitedTables" class="text-amber-600">{{ t("databaseSearch.limitedTables", { count: 200 }) }}</span>
</div>
- <div
- v-if="generalError"
- class="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive"
- >
+ <div v-if="generalError" class="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
<AlertCircle class="mt-0.5 h-4 w-4" />
<span>{{ generalError }}</span>
</div>
@@ -359,18 +320,11 @@ function openResult(item: SearchResultItem) {
<Badge variant="outline">{{ results.length }}</Badge>
</div>
<div v-if="results.length" class="max-h-[360px] space-y-2 overflow-auto pr-1">
- <button
- v-for="item in results"
- :key="item.id"
- class="flex w-full items-start gap-3 rounded-md border bg-background px-3 py-2 text-left transition-colors hover:bg-muted/40"
- @click="openResult(item)"
- >
+ <button v-for="item in results" :key="item.id" class="flex w-full items-start gap-3 rounded-md border bg-background px-3 py-2 text-left transition-colors hover:bg-muted/40" @click="openResult(item)">
<Table2 class="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div class="min-w-0 flex-1">
<div class="flex min-w-0 flex-wrap items-center gap-2">
- <span class="truncate font-medium">{{
- item.schema ? `${item.schema}.${item.tableName}` : item.tableName
- }}</span>
+ <span class="truncate font-medium">{{ item.schema ? `${item.schema}.${item.tableName}` : item.tableName }}</span>
<Badge v-for="column in item.matchedColumns" :key="column" variant="secondary">{{ column }}</Badge>
</div>
<div class="mt-1 truncate text-xs text-muted-foreground">{{ item.preview }}</div>
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index 0a11b92661..8e8965da8e 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -10,22 +10,8 @@ import { filterSidebarSearchRootsByConnectionState, filterSidebarTree } from "@/
import { isCancelSearchShortcut } from "@/lib/keyboardShortcuts";
import { usesTreeSchemaMode } from "@/lib/databaseFeatureSupport";
import { connectionUsesDatabaseObjectTreeMode } from "@/lib/jdbcDialect";
-import {
- findSidebarNodeForActiveTab,
- findNodePathForActiveTab,
- scrollTopForSidebarNode,
- shouldScrollActiveSidebarSelection,
-} from "@/lib/sidebarActiveTabTarget";
-import {
- SIDEBAR_TREE_ROW_HEIGHT,
- SIDEBAR_TREE_PRERENDER_COUNT,
- SIDEBAR_TREE_SCROLL_BUFFER,
- flattenTree,
- scrollTopForExpandedTreeNode,
- shouldAutoScrollExpandedTreeNode,
- shouldVirtualizeFlatTree,
- type FlatTreeNode,
-} from "@/composables/useFlatTree";
+import { findSidebarNodeForActiveTab, findNodePathForActiveTab, scrollTopForSidebarNode, shouldScrollActiveSidebarSelection } from "@/lib/sidebarActiveTabTarget";
+import { SIDEBAR_TREE_ROW_HEIGHT, SIDEBAR_TREE_PRERENDER_COUNT, SIDEBAR_TREE_SCROLL_BUFFER, flattenTree, scrollTopForExpandedTreeNode, shouldAutoScrollExpandedTreeNode, shouldVirtualizeFlatTree, type FlatTreeNode } from "@/composables/useFlatTree";
import { sidebarTreeContextKey } from "@/lib/sidebarTreeContext";
import TreeItem from "./TreeItem.vue";
import { RecycleScroller } from "vue-virtual-scroller";
@@ -156,11 +142,7 @@ const visibleNodeIndexById = computed(() => {
});
const useVirtualTree = computed(() => shouldVirtualizeFlatTree(flatNodes.value.length));
const activeTab = computed(() => queryStore.tabs.find((tab) => tab.id === queryStore.activeTabId));
-const sidebarTreeOverflowClass = computed(() =>
- settingsStore.editorSettings.sidebarAllowHorizontalScroll
- ? "overflow-x-auto sidebar-tree-horizontal-scroll"
- : "overflow-x-hidden",
-);
+const sidebarTreeOverflowClass = computed(() => (settingsStore.editorSettings.sidebarAllowHorizontalScroll ? "overflow-x-auto sidebar-tree-horizontal-scroll" : "overflow-x-hidden"));
provide(sidebarTreeContextKey, {
getVisibleNodes: () => visibleNodes.value,
@@ -389,10 +371,7 @@ async function onNodeToggled(node: TreeNode, wasExpanded: boolean) {
}
function currentTreeScroller(): HTMLElement | null {
- return (
- ((useVirtualTree.value ? treeScrollerRef.value?.$el : plainTreeScrollerRef.value) as HTMLElement | undefined) ??
- null
- );
+ return ((useVirtualTree.value ? treeScrollerRef.value?.$el : plainTreeScrollerRef.value) as HTMLElement | undefined) ?? null;
}
async function selectActiveTabSidebarNode(options: { scroll: boolean }) {
@@ -467,19 +446,11 @@ defineExpose({ focusSearch, createNewGroup });
:placeholder="t('grid.search')"
@keydown="onSearchKeydown"
/>
- <button
- v-if="searchQuery"
- class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- @click="searchQuery = ''"
- >
+ <button v-if="searchQuery" class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground" @click="searchQuery = ''">
<X class="h-3 w-3" />
</button>
</div>
- <button
- class="shrink-0 h-6 w-6 flex items-center justify-center rounded border border-border text-muted-foreground hover:bg-accent hover:text-foreground"
- :title="t('sidebar.locateActiveTab')"
- @click="locateActiveTabInSidebar"
- >
+ <button class="shrink-0 h-6 w-6 flex items-center justify-center rounded border border-border text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('sidebar.locateActiveTab')" @click="locateActiveTabInSidebar">
<Crosshair class="h-3.5 w-3.5" />
</button>
<LightDropdown
@@ -491,12 +462,7 @@ defineExpose({ focusSearch, createNewGroup });
:label="t('sidebar.filterByType')"
:trigger-title="t('sidebar.filterByType')"
:trigger-icon="ListFilter"
- :trigger-class="
- [
- 'shrink-0 h-6 w-6 flex items-center justify-center rounded border border-border hover:bg-accent',
- hasSearchScopeFilter ? 'text-primary bg-primary/10 border-primary/30' : 'text-muted-foreground',
- ].join(' ')
- "
+ :trigger-class="['shrink-0 h-6 w-6 flex items-center justify-center rounded border border-border hover:bg-accent', hasSearchScopeFilter ? 'text-primary bg-primary/10 border-primary/30' : 'text-muted-foreground'].join(' ')"
trigger-icon-class="h-3.5 w-3.5"
item-icon-class="h-3.5 w-3.5"
content-class="w-max min-w-0"
@@ -538,13 +504,7 @@ defineExpose({ focusSearch, createNewGroup });
/>
</template>
</RecycleScroller>
- <div
- v-else-if="flatNodes.length > 0"
- ref="plainTreeScrollerRef"
- class="sidebar-tree min-h-0 flex-1 overflow-y-auto"
- :class="sidebarTreeOverflowClass"
- @click="clearSidebarSelection"
- >
+ <div v-else-if="flatNodes.length > 0" ref="plainTreeScrollerRef" class="sidebar-tree min-h-0 flex-1 overflow-y-auto" :class="sidebarTreeOverflowClass" @click="clearSidebarSelection">
<TreeItem
v-for="item in flatNodes"
:key="item.id"
diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vue
index 588c4dd3b4..05388f25ac 100644
--- a/apps/desktop/src/components/sidebar/TreeItem.vue
+++ b/apps/desktop/src/components/sidebar/TreeItem.vue
@@ -60,42 +60,13 @@ import { uuid } from "@/lib/utils";
import { resolveDefaultDatabase } from "@/lib/defaultDatabase";
import { canTreeNodeShowExpander, treeItemPaddingLeft, usesFullWidthTreeLabel } from "@/lib/sidebarTreeItemLayout";
import { buildTableSelectSql } from "@/lib/tableSelectSql";
-import {
- clearActiveTableReferencePayload,
- createTableReferencePayload,
- createTableReferenceDropEvent,
- setActiveTableReferencePayload,
- type QueryEditorTableReferencePayload,
-} from "@/lib/queryEditorTableDrop";
+import { clearActiveTableReferencePayload, createTableReferencePayload, createTableReferenceDropEvent, setActiveTableReferencePayload, type QueryEditorTableReferencePayload } from "@/lib/queryEditorTableDrop";
import { editablePrimaryKeys } from "@/lib/tableEditing";
-import {
- supportsDatabaseCreation,
- supportsDatabaseSearch,
- supportsFieldLineage,
- supportsObjectBrowserTreeNode,
- supportsSchemaDiagram,
- supportsSqlFileExecution,
- supportsTableImport,
- supportsTableTruncate,
- supportsTableStructureEditing,
- usesTreeSchemaMode,
-} from "@/lib/databaseCapabilities";
-import {
- copyNameForTreeNode,
- objectSourceKindForTreeNode,
- sidebarSelectionCopyAction,
- treeNodeRowAction,
- treeNodeRowDoubleClickAction,
-} from "@/lib/treeNodeClick";
+import { supportsDatabaseCreation, supportsDatabaseSearch, supportsFieldLineage, supportsObjectBrowserTreeNode, supportsSchemaDiagram, supportsSqlFileExecution, supportsTableImport, supportsTableTruncate, supportsTableStructureEditing, usesTreeSchemaMode } from "@/lib/databaseCapabilities";
+import { copyNameForTreeNode, objectSourceKindForTreeNode, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "@/lib/treeNodeClick";
import { formatSqlInsert } from "@/lib/exportFormats";
import { fetchTableDataForExport } from "@/lib/tableDataExport";
-import {
- buildCreateDatabaseSql,
- buildDuckDbAttachDatabaseSql,
- duckDbAttachedDatabaseNameFromPath,
- supportsCreateDatabaseCharset,
- uniqueDuckDbAttachedDatabaseName,
-} from "@/lib/createDatabaseSql";
+import { buildCreateDatabaseSql, buildDuckDbAttachDatabaseSql, duckDbAttachedDatabaseNameFromPath, supportsCreateDatabaseCharset, uniqueDuckDbAttachedDatabaseName } from "@/lib/createDatabaseSql";
import {
buildCreateSchemaSql,
buildDropDatabaseSql,
@@ -115,21 +86,12 @@ import { buildRenameObjectSql, supportsObjectRename, type RenameableObjectType }
import { buildRoutineRenameObjectSourceStatements, supportsSourceBackedRoutineRename } from "@/lib/objectSourceEditor";
import { buildViewDdl } from "@/lib/viewDdl";
import { getTableStructureCapabilities } from "@/lib/tableStructureCapabilities";
-import {
- connectionObjectTreeNodeSchema,
- connectionObjectTreeQuerySchema,
- connectionUsesDatabaseObjectTreeMode,
- effectiveDatabaseTypeForConnection,
-} from "@/lib/jdbcDialect";
+import { connectionObjectTreeNodeSchema, connectionObjectTreeQuerySchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
import { hexToRgba } from "@/lib/color";
import { focusSidebarRenameInput } from "@/lib/sidebarRenameFocus";
import { hasTreeNodeDatabaseContext } from "@/lib/treeNodeContext";
import { sidebarDisplayTableName } from "@/lib/sidebarTableNameDisplay";
-import {
- selectedTreeNodesInVisibleOrder as orderSelectedTreeNodes,
- treeSelectionRangeIdsByIndex,
- treeSelectionRangeIds,
-} from "@/lib/sidebarTreeSelection";
+import { selectedTreeNodesInVisibleOrder as orderSelectedTreeNodes, treeSelectionRangeIdsByIndex, treeSelectionRangeIds } from "@/lib/sidebarTreeSelection";
import { selectedConnectionDeleteTargets } from "@/lib/sidebarConnectionSelection";
import { supportsDatabaseUserAdmin } from "@/lib/databaseUserAdmin";
import { sidebarTreeContextKey } from "@/lib/sidebarTreeContext";
@@ -186,19 +148,13 @@ const emit = defineEmits<{
"search-toggle": [node: TreeNode];
}>();
-const usesFullWidthLabel = computed(() =>
- usesFullWidthTreeLabel(props.node.type, settingsStore.editorSettings.sidebarAllowHorizontalScroll),
-);
+const usesFullWidthLabel = computed(() => usesFullWidthTreeLabel(props.node.type, settingsStore.editorSettings.sidebarAllowHorizontalScroll));
const sidebarTreeContext = inject(sidebarTreeContextKey, null);
const rowWidthClass = computed(() => (usesFullWidthLabel.value ? "w-max min-w-full" : "w-full min-w-0"));
-const labelWidthClass = computed(() =>
- usesFullWidthLabel.value ? "shrink-0 whitespace-nowrap" : "min-w-0 flex-1 truncate",
-);
+const labelWidthClass = computed(() => (usesFullWidthLabel.value ? "shrink-0 whitespace-nowrap" : "min-w-0 flex-1 truncate"));
function currentDatabaseType(): DatabaseType | undefined {
- return props.node.connectionId
- ? effectiveDatabaseTypeForConnection(connectionStore.getConfig(props.node.connectionId))
- : undefined;
+ return props.node.connectionId ? effectiveDatabaseTypeForConnection(connectionStore.getConfig(props.node.connectionId)) : undefined;
}
function rawDatabaseType(): DatabaseType | undefined {
@@ -206,9 +162,7 @@ function rawDatabaseType(): DatabaseType | undefined {
}
function databaseTypeForNode(node: TreeNode): DatabaseType | undefined {
- return node.connectionId
- ? effectiveDatabaseTypeForConnection(connectionStore.getConfig(node.connectionId))
- : undefined;
+ return node.connectionId ? effectiveDatabaseTypeForConnection(connectionStore.getConfig(node.connectionId)) : undefined;
}
function hasNodeDatabaseContext(node: TreeNode): node is TreeNode & { connectionId: string; database: string } {
@@ -286,29 +240,8 @@ function getIconInfo(node: TreeNode): { icon: any; colorClass: string } | null {
}
}
-const groupTypes: Set<TreeNodeType> = new Set([
- "group-columns",
- "group-indexes",
- "group-fkeys",
- "group-triggers",
- "group-tables",
- "group-views",
- "group-procedures",
- "group-functions",
- "group-sequences",
- "group-packages",
- "group-partitions",
-]);
-const pinnableTypes: Set<TreeNodeType> = new Set([
- "connection-group",
- "database",
- "schema",
- "table",
- "view",
- "redis-db",
- "mongo-db",
- "mongo-collection",
-]);
+const groupTypes: Set<TreeNodeType> = new Set(["group-columns", "group-indexes", "group-fkeys", "group-triggers", "group-tables", "group-views", "group-procedures", "group-functions", "group-sequences", "group-packages", "group-partitions"]);
+const pinnableTypes: Set<TreeNodeType> = new Set(["connection-group", "database", "schema", "table", "view", "redis-db", "mongo-db", "mongo-collection"]);
function isGroupLabel(node: TreeNode): boolean {
return groupTypes.has(node.type);
@@ -351,13 +284,7 @@ async function toggle() {
return;
}
- const databaseObjectGroup =
- node.type === "group-tables" ||
- node.type === "group-views" ||
- node.type === "group-procedures" ||
- node.type === "group-functions" ||
- node.type === "group-sequences" ||
- node.type === "group-packages";
+ const databaseObjectGroup = node.type === "group-tables" || node.type === "group-views" || node.type === "group-procedures" || node.type === "group-functions" || node.type === "group-sequences" || node.type === "group-packages";
if (databaseObjectGroup && connectionStore.isTreeNodeChildrenLoaded(node.id)) {
node.isExpanded = !node.isExpanded;
emit("node-toggled", node, wasExpanded);
@@ -407,34 +334,15 @@ async function toggle() {
}
} else if (node.type === "schema" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.schema) {
await connectionStore.loadTables(node.connectionId, node.database, node.schema);
- } else if (
- (node.type === "table" || node.type === "view") &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node)
- ) {
+ } else if ((node.type === "table" || node.type === "view") && node.connectionId && hasTreeNodeDatabaseContext(node)) {
await connectionStore.loadTableGroups(node.connectionId, node.database, node.label, node.schema, node.id);
- } else if (
- node.type === "group-columns" &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node) &&
- node.tableName
- ) {
+ } else if (node.type === "group-columns" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await connectionStore.loadColumns(node.connectionId, node.database, node.tableName, node.schema, node.id);
- } else if (
- node.type === "group-indexes" &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node) &&
- node.tableName
- ) {
+ } else if (node.type === "group-indexes" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await connectionStore.loadIndexes(node.connectionId, node.database, node.tableName, node.schema, node.id);
} else if (node.type === "group-fkeys" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await connectionStore.loadForeignKeys(node.connectionId, node.database, node.tableName, node.schema, node.id);
- } else if (
- node.type === "group-triggers" &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node) &&
- node.tableName
- ) {
+ } else if (node.type === "group-triggers" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await connectionStore.loadTriggers(node.connectionId, node.database, node.tableName, node.schema, node.id);
} else if (databaseObjectGroup) {
await connectionStore.loadObjectGroupChildren(node);
@@ -459,13 +367,7 @@ function runRowClickAction() {
const action = treeNodeRowAction(node.type, canExpand.value, settingsStore.editorSettings.sidebarActivation);
if (action === "open-data") {
openData();
- } else if (
- node.type === "procedure" ||
- node.type === "function" ||
- node.type === "sequence" ||
- node.type === "package" ||
- node.type === "package-body"
- ) {
+ } else if (node.type === "procedure" || node.type === "function" || node.type === "sequence" || node.type === "package" || node.type === "package-body") {
void viewObjectSource();
} else if (action === "toggle") {
toggle();
@@ -557,12 +459,7 @@ function onTreeItemContextMenu(event: MouseEvent, openContextMenu: (event: Mouse
function isEditableShortcutTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
- return (
- target instanceof HTMLInputElement ||
- target instanceof HTMLTextAreaElement ||
- target.isContentEditable ||
- !!target.closest("[contenteditable='true']")
- );
+ return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target.isContentEditable || !!target.closest("[contenteditable='true']");
}
function onKeydown(event: KeyboardEvent) {
@@ -670,12 +567,7 @@ function requestDeleteSelectedNode(): boolean {
}
function onDoubleClick() {
- const action = treeNodeRowDoubleClickAction(
- props.node.type,
- canOpenObjectBrowser.value,
- settingsStore.editorSettings.sidebarActivation,
- canExpand.value,
- );
+ const action = treeNodeRowDoubleClickAction(props.node.type, canOpenObjectBrowser.value, settingsStore.editorSettings.sidebarActivation, canExpand.value);
if (action === "open-object-browser") {
void openObjectBrowser();
} else if (action === "open-object-browser-and-expand") {
@@ -713,10 +605,7 @@ async function openObjectBrowser() {
}
} catch (e: any) {
toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);
- if (
- e?.message?.includes("driver is not installed") ||
- (e?.message?.includes("JRE") && e?.message?.includes("not installed"))
- ) {
+ if (e?.message?.includes("driver is not installed") || (e?.message?.includes("JRE") && e?.message?.includes("not installed"))) {
window.dispatchEvent(new Event("dbx-open-driver-store"));
}
}
@@ -753,9 +642,7 @@ async function openData() {
const tableSchema = connectionObjectTreeNodeSchema(config, node.database, node.schema);
const tabId = (() => {
if (settingsStore.editorSettings.reuseDataTab) {
- const existing = queryStore.tabs.find(
- (tab) => tab.mode === "data" && tab.connectionId === node.connectionId && tab.database === node.database,
- );
+ const existing = queryStore.tabs.find((tab) => tab.mode === "data" && tab.connectionId === node.connectionId && tab.database === node.database);
if (existing) {
existing.title = node.label;
existing.schema = tableSchema;
@@ -855,10 +742,7 @@ async function newQuery() {
queryStore.createTab(node.connectionId, resolveDefaultDatabase(connection, options), undefined, "query");
} catch (e: any) {
toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);
- if (
- e?.message?.includes("driver is not installed") ||
- (e?.message?.includes("JRE") && e?.message?.includes("not installed"))
- ) {
+ if (e?.message?.includes("driver is not installed") || (e?.message?.includes("JRE") && e?.message?.includes("not installed"))) {
window.dispatchEvent(new Event("dbx-open-driver-store"));
}
}
@@ -889,10 +773,7 @@ async function refresh() {
await connectionStore.refreshTreeNode(props.node);
} catch (e: any) {
toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);
- if (
- e?.message?.includes("driver is not installed") ||
- (e?.message?.includes("JRE") && e?.message?.includes("not installed"))
- ) {
+ if (e?.message?.includes("driver is not installed") || (e?.message?.includes("JRE") && e?.message?.includes("not installed"))) {
window.dispatchEvent(new Event("dbx-open-driver-store"));
}
}
@@ -911,9 +792,7 @@ function connectionDeleteMenuLabel(): string {
function connectionDeleteConfirmMessage(): string {
const targets = connectionDeleteTargets();
- return targets.length > 1
- ? t("contextMenu.confirmDeleteSelectedMessage", { count: targets.length })
- : t("contextMenu.confirmDeleteMessage", { name: props.node.label });
+ return targets.length > 1 ? t("contextMenu.confirmDeleteSelectedMessage", { count: targets.length }) : t("contextMenu.confirmDeleteMessage", { name: props.node.label });
}
function deleteConnection() {
@@ -929,10 +808,7 @@ async function confirmDelete() {
await connectionStore.disconnect(target.connectionId);
}
await connectionStore.removeConnections(targets.map((target) => target.connectionId));
- toast(
- targets.length > 1 ? t("connection.deletedSelected", { count: targets.length }) : t("connection.deleted"),
- 2000,
- );
+ toast(targets.length > 1 ? t("connection.deletedSelected", { count: targets.length }) : t("connection.deleted"), 2000);
} catch (e: any) {
toast(t("connection.saveFailed", { message: e?.message || String(e) }), 5000);
}
@@ -964,8 +840,7 @@ async function copyFinalProxyPort() {
async function copySelectedNames() {
const selectedNodes = selectedTreeNodesInVisibleOrder();
- const nodes =
- selectedNodes.length > 1 && selectedNodes.some((node) => node.id === props.node.id) ? selectedNodes : [props.node];
+ const nodes = selectedNodes.length > 1 && selectedNodes.some((node) => node.id === props.node.id) ? selectedNodes : [props.node];
updateTreeClipboardForNodes(nodes);
try {
await copyToClipboard(nodes.map(copyNameForTreeNode).join("\n"));
@@ -976,10 +851,7 @@ async function copySelectedNames() {
}
function updateTreeClipboardForNodes(nodes: TreeNode[]) {
- const tableNodes = nodes.filter(
- (node): node is DuplicateStructureSource =>
- node.type === "table" && !!node.connectionId && !!node.database && typeof node.label === "string",
- );
+ const tableNodes = nodes.filter((node): node is DuplicateStructureSource => node.type === "table" && !!node.connectionId && !!node.database && typeof node.label === "string");
if (nodes.length !== 1 || tableNodes.length !== 1) {
connectionStore.treeClipboard = null;
return;
@@ -1072,13 +944,10 @@ function tableChildDropObjectType(type: TreeNodeType): TableChildObjectType | nu
}
function tableChildDropObjectName(node: TreeNode): string {
- if (node.type === "column")
- return node.meta && "name" in node.meta ? node.meta.name : node.label.replace(/\s+\(.+\)$/, "");
- if (node.type === "index")
- return node.meta && "name" in node.meta ? node.meta.name : node.label.replace(/\s+\(.+\)$/, "");
+ if (node.type === "column") return node.meta && "name" in node.meta ? node.meta.name : node.label.replace(/\s+\(.+\)$/, "");
+ if (node.type === "index") return node.meta && "name" in node.meta ? node.meta.name : node.label.replace(/\s+\(.+\)$/, "");
if (node.type === "fkey") return node.meta && "name" in node.meta ? node.meta.name : node.label;
- if (node.type === "trigger")
- return node.meta && "name" in node.meta ? node.meta.name : node.label.replace(/\s+\(.+\)$/, "");
+ if (node.type === "trigger") return node.meta && "name" in node.meta ? node.meta.name : node.label.replace(/\s+\(.+\)$/, "");
return node.label;
}
@@ -1268,11 +1137,7 @@ function selectedBatchDropTargets(): TreeNode[] {
if (selected.length <= 1 || !selected.some((node) => node.id === props.node.id)) return [];
const first = selected[0];
if (!first?.connectionId || !first.database || !selected.every((node) => node.type === first.type)) return [];
- if (
- !selected.every(
- (node) => node.connectionId === first.connectionId && node.database === first.database && canDropTreeNode(node),
- )
- ) {
+ if (!selected.every((node) => node.connectionId === first.connectionId && node.database === first.database && canDropTreeNode(node))) {
return [];
}
return selected;
@@ -1357,11 +1222,7 @@ function nodeRenameObjectType(): RenameableObjectType | null {
const canRenameObject = computed(() => {
const objectType = nodeRenameObjectType();
- return (
- !!objectType &&
- (supportsObjectRename(currentDatabaseType(), objectType) ||
- supportsSourceBackedRoutineRename(currentDatabaseType(), objectType as any))
- );
+ return !!objectType && (supportsObjectRename(currentDatabaseType(), objectType) || supportsSourceBackedRoutineRename(currentDatabaseType(), objectType as any));
});
function openRenameObjectDialog() {
@@ -1399,19 +1260,9 @@ async function refreshRenameObjectPreviewSql() {
}
}
-watch(
- [
- showRenameObjectDialog,
- renameObjectName,
- () => props.node.label,
- () => props.node.schema,
- () => props.node.type,
- () => currentDatabaseType(),
- ],
- () => {
- void refreshRenameObjectPreviewSql();
- },
-);
+watch([showRenameObjectDialog, renameObjectName, () => props.node.label, () => props.node.schema, () => props.node.type, () => currentDatabaseType()], () => {
+ void refreshRenameObjectPreviewSql();
+});
async function confirmRenameObject() {
const node = props.node;
@@ -1463,12 +1314,7 @@ async function confirmDropObject() {
await connectionStore.ensureConnected(node.connectionId);
const sql = dropObjectPreviewSql.value || (await buildDropObjectSql(options));
await api.executeQuery(node.connectionId, node.database, sql, node.schema);
- const msgKey =
- node.type === "view"
- ? "contextMenu.dropViewSuccess"
- : node.type === "procedure"
- ? "contextMenu.dropProcedureSuccess"
- : "contextMenu.dropFunctionSuccess";
+ const msgKey = node.type === "view" ? "contextMenu.dropViewSuccess" : node.type === "procedure" ? "contextMenu.dropProcedureSuccess" : "contextMenu.dropFunctionSuccess";
toast(t(msgKey, { name: node.label }), 3000);
if (node.type === "view") {
connectionStore.removeTreeNode(node.id);
@@ -1523,18 +1369,12 @@ const supportsTruncate = computed(() => {
const canCreateTable = computed(() => {
const config = props.node.connectionId ? connectionStore.getConfig(props.node.connectionId) : undefined;
- return (
- (props.node.type === "database" || props.node.type === "schema" || props.node.type === "group-tables") &&
- !!props.node.database &&
- supportsTableStructureEditing(effectiveDatabaseTypeForConnection(config))
- );
+ return (props.node.type === "database" || props.node.type === "schema" || props.node.type === "group-tables") && !!props.node.database && supportsTableStructureEditing(effectiveDatabaseTypeForConnection(config));
});
const canCreateDatabase = computed(() => {
const config = props.node.connectionId ? connectionStore.getConfig(props.node.connectionId) : undefined;
- return (
- props.node.type === "connection" && (supportsDatabaseCreation(config?.db_type) || config?.db_type === "duckdb")
- );
+ return props.node.type === "connection" && (supportsDatabaseCreation(config?.db_type) || config?.db_type === "duckdb");
});
const isDuckDbConnection = computed(() => {
@@ -1554,18 +1394,12 @@ const canDropDatabase = computed(() => {
const canCreateSchema = computed(() => {
const config = props.node.connectionId ? connectionStore.getConfig(props.node.connectionId) : undefined;
- return (
- props.node.type === "database" &&
- usesTreeSchemaMode(config?.db_type) &&
- !connectionUsesDatabaseObjectTreeMode(config)
- );
+ return props.node.type === "database" && usesTreeSchemaMode(config?.db_type) && !connectionUsesDatabaseObjectTreeMode(config);
});
const canDropSchema = computed(() => {
const config = props.node.connectionId ? connectionStore.getConfig(props.node.connectionId) : undefined;
- return (
- props.node.type === "schema" && usesTreeSchemaMode(config?.db_type) && !connectionUsesDatabaseObjectTreeMode(config)
- );
+ return props.node.type === "schema" && usesTreeSchemaMode(config?.db_type) && !connectionUsesDatabaseObjectTreeMode(config);
});
function tableAdminSqlOptions(): TableAdminSqlOptions {
@@ -1897,13 +1731,7 @@ function createView() {
if (!node.connectionId || !node.database) return;
connectionStore.activeConnectionId = node.connectionId;
const viewName = node.schema ? `${node.schema}.new_view` : "new_view";
- const tabId = queryStore.createTab(
- node.connectionId,
- node.database,
- t("contextMenu.createView"),
- "query",
- node.schema,
- );
+ const tabId = queryStore.createTab(node.connectionId, node.database, t("contextMenu.createView"), "query", node.schema);
queryStore.updateSql(tabId, `CREATE VIEW ${viewName} AS\nSELECT\n *\nFROM table_name;\n`);
}
@@ -1933,22 +1761,14 @@ async function exportStructure() {
isLoadingStructurePreview.value = true;
structurePreviewError.value = "";
structurePreviewSql.value = "";
- structurePreviewTitle.value =
- targets.length === 1
- ? t("contextMenu.exportStructurePreviewTitle", { name: targets[0]!.label })
- : t("contextMenu.exportStructurePreviewTitleMultiple", { count: targets.length });
+ structurePreviewTitle.value = targets.length === 1 ? t("contextMenu.exportStructurePreviewTitle", { name: targets[0]!.label }) : t("contextMenu.exportStructurePreviewTitleMultiple", { count: targets.length });
structurePreviewDefaultFileName.value = targets.length === 1 ? `${targets[0]!.label}.sql` : "structures.sql";
showStructurePreviewDialog.value = true;
try {
const parts: string[] = [];
for (const target of targets) {
await connectionStore.ensureConnected(target.connectionId);
- const ddl = await api.getTableDdl(
- target.connectionId,
- target.database,
- target.schema || target.database,
- target.label,
- );
+ const ddl = await api.getTableDdl(target.connectionId, target.database, target.schema || target.database, target.label);
parts.push(ddl.trim());
}
structurePreviewSql.value = `${parts.filter(Boolean).join("\n\n")}\n`;
@@ -1980,12 +1800,7 @@ function selectedStructureNodes(): TreeNode[] {
function structureExportTargets(): Array<TreeNode & { connectionId: string; database: string }> {
if (!canExportStructureNode(props.node)) return [];
- const selected = selectedStructureNodes().filter(
- (node): node is TreeNode & { connectionId: string; database: string } =>
- canExportStructureNode(node) &&
- node.connectionId === props.node.connectionId &&
- node.database === props.node.database,
- );
+ const selected = selectedStructureNodes().filter((node): node is TreeNode & { connectionId: string; database: string } => canExportStructureNode(node) && node.connectionId === props.node.connectionId && node.database === props.node.database);
return selected.some((node) => node.id === props.node.id) ? selected : [props.node];
}
@@ -2006,39 +1821,18 @@ function markdownCell(value: unknown): string {
}
function columnDocHeaders(includeTable: boolean): string[] {
- const headers = [
- t("contextMenu.structureDocColumn"),
- t("contextMenu.structureDocType"),
- t("contextMenu.structureDocPrimaryKey"),
- t("contextMenu.structureDocNullable"),
- t("contextMenu.structureDocDefault"),
- t("contextMenu.structureDocComment"),
- ];
+ const headers = [t("contextMenu.structureDocColumn"), t("contextMenu.structureDocType"), t("contextMenu.structureDocPrimaryKey"), t("contextMenu.structureDocNullable"), t("contextMenu.structureDocDefault"), t("contextMenu.structureDocComment")];
return includeTable ? [t("contextMenu.structureDocTable"), ...headers] : headers;
}
function columnDocCells(target: TreeNode, column: ColumnInfo, includeTable: boolean): unknown[] {
- const cells = [
- column.name,
- column.data_type,
- column.is_primary_key ? t("contextMenu.structureDocYes") : t("contextMenu.structureDocNo"),
- column.is_nullable ? t("contextMenu.structureDocYes") : t("contextMenu.structureDocNo"),
- column.column_default,
- column.comment,
- ];
+ const cells = [column.name, column.data_type, column.is_primary_key ? t("contextMenu.structureDocYes") : t("contextMenu.structureDocNo"), column.is_nullable ? t("contextMenu.structureDocYes") : t("contextMenu.structureDocNo"), column.column_default, column.comment];
return includeTable ? [structureTargetName(target), ...cells] : cells;
}
-async function tableColumnsForStructureCopy(
- target: TreeNode & { connectionId: string; database: string },
-): Promise<ColumnInfo[]> {
+async function tableColumnsForStructureCopy(target: TreeNode & { connectionId: string; database: string }): Promise<ColumnInfo[]> {
await connectionStore.ensureConnected(target.connectionId);
- return (await api.getColumns(
- target.connectionId,
- target.database,
- target.schema || target.database,
- target.label,
- )) as ColumnInfo[];
+ return (await api.getColumns(target.connectionId, target.database, target.schema || target.database, target.label)) as ColumnInfo[];
}
async function buildStructureCopyText(format: StructureCopyFormat): Promise<string> {
@@ -2062,13 +1856,7 @@ async function buildStructureCopyText(format: StructureCopyFormat): Promise<stri
const markdownHeaders = columnDocHeaders(false);
for (const target of targets) {
const columns = await tableColumnsForStructureCopy(target);
- const tableLines = [
- `### ${markdownCell(structureTargetName(target))}`,
- "",
- `| ${markdownHeaders.map(markdownCell).join(" | ")} |`,
- `| ${markdownHeaders.map(() => "---").join(" | ")} |`,
- ...columns.map((column) => `| ${columnDocCells(target, column, false).map(markdownCell).join(" | ")} |`),
- ];
+ const tableLines = [`### ${markdownCell(structureTargetName(target))}`, "", `| ${markdownHeaders.map(markdownCell).join(" | ")} |`, `| ${markdownHeaders.map(() => "---").join(" | ")} |`, ...columns.map((column) => `| ${columnDocCells(target, column, false).map(markdownCell).join(" | ")} |`)];
tables.push(tableLines.join("\n"));
}
return `${tables.join("\n\n")}\n`;
@@ -2084,8 +1872,7 @@ async function copyStructureAs(format: StructureCopyFormat) {
} catch (e: any) {
if (text) {
structureDocCopyText.value = text;
- structureDocCopyTitle.value =
- format === "tsv" ? t("contextMenu.copyStructureAsTsv") : t("contextMenu.copyStructureAsMarkdown");
+ structureDocCopyTitle.value = format === "tsv" ? t("contextMenu.copyStructureAsTsv") : t("contextMenu.copyStructureAsMarkdown");
showStructureDocCopyDialog.value = true;
return;
}
@@ -2137,14 +1924,8 @@ async function exportDataLegacy(format: "csv" | "json" | "sql") {
try {
await connectionStore.ensureConnected(connectionId);
- const tableColumns =
- format === "sql" ? await api.getColumns(connectionId, database, node.schema || database, node.label) : undefined;
- const queryColumns =
- config.db_type === "neo4j"
- ? (tableColumns ?? (await api.getColumns(connectionId, database, node.schema || database, node.label))).map(
- (column) => column.name,
- )
- : undefined;
+ const tableColumns = format === "sql" ? await api.getColumns(connectionId, database, node.schema || database, node.label) : undefined;
+ const queryColumns = config.db_type === "neo4j" ? (tableColumns ?? (await api.getColumns(connectionId, database, node.schema || database, node.label))).map((column) => column.name) : undefined;
const effectiveDbType = effectiveDatabaseTypeForConnection(config);
const result = await fetchTableDataForExport({
databaseType: effectiveDbType,
@@ -2243,10 +2024,7 @@ async function exportTableData(format: "csv" | "xlsx") {
const currentTask = task;
// Step 3: Get query columns for neo4j
- const queryColumns =
- config.db_type === "neo4j"
- ? (await api.getColumns(connectionId, database, node.schema || database, node.label)).map((c) => c.name)
- : undefined;
+ const queryColumns = config.db_type === "neo4j" ? (await api.getColumns(connectionId, database, node.schema || database, node.label)).map((c) => c.name) : undefined;
// Step 4: Start streaming export (background, non-blocking)
const request: api.TableExportRequest = {
@@ -2442,62 +2220,19 @@ const canOpenStructureEditor = computed(() => {
return props.node.type === "table" && !!props.node.database && supportsTableStructureEditing(currentDatabaseType());
});
const canOpenFieldLineage = computed(() => {
- return (
- props.node.type === "column" &&
- !!props.node.database &&
- !!props.node.tableName &&
- supportsFieldLineage(currentDatabaseType())
- );
+ return props.node.type === "column" && !!props.node.database && !!props.node.tableName && supportsFieldLineage(currentDatabaseType());
});
const isPinned = computed(() => props.node.pinned || connectionStore.isTreeNodePinned(props.node.id));
-const isNodeDefaultDatabase = computed(
- () =>
- (props.node.type === "database" || props.node.type === "redis-db" || props.node.type === "mongo-db") &&
- !!props.node.connectionId &&
- !!props.node.database &&
- connectionStore.isDefaultDatabase(props.node.connectionId, props.node.database),
-);
+const isNodeDefaultDatabase = computed(() => (props.node.type === "database" || props.node.type === "redis-db" || props.node.type === "mongo-db") && !!props.node.connectionId && !!props.node.database && connectionStore.isDefaultDatabase(props.node.connectionId, props.node.database));
const hasTypeMenu = computed(() => {
const t = props.node.type;
- return (
- t === "connection" ||
- t === "database" ||
- t === "schema" ||
- t === "table" ||
- t === "view" ||
- t === "column" ||
- t === "procedure" ||
- t === "function" ||
- t === "package" ||
- t === "package-body" ||
- isGroupLabel(props.node)
- );
+ return t === "connection" || t === "database" || t === "schema" || t === "table" || t === "view" || t === "column" || t === "procedure" || t === "function" || t === "package" || t === "package-body" || isGroupLabel(props.node);
});
-const columnComment = computed(() =>
- props.node.type === "column" && props.node.meta && "comment" in props.node.meta
- ? (props.node.meta as any).comment
- : null,
-);
-const tableComment = computed(() =>
- (props.node.type === "table" || props.node.type === "view" || props.node.type === "mongo-collection") &&
- props.node.comment
- ? props.node.comment
- : null,
-);
+const columnComment = computed(() => (props.node.type === "column" && props.node.meta && "comment" in props.node.meta ? (props.node.meta as any).comment : null));
+const tableComment = computed(() => ((props.node.type === "table" || props.node.type === "view" || props.node.type === "mongo-collection") && props.node.comment ? props.node.comment : null));
const paddingLeft = computed(() => treeItemPaddingLeft(props.depth));
-const isConnected = computed(
- () =>
- props.node.type === "connection" &&
- !!props.node.connectionId &&
- connectionStore.connectedIds.has(props.node.connectionId),
-);
-const canCloseDatabaseConnection = computed(
- () =>
- props.node.type === "database" &&
- !!props.node.connectionId &&
- props.node.database != null &&
- connectionStore.connectedIds.has(props.node.connectionId),
-);
+const isConnected = computed(() => props.node.type === "connection" && !!props.node.connectionId && connectionStore.connectedIds.has(props.node.connectionId));
+const canCloseDatabaseConnection = computed(() => props.node.type === "database" && !!props.node.connectionId && props.node.database != null && connectionStore.connectedIds.has(props.node.connectionId));
const nodeIconClass = computed(() => {
const infoClass = getIconInfo(props.node)?.colorClass;
if (props.node.type !== "database") return infoClass;
@@ -2522,9 +2257,7 @@ const connectionColor = computed(() => {
const connectionId = props.node.connectionId;
return connectionId ? connectionStore.getConfig(connectionId)?.color || "" : "";
});
-const isActiveConnectionScope = computed(
- () => !!props.node.connectionId && connectionStore.activeConnectionId === props.node.connectionId,
-);
+const isActiveConnectionScope = computed(() => !!props.node.connectionId && connectionStore.activeConnectionId === props.node.connectionId);
const isSelected = computed(() => connectionStore.selectedTreeNodeId === props.node.id);
const isMultiSelected = computed(() => connectionStore.selectedTreeNodeIds.includes(props.node.id));
const rowStyle = computed(() => {
@@ -2660,25 +2393,13 @@ const isDraggable = computed(() => {
const isDropTarget = computed(() => props.node.type === "connection" || props.node.type === "connection-group");
-const showDropBefore = computed(
- () => dragState.active && dragState.targetId === props.node.id && dragState.dropPosition === "before",
-);
-const showDropAfter = computed(
- () => dragState.active && dragState.targetId === props.node.id && dragState.dropPosition === "after",
-);
-const showDropInside = computed(
- () => dragState.active && dragState.targetId === props.node.id && dragState.dropPosition === "inside",
-);
+const showDropBefore = computed(() => dragState.active && dragState.targetId === props.node.id && dragState.dropPosition === "before");
+const showDropAfter = computed(() => dragState.active && dragState.targetId === props.node.id && dragState.dropPosition === "after");
+const showDropInside = computed(() => dragState.active && dragState.targetId === props.node.id && dragState.dropPosition === "inside");
const isDragging = computed(() => dragState.active && dragState.draggedId === props.node.id);
const TABLE_REFERENCE_DRAG_THRESHOLD = 5;
const TABLE_REFERENCE_DRAGGING_CLASS = "dbx-table-reference-dragging";
-const canDragTableReference = computed(
- () =>
- !props.dragDisabled &&
- (props.node.type === "table" || props.node.type === "view") &&
- !!props.node.connectionId &&
- props.node.database != null,
-);
+const canDragTableReference = computed(() => !props.dragDisabled && (props.node.type === "table" || props.node.type === "view") && !!props.node.connectionId && props.node.database != null);
let pendingTableReferenceDrag: {
payload: QueryEditorTableReferencePayload;
@@ -3132,9 +2853,7 @@ function treeItemMenuItems(): ContextMenuItem[] {
}
items.push({ label: "", separator: true });
items.push({
- label: deleteMenuLabel(
- node.type === "procedure" ? t("contextMenu.dropProcedure") : t("contextMenu.dropFunction"),
- ),
+ label: deleteMenuLabel(node.type === "procedure" ? t("contextMenu.dropProcedure") : t("contextMenu.dropFunction")),
action: deleteMenuAction(requestDropObject),
icon: Trash2,
shortcut: shortcutDelete,
@@ -3159,9 +2878,7 @@ function treeItemMenuItems(): ContextMenuItem[] {
// 9. Group Labels (group-columns, group-tables, etc.)
if (isGroupLabel(node)) {
- const hasGroupCreateAction =
- (node.type === "group-tables" && canCreateTable.value) ||
- (node.type === "group-views" && !!node.connectionId && !!node.database);
+ const hasGroupCreateAction = (node.type === "group-tables" && canCreateTable.value) || (node.type === "group-views" && !!node.connectionId && !!node.database);
if (node.type === "group-tables" && canCreateTable.value) {
items.push({ label: t("contextMenu.createTable"), action: createTable, icon: Plus });
}
@@ -3221,39 +2938,18 @@ function treeItemMenuItems(): ContextMenuItem[] {
@mousemove="isDropTarget ? updateTarget($event, node.id, node.type) : undefined"
@mouseleave="clearTarget(node.id)"
>
- <div
- v-if="showDropBefore"
- class="absolute right-2 top-0 h-0.5 bg-primary rounded-full pointer-events-none"
- :style="{ left: paddingLeft }"
- />
- <div
- v-if="showDropAfter"
- class="absolute right-2 bottom-0 h-0.5 bg-primary rounded-full pointer-events-none"
- :style="{ left: paddingLeft }"
- />
+ <div v-if="showDropBefore" class="absolute right-2 top-0 h-0.5 bg-primary rounded-full pointer-events-none" :style="{ left: paddingLeft }" />
+ <div v-if="showDropAfter" class="absolute right-2 bottom-0 h-0.5 bg-primary rounded-full pointer-events-none" :style="{ left: paddingLeft }" />
<template v-if="canExpand">
- <button
- type="button"
- class="-m-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground"
- @click.stop="toggle"
- >
+ <button type="button" class="-m-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground" @click.stop="toggle">
<Loader2 v-if="node.isLoading" class="w-3.5 h-3.5 animate-spin" />
<ChevronDown v-else-if="node.isExpanded" class="w-3.5 h-3.5" />
<ChevronRight v-else class="w-3.5 h-3.5" />
</button>
</template>
<span v-else class="w-3.5 h-3.5 shrink-0" />
- <DatabaseIcon
- v-if="node.type === 'connection'"
- :db-type="connectionIconType(node.connectionId)"
- class="w-3.5 h-3.5 shrink-0"
- />
- <component
- v-else
- :is="getIconInfo(node)?.icon || Database"
- class="w-3.5 h-3.5 shrink-0"
- :class="nodeIconClass"
- />
+ <DatabaseIcon v-if="node.type === 'connection'" :db-type="connectionIconType(node.connectionId)" class="w-3.5 h-3.5 shrink-0" />
+ <component v-else :is="getIconInfo(node)?.icon || Database" class="w-3.5 h-3.5 shrink-0" :class="nodeIconClass" />
<input
v-if="isRenamingGroup"
ref="renameInputRef"
@@ -3266,42 +2962,17 @@ function treeItemMenuItems(): ContextMenuItem[] {
/>
<span v-else ref="labelRef" :class="labelWidthClass">{{ visibleLabel(node) }}</span>
<span
- v-if="
- (node.type === 'group-tables' ||
- node.type === 'group-views' ||
- node.type === 'group-procedures' ||
- node.type === 'group-functions' ||
- node.type === 'group-sequences' ||
- node.type === 'group-packages' ||
- node.type === 'group-partitions') &&
- node.objectCount != null
- "
+ v-if="(node.type === 'group-tables' || node.type === 'group-views' || node.type === 'group-procedures' || node.type === 'group-functions' || node.type === 'group-sequences' || node.type === 'group-packages' || node.type === 'group-partitions') && node.objectCount != null"
class="text-muted-foreground text-[10px] shrink-0"
>{{ node.objectCount }}</span
>
<Badge v-if="isNodeDefaultDatabase" variant="secondary" class="h-4 px-1.5 text-[10px]">
{{ t("editor.defaultDatabase") }}
</Badge>
- <span v-if="columnComment" class="truncate text-muted-foreground/60 text-[10px] max-w-[40%]">{{
- columnComment
- }}</span>
- <span
- v-if="tableComment && !settingsStore.editorSettings.sidebarHideTableComments"
- class="truncate text-muted-foreground/60 text-[10px] max-w-[25%] group-hover:hidden"
- :title="tableComment"
- >{{ tableComment }}</span
- >
- <span
- v-if="
- node.type === 'connection' && node.connectionId && connectionStore.connectedIds.has(node.connectionId)
- "
- class="w-1.5 h-1.5 rounded-full bg-green-500 shrink-0"
- />
- <ConnectionErrorIndicator
- v-if="node.type === 'connection'"
- :connection-id="node.connectionId"
- trigger-class="h-4 w-4"
- />
+ <span v-if="columnComment" class="truncate text-muted-foreground/60 text-[10px] max-w-[40%]">{{ columnComment }}</span>
+ <span v-if="tableComment && !settingsStore.editorSettings.sidebarHideTableComments" class="truncate text-muted-foreground/60 text-[10px] max-w-[25%] group-hover:hidden" :title="tableComment">{{ tableComment }}</span>
+ <span v-if="node.type === 'connection' && node.connectionId && connectionStore.connectedIds.has(node.connectionId)" class="w-1.5 h-1.5 rounded-full bg-green-500 shrink-0" />
+ <ConnectionErrorIndicator v-if="node.type === 'connection'" :connection-id="node.connectionId" trigger-class="h-4 w-4" />
<button
v-if="canPin"
class="rounded p-0.5 text-muted-foreground hover:bg-muted-foreground/15 hover:text-foreground focus:opacity-100"
@@ -3315,12 +2986,7 @@ function treeItemMenuItems(): ContextMenuItem[] {
</LightTooltip>
</div>
</CustomContextMenu>
- <VisibleDatabasesDialog
- v-if="node.type === 'connection' && node.connectionId"
- v-model:open="showVisibleDatabasesDialog"
- :connection-id="node.connectionId"
- :connection-name="node.label"
- />
+ <VisibleDatabasesDialog v-if="node.type === 'connection' && node.connectionId" v-model:open="showVisibleDatabasesDialog" :connection-id="node.connectionId" :connection-name="node.label" />
<Dialog v-model:open="showDeleteConfirm">
<DialogContent class="sm:max-w-[400px]">
@@ -3349,16 +3015,10 @@ function treeItemMenuItems(): ContextMenuItem[] {
<DialogHeader>
<DialogTitle>{{ t("connectionGroup.createGroup") }}</DialogTitle>
</DialogHeader>
- <Input
- v-model="moveToNewGroupName"
- :placeholder="t('connectionGroup.groupNamePlaceholder')"
- @keydown.enter.prevent="confirmMoveToNewGroup"
- />
+ <Input v-model="moveToNewGroupName" :placeholder="t('connectionGroup.groupNamePlaceholder')" @keydown.enter.prevent="confirmMoveToNewGroup" />
<DialogFooter>
<Button variant="outline" @click="showMoveToNewGroupDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button :disabled="!moveToNewGroupName.trim()" @click="confirmMoveToNewGroup">{{
- t("connectionGroup.createGroup")
- }}</Button>
+ <Button :disabled="!moveToNewGroupName.trim()" @click="confirmMoveToNewGroup">{{ t("connectionGroup.createGroup") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -3384,24 +3044,13 @@ function treeItemMenuItems(): ContextMenuItem[] {
<DialogTitle>{{ t("contextMenu.renameObjectTitle") }}</DialogTitle>
</DialogHeader>
<div class="grid gap-3">
- <Input
- v-model="renameObjectName"
- :placeholder="t('contextMenu.renameObjectNamePlaceholder')"
- @keydown.enter.prevent="confirmRenameObject"
- />
- <pre
- v-if="renameObjectPreviewSql"
- class="max-h-32 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap"
- v-html="highlight(renameObjectPreviewSql)"
- ></pre>
+ <Input v-model="renameObjectName" :placeholder="t('contextMenu.renameObjectNamePlaceholder')" @keydown.enter.prevent="confirmRenameObject" />
+ <pre v-if="renameObjectPreviewSql" class="max-h-32 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap" v-html="highlight(renameObjectPreviewSql)"></pre>
<p v-if="renameObjectError" class="text-sm text-destructive">{{ renameObjectError }}</p>
</div>
<DialogFooter>
<Button variant="outline" @click="showRenameObjectDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button
- :disabled="!renameObjectName.trim() || renameObjectName.trim() === node.label"
- @click="confirmRenameObject"
- >
+ <Button :disabled="!renameObjectName.trim() || renameObjectName.trim() === node.label" @click="confirmRenameObject">
{{ t("contextMenu.renameObject") }}
</Button>
</DialogFooter>
@@ -3419,19 +3068,11 @@ function treeItemMenuItems(): ContextMenuItem[] {
<span>{{ t("contextMenu.exportStructureLoading") }}</span>
</div>
<p v-else-if="structurePreviewError" class="text-sm text-destructive">{{ structurePreviewError }}</p>
- <pre
- v-else
- class="max-h-[56vh] min-h-64 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap"
- v-html="highlight(structurePreviewSql)"
- ></pre>
+ <pre v-else class="max-h-[56vh] min-h-64 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap" v-html="highlight(structurePreviewSql)"></pre>
</div>
<DialogFooter>
<Button variant="outline" @click="showStructurePreviewDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button
- variant="outline"
- :disabled="isLoadingStructurePreview || !structurePreviewSql"
- @click="copyStructurePreview"
- >
+ <Button variant="outline" :disabled="isLoadingStructurePreview || !structurePreviewSql" @click="copyStructurePreview">
<Clipboard class="h-4 w-4" />
{{ t("contextMenu.copyStructure") }}
</Button>
@@ -3450,12 +3091,7 @@ function treeItemMenuItems(): ContextMenuItem[] {
</DialogHeader>
<div class="grid gap-3">
<p class="text-sm text-muted-foreground">{{ t("contextMenu.structureDocCopyFallbackHint") }}</p>
- <textarea
- readonly
- class="max-h-[56vh] min-h-64 resize-y overflow-auto rounded bg-muted p-3 font-mono text-xs whitespace-pre"
- :value="structureDocCopyText"
- @focus="selectTextareaContent"
- ></textarea>
+ <textarea readonly class="max-h-[56vh] min-h-64 resize-y overflow-auto rounded bg-muted p-3 font-mono text-xs whitespace-pre" :value="structureDocCopyText" @focus="selectTextareaContent"></textarea>
</div>
<DialogFooter>
<Button variant="outline" @click="showStructureDocCopyDialog = false">{{ t("dangerDialog.cancel") }}</Button>
@@ -3467,23 +3103,9 @@ function treeItemMenuItems(): ContextMenuItem[] {
</DialogContent>
</Dialog>
- <DangerConfirmDialog
- v-model:open="showDropTableConfirm"
- :title="t('contextMenu.confirmDropTableTitle')"
- :message="t('contextMenu.confirmDropTableMessage', { name: node.label })"
- :sql="dropTablePreviewSql"
- :confirm-label="t('contextMenu.dropTable')"
- @confirm="confirmDropTable"
- />
+ <DangerConfirmDialog v-model:open="showDropTableConfirm" :title="t('contextMenu.confirmDropTableTitle')" :message="t('contextMenu.confirmDropTableMessage', { name: node.label })" :sql="dropTablePreviewSql" :confirm-label="t('contextMenu.dropTable')" @confirm="confirmDropTable" />
- <DangerConfirmDialog
- v-model:open="showEmptyTableConfirm"
- :title="t('contextMenu.confirmEmptyTableTitle')"
- :message="t('contextMenu.confirmEmptyTableMessage', { name: node.label })"
- :sql="emptyTablePreviewSql"
- :confirm-label="t('contextMenu.emptyTable')"
- @confirm="confirmEmptyTable"
- />
+ <DangerConfirmDialog v-model:open="showEmptyTableConfirm" :title="t('contextMenu.confirmEmptyTableTitle')" :message="t('contextMenu.confirmEmptyTableMessage', { name: node.label })" :sql="emptyTablePreviewSql" :confirm-label="t('contextMenu.emptyTable')" @confirm="confirmEmptyTable" />
<DangerConfirmDialog
v-model:open="showTruncateTableConfirm"
@@ -3494,32 +3116,11 @@ function treeItemMenuItems(): ContextMenuItem[] {
@confirm="confirmTruncateTable"
/>
- <DangerConfirmDialog
- v-model:open="showDropObjectConfirm"
- :title="dropObjectConfirmTitle()"
- :message="dropObjectConfirmMessage()"
- :sql="dropObjectPreviewSql"
- :confirm-label="dropObjectMenuLabel()"
- @confirm="confirmDropObject"
- />
+ <DangerConfirmDialog v-model:open="showDropObjectConfirm" :title="dropObjectConfirmTitle()" :message="dropObjectConfirmMessage()" :sql="dropObjectPreviewSql" :confirm-label="dropObjectMenuLabel()" @confirm="confirmDropObject" />
- <DangerConfirmDialog
- v-model:open="showDropTableChildObjectConfirm"
- :title="dropTableChildObjectConfirmTitle()"
- :message="dropTableChildObjectConfirmMessage()"
- :sql="dropTableChildObjectPreviewSql"
- :confirm-label="dropTableChildObjectMenuLabel()"
- @confirm="confirmDropTableChildObject"
- />
+ <DangerConfirmDialog v-model:open="showDropTableChildObjectConfirm" :title="dropTableChildObjectConfirmTitle()" :message="dropTableChildObjectConfirmMessage()" :sql="dropTableChildObjectPreviewSql" :confirm-label="dropTableChildObjectMenuLabel()" @confirm="confirmDropTableChildObject" />
- <DangerConfirmDialog
- v-model:open="showBatchDropConfirm"
- :title="batchDropConfirmTitle()"
- :message="batchDropConfirmMessage()"
- :sql="batchDropPreviewSql"
- :confirm-label="batchDropMenuLabel()"
- @confirm="confirmBatchDrop"
- />
+ <DangerConfirmDialog v-model:open="showBatchDropConfirm" :title="batchDropConfirmTitle()" :message="batchDropConfirmMessage()" :sql="batchDropPreviewSql" :confirm-label="batchDropMenuLabel()" @confirm="confirmBatchDrop" />
<ProcedureExecutionDialog
v-if="node.type === 'procedure' && node.connectionId && node.database"
@@ -3538,16 +3139,10 @@ function treeItemMenuItems(): ContextMenuItem[] {
<DialogHeader>
<DialogTitle>{{ t("contextMenu.duplicateNameTitle") }}</DialogTitle>
</DialogHeader>
- <Input
- v-model="duplicateTableName"
- :placeholder="t('contextMenu.duplicateNamePlaceholder')"
- @keydown.enter.prevent="confirmDuplicateStructure"
- />
+ <Input v-model="duplicateTableName" :placeholder="t('contextMenu.duplicateNamePlaceholder')" @keydown.enter.prevent="confirmDuplicateStructure" />
<DialogFooter>
<Button variant="outline" @click="showDuplicateDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button :disabled="!duplicateTableName.trim()" @click="confirmDuplicateStructure">{{
- t("dangerDialog.confirm")
- }}</Button>
+ <Button :disabled="!duplicateTableName.trim()" @click="confirmDuplicateStructure">{{ t("dangerDialog.confirm") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -3557,85 +3152,42 @@ function treeItemMenuItems(): ContextMenuItem[] {
<DialogHeader>
<DialogTitle>{{ t("contextMenu.createDatabase") }}</DialogTitle>
</DialogHeader>
- <Input
- v-model="createDatabaseName"
- :placeholder="t('contextMenu.createDatabaseNamePlaceholder')"
- @keydown.enter.prevent="confirmCreateDatabase"
- />
+ <Input v-model="createDatabaseName" :placeholder="t('contextMenu.createDatabaseNamePlaceholder')" @keydown.enter.prevent="confirmCreateDatabase" />
<div v-if="canSetCreateDatabaseCharset" class="grid gap-2">
<div class="grid gap-1.5">
<label class="text-xs font-medium text-muted-foreground">{{ t("contextMenu.createDatabaseCharset") }}</label>
- <Input
- v-model="createDatabaseCharset"
- :placeholder="t('contextMenu.createDatabaseCharsetPlaceholder')"
- @keydown.enter.prevent="confirmCreateDatabase"
- />
+ <Input v-model="createDatabaseCharset" :placeholder="t('contextMenu.createDatabaseCharsetPlaceholder')" @keydown.enter.prevent="confirmCreateDatabase" />
</div>
<div class="grid gap-1.5">
- <label class="text-xs font-medium text-muted-foreground">{{
- t("contextMenu.createDatabaseCollation")
- }}</label>
- <Input
- v-model="createDatabaseCollation"
- :placeholder="t('contextMenu.createDatabaseCollationPlaceholder')"
- @keydown.enter.prevent="confirmCreateDatabase"
- />
+ <label class="text-xs font-medium text-muted-foreground">{{ t("contextMenu.createDatabaseCollation") }}</label>
+ <Input v-model="createDatabaseCollation" :placeholder="t('contextMenu.createDatabaseCollationPlaceholder')" @keydown.enter.prevent="confirmCreateDatabase" />
</div>
</div>
<DialogFooter>
<Button variant="outline" @click="showCreateDatabaseDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button :disabled="!createDatabaseName.trim()" @click="confirmCreateDatabase">{{
- t("dangerDialog.confirm")
- }}</Button>
+ <Button :disabled="!createDatabaseName.trim()" @click="confirmCreateDatabase">{{ t("dangerDialog.confirm") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
- <DangerConfirmDialog
- v-model:open="showDropDatabaseConfirm"
- :title="t('contextMenu.confirmDropDatabaseTitle')"
- :message="t('contextMenu.confirmDropDatabaseMessage', { name: node.label })"
- :sql="dropDatabasePreviewSql"
- :confirm-label="t('contextMenu.dropDatabase')"
- @confirm="confirmDropDatabase"
- />
+ <DangerConfirmDialog v-model:open="showDropDatabaseConfirm" :title="t('contextMenu.confirmDropDatabaseTitle')" :message="t('contextMenu.confirmDropDatabaseMessage', { name: node.label })" :sql="dropDatabasePreviewSql" :confirm-label="t('contextMenu.dropDatabase')" @confirm="confirmDropDatabase" />
- <DangerConfirmDialog
- v-model:open="showFlushRedisDbConfirm"
- :title="t('redis.flushDb')"
- :message="t('redis.flushDbMessage')"
- :details="t('redis.flushDbDetails', { db: node.database })"
- :confirm-label="t('redis.flushDbConfirm')"
- @confirm="confirmFlushRedisDb"
- />
+ <DangerConfirmDialog v-model:open="showFlushRedisDbConfirm" :title="t('redis.flushDb')" :message="t('redis.flushDbMessage')" :details="t('redis.flushDbDetails', { db: node.database })" :confirm-label="t('redis.flushDbConfirm')" @confirm="confirmFlushRedisDb" />
<Dialog v-model:open="showCreateSchemaDialog">
<DialogContent class="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>{{ t("contextMenu.createSchema") }}</DialogTitle>
</DialogHeader>
- <Input
- v-model="createSchemaName"
- :placeholder="t('contextMenu.createSchemaNamePlaceholder')"
- @keydown.enter.prevent="confirmCreateSchema"
- />
+ <Input v-model="createSchemaName" :placeholder="t('contextMenu.createSchemaNamePlaceholder')" @keydown.enter.prevent="confirmCreateSchema" />
<DialogFooter>
<Button variant="outline" @click="showCreateSchemaDialog = false">{{ t("dangerDialog.cancel") }}</Button>
- <Button :disabled="!createSchemaName.trim()" @click="confirmCreateSchema">{{
- t("dangerDialog.confirm")
- }}</Button>
+ <Button :disabled="!createSchemaName.trim()" @click="confirmCreateSchema">{{ t("dangerDialog.confirm") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
- <DangerConfirmDialog
- v-model:open="showDropSchemaConfirm"
- :title="t('contextMenu.confirmDropSchemaTitle')"
- :message="t('contextMenu.confirmDropSchemaMessage', { name: node.label })"
- :sql="dropSchemaPreviewSql"
- :confirm-label="t('contextMenu.dropSchema')"
- @confirm="confirmDropSchema"
- />
+ <DangerConfirmDialog v-model:open="showDropSchemaConfirm" :title="t('contextMenu.confirmDropSchemaTitle')" :message="t('contextMenu.confirmDropSchemaMessage', { name: node.label })" :sql="dropSchemaPreviewSql" :confirm-label="t('contextMenu.dropSchema')" @confirm="confirmDropSchema" />
</template>
<style>
diff --git a/apps/desktop/src/components/sidebar/VisibleDatabasesDialog.vue b/apps/desktop/src/components/sidebar/VisibleDatabasesDialog.vue
index 72e4daef3f..988c400bb7 100644
--- a/apps/desktop/src/components/sidebar/VisibleDatabasesDialog.vue
+++ b/apps/desktop/src/components/sidebar/VisibleDatabasesDialog.vue
@@ -6,12 +6,7 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { useConnectionStore } from "@/stores/connectionStore";
-import {
- canSaveVisibleDatabaseSelection,
- filterDatabaseNamesForConnection,
- isSystemDatabaseName,
- normalizeVisibleDatabaseSelection,
-} from "@/lib/visibleDatabases";
+import { canSaveVisibleDatabaseSelection, filterDatabaseNamesForConnection, isSystemDatabaseName, normalizeVisibleDatabaseSelection } from "@/lib/visibleDatabases";
import * as api from "@/lib/api";
const props = defineProps<{
@@ -47,9 +42,7 @@ const filteredDatabaseNames = computed(() => {
const selectedCount = computed(() => selectedNames.value.size);
const totalCount = computed(() => listedDatabaseNames.value.length);
const canSaveSelection = computed(() => canSaveVisibleDatabaseSelection([...selectedNames.value]));
-const hasSystemDatabases = computed(() =>
- databaseNames.value.some((database) => isSystemDatabaseName(connection.value?.db_type, database)),
-);
+const hasSystemDatabases = computed(() => databaseNames.value.some((database) => isSystemDatabaseName(connection.value?.db_type, database)));
watch(
() => props.open,
@@ -61,9 +54,7 @@ watch(
watch(showSystemDatabases, (show) => {
if (show) return;
- selectedNames.value = new Set(
- [...selectedNames.value].filter((database) => !isSystemDatabaseName(connection.value?.db_type, database)),
- );
+ selectedNames.value = new Set([...selectedNames.value].filter((database) => !isSystemDatabaseName(connection.value?.db_type, database)));
});
async function loadDatabases() {
@@ -74,13 +65,9 @@ async function loadDatabases() {
const names = await loadDatabaseNames();
databaseNames.value = names;
const configured = connection.value?.visible_databases;
- const initialSelection = Array.isArray(configured)
- ? normalizeVisibleDatabaseSelection(configured, names)
- : filterDatabaseNamesForConnection(names, connection.value);
+ const initialSelection = Array.isArray(configured) ? normalizeVisibleDatabaseSelection(configured, names) : filterDatabaseNamesForConnection(names, connection.value);
selectedNames.value = new Set(initialSelection);
- showSystemDatabases.value = initialSelection.some((database) =>
- isSystemDatabaseName(connection.value?.db_type, database),
- );
+ showSystemDatabases.value = initialSelection.some((database) => isSystemDatabaseName(connection.value?.db_type, database));
} catch (e: any) {
databaseNames.value = [];
selectedNames.value = new Set();
@@ -146,12 +133,7 @@ async function saveSelection() {
<div class="flex items-center gap-2 rounded-md border bg-background px-2">
<Search class="h-4 w-4 shrink-0 text-muted-foreground" />
- <Input
- v-model="searchText"
- :placeholder="t('visibleDatabases.searchPlaceholder')"
- class="h-8 border-0 px-0 shadow-none focus-visible:ring-0"
- :disabled="isLoading || !!errorMessage"
- />
+ <Input v-model="searchText" :placeholder="t('visibleDatabases.searchPlaceholder')" class="h-8 border-0 px-0 shadow-none focus-visible:ring-0" :disabled="isLoading || !!errorMessage" />
</div>
<div class="flex items-center justify-between text-xs text-muted-foreground">
@@ -163,11 +145,7 @@ async function saveSelection() {
<button class="hover:text-foreground disabled:opacity-50" :disabled="isLoading" @click="clearSelection">
{{ t("visibleDatabases.clear") }}
</button>
- <button
- class="hover:text-foreground disabled:opacity-50"
- :disabled="isLoading || !Array.isArray(connection?.visible_databases)"
- @click="showAllDatabases"
- >
+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoading || !Array.isArray(connection?.visible_databases)" @click="showAllDatabases">
{{ t("visibleDatabases.showAll") }}
</button>
</div>
@@ -176,16 +154,8 @@ async function saveSelection() {
{{ t("visibleDatabases.emptySelection") }}
</p>
- <label
- v-if="hasSystemDatabases"
- class="flex h-8 items-center gap-2 rounded-md px-1 text-xs text-muted-foreground"
- >
- <input
- v-model="showSystemDatabases"
- type="checkbox"
- class="h-3.5 w-3.5 accent-primary"
- :disabled="isLoading || !!errorMessage"
- />
+ <label v-if="hasSystemDatabases" class="flex h-8 items-center gap-2 rounded-md px-1 text-xs text-muted-foreground">
+ <input v-model="showSystemDatabases" type="checkbox" class="h-3.5 w-3.5 accent-primary" :disabled="isLoading || !!errorMessage" />
<span>{{ t("visibleDatabases.showSystemDatabases") }}</span>
</label>
diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
index 4ee64d6967..a5755eb4d2 100644
--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
@@ -13,16 +13,7 @@ import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import { useToast } from "@/composables/useToast";
import { useConnectionStore } from "@/stores/connectionStore";
import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions";
-import {
- cancelSqlFileExecution,
- executeSqlFile,
- listenSqlFileProgress,
- listDatabases,
- previewSqlFile,
- type SqlFilePreview,
- type SqlFileProgress,
- type SqlFileStatus,
-} from "@/lib/api";
+import { cancelSqlFileExecution, executeSqlFile, listenSqlFileProgress, listDatabases, previewSqlFile, type SqlFilePreview, type SqlFileProgress, type SqlFileStatus } from "@/lib/api";
import { Check, CheckSquare, FileCode, FolderOpen, Loader2, Play, Square, X } from "@lucide/vue";
const { t } = useI18n();
@@ -58,22 +49,11 @@ const terminalStatus = ref<SqlFileStatus | "idle">("idle");
const terminalError = ref("");
const refreshedTarget = ref(false);
-const sqlConnections = computed(() =>
- store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)),
-);
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)));
const selectedConnection = computed(() => sqlConnections.value.find((c) => c.id === connectionId.value));
-const canStart = computed(() =>
- Boolean(
- preview.value &&
- selectedConnection.value &&
- database.value.trim() &&
- !running.value &&
- !loadingPreview.value &&
- !loadingDatabases.value,
- ),
-);
+const canStart = computed(() => Boolean(preview.value && selectedConnection.value && database.value.trim() && !running.value && !loadingPreview.value && !loadingDatabases.value));
const statusTone = computed(() => {
if (terminalStatus.value === "done") return "text-green-600";
@@ -104,11 +84,7 @@ const previewIsTruncated = computed(() => {
if (!preview.value) return false;
return preview.value.sizeBytes > preview.value.preview.length;
});
-const previewLineSummary = computed(() =>
- previewIsTruncated.value
- ? t("sqlFile.previewingFirstLines", { count: previewLineCount.value })
- : t("sqlFile.previewingLines", { count: previewLineCount.value }),
-);
+const previewLineSummary = computed(() => (previewIsTruncated.value ? t("sqlFile.previewingFirstLines", { count: previewLineCount.value }) : t("sqlFile.previewingLines", { count: previewLineCount.value })));
function connectionIconType(id: string) {
const config = store.getConfig(id);
@@ -424,19 +400,8 @@ watch(
<div class="flex items-center gap-2">
<input ref="fileInput" type="file" accept=".sql,text/sql" class="hidden" @change="handleFileInputChange" />
- <Input
- :model-value="filePath"
- readonly
- class="h-8 text-xs font-mono"
- :placeholder="t('sqlFile.selectSqlFile')"
- />
- <Button
- variant="outline"
- size="sm"
- class="h-8 shrink-0"
- :disabled="running || selectingFile"
- @click="selectFile"
- >
+ <Input :model-value="filePath" readonly class="h-8 text-xs font-mono" :placeholder="t('sqlFile.selectSqlFile')" />
+ <Button variant="outline" size="sm" class="h-8 shrink-0" :disabled="running || selectingFile" @click="selectFile">
<Loader2 v-if="selectingFile || loadingPreview" class="w-3.5 h-3.5 mr-1.5 animate-spin" />
<FolderOpen v-else class="w-3.5 h-3.5 mr-1.5" />
{{ t("sqlFile.browse") }}
@@ -455,18 +420,11 @@ watch(
<span>{{ formatBytes(preview.sizeBytes) }}</span>
</div>
</div>
- <div
- class="sql-file-preview-viewer flex min-h-56 max-h-[min(42vh,360px)] max-w-full overflow-auto bg-muted/15 text-xs"
- >
- <div
- class="sticky left-0 z-10 select-none border-r bg-background/95 px-2 py-3 text-right font-mono leading-5 text-muted-foreground/70"
- >
+ <div class="sql-file-preview-viewer flex min-h-56 max-h-[min(42vh,360px)] max-w-full overflow-auto bg-muted/15 text-xs">
+ <div class="sticky left-0 z-10 select-none border-r bg-background/95 px-2 py-3 text-right font-mono leading-5 text-muted-foreground/70">
<div v-for="lineNumber in previewLineNumbers" :key="lineNumber">{{ lineNumber }}</div>
</div>
- <pre
- class="min-w-max flex-1 p-3 font-mono leading-5 whitespace-pre"
- v-html="highlight(preview.preview)"
- ></pre>
+ <pre class="min-w-max flex-1 p-3 font-mono leading-5 whitespace-pre" v-html="highlight(preview.preview)"></pre>
</div>
</div>
</div>
@@ -509,16 +467,8 @@ watch(
</SelectContent>
</Select>
<div v-else class="relative">
- <Input
- v-model="database"
- class="h-8 text-xs"
- :disabled="running || loadingDatabases"
- :placeholder="t('sqlFile.databasePlaceholder')"
- />
- <Loader2
- v-if="loadingDatabases"
- class="absolute right-2 top-2 w-3.5 h-3.5 animate-spin text-muted-foreground"
- />
+ <Input v-model="database" class="h-8 text-xs" :disabled="running || loadingDatabases" :placeholder="t('sqlFile.databasePlaceholder')" />
+ <Loader2 v-if="loadingDatabases" class="absolute right-2 top-2 w-3.5 h-3.5 animate-spin text-muted-foreground" />
</div>
</div>
</div>
@@ -529,12 +479,7 @@ watch(
{{ t("sqlFile.options") }}
</div>
- <button
- type="button"
- class="flex items-center gap-2 text-xs text-left"
- :disabled="running"
- @click="continueOnError = !continueOnError"
- >
+ <button type="button" class="flex items-center gap-2 text-xs text-left" :disabled="running" @click="continueOnError = !continueOnError">
<CheckSquare v-if="continueOnError" class="w-3.5 h-3.5 text-primary shrink-0" />
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
{{ t("sqlFile.continueOnError") }}
@@ -555,17 +500,7 @@ watch(
</div>
<div class="w-full bg-muted rounded-full h-2 overflow-hidden">
- <div
- class="h-full rounded-full transition-all duration-300"
- :class="
- terminalStatus === 'error'
- ? 'bg-destructive'
- : terminalStatus === 'cancelled'
- ? 'bg-yellow-500'
- : 'bg-primary'
- "
- :style="{ width: `${progressPercent}%` }"
- />
+ <div class="h-full rounded-full transition-all duration-300" :class="terminalStatus === 'error' ? 'bg-destructive' : terminalStatus === 'cancelled' ? 'bg-yellow-500' : 'bg-primary'" :style="{ width: `${progressPercent}%` }" />
</div>
<div class="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
@@ -595,17 +530,12 @@ watch(
<div v-if="progress?.statementSummary" class="space-y-1">
<Label class="text-xs">{{ t("sqlFile.currentStatement") }}</Label>
- <div
- class="max-h-20 max-w-full overflow-auto rounded-md border bg-muted/15 p-2 text-xs font-mono whitespace-pre"
- >
+ <div class="max-h-20 max-w-full overflow-auto rounded-md border bg-muted/15 p-2 text-xs font-mono whitespace-pre">
{{ progress.statementSummary }}
</div>
</div>
- <div
- v-if="progress?.error || terminalError"
- class="max-w-full overflow-auto rounded-md border bg-destructive/5 p-2 text-xs text-destructive whitespace-pre-wrap"
- >
+ <div v-if="progress?.error || terminalError" class="max-w-full overflow-auto rounded-md border bg-destructive/5 p-2 text-xs text-destructive whitespace-pre-wrap">
{{ progress?.error || terminalError }}
</div>
</div>
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index b712d8f314..8ca80dfadf 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -6,30 +6,8 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import {
- AlertTriangle,
- Check,
- ChevronDown,
- ChevronUp,
- Copy,
- Database,
- Info,
- KeyRound,
- Loader2,
- Maximize2,
- Plus,
- RefreshCw,
- Save,
- SlidersHorizontal,
- Trash2,
- X,
-} from "@lucide/vue";
-import {
- DropdownMenu,
- DropdownMenuCheckboxItem,
- DropdownMenuContent,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+import { AlertTriangle, Check, ChevronDown, ChevronUp, Copy, Database, Info, KeyRound, Loader2, Maximize2, Plus, RefreshCw, Save, SlidersHorizontal, Trash2, X } from "@lucide/vue";
+import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { SearchableSelect } from "@/components/ui/searchable-select";
@@ -46,16 +24,7 @@ import { queryTimeoutSecsForConnection } from "@/lib/queryTimeout";
import { type EditableStructureColumn, type EditableStructureIndex } from "@/lib/tableStructureEditorSql";
import { getTableStructureCapabilities } from "@/lib/tableStructureCapabilities";
import { connectionObjectTreeQuerySchema, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
-import {
- buildStructureTargetLabel,
- combineDataTypeForDatabase,
- createColumnDrafts,
- createIndexDrafts,
- getDataTypeOptions,
- getDefaultLengthForType,
- splitDataType,
- toColumnNames,
-} from "@/lib/tableStructureEditorState";
+import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, getDataTypeOptions, getDefaultLengthForType, splitDataType, toColumnNames } from "@/lib/tableStructureEditorState";
import type { ForeignKeyInfo, TriggerInfo } from "@/types/database";
import * as api from "@/lib/api";
@@ -229,16 +198,13 @@ const structureDensityStyle = computed(() => {
"--structure-line-height": String(metric.lineHeight),
};
});
-const structureControlClass =
- "h-[var(--structure-control-height)] min-w-0 px-[var(--structure-control-px)] py-0 text-[length:var(--structure-font-size)]";
+const structureControlClass = "h-[var(--structure-control-height)] min-w-0 px-[var(--structure-control-px)] py-0 text-[length:var(--structure-font-size)]";
const structureMonoControlClass = `${structureControlClass} font-mono`;
-const structureToolbarButtonClass =
- "h-[var(--structure-control-height)] gap-1 px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]";
+const structureToolbarButtonClass = "h-[var(--structure-control-height)] gap-1 px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]";
const structureIconButtonClass = "h-[var(--structure-control-height)] w-[var(--structure-control-height)]";
const structureIconClass = "h-[var(--structure-icon-size)] w-[var(--structure-icon-size)]";
const structureCheckboxClass = "h-[var(--structure-checkbox-size)] w-[var(--structure-checkbox-size)]";
-const structureHeaderCellClass =
- "relative border-b border-r px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-left";
+const structureHeaderCellClass = "relative border-b border-r px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-left";
const structureCellClass = "border-b border-r px-[var(--structure-cell-px)] py-[var(--structure-cell-py)]";
const structureLastCellClass = "border-b px-[var(--structure-cell-px)] py-[var(--structure-cell-py)]";
@@ -288,10 +254,7 @@ function onIndexColResize(e: MouseEvent, col: number) {
const onMove = (ev: MouseEvent) => {
if (!resizing.value) return;
const delta = ev.clientX - resizing.value.startX;
- indexColWidths.value[col] = Math.max(
- structureDensityMetric.value.minIndexColumnWidth,
- resizing.value.startW + delta,
- );
+ indexColWidths.value[col] = Math.max(structureDensityMetric.value.minIndexColumnWidth, resizing.value.startW + delta);
};
const onUp = () => {
resizing.value = null;
@@ -316,20 +279,10 @@ const indexTypesByDb: Record<string, string[]> = {
oracle: ["NORMAL", "BITMAP", "FUNCTION-BASED NORMAL", "FUNCTION-BASED DOMAIN", "DOMAIN", "CLUSTER"],
sqlite: ["BTREE"],
};
-const indexTypeOptions = computed(() =>
- structureCapabilities.value.indexType ? (indexTypesByDb[structureDialect.value] ?? []) : [],
-);
+const indexTypeOptions = computed(() => (structureCapabilities.value.indexType ? (indexTypesByDb[structureDialect.value] ?? []) : []));
function isPostgresIdentityType(dbType: string | undefined): boolean {
- return (
- dbType === "postgres" ||
- dbType === "gaussdb" ||
- dbType === "kwdb" ||
- dbType === "opengauss" ||
- dbType === "highgo" ||
- dbType === "vastbase" ||
- dbType === "kingbase"
- );
+ return dbType === "postgres" || dbType === "gaussdb" || dbType === "kwdb" || dbType === "opengauss" || dbType === "highgo" || dbType === "vastbase" || dbType === "kingbase";
}
const showExtendedProperties = computed(() => {
@@ -337,63 +290,28 @@ const showExtendedProperties = computed(() => {
return dt === "mysql" || isPostgresIdentityType(dt) || dt === "sqlserver";
});
const extendedPropertiesColumnIndex = 8;
-const visibleColWidths = computed(() =>
- showExtendedProperties.value
- ? colWidths.value
- : colWidths.value.filter((_, index) => index !== extendedPropertiesColumnIndex),
-);
+const visibleColWidths = computed(() => (showExtendedProperties.value ? colWidths.value : colWidths.value.filter((_, index) => index !== extendedPropertiesColumnIndex)));
function columnWidthIndex(visibleIndex: number) {
- return !showExtendedProperties.value && visibleIndex >= extendedPropertiesColumnIndex
- ? visibleIndex + 1
- : visibleIndex;
+ return !showExtendedProperties.value && visibleIndex >= extendedPropertiesColumnIndex ? visibleIndex + 1 : visibleIndex;
}
const colLabels = computed(() => {
- const labels = [
- "#",
- t("structureEditor.columnName"),
- t("structureEditor.dataType"),
- t("structureEditor.length"),
- t("structureEditor.nullable"),
- t("structureEditor.primaryKey"),
- t("structureEditor.defaultValue"),
- t("structureEditor.comment"),
- ];
+ const labels = ["#", t("structureEditor.columnName"), t("structureEditor.dataType"), t("structureEditor.length"), t("structureEditor.nullable"), t("structureEditor.primaryKey"), t("structureEditor.defaultValue"), t("structureEditor.comment")];
if (showExtendedProperties.value) {
labels.push(t("structureEditor.extendedProperties"));
}
labels.push(t("structureEditor.actions"));
return labels;
});
-const indexColLabels = computed(() => [
- t("structureEditor.indexName"),
- t("structureEditor.indexColumns"),
- t("structureEditor.unique"),
- t("structureEditor.indexType"),
- t("structureEditor.includedColumns"),
- t("structureEditor.filter"),
- t("structureEditor.comment"),
- t("structureEditor.actions"),
-]);
+const indexColLabels = computed(() => [t("structureEditor.indexName"), t("structureEditor.indexColumns"), t("structureEditor.unique"), t("structureEditor.indexType"), t("structureEditor.includedColumns"), t("structureEditor.filter"), t("structureEditor.comment"), t("structureEditor.actions")]);
const metadataSchema = computed(() => connectionObjectTreeQuerySchema(connection.value, props.database, props.schema));
-const refreshVersion = computed(() =>
- props.connectionId && props.tableName
- ? queryStore.tableStructureRefreshVersion(props.connectionId, props.database, props.schema, props.tableName)
- : 0,
-);
+const refreshVersion = computed(() => (props.connectionId && props.tableName ? queryStore.tableStructureRefreshVersion(props.connectionId, props.database, props.schema, props.tableName) : 0));
const isCreateMode = computed(() => !props.tableName);
const newTableName = ref("");
const tableComment = ref("");
const originalTableComment = ref("");
-const targetLabel = computed(() =>
- buildStructureTargetLabel(
- connection.value?.name,
- props.database,
- props.schema,
- isCreateMode.value ? undefined : props.tableName,
- ),
-);
+const targetLabel = computed(() => buildStructureTargetLabel(connection.value?.name, props.database, props.schema, isCreateMode.value ? undefined : props.tableName));
let sqlPreviewRequestId = 0;
let keydownListenerRegistered = false;
@@ -411,9 +329,7 @@ async function refreshSqlPreview() {
originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,
};
try {
- const result = isCreateMode.value
- ? await api.buildCreateTableSql(options)
- : await api.buildTableStructureChangeSql(options);
+ const result = isCreateMode.value ? await api.buildCreateTableSql(options) : await api.buildTableStructureChangeSql(options);
if (requestId !== sqlPreviewRequestId) return;
pendingStatements.value = result.statements;
warnings.value = result.warnings;
@@ -426,16 +342,7 @@ async function refreshSqlPreview() {
}
}
-const canApply = computed(
- () =>
- !loading.value &&
- !saving.value &&
- !sqlPreviewLoading.value &&
- pendingStatements.value.length > 0 &&
- warnings.value.length === 0 &&
- !!props.connectionId &&
- (isCreateMode.value ? !!newTableName.value.trim() : !!props.tableName),
-);
+const canApply = computed(() => !loading.value && !saving.value && !sqlPreviewLoading.value && pendingStatements.value.length > 0 && warnings.value.length === 0 && !!props.connectionId && (isCreateMode.value ? !!newTableName.value.trim() : !!props.tableName));
function resetState() {
activeTab.value = "columns";
@@ -474,9 +381,7 @@ async function loadStructure(silent = false) {
triggers.value = nextTriggers;
try {
const tables = await api.listTables(props.connectionId, props.database, metadataSchema.value);
- const table = tables.find(
- (t) => t.name.toLowerCase() === props.tableName!.toLowerCase() && t.table_type !== "VIEW",
- );
+ const table = tables.find((t) => t.name.toLowerCase() === props.tableName!.toLowerCase() && t.table_type !== "VIEW");
originalTableComment.value = table?.comment || "";
tableComment.value = table?.comment || "";
} catch {
@@ -547,9 +452,7 @@ function isColumnTypeDisabled(column: EditableStructureColumn): boolean {
}
function isColumnNullableDisabled(column: EditableStructureColumn): boolean {
- return (
- column.markedForDrop || column.isPrimaryKey || (!!column.original && !structureCapabilities.value.alterNullability)
- );
+ return column.markedForDrop || column.isPrimaryKey || (!!column.original && !structureCapabilities.value.alterNullability);
}
function isColumnDefaultDisabled(column: EditableStructureColumn): boolean {
@@ -634,11 +537,7 @@ function toggleDropIndex(index: EditableStructureIndex) {
function canEditIndexDraft(index: EditableStructureIndex): boolean {
if (index.markedForDrop || index.isPrimary) return false;
if (!index.original) return structureCapabilities.value.createIndex;
- return (
- structureCapabilities.value.rebuildIndex &&
- structureCapabilities.value.createIndex &&
- structureCapabilities.value.dropIndex
- );
+ return structureCapabilities.value.rebuildIndex && structureCapabilities.value.createIndex && structureCapabilities.value.dropIndex;
}
function canEditIndexFilter(index: EditableStructureIndex): boolean {
@@ -661,13 +560,7 @@ function primarySqlOperation(sql: string): string {
return statement?.match(/^([a-z]+)/i)?.[1]?.toUpperCase() || "SQL";
}
-async function recordStructureHistory(
- sql: string,
- start: number,
- success: boolean,
- result?: { affected_rows?: number },
- error?: string,
-) {
+async function recordStructureHistory(sql: string, start: number, success: boolean, result?: { affected_rows?: number }, error?: string) {
const connection = store.getConfig(props.connectionId);
try {
await historyStore.add({
@@ -707,13 +600,7 @@ async function applyChanges() {
try {
const connection = store.getConfig(props.connectionId);
const timeoutSecs = queryTimeoutSecsForConnection(connection);
- const result = await api.executeBatch(
- props.connectionId,
- props.database,
- pendingStatements.value,
- props.schema,
- timeoutSecs,
- );
+ const result = await api.executeBatch(props.connectionId, props.database, pendingStatements.value, props.schema, timeoutSecs);
await recordStructureHistory(sql, startedAt, true, result);
toast(t("structureEditor.saved"), 2500);
emit("saved", tableComment.value !== originalTableComment.value);
@@ -804,26 +691,12 @@ watch(activeTab, (tab) => {
</script>
<template>
- <div
- ref="rootRef"
- class="flex h-full min-h-0 flex-col gap-2 overflow-hidden p-[var(--structure-shell-padding)] text-[length:var(--structure-font-size)]"
- :data-structure-density="structureDensity"
- :style="structureDensityStyle"
- >
- <div
- class="flex shrink-0 items-center gap-2 rounded-md border bg-muted/20 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]"
- >
+ <div ref="rootRef" class="flex h-full min-h-0 flex-col gap-2 overflow-hidden p-[var(--structure-shell-padding)] text-[length:var(--structure-font-size)]" :data-structure-density="structureDensity" :style="structureDensityStyle">
+ <div class="flex shrink-0 items-center gap-2 rounded-md border bg-muted/20 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">
<Database :class="[structureIconClass, 'text-muted-foreground']" />
<span class="min-w-0 flex-1 truncate font-medium">{{ targetLabel || t("editor.noDatabase") }}</span>
<Badge variant="outline">{{ connection?.driver_label || databaseType }}</Badge>
- <Button
- v-if="!isCreateMode"
- variant="ghost"
- size="sm"
- :class="structureToolbarButtonClass"
- :disabled="loading || saving"
- @click="loadStructure()"
- >
+ <Button v-if="!isCreateMode" variant="ghost" size="sm" :class="structureToolbarButtonClass" :disabled="loading || saving" @click="loadStructure()">
<RefreshCw :class="structureIconClass" />
{{ t("structureEditor.refresh") }}
</Button>
@@ -831,21 +704,12 @@ watch(activeTab, (tab) => {
<div v-if="isCreateMode" class="flex shrink-0 items-center gap-2">
<label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.tableName") }}</label>
- <Input
- v-model="newTableName"
- :placeholder="t('contextMenu.duplicateNamePlaceholder')"
- :class="[structureControlClass, 'max-w-[220px]']"
- />
+ <Input v-model="newTableName" :placeholder="t('contextMenu.duplicateNamePlaceholder')" :class="[structureControlClass, 'max-w-[220px]']" />
</div>
<div class="flex shrink-0 items-center gap-2">
<label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.comment") }}</label>
- <Input
- v-model="tableComment"
- :placeholder="t('structureEditor.tableCommentPlaceholder')"
- :class="[structureControlClass, 'max-w-[320px]']"
- :disabled="isTableCommentDisabled"
- />
+ <Input v-model="tableComment" :placeholder="t('structureEditor.tableCommentPlaceholder')" :class="[structureControlClass, 'max-w-[320px]']" :disabled="isTableCommentDisabled" />
<Tooltip v-if="isTableCommentDisabled">
<TooltipTrigger as-child>
<Info :class="[structureIconClass, 'shrink-0 text-muted-foreground']" />
@@ -854,10 +718,7 @@ watch(activeTab, (tab) => {
</Tooltip>
</div>
- <div
- v-if="loading"
- class="flex min-h-0 flex-1 items-center justify-center gap-2 text-[length:var(--structure-font-size)] text-muted-foreground"
- >
+ <div v-if="loading" class="flex min-h-0 flex-1 items-center justify-center gap-2 text-[length:var(--structure-font-size)] text-muted-foreground">
<Loader2 class="h-4 w-4 animate-spin" />
{{ t("common.loading") }}
</div>
@@ -877,11 +738,7 @@ watch(activeTab, (tab) => {
<div class="flex items-center gap-1.5">
<SlidersHorizontal :class="[structureIconClass, 'text-muted-foreground']" />
<Select :model-value="structureDensity" @update:model-value="setStructureDensity">
- <SelectTrigger
- size="sm"
- class="h-[var(--structure-control-height)] w-[108px] rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]"
- :aria-label="t('structureEditor.density')"
- >
+ <SelectTrigger size="sm" class="h-[var(--structure-control-height)] w-[108px] rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]" :aria-label="t('structureEditor.density')">
<SelectValue :placeholder="t('structureEditor.density')" />
</SelectTrigger>
<SelectContent align="end" class="min-w-28">
@@ -891,23 +748,11 @@ watch(activeTab, (tab) => {
</SelectContent>
</Select>
</div>
- <Button
- v-if="activeTab === 'columns'"
- size="sm"
- :class="structureToolbarButtonClass"
- :disabled="!structureCapabilities.addColumn"
- @click="addColumn"
- >
+ <Button v-if="activeTab === 'columns'" size="sm" :class="structureToolbarButtonClass" :disabled="!structureCapabilities.addColumn" @click="addColumn">
<Plus :class="structureIconClass" />
{{ t("structureEditor.addColumn") }}
</Button>
- <Button
- v-if="activeTab === 'indexes'"
- size="sm"
- :class="structureToolbarButtonClass"
- :disabled="!structureCapabilities.createIndex"
- @click="addIndex"
- >
+ <Button v-if="activeTab === 'indexes'" size="sm" :class="structureToolbarButtonClass" :disabled="!structureCapabilities.createIndex" @click="addIndex">
<Plus :class="structureIconClass" />
{{ t("structureEditor.addIndex") }}
</Button>
@@ -915,35 +760,17 @@ watch(activeTab, (tab) => {
</div>
<TabsContent value="columns" class="m-0 min-h-0 flex-1 overflow-auto p-0">
- <table
- class="border-separate border-spacing-0 text-[length:var(--structure-font-size)] leading-[var(--structure-line-height)]"
- :style="{ minWidth: visibleColWidths.reduce((a, w) => a + w, 0) + 'px' }"
- >
+ <table class="border-separate border-spacing-0 text-[length:var(--structure-font-size)] leading-[var(--structure-line-height)]" :style="{ minWidth: visibleColWidths.reduce((a, w) => a + w, 0) + 'px' }">
<thead class="sticky top-0 z-10 bg-background">
<tr>
- <th
- v-for="(label, i) in colLabels"
- :key="i"
- :class="[structureHeaderCellClass, { 'text-center': i === 5 }]"
- :style="{ width: visibleColWidths[i] + 'px', minWidth: visibleColWidths[i] + 'px' }"
- >
+ <th v-for="(label, i) in colLabels" :key="i" :class="[structureHeaderCellClass, { 'text-center': i === 5 }]" :style="{ width: visibleColWidths[i] + 'px', minWidth: visibleColWidths[i] + 'px' }">
{{ label }}
- <div
- v-if="i < colLabels.length - 1"
- class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30"
- :class="colResizing?.col === columnWidthIndex(i) ? 'bg-primary/30' : ''"
- @mousedown="onColResize($event, i)"
- />
+ <div v-if="i < colLabels.length - 1" class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30" :class="colResizing?.col === columnWidthIndex(i) ? 'bg-primary/30' : ''" @mousedown="onColResize($event, i)" />
</th>
</tr>
</thead>
<tbody>
- <tr
- v-for="(column, index) in columns"
- :key="column.id"
- :class="column.markedForDrop ? 'bg-destructive/5 opacity-60' : ''"
- :data-new-column-row="!column.original ? 'true' : undefined"
- >
+ <tr v-for="(column, index) in columns" :key="column.id" :class="column.markedForDrop ? 'bg-destructive/5 opacity-60' : ''" :data-new-column-row="!column.original ? 'true' : undefined">
<td :class="[structureCellClass, 'text-muted-foreground']">
<div class="flex items-center gap-1">
<span>{{ index + 1 }}</span>
@@ -951,12 +778,7 @@ watch(activeTab, (tab) => {
</div>
</td>
<td :class="structureCellClass">
- <Input
- v-model="column.name"
- :class="structureControlClass"
- :disabled="isColumnNameDisabled(column)"
- data-column-name-input
- />
+ <Input v-model="column.name" :class="structureControlClass" :disabled="isColumnNameDisabled(column)" data-column-name-input />
</td>
<td :class="structureCellClass">
<SearchableSelect
@@ -969,44 +791,16 @@ watch(activeTab, (tab) => {
:loading-text="t('common.loading')"
:allow-custom="true"
:trigger-class="[structureMonoControlClass, 'w-full']"
- @update:model-value="
- (v: string) =>
- (column.dataType = combineDataTypeForDatabase(
- databaseType,
- v,
- getDefaultLengthForType(databaseType, v),
- ))
- "
- />
- <Input
- v-else
- :model-value="splitDataType(column.dataType).baseType"
- :class="[structureMonoControlClass, 'w-full']"
- disabled
+ @update:model-value="(v: string) => (column.dataType = combineDataTypeForDatabase(databaseType, v, getDefaultLengthForType(databaseType, v)))"
/>
+ <Input v-else :model-value="splitDataType(column.dataType).baseType" :class="[structureMonoControlClass, 'w-full']" disabled />
</td>
<td :class="structureCellClass">
- <Input
- :model-value="splitDataType(column.dataType).params"
- :class="structureMonoControlClass"
- :disabled="isColumnTypeDisabled(column)"
- @update:model-value="
- column.dataType = combineDataTypeForDatabase(
- databaseType,
- splitDataType(column.dataType).baseType,
- String($event),
- )
- "
- />
+ <Input :model-value="splitDataType(column.dataType).params" :class="structureMonoControlClass" :disabled="isColumnTypeDisabled(column)" @update:model-value="column.dataType = combineDataTypeForDatabase(databaseType, splitDataType(column.dataType).baseType, String($event))" />
</td>
<td :class="structureCellClass">
<label class="flex items-center gap-1.5">
- <input
- v-model="column.isNullable"
- type="checkbox"
- :class="structureCheckboxClass"
- :disabled="isColumnNullableDisabled(column)"
- />
+ <input v-model="column.isNullable" type="checkbox" :class="structureCheckboxClass" :disabled="isColumnNullableDisabled(column)" />
<span>{{ column.isNullable ? t("structureEditor.yes") : t("structureEditor.no") }}</span>
</label>
</td>
@@ -1024,29 +818,14 @@ watch(activeTab, (tab) => {
/>
</td>
<td :class="structureCellClass">
- <Input
- v-model="column.defaultValue"
- :class="structureMonoControlClass"
- :disabled="isColumnDefaultDisabled(column)"
- />
+ <Input v-model="column.defaultValue" :class="structureMonoControlClass" :disabled="isColumnDefaultDisabled(column)" />
</td>
<td :class="structureCellClass">
<div class="flex min-w-0 items-center gap-1">
- <Input
- v-model="column.comment"
- :class="[structureControlClass, 'flex-1']"
- :disabled="isColumnCommentDisabled(column)"
- />
+ <Input v-model="column.comment" :class="[structureControlClass, 'flex-1']" :disabled="isColumnCommentDisabled(column)" />
<Popover>
<PopoverTrigger as-child>
- <Button
- variant="ghost"
- size="icon"
- :class="[structureIconButtonClass, 'shrink-0']"
- :disabled="isColumnCommentDisabled(column)"
- :aria-label="t('structureEditor.editComment')"
- :title="t('structureEditor.editComment')"
- >
+ <Button variant="ghost" size="icon" :class="[structureIconButtonClass, 'shrink-0']" :disabled="isColumnCommentDisabled(column)" :aria-label="t('structureEditor.editComment')" :title="t('structureEditor.editComment')">
<Maximize2 :class="structureIconClass" />
</Button>
</PopoverTrigger>
@@ -1055,9 +834,7 @@ watch(activeTab, (tab) => {
<span class="min-w-0 truncate text-xs font-medium">
{{ t("structureEditor.editComment") }}
</span>
- <span
- class="max-w-44 truncate font-mono text-[length:var(--structure-font-size)] text-muted-foreground"
- >
+ <span class="max-w-44 truncate font-mono text-[length:var(--structure-font-size)] text-muted-foreground">
{{ column.name || t("structureEditor.columnName") }}
</span>
</div>
@@ -1080,11 +857,7 @@ watch(activeTab, (tab) => {
{{ t("structureEditor.autoIncrement") }}
</label>
<label class="flex items-center gap-1 whitespace-nowrap">
- <input
- v-model="column.extra.onUpdateCurrentTimestamp"
- type="checkbox"
- :class="structureCheckboxClass"
- />
+ <input v-model="column.extra.onUpdateCurrentTimestamp" type="checkbox" :class="structureCheckboxClass" />
{{ t("structureEditor.onUpdateCurrentTimestamp") }}
</label>
</template>
@@ -1106,9 +879,7 @@ watch(activeTab, (tab) => {
}
"
>
- <SelectTrigger
- class="h-[var(--structure-control-height)] w-28 rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]"
- >
+ <SelectTrigger class="h-[var(--structure-control-height)] w-28 rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -1184,47 +955,18 @@ watch(activeTab, (tab) => {
<td :class="structureLastCellClass">
<div class="flex items-center gap-1">
<template v-if="canShowColumnMoveControls">
- <Button
- variant="ghost"
- size="icon"
- :class="structureIconButtonClass"
- :disabled="!canMoveColumn(index, -1)"
- :title="t('structureEditor.moveColumnUp')"
- :aria-label="t('structureEditor.moveColumnUp')"
- @click="moveColumn(index, -1)"
- >
+ <Button variant="ghost" size="icon" :class="structureIconButtonClass" :disabled="!canMoveColumn(index, -1)" :title="t('structureEditor.moveColumnUp')" :aria-label="t('structureEditor.moveColumnUp')" @click="moveColumn(index, -1)">
<ChevronUp :class="structureIconClass" />
</Button>
- <Button
- variant="ghost"
- size="icon"
- :class="structureIconButtonClass"
- :disabled="!canMoveColumn(index, 1)"
- :title="t('structureEditor.moveColumnDown')"
- :aria-label="t('structureEditor.moveColumnDown')"
- @click="moveColumn(index, 1)"
- >
+ <Button variant="ghost" size="icon" :class="structureIconButtonClass" :disabled="!canMoveColumn(index, 1)" :title="t('structureEditor.moveColumnDown')" :aria-label="t('structureEditor.moveColumnDown')" @click="moveColumn(index, 1)">
<ChevronDown :class="structureIconClass" />
</Button>
</template>
- <Button
- v-if="column.original"
- variant="ghost"
- size="sm"
- :class="structureToolbarButtonClass"
- :disabled="!canDropColumn(column)"
- @click="toggleDropColumn(column)"
- >
+ <Button v-if="column.original" variant="ghost" size="sm" :class="structureToolbarButtonClass" :disabled="!canDropColumn(column)" @click="toggleDropColumn(column)">
<Trash2 :class="structureIconClass" />
{{ column.markedForDrop ? t("structureEditor.restore") : t("structureEditor.drop") }}
</Button>
- <Button
- v-else
- variant="ghost"
- size="sm"
- :class="structureToolbarButtonClass"
- @click="removeNewColumn(column)"
- >
+ <Button v-else variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="removeNewColumn(column)">
<X :class="structureIconClass" />
{{ t("structureEditor.remove") }}
</Button>
@@ -1236,10 +978,7 @@ watch(activeTab, (tab) => {
</TabsContent>
<TabsContent value="indexes" class="m-0 min-h-0 flex-1 overflow-auto p-0">
- <table
- class="border-separate border-spacing-0 text-[length:var(--structure-font-size)] leading-[var(--structure-line-height)]"
- :style="{ minWidth: indexColWidths.reduce((a, w) => a + w, 0) + 'px' }"
- >
+ <table class="border-separate border-spacing-0 text-[length:var(--structure-font-size)] leading-[var(--structure-line-height)]" :style="{ minWidth: indexColWidths.reduce((a, w) => a + w, 0) + 'px' }">
<thead class="sticky top-0 z-10 bg-background">
<tr>
<th
@@ -1252,182 +991,83 @@ watch(activeTab, (tab) => {
}"
>
{{ label }}
- <div
- v-if="i < indexColLabels.length - 1"
- class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30"
- :class="resizing?.col === i ? 'bg-primary/30' : ''"
- @mousedown="onIndexColResize($event, i)"
- />
+ <div v-if="i < indexColLabels.length - 1" class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30" :class="resizing?.col === i ? 'bg-primary/30' : ''" @mousedown="onIndexColResize($event, i)" />
</th>
</tr>
</thead>
<tbody>
- <tr
- v-for="index in indexes"
- :key="index.id"
- :class="index.markedForDrop ? 'bg-destructive/5 opacity-60' : ''"
- :data-new-index-row="!index.original ? 'true' : undefined"
- >
+ <tr v-for="index in indexes" :key="index.id" :class="index.markedForDrop ? 'bg-destructive/5 opacity-60' : ''" :data-new-index-row="!index.original ? 'true' : undefined">
<td :class="structureCellClass">
- <Input
- v-model="index.name"
- :class="structureControlClass"
- :disabled="!canEditIndexDraft(index)"
- data-index-name-input
- />
+ <Input v-model="index.name" :class="structureControlClass" :disabled="!canEditIndexDraft(index)" data-index-name-input />
</td>
<td :class="[structureCellClass, 'overflow-hidden']">
<DropdownMenu v-if="canEditIndexDraft(index)">
<DropdownMenuTrigger as-child>
<Button variant="outline" :class="[structureMonoControlClass, 'w-full justify-between']">
- <span class="truncate">{{
- toColumnNames(index.columns) || t("structureEditor.indexColumnsPlaceholder")
- }}</span>
+ <span class="truncate">{{ toColumnNames(index.columns) || t("structureEditor.indexColumnsPlaceholder") }}</span>
<ChevronDown :class="[structureIconClass, 'ml-1 shrink-0 opacity-50']" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- class="max-h-56 min-w-44 overflow-y-auto"
- side="bottom"
- :side-offset="2"
- :avoid-collisions="false"
- @interactOutside="colSearch = ''"
- >
+ <DropdownMenuContent class="max-h-56 min-w-44 overflow-y-auto" side="bottom" :side-offset="2" :avoid-collisions="false" @interactOutside="colSearch = ''">
<div class="px-[var(--structure-cell-px)] pb-1 pt-0.5">
- <Input
- v-model="colSearch"
- :class="structureControlClass"
- :placeholder="t('grid.search')"
- @click.stop
- />
+ <Input v-model="colSearch" :class="structureControlClass" :placeholder="t('grid.search')" @click.stop />
</div>
- <DropdownMenuCheckboxItem
- v-for="col in filteredColumnNames"
- :key="col"
- :checked="index.columns.includes(col)"
- :class="index.columns.includes(col) ? 'bg-primary/10' : ''"
- @select.prevent
- @click="toggleIndexColumn(index, col)"
- >
+ <DropdownMenuCheckboxItem v-for="col in filteredColumnNames" :key="col" :checked="index.columns.includes(col)" :class="index.columns.includes(col) ? 'bg-primary/10' : ''" @select.prevent @click="toggleIndexColumn(index, col)">
{{ col }}
</DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
- <span v-else class="font-mono text-[length:var(--structure-font-size)] text-muted-foreground">{{
- toColumnNames(index.columns)
- }}</span>
+ <span v-else class="font-mono text-[length:var(--structure-font-size)] text-muted-foreground">{{ toColumnNames(index.columns) }}</span>
</td>
<td :class="structureCellClass">
<label class="flex items-center gap-1.5">
- <input
- v-model="index.isUnique"
- type="checkbox"
- :class="structureCheckboxClass"
- :disabled="!canEditIndexDraft(index)"
- />
+ <input v-model="index.isUnique" type="checkbox" :class="structureCheckboxClass" :disabled="!canEditIndexDraft(index)" />
<span>{{ index.isUnique ? t("structureEditor.yes") : t("structureEditor.no") }}</span>
</label>
</td>
<td :class="structureCellClass">
- <Select
- v-if="indexTypeOptions.length > 0"
- :model-value="index.indexType || 'BTREE'"
- :disabled="!canEditIndexDraft(index)"
- @update:model-value="(v: any) => (index.indexType = String(v ?? ''))"
- >
- <SelectTrigger
- class="h-[var(--structure-control-height)] w-full rounded-md px-[var(--structure-control-px)] font-mono text-[length:var(--structure-font-size)]"
- >
+ <Select v-if="indexTypeOptions.length > 0" :model-value="index.indexType || 'BTREE'" :disabled="!canEditIndexDraft(index)" @update:model-value="(v: any) => (index.indexType = String(v ?? ''))">
+ <SelectTrigger class="h-[var(--structure-control-height)] w-full rounded-md px-[var(--structure-control-px)] font-mono text-[length:var(--structure-font-size)]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="opt in indexTypeOptions" :key="opt" :value="opt">{{ opt }}</SelectItem>
</SelectContent>
</Select>
- <Input
- v-else
- v-model="index.indexType"
- :class="structureMonoControlClass"
- placeholder="BTREE"
- :disabled="!canEditIndexDraft(index) || !structureCapabilities.indexType"
- />
+ <Input v-else v-model="index.indexType" :class="structureMonoControlClass" placeholder="BTREE" :disabled="!canEditIndexDraft(index) || !structureCapabilities.indexType" />
</td>
<td :class="[structureCellClass, 'overflow-hidden']">
<DropdownMenu v-if="canEditIndexDraft(index) && structureCapabilities.indexInclude">
<DropdownMenuTrigger as-child>
<Button variant="outline" :class="[structureMonoControlClass, 'w-full justify-between']">
- <span class="truncate">{{
- index.includedColumns.join(", ") || t("structureEditor.includedColumnsPlaceholder")
- }}</span>
+ <span class="truncate">{{ index.includedColumns.join(", ") || t("structureEditor.includedColumnsPlaceholder") }}</span>
<ChevronDown :class="[structureIconClass, 'ml-1 shrink-0 opacity-50']" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- class="max-h-56 min-w-44 overflow-y-auto"
- side="bottom"
- :side-offset="2"
- :avoid-collisions="false"
- @interactOutside="colSearch = ''"
- >
+ <DropdownMenuContent class="max-h-56 min-w-44 overflow-y-auto" side="bottom" :side-offset="2" :avoid-collisions="false" @interactOutside="colSearch = ''">
<div class="px-[var(--structure-cell-px)] pb-1 pt-0.5">
- <Input
- v-model="colSearch"
- :class="structureControlClass"
- :placeholder="t('grid.search')"
- @click.stop
- />
+ <Input v-model="colSearch" :class="structureControlClass" :placeholder="t('grid.search')" @click.stop />
</div>
- <DropdownMenuCheckboxItem
- v-for="col in filteredColumnNames"
- :key="col"
- :checked="index.includedColumns.includes(col)"
- :class="index.includedColumns.includes(col) ? 'bg-primary/10' : ''"
- @select.prevent
- @click="toggleIncludedColumn(index, col)"
- >
+ <DropdownMenuCheckboxItem v-for="col in filteredColumnNames" :key="col" :checked="index.includedColumns.includes(col)" :class="index.includedColumns.includes(col) ? 'bg-primary/10' : ''" @select.prevent @click="toggleIncludedColumn(index, col)">
{{ col }}
</DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
- <span v-else class="text-[length:var(--structure-font-size)] text-muted-foreground">{{
- index.includedColumns.join(", ")
- }}</span>
+ <span v-else class="text-[length:var(--structure-font-size)] text-muted-foreground">{{ index.includedColumns.join(", ") }}</span>
</td>
<td :class="structureCellClass">
- <Input
- v-model="index.filter"
- :class="structureMonoControlClass"
- :placeholder="index.original?.filter || ''"
- :disabled="!canEditIndexFilter(index)"
- />
+ <Input v-model="index.filter" :class="structureMonoControlClass" :placeholder="index.original?.filter || ''" :disabled="!canEditIndexFilter(index)" />
</td>
<td :class="structureCellClass">
- <Input
- v-model="index.comment"
- :class="structureControlClass"
- :disabled="!canEditIndexComment(index)"
- />
+ <Input v-model="index.comment" :class="structureControlClass" :disabled="!canEditIndexComment(index)" />
</td>
<td :class="structureLastCellClass">
<Badge v-if="index.isPrimary" variant="outline">{{ t("structureEditor.primary") }}</Badge>
- <Button
- v-else-if="index.original"
- variant="ghost"
- size="sm"
- :class="structureToolbarButtonClass"
- :disabled="!canDropIndex(index)"
- @click="toggleDropIndex(index)"
- >
+ <Button v-else-if="index.original" variant="ghost" size="sm" :class="structureToolbarButtonClass" :disabled="!canDropIndex(index)" @click="toggleDropIndex(index)">
<Trash2 :class="structureIconClass" />
{{ index.markedForDrop ? t("structureEditor.restore") : t("structureEditor.drop") }}
</Button>
- <Button
- v-else
- variant="ghost"
- size="sm"
- :class="structureToolbarButtonClass"
- @click="removeNewIndex(index)"
- >
+ <Button v-else variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="removeNewIndex(index)">
<X :class="structureIconClass" />
{{ t("structureEditor.remove") }}
</Button>
@@ -1442,15 +1082,9 @@ watch(activeTab, (tab) => {
{{ t("structureEditor.emptyReadonly") }}
</div>
<div v-else class="space-y-1.5">
- <div
- v-for="fk in foreignKeys"
- :key="fk.name"
- class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]"
- >
+ <div v-for="fk in foreignKeys" :key="fk.name" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">
<div class="font-medium">{{ fk.name }}</div>
- <div class="mt-1 font-mono text-muted-foreground">
- {{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}
- </div>
+ <div class="mt-1 font-mono text-muted-foreground">{{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}</div>
</div>
</div>
</TabsContent>
@@ -1460,11 +1094,7 @@ watch(activeTab, (tab) => {
{{ t("structureEditor.emptyReadonly") }}
</div>
<div v-else class="space-y-1.5">
- <div
- v-for="trigger in triggers"
- :key="trigger.name"
- class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]"
- >
+ <div v-for="trigger in triggers" :key="trigger.name" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">
<div class="font-medium">{{ trigger.name }}</div>
<div class="mt-1 font-mono text-muted-foreground">{{ trigger.timing }} {{ trigger.event }}</div>
</div>
@@ -1476,37 +1106,22 @@ watch(activeTab, (tab) => {
<Loader2 class="h-4 w-4 animate-spin" />
{{ t("common.loading") }}
</div>
- <pre
- v-else
- class="m-0 min-h-0 flex-1 whitespace-pre p-3 font-mono text-xs leading-5 select-text"
- v-html="ddlContent ? (sqlHighlighter?.(ddlContent) ?? ddlContent) : t('structureEditor.emptyReadonly')"
- ></pre>
+ <pre v-else class="m-0 min-h-0 flex-1 whitespace-pre p-3 font-mono text-xs leading-5 select-text" v-html="ddlContent ? (sqlHighlighter?.(ddlContent) ?? ddlContent) : t('structureEditor.emptyReadonly')"></pre>
</TabsContent>
</Tabs>
</div>
<div class="flex h-[28%] min-h-40 min-w-0 max-h-64 shrink-0 flex-col overflow-hidden rounded-md border">
- <div
- class="flex shrink-0 items-center justify-between border-b px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)] font-medium"
- >
+ <div class="flex shrink-0 items-center justify-between border-b px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)] font-medium">
<div class="flex items-center gap-1.5">
<span>{{ t("structureEditor.sqlPreview") }}</span>
- <Badge
- v-if="!saving && pendingStatements.length && warnings.length === 0"
- variant="outline"
- class="h-4 px-1 text-[10px]"
- >
+ <Badge v-if="!saving && pendingStatements.length && warnings.length === 0" variant="outline" class="h-4 px-1 text-[10px]">
<Check class="h-3 w-3" />
{{ t("structureEditor.ready") }}
</Badge>
</div>
<div class="flex items-center gap-1.5">
- <Button
- variant="ghost"
- :class="structureToolbarButtonClass"
- :disabled="!previewSqlText.trim()"
- @click="copyPreviewSql"
- >
+ <Button variant="ghost" :class="structureToolbarButtonClass" :disabled="!previewSqlText.trim()" @click="copyPreviewSql">
<Copy :class="[structureIconClass, 'mr-1']" />
{{ t("structureEditor.copySql") }}
</Button>
@@ -1518,34 +1133,20 @@ watch(activeTab, (tab) => {
</div>
<div class="min-h-0 flex-1 overflow-auto p-2.5">
<div v-if="warnings.length" class="mb-2 space-y-1">
- <div
- v-for="warning in warnings"
- :key="warning"
- class="flex gap-1.5 rounded-md border border-yellow-300/40 bg-yellow-500/10 px-[var(--structure-cell-px)] py-[var(--structure-cell-py)] text-[length:var(--structure-font-size)] text-yellow-700 dark:text-yellow-300"
- >
+ <div v-for="warning in warnings" :key="warning" class="flex gap-1.5 rounded-md border border-yellow-300/40 bg-yellow-500/10 px-[var(--structure-cell-px)] py-[var(--structure-cell-py)] text-[length:var(--structure-font-size)] text-yellow-700 dark:text-yellow-300">
<AlertTriangle :class="[structureIconClass, 'mt-0.5 shrink-0']" />
<span>{{ warning }}</span>
</div>
</div>
- <pre
- v-if="pendingStatements.length"
- class="select-text whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2.5 font-mono text-[calc(var(--structure-font-size)+1px)] leading-5"
- v-html="highlightedSql"
- />
- <div
- v-else
- class="flex h-full items-center justify-center text-[length:var(--structure-font-size)] text-muted-foreground"
- >
+ <pre v-if="pendingStatements.length" class="select-text whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2.5 font-mono text-[calc(var(--structure-font-size)+1px)] leading-5" v-html="highlightedSql" />
+ <div v-else class="flex h-full items-center justify-center text-[length:var(--structure-font-size)] text-muted-foreground">
{{ t("structureEditor.noChanges") }}
</div>
</div>
</div>
</div>
- <div
- v-if="errorMessage"
- class="shrink-0 rounded-md border border-destructive/30 bg-destructive/10 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)] text-destructive"
- >
+ <div v-if="errorMessage" class="shrink-0 rounded-md border border-destructive/30 bg-destructive/10 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)] text-destructive">
{{ errorMessage }}
</div>
diff --git a/apps/desktop/src/components/transfer/DataTransferDialog.vue b/apps/desktop/src/components/transfer/DataTransferDialog.vue
index 3e482e0355..0c8ebd740f 100644
--- a/apps/desktop/src/components/transfer/DataTransferDialog.vue
+++ b/apps/desktop/src/components/transfer/DataTransferDialog.vue
@@ -66,9 +66,7 @@ const filteredTables = computed(() => {
return q ? sourceTables.value.filter((t) => t.toLowerCase().includes(q)) : sourceTables.value;
});
-const allSelected = computed(
- () => filteredTables.value.length > 0 && filteredTables.value.every((t) => selectedTables.value.has(t)),
-);
+const allSelected = computed(() => filteredTables.value.length > 0 && filteredTables.value.every((t) => selectedTables.value.has(t)));
function connectionType(id: string): DatabaseType | undefined {
return store.connections.find((c) => c.id === id)?.db_type;
@@ -78,15 +76,7 @@ function isMongoConnection(id: string): boolean {
return connectionType(id) === "mongodb";
}
-const canStart = computed(
- () =>
- sourceConnectionId.value &&
- sourceDatabase.value &&
- targetConnectionId.value &&
- targetDatabase.value &&
- selectedTables.value.size > 0 &&
- sourceConnectionId.value + sourceDatabase.value !== targetConnectionId.value + targetDatabase.value,
-);
+const canStart = computed(() => sourceConnectionId.value && sourceDatabase.value && targetConnectionId.value && targetDatabase.value && selectedTables.value.size > 0 && sourceConnectionId.value + sourceDatabase.value !== targetConnectionId.value + targetDatabase.value);
function toggleSelectAll() {
if (allSelected.value) {
@@ -108,9 +98,7 @@ async function loadDatabases(connectionId: string, target: "source" | "target")
if (!connectionId) return;
try {
await store.ensureConnected(connectionId);
- const rawNames = isMongoConnection(connectionId)
- ? await api.mongoListDatabases(connectionId)
- : (await api.listDatabases(connectionId)).map((d) => d.name);
+ const rawNames = isMongoConnection(connectionId) ? await api.mongoListDatabases(connectionId) : (await api.listDatabases(connectionId)).map((d) => d.name);
const names = databaseOptionsForConnection(rawNames, store.getConfig(connectionId));
if (target === "source") {
sourceDatabases.value = names;
@@ -139,12 +127,7 @@ async function loadSchemas(connectionId: string, database: string, side: "source
}
try {
const schemas = await api.listSchemas(connectionId, database);
- const selected =
- preferredSchema && schemas.includes(preferredSchema)
- ? preferredSchema
- : schemas.includes("public")
- ? "public"
- : (schemas[0] ?? "");
+ const selected = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
if (side === "source") {
sourceSchemas.value = schemas;
sourceSchema.value = selected;
@@ -179,9 +162,7 @@ async function loadTables() {
const needsSchema = isSchemaAware(config?.db_type);
const schema = needsSchema && sourceSchema.value ? sourceSchema.value : sourceDatabase.value;
const tables = await api.listTables(sourceConnectionId.value, sourceDatabase.value, schema);
- sourceTables.value = tables
- .filter((t) => t.table_type === "TABLE" || t.table_type === "BASE TABLE")
- .map((t) => t.name);
+ sourceTables.value = tables.filter((t) => t.table_type === "TABLE" || t.table_type === "BASE TABLE").map((t) => t.name);
selectedTables.value = new Set(sourceTables.value);
} catch {
sourceTables.value = [];
@@ -358,25 +339,15 @@ function formatTableRows(progress: TransferProgress) {
return formatRowCount(progress.rowsTransferred);
}
-const completedTables = computed(
- () => [...transferProgress.value.values()].filter((p) => processedStatuses.has(p.status)).length,
-);
+const completedTables = computed(() => [...transferProgress.value.values()].filter((p) => processedStatuses.has(p.status)).length);
const failedTables = computed(() => [...transferProgress.value.values()].filter((p) => p.status === "error").length);
-const totalTransferred = computed(() =>
- [...transferProgress.value.values()].reduce((sum, p) => sum + p.rowsTransferred, 0),
-);
+const totalTransferred = computed(() => [...transferProgress.value.values()].reduce((sum, p) => sum + p.rowsTransferred, 0));
-const knownTotalRows = computed(() =>
- [...transferProgress.value.values()].reduce((sum, p) => sum + (typeof p.totalRows === "number" ? p.totalRows : 0), 0),
-);
+const knownTotalRows = computed(() => [...transferProgress.value.values()].reduce((sum, p) => sum + (typeof p.totalRows === "number" ? p.totalRows : 0), 0));
-const overallRowsLabel = computed(() =>
- knownTotalRows.value > 0
- ? `${formatRowCount(totalTransferred.value)} / ${formatRowCount(knownTotalRows.value)}`
- : formatRowCount(totalTransferred.value),
-);
+const overallRowsLabel = computed(() => (knownTotalRows.value > 0 ? `${formatRowCount(totalTransferred.value)} / ${formatRowCount(knownTotalRows.value)}` : formatRowCount(totalTransferred.value)));
</script>
<template>
@@ -505,48 +476,27 @@ const overallRowsLabel = computed(() =>
<div class="flex items-center justify-between">
<div class="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{{ t("transfer.tables") }}
- <span v-if="sourceTables.length" class="text-muted-foreground/60"
- >({{ selectedTables.size }}/{{ sourceTables.length }})</span
- >
+ <span v-if="sourceTables.length" class="text-muted-foreground/60">({{ selectedTables.size }}/{{ sourceTables.length }})</span>
</div>
- <Button
- v-if="sourceTables.length"
- variant="ghost"
- size="sm"
- class="h-6 text-xs px-2"
- @click="toggleSelectAll"
- >
+ <Button v-if="sourceTables.length" variant="ghost" size="sm" class="h-6 text-xs px-2" @click="toggleSelectAll">
{{ allSelected ? t("transfer.deselectAll") : t("transfer.selectAll") }}
</Button>
</div>
- <Input
- v-if="sourceTables.length > 5"
- v-model="tableSearch"
- :placeholder="t('transfer.searchTables')"
- class="h-7 text-xs"
- />
+ <Input v-if="sourceTables.length > 5" v-model="tableSearch" :placeholder="t('transfer.searchTables')" class="h-7 text-xs" />
<div v-if="loadingTables" class="flex items-center gap-2 text-xs text-muted-foreground py-4 justify-center">
<Loader2 class="w-3.5 h-3.5 animate-spin" />
{{ t("common.loading") }}
</div>
- <div
- v-else-if="!sourceConnectionId || !sourceDatabase"
- class="text-xs text-muted-foreground py-4 text-center"
- >
+ <div v-else-if="!sourceConnectionId || !sourceDatabase" class="text-xs text-muted-foreground py-4 text-center">
{{ t("transfer.selectSourceFirst") }}
</div>
<div v-else-if="sourceTables.length === 0" class="text-xs text-muted-foreground py-4 text-center">
{{ t("transfer.noTables") }}
</div>
<div v-else class="border rounded-md max-h-[200px] overflow-y-auto">
- <div
- v-for="table in filteredTables"
- :key="table"
- class="flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/50 cursor-pointer text-xs"
- @click="toggleTable(table)"
- >
+ <div v-for="table in filteredTables" :key="table" class="flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/50 cursor-pointer text-xs" @click="toggleTable(table)">
<CheckSquare v-if="selectedTables.has(table)" class="w-3.5 h-3.5 text-primary shrink-0" />
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
<span class="truncate">{{ table }}</span>
@@ -576,14 +526,7 @@ const overallRowsLabel = computed(() =>
</div>
<div class="flex items-center gap-3">
<Label class="text-xs shrink-0">{{ t("transfer.batchSize") }}</Label>
- <Input
- v-model.number="batchSize"
- type="number"
- min="100"
- max="10000"
- step="100"
- class="h-7 text-xs w-24"
- />
+ <Input v-model.number="batchSize" type="number" min="100" max="10000" step="100" class="h-7 text-xs w-24" />
</div>
</div>
</div>
@@ -592,13 +535,10 @@ const overallRowsLabel = computed(() =>
<div v-else class="py-3 space-y-3">
<div class="flex items-center justify-between text-xs text-muted-foreground">
<span>
- {{ t("transfer.overallProgress") }}: {{ completedTables }} / {{ selectedTables.size }}
- {{ t("transfer.tables").toLowerCase() }} · {{ overallRowsLabel }}
+ {{ t("transfer.overallProgress") }}: {{ completedTables }} / {{ selectedTables.size }} {{ t("transfer.tables").toLowerCase() }} · {{ overallRowsLabel }}
{{ t("grid.rows", { count: "" }).trim() }}
</span>
- <span v-if="overallDone && !failedTables" class="text-green-600 font-medium">{{
- t("transfer.completed")
- }}</span>
+ <span v-if="overallDone && !failedTables" class="text-green-600 font-medium">{{ t("transfer.completed") }}</span>
<span v-else-if="overallDone && failedTables" class="text-amber-600 font-medium">
{{ t("transfer.completedWithErrors", { count: failedTables }) }}
</span>
@@ -609,15 +549,7 @@ const overallRowsLabel = computed(() =>
<div class="w-full bg-muted rounded-full h-2 overflow-hidden">
<div
class="h-full rounded-full transition-all duration-300"
- :class="
- overallError
- ? 'bg-destructive'
- : overallCancelled
- ? 'bg-yellow-500'
- : overallDone && failedTables
- ? 'bg-amber-500'
- : 'bg-primary'
- "
+ :class="overallError ? 'bg-destructive' : overallCancelled ? 'bg-yellow-500' : overallDone && failedTables ? 'bg-amber-500' : 'bg-primary'"
:style="{
width: `${selectedTables.size ? (completedTables / selectedTables.size) * 100 : 0}%`,
}"
@@ -625,11 +557,7 @@ const overallRowsLabel = computed(() =>
</div>
<div class="border rounded-md max-h-[280px] overflow-y-auto">
- <div
- v-for="table in [...selectedTables]"
- :key="table"
- class="flex items-center justify-between px-2.5 py-1.5 text-xs border-b last:border-b-0"
- >
+ <div v-for="table in [...selectedTables]" :key="table" class="flex items-center justify-between px-2.5 py-1.5 text-xs border-b last:border-b-0">
<span class="truncate">{{ table }}</span>
<div class="flex items-center gap-1.5 shrink-0 text-muted-foreground">
<template v-if="transferProgress.get(table)">
@@ -637,22 +565,14 @@ const overallRowsLabel = computed(() =>
<Loader2 class="w-3 h-3 animate-spin text-primary" />
<span>{{ formatTableRows(transferProgress.get(table)!) }}</span>
</template>
- <template
- v-else-if="
- transferProgress.get(table)!.status === 'tableDone' ||
- transferProgress.get(table)!.status === 'done'
- "
- >
+ <template v-else-if="transferProgress.get(table)!.status === 'tableDone' || transferProgress.get(table)!.status === 'done'">
<Check class="w-3 h-3 text-green-500" />
<span>{{ formatTableRows(transferProgress.get(table)!) }}</span>
</template>
<template v-else-if="transferProgress.get(table)!.status === 'error'">
<X class="w-3 h-3 text-destructive" />
<span>{{ formatTableRows(transferProgress.get(table)!) }}</span>
- <span
- class="max-w-[520px] whitespace-normal break-words text-destructive"
- :title="transferProgress.get(table)!.error ?? ''"
- >
+ <span class="max-w-[520px] whitespace-normal break-words text-destructive" :title="transferProgress.get(table)!.error ?? ''">
{{ transferProgress.get(table)!.error }}
</span>
</template>
diff --git a/apps/desktop/src/components/ui/CustomContextMenu.vue b/apps/desktop/src/components/ui/CustomContextMenu.vue
index 53a1acc67d..03c0d9aa72 100644
--- a/apps/desktop/src/components/ui/CustomContextMenu.vue
+++ b/apps/desktop/src/components/ui/CustomContextMenu.vue
@@ -210,9 +210,7 @@ function adjustSubPosition() {
function itemButtonClass(variant?: "default" | "destructive") {
return [
"w-full gap-2 rounded-md px-2 py-1 text-[13px] leading-4 outline-hidden select-none text-left cursor-default flex items-center disabled:pointer-events-none disabled:opacity-50 transition-colors",
- variant === "destructive"
- ? "text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive"
- : "hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground",
+ variant === "destructive" ? "text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive" : "hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground",
];
}
@@ -245,39 +243,19 @@ onBeforeUnmount(() => {
<slot :on-context-menu="onContextMenu" />
<!-- Main menu -->
<Teleport to="body">
- <div
- v-if="show"
- ref="menuRef"
- :style="{ position: 'fixed', left: x + 'px', top: y + 'px', zIndex: 9999 }"
- class="bg-popover text-popover-foreground min-w-40 rounded-xl p-1 overflow-x-hidden overflow-y-auto ring-1 ring-foreground/10 shadow-lg"
- >
+ <div v-if="show" ref="menuRef" :style="{ position: 'fixed', left: x + 'px', top: y + 'px', zIndex: 9999 }" class="bg-popover text-popover-foreground min-w-40 rounded-xl p-1 overflow-x-hidden overflow-y-auto ring-1 ring-foreground/10 shadow-lg">
<template v-for="(item, index) in items" :key="index">
<template v-if="item.visible !== false">
<div v-if="item.separator" class="-mx-1 my-1 flex items-center px-1">
<div class="h-px flex-1 bg-border/70" />
</div>
- <button
- v-else
- :disabled="item.disabled"
- :class="[
- ...itemButtonClass(item.variant),
- activeSubIndex === index ? 'bg-accent text-accent-foreground' : '',
- ]"
- @click="handleItemClick(item)"
- @mouseenter="(e) => onItemMouseEnter(index, e)"
- @mouseleave="onItemMouseLeave"
- >
+ <button v-else :disabled="item.disabled" :class="[...itemButtonClass(item.variant), activeSubIndex === index ? 'bg-accent text-accent-foreground' : '']" @click="handleItemClick(item)" @mouseenter="(e) => onItemMouseEnter(index, e)" @mouseleave="onItemMouseLeave">
<span class="flex size-4 shrink-0 items-center justify-center">
<component :is="item.icon" v-if="item.icon" :class="['size-4', item.iconClass]" />
</span>
<span class="min-w-0 flex-1 truncate">{{ item.label }}</span>
<span v-if="item.shortcut" class="ml-8 inline-flex shrink-0 items-center gap-1 text-muted-foreground">
- <kbd
- v-for="key in shortcutKeys(item.shortcut)"
- :key="key"
- class="min-w-4 rounded border border-border/70 bg-muted/60 px-1 py-0.5 text-center font-mono text-[10px] leading-none text-muted-foreground shadow-xs"
- >{{ key }}</kbd
- >
+ <kbd v-for="key in shortcutKeys(item.shortcut)" :key="key" class="min-w-4 rounded border border-border/70 bg-muted/60 px-1 py-0.5 text-center font-mono text-[10px] leading-none text-muted-foreground shadow-xs">{{ key }}</kbd>
</span>
<ChevronRight v-if="item.children?.length" class="ml-auto size-4 text-muted-foreground/80" />
</button>
@@ -300,23 +278,13 @@ onBeforeUnmount(() => {
<div v-if="child.separator" class="-mx-1 my-1 flex items-center px-1">
<div class="h-px flex-1 bg-border/70" />
</div>
- <button
- v-else
- :disabled="child.disabled"
- :class="itemButtonClass(child.variant)"
- @click="handleSubItemClick(child)"
- >
+ <button v-else :disabled="child.disabled" :class="itemButtonClass(child.variant)" @click="handleSubItemClick(child)">
<span class="flex size-4 shrink-0 items-center justify-center">
<component :is="child.icon" v-if="child.icon" :class="['size-4', child.iconClass]" />
</span>
<span class="min-w-0 flex-1 truncate">{{ child.label }}</span>
<span v-if="child.shortcut" class="ml-8 inline-flex shrink-0 items-center gap-1 text-muted-foreground">
- <kbd
- v-for="key in shortcutKeys(child.shortcut)"
- :key="key"
- class="min-w-4 rounded border border-border/70 bg-muted/60 px-1 py-0.5 text-center font-mono text-[10px] leading-none text-muted-foreground shadow-xs"
- >{{ key }}</kbd
- >
+ <kbd v-for="key in shortcutKeys(child.shortcut)" :key="key" class="min-w-4 rounded border border-border/70 bg-muted/60 px-1 py-0.5 text-center font-mono text-[10px] leading-none text-muted-foreground shadow-xs">{{ key }}</kbd>
</span>
</button>
</template>
diff --git a/apps/desktop/src/components/ui/LightDropdown.vue b/apps/desktop/src/components/ui/LightDropdown.vue
index f177060c6e..84bc84108b 100644
--- a/apps/desktop/src/components/ui/LightDropdown.vue
+++ b/apps/desktop/src/components/ui/LightDropdown.vue
@@ -42,8 +42,7 @@ const props = withDefaults(
{
ariaLabel: undefined,
contentClass: "",
- triggerClass:
- "flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",
+ triggerClass: "flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",
triggerTitle: undefined,
triggerIcon: undefined,
triggerLabel: undefined,
@@ -161,28 +160,13 @@ onBeforeUnmount(close);
</script>
<template>
- <button
- ref="triggerRef"
- type="button"
- :class="triggerClass"
- :title="triggerTitle ?? selectedItem?.title"
- :aria-label="ariaLabel"
- :aria-expanded="open"
- @click="toggle"
- >
+ <button ref="triggerRef" type="button" :class="triggerClass" :title="triggerTitle ?? selectedItem?.title" :aria-label="ariaLabel" :aria-expanded="open" @click="toggle">
<component :is="triggerIcon" v-if="triggerIcon" :class="triggerIconClass" />
<span v-if="showTriggerLabel">{{ triggerLabel ?? selectedItem?.label }}</span>
<ChevronDown v-if="showChevron" class="h-3 w-3 opacity-50" />
</button>
<Teleport to="body">
- <div
- v-if="open"
- ref="menuRef"
- class="fixed z-50 min-w-32 rounded-lg p-1 cn-menu-translucent text-popover-foreground"
- :class="contentClass"
- :style="menuStyle"
- role="menu"
- >
+ <div v-if="open" ref="menuRef" class="fixed z-50 min-w-32 rounded-lg p-1 cn-menu-translucent text-popover-foreground" :class="contentClass" :style="menuStyle" role="menu">
<div v-if="label" :class="labelClass">{{ label }}</div>
<div v-if="label" class="bg-border -mx-1 my-1 h-px" />
<template v-for="item in items" :key="item.value">
@@ -196,28 +180,13 @@ onBeforeUnmount(close);
role="menuitem"
@click="selectItem(item)"
>
- <Check
- v-if="checkPosition === 'left'"
- class="h-3 w-3 shrink-0"
- :class="[isItemSelected(item) ? selectedCheckClass : 'opacity-0']"
- />
- <span
- v-if="item.leadingText"
- class="inline-flex h-5 w-6 shrink-0 items-center justify-center text-sm font-medium leading-none"
- >
+ <Check v-if="checkPosition === 'left'" class="h-3 w-3 shrink-0" :class="[isItemSelected(item) ? selectedCheckClass : 'opacity-0']" />
+ <span v-if="item.leadingText" class="inline-flex h-5 w-6 shrink-0 items-center justify-center text-sm font-medium leading-none">
{{ item.leadingText }}
</span>
- <component
- :is="item.icon"
- v-if="item.icon"
- :class="[itemIconClass, 'shrink-0 text-muted-foreground', item.iconClass]"
- />
+ <component :is="item.icon" v-if="item.icon" :class="[itemIconClass, 'shrink-0 text-muted-foreground', item.iconClass]" />
<span class="truncate">{{ item.label }}</span>
- <Check
- v-if="checkPosition === 'right' && isItemSelected(item)"
- class="ml-auto h-4 w-4 shrink-0"
- :class="selectedCheckClass"
- />
+ <Check v-if="checkPosition === 'right' && isItemSelected(item)" class="ml-auto h-4 w-4 shrink-0" :class="selectedCheckClass" />
</button>
</template>
<slot />
diff --git a/apps/desktop/src/components/ui/LightTooltip.vue b/apps/desktop/src/components/ui/LightTooltip.vue
index 70125875df..4f231524ac 100644
--- a/apps/desktop/src/components/ui/LightTooltip.vue
+++ b/apps/desktop/src/components/ui/LightTooltip.vue
@@ -166,27 +166,11 @@ watch(
</script>
<template>
- <span
- ref="triggerRef"
- class="contents"
- @mouseenter="scheduleOpen"
- @mouseleave="close"
- @focusin="scheduleFocusOpen"
- @focusout="close"
- >
+ <span ref="triggerRef" class="contents" @mouseenter="scheduleOpen" @mouseleave="close" @focusin="scheduleFocusOpen" @focusout="close">
<slot />
</span>
<Teleport to="body">
- <div
- v-if="show"
- class="pointer-events-none fixed z-50 rounded-md bg-foreground text-xs text-background"
- :class="[
- slots.content ? '' : 'inline-flex w-fit max-w-xs items-center gap-1.5 px-3 py-1.5',
- tooltipTransformClass,
- ]"
- :style="{ left: `${x}px`, top: `${y}px` }"
- role="tooltip"
- >
+ <div v-if="show" class="pointer-events-none fixed z-50 rounded-md bg-foreground text-xs text-background" :class="[slots.content ? '' : 'inline-flex w-fit max-w-xs items-center gap-1.5 px-3 py-1.5', tooltipTransformClass]" :style="{ left: `${x}px`, top: `${y}px` }" role="tooltip">
<slot name="content">{{ text }}</slot>
<span :class="[arrowClass, 'size-2.5 rotate-45 rounded-[2px] bg-foreground']" aria-hidden="true" />
</div>
diff --git a/apps/desktop/src/components/ui/TruncatedTextTooltip.vue b/apps/desktop/src/components/ui/TruncatedTextTooltip.vue
index a4bdff841f..5d6a4381f5 100644
--- a/apps/desktop/src/components/ui/TruncatedTextTooltip.vue
+++ b/apps/desktop/src/components/ui/TruncatedTextTooltip.vue
@@ -31,14 +31,7 @@ function isTooltipDisabled(): boolean {
</script>
<template>
- <LightTooltip
- :text="text"
- :delay="delay"
- :disabled="isTooltipDisabled"
- :side="side"
- :side-offset="sideOffset"
- :open-on-focus="openOnFocus"
- >
+ <LightTooltip :text="text" :delay="delay" :disabled="isTooltipDisabled" :side="side" :side-offset="sideOffset" :open-on-focus="openOnFocus">
<span ref="textRef" :class="cn('truncate', props.class)">
<slot>{{ text }}</slot>
</span>
diff --git a/apps/desktop/src/components/ui/badge/Badge.vue b/apps/desktop/src/components/ui/badge/Badge.vue
index 62ffbe1092..00a6f77ecb 100644
--- a/apps/desktop/src/components/ui/badge/Badge.vue
+++ b/apps/desktop/src/components/ui/badge/Badge.vue
@@ -18,12 +18,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <Primitive
- data-slot="badge"
- :data-variant="variant"
- :class="cn(badgeVariants({ variant }), props.class)"
- v-bind="delegatedProps"
- >
+ <Primitive data-slot="badge" :data-variant="variant" :class="cn(badgeVariants({ variant }), props.class)" v-bind="delegatedProps">
<slot />
</Primitive>
</template>
diff --git a/apps/desktop/src/components/ui/badge/index.ts b/apps/desktop/src/components/ui/badge/index.ts
index 5ea5bdc05e..d8541205bb 100644
--- a/apps/desktop/src/components/ui/badge/index.ts
+++ b/apps/desktop/src/components/ui/badge/index.ts
@@ -10,8 +10,7 @@ export const badgeVariants = cva(
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
- destructive:
- "bg-destructive/10 [a]:hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-destructive dark:bg-destructive/20",
+ destructive: "bg-destructive/10 [a]:hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-destructive dark:bg-destructive/20",
outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost: "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
diff --git a/apps/desktop/src/components/ui/button/Button.vue b/apps/desktop/src/components/ui/button/Button.vue
index 4a9a8af6c5..0219ee512d 100644
--- a/apps/desktop/src/components/ui/button/Button.vue
+++ b/apps/desktop/src/components/ui/button/Button.vue
@@ -18,14 +18,7 @@ const props = withDefaults(defineProps<Props>(), {
</script>
<template>
- <Primitive
- data-slot="button"
- :data-variant="variant"
- :data-size="size"
- :as="as"
- :as-child="asChild"
- :class="cn(buttonVariants({ variant, size }), props.class)"
- >
+ <Primitive data-slot="button" :data-variant="variant" :data-size="size" :as="as" :as-child="asChild" :class="cn(buttonVariants({ variant, size }), props.class)">
<slot />
</Primitive>
</template>
diff --git a/apps/desktop/src/components/ui/button/index.ts b/apps/desktop/src/components/ui/button/index.ts
index 8f5204452f..9a7220bb19 100644
--- a/apps/desktop/src/components/ui/button/index.ts
+++ b/apps/desktop/src/components/ui/button/index.ts
@@ -9,14 +9,10 @@ export const buttonVariants = cva(
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
- outline:
- "border-border bg-background hover:bg-muted hover:text-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 aria-expanded:bg-muted aria-expanded:text-foreground",
- secondary:
- "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
- ghost:
- "hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 aria-expanded:bg-muted aria-expanded:text-foreground",
- destructive:
- "bg-destructive/10 hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/20 text-destructive focus-visible:border-destructive/40 dark:hover:bg-destructive/30",
+ outline: "border-border bg-background hover:bg-muted hover:text-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 aria-expanded:bg-muted aria-expanded:text-foreground",
+ secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
+ ghost: "hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 aria-expanded:bg-muted aria-expanded:text-foreground",
+ destructive: "bg-destructive/10 hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/20 text-destructive focus-visible:border-destructive/40 dark:hover:bg-destructive/30",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
@@ -25,8 +21,7 @@ export const buttonVariants = cva(
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*=size-])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
- "icon-xs":
- "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*=size-])]:size-3",
+ "icon-xs": "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*=size-])]:size-3",
"icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
diff --git a/apps/desktop/src/components/ui/context-menu/ContextMenuLabel.vue b/apps/desktop/src/components/ui/context-menu/ContextMenuLabel.vue
index 21a53d3115..5dbbd1f2f5 100644
--- a/apps/desktop/src/components/ui/context-menu/ContextMenuLabel.vue
+++ b/apps/desktop/src/components/ui/context-menu/ContextMenuLabel.vue
@@ -11,12 +11,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <ContextMenuLabel
- data-slot="context-menu-label"
- :data-inset="inset ? '' : undefined"
- v-bind="delegatedProps"
- :class="cn('text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:pl-7', props.class)"
- >
+ <ContextMenuLabel data-slot="context-menu-label" :data-inset="inset ? '' : undefined" v-bind="delegatedProps" :class="cn('text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:pl-7', props.class)">
<slot />
</ContextMenuLabel>
</template>
diff --git a/apps/desktop/src/components/ui/context-menu/ContextMenuSeparator.vue b/apps/desktop/src/components/ui/context-menu/ContextMenuSeparator.vue
index 68d8c583e3..60ceb5a59f 100644
--- a/apps/desktop/src/components/ui/context-menu/ContextMenuSeparator.vue
+++ b/apps/desktop/src/components/ui/context-menu/ContextMenuSeparator.vue
@@ -11,9 +11,5 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <ContextMenuSeparator
- data-slot="context-menu-separator"
- v-bind="delegatedProps"
- :class="cn('bg-foreground/6 -mx-1 my-0.5 h-px', props.class)"
- />
+ <ContextMenuSeparator data-slot="context-menu-separator" v-bind="delegatedProps" :class="cn('bg-foreground/6 -mx-1 my-0.5 h-px', props.class)" />
</template>
diff --git a/apps/desktop/src/components/ui/context-menu/ContextMenuShortcut.vue b/apps/desktop/src/components/ui/context-menu/ContextMenuShortcut.vue
index 30e32c0010..57134014b1 100644
--- a/apps/desktop/src/components/ui/context-menu/ContextMenuShortcut.vue
+++ b/apps/desktop/src/components/ui/context-menu/ContextMenuShortcut.vue
@@ -8,15 +8,7 @@ const props = defineProps<{
</script>
<template>
- <span
- data-slot="context-menu-shortcut"
- :class="
- cn(
- 'text-muted-foreground group-focus/context-menu-item:text-accent-foreground ml-auto text-xs tracking-widest',
- props.class,
- )
- "
- >
+ <span data-slot="context-menu-shortcut" :class="cn('text-muted-foreground group-focus/context-menu-item:text-accent-foreground ml-auto text-xs tracking-widest', props.class)">
<slot />
</span>
</template>
diff --git a/apps/desktop/src/components/ui/dialog/DialogContent.vue b/apps/desktop/src/components/ui/dialog/DialogContent.vue
index bb61d37452..fec83146cf 100644
--- a/apps/desktop/src/components/ui/dialog/DialogContent.vue
+++ b/apps/desktop/src/components/ui/dialog/DialogContent.vue
@@ -4,14 +4,7 @@ import type { DialogContentEmits, DialogContentProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { XIcon } from "@lucide/vue";
-import {
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogPortal,
- VisuallyHidden,
- useForwardPropsEmits,
-} from "reka-ui";
+import { DialogClose, DialogContent, DialogDescription, DialogPortal, VisuallyHidden, useForwardPropsEmits } from "reka-ui";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import DialogOverlay from "./DialogOverlay.vue";
@@ -20,12 +13,9 @@ defineOptions({
inheritAttrs: false,
});
-const props = withDefaults(
- defineProps<DialogContentProps & { class?: HTMLAttributes["class"]; showCloseButton?: boolean }>(),
- {
- showCloseButton: true,
- },
-);
+const props = withDefaults(defineProps<DialogContentProps & { class?: HTMLAttributes["class"]; showCloseButton?: boolean }>(), {
+ showCloseButton: true,
+});
const emits = defineEmits<DialogContentEmits>();
const delegatedProps = reactiveOmit(props, "class");
diff --git a/apps/desktop/src/components/ui/dialog/DialogDescription.vue b/apps/desktop/src/components/ui/dialog/DialogDescription.vue
index 81b73f3398..ffc8d812fe 100644
--- a/apps/desktop/src/components/ui/dialog/DialogDescription.vue
+++ b/apps/desktop/src/components/ui/dialog/DialogDescription.vue
@@ -13,16 +13,7 @@ const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
- <DialogDescription
- data-slot="dialog-description"
- v-bind="forwardedProps"
- :class="
- cn(
- 'text-muted-foreground *:[a]:hover:text-foreground text-sm *:[a]:underline *:[a]:underline-offset-3',
- props.class,
- )
- "
- >
+ <DialogDescription data-slot="dialog-description" v-bind="forwardedProps" :class="cn('text-muted-foreground *:[a]:hover:text-foreground text-sm *:[a]:underline *:[a]:underline-offset-3', props.class)">
<slot />
</DialogDescription>
</template>
diff --git a/apps/desktop/src/components/ui/dialog/DialogFooter.vue b/apps/desktop/src/components/ui/dialog/DialogFooter.vue
index b12a7cb381..6199e11a95 100644
--- a/apps/desktop/src/components/ui/dialog/DialogFooter.vue
+++ b/apps/desktop/src/components/ui/dialog/DialogFooter.vue
@@ -16,15 +16,7 @@ const props = withDefaults(
</script>
<template>
- <div
- data-slot="dialog-footer"
- :class="
- cn(
- 'bg-muted/50 -mx-4 -mb-4 rounded-b-xl border-t p-4 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end',
- props.class,
- )
- "
- >
+ <div data-slot="dialog-footer" :class="cn('bg-muted/50 -mx-4 -mb-4 rounded-b-xl border-t p-4 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', props.class)">
<slot />
<DialogClose v-if="showCloseButton" as-child>
<Button variant="outline"> Close </Button>
diff --git a/apps/desktop/src/components/ui/dialog/DialogOverlay.vue b/apps/desktop/src/components/ui/dialog/DialogOverlay.vue
index 9a699166aa..4b001dd03f 100644
--- a/apps/desktop/src/components/ui/dialog/DialogOverlay.vue
+++ b/apps/desktop/src/components/ui/dialog/DialogOverlay.vue
@@ -11,16 +11,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <DialogOverlay
- data-slot="dialog-overlay"
- v-bind="delegatedProps"
- :class="
- cn(
- 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-open:supports-backdrop-filter:backdrop-blur-xs bg-black/10 duration-100 fixed inset-0 isolate z-50',
- props.class,
- )
- "
- >
+ <DialogOverlay data-slot="dialog-overlay" v-bind="delegatedProps" :class="cn('data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-open:supports-backdrop-filter:backdrop-blur-xs bg-black/10 duration-100 fixed inset-0 isolate z-50', props.class)">
<slot />
</DialogOverlay>
</template>
diff --git a/apps/desktop/src/components/ui/dialog/DialogScrollContent.vue b/apps/desktop/src/components/ui/dialog/DialogScrollContent.vue
index 55caa3ed6e..dc9721eeeb 100644
--- a/apps/desktop/src/components/ui/dialog/DialogScrollContent.vue
+++ b/apps/desktop/src/components/ui/dialog/DialogScrollContent.vue
@@ -21,16 +21,9 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
<template>
<DialogPortal>
- <DialogOverlay
- class="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-black/10 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=open]:supports-backdrop-filter:backdrop-blur-xs"
- >
+ <DialogOverlay class="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-black/10 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=open]:supports-backdrop-filter:backdrop-blur-xs">
<DialogContent
- :class="
- cn(
- 'relative z-50 grid w-full max-w-lg my-8 gap-4 border border-border bg-background p-4 shadow-lg duration-200 sm:rounded-lg md:w-full',
- props.class,
- )
- "
+ :class="cn('relative z-50 grid w-full max-w-lg my-8 gap-4 border border-border bg-background p-4 shadow-lg duration-200 sm:rounded-lg md:w-full', props.class)"
v-bind="{ ...$attrs, ...forwarded }"
@pointer-down-outside="
(event) => {
diff --git a/apps/desktop/src/components/ui/dialog/DialogTitle.vue b/apps/desktop/src/components/ui/dialog/DialogTitle.vue
index e135f69f84..2af2f59172 100644
--- a/apps/desktop/src/components/ui/dialog/DialogTitle.vue
+++ b/apps/desktop/src/components/ui/dialog/DialogTitle.vue
@@ -13,11 +13,7 @@ const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
- <DialogTitle
- data-slot="dialog-title"
- v-bind="forwardedProps"
- :class="cn('text-base leading-none font-medium cn-font-heading', props.class)"
- >
+ <DialogTitle data-slot="dialog-title" v-bind="forwardedProps" :class="cn('text-base leading-none font-medium cn-font-heading', props.class)">
<slot />
</DialogTitle>
</template>
diff --git a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuCheckboxItem.vue b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuCheckboxItem.vue
index 7379712624..34f4817d12 100644
--- a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuCheckboxItem.vue
+++ b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuCheckboxItem.vue
@@ -36,10 +36,7 @@ function guardRepeatedClick(event: MouseEvent) {
)
"
>
- <span
- class="absolute right-2 flex items-center justify-center pointer-events-none"
- data-slot="dropdown-menu-checkbox-item-indicator"
- >
+ <span class="absolute right-2 flex items-center justify-center pointer-events-none" data-slot="dropdown-menu-checkbox-item-indicator">
<DropdownMenuItemIndicator>
<slot name="indicator-icon">
<CheckIcon />
diff --git a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuLabel.vue b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuLabel.vue
index a670078228..f84980913b 100644
--- a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuLabel.vue
+++ b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuLabel.vue
@@ -12,12 +12,7 @@ const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
- <DropdownMenuLabel
- data-slot="dropdown-menu-label"
- :data-inset="inset ? '' : undefined"
- v-bind="forwardedProps"
- :class="cn('text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:pl-7', props.class)"
- >
+ <DropdownMenuLabel data-slot="dropdown-menu-label" :data-inset="inset ? '' : undefined" v-bind="forwardedProps" :class="cn('text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:pl-7', props.class)">
<slot />
</DropdownMenuLabel>
</template>
diff --git a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuRadioItem.vue b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuRadioItem.vue
index 5ebaf4d34f..f364fe7846 100644
--- a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuRadioItem.vue
+++ b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuRadioItem.vue
@@ -37,10 +37,7 @@ function guardRepeatedClick(event: MouseEvent) {
)
"
>
- <span
- class="absolute right-2 flex items-center justify-center pointer-events-none"
- data-slot="dropdown-menu-radio-item-indicator"
- >
+ <span class="absolute right-2 flex items-center justify-center pointer-events-none" data-slot="dropdown-menu-radio-item-indicator">
<DropdownMenuItemIndicator>
<slot name="indicator-icon">
<CheckIcon />
diff --git a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuSeparator.vue b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuSeparator.vue
index 6f3568af8d..22a1a02775 100644
--- a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuSeparator.vue
+++ b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuSeparator.vue
@@ -15,9 +15,5 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <DropdownMenuSeparator
- data-slot="dropdown-menu-separator"
- v-bind="delegatedProps"
- :class="cn('bg-border -mx-1 my-1 h-px', props.class)"
- />
+ <DropdownMenuSeparator data-slot="dropdown-menu-separator" v-bind="delegatedProps" :class="cn('bg-border -mx-1 my-1 h-px', props.class)" />
</template>
diff --git a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuShortcut.vue b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuShortcut.vue
index aba386da96..06aa117498 100644
--- a/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuShortcut.vue
+++ b/apps/desktop/src/components/ui/dropdown-menu/DropdownMenuShortcut.vue
@@ -8,15 +8,7 @@ const props = defineProps<{
</script>
<template>
- <span
- data-slot="dropdown-menu-shortcut"
- :class="
- cn(
- 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ml-auto text-xs tracking-widest',
- props.class,
- )
- "
- >
+ <span data-slot="dropdown-menu-shortcut" :class="cn('text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ml-auto text-xs tracking-widest', props.class)">
<slot />
</span>
</template>
diff --git a/apps/desktop/src/components/ui/label/Label.vue b/apps/desktop/src/components/ui/label/Label.vue
index 2d472e0f3b..d018ab590d 100644
--- a/apps/desktop/src/components/ui/label/Label.vue
+++ b/apps/desktop/src/components/ui/label/Label.vue
@@ -11,16 +11,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <Label
- data-slot="label"
- v-bind="delegatedProps"
- :class="
- cn(
- 'gap-2 text-sm leading-none font-medium group-data-[disabled=true]:opacity-50 peer-disabled:opacity-50 flex items-center select-none group-data-[disabled=true]:pointer-events-none peer-disabled:cursor-not-allowed',
- props.class,
- )
- "
- >
+ <Label data-slot="label" v-bind="delegatedProps" :class="cn('gap-2 text-sm leading-none font-medium group-data-[disabled=true]:opacity-50 peer-disabled:opacity-50 flex items-center select-none group-data-[disabled=true]:pointer-events-none peer-disabled:cursor-not-allowed', props.class)">
<slot />
</Label>
</template>
diff --git a/apps/desktop/src/components/ui/scroll-area/ScrollArea.vue b/apps/desktop/src/components/ui/scroll-area/ScrollArea.vue
index 1d75e77d1a..022af0e17d 100644
--- a/apps/desktop/src/components/ui/scroll-area/ScrollArea.vue
+++ b/apps/desktop/src/components/ui/scroll-area/ScrollArea.vue
@@ -13,10 +13,7 @@ const delegatedProps = reactiveOmit(props, "class");
<template>
<ScrollAreaRoot data-slot="scroll-area" v-bind="delegatedProps" :class="cn('relative', props.class)">
- <ScrollAreaViewport
- data-slot="scroll-area-viewport"
- class="size-full overflow-auto rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
- >
+ <ScrollAreaViewport data-slot="scroll-area-viewport" class="size-full overflow-auto rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1">
<slot />
</ScrollAreaViewport>
<ScrollBar />
diff --git a/apps/desktop/src/components/ui/scroll-area/ScrollBar.vue b/apps/desktop/src/components/ui/scroll-area/ScrollBar.vue
index 5042bcf4fa..5b31c550f1 100644
--- a/apps/desktop/src/components/ui/scroll-area/ScrollBar.vue
+++ b/apps/desktop/src/components/ui/scroll-area/ScrollBar.vue
@@ -17,12 +17,7 @@ const delegatedProps = reactiveOmit(props, "class");
data-slot="scroll-area-scrollbar"
:data-orientation="orientation"
v-bind="delegatedProps"
- :class="
- cn(
- 'data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent flex touch-none p-px transition-colors select-none',
- props.class,
- )
- "
+ :class="cn('data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent flex touch-none p-px transition-colors select-none', props.class)"
>
<ScrollAreaThumb data-slot="scroll-area-thumb" class="rounded-full relative flex-1 bg-border" />
</ScrollAreaScrollbar>
diff --git a/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue b/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue
index 0088df3912..c525151421 100644
--- a/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue
+++ b/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue
@@ -49,9 +49,7 @@ const selectedLabel = computed(() => {
const filteredOptions = computed(() => filterDatabaseOptions(props.options, searchText.value, props.displayName));
const customOptionValue = computed(() => props.normalizeCustom(searchText.value.trim()));
-const canSelectCustom = computed(
- () => props.allowCustom && !!customOptionValue.value && !props.options.includes(customOptionValue.value),
-);
+const canSelectCustom = computed(() => props.allowCustom && !!customOptionValue.value && !props.options.includes(customOptionValue.value));
watch(open, async (value) => {
emit("update:open", value);
@@ -120,16 +118,7 @@ function handleKeydown(event: KeyboardEvent) {
<template>
<Popover v-model:open="open">
<PopoverTrigger as-child>
- <Button
- type="button"
- variant="ghost"
- :class="
- cn(
- 'h-6 w-auto max-w-56 justify-between gap-1 border-0 bg-transparent px-1 text-xs font-normal shadow-none hover:bg-muted/50 focus-visible:ring-0',
- triggerClass,
- )
- "
- >
+ <Button type="button" variant="ghost" :class="cn('h-6 w-auto max-w-56 justify-between gap-1 border-0 bg-transparent px-1 text-xs font-normal shadow-none hover:bg-muted/50 focus-visible:ring-0', triggerClass)">
<slot name="trigger-label" :value="modelValue" :label="selectedLabel" :loading="loading">
<span class="truncate">{{ loading ? loadingText : selectedLabel }}</span>
</slot>
@@ -139,14 +128,7 @@ function handleKeydown(event: KeyboardEvent) {
<PopoverContent align="end" :class="cn('w-52 gap-1 p-1.5', contentClass)">
<div class="flex items-center gap-1.5 rounded-sm border bg-background px-2">
<Search class="h-3 w-3 shrink-0 text-muted-foreground" />
- <Input
- ref="searchInput"
- :model-value="searchText"
- :placeholder="searchPlaceholder"
- class="h-6 border-0 px-0 text-sm shadow-none focus-visible:ring-0"
- @update:model-value="(value) => (searchText = String(value))"
- @keydown="handleKeydown"
- />
+ <Input ref="searchInput" :model-value="searchText" :placeholder="searchPlaceholder" class="h-6 border-0 px-0 text-sm shadow-none focus-visible:ring-0" @update:model-value="(value) => (searchText = String(value))" @keydown="handleKeydown" />
</div>
<div ref="listContainer" class="max-h-64 overflow-y-auto py-1">
<div v-if="loading" class="px-2 py-2 text-sm text-muted-foreground">
@@ -157,12 +139,7 @@ function handleKeydown(event: KeyboardEvent) {
v-for="(option, index) in filteredOptions"
:key="option"
type="button"
- :class="
- cn(
- 'flex h-8 w-full min-w-0 items-center gap-2 rounded-sm px-2 text-left text-sm hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none',
- index === highlightIndex && 'bg-accent text-accent-foreground',
- )
- "
+ :class="cn('flex h-8 w-full min-w-0 items-center gap-2 rounded-sm px-2 text-left text-sm hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none', index === highlightIndex && 'bg-accent text-accent-foreground')"
@click="selectOption(option)"
>
<Check :class="cn('h-3.5 w-3.5 shrink-0', option === modelValue ? 'opacity-100' : 'opacity-0')" />
@@ -190,12 +167,7 @@ function handleKeydown(event: KeyboardEvent) {
<button
v-else-if="canSelectCustom"
type="button"
- :class="
- cn(
- 'flex h-8 w-full min-w-0 items-center gap-2 rounded-sm px-2 text-left text-sm hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none',
- 0 === highlightIndex && 'bg-accent text-accent-foreground',
- )
- "
+ :class="cn('flex h-8 w-full min-w-0 items-center gap-2 rounded-sm px-2 text-left text-sm hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none', 0 === highlightIndex && 'bg-accent text-accent-foreground')"
@click="selectCustomOption"
>
<Check class="h-3.5 w-3.5 shrink-0 opacity-0" />
diff --git a/apps/desktop/src/components/ui/select/SelectContent.vue b/apps/desktop/src/components/ui/select/SelectContent.vue
index a47b73a85c..e2d81d9163 100644
--- a/apps/desktop/src/components/ui/select/SelectContent.vue
+++ b/apps/desktop/src/components/ui/select/SelectContent.vue
@@ -40,17 +40,13 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
:class="
cn(
'text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 min-w-36 rounded-lg ring-1 duration-100 data-[side=inline-start]:slide-in-from-right-2 data-[side=inline-end]:slide-in-from-left-2 cn-menu-translucent relative z-50 max-h-(--reka-select-content-available-height) origin-(--reka-select-content-transform-origin) overflow-x-hidden overflow-y-auto data-[align-trigger=true]:animate-none',
- position === 'popper' &&
- 'w-fit min-w-[var(--reka-select-trigger-width)] data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
+ position === 'popper' && 'w-fit min-w-[var(--reka-select-trigger-width)] data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
props.class,
)
"
>
<SelectScrollUpButton />
- <SelectViewport
- :data-position="position"
- :class="cn('data-[position=popper]:h-[var(--reka-select-trigger-height)] data-[position=popper]:w-full')"
- >
+ <SelectViewport :data-position="position" :class="cn('data-[position=popper]:h-[var(--reka-select-trigger-height)] data-[position=popper]:w-full')">
<slot />
</SelectViewport>
<SelectScrollDownButton />
diff --git a/apps/desktop/src/components/ui/select/SelectScrollDownButton.vue b/apps/desktop/src/components/ui/select/SelectScrollDownButton.vue
index 7329e8f48d..e0a140535a 100644
--- a/apps/desktop/src/components/ui/select/SelectScrollDownButton.vue
+++ b/apps/desktop/src/components/ui/select/SelectScrollDownButton.vue
@@ -15,16 +15,7 @@ const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
- <SelectScrollDownButton
- data-slot="select-scroll-down-button"
- v-bind="forwardedProps"
- :class="
- cn(
- 'bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*=size-])]:size-4',
- props.class,
- )
- "
- >
+ <SelectScrollDownButton data-slot="select-scroll-down-button" v-bind="forwardedProps" :class="cn('bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*=size-])]:size-4', props.class)">
<slot>
<ChevronDownIcon />
</slot>
diff --git a/apps/desktop/src/components/ui/select/SelectScrollUpButton.vue b/apps/desktop/src/components/ui/select/SelectScrollUpButton.vue
index aae9a236b7..9ef499b72b 100644
--- a/apps/desktop/src/components/ui/select/SelectScrollUpButton.vue
+++ b/apps/desktop/src/components/ui/select/SelectScrollUpButton.vue
@@ -15,16 +15,7 @@ const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
- <SelectScrollUpButton
- data-slot="select-scroll-up-button"
- v-bind="forwardedProps"
- :class="
- cn(
- 'bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*=size-])]:size-4',
- props.class,
- )
- "
- >
+ <SelectScrollUpButton data-slot="select-scroll-up-button" v-bind="forwardedProps" :class="cn('bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*=size-])]:size-4', props.class)">
<slot>
<ChevronUpIcon />
</slot>
diff --git a/apps/desktop/src/components/ui/select/SelectSeparator.vue b/apps/desktop/src/components/ui/select/SelectSeparator.vue
index e0b55d043b..3148122666 100644
--- a/apps/desktop/src/components/ui/select/SelectSeparator.vue
+++ b/apps/desktop/src/components/ui/select/SelectSeparator.vue
@@ -11,9 +11,5 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <SelectSeparator
- data-slot="select-separator"
- v-bind="delegatedProps"
- :class="cn('bg-border -mx-1 my-1 h-px pointer-events-none', props.class)"
- />
+ <SelectSeparator data-slot="select-separator" v-bind="delegatedProps" :class="cn('bg-border -mx-1 my-1 h-px pointer-events-none', props.class)" />
</template>
diff --git a/apps/desktop/src/components/ui/select/SelectTrigger.vue b/apps/desktop/src/components/ui/select/SelectTrigger.vue
index 46680c761a..2d55075543 100644
--- a/apps/desktop/src/components/ui/select/SelectTrigger.vue
+++ b/apps/desktop/src/components/ui/select/SelectTrigger.vue
@@ -7,10 +7,7 @@ import { ChevronDownIcon } from "@lucide/vue";
import { SelectIcon, SelectTrigger, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
-const props = withDefaults(
- defineProps<SelectTriggerProps & { class?: HTMLAttributes["class"]; size?: "sm" | "default" }>(),
- { size: "default" },
-);
+const props = withDefaults(defineProps<SelectTriggerProps & { class?: HTMLAttributes["class"]; size?: "sm" | "default" }>(), { size: "default" });
const delegatedProps = reactiveOmit(props, "class", "size");
const forwardedProps = useForwardProps(delegatedProps);
diff --git a/apps/desktop/src/components/ui/separator/Separator.vue b/apps/desktop/src/components/ui/separator/Separator.vue
index f3bbe0324c..1c61a31612 100644
--- a/apps/desktop/src/components/ui/separator/Separator.vue
+++ b/apps/desktop/src/components/ui/separator/Separator.vue
@@ -14,14 +14,5 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <Separator
- data-slot="separator"
- v-bind="delegatedProps"
- :class="
- cn(
- 'shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:self-stretch',
- props.class,
- )
- "
- />
+ <Separator data-slot="separator" v-bind="delegatedProps" :class="cn('shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:self-stretch', props.class)" />
</template>
diff --git a/apps/desktop/src/components/ui/sheet/SheetDescription.vue b/apps/desktop/src/components/ui/sheet/SheetDescription.vue
index 9a8eb2f243..f19883a34c 100644
--- a/apps/desktop/src/components/ui/sheet/SheetDescription.vue
+++ b/apps/desktop/src/components/ui/sheet/SheetDescription.vue
@@ -11,11 +11,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <DialogDescription
- data-slot="sheet-description"
- :class="cn('text-muted-foreground text-sm', props.class)"
- v-bind="delegatedProps"
- >
+ <DialogDescription data-slot="sheet-description" :class="cn('text-muted-foreground text-sm', props.class)" v-bind="delegatedProps">
<slot />
</DialogDescription>
</template>
diff --git a/apps/desktop/src/components/ui/sheet/SheetOverlay.vue b/apps/desktop/src/components/ui/sheet/SheetOverlay.vue
index 004abc4390..01b044b2c9 100644
--- a/apps/desktop/src/components/ui/sheet/SheetOverlay.vue
+++ b/apps/desktop/src/components/ui/sheet/SheetOverlay.vue
@@ -11,13 +11,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <DialogOverlay
- data-slot="sheet-overlay"
- :class="
- cn('bg-black/20 fixed inset-0 z-50 data-open:animate-in data-open:fade-in-0 data-open:duration-200', props.class)
- "
- v-bind="delegatedProps"
- >
+ <DialogOverlay data-slot="sheet-overlay" :class="cn('bg-black/20 fixed inset-0 z-50 data-open:animate-in data-open:fade-in-0 data-open:duration-200', props.class)" v-bind="delegatedProps">
<slot />
</DialogOverlay>
</template>
diff --git a/apps/desktop/src/components/ui/sheet/SheetTitle.vue b/apps/desktop/src/components/ui/sheet/SheetTitle.vue
index ce9aece81f..37e4d6a47c 100644
--- a/apps/desktop/src/components/ui/sheet/SheetTitle.vue
+++ b/apps/desktop/src/components/ui/sheet/SheetTitle.vue
@@ -11,11 +11,7 @@ const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
- <DialogTitle
- data-slot="sheet-title"
- :class="cn('text-foreground text-base font-medium cn-font-heading', props.class)"
- v-bind="delegatedProps"
- >
+ <DialogTitle data-slot="sheet-title" :class="cn('text-foreground text-base font-medium cn-font-heading', props.class)" v-bind="delegatedProps">
<slot />
</DialogTitle>
</template>
diff --git a/apps/desktop/src/components/ui/tabs/Tabs.vue b/apps/desktop/src/components/ui/tabs/Tabs.vue
index e2fa477d2b..3814fc23f0 100644
--- a/apps/desktop/src/components/ui/tabs/Tabs.vue
+++ b/apps/desktop/src/components/ui/tabs/Tabs.vue
@@ -13,13 +13,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
- <TabsRoot
- v-slot="slotProps"
- data-slot="tabs"
- :data-orientation="forwarded.orientation || 'horizontal'"
- v-bind="forwarded"
- :class="cn('gap-2 group/tabs flex data-horizontal:flex-col', props.class)"
- >
+ <TabsRoot v-slot="slotProps" data-slot="tabs" :data-orientation="forwarded.orientation || 'horizontal'" v-bind="forwarded" :class="cn('gap-2 group/tabs flex data-horizontal:flex-col', props.class)">
<slot v-bind="slotProps" />
</TabsRoot>
</template>
diff --git a/apps/desktop/src/components/ui/tabs/TabsList.vue b/apps/desktop/src/components/ui/tabs/TabsList.vue
index 96b805ff2b..ceac23d358 100644
--- a/apps/desktop/src/components/ui/tabs/TabsList.vue
+++ b/apps/desktop/src/components/ui/tabs/TabsList.vue
@@ -23,12 +23,7 @@ const delegatedProps = reactiveOmit(props, "class", "variant");
</script>
<template>
- <TabsList
- data-slot="tabs-list"
- :data-variant="variant"
- v-bind="delegatedProps"
- :class="cn(tabsListVariants({ variant }), props.class)"
- >
+ <TabsList data-slot="tabs-list" :data-variant="variant" v-bind="delegatedProps" :class="cn(tabsListVariants({ variant }), props.class)">
<slot />
</TabsList>
</template>
diff --git a/apps/desktop/src/components/ui/tabs/index.ts b/apps/desktop/src/components/ui/tabs/index.ts
index f117e14716..5d80b480e1 100644
--- a/apps/desktop/src/components/ui/tabs/index.ts
+++ b/apps/desktop/src/components/ui/tabs/index.ts
@@ -6,19 +6,16 @@ export { default as TabsContent } from "./TabsContent.vue";
export { default as TabsList } from "./TabsList.vue";
export { default as TabsTrigger } from "./TabsTrigger.vue";
-export const tabsListVariants = cva(
- "rounded-lg p-[3px] group-data-horizontal/tabs:h-8 data-[variant=line]:rounded-none group/tabs-list inline-flex w-fit select-none items-center justify-center text-muted-foreground group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col",
- {
- variants: {
- variant: {
- default: "bg-muted",
- line: "gap-1 bg-transparent",
- },
- },
- defaultVariants: {
- variant: "default",
+export const tabsListVariants = cva("rounded-lg p-[3px] group-data-horizontal/tabs:h-8 data-[variant=line]:rounded-none group/tabs-list inline-flex w-fit select-none items-center justify-center text-muted-foreground group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col", {
+ variants: {
+ variant: {
+ default: "bg-muted",
+ line: "gap-1 bg-transparent",
},
},
-);
+ defaultVariants: {
+ variant: "default",
+ },
+});
export type TabsListVariants = VariantProps<typeof tabsListVariants>;
diff --git a/apps/desktop/src/components/ui/tooltip/TooltipContent.vue b/apps/desktop/src/components/ui/tooltip/TooltipContent.vue
index 4a6e1a4dc6..167da296da 100644
--- a/apps/desktop/src/components/ui/tooltip/TooltipContent.vue
+++ b/apps/desktop/src/components/ui/tooltip/TooltipContent.vue
@@ -33,9 +33,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
>
<slot />
- <TooltipArrow
- class="size-2.5 rotate-45 rounded-[2px] bg-foreground fill-foreground z-50 translate-y-[calc(-50%_-_2px)]"
- />
+ <TooltipArrow class="size-2.5 rotate-45 rounded-[2px] bg-foreground fill-foreground z-50 translate-y-[calc(-50%_-_2px)]" />
</TooltipContent>
</TooltipPortal>
</template>
diff --git a/apps/desktop/src/composables/useCellDetailEditor.ts b/apps/desktop/src/composables/useCellDetailEditor.ts
index 2d1cc0da46..831f92b57f 100644
--- a/apps/desktop/src/composables/useCellDetailEditor.ts
+++ b/apps/desktop/src/composables/useCellDetailEditor.ts
@@ -1,34 +1,16 @@
import { shallowRef, onBeforeUnmount, type ShallowRef, createApp, watch } from "vue";
import { EditorState, Compartment } from "@codemirror/state";
-import {
- EditorView,
- keymap,
- drawSelection,
- dropCursor,
- highlightSpecialChars,
- highlightActiveLine,
-} from "@codemirror/view";
+import { EditorView, keymap, drawSelection, dropCursor, highlightSpecialChars, highlightActiveLine } from "@codemirror/view";
import { json } from "@codemirror/lang-json";
import { search as cmSearch } from "@codemirror/search";
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
import { bracketMatching } from "@codemirror/language";
import { trimmedSelectionLayer } from "@/lib/codemirrorTrimmedSelectionLayer";
-import {
- EDITOR_FONT_FAMILY_CSS_VAR,
- EDITOR_FONT_SIZE_CSS_VAR,
- cellDetailActiveLineColor,
- loadEditorTheme,
- editorFontTheme,
-} from "@/lib/editorThemes";
+import { EDITOR_FONT_FAMILY_CSS_VAR, EDITOR_FONT_SIZE_CSS_VAR, cellDetailActiveLineColor, loadEditorTheme, editorFontTheme } from "@/lib/editorThemes";
import { shortcutToCodeMirrorKey } from "@/lib/shortcutRegistry";
import { useSettingsStore } from "@/stores/settingsStore";
import { CELL_DETAIL_JSON_FORMAT_MAX_LENGTH, isJsonColumnType } from "@/lib/cellDetailPresentation";
-import {
- clampEditorFontSize,
- createEditorZoomCommitScheduler,
- fontSizeFromGestureScale,
- fontSizeFromWheelDelta,
-} from "@/lib/editorZoom";
+import { clampEditorFontSize, createEditorZoomCommitScheduler, fontSizeFromGestureScale, fontSizeFromWheelDelta } from "@/lib/editorZoom";
import i18n from "@/i18n";
import EditorSearchPanel from "@/components/editor/EditorSearchPanel.vue";
import type { EditorTheme } from "@/stores/settingsStore";
@@ -147,25 +129,19 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCel
zoomCommitScheduler.flush(liveFontSize);
}
- watch(
- [() => options.fontSize(), () => options.fontFamily(), () => options.editorTheme(), () => options.appAppearance()],
- async ([fontSize, fontFamily, editorTheme, appearance]) => {
- const editor = view.value;
- if (!editor || destroyed) return;
- if (!isGestureZooming && !zoomCommitScheduler.hasPendingCommit()) {
- liveFontSize = clampEditorFontSize(fontSize);
- }
- syncEditorFontCssVars(liveFontSize, fontFamily);
- const theme = await loadEditorTheme(editorTheme, appearance);
- if (!view.value || destroyed) return;
- view.value.dispatch({
- effects: [
- themeComp.reconfigure(theme),
- fontThemeComp.reconfigure(editorFontTheme(EditorView, liveFontSize, fontFamily, { scrollable: false })),
- ],
- });
- },
- );
+ watch([() => options.fontSize(), () => options.fontFamily(), () => options.editorTheme(), () => options.appAppearance()], async ([fontSize, fontFamily, editorTheme, appearance]) => {
+ const editor = view.value;
+ if (!editor || destroyed) return;
+ if (!isGestureZooming && !zoomCommitScheduler.hasPendingCommit()) {
+ liveFontSize = clampEditorFontSize(fontSize);
+ }
+ syncEditorFontCssVars(liveFontSize, fontFamily);
+ const theme = await loadEditorTheme(editorTheme, appearance);
+ if (!view.value || destroyed) return;
+ view.value.dispatch({
+ effects: [themeComp.reconfigure(theme), fontThemeComp.reconfigure(editorFontTheme(EditorView, liveFontSize, fontFamily, { scrollable: false }))],
+ });
+ });
async function create(parent: HTMLElement, initialValue: string, columnType?: string): Promise<void> {
if (destroyed) return;
diff --git a/apps/desktop/src/composables/useDataGridActions.ts b/apps/desktop/src/composables/useDataGridActions.ts
index 1d93ac43da..98fc09d3ef 100644
--- a/apps/desktop/src/composables/useDataGridActions.ts
+++ b/apps/desktop/src/composables/useDataGridActions.ts
@@ -23,23 +23,15 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
return quoteTableIdentifier(effectiveDatabaseTypeForConnection(config), name);
}
- function buildTableSql(
- tab: QueryTab,
- options: { orderBy?: string; limit?: number; offset?: number; whereInput?: string } = {},
- ): Promise<string> {
+ function buildTableSql(tab: QueryTab, options: { orderBy?: string; limit?: number; offset?: number; whereInput?: string } = {}): Promise<string> {
const config = connectionStore.getConfig(tab.connectionId);
const effectiveDbType = effectiveDatabaseTypeForConnection(config);
const tableMeta = tableMetaForDataTab(tab);
- const primaryKeys = tab.tableMeta
- ? editablePrimaryKeys(effectiveDbType, tab.tableMeta.columns)
- : (tableMeta?.primaryKeys ?? []);
+ const primaryKeys = tab.tableMeta ? editablePrimaryKeys(effectiveDbType, tab.tableMeta.columns) : (tableMeta?.primaryKeys ?? []);
if (tab.tableMeta && primaryKeys.join("\0") !== tab.tableMeta.primaryKeys.join("\0")) {
tab.tableMeta.primaryKeys = primaryKeys;
}
- const fallbackOrderColumns =
- effectiveDbType === "sqlserver" && !primaryKeys.length
- ? tableMeta?.columns.slice(0, 1).map((column) => column.name)
- : undefined;
+ const fallbackOrderColumns = effectiveDbType === "sqlserver" && !primaryKeys.length ? tableMeta?.columns.slice(0, 1).map((column) => column.name) : undefined;
const useRowId = usesSyntheticRowIdKey(effectiveDbType, primaryKeys);
return buildTableSelectSql({
databaseType: effectiveDbType,
@@ -61,14 +53,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
await queryStore.executeTabSql(tab.id, sql, { preserveResultDuringExecution: true });
}
- async function onReloadData(
- sql?: string,
- _searchText?: string,
- whereInput?: string,
- orderBy?: string,
- limit?: number,
- offset?: number,
- ) {
+ async function onReloadData(sql?: string, _searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) {
const tab = activeTab.value;
if (!tab) return;
if (tab.mode === "data" && tableMetaForDataTab(tab)) {
@@ -110,10 +95,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
const baseSql = tab.resultSortedSql ?? tab.resultBaseSql ?? tab.lastExecutedSql ?? tab.sql;
if (!baseSql.trim()) return;
const expectedNextOffset = (tab.resultPageOffset ?? 0) + (tab.resultPageLimit ?? limit);
- const sessionId =
- tab.result?.has_more && tab.result?.session_id && offset === expectedNextOffset && limit === tab.resultPageLimit
- ? tab.result.session_id
- : undefined;
+ const sessionId = tab.result?.has_more && tab.result?.session_id && offset === expectedNextOffset && limit === tab.resultPageLimit ? tab.result.session_id : undefined;
await queryStore.executeTabSql(tab.id, baseSql, {
resultBaseSql: tab.resultBaseSql ?? tab.sql,
resultSortedSql: tab.resultSortedSql,
@@ -146,9 +128,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
tab.whereInput = whereInput ?? "";
const config = connectionStore.getConfig(tab.connectionId);
const quotedColumn = quoteIdent(tab, column);
- const orderBy = direction
- ? `${config?.db_type === "neo4j" ? `n.${quotedColumn}` : quotedColumn} ${direction.toUpperCase()}`
- : undefined;
+ const orderBy = direction ? `${config?.db_type === "neo4j" ? `n.${quotedColumn}` : quotedColumn} ${direction.toUpperCase()}` : undefined;
const sql = await buildTableSql(tab, { orderBy, whereInput });
queryStore.updateSql(tab.id, sql);
await queryStore.executeTabSql(tab.id, sql, { preserveResultDuringExecution: true });
diff --git a/apps/desktop/src/composables/useDataGridColumnResize.ts b/apps/desktop/src/composables/useDataGridColumnResize.ts
index 9f7fb20fe3..92f36458c7 100644
--- a/apps/desktop/src/composables/useDataGridColumnResize.ts
+++ b/apps/desktop/src/composables/useDataGridColumnResize.ts
@@ -1,10 +1,6 @@
import { ref, computed, type ComputedRef, type Ref } from "vue";
import { useElementSize } from "@vueuse/core";
-import {
- calculateDataGridColumnWidth,
- DATA_GRID_COL_MIN_WIDTH,
- DATA_GRID_SAMPLE_ROWS,
-} from "@/lib/dataGridColumnWidth";
+import { calculateDataGridColumnWidth, DATA_GRID_COL_MIN_WIDTH, DATA_GRID_SAMPLE_ROWS } from "@/lib/dataGridColumnWidth";
type CellValue = string | number | boolean | null;
diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts
index 45f8e2c82d..b19d57f6f5 100644
--- a/apps/desktop/src/composables/useDataGridEditor.ts
+++ b/apps/desktop/src/composables/useDataGridEditor.ts
@@ -1,16 +1,4 @@
-import {
- ref,
- computed,
- nextTick,
- watch,
- getCurrentInstance,
- onActivated,
- onBeforeUnmount,
- onDeactivated,
- onMounted,
- type ComputedRef,
- type Ref,
-} from "vue";
+import { ref, computed, nextTick, watch, getCurrentInstance, onActivated, onBeforeUnmount, onDeactivated, onMounted, type ComputedRef, type Ref } from "vue";
import * as api from "@/lib/api";
import type { CellValue } from "@/lib/cellValue";
import { coerceDataGridCellValue, dataGridCellEditorText } from "@/lib/dataGridCellCoercion";
@@ -60,16 +48,7 @@ export interface UseDataGridEditorOptions {
sourceColumns?: ComputedRef<Array<string | undefined> | undefined>;
canEditExistingRows?: ComputedRef<boolean>;
onExecuteSql: ComputedRef<((sql: string) => Promise<void>) | undefined>;
- customSave?: ComputedRef<
- | ((changes: {
- dirtyRows: Map<number, Map<number, CellValue>>;
- newRows: CellValue[][];
- deletedRows: Set<number>;
- columns: string[];
- rows: CellValue[][];
- }) => Promise<void>)
- | undefined
- >;
+ customSave?: ComputedRef<((changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<void>) | undefined>;
sql: ComputedRef<string | undefined>;
searchText: Ref<string>;
whereFilterInput: Ref<string>;
@@ -82,15 +61,7 @@ export interface UseDataGridEditorOptions {
currentPage: Ref<number>;
cacheKey?: ComputedRef<string | undefined>;
emit: {
- (
- event: "reload",
- sql?: string,
- searchText?: string,
- whereInput?: string,
- orderBy?: string,
- limit?: number,
- offset?: number,
- ): void;
+ (event: "reload", sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number): void;
};
}
@@ -203,12 +174,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const isSaving = ref(false);
const saveError = ref("");
- const useTransaction = computed(
- () =>
- editable.value &&
- supportsDataGridTransaction(databaseType.value) &&
- (!!customSave?.value || (!!connectionId.value && !!database.value && !!tableMeta.value)),
- );
+ const useTransaction = computed(() => editable.value && supportsDataGridTransaction(databaseType.value) && (!!customSave?.value || (!!connectionId.value && !!database.value && !!tableMeta.value)));
if (hasPendingChanges.value && useTransaction.value) {
transactionActive.value = true;
@@ -543,9 +509,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function clonedRowData(item: RowItem): CellValue[] {
- const columnInfoByName = new Map(
- (tableMeta.value?.columns ?? []).map((column) => [column.name.toLowerCase(), column]),
- );
+ const columnInfoByName = new Map((tableMeta.value?.columns ?? []).map((column) => [column.name.toLowerCase(), column]));
return item.data.map((val, i) => {
const columnName = result.value.columns[i];
const columnInfo = columnInfoByName.get(columnName.toLowerCase());
@@ -558,9 +522,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (databaseType.value === "neo4j" && columnName === DBX_NEO4J_ELEMENT_ID_COLUMN) return true;
const extra = columnInfo?.extra ?? "";
const columnDefault = columnInfo?.column_default ?? "";
- return (
- /\b(auto_increment|autoincrement|identity|generated)\b/i.test(extra) || /\bnextval\s*\(/i.test(columnDefault)
- );
+ return /\b(auto_increment|autoincrement|identity|generated)\b/i.test(extra) || /\bnextval\s*\(/i.test(columnDefault);
}
function cloneRow(rowId: number) {
@@ -663,9 +625,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
columns: result.value.columns,
sourceColumns: sourceColumns.value,
rows: result.value.rows,
- dirtyRows: [...dirtyRows.value.entries()].map(
- ([rowIndex, changes]) => [rowIndex, [...changes.entries()]] as [number, Array<[number, CellValue]>],
- ),
+ dirtyRows: [...dirtyRows.value.entries()].map(([rowIndex, changes]) => [rowIndex, [...changes.entries()]] as [number, Array<[number, CellValue]>]),
deletedRows: [...deletedRows.value],
newRows: newRows.value,
};
@@ -677,20 +637,11 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function dataChangeOperation() {
- const operations = [
- newRows.value.length > 0 ? "INSERT" : "",
- dirtyRows.value.size > 0 ? "UPDATE" : "",
- deletedRows.value.size > 0 ? "DELETE" : "",
- ].filter(Boolean);
+ const operations = [newRows.value.length > 0 ? "INSERT" : "", dirtyRows.value.size > 0 ? "UPDATE" : "", deletedRows.value.size > 0 ? "DELETE" : ""].filter(Boolean);
return operations.length === 1 ? operations[0] : "DATA CHANGE";
}
- async function recordDataGridHistory(
- statements: string[],
- rollbackStatements: string[],
- elapsed: number,
- historyResult?: { affected_rows?: number; success?: boolean; error?: string },
- ) {
+ async function recordDataGridHistory(statements: string[], rollbackStatements: string[], elapsed: number, historyResult?: { affected_rows?: number; success?: boolean; error?: string }) {
if (!connectionId.value || !database.value || !tableMeta.value) return;
const connName = connectionStore.getConfig(connectionId.value)?.name || "";
const success = historyResult?.success ?? true;
@@ -721,12 +672,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
});
}
- async function recordFailedDataGridHistory(
- statements: string[],
- rollbackStatements: string[],
- start: number,
- error: unknown,
- ) {
+ async function recordFailedDataGridHistory(statements: string[], rollbackStatements: string[], start: number, error: unknown) {
const message = normalizeDataGridSaveError(databaseType.value, error);
try {
await recordDataGridHistory(statements, rollbackStatements, Date.now() - start, {
@@ -740,15 +686,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function reloadCurrentData() {
- options.emit(
- "reload",
- sql.value,
- searchText.value,
- options.currentWhereInput.value,
- orderByInput.value.trim() || undefined,
- pageSize.value,
- (currentPage.value - 1) * pageSize.value,
- );
+ options.emit("reload", sql.value, searchText.value, options.currentWhereInput.value, orderByInput.value.trim() || undefined, pageSize.value, (currentPage.value - 1) * pageSize.value);
}
async function saveChanges() {
@@ -808,21 +746,14 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
let apiResult: { affected_rows?: number } | undefined;
console.info("[DBX][dataGrid:save-statements]", {
databaseType: databaseType.value,
- table: tableMeta.value
- ? [tableMeta.value.schema, tableMeta.value.tableName].filter(Boolean).join(".")
- : undefined,
+ table: tableMeta.value ? [tableMeta.value.schema, tableMeta.value.tableName].filter(Boolean).join(".") : undefined,
statements: stmts,
rollbackStatements: rollbackStmts,
});
if (useTransaction.value && connectionId.value && database.value) {
try {
- apiResult = await api.executeInTransaction(
- connectionId.value,
- database.value,
- stmts,
- preparedSave?.executionSchema,
- );
+ apiResult = await api.executeInTransaction(connectionId.value, database.value, stmts, preparedSave?.executionSchema);
} catch (e: any) {
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, e);
isSaving.value = false;
diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts
index 152a48aa06..dc7107583c 100644
--- a/apps/desktop/src/composables/useDataGridExport.ts
+++ b/apps/desktop/src/composables/useDataGridExport.ts
@@ -2,23 +2,12 @@ import { computed, ref, type ComputedRef, type Ref } from "vue";
import { useI18n } from "vue-i18n";
import { isTauriRuntime } from "@/lib/tauriRuntime";
import * as api from "@/lib/api";
-import {
- formatSelectionAsCsv,
- formatSelectionAsJson,
- formatSelectionAsSqlInList,
- formatSelectionAsTsv,
- type CellSelectionRange,
- type SelectionData,
-} from "@/lib/gridSelection";
+import { formatSelectionAsCsv, formatSelectionAsJson, formatSelectionAsSqlInList, formatSelectionAsTsv, type CellSelectionRange, type SelectionData } from "@/lib/gridSelection";
import { useToast } from "@/composables/useToast";
import { displayCellValue, type CellValue } from "@/lib/cellValue";
import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/actionActivation";
import { copyToClipboard } from "@/lib/clipboard";
-import {
- buildDataGridCopyInsertStatement,
- buildDataGridCopyUpdateStatements,
- type DataGridTableMeta,
-} from "@/lib/dataGridSql";
+import { buildDataGridCopyInsertStatement, buildDataGridCopyUpdateStatements, type DataGridTableMeta } from "@/lib/dataGridSql";
import { formatSqlInsert } from "@/lib/exportFormats";
import { uuid } from "@/lib/utils";
import type { DatabaseType, QueryResult } from "@/types/database";
@@ -51,9 +40,7 @@ export interface UseDataGridExportOptions {
hasCellSelection: ComputedRef<boolean>;
selectedCells: ComputedRef<SelectionData>;
selectedRange: ComputedRef<CellSelectionRange | null>;
- contextCell:
- | Ref<{ rowId: number; rowIndex: number; col: number } | null>
- | ComputedRef<{ rowId: number; rowIndex: number; col: number } | null>;
+ contextCell: Ref<{ rowId: number; rowIndex: number; col: number } | null> | ComputedRef<{ rowId: number; rowIndex: number; col: number } | null>;
getRowItem: (rowId: number) => RowItem | undefined;
selectedRowIds: Ref<Set<number>> | ComputedRef<Set<number>>;
hasRowSelection: ComputedRef<boolean>;
@@ -446,9 +433,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const saveColumns = effectiveColumns(sourceColumns.value, columns.value);
const primaryKeySet = new Set(tableMeta.value.primaryKeys.map(normalizeColumnName));
const insertableCount = saveColumns.filter(Boolean).length;
- const insertColumnsCount = saveColumns.filter(
- (column) => column && !primaryKeySet.has(normalizeColumnName(column)),
- ).length;
+ const insertColumnsCount = saveColumns.filter((column) => column && !primaryKeySet.has(normalizeColumnName(column))).length;
return insertColumnsCount > 0 && insertColumnsCount < insertableCount;
});
@@ -616,12 +601,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
rowsExported: result.rows.length,
};
}
- await api.exportQueryResultXlsx(
- outputPath,
- tableMeta.value?.tableName || "Export",
- result.columns,
- result.rows,
- );
+ await api.exportQueryResultXlsx(outputPath, tableMeta.value?.tableName || "Export", result.columns, result.rows);
if (needsFullExport && exportProgressState) {
exportProgressState.value = {
...exportProgressState.value,
@@ -644,26 +624,14 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
});
}
- async function exportFullTableDataViaBackend(
- format: "csv" | "xlsx" | "json" | "markdown" | "sql",
- rowIds?: number[],
- ): Promise<boolean> {
+ async function exportFullTableDataViaBackend(format: "csv" | "xlsx" | "json" | "markdown" | "sql", rowIds?: number[]): Promise<boolean> {
const meta = tableMeta.value;
if (rowIds?.length || context.value !== "table-data" || !meta || !connectionId.value || !database.value) {
return false;
}
const extension = format === "markdown" ? "md" : format;
- const filterName =
- format === "csv"
- ? "CSV"
- : format === "xlsx"
- ? "Excel"
- : format === "json"
- ? "JSON"
- : format === "markdown"
- ? "Markdown"
- : "SQL";
+ const filterName = format === "csv" ? "CSV" : format === "xlsx" ? "Excel" : format === "json" ? "JSON" : format === "markdown" ? "Markdown" : "SQL";
let outputPath = `${meta.tableName || "export"}.${extension}`;
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
@@ -756,9 +724,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
rows: CellValue[][];
} {
const exportColumns = tableMeta.value ? effectiveColumns(sourceColumns.value, result.columns) : result.columns;
- const columnIndexes = exportColumns
- .map((column, index) => ({ column, index }))
- .filter((item): item is { column: string; index: number } => !!item.column);
+ const columnIndexes = exportColumns.map((column, index) => ({ column, index })).filter((item): item is { column: string; index: number } => !!item.column);
return {
columns: columnIndexes.map((item) => item.column),
columnTypes: tableMeta.value ? columnIndexes.map((item) => columnTypes.value?.[item.index]) : undefined,
@@ -817,10 +783,7 @@ async function saveTextFile(content: string, defaultFileName: string, filterName
URL.revokeObjectURL(url);
}
-function effectiveColumns(
- sourceColumns: Array<string | undefined> | undefined,
- columns: string[],
-): Array<string | undefined> {
+function effectiveColumns(sourceColumns: Array<string | undefined> | undefined, columns: string[]): Array<string | undefined> {
if (!sourceColumns || sourceColumns.length !== columns.length) return columns;
return sourceColumns;
}
diff --git a/apps/desktop/src/composables/useDataGridSelection.ts b/apps/desktop/src/composables/useDataGridSelection.ts
index a8144c612a..0a7e706698 100644
--- a/apps/desktop/src/composables/useDataGridSelection.ts
+++ b/apps/desktop/src/composables/useDataGridSelection.ts
@@ -1,16 +1,5 @@
import { ref, computed, type ComputedRef, type Ref } from "vue";
-import {
- allCellsSelectionRange,
- extractColumnsSelection,
- extractSelection,
- isCellInSelection,
- normalizeSelectionRange,
- normalizeSelectedColumnIndexes,
- rowSelectionRange,
- type CellPosition,
- type CellSelectionRange,
- type SelectionData,
-} from "@/lib/gridSelection";
+import { allCellsSelectionRange, extractColumnsSelection, extractSelection, isCellInSelection, normalizeSelectionRange, normalizeSelectedColumnIndexes, rowSelectionRange, type CellPosition, type CellSelectionRange, type SelectionData } from "@/lib/gridSelection";
type CellValue = string | number | boolean | null;
@@ -101,9 +90,7 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
}
function selectColumns(startCol: number, endCol: number, options?: { merge?: boolean }) {
- const normalizedColumns = normalizeSelectedColumnIndexes(
- Array.from({ length: Math.abs(endCol - startCol) + 1 }, (_, index) => Math.min(startCol, endCol) + index),
- );
+ const normalizedColumns = normalizeSelectedColumnIndexes(Array.from({ length: Math.abs(endCol - startCol) + 1 }, (_, index) => Math.min(startCol, endCol) + index));
if (normalizedColumns.length === 0 || displayItems.value.length <= 0) return;
clearRowSelection();
selectionAnchor.value = null;
@@ -240,8 +227,7 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
}
function cellIsSelected(rowIndex: number, colIndex: number): boolean {
- if (hasColumnSelection.value)
- return rowIndex >= 0 && rowIndex < displayItems.value.length && selectedColumnIndexes.value.has(colIndex);
+ if (hasColumnSelection.value) return rowIndex >= 0 && rowIndex < displayItems.value.length && selectedColumnIndexes.value.has(colIndex);
return isCellInSelection(rowIndex, colIndex, selectedRange.value);
}
@@ -249,12 +235,7 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
if (hasColumnSelection.value) return selectedColumnIndexes.value.has(colIndex);
const range = selectedRange.value;
if (!range) return false;
- return (
- range.startCol <= colIndex &&
- range.endCol >= colIndex &&
- range.startRow === 0 &&
- range.endRow >= displayItems.value.length - 1
- );
+ return range.startCol <= colIndex && range.endCol >= colIndex && range.startRow === 0 && range.endRow >= displayItems.value.length - 1;
}
function selectedRangeStart(): CellPosition | null {
diff --git a/apps/desktop/src/composables/useDatabaseOptions.ts b/apps/desktop/src/composables/useDatabaseOptions.ts
index cc520899d2..1497bba441 100644
--- a/apps/desktop/src/composables/useDatabaseOptions.ts
+++ b/apps/desktop/src/composables/useDatabaseOptions.ts
@@ -5,10 +5,7 @@ import { usesTreeSchemaMode } from "@/lib/databaseCapabilities";
import type { ConnectionConfig } from "@/types/database";
import * as api from "@/lib/api";
-export function databaseOptionsForConnection(
- databaseNames: string[],
- connection: Pick<ConnectionConfig, "db_type" | "visible_databases"> | undefined,
-): string[] {
+export function databaseOptionsForConnection(databaseNames: string[], connection: Pick<ConnectionConfig, "db_type" | "visible_databases"> | undefined): string[] {
const names = filterDatabaseNamesForConnection(databaseNames, connection);
if (names.length === 0 && usesTreeSchemaMode(connection?.db_type)) return [""];
return names;
@@ -34,10 +31,7 @@ export function useDatabaseOptions() {
connection,
);
} else if (connection.db_type === "mongodb") {
- databaseOptions.value[connectionId] = filterDatabaseNamesForConnection(
- await api.mongoListDatabases(connectionId),
- connection,
- );
+ databaseOptions.value[connectionId] = filterDatabaseNamesForConnection(await api.mongoListDatabases(connectionId), connection);
} else {
const dbs = await api.listDatabases(connectionId);
databaseOptions.value[connectionId] = databaseOptionsForConnection(
diff --git a/apps/desktop/src/composables/useDialogSources.ts b/apps/desktop/src/composables/useDialogSources.ts
index 383c272a8b..d72f7e183b 100644
--- a/apps/desktop/src/composables/useDialogSources.ts
+++ b/apps/desktop/src/composables/useDialogSources.ts
@@ -200,8 +200,7 @@ export function useDialogSources() {
showConfigPassphraseDialog.value = false;
toast(t("configExport.exportSuccess"), 2000);
} catch (e: any) {
- configPassphraseError.value =
- e?.message === "crypto_unavailable" ? t("configExport.cryptoUnavailable") : e?.message || String(e);
+ configPassphraseError.value = e?.message === "crypto_unavailable" ? t("configExport.cryptoUnavailable") : e?.message || String(e);
}
}
@@ -253,12 +252,7 @@ export function useDialogSources() {
showImportLayoutConfirm.value = true;
}
} catch (e: any) {
- configPassphraseError.value =
- e?.message === "wrong_passphrase"
- ? t("configExport.wrongPassphrase")
- : e?.message === "crypto_unavailable"
- ? t("configExport.cryptoUnavailable")
- : e?.message || String(e);
+ configPassphraseError.value = e?.message === "wrong_passphrase" ? t("configExport.wrongPassphrase") : e?.message === "crypto_unavailable" ? t("configExport.cryptoUnavailable") : e?.message || String(e);
}
}
diff --git a/apps/desktop/src/composables/useExportTracker.ts b/apps/desktop/src/composables/useExportTracker.ts
index ec6d501bf8..043f1ef4c7 100644
--- a/apps/desktop/src/composables/useExportTracker.ts
+++ b/apps/desktop/src/composables/useExportTracker.ts
@@ -17,9 +17,7 @@ const taskMap = reactive<Map<string, ExportTask>>(new Map());
export function useExportTracker() {
const tasks = computed(() => Array.from(taskMap.values()));
- const activeCount = computed(
- () => tasks.value.filter((t) => t.status === "Running" || t.status === "Writing").length,
- );
+ const activeCount = computed(() => tasks.value.filter((t) => t.status === "Running" || t.status === "Writing").length);
const hasActive = computed(() => activeCount.value > 0);
diff --git a/apps/desktop/src/composables/useFlatTree.ts b/apps/desktop/src/composables/useFlatTree.ts
index f1aadeffed..5e3af8d401 100644
--- a/apps/desktop/src/composables/useFlatTree.ts
+++ b/apps/desktop/src/composables/useFlatTree.ts
@@ -34,13 +34,7 @@ export function shouldAutoScrollExpandedTreeNode(type: TreeNodeType): boolean {
return type !== "connection" && type !== "connection-group";
}
-export function scrollTopForExpandedTreeNode(options: {
- expandedIndex: number;
- insertedRowCount: number;
- currentScrollTop: number;
- viewportHeight: number;
- rowHeight?: number;
-}): number {
+export function scrollTopForExpandedTreeNode(options: { expandedIndex: number; insertedRowCount: number; currentScrollTop: number; viewportHeight: number; rowHeight?: number }): number {
const rowHeight = options.rowHeight ?? SIDEBAR_TREE_ROW_HEIGHT;
if (options.expandedIndex < 0 || options.insertedRowCount <= 0 || options.viewportHeight <= 0) {
return options.currentScrollTop;
diff --git a/apps/desktop/src/composables/useNavigationTargets.ts b/apps/desktop/src/composables/useNavigationTargets.ts
index abacd96dd3..4024da5a87 100644
--- a/apps/desktop/src/composables/useNavigationTargets.ts
+++ b/apps/desktop/src/composables/useNavigationTargets.ts
@@ -26,9 +26,7 @@ async function openTableTarget(target: NavigationTarget) {
const tabTitle = target.schema ? `${target.schema}.${target.tableName}` : target.tableName;
const tabId = (() => {
if (settingsStore.editorSettings.reuseDataTab) {
- const existing = queryStore.tabs.find(
- (tab) => tab.mode === "data" && tab.connectionId === target.connectionId && tab.database === target.database,
- );
+ const existing = queryStore.tabs.find((tab) => tab.mode === "data" && tab.connectionId === target.connectionId && tab.database === target.database);
if (existing) {
existing.title = tabTitle;
existing.schema = target.schema;
@@ -110,17 +108,13 @@ async function openTableTarget(target: NavigationTarget) {
}
}
if (dataResult.status === "rejected") throw dataResult.reason;
- if (columnsResult.status === "rejected")
- console.error("[DBX] ERROR fetching table metadata:", columnsResult.reason);
+ if (columnsResult.status === "rejected") console.error("[DBX] ERROR fetching table metadata:", columnsResult.reason);
} catch (e: any) {
queryStore.setErrorResult(tabId, e);
}
}
-export function useNavigationTargets(dialogs: {
- showFieldLineageDialog: { value: boolean };
- showDatabaseSearchDialog: { value: boolean };
-}) {
+export function useNavigationTargets(dialogs: { showFieldLineageDialog: { value: boolean }; showDatabaseSearchDialog: { value: boolean } }) {
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
@@ -134,40 +128,20 @@ export function useNavigationTargets(dialogs: {
await openTableTarget(target);
}
- async function onStructureEditorSaved(
- reloadData: () => Promise<void>,
- toast: (msg: string, duration?: number) => void,
- context: { connectionId: string; database: string; schema?: string; tableName: string },
- commentChanged?: boolean,
- ) {
+ async function onStructureEditorSaved(reloadData: () => Promise<void>, toast: (msg: string, duration?: number) => void, context: { connectionId: string; database: string; schema?: string; tableName: string }, commentChanged?: boolean) {
if (!context.tableName) {
try {
- await connectionStore.refreshObjectListTreeNode(
- context.connectionId,
- context.database,
- context.schema || undefined,
- );
+ await connectionStore.refreshObjectListTreeNode(context.connectionId, context.database, context.schema || undefined);
} catch {}
return;
}
if (commentChanged) {
try {
- await connectionStore.refreshObjectListTreeNode(
- context.connectionId,
- context.database,
- context.schema || undefined,
- );
+ await connectionStore.refreshObjectListTreeNode(context.connectionId, context.database, context.schema || undefined);
} catch {}
}
queryStore.invalidateTableStructure(context.connectionId, context.database, context.schema, context.tableName);
- const matchingDataTabs = queryStore.tabs.filter(
- (tab) =>
- tab.mode === "data" &&
- tab.connectionId === context.connectionId &&
- tab.database === context.database &&
- tab.tableMeta?.tableName === context.tableName &&
- (tab.tableMeta.schema || "") === (context.schema || ""),
- );
+ const matchingDataTabs = queryStore.tabs.filter((tab) => tab.mode === "data" && tab.connectionId === context.connectionId && tab.database === context.database && tab.tableMeta?.tableName === context.tableName && (tab.tableMeta.schema || "") === (context.schema || ""));
for (const tab of matchingDataTabs) {
try {
const connection = connectionStore.getConfig(tab.connectionId);
diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.ts
index 47342c00fb..abe83878ba 100644
--- a/apps/desktop/src/composables/useSqlExecution.ts
+++ b/apps/desktop/src/composables/useSqlExecution.ts
@@ -32,13 +32,7 @@ function primarySqlOperation(sql: string): string {
return statement?.match(/^([a-z]+)/i)?.[1]?.toUpperCase() || "SQL";
}
-export function useSqlExecution(deps: {
- activeTab: ComputedRef<QueryTab | undefined>;
- activeConnection: ComputedRef<ConnectionConfig | undefined>;
- executableSql: ComputedRef<string>;
- resolveExecutableSql?: () => Promise<string>;
- activeOutputView: Ref<"result" | "summary" | "explain" | "chart">;
-}) {
+export function useSqlExecution(deps: { activeTab: ComputedRef<QueryTab | undefined>; activeConnection: ComputedRef<ConnectionConfig | undefined>; executableSql: ComputedRef<string>; resolveExecutableSql?: () => Promise<string>; activeOutputView: Ref<"result" | "summary" | "explain" | "chart"> }) {
const { t } = useI18n();
const queryStore = useQueryStore();
const historyStore = useHistoryStore();
diff --git a/apps/desktop/src/composables/useTabScroll.ts b/apps/desktop/src/composables/useTabScroll.ts
index f3248193c9..34fa07bac4 100644
--- a/apps/desktop/src/composables/useTabScroll.ts
+++ b/apps/desktop/src/composables/useTabScroll.ts
@@ -68,10 +68,7 @@ export function useTabScroll(tabsContainerRef: Ref<HTMLElement | null>) {
const thumbWidthPx = dragState.trackRect.width * (scrollThumbWidthPercent.value / 100);
const maxThumbLeftPx = Math.max(1, dragState.trackRect.width - thumbWidthPx);
- const thumbLeftPx = Math.min(
- maxThumbLeftPx,
- Math.max(0, clientX - dragState.trackRect.left - dragState.thumbOffsetPx),
- );
+ const thumbLeftPx = Math.min(maxThumbLeftPx, Math.max(0, clientX - dragState.trackRect.left - dragState.thumbOffsetPx));
el.scrollLeft = (thumbLeftPx / maxThumbLeftPx) * maxScrollLeft;
updateScrollButtons();
}
diff --git a/apps/desktop/src/composables/useTauriEvents.ts b/apps/desktop/src/composables/useTauriEvents.ts
index 423a2f2ddf..86dc779ae3 100644
--- a/apps/desktop/src/composables/useTauriEvents.ts
+++ b/apps/desktop/src/composables/useTauriEvents.ts
@@ -2,12 +2,7 @@ import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import type { NavigationTarget } from "@/composables/useNavigationTargets";
-export function useTauriEvents(deps: {
- openTableTarget: (target: NavigationTarget) => Promise<void>;
- openSqlFilePath: (path: string) => Promise<void>;
- openDbFilePath: (path: string) => Promise<void>;
- openConnectionDeepLink: (url: string) => Promise<void>;
-}) {
+export function useTauriEvents(deps: { openTableTarget: (target: NavigationTarget) => Promise<void>; openSqlFilePath: (path: string) => Promise<void>; openDbFilePath: (path: string) => Promise<void>; openConnectionDeepLink: (url: string) => Promise<void> }) {
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
const unlistenHandles: Array<() => void> = [];
@@ -23,29 +18,26 @@ export function useTauriEvents(deps: {
function setupTauriListeners() {
import("@tauri-apps/api/event")
.then(({ listen }) => {
- listen<{ connection_id: string; database: string; schema?: string; table: string }>(
- "mcp-open-table",
- async (event) => {
- try {
- const { connection_id, database, schema, table } = event.payload;
- if (!connectionStore.connections.length) await connectionStore.initFromDisk();
- const config = connectionStore.getConfig(connection_id);
- if (!config) return;
- connectionStore.activeConnectionId = connection_id;
- await connectionStore.ensureConnected(connection_id);
- if (config.db_type === "redis") {
- queryStore.createTab(connection_id, database || "0", `db${database || "0"}`, "redis");
- } else if (config.db_type === "mongodb") {
- queryStore.createTab(connection_id, database, table, "mongo");
- } else {
- deps.openTableTarget({ connectionId: connection_id, database, schema, tableName: table });
- }
- focusCurrentWindow();
- } catch (e) {
- console.error("[DBX] mcp-open-table error:", e);
+ listen<{ connection_id: string; database: string; schema?: string; table: string }>("mcp-open-table", async (event) => {
+ try {
+ const { connection_id, database, schema, table } = event.payload;
+ if (!connectionStore.connections.length) await connectionStore.initFromDisk();
+ const config = connectionStore.getConfig(connection_id);
+ if (!config) return;
+ connectionStore.activeConnectionId = connection_id;
+ await connectionStore.ensureConnected(connection_id);
+ if (config.db_type === "redis") {
+ queryStore.createTab(connection_id, database || "0", `db${database || "0"}`, "redis");
+ } else if (config.db_type === "mongodb") {
+ queryStore.createTab(connection_id, database, table, "mongo");
+ } else {
+ deps.openTableTarget({ connectionId: connection_id, database, schema, tableName: table });
}
- },
- ).then((unlisten) => unlistenHandles.push(unlisten));
+ focusCurrentWindow();
+ } catch (e) {
+ console.error("[DBX] mcp-open-table error:", e);
+ }
+ }).then((unlisten) => unlistenHandles.push(unlisten));
listen("mcp-reload-connections", async () => {
try {
diff --git a/apps/desktop/src/composables/useTheme.ts b/apps/desktop/src/composables/useTheme.ts
index 8753610d09..903308a1c9 100644
--- a/apps/desktop/src/composables/useTheme.ts
+++ b/apps/desktop/src/composables/useTheme.ts
@@ -1,11 +1,5 @@
import { computed, ref } from "vue";
-import {
- APP_THEME_STORAGE_KEY,
- getTauriThemeForMode,
- normalizeAppThemeMode,
- resolveAppThemeAppearance,
- type AppThemeMode,
-} from "@/lib/appTheme";
+import { APP_THEME_STORAGE_KEY, getTauriThemeForMode, normalizeAppThemeMode, resolveAppThemeAppearance, type AppThemeMode } from "@/lib/appTheme";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/safeStorage";
import { isTauriRuntime } from "@/lib/tauriRuntime";
diff --git a/apps/desktop/src/i18n/backend-errors.ts b/apps/desktop/src/i18n/backend-errors.ts
index 45f8e4da5a..35b49a2b1b 100644
--- a/apps/desktop/src/i18n/backend-errors.ts
+++ b/apps/desktop/src/i18n/backend-errors.ts
@@ -3,15 +3,9 @@ import type { ComposerTranslation } from "vue-i18n";
const patterns: [RegExp, string][] = [
[/^(.+?) driver is not installed\. Please install it from the Driver Manager\.$/, "connection.driverNotInstalled"],
[/^JRE (.+?) runtime is not installed\. Please install it from the Driver Manager\.$/, "connection.jreNotInstalled"],
- [
- /^System Java runtime was not found on PATH\. Please install Java or choose a custom Java executable\.$/,
- "connection.systemJavaNotFound",
- ],
+ [/^System Java runtime was not found on PATH\. Please install Java or choose a custom Java executable\.$/, "connection.systemJavaNotFound"],
[/^Custom Java runtime path is empty\. Please choose a Java executable\.$/, "connection.customJavaPathEmpty"],
- [
- /^JDBC plugin is not installed\. Install the optional JDBC plugin to use this connection\.$/,
- "connection.jdbcPluginNotInstalled",
- ],
+ [/^JDBC plugin is not installed\. Install the optional JDBC plugin to use this connection\.$/, "connection.jdbcPluginNotInstalled"],
];
const paramNames: Record<string, string> = {
diff --git a/apps/desktop/src/i18n/index.ts b/apps/desktop/src/i18n/index.ts
index 00343819a0..916bb546df 100644
--- a/apps/desktop/src/i18n/index.ts
+++ b/apps/desktop/src/i18n/index.ts
@@ -31,12 +31,7 @@ export function localeFromLanguageTag(value: string | null | undefined): Locale
if (!value) return null;
const normalized = value.replace("_", "-").toLowerCase();
if (normalized === "zh" || normalized.startsWith("zh-")) {
- if (
- normalized.includes("hant") ||
- normalized.startsWith("zh-tw") ||
- normalized.startsWith("zh-hk") ||
- normalized.startsWith("zh-mo")
- ) {
+ if (normalized.includes("hant") || normalized.startsWith("zh-tw") || normalized.startsWith("zh-hk") || normalized.startsWith("zh-mo")) {
return "zh-TW";
}
return "zh-CN";
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 8e165e4967..0e3392381b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -51,12 +51,10 @@ export default {
availableMessage: "DBX {latest} is available. You are using {current}.",
upToDate: "DBX is up to date ({version}).",
failed: "Failed to check updates: {error}",
- rateLimited:
- "GitHub update checks are temporarily rate limited. You can still open the release page to check manually.",
+ rateLimited: "GitHub update checks are temporarily rate limited. You can still open the release page to check manually.",
openRelease: "Open Release",
downloadAndInstall: "Download & Install",
- portableManualUpdate:
- "Portable builds cannot use the in-app installer. Download the portable ZIP from the release page, then extract it over the current DBX folder to keep portable.dbx and data.",
+ portableManualUpdate: "Portable builds cannot use the in-app installer. Download the portable ZIP from the release page, then extract it over the current DBX folder to keep portable.dbx and data.",
downloading: "Downloading {progress}%",
downloadFailed: "Update download failed: {error}",
restart: "Exit & Restart",
@@ -146,8 +144,7 @@ export default {
memoryDatabasePathHint: "Use :memory: to create an in-memory SQLite or DuckDB database.",
sqliteExtensions: "SQLite Extensions",
sqliteExtensionsPlaceholder: "/path/to/regexp.dylib\n/path/to/text.dylib|sqlite3_text_init",
- sqliteExtensionsHint:
- "One .dylib/.so/.dll per line. Use “path|entry point” when an entry point is required. Loaded on connect, then load_extension is disabled.",
+ sqliteExtensionsHint: "One .dylib/.so/.dll per line. Use “path|entry point” when an entry point is required. Loaded on connect, then load_extension is disabled.",
sqliteExtensionBrowse: "Select SQLite extension",
user: "User",
password: "Password",
@@ -194,14 +191,12 @@ export default {
postgresSslModeVerifyFull: "Verify Full",
postgresServerCert: "Server CA",
postgresRootCertPlaceholder: "/path/to/ca.crt",
- postgresRootCertHint:
- "Use this for verify-ca or verify-full when the server certificate is signed by a private CA.",
+ postgresRootCertHint: "Use this for verify-ca or verify-full when the server certificate is signed by a private CA.",
postgresRootCertBrowse: "Choose CA certificate",
postgresClientCert: "Client Auth",
postgresClientCertPlaceholder: "/path/to/client.crt",
postgresClientKeyPlaceholder: "/path/to/client.key",
- postgresClientCertHint:
- "Client certificate and private key must be provided together when PostgreSQL requires mTLS.",
+ postgresClientCertHint: "Client certificate and private key must be provided together when PostgreSQL requires mTLS.",
postgresClientCertBrowse: "Choose client certificate",
postgresClientKeyBrowse: "Choose client private key",
connectionUrlOptional: "URL (optional)",
@@ -257,8 +252,7 @@ export default {
connectFailed: "Connection failed: {message}",
driverNotInstalled: "{driver} driver is not installed. Please install it from the Driver Manager.",
jreNotInstalled: "JRE {jre} runtime is not installed. Please install it from the Driver Manager.",
- systemJavaNotFound:
- "System Java runtime was not found on PATH. Please install Java or choose a custom Java executable.",
+ systemJavaNotFound: "System Java runtime was not found on PATH. Please install Java or choose a custom Java executable.",
customJavaPathEmpty: "Custom Java runtime path is empty. Please choose a Java executable.",
jdbcPluginNotInstalled: "JDBC plugin is not installed. Install the optional JDBC plugin to use this connection.",
lastError: "Connection error",
@@ -322,8 +316,7 @@ export default {
jdbcPluginHint: "Install the DBX JDBC plugin first, then import the database vendor's JDBC driver JAR.",
dmCompatHint: "Requires DM8 ODBC driver installed on your system.",
dmDownload: "Download from Dameng",
- mongoLegacyHint:
- "MongoDB below 4.2 requires the MongoDB (Legacy) driver. If authentication fails and the user was created in admin, set Auth DB to admin.",
+ mongoLegacyHint: "MongoDB below 4.2 requires the MongoDB (Legacy) driver. If authentication fails and the user was created in admin, set Auth DB to admin.",
compatible: "Compatible",
mainstream: "Popular",
color: "Color",
@@ -551,8 +544,7 @@ export default {
formatterCustomName: "Template name",
formatterCustomNamePlaceholder: "Example: User label",
formatterCustomTemplateInput: "Template",
- formatterCustomTemplateHint:
- "Available variables: ${value}, ${upper}, ${lower}, ${length}. Give it a name to save it to the list.",
+ formatterCustomTemplateHint: "Available variables: ${value}, ${upper}, ${lower}, ${length}. Give it a name to save it to the list.",
formatterPreview: "Preview",
saveFormatter: "Save",
clearFormatter: "Clear",
@@ -688,8 +680,7 @@ export default {
transposeMultiRowToggle: "Multi-row",
transposeSingleRow: "Current row",
transposeMultiRow: "Multi-row",
- transposeMultiRowHint:
- "When enabled, transpose view shows multiple rows. When disabled, it only shows the current row.",
+ transposeMultiRowHint: "When enabled, transpose view shows multiple rows. When disabled, it only shows the current row.",
rowsPerPageShort: " rows",
columnDetails: "Column Details",
tableInfo: "Table Info",
@@ -709,29 +700,23 @@ export default {
commit: "Commit",
rollback: "Rollback",
transactionSaveHint: "Commit {count} pending change(s) in a transaction.",
- nonTransactionalSaveHint:
- "Save {count} pending change(s) one by one. If one fails, earlier successful changes will not be rolled back.",
+ nonTransactionalSaveHint: "Save {count} pending change(s) one by one. If one fails, earlier successful changes will not be rolled back.",
keylessEditWarning: "No primary key",
- keylessEditWarningHint:
- "This table has no primary key. Updates and deletes use all original row values in the WHERE clause; exact duplicate rows may be affected together.",
+ keylessEditWarningHint: "This table has no primary key. Updates and deletes use all original row values in the WHERE clause; exact duplicate rows may be affected together.",
queryEditReady: "Editable",
- queryEditReadyHint:
- "This single-table result comes from “{table}”. You can edit, delete, or add rows, then use the pending-changes action to save.",
+ queryEditReadyHint: "This single-table result comes from “{table}”. You can edit, delete, or add rows, then use the pending-changes action to save.",
queryEditReadOnly: "Read-only result",
queryEditUnsupported: {
"not-select": "Only SELECT query results can be edited directly.",
cte: "Queries with WITH/CTE are not editable yet. Use a simple single-table SELECT.",
"set-operation": "UNION, INTERSECT, or EXCEPT results cannot be mapped safely back to source rows.",
aggregation: "DISTINCT, GROUP BY, HAVING, and aggregate results cannot be edited directly.",
- "external-source":
- "External files and table-function results cannot be written back directly. Import them into a database table before editing.",
+ "external-source": "External files and table-function results cannot be written back directly. Import them into a database table before editing.",
"complex-source": "JOINs, multiple tables, and subqueries cannot be mapped safely to one source row.",
- "computed-columns":
- "Computed expressions or function results cannot be written back. Select raw column names instead.",
+ "computed-columns": "Computed expressions or function results cannot be written back. Select raw column names instead.",
"no-table": "No editable source table was detected.",
"no-primary-key": "The target table has no primary key, so rows cannot be updated or deleted safely.",
- "primary-key-not-returned":
- "The result is missing the raw primary key column. Include it by its original column name.",
+ "primary-key-not-returned": "The result is missing the raw primary key column. Include it by its original column name.",
"aliased-columns": "Result columns use aliases or expressions. Select editable columns by their original names.",
"metadata-unavailable": "DBX could not load table metadata, so result editing is disabled.",
},
@@ -773,8 +758,7 @@ export default {
tipExecute: "to execute query",
fileOpened: "Opened {name}",
mcpTitle: "AI Agent Integration",
- mcpDescription:
- "Beyond the built-in AI assistant, you can also use Claude Code, Cursor, and other coding agents to query your databases via MCP.",
+ mcpDescription: "Beyond the built-in AI assistant, you can also use Claude Code, Cursor, and other coding agents to query your databases via MCP.",
mcpLearnMore: "Learn more",
},
common: {
@@ -830,13 +814,10 @@ export default {
foreignKeyIncoming: "{target} points to the current field through a foreign key. This is a verified dependency.",
foreignKeyOutgoing: "The current field references {target} through a foreign key. This is a verified dependency.",
viewLikely: "The view definition mentions both the target table and field, usually indicating query dependency.",
- viewPossible:
- "The view definition mentions a same-name field but not the target table, so it needs confirmation.",
- historyLikely:
- "A historical SQL statement mentions both the target table and field. Use it as impact-analysis context.",
+ viewPossible: "The view definition mentions a same-name field but not the target table, so it needs confirmation.",
+ historyLikely: "A historical SQL statement mentions both the target table and field. Use it as impact-analysis context.",
historyPossible: "A historical SQL statement mentions a same-name field. It may be related but needs context.",
- sameName:
- "Another table has a same-name field. This may share business meaning but is not a verified database dependency.",
+ sameName: "Another table has a same-name field. This may share business meaning but is not a verified database dependency.",
},
cancel: "Cancel",
refresh: "Analyze Again",
@@ -877,8 +858,7 @@ export default {
configExport: {
passphraseTitle: "Encrypt & Export",
passphraseImportTitle: "Decrypt & Import",
- passphraseExportHint:
- "To include connection passwords in the export, set a passphrase for encryption. You will need the same passphrase to import.",
+ passphraseExportHint: "To include connection passwords in the export, set a passphrase for encryption. You will need the same passphrase to import.",
passphraseImportHint: "This file is encrypted. Enter the passphrase to decrypt and import.",
passphrase: "Passphrase",
passphraseConfirm: "Confirm Passphrase",
@@ -890,15 +870,12 @@ export default {
exportEncrypted: "Export",
decryptImport: "Decrypt & Import",
wrongPassphrase: "Wrong passphrase or corrupted file",
- cryptoUnavailable:
- "Encrypted config import is unavailable in this browser context. Use HTTPS, localhost, or DBX Desktop.",
+ cryptoUnavailable: "Encrypted config import is unavailable in this browser context. Use HTTPS, localhost, or DBX Desktop.",
exportSuccess: "Connections exported successfully",
importSuccess: "Imported {count} connection(s)",
- importNavicatSuccess:
- "Imported {count} Navicat connection(s). Fill in any connection whose password is still empty before testing.",
+ importNavicatSuccess: "Imported {count} Navicat connection(s). Fill in any connection whose password is still empty before testing.",
importDatagripSuccess: "Imported {count} DataGrip connection(s), filled {filled} password(s) from macOS Keychain.",
- importDbeaverSuccess:
- "Imported {count} DBeaver connection(s). Fill in any connection whose password is still empty before testing.",
+ importDbeaverSuccess: "Imported {count} DBeaver connection(s). Fill in any connection whose password is still empty before testing.",
importNone: "No new connections to import",
importLayoutConfirm: "The imported file contains connection groups. Apply them?",
importLayoutTitle: "Import Groups",
@@ -984,8 +961,7 @@ export default {
enableThinking: "Thinking",
enableThinkingOn: "Enabled",
enableThinkingOff: "Disabled",
- enableThinkingHint:
- "This option only takes effect on /chat/completions APIs and supported models. When disabled, it can significantly reduce token usage, but the quality of generated results may decrease slightly.",
+ enableThinkingHint: "This option only takes effect on /chat/completions APIs and supported models. When disabled, it can significantly reduce token usage, but the quality of generated results may decrease slightly.",
actions: {
generate: "Generate SQL",
explain: "Explain SQL",
@@ -1011,8 +987,7 @@ export default {
deleteSelectedConnections: "Delete Selected {count} Connections",
confirmDeleteTitle: "Delete Connection",
confirmDeleteMessage: 'Are you sure you want to delete "{name}"? This cannot be undone.',
- confirmDeleteSelectedMessage:
- "Are you sure you want to delete the selected {count} connections? This cannot be undone.",
+ confirmDeleteSelectedMessage: "Are you sure you want to delete the selected {count} connections? This cannot be undone.",
editConnection: "Edit Connection",
selectVisibleDatabases: "Select Visible Databases",
userAdmin: "Users & Privileges",
@@ -1073,8 +1048,7 @@ export default {
renameObjectNamePlaceholder: "New name",
renameObjectSuccess: '"{oldName}" renamed to "{newName}"',
confirmDropTableTitle: "Drop Table",
- confirmDropTableMessage:
- 'Are you sure you want to drop "{name}"? This will permanently delete the table and all its data.',
+ confirmDropTableMessage: 'Are you sure you want to drop "{name}"? This will permanently delete the table and all its data.',
confirmEmptyTableTitle: "Empty Table",
confirmEmptyTableMessage: 'Are you sure you want to delete all data from "{name}"?',
confirmTruncateTableTitle: "Truncate Table",
@@ -1094,8 +1068,7 @@ export default {
confirmExecuteProcedureTitle: "Execute Procedure",
confirmExecuteProcedureMessage: 'Execute procedure "{name}"? You can fill or adjust parameter values first.',
loadingProcedureParameters: "Loading parameters...",
- procedureParametersUnavailable:
- "Could not load parameter metadata. You can still edit the SQL below and execute it.",
+ procedureParametersUnavailable: "Could not load parameter metadata. You can still edit the SQL below and execute it.",
noProcedureParameters: "No parameters were found. The current SQL will be executed as shown.",
inputParameters: "{count} input parameters",
outputParameters: "{count} output parameters",
@@ -1105,8 +1078,7 @@ export default {
parameterValue: "Value",
parameterNull: "NULL",
parameterDefault: "DEFAULT",
- parameterDefaultHint:
- "When DEFAULT is checked, DBX omits that argument so the database uses the procedure default.",
+ parameterDefaultHint: "When DEFAULT is checked, DBX omits that argument so the database uses the procedure default.",
parameterValuePlaceholder: "Enter value",
outputOnly: "Output only",
sqlPreview: "SQL Preview",
@@ -1144,8 +1116,7 @@ export default {
createDuckDbFile: "Create Database File",
dropDatabase: "Drop Database",
confirmDropDatabaseTitle: "Drop Database",
- confirmDropDatabaseMessage:
- 'Are you sure you want to drop database "{name}"? This will permanently delete the database and all its data.',
+ confirmDropDatabaseMessage: 'Are you sure you want to drop database "{name}"? This will permanently delete the database and all its data.',
createDatabaseSuccess: 'Database "{name}" created',
createDuckDbFileSuccess: 'DuckDB database file "{name}" created and attached',
createDuckDbFileDesktopOnly: "Creating DuckDB database files is only available in the desktop app",
@@ -1158,8 +1129,7 @@ export default {
createSchema: "Create Schema",
dropSchema: "Drop Schema",
confirmDropSchemaTitle: "Drop Schema",
- confirmDropSchemaMessage:
- 'Are you sure you want to drop schema "{name}"? This will permanently delete the schema and all its objects.',
+ confirmDropSchemaMessage: 'Are you sure you want to drop schema "{name}"? This will permanently delete the schema and all its objects.',
createSchemaSuccess: 'Schema "{name}" created',
dropSchemaSuccess: 'Schema "{name}" dropped',
createSchemaNamePlaceholder: "Schema name",
@@ -1196,8 +1166,7 @@ export default {
},
userAdmin: {
title: "Users & Privileges",
- unsupported:
- "MySQL-compatible and PostgreSQL-compatible connections are supported. SQL Server, Oracle, and other permission models can be added next.",
+ unsupported: "MySQL-compatible and PostgreSQL-compatible connections are supported. SQL Server, Oracle, and other permission models can be added next.",
newUser: "New User",
anonymous: "Anonymous",
roleName: "Role name",
@@ -1210,8 +1179,7 @@ export default {
grants: "Grants",
noGrants: "No grants found",
privilegeEditor: "Privilege Editor",
- privilegeHint:
- "Choose privileges, database, and table, then preview SQL before applying. * means global or all tables.",
+ privilegeHint: "Choose privileges, database, and table, then preview SQL before applying. * means global or all tables.",
database: "Database",
schema: "Schema",
table: "Table",
@@ -1421,8 +1389,7 @@ export default {
columnValue: "Value",
columnSize: "Size",
columnTTL: "TTL",
- binaryStringReadonlyHint:
- "Binary string values are shown as escaped text in read-only mode; editing raw bytes is not supported.",
+ binaryStringReadonlyHint: "Binary string values are shown as escaped text in read-only mode; editing raw bytes is not supported.",
selectedKeys: "Selected keys",
deleteGroup: "Delete group",
deleteGroupDetails: "{target}\n{count} keys",
@@ -1569,8 +1536,7 @@ export default {
deleteMessage: "This delete operation may be irreversible. Continue?",
deleteConfirm: "Confirm Delete",
deleteRowMessage: "This row will be marked for deletion and removed from the database after saving. Continue?",
- deleteRowsMessage:
- "These {count} rows will be marked for deletion and removed from the database after saving. Continue?",
+ deleteRowsMessage: "These {count} rows will be marked for deletion and removed from the database after saving. Continue?",
deleteRowDetails: "Table: {table}",
deleteRowDetailsNoTable: "Current result row",
redisKeyDetails: "Redis key: {key}",
@@ -1719,14 +1685,12 @@ export default {
missingTargetTables: "Missing same-name target tables: {tables}",
keyColumns: "Key Columns",
keyColumnsPlaceholder: "Comma-separated primary or unique columns",
- keyColumnsAutoHint:
- "Leave blank to auto-detect primary keys for single-table compare, or per table in batch compare.",
+ keyColumnsAutoHint: "Leave blank to auto-detect primary keys for single-table compare, or per table in batch compare.",
rowCounts: "Source {source} rows, target {target} rows; full compare completed",
previewLimitOption: "Preview {count}",
compare: "Compare Data",
summary: "Added {added}, removed {removed}, modified {modified}",
- batchSummary:
- "Compared {tables} tables: {different} different, {same} identical, {failed} failed; added {added}, removed {removed}, modified {modified}",
+ batchSummary: "Compared {tables} tables: {different} different, {same} identical, {failed} failed; added {added}, removed {removed}, modified {modified}",
comparingTable: "Comparing {current}/{total}: {table}",
keyColumnsInline: "Key columns: {columns}",
selectedInline: "Selected {selected}/{total}",
@@ -1817,8 +1781,7 @@ export default {
languageTitle: "Language / 语言",
fontSize: "Font Size",
uiScale: "UI Scale",
- uiScaleDescription:
- "Scale the entire desktop UI for high-DPI displays. Changes apply immediately and are restored on next launch.",
+ uiScaleDescription: "Scale the entire desktop UI for high-DPI displays. Changes apply immediately and are restored on next launch.",
theme: "Theme",
selectTheme: "Select theme...",
followAppTheme: "Follow app theme",
@@ -1833,14 +1796,11 @@ export default {
iconThemeBlack: "Black",
iconThemeBlackDescription: "Use the black DBX mark for the window, tray, and logo.",
showTrayIcon: "Show tray/menu bar icon",
- showTrayIconDescription:
- "When disabled, no icon is shown, but closing the window still hides DBX in the background as before.",
+ showTrayIconDescription: "When disabled, no icon is shown, but closing the window still hides DBX in the background as before.",
updateNotificationsEnabled: "Enable update reminders",
- updateNotificationsEnabledDescription:
- "When disabled, DBX will not automatically check app or driver updates or show update badges. Manual checks are still available.",
+ updateNotificationsEnabledDescription: "When disabled, DBX will not automatically check app or driver updates or show update badges. Manual checks are still available.",
debugLoggingEnabled: "Enable debug logs",
- debugLoggingEnabledDescription:
- "Record more detailed local user-side diagnostic logs while troubleshooting reports. Disabled by default.",
+ debugLoggingEnabledDescription: "Record more detailed local user-side diagnostic logs while troubleshooting reports. Disabled by default.",
debugLogsCopy: "Copy logs",
debugLogsCopied: "Copied",
debugLogsDownload: "Download logs",
@@ -1852,8 +1812,7 @@ export default {
showColumnTypesInHeader: "Show column types under names",
showColumnTypesInHeaderDescription: "Display each column's data type directly below grid column names.",
compactColumnHeaderActions: "Compact column header tools",
- compactColumnHeaderActionsDescription:
- "Move formatter and local filter tools into a more menu so column names get priority.",
+ compactColumnHeaderActionsDescription: "Move formatter and local filter tools into a more menu so column names get priority.",
sidebarActivation: "Sidebar activation",
sidebarActivationSingle: "Single click",
sidebarActivationSingleDescription: "Open actionable sidebar items with one click.",
@@ -1861,38 +1820,28 @@ export default {
sidebarActivationDoubleDescription: "Single click selects rows; double click opens items.",
sidebarObjectDisplay: "Sidebar object layout",
sidebarObjectDisplayGrouped: "Advanced view",
- sidebarObjectDisplayGroupedDescription:
- "Group objects by tables, views, procedures, and functions for databases with more object types.",
+ sidebarObjectDisplayGroupedDescription: "Group objects by tables, views, procedures, and functions for databases with more object types.",
sidebarObjectDisplaySimple: "Simple view",
- sidebarObjectDisplaySimpleDescription:
- "List tables and views directly under each database or schema to reduce intermediate levels.",
+ sidebarObjectDisplaySimpleDescription: "List tables and views directly under each database or schema to reduce intermediate levels.",
autoSelectActiveSidebarNode: "Always select opened item",
- autoSelectActiveSidebarNodeDescription:
- "When switching tabs, select the matching visible table, collection, or SQL file in the sidebar.",
+ autoSelectActiveSidebarNodeDescription: "When switching tabs, select the matching visible table, collection, or SQL file in the sidebar.",
disconnectTabHandlingMode: "Tabs after disconnect",
- disconnectTabHandlingModeDescription:
- "Choose how related tabs should be handled after closing a connection or database.",
+ disconnectTabHandlingModeDescription: "Choose how related tabs should be handled after closing a connection or database.",
disconnectTabHandlingModeCloseTabs: "Close all tabs",
disconnectTabHandlingModeCloseTabsDescription: "Close all related tabs for the connection or database.",
disconnectTabHandlingModeKeepTabsClearResults: "Close object tabs, keep SQL tabs",
- disconnectTabHandlingModeKeepTabsClearResultsDescription:
- "Close table data, object browser, and structure tabs while keeping SQL query tabs and SQL text, and also clear execution state and result sessions.",
+ disconnectTabHandlingModeKeepTabsClearResultsDescription: "Close table data, object browser, and structure tabs while keeping SQL query tabs and SQL text, and also clear execution state and result sessions.",
disconnectTabHandlingModeKeepTabsKeepResults: "Do not close related tabs",
- disconnectTabHandlingModeKeepTabsKeepResultsDescription:
- "Keep related tabs, SQL text, and current results without extra cleanup.",
+ disconnectTabHandlingModeKeepTabsKeepResultsDescription: "Keep related tabs, SQL text, and current results without extra cleanup.",
reuseDataTab: "Reuse data tab",
- reuseDataTabDescription:
- "When clicking a table in the sidebar, reuse the existing data tab instead of creating a new one each time.",
+ reuseDataTabDescription: "When clicking a table in the sidebar, reuse the existing data tab instead of creating a new one each time.",
sidebarHiddenTablePrefixes: "Hidden table name prefixes",
- sidebarHiddenTablePrefixesDescription:
- "One prefix per line. Only sidebar table, view, and collection labels are shortened; tooltips and actions still use the full name.",
+ sidebarHiddenTablePrefixesDescription: "One prefix per line. Only sidebar table, view, and collection labels are shortened; tooltips and actions still use the full name.",
sidebarHiddenTablePrefixesPlaceholder: "Example:\nODS_\nT8Y2_LONG_",
sidebarHideTableComments: "Hide table comments in sidebar",
- sidebarHideTableCommentsDescription:
- "Hide the inline table/view comments shown next to names in the sidebar tree to save horizontal space.",
+ sidebarHideTableCommentsDescription: "Hide the inline table/view comments shown next to names in the sidebar tree to save horizontal space.",
sidebarAllowHorizontalScroll: "Allow sidebar horizontal scroll",
- sidebarAllowHorizontalScrollDescription:
- "Show long table, view, and collection names in full by allowing horizontal sidebar scrolling.",
+ sidebarAllowHorizontalScrollDescription: "Show long table, view, and collection names in full by allowing horizontal sidebar scrolling.",
snippetsDescription: "Customize SQL snippet templates triggered in the editor.",
snippetsAdd: "Add Snippet",
snippetsLabel: "Label",
@@ -1913,18 +1862,14 @@ export default {
syncClearSavedPassword: "Clear saved password",
syncRememberWebDavPassword: "Remember WebDAV app password",
syncSavedPassword: "(saved)",
- syncRememberWebDavPasswordDescription:
- "The password is encrypted and stored on this device only. It is not synced to WebDAV and does not replace the sync password.",
+ syncRememberWebDavPasswordDescription: "The password is encrypted and stored on this device only. It is not synced to WebDAV and does not replace the sync password.",
syncRemotePath: "Remote snapshot path",
syncRemotePathDescription: "DBX will create missing parent folders when uploading.",
- syncSecretNotice:
- "By default, DBX syncs connection details and settings only. Database passwords, SSH passwords, proxy passwords, connection strings, and AI API keys stay local.",
+ syncSecretNotice: "By default, DBX syncs connection details and settings only. Database passwords, SSH passwords, proxy passwords, connection strings, and AI API keys stay local.",
syncSecrets: "Sync encrypted secrets",
- syncSecretsDescription:
- "When enabled, DBX encrypts database passwords, SSH passwords, and AI API keys before uploading them to WebDAV.",
+ syncSecretsDescription: "When enabled, DBX encrypts database passwords, SSH passwords, and AI API keys before uploading them to WebDAV.",
syncSecretsPassphrase: "Sync password",
- syncSecretsPassphraseDescription:
- "This password is only used to encrypt and restore sensitive data. DBX does not save it; enter it again on each device.",
+ syncSecretsPassphraseDescription: "This password is only used to encrypt and restore sensitive data. DBX does not save it; enter it again on each device.",
syncTest: "Test",
syncUpload: "Upload",
syncDownload: "Download",
@@ -1946,8 +1891,7 @@ export default {
wordWrap: "Word wrap",
wordWrapDescription: "Wrap long SQL lines within the editor width",
confirmDangerousSqlExecution: "Confirm before dangerous SQL",
- confirmDangerousSqlExecutionDescription:
- "When disabled, ALTER, DROP, DELETE, TRUNCATE, and other dangerous SQL run without the warning dialog.",
+ confirmDangerousSqlExecutionDescription: "When disabled, ALTER, DROP, DELETE, TRUNCATE, and other dangerous SQL run without the warning dialog.",
redisScanPageSize: "Redis scan count",
redisScanPageSizeDescription: "Keys requested per Redis SCAN page when browsing keys.",
redisScanPageSizeOption: "{count} keys",
@@ -2050,8 +1994,7 @@ export default {
mcpReadonlyMode: "Read-only mode",
mcpReadonlyModeDescription: "Adds DBX_MCP_ALLOW_WRITES=0 to the sample config so the MCP session stays query-only.",
mcpAllowDangerous: "Allow dangerous SQL",
- mcpAllowDangerousDescription:
- "Adds DBX_MCP_ALLOW_DANGEROUS_SQL=1 to the sample config so DROP, TRUNCATE, ALTER, and similar statements are allowed.",
+ mcpAllowDangerousDescription: "Adds DBX_MCP_ALLOW_DANGEROUS_SQL=1 to the sample config so DROP, TRUNCATE, ALTER, and similar statements are allowed.",
mcpDetectionTiming: "DBX checks automatically when this page opens; use Check again to refresh.",
mcpNpmBoundary: "DBX only checks and explains MCP status; installation and upgrades still run through npm.",
mcpRefresh: "Check again",
@@ -2077,8 +2020,7 @@ export default {
usageAgentDrivers: "Built-in driver agents",
usageJdbcPlugin: "JDBC plugin",
usageJdbcDriverJars: "JDBC driver JARs",
- offlineDownloadHint:
- "For air-gapped environments, download offline driver packages on an internet-connected machine, then import them here.",
+ offlineDownloadHint: "For air-gapped environments, download offline driver packages on an internet-connected machine, then import them here.",
offlineDownloadLink: "Offline driver downloads",
searchDrivers: "Search driver name, type, version...",
searchJdbcDrivers: "Search JDBC driver name or path...",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 2b8288515e..949a21e2d5 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -51,12 +51,10 @@ export default {
availableMessage: "DBX {latest} está disponible. Estás usando la versión {current}.",
upToDate: "DBX está actualizado ({version}).",
failed: "Error al buscar actualizaciones: {error}",
- rateLimited:
- "Las verificaciones de actualizaciones de GitHub están temporalmente limitadas. Puedes abrir la página de lanzamientos para verificar manualmente.",
+ rateLimited: "Las verificaciones de actualizaciones de GitHub están temporalmente limitadas. Puedes abrir la página de lanzamientos para verificar manualmente.",
openRelease: "Abrir lanzamiento",
downloadAndInstall: "Descargar e instalar",
- portableManualUpdate:
- "Las versiones portables no pueden usar el instalador integrado. Descarga el ZIP portable desde la página de lanzamiento y extráelo sobre la carpeta actual de DBX para conservar portable.dbx y data.",
+ portableManualUpdate: "Las versiones portables no pueden usar el instalador integrado. Descarga el ZIP portable desde la página de lanzamiento y extráelo sobre la carpeta actual de DBX para conservar portable.dbx y data.",
downloading: "Descargando {progress}%",
downloadFailed: "Error al descargar la actualización: {error}",
restart: "Salir y reiniciar",
@@ -240,8 +238,7 @@ export default {
jreNotInstalled: "El entorno JRE {jre} no está instalado. Instálelo desde el Administrador de controladores.",
systemJavaNotFound: "No se encontró Java en el PATH del sistema. Instale Java o elija un ejecutable personalizado.",
customJavaPathEmpty: "La ruta de Java personalizada está vacía. Elija un ejecutable de Java.",
- jdbcPluginNotInstalled:
- "El plugin JDBC no está instalado. Instale el plugin JDBC opcional para usar esta conexión.",
+ jdbcPluginNotInstalled: "El plugin JDBC no está instalado. Instale el plugin JDBC opcional para usar esta conexión.",
lastError: "Error de conexión",
clearError: "Limpiar error de conexión",
saveFailed: "Error al guardar la conexión: {message}",
@@ -294,8 +291,7 @@ export default {
jdbcUrl: "URL JDBC",
jdbcUrlPlaceholder: "jdbc:postgresql://localhost:5432/base_de_datos",
jdbcDriverClass: "Clase del driver (opcional)",
- jdbcDriverClassPlaceholder:
- "La mayoría de los drivers se registran automáticamente; usa com.vendor.jdbc.Driver si es necesario",
+ jdbcDriverClassPlaceholder: "La mayoría de los drivers se registran automáticamente; usa com.vendor.jdbc.Driver si es necesario",
jdbcDriverPaths: "JARs del driver JDBC",
jdbcDriverSelectPlaceholder: "Seleccionar driver importado",
jdbcDriverPathsPlaceholder: "/ruta/al/driver.jar\n/ruta/a/otro-driver.jar",
@@ -304,8 +300,7 @@ export default {
jdbcPluginHint: "Instala primero el plugin JDBC de DBX y luego importa el JAR del driver JDBC del proveedor.",
dmCompatHint: "Requiere el driver ODBC DM8 instalado en el sistema.",
dmDownload: "Descargar desde Dameng",
- mongoLegacyHint:
- "MongoDB inferior a 4.2 requiere el controlador MongoDB (Legacy) del Gestor de controladores; la conexión cambiará automáticamente.",
+ mongoLegacyHint: "MongoDB inferior a 4.2 requiere el controlador MongoDB (Legacy) del Gestor de controladores; la conexión cambiará automáticamente.",
compatible: "Compatible",
mainstream: "Popular",
color: "Color",
@@ -622,8 +617,7 @@ export default {
transposeMultiRowToggle: "Varias filas",
transposeSingleRow: "Fila actual",
transposeMultiRow: "Varias filas",
- transposeMultiRowHint:
- "Cuando está activado, la vista transpuesta muestra varias filas. Cuando está desactivado, solo muestra la fila actual.",
+ transposeMultiRowHint: "Cuando está activado, la vista transpuesta muestra varias filas. Cuando está desactivado, solo muestra la fila actual.",
rowsPerPageShort: " filas",
columnDetails: "Detalles de columna",
tableInfoSearch: "Buscar...",
@@ -634,11 +628,9 @@ export default {
commit: "Confirmar",
rollback: "Revertir",
transactionSaveHint: "Confirma {count} cambio(s) pendiente(s) en una transacción.",
- nonTransactionalSaveHint:
- "Guarda {count} cambio(s) pendiente(s) uno por uno. Si uno falla, los cambios anteriores correctos no se revierten.",
+ nonTransactionalSaveHint: "Guarda {count} cambio(s) pendiente(s) uno por uno. Si uno falla, los cambios anteriores correctos no se revierten.",
keylessEditWarning: "Sin clave primaria",
- keylessEditWarningHint:
- "Esta tabla no tiene clave primaria. Las actualizaciones y eliminaciones usan todos los valores originales de la fila en WHERE; filas duplicadas exactas pueden verse afectadas juntas.",
+ keylessEditWarningHint: "Esta tabla no tiene clave primaria. Las actualizaciones y eliminaciones usan todos los valores originales de la fila en WHERE; filas duplicadas exactas pueden verse afectadas juntas.",
sortUnsupported: "Este SQL no admite ordenamiento del resultado completo. Intenta con una consulta SELECT simple.",
truncatedHint: "Los resultados están limitados a 10.000 filas. Usa LIMIT/OFFSET en tu consulta para paginar.",
},
@@ -664,8 +656,7 @@ export default {
},
welcome: {
title: "Espacio de trabajo de base de datos",
- subtitle:
- "Selecciona una conexión a la izquierda para explorar el esquema, o abre una pestaña de consulta directamente.",
+ subtitle: "Selecciona una conexión a la izquierda para explorar el esquema, o abre una pestaña de consulta directamente.",
connections: "Conexiones",
connected: "Conectado",
databaseTypes: "Tipos de bases de datos",
@@ -678,8 +669,7 @@ export default {
tipExecute: "para ejecutar la consulta",
fileOpened: "Abierto {name}",
mcpTitle: "Integración con agentes de IA",
- mcpDescription:
- "Además del asistente de IA integrado, puedes usar Claude Code, Cursor y otros agentes de programación para consultar tus bases de datos mediante MCP.",
+ mcpDescription: "Además del asistente de IA integrado, puedes usar Claude Code, Cursor y otros agentes de programación para consultar tus bases de datos mediante MCP.",
mcpLearnMore: "Más información",
},
common: {
@@ -730,20 +720,13 @@ export default {
sameName: "Mismo nombre",
},
description: {
- foreignKeyIncoming:
- "{target} apunta al campo actual mediante una clave foránea. Esta es una dependencia verificada.",
- foreignKeyOutgoing:
- "El campo actual referencia a {target} mediante una clave foránea. Esta es una dependencia verificada.",
- viewLikely:
- "La definición de la vista menciona tanto la tabla como el campo destino, lo que generalmente indica una dependencia de consulta.",
- viewPossible:
- "La definición de la vista menciona un campo con el mismo nombre pero no la tabla destino, por lo que requiere confirmación.",
- historyLikely:
- "Una sentencia SQL del historial menciona tanto la tabla como el campo destino. Úsala como contexto de análisis de impacto.",
- historyPossible:
- "Una sentencia SQL del historial menciona un campo con el mismo nombre. Puede estar relacionado pero requiere verificación.",
- sameName:
- "Otra tabla tiene un campo con el mismo nombre. Puede compartir significado de negocio, pero no es una dependencia verificada en la base de datos.",
+ foreignKeyIncoming: "{target} apunta al campo actual mediante una clave foránea. Esta es una dependencia verificada.",
+ foreignKeyOutgoing: "El campo actual referencia a {target} mediante una clave foránea. Esta es una dependencia verificada.",
+ viewLikely: "La definición de la vista menciona tanto la tabla como el campo destino, lo que generalmente indica una dependencia de consulta.",
+ viewPossible: "La definición de la vista menciona un campo con el mismo nombre pero no la tabla destino, por lo que requiere confirmación.",
+ historyLikely: "Una sentencia SQL del historial menciona tanto la tabla como el campo destino. Úsala como contexto de análisis de impacto.",
+ historyPossible: "Una sentencia SQL del historial menciona un campo con el mismo nombre. Puede estar relacionado pero requiere verificación.",
+ sameName: "Otra tabla tiene un campo con el mismo nombre. Puede compartir significado de negocio, pero no es una dependencia verificada en la base de datos.",
},
cancel: "Cancelar",
refresh: "Analizar de nuevo",
@@ -784,8 +767,7 @@ export default {
configExport: {
passphraseTitle: "Cifrar y exportar",
passphraseImportTitle: "Descifrar e importar",
- passphraseExportHint:
- "Para incluir las contraseñas de conexión en la exportación, define una frase de paso para el cifrado. Necesitarás la misma frase para importar.",
+ passphraseExportHint: "Para incluir las contraseñas de conexión en la exportación, define una frase de paso para el cifrado. Necesitarás la misma frase para importar.",
passphraseImportHint: "Este archivo está cifrado. Ingresa la frase de paso para descifrarlo e importarlo.",
passphrase: "Frase de paso",
passphraseConfirm: "Confirmar frase de paso",
@@ -797,16 +779,12 @@ export default {
exportEncrypted: "Exportar",
decryptImport: "Descifrar e importar",
wrongPassphrase: "Frase de paso incorrecta o archivo corrupto",
- cryptoUnavailable:
- "La importación cifrada no está disponible en este navegador. Usa HTTPS, localhost o DBX Desktop.",
+ cryptoUnavailable: "La importación cifrada no está disponible en este navegador. Usa HTTPS, localhost o DBX Desktop.",
exportSuccess: "Conexiones exportadas exitosamente",
importSuccess: "Se importaron {count} conexión(es)",
- importNavicatSuccess:
- "Se importaron {count} conexión(es) de Navicat. Completa la contraseña de las conexiones que aún la tengan vacía antes de probarlas.",
- importDatagripSuccess:
- "Se importaron {count} conexión(es) de DataGrip, se llenaron {filled} contraseña(s) del Keychain.",
- importDbeaverSuccess:
- "Se importaron {count} conexión(es) de DBeaver. Completa la contraseña de las conexiones que aún la tengan vacía antes de probarlas.",
+ importNavicatSuccess: "Se importaron {count} conexión(es) de Navicat. Completa la contraseña de las conexiones que aún la tengan vacía antes de probarlas.",
+ importDatagripSuccess: "Se importaron {count} conexión(es) de DataGrip, se llenaron {filled} contraseña(s) del Keychain.",
+ importDbeaverSuccess: "Se importaron {count} conexión(es) de DBeaver. Completa la contraseña de las conexiones que aún la tengan vacía antes de probarlas.",
importNone: "No hay nuevas conexiones para importar",
importLayoutConfirm: "El archivo importado contiene grupos de conexiones. ¿Deseas aplicarlos?",
importLayoutTitle: "Importar grupos",
@@ -848,8 +826,7 @@ export default {
fixWithAi: "Corregir con IA",
truncated: "Contexto truncado",
contextSummary: "{database} · {tables} tablas",
- autoSqlBlocked:
- "El SQL generado por la IA parecía demasiado riesgoso para ejecutarse automáticamente. Revísalo manualmente antes de ejecutar.",
+ autoSqlBlocked: "El SQL generado por la IA parecía demasiado riesgoso para ejecutarse automáticamente. Revísalo manualmente antes de ejecutar.",
proxy: "Proxy",
proxyEnable: "Enviar solicitudes de IA mediante proxy",
proxyUrl: "URL del proxy",
@@ -922,8 +899,7 @@ export default {
structureDocYes: "Sí",
structureDocNo: "No",
structureDocCopied: "Estructura copiada",
- structureDocCopyFallbackHint:
- "La copia automática fue bloqueada. Haz clic en Copiar de nuevo o selecciona el contenido inferior.",
+ structureDocCopyFallbackHint: "La copia automática fue bloqueada. Haz clic en Copiar de nuevo o selecciona el contenido inferior.",
saveStructure: "Guardar SQL",
exportStructureCopied: "Estructura copiada",
createTable: "Crear tabla",
@@ -933,8 +909,7 @@ export default {
truncateTable: "Truncar tabla",
duplicateStructure: "Clonar como tabla nueva",
confirmDropTableTitle: "Eliminar tabla",
- confirmDropTableMessage:
- '¿Estás seguro de que deseas eliminar "{name}"? Esto borrará permanentemente la tabla y todos sus datos.',
+ confirmDropTableMessage: '¿Estás seguro de que deseas eliminar "{name}"? Esto borrará permanentemente la tabla y todos sus datos.',
confirmEmptyTableTitle: "Vaciar tabla",
confirmEmptyTableMessage: '¿Estás seguro de que deseas eliminar todos los datos de "{name}"?',
confirmTruncateTableTitle: "Truncar tabla",
@@ -952,11 +927,9 @@ export default {
batchDrop: "Eliminar seleccionados ({count})",
executeProcedure: "Ejecutar procedimiento",
confirmExecuteProcedureTitle: "Ejecutar procedimiento",
- confirmExecuteProcedureMessage:
- '¿Ejecutar el procedimiento "{name}"? Puedes completar o ajustar los valores de los parámetros primero.',
+ confirmExecuteProcedureMessage: '¿Ejecutar el procedimiento "{name}"? Puedes completar o ajustar los valores de los parámetros primero.',
loadingProcedureParameters: "Cargando parámetros...",
- procedureParametersUnavailable:
- "No se pudo cargar la metadata de parámetros. Aún puedes editar el SQL inferior y ejecutarlo.",
+ procedureParametersUnavailable: "No se pudo cargar la metadata de parámetros. Aún puedes editar el SQL inferior y ejecutarlo.",
noProcedureParameters: "No se encontraron parámetros. El SQL actual se ejecutará tal como se muestra.",
inputParameters: "{count} parámetros de entrada",
outputParameters: "{count} parámetros de salida",
@@ -966,8 +939,7 @@ export default {
parameterValue: "Value",
parameterNull: "NULL",
parameterDefault: "DEFAULT",
- parameterDefaultHint:
- "Cuando DEFAULT está marcado, DBX omite ese argumento para que la base de datos use el valor predeterminado.",
+ parameterDefaultHint: "Cuando DEFAULT está marcado, DBX omite ese argumento para que la base de datos use el valor predeterminado.",
parameterValuePlaceholder: "Ingresa un valor",
outputOnly: "Solo salida",
sqlPreview: "Vista previa SQL",
@@ -985,8 +957,7 @@ export default {
confirmDropTriggerTitle: "Eliminar disparador",
confirmDropTableChildObjectMessage: '¿Seguro que deseas eliminar "{name}" de "{table}"?',
confirmBatchDropTitle: "Eliminar objetos seleccionados",
- confirmBatchDropMessage:
- "¿Seguro que deseas eliminar {count} objetos seleccionados? Esta acción no se puede deshacer.",
+ confirmBatchDropMessage: "¿Seguro que deseas eliminar {count} objetos seleccionados? Esta acción no se puede deshacer.",
confirmDropProcedureTitle: "Eliminar procedimiento",
confirmDropProcedureMessage: '¿Seguro que deseas eliminar el procedimiento "{name}"?',
confirmDropFunctionTitle: "Eliminar función",
@@ -1006,8 +977,7 @@ export default {
createDuckDbFile: "Crear archivo de base de datos",
dropDatabase: "Eliminar base de datos",
confirmDropDatabaseTitle: "Eliminar base de datos",
- confirmDropDatabaseMessage:
- '¿Estás seguro de que deseas eliminar la base de datos "{name}"? Esto borrará permanentemente la base de datos y todos sus datos.',
+ confirmDropDatabaseMessage: '¿Estás seguro de que deseas eliminar la base de datos "{name}"? Esto borrará permanentemente la base de datos y todos sus datos.',
createDatabaseSuccess: 'Base de datos "{name}" creada',
createDuckDbFileSuccess: 'Archivo de base de datos DuckDB "{name}" creado y adjuntado',
createDuckDbFileDesktopOnly: "Crear archivos de base de datos DuckDB solo está disponible en la app de escritorio",
@@ -1016,8 +986,7 @@ export default {
createSchema: "Crear esquema",
dropSchema: "Eliminar esquema",
confirmDropSchemaTitle: "Eliminar esquema",
- confirmDropSchemaMessage:
- '¿Estás seguro de que deseas eliminar el esquema "{name}"? Esto borrará permanentemente el esquema y todos sus objetos.',
+ confirmDropSchemaMessage: '¿Estás seguro de que deseas eliminar el esquema "{name}"? Esto borrará permanentemente el esquema y todos sus objetos.',
createSchemaSuccess: 'Esquema "{name}" creado',
dropSchemaSuccess: 'Esquema "{name}" eliminado',
createSchemaNamePlaceholder: "Nombre del esquema",
@@ -1088,8 +1057,7 @@ export default {
dropSelected: "Eliminar seleccionadas",
clearSelection: "Limpiar selección",
confirmBatchDropTitle: "Eliminar tablas seleccionadas",
- confirmBatchDropMessage:
- "¿Seguro que quieres eliminar {count} tablas seleccionadas? Esta acción no se puede deshacer.",
+ confirmBatchDropMessage: "¿Seguro que quieres eliminar {count} tablas seleccionadas? Esta acción no se puede deshacer.",
batchDropSuccess: "{count} tablas eliminadas",
},
structureEditor: {
@@ -1213,14 +1181,12 @@ export default {
columnValue: "Valor",
columnSize: "Tamaño",
columnTTL: "TTL",
- binaryStringReadonlyHint:
- "Los valores de cadena binaria se muestran como texto escapado en modo de solo lectura; la edición de bytes sin procesar no está disponible.",
+ binaryStringReadonlyHint: "Los valores de cadena binaria se muestran como texto escapado en modo de solo lectura; la edición de bytes sin procesar no está disponible.",
selectedKeys: "Claves seleccionadas",
deleteGroup: "Eliminar grupo",
deleteGroupDetails: "{target}\n{count} claves",
flushDb: "Limpiar DB actual",
- flushDbMessage:
- "Esto eliminará todas las claves de la base de datos Redis actual y no se puede deshacer. ¿Continuar?",
+ flushDbMessage: "Esto eliminará todas las claves de la base de datos Redis actual y no se puede deshacer. ¿Continuar?",
flushDbDetails: "Destino: Redis db{db}\nAlcance: todas las claves de la DB actual",
flushDbConfirm: "Limpiar DB",
flushDbSuccess: "Redis db{db} limpiada",
@@ -1349,15 +1315,12 @@ export default {
},
dangerDialog: {
title: "Operación peligrosa",
- message:
- "Esta sentencia SQL puede modificar o eliminar datos de forma irreversible. ¿Estás seguro de que deseas ejecutarla?",
+ message: "Esta sentencia SQL puede modificar o eliminar datos de forma irreversible. ¿Estás seguro de que deseas ejecutarla?",
suppressFuturePrompts: "No volver a preguntar para SQL peligroso",
deleteMessage: "Esta operación de eliminación puede ser irreversible. ¿Continuar?",
deleteConfirm: "Confirmar eliminación",
- deleteRowMessage:
- "Esta fila quedará marcada para eliminación y se borrará de la base de datos al guardar. ¿Continuar?",
- deleteRowsMessage:
- "Estas {count} filas se marcarán para eliminación y se eliminarán de la base de datos después de guardar. ¿Continuar?",
+ deleteRowMessage: "Esta fila quedará marcada para eliminación y se borrará de la base de datos al guardar. ¿Continuar?",
+ deleteRowsMessage: "Estas {count} filas se marcarán para eliminación y se eliminarán de la base de datos después de guardar. ¿Continuar?",
deleteRowDetails: "Tabla: {table}",
deleteRowDetailsNoTable: "Fila actual del resultado",
redisKeyDetails: "Clave Redis: {key}",
@@ -1504,14 +1467,12 @@ export default {
missingTargetTables: "Faltan tablas de destino con el mismo nombre: {tables}",
keyColumns: "Columnas clave",
keyColumnsPlaceholder: "Columnas primarias o únicas separadas por comas",
- keyColumnsAutoHint:
- "Déjalo vacío para detectar claves primarias automáticamente en comparación simple o por tabla en lote.",
+ keyColumnsAutoHint: "Déjalo vacío para detectar claves primarias automáticamente en comparación simple o por tabla en lote.",
rowCounts: "Origen {source} filas, destino {target} filas; comparación completa terminada",
previewLimitOption: "Vista previa {count}",
compare: "Comparar datos",
summary: "Agregadas {added}, eliminadas {removed}, modificadas {modified}",
- batchSummary:
- "Se compararon {tables} tablas: {different} con diferencias, {same} iguales, {failed} con error; agregadas {added}, eliminadas {removed}, modificadas {modified}",
+ batchSummary: "Se compararon {tables} tablas: {different} con diferencias, {same} iguales, {failed} con error; agregadas {added}, eliminadas {removed}, modificadas {modified}",
comparingTable: "Comparando {current}/{total}: {table}",
keyColumnsInline: "Columnas clave: {columns}",
selectedInline: "Seleccionadas {selected}/{total}",
@@ -1524,8 +1485,7 @@ export default {
remainingRows: "Quedan {count} filas fuera de la vista previa",
planningSync: "Actualizando el plan de sincronización...",
noSelectedDifferences: "No hay diferencias seleccionadas para ejecutar",
- planSummary:
- "Plan: {inserts} inserciones, {updates} actualizaciones, {deletes} eliminaciones, {statements} sentencias",
+ planSummary: "Plan: {inserts} inserciones, {updates} actualizaciones, {deletes} eliminaciones, {statements} sentencias",
statusDifferent: "Con diferencias",
statusSame: "Igual",
statusError: "Error",
@@ -1533,8 +1493,7 @@ export default {
missingKeyColumns: "Las columnas clave deben existir en las tablas de origen y destino: {columns}",
noCommonColumns: "Las tablas de origen y destino no tienen columnas en común para comparar",
targetTableMissing: "No se encontró la tabla de destino: {table}",
- noComparableTables:
- "No se encontraron tablas comparables. Verifica si existen tablas de destino con el mismo nombre.",
+ noComparableTables: "No se encontraron tablas comparables. Verifica si existen tablas de destino con el mismo nombre.",
noDifferences: "Los datos son idénticos, no se necesita SQL de sincronización",
syncSuccess: "Sincronización de datos ejecutada exitosamente",
},
@@ -1604,8 +1563,7 @@ export default {
languageTitle: "Idioma / Language",
fontSize: "Tamaño de fuente",
uiScale: "Escala de interfaz",
- uiScaleDescription:
- "Escala toda la interfaz de escritorio para pantallas de alta densidad. Los cambios se aplican al instante y se restauran al volver a abrir.",
+ uiScaleDescription: "Escala toda la interfaz de escritorio para pantallas de alta densidad. Los cambios se aplican al instante y se restauran al volver a abrir.",
theme: "Tema",
selectTheme: "Seleccionar tema...",
appLayout: "Diseño de la interfaz",
@@ -1619,14 +1577,11 @@ export default {
iconThemeBlack: "Negro",
iconThemeBlackDescription: "Usar la marca negra de DBX en ventana, bandeja y logo.",
showTrayIcon: "Mostrar icono en bandeja/barra de menú",
- showTrayIconDescription:
- "Si está desactivado, no se muestra el icono, pero cerrar la ventana sigue ocultando DBX en segundo plano como antes.",
+ showTrayIconDescription: "Si está desactivado, no se muestra el icono, pero cerrar la ventana sigue ocultando DBX en segundo plano como antes.",
updateNotificationsEnabled: "Activar recordatorios de actualización",
- updateNotificationsEnabledDescription:
- "Al desactivarlo, DBX no comprobará automáticamente actualizaciones de la app ni de los controladores, ni mostrará indicadores. Las comprobaciones manuales siguen disponibles.",
+ updateNotificationsEnabledDescription: "Al desactivarlo, DBX no comprobará automáticamente actualizaciones de la app ni de los controladores, ni mostrará indicadores. Las comprobaciones manuales siguen disponibles.",
debugLoggingEnabled: "Activar logs de depuración",
- debugLoggingEnabledDescription:
- "Registra logs de diagnóstico locales del lado del usuario al investigar reportes. Desactivado por defecto.",
+ debugLoggingEnabledDescription: "Registra logs de diagnóstico locales del lado del usuario al investigar reportes. Desactivado por defecto.",
debugLogsCopy: "Copiar logs",
debugLogsCopied: "Copiado",
debugLogsDownload: "Descargar logs",
@@ -1634,14 +1589,11 @@ export default {
debugLogsClear: "Borrar logs",
dataGridDisplay: "Visualización de la tabla",
showColumnCommentsInHeader: "Mostrar comentarios bajo los nombres",
- showColumnCommentsInHeaderDescription:
- "Muestra los comentarios de columnas directamente debajo del nombre de la columna.",
+ showColumnCommentsInHeaderDescription: "Muestra los comentarios de columnas directamente debajo del nombre de la columna.",
showColumnTypesInHeader: "Mostrar tipos de columna bajo los nombres",
- showColumnTypesInHeaderDescription:
- "Muestra el tipo de dato de cada columna directamente debajo del nombre de la columna.",
+ showColumnTypesInHeaderDescription: "Muestra el tipo de dato de cada columna directamente debajo del nombre de la columna.",
compactColumnHeaderActions: "Compactar herramientas del encabezado",
- compactColumnHeaderActionsDescription:
- "Mueve formatear y filtrar a un menú de más acciones para priorizar el nombre de columna.",
+ compactColumnHeaderActionsDescription: "Mueve formatear y filtrar a un menú de más acciones para priorizar el nombre de columna.",
sidebarActivation: "Activación de la barra lateral",
sidebarActivationSingle: "Un clic",
sidebarActivationSingleDescription: "Abrir elementos accionables de la barra lateral con un clic.",
@@ -1649,39 +1601,28 @@ export default {
sidebarActivationDoubleDescription: "Un clic selecciona la fila; doble clic abre elementos.",
sidebarObjectDisplay: "Diseño de objetos en la barra lateral",
sidebarObjectDisplayGrouped: "Vista avanzada",
- sidebarObjectDisplayGroupedDescription:
- "Agrupa objetos por tablas, vistas, procedimientos y funciones para bases con más tipos de objeto.",
+ sidebarObjectDisplayGroupedDescription: "Agrupa objetos por tablas, vistas, procedimientos y funciones para bases con más tipos de objeto.",
sidebarObjectDisplaySimple: "Vista simple",
- sidebarObjectDisplaySimpleDescription:
- "Muestra tablas y vistas directamente bajo cada base de datos o esquema para reducir niveles intermedios.",
+ sidebarObjectDisplaySimpleDescription: "Muestra tablas y vistas directamente bajo cada base de datos o esquema para reducir niveles intermedios.",
autoSelectActiveSidebarNode: "Seleccionar siempre el elemento abierto",
- autoSelectActiveSidebarNodeDescription:
- "Al cambiar de pestaña, selecciona la tabla, colección o archivo SQL visible correspondiente en la barra lateral.",
+ autoSelectActiveSidebarNodeDescription: "Al cambiar de pestaña, selecciona la tabla, colección o archivo SQL visible correspondiente en la barra lateral.",
disconnectTabHandlingMode: "Pestañas tras desconectar",
- disconnectTabHandlingModeDescription:
- "Elige cómo conservar las pestañas relacionadas al cerrar una conexión o base de datos.",
+ disconnectTabHandlingModeDescription: "Elige cómo conservar las pestañas relacionadas al cerrar una conexión o base de datos.",
disconnectTabHandlingModeCloseTabs: "Cerrar todas las pestañas",
- disconnectTabHandlingModeCloseTabsDescription:
- "Cierra todas las pestañas relacionadas de la conexión o base de datos.",
+ disconnectTabHandlingModeCloseTabsDescription: "Cierra todas las pestañas relacionadas de la conexión o base de datos.",
disconnectTabHandlingModeKeepTabsClearResults: "Cerrar objetos y conservar SQL",
- disconnectTabHandlingModeKeepTabsClearResultsDescription:
- "Cierra pestañas de datos, explorador de objetos y estructura, conserva las pestañas SQL y limpia el estado de ejecución y las sesiones.",
+ disconnectTabHandlingModeKeepTabsClearResultsDescription: "Cierra pestañas de datos, explorador de objetos y estructura, conserva las pestañas SQL y limpia el estado de ejecución y las sesiones.",
disconnectTabHandlingModeKeepTabsKeepResults: "No cerrar pestañas relacionadas",
- disconnectTabHandlingModeKeepTabsKeepResultsDescription:
- "Conserva las pestañas relacionadas, el texto SQL y los resultados actuales sin limpieza adicional.",
+ disconnectTabHandlingModeKeepTabsKeepResultsDescription: "Conserva las pestañas relacionadas, el texto SQL y los resultados actuales sin limpieza adicional.",
reuseDataTab: "Reutilizar pestaña de datos",
- reuseDataTabDescription:
- "Al hacer clic en una tabla en la barra lateral, reutiliza la pestaña de datos existente en lugar de crear una nueva cada vez.",
+ reuseDataTabDescription: "Al hacer clic en una tabla en la barra lateral, reutiliza la pestaña de datos existente en lugar de crear una nueva cada vez.",
sidebarHiddenTablePrefixes: "Prefijos ocultos de tablas",
- sidebarHiddenTablePrefixesDescription:
- "Un prefijo por linea. Solo acorta etiquetas de tablas, vistas y colecciones en la barra lateral; las acciones y ayudas usan el nombre completo.",
+ sidebarHiddenTablePrefixesDescription: "Un prefijo por linea. Solo acorta etiquetas de tablas, vistas y colecciones en la barra lateral; las acciones y ayudas usan el nombre completo.",
sidebarHiddenTablePrefixesPlaceholder: "Ejemplo:\nODS_\nT8Y2_LONG_",
sidebarHideTableComments: "Ocultar comentarios de tablas en la barra lateral",
- sidebarHideTableCommentsDescription:
- "Oculta los comentarios de tablas/vistas junto a los nombres en el árbol de la barra lateral para ahorrar espacio horizontal.",
+ sidebarHideTableCommentsDescription: "Oculta los comentarios de tablas/vistas junto a los nombres en el árbol de la barra lateral para ahorrar espacio horizontal.",
sidebarAllowHorizontalScroll: "Permitir desplazamiento horizontal lateral",
- sidebarAllowHorizontalScrollDescription:
- "Muestra completos los nombres largos de tablas, vistas y colecciones permitiendo desplazamiento horizontal en la barra lateral.",
+ sidebarAllowHorizontalScrollDescription: "Muestra completos los nombres largos de tablas, vistas y colecciones permitiendo desplazamiento horizontal en la barra lateral.",
snippetsDescription: "Personaliza plantillas SQL activadas en el editor.",
snippetsAdd: "Agregar fragmento",
snippetsLabel: "Etiqueta",
@@ -1702,18 +1643,14 @@ export default {
syncClearSavedPassword: "Borrar contraseña guardada",
syncRememberWebDavPassword: "Recordar contraseña de app WebDAV",
syncSavedPassword: "(guardada)",
- syncRememberWebDavPasswordDescription:
- "La contraseña se cifra y se guarda solo en este dispositivo. No se sincroniza a WebDAV ni reemplaza la contraseña de sync.",
+ syncRememberWebDavPasswordDescription: "La contraseña se cifra y se guarda solo en este dispositivo. No se sincroniza a WebDAV ni reemplaza la contraseña de sync.",
syncRemotePath: "Ruta remota",
syncRemotePathDescription: "DBX creará las carpetas padre faltantes al subir.",
- syncSecretNotice:
- "De forma predeterminada, DBX solo sincroniza detalles de conexión y ajustes. Las contraseñas de base de datos, SSH, proxy, cadenas de conexión y API keys de IA quedan locales.",
+ syncSecretNotice: "De forma predeterminada, DBX solo sincroniza detalles de conexión y ajustes. Las contraseñas de base de datos, SSH, proxy, cadenas de conexión y API keys de IA quedan locales.",
syncSecrets: "Sincronizar secretos cifrados",
- syncSecretsDescription:
- "Al activarlo, DBX cifra contraseñas de base de datos, contraseñas SSH y API keys de IA antes de subirlas a WebDAV.",
+ syncSecretsDescription: "Al activarlo, DBX cifra contraseñas de base de datos, contraseñas SSH y API keys de IA antes de subirlas a WebDAV.",
syncSecretsPassphrase: "Contraseña de sync",
- syncSecretsPassphraseDescription:
- "Esta contraseña solo se usa para cifrar y restaurar datos sensibles. DBX no la guarda; tendrás que ingresarla en cada dispositivo.",
+ syncSecretsPassphraseDescription: "Esta contraseña solo se usa para cifrar y restaurar datos sensibles. DBX no la guarda; tendrás que ingresarla en cada dispositivo.",
syncTest: "Probar",
syncUpload: "Subir",
syncDownload: "Descargar",
@@ -1722,8 +1659,7 @@ export default {
syncDownloadSuccess: "Se descargaron y aplicaron {bytes} bytes desde {path}.",
syncSecretsApplied: "Los secretos cifrados fueron restaurados.",
syncSecretsSkipped: "Había secretos cifrados, pero no fueron restaurados.",
- syncDownloadConfirm:
- "¿Descargar y aplicar la instantánea remota de DBX? Se reemplazarán metadatos locales y SQL guardado.",
+ syncDownloadConfirm: "¿Descargar y aplicar la instantánea remota de DBX? Se reemplazarán metadatos locales y SQL guardado.",
apply: "Aplicar",
applyAndClose: "Aplicar y cerrar",
reset: "Restablecer",
@@ -1734,8 +1670,7 @@ export default {
wordWrap: "Ajuste de línea",
wordWrapDescription: "Ajustar las líneas largas de SQL al ancho del editor",
confirmDangerousSqlExecution: "Confirmar antes de SQL peligroso",
- confirmDangerousSqlExecutionDescription:
- "Cuando se desactiva, ALTER, DROP, DELETE, TRUNCATE y otras sentencias peligrosas se ejecutan sin el diálogo de advertencia.",
+ confirmDangerousSqlExecutionDescription: "Cuando se desactiva, ALTER, DROP, DELETE, TRUNCATE y otras sentencias peligrosas se ejecutan sin el diálogo de advertencia.",
redisScanPageSize: "Cantidad de escaneo Redis",
redisScanPageSizeDescription: "Claves solicitadas por página SCAN al explorar claves Redis.",
redisScanPageSizeOption: "{count} claves",
@@ -1836,11 +1771,9 @@ export default {
mcpCodexConfig: "Configuración de Codex",
mcpCodexConfigPath: "Codex puede usar ~/.codex/config.toml o .codex/config.toml dentro del proyecto.",
mcpReadonlyMode: "Modo solo lectura",
- mcpReadonlyModeDescription:
- "Añade DBX_MCP_ALLOW_WRITES=0 al ejemplo de configuración para que la sesión MCP solo permita consultas.",
+ mcpReadonlyModeDescription: "Añade DBX_MCP_ALLOW_WRITES=0 al ejemplo de configuración para que la sesión MCP solo permita consultas.",
mcpAllowDangerous: "Permitir SQL peligroso",
- mcpAllowDangerousDescription:
- "Añade DBX_MCP_ALLOW_DANGEROUS_SQL=1 al ejemplo de configuración para permitir DROP, TRUNCATE, ALTER y sentencias similares.",
+ mcpAllowDangerousDescription: "Añade DBX_MCP_ALLOW_DANGEROUS_SQL=1 al ejemplo de configuración para permitir DROP, TRUNCATE, ALTER y sentencias similares.",
mcpDetectionTiming: "DBX comprueba automáticamente al abrir esta página; usa Comprobar de nuevo para actualizar.",
mcpNpmBoundary: "DBX solo comprueba y explica el estado de MCP; la instalación y actualización siguen usando npm.",
mcpRefresh: "Comprobar de nuevo",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index d957a896b2..3e9b7d4eda 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -51,12 +51,10 @@ export default {
availableMessage: "DBX {latest} è disponibile. Stai usando la versione {current}.",
upToDate: "DBX è aggiornato ({version}).",
failed: "Verifica aggiornamenti non riuscita: {error}",
- rateLimited:
- "Le verifiche degli aggiornamenti di GitHub sono temporaneamente limitate. Puoi comunque aprire la pagina delle release per verificare manualmente.",
+ rateLimited: "Le verifiche degli aggiornamenti di GitHub sono temporaneamente limitate. Puoi comunque aprire la pagina delle release per verificare manualmente.",
openRelease: "Apri Release",
downloadAndInstall: "Scarica e Installa",
- portableManualUpdate:
- "Le build portatili non possono utilizzare l'installer in-app. Scarica lo ZIP portatile dalla pagina delle release, quindi estrailo nella cartella DBX corrente per mantenere portable.dbx e i dati.",
+ portableManualUpdate: "Le build portatili non possono utilizzare l'installer in-app. Scarica lo ZIP portatile dalla pagina delle release, quindi estrailo nella cartella DBX corrente per mantenere portable.dbx e i dati.",
downloading: "Download in corso {progress}%",
downloadFailed: "Download dell'aggiornamento non riuscito: {error}",
restart: "Esci e Riavvia",
@@ -146,8 +144,7 @@ export default {
memoryDatabasePathHint: "Usa :memory: per creare un database SQLite o DuckDB in memoria.",
sqliteExtensions: "Estensioni SQLite",
sqliteExtensionsPlaceholder: "/percorso/per/regexp.dylib\n/percorso/per/text.dylib|sqlite3_text_init",
- sqliteExtensionsHint:
- "Una .dylib/.so/.dll per riga. Usa “percorso|punto di ingresso” quando è richiesto un punto di ingresso. Caricata alla connessione, poi load_extension viene disabilitata.",
+ sqliteExtensionsHint: "Una .dylib/.so/.dll per riga. Usa “percorso|punto di ingresso” quando è richiesto un punto di ingresso. Caricata alla connessione, poi load_extension viene disabilitata.",
sqliteExtensionBrowse: "Seleziona estensione SQLite",
user: "Utente",
password: "Password",
@@ -179,13 +176,11 @@ export default {
mysqlTlsModeRequired: "Richiesta",
mysqlTlsModeVerifyCa: "Verifica CA",
mysqlTlsModeVerifyIdentity: "Verifica Identità",
- mysqlCaCertHint:
- "Richiesto per Verifica CA e Verifica Identità quando il certificato del server usa una CA privata.",
+ mysqlCaCertHint: "Richiesto per Verifica CA e Verifica Identità quando il certificato del server usa una CA privata.",
mysqlClientCert: "Autenticazione Client",
mysqlClientCertPlaceholder: "/percorso/per/client.crt",
mysqlClientKeyPlaceholder: "/percorso/per/client.key",
- mysqlClientCertHint:
- "Il certificato client e la chiave privata devono essere forniti insieme quando MySQL richiede mTLS.",
+ mysqlClientCertHint: "Il certificato client e la chiave privata devono essere forniti insieme quando MySQL richiede mTLS.",
mysqlClientCertBrowse: "Scegli certificato client",
mysqlClientKeyBrowse: "Scegli chiave privata client",
postgresSslMode: "Modalità TLS",
@@ -196,14 +191,12 @@ export default {
postgresSslModeVerifyFull: "Verifica Completa",
postgresServerCert: "CA Server",
postgresRootCertPlaceholder: "/percorso/per/ca.crt",
- postgresRootCertHint:
- "Usa questo per verifica-ca o verifica-completa quando il certificato del server è firmato da una CA privata.",
+ postgresRootCertHint: "Usa questo per verifica-ca o verifica-completa quando il certificato del server è firmato da una CA privata.",
postgresRootCertBrowse: "Scegli certificato CA",
postgresClientCert: "Autenticazione Client",
postgresClientCertPlaceholder: "/percorso/per/client.crt",
postgresClientKeyPlaceholder: "/percorso/per/client.key",
- postgresClientCertHint:
- "Il certificato client e la chiave privata devono essere forniti insieme quando PostgreSQL richiede mTLS.",
+ postgresClientCertHint: "Il certificato client e la chiave privata devono essere forniti insieme quando PostgreSQL richiede mTLS.",
postgresClientCertBrowse: "Scegli certificato client",
postgresClientKeyBrowse: "Scegli chiave privata client",
connectionUrlOptional: "URL (opzionale)",
@@ -248,11 +241,9 @@ export default {
connectFailed: "Connessione non riuscita: {message}",
driverNotInstalled: "Il driver {driver} non è installato. Installalo da Gestione Driver.",
jreNotInstalled: "Il runtime JRE {jre} non è installato. Installalo da Gestione Driver.",
- systemJavaNotFound:
- "Runtime Java di sistema non trovato in PATH. Installa Java o scegli un eseguibile Java personalizzato.",
+ systemJavaNotFound: "Runtime Java di sistema non trovato in PATH. Installa Java o scegli un eseguibile Java personalizzato.",
customJavaPathEmpty: "Il percorso del runtime Java personalizzato è vuoto. Scegli un eseguibile Java.",
- jdbcPluginNotInstalled:
- "Il plugin JDBC non è installato. Installa il plugin JDBC opzionale per utilizzare questa connessione.",
+ jdbcPluginNotInstalled: "Il plugin JDBC non è installato. Installa il plugin JDBC opzionale per utilizzare questa connessione.",
lastError: "Errore di connessione",
clearError: "Cancella errore di connessione",
saveFailed: "Impossibile salvare la connessione: {message}",
@@ -305,19 +296,16 @@ export default {
jdbcUrl: "URL JDBC",
jdbcUrlPlaceholder: "jdbc:postgresql://localhost:5432/database",
jdbcDriverClass: "Classe Driver (opzionale)",
- jdbcDriverClassPlaceholder:
- "La maggior parte dei driver si registra automaticamente; usa com.vendor.jdbc.Driver si necessario",
+ jdbcDriverClassPlaceholder: "La maggior parte dei driver si registra automaticamente; usa com.vendor.jdbc.Driver si necessario",
jdbcDriverPaths: "JAR del Driver",
jdbcDriverSelectPlaceholder: "Scegli il driver importato",
jdbcDriverPathsPlaceholder: "/percorso/per/driver.jar\n/percorso/per/un-altro-driver.jar",
jdbcDriverBrowse: "Scegli file JAR del driver JDBC",
jdbcDocs: "Visualizza documentazione JDBC",
- jdbcPluginHint:
- "Installa prima il plugin DBX JDBC, quindi importa il file JAR del driver JDBC del fornitore del database.",
+ jdbcPluginHint: "Installa prima il plugin DBX JDBC, quindi importa il file JAR del driver JDBC del fornitore del database.",
dmCompatHint: "Richiede il driver ODBC DM8 installato sul sistema.",
dmDownload: "Scarica da Dameng",
- mongoLegacyHint:
- "MongoDB precedente a 4.2 richiede il driver MongoDB (Legacy). Se l'autenticazione fallisce e l'utente è stato creato in admin, imposta DB di Autenticazione su admin.",
+ mongoLegacyHint: "MongoDB precedente a 4.2 richiede il driver MongoDB (Legacy). Se l'autenticazione fallisce e l'utente è stato creato in admin, imposta DB di Autenticazione su admin.",
compatible: "Compatibile",
mainstream: "Popolare",
color: "Colore",
@@ -529,8 +517,7 @@ export default {
formatterCustomName: "Nome modello",
formatterCustomNamePlaceholder: "Esempio: Etichetta utente",
formatterCustomTemplateInput: "Modello",
- formatterCustomTemplateHint:
- "Variabili disponibili: ${value}, ${upper}, ${lower}, ${length}. Assegna un nome per salvarlo nell'elenco.",
+ formatterCustomTemplateHint: "Variabili disponibili: ${value}, ${upper}, ${lower}, ${length}. Assegna un nome per salvarlo nell'elenco.",
formatterPreview: "Anteprima",
saveFormatter: "Salva",
clearFormatter: "Cancella",
@@ -666,8 +653,7 @@ export default {
transposeMultiRowToggle: "Più righe",
transposeSingleRow: "Riga corrente",
transposeMultiRow: "Più righe",
- transposeMultiRowHint:
- "Quando è attiva, la vista trasposta mostra più righe. Quando è disattiva, mostra solo la riga corrente.",
+ transposeMultiRowHint: "Quando è attiva, la vista trasposta mostra più righe. Quando è disattiva, mostra solo la riga corrente.",
rowsPerPageShort: " righe",
columnDetails: "Dettagli Colonna",
tableInfo: "Informazioni Tabella",
@@ -685,42 +671,28 @@ export default {
commit: "Commit",
rollback: "Rollback",
transactionSaveHint: "Applica {count} modifica/he in sospeso in una transazione.",
- nonTransactionalSaveHint:
- "Salva {count} modifica/he in sospeso una ad una. In caso di errore, le modifiche salvate in precedenza non saranno annullate.",
+ nonTransactionalSaveHint: "Salva {count} modifica/he in sospeso una ad una. In caso di errore, le modifiche salvate in precedenza non saranno annullate.",
keylessEditWarning: "Nessuna chiave primaria",
- keylessEditWarningHint:
- "Questa tabella non ha chiavi primarie. Gli aggiornamenti e le eliminazioni utilizzano tutti i valori originali delle righe nella clausola WHERE; le righe duplicate esatte potrebbero essere influenzate contemporaneamente.",
+ keylessEditWarningHint: "Questa tabella non ha chiavi primarie. Gli aggiornamenti e le eliminazioni utilizzano tutti i valori originali delle righe nella clausola WHERE; le righe duplicate esatte potrebbero essere influenzate contemporaneamente.",
queryEditReady: "Modificabile",
- queryEditReadyHint:
- "Questo risultato a tabella singola proviene da “{table}”. Puoi modificare, eliminare o aggiungere righe, quindi utilizzare l'azione delle modifiche in sospeso per salvare.",
+ queryEditReadyHint: "Questo risultato a tabella singola proviene da “{table}”. Puoi modificare, eliminare o aggiungere righe, quindi utilizzare l'azione delle modifiche in sospeso per salvare.",
queryEditReadOnly: "Risultato in sola lettura",
queryEditUnsupported: {
"not-select": "Solo i risultati di query SELECT possono essere modificati direttamente.",
cte: "Le query con WITH/CTE non sono ancora modificabili. Usa una semplice SELECT a tabella singola.",
- "set-operation":
- "I risultati di UNION, INTERSECT o EXCEPT non possono essere mappati in sicurezza alle righe di origine.",
- aggregation:
- "I risultati di DISTINCT, GROUP BY, HAVING e aggregazioni non possono essere modificati direttamente.",
- "external-source":
- "I file esterni e i risultati di funzioni tabella non possono essere riscritti direttamente. Importali in una tabella di database prima di modificarli.",
- "complex-source":
- "JOIN, tabelle multiple e sottoquery non possono essere mappati in sicurezza ad una singola riga di origine.",
- "computed-columns":
- "Le espressioni calcolate o i risultati di funzioni non possono essere riscritti. Seleziona invece nomi di colonna grezzi.",
+ "set-operation": "I risultati di UNION, INTERSECT o EXCEPT non possono essere mappati in sicurezza alle righe di origine.",
+ aggregation: "I risultati di DISTINCT, GROUP BY, HAVING e aggregazioni non possono essere modificati direttamente.",
+ "external-source": "I file esterni e i risultati di funzioni tabella non possono essere riscritti direttamente. Importali in una tabella di database prima di modificarli.",
+ "complex-source": "JOIN, tabelle multiple e sottoquery non possono essere mappati in sicurezza ad una singola riga di origine.",
+ "computed-columns": "Le espressioni calcolate o i risultati di funzioni non possono essere riscritti. Seleziona invece nomi di colonna grezzi.",
"no-table": "Nessuna tabella di origine modificabile rilevata.",
- "no-primary-key":
- "La tabella di destinazione non ha chiavi primarie, quindi le righe non possono essere aggiornate o eliminate in sicurezza.",
- "primary-key-not-returned":
- "Nel risultato manca la colonna della chiave primaria. Includila con il suo nome di colonna originale.",
- "aliased-columns":
- "Le colonne del risultato utilizzano alias o espressioni. Seleziona le colonne modificabili con i loro nomi originali.",
- "metadata-unavailable":
- "DBX non è riuscito a caricare i metadati della tabella, quindi la modifica del risultato è disabilitata.",
+ "no-primary-key": "La tabella di destinazione non ha chiavi primarie, quindi le righe non possono essere aggiornate o eliminate in sicurezza.",
+ "primary-key-not-returned": "Nel risultato manca la colonna della chiave primaria. Includila con il suo nome di colonna originale.",
+ "aliased-columns": "Le colonne del risultato utilizzano alias o espressioni. Seleziona le colonne modificabili con i loro nomi originali.",
+ "metadata-unavailable": "DBX non è riuscito a caricare i metadati della tabella, quindi la modifica del risultato è disabilitata.",
},
- sortUnsupported:
- "Questo SQL non supporta l'ordinamento sull'intero risultato. Riprova con una query SELECT semplice.",
- truncatedHint:
- "Risultati troncati a {count} righe. Usa la paginazione a piè di pagina o regola le righe per pagina.",
+ sortUnsupported: "Questo SQL non supporta l'ordinamento sull'intero risultato. Riprova con una query SELECT semplice.",
+ truncatedHint: "Risultati troncati a {count} righe. Usa la paginazione a piè di pagina o regola le righe per pagina.",
},
exportProgress: {
title: "Esportazione Dati Tabella",
@@ -757,8 +729,7 @@ export default {
tipExecute: "per eseguire la query",
fileOpened: "Aperto {name}",
mcpTitle: "Integrazione Agente AI",
- mcpDescription:
- "Oltre all'assistente AI integrato, puoi utilizzare Claude Code, Cursor e altri agenti di sviluppo per interrogare i tuoi database tramite MCP.",
+ mcpDescription: "Oltre all'assistente AI integrato, puoi utilizzare Claude Code, Cursor e altri agenti di sviluppo per interrogare i tuoi database tramite MCP.",
mcpLearnMore: "Scopri di più",
},
common: {
@@ -809,20 +780,13 @@ export default {
sameName: "Stesso Nome",
},
description: {
- foreignKeyIncoming:
- "{target} punta al campo corrente tramite una chiave esterna. Si tratta di una dipendenza verificata.",
- foreignKeyOutgoing:
- "Il campo corrente fa riferimento a {target} tramite una chiave esterna. Si tratta di una dipendenza verificata.",
- viewLikely:
- "La definizione della vista menziona sia la tabella che il campo di destinazione, indicando solitamente una dipendenza della query.",
- viewPossible:
- "La definizione della vista menziona un campo con lo stesso nome ma non la tabella di destinazione, pertanto richiede conferma.",
- historyLikely:
- "Un'istruzione SQL della cronologia menziona sia la tabella che il campo di destinazione. Utilizzalo come contesto per l'analisi dell'impatto.",
- historyPossible:
- "Un'istruzione SQL della cronologia menziona un campo con lo stesso nome. Potrebbe essere correlata, ma necessita di contesto.",
- sameName:
- "Un'altra tabella ha un campo con lo stesso nome. Potrebbe condividere il significato aziendale ma non è una dipendenza verificata del database.",
+ foreignKeyIncoming: "{target} punta al campo corrente tramite una chiave esterna. Si tratta di una dipendenza verificata.",
+ foreignKeyOutgoing: "Il campo corrente fa riferimento a {target} tramite una chiave esterna. Si tratta di una dipendenza verificata.",
+ viewLikely: "La definizione della vista menziona sia la tabella che il campo di destinazione, indicando solitamente una dipendenza della query.",
+ viewPossible: "La definizione della vista menziona un campo con lo stesso nome ma non la tabella di destinazione, pertanto richiede conferma.",
+ historyLikely: "Un'istruzione SQL della cronologia menziona sia la tabella che il campo di destinazione. Utilizzalo come contesto per l'analisi dell'impatto.",
+ historyPossible: "Un'istruzione SQL della cronologia menziona un campo con lo stesso nome. Potrebbe essere correlata, ma necessita di contesto.",
+ sameName: "Un'altra tabella ha un campo con lo stesso nome. Potrebbe condividere il significato aziendale ma non è una dipendenza verificata del database.",
},
cancel: "Annulla",
refresh: "Analizza di Nuovo",
@@ -838,8 +802,7 @@ export default {
newGroup: "Nuovo Gruppo...",
newGroupDefault: "Nuovo Gruppo",
deleteGroupConfirmTitle: "Elimina Gruppo",
- deleteGroupConfirmMessage:
- 'Eliminare il gruppo "{name}"? Le connessioni al suo interno verranno spostate al livello principale.',
+ deleteGroupConfirmMessage: 'Eliminare il gruppo "{name}"? Le connessioni al suo interno verranno spostate al livello principale.',
},
databaseSearch: {
title: "Cerca nel Database",
@@ -864,8 +827,7 @@ export default {
configExport: {
passphraseTitle: "Crittografa ed Esporta",
passphraseImportTitle: "Decrittografa e Importa",
- passphraseExportHint:
- "Per includere le password di connessione nell'esportazione, imposta una passphrase per la crittografia. Avrai bisogno della stessa passphrase per importare.",
+ passphraseExportHint: "Per includere le password di connessione nell'esportazione, imposta una passphrase per la crittografia. Avrai bisogno della stessa passphrase per importare.",
passphraseImportHint: "Questo file è crittografato. Inserisci la passphrase per decrittografarlo e importarlo.",
passphrase: "Passphrase",
passphraseConfirm: "Conferma Passphrase",
@@ -877,15 +839,12 @@ export default {
exportEncrypted: "Esporta",
decryptImport: "Decrittografa e Importa",
wrongPassphrase: "Passphrase errata o file corrotto",
- cryptoUnavailable:
- "L'importazione cifrata non è disponibile in questo contesto del browser. Usa HTTPS, localhost o DBX Desktop.",
+ cryptoUnavailable: "L'importazione cifrata non è disponibile in questo contesto del browser. Usa HTTPS, localhost o DBX Desktop.",
exportSuccess: "Connessioni esportate con successo",
importSuccess: "Importata/e {count} connessione/i",
- importNavicatSuccess:
- "Importata/e {count} connessione/i Navicat. Inserisci le password mancanti prima di testare la connessione.",
+ importNavicatSuccess: "Importata/e {count} connessione/i Navicat. Inserisci le password mancanti prima di testare la connessione.",
importDatagripSuccess: "Importate {count} connessione/i DataGrip, riempite {filled} password dalla Keychain.",
- importDbeaverSuccess:
- "Importata/e {count} connessione/i DBeaver. Inserisci le password mancanti prima di testare la connessione.",
+ importDbeaverSuccess: "Importata/e {count} connessione/i DBeaver. Inserisci le password mancanti prima di testare la connessione.",
importNone: "Nessuna nuova connessione da importare",
importLayoutConfirm: "Il file importato contiene gruppi di connessioni. Vuoi applicarli?",
importLayoutTitle: "Importa Gruppi",
@@ -944,8 +903,7 @@ export default {
fixWithAi: "Correggi con AI",
truncated: "Contesto troncato",
contextSummary: "{database} · {tables} tabelle",
- autoSqlBlocked:
- "L'SQL generato dall'AI è sembrato troppo rischioso per l'esecuzione automatica. Rivedilo manualmente prima di eseguirlo.",
+ autoSqlBlocked: "L'SQL generato dall'AI è sembrato troppo rischioso per l'esecuzione automatica. Rivedilo manualmente prima di eseguirlo.",
agentSteps: {
generated: "SQL generato",
noSql: "Nessun SQL trovato",
@@ -972,8 +930,7 @@ export default {
enableThinking: "Pensiero (Thinking)",
enableThinkingOn: "Abilitato",
enableThinkingOff: "Disabilitato",
- enableThinkingHint:
- "Questa opzione ha effetto solo sulle API /chat/completions e sui modelli supportati. Quando è disabilitata, può ridurre notevolmente l'uso dei token, ma la qualità dei risultati generati potrebbe diminuire leggermente.",
+ enableThinkingHint: "Questa opzione ha effetto solo sulle API /chat/completions e sui modelli supportati. Quando è disabilitata, può ridurre notevolmente l'uso dei token, ma la qualità dei risultati generati potrebbe diminuire leggermente.",
actions: {
generate: "Genera SQL",
explain: "Spiega SQL",
@@ -999,8 +956,7 @@ export default {
deleteSelectedConnections: "Elimina {count} connessioni selezionate",
confirmDeleteTitle: "Elimina Connessione",
confirmDeleteMessage: 'Sei sicuro di voler eliminare "{name}"? Questa azione non può essere annullata.',
- confirmDeleteSelectedMessage:
- "Eliminare le {count} connessioni selezionate? Questa azione non può essere annullata.",
+ confirmDeleteSelectedMessage: "Eliminare le {count} connessioni selezionate? Questa azione non può essere annullata.",
editConnection: "Modifica Connessione",
selectVisibleDatabases: "Seleziona Database Visibili",
duplicateConnection: "Duplica Connessione",
@@ -1045,8 +1001,7 @@ export default {
structureDocYes: "Sì",
structureDocNo: "No",
structureDocCopied: "Struttura copiata",
- structureDocCopyFallbackHint:
- "La copia automatica è stata bloccata. Fai di nuovo clic su Copia o seleziona il contenuto di seguito.",
+ structureDocCopyFallbackHint: "La copia automatica è stata bloccata. Fai di nuovo clic su Copia o seleziona il contenuto di seguito.",
saveStructure: "Salva SQL",
exportStructureCopied: "Struttura copiata",
createTable: "Crea Tabella",
@@ -1060,13 +1015,11 @@ export default {
renameObjectNamePlaceholder: "Nuovo nome",
renameObjectSuccess: '"{oldName}" rinominato in "{newName}"',
confirmDropTableTitle: "Elimina Tabella",
- confirmDropTableMessage:
- 'Sei sicuro di voler eliminare (DROP) la tabella "{name}"? Questa operazione eliminerà permanentemente la tabella e tutti i suoi dati.',
+ confirmDropTableMessage: 'Sei sicuro di voler eliminare (DROP) la tabella "{name}"? Questa operazione eliminerà permanentemente la tabella e tutti i suoi dati.',
confirmEmptyTableTitle: "Svuota Tabella",
confirmEmptyTableMessage: 'Sei sicuro di voler eliminare tutti i dati da "{name}"?',
confirmTruncateTableTitle: "Tronca Tabella",
- confirmTruncateTableMessage:
- 'Sei sicuro di voler troncare (TRUNCATE) la tabella "{name}"? Questa operazione rimuoverà tutte le righe.',
+ confirmTruncateTableMessage: 'Sei sicuro di voler troncare (TRUNCATE) la tabella "{name}"? Questa operazione rimuoverà tutte le righe.',
dropTableSuccess: 'Tabella "{name}" eliminata',
editView: "Modifica Vista",
viewSource: "Visualizza Origine",
@@ -1080,11 +1033,9 @@ export default {
batchDrop: "Elimina selezionati ({count})",
executeProcedure: "Esegui Procedura",
confirmExecuteProcedureTitle: "Esegui Procedura",
- confirmExecuteProcedureMessage:
- 'Eseguire la procedura "{name}"? È possibile compilare o regolare i valori dei parametri prima.',
+ confirmExecuteProcedureMessage: 'Eseguire la procedura "{name}"? È possibile compilare o regolare i valori dei parametri prima.',
loadingProcedureParameters: "Caricamento parametri...",
- procedureParametersUnavailable:
- "Impossibile caricare i metadati dei parametri. Puoi comunque modificare l'SQL di seguito ed eseguirlo.",
+ procedureParametersUnavailable: "Impossibile caricare i metadati dei parametri. Puoi comunque modificare l'SQL di seguito ed eseguirlo.",
noProcedureParameters: "Nessun parametro trovato. L'SQL corrente verrà eseguito come mostrato.",
inputParameters: "{count} parametri di input",
outputParameters: "{count} parametri di output",
@@ -1094,8 +1045,7 @@ export default {
parameterValue: "Valore",
parameterNull: "NULL",
parameterDefault: "DEFAULT",
- parameterDefaultHint:
- "Quando DEFAULT è selezionato, DBX omette quell'argomento in modo che il database utilizzi il valore predefinito della procedura.",
+ parameterDefaultHint: "Quando DEFAULT è selezionato, DBX omette quell'argomento in modo che il database utilizzi il valore predefinito della procedura.",
parameterValuePlaceholder: "Inserisci valore",
outputOnly: "Solo output",
sqlPreview: "Anteprima SQL",
@@ -1113,8 +1063,7 @@ export default {
confirmDropTriggerTitle: "Elimina Trigger",
confirmDropTableChildObjectMessage: 'Sei sicuro di voler eliminare "{name}" da "{table}"?',
confirmBatchDropTitle: "Elimina Oggetti Selezionati",
- confirmBatchDropMessage:
- "Sei sicuro di voler eliminare {count} oggetti selezionati? Questa azione non può essere annullata.",
+ confirmBatchDropMessage: "Sei sicuro di voler eliminare {count} oggetti selezionati? Questa azione non può essere annullata.",
confirmDropProcedureTitle: "Elimina Procedura",
confirmDropProcedureMessage: 'Sei sicuro di voler eliminare la procedura "{name}"?',
confirmDropFunctionTitle: "Elimina Funzione",
@@ -1134,8 +1083,7 @@ export default {
createDuckDbFile: "Crea File Database",
dropDatabase: "Elimina Database",
confirmDropDatabaseTitle: "Elimina Database",
- confirmDropDatabaseMessage:
- 'Sei sicuro di voler eliminare il database "{name}"? Questa operazione eliminerà permanentemente il database e tutti i suoi dati.',
+ confirmDropDatabaseMessage: 'Sei sicuro di voler eliminare il database "{name}"? Questa operazione eliminerà permanentemente il database e tutti i suoi dati.',
createDatabaseSuccess: 'Database "{name}" creato',
createDuckDbFileSuccess: 'File di database DuckDB "{name}" creato e collegato',
createDuckDbFileDesktopOnly: "La creazione di file di database DuckDB è disponibile solo nell'applicazione desktop",
@@ -1148,8 +1096,7 @@ export default {
createSchema: "Crea Schema",
dropSchema: "Elimina Schema",
confirmDropSchemaTitle: "Elimina Schema",
- confirmDropSchemaMessage:
- 'Sei sicuro di voler eliminare lo schema "{name}"? Questa operazione eliminerà permanentemente lo schema e tutti i suoi oggetti.',
+ confirmDropSchemaMessage: 'Sei sicuro di voler eliminare lo schema "{name}"? Questa operazione eliminerà permanentemente lo schema e tutti i suoi oggetti.',
createSchemaSuccess: 'Schema "{name}" creato',
dropSchemaSuccess: 'Schema "{name}" eliminato',
createSchemaNamePlaceholder: "Nome schema",
@@ -1220,8 +1167,7 @@ export default {
dropSelected: "Elimina selezionate",
clearSelection: "Cancella selezione",
confirmBatchDropTitle: "Elimina Tabelle Selezionate",
- confirmBatchDropMessage:
- "Sei sicuro di voler eliminare {count} tabelle selezionate? Questa azione non può essere annullata.",
+ confirmBatchDropMessage: "Sei sicuro di voler eliminare {count} tabelle selezionate? Questa azione non può essere annullata.",
batchDropSuccess: "Eliminate {count} tabelle",
},
structureEditor: {
@@ -1345,8 +1291,7 @@ export default {
columnValue: "Valore",
columnSize: "Dimensione",
columnTTL: "TTL",
- binaryStringReadonlyHint:
- "I valori delle stringhe binarie sono mostrati come testo con escape in modalità sola lettura; la modifica dei byte grezzi non è supportata.",
+ binaryStringReadonlyHint: "I valori delle stringhe binarie sono mostrati come testo con escape in modalità sola lettura; la modifica dei byte grezzi non è supportata.",
selectedKeys: "Chiavi selezionate",
deleteGroup: "Elimina gruppo",
deleteGroupDetails: "{target}\n{count} chiavi",
@@ -1435,8 +1380,7 @@ export default {
clear: "Cancella Cronologia",
viewDetails: "Visualizza dettagli",
analyzeWithAi: "Analizza con AI",
- aiAnalyzeNoConnection:
- "Impossibile analizzare questa voce della cronologia poiché la sua connessione non esiste più.",
+ aiAnalyzeNoConnection: "Impossibile analizzare questa voce della cronologia poiché la sua connessione non esiste più.",
aiAnalysisTab: "Analisi Cronologia",
rollback: "Rollback",
rollbackSql: "SQL di Rollback",
@@ -1486,15 +1430,12 @@ export default {
},
dangerDialog: {
title: "Operazione Pericolosa",
- message:
- "Questa istruzione SQL potrebbe modificare o eliminare i dati in modo irreversibile. Sei sicuro di volerla eseguire?",
+ message: "Questa istruzione SQL potrebbe modificare o eliminare i dati in modo irreversibile. Sei sicuro di volerla eseguire?",
suppressFuturePrompts: "Non chiedere più per SQL pericolosi",
deleteMessage: "Questa operazione di eliminazione potrebbe essere irreversibile. Continuare?",
deleteConfirm: "Conferma Eliminazione",
- deleteRowMessage:
- "Questa riga verrà contrassegnata per l'eliminazione e rimossa dal database dopo il salvataggio. Continuare?",
- deleteRowsMessage:
- "Queste {count} righe verranno contrassegnate per l'eliminazione e rimosse dal database dopo il salvataggio. Continuare?",
+ deleteRowMessage: "Questa riga verrà contrassegnata per l'eliminazione e rimossa dal database dopo il salvataggio. Continuare?",
+ deleteRowsMessage: "Queste {count} righe verranno contrassegnate per l'eliminazione e rimosse dal database dopo il salvataggio. Continuare?",
deleteRowDetails: "Tabella: {table}",
deleteRowDetailsNoTable: "Riga del risultato corrente",
redisKeyDetails: "Chiave Redis: {key}",
@@ -1636,22 +1577,19 @@ export default {
selectedTables: "{selected}/{total} selezionate",
selectAllTables: "Seleziona tutte",
deselectAllTables: "Deseleziona tutte",
- selectSourceTables:
- "Seleziona prima la connessione e il database sorgente, quindi scegli le tabelle da confrontare",
+ selectSourceTables: "Seleziona prima la connessione e il database sorgente, quindi scegli le tabelle da confrontare",
noTables: "Nessuna tabella disponibile per il confronto",
autoMatchHint: "La modalità batch associa automaticamente le tabelle di destinazione con lo stesso nome",
matchedTables: "{matched}/{total} tabelle associate",
missingTargetTables: "Tabelle di destinazione con lo stesso nome mancanti: {tables}",
keyColumns: "Colonne Chiave",
keyColumnsPlaceholder: "Colonne primarie o uniche separate da virgola",
- keyColumnsAutoHint:
- "Lascia vuoto per rilevare automaticamente le chiavi primarie per il confronto a tabella singola, o per tabella nel confronto batch.",
+ keyColumnsAutoHint: "Lascia vuoto per rilevare automaticamente le chiavi primarie per il confronto a tabella singola, o per tabella nel confronto batch.",
rowCounts: "Sorgente {source} righe, destinazione {target} righe; confronto completo completato",
previewLimitOption: "Anteprima {count}",
compare: "Confronta Dati",
summary: "Aggiunte {added}, rimosse {removed}, modificate {modified}",
- batchSummary:
- "Confrontate {tables} tabelle: {different} diverse, {same} identiche, {failed} non riuscite; aggiunte {added}, rimosse {removed}, modificate {modified}",
+ batchSummary: "Confrontate {tables} tabelle: {different} diverse, {same} identiche, {failed} non riuscite; aggiunte {added}, rimosse {removed}, modificate {modified}",
comparingTable: "Confronto di {current}/{total}: {table}",
keyColumnsInline: "Colonne chiave: {columns}",
selectedInline: "Selezionate {selected}/{total}",
@@ -1664,18 +1602,15 @@ export default {
remainingRows: "altre {count} righe nascoste nell'anteprima",
planningSync: "Aggiornamento del piano di sincronizzazione...",
noSelectedDifferences: "Nessuna differenza selezionata per l'esecuzione",
- planSummary:
- "Piano: {inserts} inserimenti, {updates} aggiornamenti, {deletes} eliminazioni, {statements} istruzioni",
+ planSummary: "Piano: {inserts} inserimenti, {updates} aggiornamenti, {deletes} eliminazioni, {statements} istruzioni",
statusDifferent: "Diverse",
statusSame: "Identiche",
statusError: "Non riuscite",
noKeyColumns: "Seleziona almeno una colonna chiave",
- missingKeyColumns:
- "Le colonne chiave devono esistere sia nella tabella sorgente che in quella di destinazione: {columns}",
+ missingKeyColumns: "Le colonne chiave devono esistere sia nella tabella sorgente che in quella di destinazione: {columns}",
noCommonColumns: "Le tabelle sorgente e destinazione non hanno colonne comuni da confrontare",
targetTableMissing: "Tabella di destinazione non trovata: {table}",
- noComparableTables:
- "Nessuna tabella confrontabile trovata. Verifica se esistono tabelle di destinazione con lo stesso nome.",
+ noComparableTables: "Nessuna tabella confrontabile trovata. Verifica se esistono tabelle di destinazione con lo stesso nome.",
noDifferences: "I dati sono identici, nessun SQL di sincronizzazione necessario",
syncSuccess: "Sincronizzazione dei dati eseguita con successo",
},
@@ -1745,8 +1680,7 @@ export default {
languageTitle: "Lingua / Language",
fontSize: "Dimensione Carattere",
uiScale: "Scala UI",
- uiScaleDescription:
- "Scala l'intera interfaccia utente desktop per display ad alta densità (High-DPI). Le modifiche si applicano immediatamente e vengono ripristinate al prossimo avvio.",
+ uiScaleDescription: "Scala l'intera interfaccia utente desktop per display ad alta densità (High-DPI). Le modifiche si applicano immediatamente e vengono ripristinate al prossimo avvio.",
theme: "Tema",
selectTheme: "Seleziona tema...",
followAppTheme: "Segui il tema dell'applicazione",
@@ -1761,14 +1695,11 @@ export default {
iconThemeBlack: "Nero",
iconThemeBlackDescription: "Utilizza il marchio DBX nero per la finestra, la barra delle applicazioni e il logo.",
showTrayIcon: "Mostra icona nella barra delle applicazioni/menu",
- showTrayIconDescription:
- "Se disattivato, non viene mostrata alcuna icona, ma la chiusura della finestra nasconderà comunque DBX in background.",
+ showTrayIconDescription: "Se disattivato, non viene mostrata alcuna icona, ma la chiusura della finestra nasconderà comunque DBX in background.",
updateNotificationsEnabled: "Abilita promemoria aggiornamenti",
- updateNotificationsEnabledDescription:
- "Se disattivato, DBX non controllerà automaticamente gli aggiornamenti dell'app o dei driver e non mostrerà badge. I controlli manuali restano disponibili.",
+ updateNotificationsEnabledDescription: "Se disattivato, DBX non controllerà automaticamente gli aggiornamenti dell'app o dei driver e non mostrerà badge. I controlli manuali restano disponibili.",
debugLoggingEnabled: "Abilita log di debug",
- debugLoggingEnabledDescription:
- "Registra log diagnostici locali lato utente durante l'analisi delle segnalazioni. Disattivato per impostazione predefinita.",
+ debugLoggingEnabledDescription: "Registra log diagnostici locali lato utente durante l'analisi delle segnalazioni. Disattivato per impostazione predefinita.",
debugLogsCopy: "Copia log",
debugLogsCopied: "Copiati",
debugLogsDownload: "Scarica log",
@@ -1776,14 +1707,11 @@ export default {
debugLogsClear: "Cancella log",
dataGridDisplay: "Visualizzazione griglia dati",
showColumnCommentsInHeader: "Mostra i commenti delle colonne sotto i nomi",
- showColumnCommentsInHeaderDescription:
- "Visualizza i commenti delle colonne della tabella direttamente sotto i nomi delle colonne nella griglia.",
+ showColumnCommentsInHeaderDescription: "Visualizza i commenti delle colonne della tabella direttamente sotto i nomi delle colonne nella griglia.",
showColumnTypesInHeader: "Mostra i tipi di colonna sotto i nomi",
- showColumnTypesInHeaderDescription:
- "Visualizza il tipo di dato di ciascuna colonna direttamente sotto i nomi delle colonne nella griglia.",
+ showColumnTypesInHeaderDescription: "Visualizza il tipo di dato di ciascuna colonna direttamente sotto i nomi delle colonne nella griglia.",
compactColumnHeaderActions: "Strumenti intestazione colonna compatti",
- compactColumnHeaderActionsDescription:
- "Sposta gli strumenti del formattatore e dei filtri locali in un menu 'altro' in modo che i nomi delle colonne abbiano la priorità.",
+ compactColumnHeaderActionsDescription: "Sposta gli strumenti del formattatore e dei filtri locali in un menu 'altro' in modo che i nomi delle colonne abbiano la priorità.",
sidebarActivation: "Attivazione barra laterale",
sidebarActivationSingle: "Singolo clic",
sidebarActivationSingleDescription: "Apri gli elementi della barra laterale con un solo clic.",
@@ -1791,38 +1719,28 @@ export default {
sidebarActivationDoubleDescription: "Un singolo clic seleziona le righe; un doppio clic apre gli elementi.",
sidebarObjectDisplay: "Layout oggetti barra laterale",
sidebarObjectDisplayGrouped: "Vista avanzata",
- sidebarObjectDisplayGroupedDescription:
- "Raggruppa gli oggetti per tabelle, viste, procedure e funzioni per i database con più tipi di oggetti.",
+ sidebarObjectDisplayGroupedDescription: "Raggruppa gli oggetti per tabelle, viste, procedure e funzioni per i database con più tipi di oggetti.",
sidebarObjectDisplaySimple: "Vista semplice",
- sidebarObjectDisplaySimpleDescription:
- "Elenca tabelle e viste direttamente sotto ogni database o schema per ridurre i livelli intermedi.",
+ sidebarObjectDisplaySimpleDescription: "Elenca tabelle e viste direttamente sotto ogni database o schema per ridurre i livelli intermedi.",
autoSelectActiveSidebarNode: "Seleziona sempre l'elemento aperto",
- autoSelectActiveSidebarNodeDescription:
- "Quando passi da una scheda all'altra, seleziona la tabella, la collezione o il file SQL visibile corrispondente nella barra laterale.",
+ autoSelectActiveSidebarNodeDescription: "Quando passi da una scheda all'altra, seleziona la tabella, la collezione o il file SQL visibile corrispondente nella barra laterale.",
disconnectTabHandlingMode: "Schede dopo la disconnessione",
- disconnectTabHandlingModeDescription:
- "Scegli come gestire le schede correlate dopo la chiusura di una connessione o di un database.",
+ disconnectTabHandlingModeDescription: "Scegli come gestire le schede correlate dopo la chiusura di una connessione o di un database.",
disconnectTabHandlingModeCloseTabs: "Chiudi tutte le schede",
disconnectTabHandlingModeCloseTabsDescription: "Chiudi tutte le schede correlate per la connessione o il database.",
disconnectTabHandlingModeKeepTabsClearResults: "Chiudi schede oggetti, mantieni schede SQL",
- disconnectTabHandlingModeKeepTabsClearResultsDescription:
- "Chiudi i dati delle tabelle, l'esplorazione degli oggetti e le schede della struttura mantenendo le schede delle query SQL e il testo SQL, e cancella anche lo stato di esecuzione e le sessioni dei risultati.",
+ disconnectTabHandlingModeKeepTabsClearResultsDescription: "Chiudi i dati delle tabelle, l'esplorazione degli oggetti e le schede della struttura mantenendo le schede delle query SQL e il testo SQL, e cancella anche lo stato di esecuzione e le sessioni dei risultati.",
disconnectTabHandlingModeKeepTabsKeepResults: "Non chiudere le schede correlate",
- disconnectTabHandlingModeKeepTabsKeepResultsDescription:
- "Mantieni le schede correlate, il testo SQL e i risultati correnti senza ulteriore pulizia.",
+ disconnectTabHandlingModeKeepTabsKeepResultsDescription: "Mantieni le schede correlate, il testo SQL e i risultati correnti senza ulteriore pulizia.",
reuseDataTab: "Riusa scheda dati",
- reuseDataTabDescription:
- "Quando fai clic su una tabella nella barra laterale, riutilizza la scheda dati esistente invece di crearne una nuova ogni volta.",
+ reuseDataTabDescription: "Quando fai clic su una tabella nella barra laterale, riutilizza la scheda dati esistente invece di crearne una nuova ogni volta.",
sidebarHiddenTablePrefixes: "Prefissi dei nomi delle tabelle nascosti",
- sidebarHiddenTablePrefixesDescription:
- "Un prefisso per riga. Solo le etichette di tabelle, viste e collezioni della barra laterale vengono abbreviate; i suggerimenti e le azioni utilizzano ancora il nome completo.",
+ sidebarHiddenTablePrefixesDescription: "Un prefisso per riga. Solo le etichette di tabelle, viste e collezioni della barra laterale vengono abbreviate; i suggerimenti e le azioni utilizzano ancora il nome completo.",
sidebarHiddenTablePrefixesPlaceholder: "Esempio:\nODS_\nT8Y2_LONG_",
sidebarHideTableComments: "Nascondi i commenti delle tabelle nella barra laterale",
- sidebarHideTableCommentsDescription:
- "Nascondi i commenti in linea delle tabelle/viste mostrati accanto ai nomi nell'albero della barra laterale per risparmiare spazio orizzontale.",
+ sidebarHideTableCommentsDescription: "Nascondi i commenti in linea delle tabelle/viste mostrati accanto ai nomi nell'albero della barra laterale per risparmiare spazio orizzontale.",
sidebarAllowHorizontalScroll: "Consenti scorrimento orizzontale barra laterale",
- sidebarAllowHorizontalScrollDescription:
- "Mostra i nomi lunghi di tabelle, viste e collezioni per intero consentendo lo scorrimento orizzontale della barra laterale.",
+ sidebarAllowHorizontalScrollDescription: "Mostra i nomi lunghi di tabelle, viste e collezioni per intero consentendo lo scorrimento orizzontale della barra laterale.",
snippetsDescription: "Personalizza i modelli di snippet SQL attivati nell'editor.",
snippetsAdd: "Aggiungi Snippet",
snippetsLabel: "Etichetta",
@@ -1835,8 +1753,7 @@ export default {
snippetsAddTitle: "Aggiungi Snippet",
snippetsEditTitle: "Modifica Snippet",
syncWebDavTitle: "Sincronizzazione WebDAV",
- syncWebDavDescription:
- "Carica o ripristina uno snapshot di DBX da un servizio di archiviazione compatibile con WebDAV.",
+ syncWebDavDescription: "Carica o ripristina uno snapshot di DBX da un servizio di archiviazione compatibile con WebDAV.",
syncEndpoint: "URL WebDAV",
syncUsername: "Nome utente",
syncPassword: "Password",
@@ -1844,18 +1761,14 @@ export default {
syncClearSavedPassword: "Cancella password salvata",
syncRememberWebDavPassword: "Ricorda la password dell'app WebDAV",
syncSavedPassword: "(salvata)",
- syncRememberWebDavPasswordDescription:
- "La password viene crittografata e memorizzata solo su questo dispositivo. Non viene sincronizzata su WebDAV e non sostituisce la password di sincronizzazione.",
+ syncRememberWebDavPasswordDescription: "La password viene crittografata e memorizzata solo su questo dispositivo. Non viene sincronizzata su WebDAV e non sostituisce la password di sincronizzazione.",
syncRemotePath: "Percorso snapshot remoto",
syncRemotePathDescription: "DBX creerà le cartelle superiori mancanti durante il caricamento.",
- syncSecretNotice:
- "Per impostazione predefinita, DBX sincronizza solo i dettagli e le impostazioni di connessione. Le password dei database, le password SSH, le password proxy, le stringhe di connessione e le chiavi API AI rimangono locali.",
+ syncSecretNotice: "Per impostazione predefinita, DBX sincronizza solo i dettagli e le impostazioni di connessione. Le password dei database, le password SSH, le password proxy, le stringhe di connessione e le chiavi API AI rimangono locali.",
syncSecrets: "Sincronizza i segreti crittografati",
- syncSecretsDescription:
- "Se abilitato, DBX crittografa le password del database, le password SSH e le chiavi API AI prima di caricarle su WebDAV.",
+ syncSecretsDescription: "Se abilitato, DBX crittografa le password del database, le password SSH e le chiavi API AI prima di caricarle su WebDAV.",
syncSecretsPassphrase: "Password di sincronizzazione",
- syncSecretsPassphraseDescription:
- "Questa password viene utilizzata solo per crittografare e ripristinare i dati sensibili. DBX non la salva; inseriscila nuovamente su ciascun dispositivo.",
+ syncSecretsPassphraseDescription: "Questa password viene utilizzata solo per crittografare e ripristinare i dati sensibili. DBX non la salva; inseriscila nuovamente su ciascun dispositivo.",
syncTest: "Verifica",
syncUpload: "Carica",
syncDownload: "Scarica",
@@ -1864,8 +1777,7 @@ export default {
syncDownloadSuccess: "Scaricati e applicati {bytes} byte da {path}.",
syncSecretsApplied: "I segreti crittografati sono stati ripristinati.",
syncSecretsSkipped: "I segreti crittografati erano presenti ma non sono stati ripristinati.",
- syncDownloadConfirm:
- "Scaricare e applicare lo snapshot DBX remoto? I metadati locali e i file SQL salvati verranno sostituiti.",
+ syncDownloadConfirm: "Scaricare e applicare lo snapshot DBX remoto? I metadati locali e i file SQL salvati verranno sostituiti.",
apply: "Applica",
applyAndClose: "Applica e Chiudi",
reset: "Reimposta",
@@ -1878,14 +1790,12 @@ export default {
wordWrap: "A capo automatico",
wordWrapDescription: "Incolonna le righe SQL lunghe entro la larghezza dell'editor",
confirmDangerousSqlExecution: "Conferma prima di SQL pericoloso",
- confirmDangerousSqlExecutionDescription:
- "Se disattivato, ALTER, DROP, DELETE, TRUNCATE e altri SQL pericolosi verranno eseguiti senza la finestra di avviso.",
+ confirmDangerousSqlExecutionDescription: "Se disattivato, ALTER, DROP, DELETE, TRUNCATE e altri SQL pericolosi verranno eseguiti senza la finestra di avviso.",
redisScanPageSize: "Conteggio scansione Redis",
redisScanPageSizeDescription: "Chiavi richieste per pagina SCAN di Redis durante la navigazione delle chiavi.",
redisScanPageSizeOption: "{count} chiavi",
exportBatchSize: "Dimensione del lotto di esportazione",
- exportBatchSizeDescription:
- "Righe recuperate per lotto durante l'esportazione dei dati della tabella (100-100000).",
+ exportBatchSizeDescription: "Righe recuperate per lotto durante l'esportazione dei dati della tabella (100-100000).",
exportSection: "Esportazione",
shortcutExecuteSql: "Esegui SQL",
shortcutFind: "Trova",
@@ -1961,8 +1871,7 @@ export default {
jdbcDeleteSuccess: "Driver rimosso",
jdbcNoDrivers: "Nessun driver JDBC ancora importato.",
mcpTitle: "Server MCP",
- mcpDescription:
- "Verifica l'installazione e la versione del Server DBX MCP utilizzata da Claude Code, Cursor e altri agenti.",
+ mcpDescription: "Verifica l'installazione e la versione del Server DBX MCP utilizzata da Claude Code, Cursor e altri agenti.",
mcpChecking: "Verifica in corso",
mcpStatusUnknown: "Non verificato",
mcpStatusError: "Verifica non riuscita",
@@ -1982,15 +1891,11 @@ export default {
mcpCodexConfig: "Configurazione Codex",
mcpCodexConfigPath: "Codex può utilizzare ~/.codex/config.toml o un .codex/config.toml a livello di progetto.",
mcpReadonlyMode: "Modalità sola lettura",
- mcpReadonlyModeDescription:
- "Aggiunge DBX_MCP_ALLOW_WRITES=0 alla configurazione di esempio in modo che la sessione MCP rimanga di sola query.",
+ mcpReadonlyModeDescription: "Aggiunge DBX_MCP_ALLOW_WRITES=0 alla configurazione di esempio in modo che la sessione MCP rimanga di sola query.",
mcpAllowDangerous: "Consenti SQL pericoloso",
- mcpAllowDangerousDescription:
- "Aggiunge DBX_MCP_ALLOW_DANGEROUS_SQL=1 alla configurazione di esempio in modo che siano consentite istruzioni come DROP, TRUNCATE, ALTER e simili.",
- mcpDetectionTiming:
- "DBX esegue la verifica automaticamente all'apertura di questa pagina; usa di nuovo Verifica per aggiornare.",
- mcpNpmBoundary:
- "DBX verifica e spiega solo lo stato di MCP; l'installazione e gli aggiornamenti vengono comunque eseguiti tramite npm.",
+ mcpAllowDangerousDescription: "Aggiunge DBX_MCP_ALLOW_DANGEROUS_SQL=1 alla configurazione di esempio in modo che siano consentite istruzioni come DROP, TRUNCATE, ALTER e simili.",
+ mcpDetectionTiming: "DBX esegue la verifica automaticamente all'apertura di questa pagina; usa di nuovo Verifica per aggiornare.",
+ mcpNpmBoundary: "DBX verifica e spiega solo lo stato di MCP; l'installazione e gli aggiornamenti vengono comunque eseguiti tramite npm.",
mcpRefresh: "Verifica di nuovo",
mcpGuide: "Guida MCP",
aboutDescription: "Uno strumento di gestione di database leggero e open-source.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 8bb395b161..7dd4593c30 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -51,12 +51,10 @@ export default {
availableMessage: "DBX {latest} está disponível. Você está usando {current}.",
upToDate: "O DBX está atualizado ({version}).",
failed: "Falha ao verificar atualizações: {error}",
- rateLimited:
- "As verificações de atualização do GitHub estão temporariamente limitadas. Você ainda pode abrir a página de lançamento para verificar manualmente.",
+ rateLimited: "As verificações de atualização do GitHub estão temporariamente limitadas. Você ainda pode abrir a página de lançamento para verificar manualmente.",
openRelease: "Abrir Lançamento",
downloadAndInstall: "Baixar e Instalar",
- portableManualUpdate:
- "Versões portáteis não podem usar o instalador interno. Baixe o ZIP portátil da página de lançamento e extraia-o sobre a pasta atual do DBX para manter o portable.dbx e os dados.",
+ portableManualUpdate: "Versões portáteis não podem usar o instalador interno. Baixe o ZIP portátil da página de lançamento e extraia-o sobre a pasta atual do DBX para manter o portable.dbx e os dados.",
downloading: "Baixando {progress}%",
downloadFailed: "Falha ao baixar a atualização: {error}",
restart: "Sair e Reiniciar",
@@ -146,8 +144,7 @@ export default {
memoryDatabasePathHint: "Use :memory: para criar um banco de dados SQLite ou DuckDB na memória.",
sqliteExtensions: "Extensões SQLite",
sqliteExtensionsPlaceholder: "/caminho/para/regexp.dylib\n/caminho/para/text.dylib|sqlite3_text_init",
- sqliteExtensionsHint:
- "Um .dylib/.so/.dll por linha. Use “caminho|ponto de entrada” quando um ponto de entrada for necessário. Carregado ao conectar, depois load_extension é desabilitado.",
+ sqliteExtensionsHint: "Um .dylib/.so/.dll por linha. Use “caminho|ponto de entrada” quando um ponto de entrada for necessário. Carregado ao conectar, depois load_extension é desabilitado.",
sqliteExtensionBrowse: "Selecionar extensão SQLite",
user: "Usuário",
password: "Senha",
@@ -179,13 +176,11 @@ export default {
mysqlTlsModeRequired: "Obrigatório",
mysqlTlsModeVerifyCa: "Verificar CA",
mysqlTlsModeVerifyIdentity: "Verificar Identidade",
- mysqlCaCertHint:
- "Necessário para Verificar CA e Verificar Identidade quando o certificado do servidor usa uma CA privada.",
+ mysqlCaCertHint: "Necessário para Verificar CA e Verificar Identidade quando o certificado do servidor usa uma CA privada.",
mysqlClientCert: "Autenticação do Cliente",
mysqlClientCertPlaceholder: "/caminho/para/client.crt",
mysqlClientKeyPlaceholder: "/caminho/para/client.key",
- mysqlClientCertHint:
- "O certificado e a chave privada do cliente devem ser fornecidos juntos quando o MySQL exige mTLS.",
+ mysqlClientCertHint: "O certificado e a chave privada do cliente devem ser fornecidos juntos quando o MySQL exige mTLS.",
mysqlClientCertBrowse: "Escolher certificado do cliente",
mysqlClientKeyBrowse: "Escolher chave privada do cliente",
postgresSslMode: "Modo TLS",
@@ -196,14 +191,12 @@ export default {
postgresSslModeVerifyFull: "Verificar Completo",
postgresServerCert: "CA do Servidor",
postgresRootCertPlaceholder: "/caminho/para/ca.crt",
- postgresRootCertHint:
- "Use isto para verify-ca ou verify-full quando o certificado do servidor é assinado por uma CA privada.",
+ postgresRootCertHint: "Use isto para verify-ca ou verify-full quando o certificado do servidor é assinado por uma CA privada.",
postgresRootCertBrowse: "Escolher certificado CA",
postgresClientCert: "Autenticação do Cliente",
postgresClientCertPlaceholder: "/caminho/para/client.crt",
postgresClientKeyPlaceholder: "/caminho/para/client.key",
- postgresClientCertHint:
- "O certificado e a chave privada do cliente devem ser fornecidos juntos quando o PostgreSQL exige mTLS.",
+ postgresClientCertHint: "O certificado e a chave privada do cliente devem ser fornecidos juntos quando o PostgreSQL exige mTLS.",
postgresClientCertBrowse: "Escolher certificado do cliente",
postgresClientKeyBrowse: "Escolher chave privada do cliente",
connectionUrlOptional: "URL (opcional)",
@@ -248,8 +241,7 @@ export default {
connectFailed: "Falha na conexão: {message}",
driverNotInstalled: "O driver {driver} não está instalado. Instale-o pelo Gerenciador de Drivers.",
jreNotInstalled: "O runtime JRE {jre} não está instalado. Instale-o pelo Gerenciador de Drivers.",
- systemJavaNotFound:
- "O runtime Java do sistema não foi encontrado no PATH. Instale o Java ou escolha um executável Java personalizado.",
+ systemJavaNotFound: "O runtime Java do sistema não foi encontrado no PATH. Instale o Java ou escolha um executável Java personalizado.",
customJavaPathEmpty: "O caminho do runtime Java personalizado está vazio. Escolha um executável Java.",
jdbcPluginNotInstalled: "O plugin JDBC não está instalado. Instale o plugin JDBC opcional para usar esta conexão.",
lastError: "Erro de conexão",
@@ -304,19 +296,16 @@ export default {
jdbcUrl: "URL JDBC",
jdbcUrlPlaceholder: "jdbc:postgresql://localhost:5432/database",
jdbcDriverClass: "Classe do Driver (opcional)",
- jdbcDriverClassPlaceholder:
- "A maioria dos drivers se registra automaticamente; use com.vendor.jdbc.Driver se necessário",
+ jdbcDriverClassPlaceholder: "A maioria dos drivers se registra automaticamente; use com.vendor.jdbc.Driver se necessário",
jdbcDriverPaths: "JARs do Driver",
jdbcDriverSelectPlaceholder: "Escolher driver importado",
jdbcDriverPathsPlaceholder: "/caminho/para/driver.jar\n/caminho/para/outro-driver.jar",
jdbcDriverBrowse: "Escolher JAR do driver JDBC",
jdbcDocs: "Ver documentação JDBC",
- jdbcPluginHint:
- "Instale primeiro o plugin JDBC do DBX e depois importe o JAR do driver JDBC do fornecedor do banco de dados.",
+ jdbcPluginHint: "Instale primeiro o plugin JDBC do DBX e depois importe o JAR do driver JDBC do fornecedor do banco de dados.",
dmCompatHint: "Requer o driver ODBC DM8 instalado no seu sistema.",
dmDownload: "Baixar da Dameng",
- mongoLegacyHint:
- "MongoDB abaixo de 4.2 requer o driver MongoDB (Legacy). Se a autenticação falhar e o usuário foi criado em admin, defina o BD de autenticação como admin.",
+ mongoLegacyHint: "MongoDB abaixo de 4.2 requer o driver MongoDB (Legacy). Se a autenticação falhar e o usuário foi criado em admin, defina o BD de autenticação como admin.",
compatible: "Compatível",
mainstream: "Popular",
color: "Cor",
@@ -528,8 +517,7 @@ export default {
formatterCustomName: "Nome do template",
formatterCustomNamePlaceholder: "Exemplo: Rótulo do usuário",
formatterCustomTemplateInput: "Template",
- formatterCustomTemplateHint:
- "Variáveis disponíveis: ${value}, ${upper}, ${lower}, ${length}. Dê um nome para salvá-lo na lista.",
+ formatterCustomTemplateHint: "Variáveis disponíveis: ${value}, ${upper}, ${lower}, ${length}. Dê um nome para salvá-lo na lista.",
formatterPreview: "Visualização",
saveFormatter: "Salvar",
clearFormatter: "Limpar",
@@ -665,8 +653,7 @@ export default {
transposeMultiRowToggle: "Várias linhas",
transposeSingleRow: "Linha atual",
transposeMultiRow: "Várias linhas",
- transposeMultiRowHint:
- "Quando ativado, a visualização transposta mostra várias linhas. Quando desativado, mostra apenas a linha atual.",
+ transposeMultiRowHint: "Quando ativado, a visualização transposta mostra várias linhas. Quando desativado, mostra apenas a linha atual.",
rowsPerPageShort: " linhas",
columnDetails: "Detalhes da Coluna",
tableInfo: "Informações da Tabela",
@@ -684,39 +671,27 @@ export default {
commit: "Confirmar",
rollback: "Reverter",
transactionSaveHint: "Confirmar {count} alteração(ões) pendente(s) em uma transação.",
- nonTransactionalSaveHint:
- "Salvar {count} alteração(ões) pendente(s) uma a uma. Se uma falhar, as alterações bem-sucedidas anteriores não serão revertidas.",
+ nonTransactionalSaveHint: "Salvar {count} alteração(ões) pendente(s) uma a uma. Se uma falhar, as alterações bem-sucedidas anteriores não serão revertidas.",
keylessEditWarning: "Sem chave primária",
- keylessEditWarningHint:
- "Esta tabela não possui chave primária. Atualizações e exclusões usam todos os valores originais da linha na cláusula WHERE; linhas exatamente duplicadas podem ser afetadas juntas.",
+ keylessEditWarningHint: "Esta tabela não possui chave primária. Atualizações e exclusões usam todos os valores originais da linha na cláusula WHERE; linhas exatamente duplicadas podem ser afetadas juntas.",
queryEditReady: "Editável",
- queryEditReadyHint:
- "Este resultado de tabela única vem de “{table}”. Você pode editar, excluir ou adicionar linhas e, em seguida, usar a ação de alterações pendentes para salvar.",
+ queryEditReadyHint: "Este resultado de tabela única vem de “{table}”. Você pode editar, excluir ou adicionar linhas e, em seguida, usar a ação de alterações pendentes para salvar.",
queryEditReadOnly: "Resultado somente leitura",
queryEditUnsupported: {
"not-select": "Apenas resultados de consultas SELECT podem ser editados diretamente.",
cte: "Consultas com WITH/CTE ainda não são editáveis. Use um SELECT simples de tabela única.",
- "set-operation":
- "Resultados de UNION, INTERSECT ou EXCEPT não podem ser mapeados com segurança de volta às linhas de origem.",
+ "set-operation": "Resultados de UNION, INTERSECT ou EXCEPT não podem ser mapeados com segurança de volta às linhas de origem.",
aggregation: "Resultados de DISTINCT, GROUP BY, HAVING e agregações não podem ser editados diretamente.",
- "external-source":
- "Arquivos externos e resultados de funções de tabela não podem ser gravados de volta diretamente. Importe-os para uma tabela do banco de dados antes de editar.",
- "complex-source":
- "JOINs, múltiplas tabelas e subconsultas não podem ser mapeados com segurança para uma única linha de origem.",
- "computed-columns":
- "Expressões computadas ou resultados de funções não podem ser gravados de volta. Selecione os nomes brutos das colunas em vez disso.",
+ "external-source": "Arquivos externos e resultados de funções de tabela não podem ser gravados de volta diretamente. Importe-os para uma tabela do banco de dados antes de editar.",
+ "complex-source": "JOINs, múltiplas tabelas e subconsultas não podem ser mapeados com segurança para uma única linha de origem.",
+ "computed-columns": "Expressões computadas ou resultados de funções não podem ser gravados de volta. Selecione os nomes brutos das colunas em vez disso.",
"no-table": "Nenhuma tabela de origem editável foi detectada.",
- "no-primary-key":
- "A tabela de destino não possui chave primária, portanto as linhas não podem ser atualizadas ou excluídas com segurança.",
- "primary-key-not-returned":
- "O resultado está sem a coluna bruta da chave primária. Inclua-a pelo seu nome de coluna original.",
- "aliased-columns":
- "As colunas do resultado usam aliases ou expressões. Selecione colunas editáveis pelos seus nomes originais.",
- "metadata-unavailable":
- "O DBX não conseguiu carregar os metadados da tabela, portanto a edição do resultado está desabilitada.",
+ "no-primary-key": "A tabela de destino não possui chave primária, portanto as linhas não podem ser atualizadas ou excluídas com segurança.",
+ "primary-key-not-returned": "O resultado está sem a coluna bruta da chave primária. Inclua-a pelo seu nome de coluna original.",
+ "aliased-columns": "As colunas do resultado usam aliases ou expressões. Selecione colunas editáveis pelos seus nomes originais.",
+ "metadata-unavailable": "O DBX não conseguiu carregar os metadados da tabela, portanto a edição do resultado está desabilitada.",
},
- sortUnsupported:
- "Este SQL não suporta a ordenação do resultado completo. Tente novamente com uma única consulta SELECT.",
+ sortUnsupported: "Este SQL não suporta a ordenação do resultado completo. Tente novamente com uma única consulta SELECT.",
truncatedHint: "Resultados truncados em {count} linhas. Use a paginação no rodapé ou ajuste as linhas por página.",
},
exportProgress: {
@@ -754,8 +729,7 @@ export default {
tipExecute: "para executar a consulta",
fileOpened: "{name} aberto",
mcpTitle: "Integração com Agente de IA",
- mcpDescription:
- "Além do assistente de IA integrado, você também pode usar Claude Code, Cursor e outros agentes de codificação para consultar seus bancos de dados via MCP.",
+ mcpDescription: "Além do assistente de IA integrado, você também pode usar Claude Code, Cursor e outros agentes de codificação para consultar seus bancos de dados via MCP.",
mcpLearnMore: "Saiba mais",
},
common: {
@@ -806,20 +780,13 @@ export default {
sameName: "Mesmo Nome",
},
description: {
- foreignKeyIncoming:
- "{target} aponta para o campo atual através de uma chave estrangeira. Esta é uma dependência verificada.",
- foreignKeyOutgoing:
- "O campo atual referencia {target} através de uma chave estrangeira. Esta é uma dependência verificada.",
- viewLikely:
- "A definição da visão menciona tanto a tabela quanto o campo de destino, geralmente indicando dependência de consulta.",
- viewPossible:
- "A definição da visão menciona um campo de mesmo nome, mas não a tabela de destino, então precisa de confirmação.",
- historyLikely:
- "Uma instrução SQL histórica menciona tanto a tabela quanto o campo de destino. Use-a como contexto de análise de impacto.",
- historyPossible:
- "Uma instrução SQL histórica menciona um campo de mesmo nome. Pode estar relacionado, mas precisa de contexto.",
- sameName:
- "Outra tabela possui um campo de mesmo nome. Isso pode compartilhar significado de negócio, mas não é uma dependência verificada do banco de dados.",
+ foreignKeyIncoming: "{target} aponta para o campo atual através de uma chave estrangeira. Esta é uma dependência verificada.",
+ foreignKeyOutgoing: "O campo atual referencia {target} através de uma chave estrangeira. Esta é uma dependência verificada.",
+ viewLikely: "A definição da visão menciona tanto a tabela quanto o campo de destino, geralmente indicando dependência de consulta.",
+ viewPossible: "A definição da visão menciona um campo de mesmo nome, mas não a tabela de destino, então precisa de confirmação.",
+ historyLikely: "Uma instrução SQL histórica menciona tanto a tabela quanto o campo de destino. Use-a como contexto de análise de impacto.",
+ historyPossible: "Uma instrução SQL histórica menciona um campo de mesmo nome. Pode estar relacionado, mas precisa de contexto.",
+ sameName: "Outra tabela possui um campo de mesmo nome. Isso pode compartilhar significado de negócio, mas não é uma dependência verificada do banco de dados.",
},
cancel: "Cancelar",
refresh: "Analisar Novamente",
@@ -860,8 +827,7 @@ export default {
configExport: {
passphraseTitle: "Criptografar e Exportar",
passphraseImportTitle: "Descriptografar e Importar",
- passphraseExportHint:
- "Para incluir as senhas de conexão na exportação, defina uma frase secreta para a criptografia. Você precisará da mesma frase secreta para importar.",
+ passphraseExportHint: "Para incluir as senhas de conexão na exportação, defina uma frase secreta para a criptografia. Você precisará da mesma frase secreta para importar.",
passphraseImportHint: "Este arquivo está criptografado. Digite a frase secreta para descriptografar e importar.",
passphrase: "Frase secreta",
passphraseConfirm: "Confirmar Frase Secreta",
@@ -873,15 +839,12 @@ export default {
exportEncrypted: "Exportar",
decryptImport: "Descriptografar e Importar",
wrongPassphrase: "Frase secreta incorreta ou arquivo corrompido",
- cryptoUnavailable:
- "A importação criptografada não está disponível neste contexto do navegador. Use HTTPS, localhost ou DBX Desktop.",
+ cryptoUnavailable: "A importação criptografada não está disponível neste contexto do navegador. Use HTTPS, localhost ou DBX Desktop.",
exportSuccess: "Conexões exportadas com sucesso",
importSuccess: "{count} conexão(ões) importada(s)",
- importNavicatSuccess:
- "{count} conexão(ões) do Navicat importada(s). Preencha qualquer conexão cuja senha ainda esteja vazia antes de testar.",
+ importNavicatSuccess: "{count} conexão(ões) do Navicat importada(s). Preencha qualquer conexão cuja senha ainda esteja vazia antes de testar.",
importDatagripSuccess: "{count} conexão(ões) DataGrip importada(s), {filled} senha(s) preenchida(s) do Keychain.",
- importDbeaverSuccess:
- "{count} conexão(ões) do DBeaver importada(s). Preencha qualquer conexão cuja senha ainda esteja vazia antes de testar.",
+ importDbeaverSuccess: "{count} conexão(ões) do DBeaver importada(s). Preencha qualquer conexão cuja senha ainda esteja vazia antes de testar.",
importNone: "Nenhuma conexão nova para importar",
importLayoutConfirm: "O arquivo importado contém grupos de conexões. Aplicá-los?",
importLayoutTitle: "Importar Grupos",
@@ -940,8 +903,7 @@ export default {
fixWithAi: "Corrigir com AI",
truncated: "Contexto truncado",
contextSummary: "{database} · {tables} tabelas",
- autoSqlBlocked:
- "O SQL gerado pela AI pareceu arriscado demais para execução automática. Revise-o manualmente antes de executar.",
+ autoSqlBlocked: "O SQL gerado pela AI pareceu arriscado demais para execução automática. Revise-o manualmente antes de executar.",
agentSteps: {
generated: "SQL gerado",
noSql: "Nenhum SQL encontrado",
@@ -968,8 +930,7 @@ export default {
enableThinking: "Raciocínio",
enableThinkingOn: "Ativado",
enableThinkingOff: "Desativado",
- enableThinkingHint:
- "Esta opção só tem efeito em APIs /chat/completions e modelos compatíveis. Quando desativada, pode reduzir significativamente o uso de tokens, mas a qualidade dos resultados gerados pode diminuir ligeiramente.",
+ enableThinkingHint: "Esta opção só tem efeito em APIs /chat/completions e modelos compatíveis. Quando desativada, pode reduzir significativamente o uso de tokens, mas a qualidade dos resultados gerados pode diminuir ligeiramente.",
actions: {
generate: "Gerar SQL",
explain: "Explicar SQL",
@@ -1040,8 +1001,7 @@ export default {
structureDocYes: "Sim",
structureDocNo: "Não",
structureDocCopied: "Estrutura copiada",
- structureDocCopyFallbackHint:
- "A cópia automática foi bloqueada. Clique em Copiar novamente ou selecione o conteúdo abaixo.",
+ structureDocCopyFallbackHint: "A cópia automática foi bloqueada. Clique em Copiar novamente ou selecione o conteúdo abaixo.",
saveStructure: "Salvar SQL",
exportStructureCopied: "Estrutura copiada",
createTable: "Criar Tabela",
@@ -1055,8 +1015,7 @@ export default {
renameObjectNamePlaceholder: "Novo nome",
renameObjectSuccess: '"{oldName}" renomeado para "{newName}"',
confirmDropTableTitle: "Remover Tabela",
- confirmDropTableMessage:
- 'Tem certeza de que deseja remover "{name}"? Isso excluirá permanentemente a tabela e todos os seus dados.',
+ confirmDropTableMessage: 'Tem certeza de que deseja remover "{name}"? Isso excluirá permanentemente a tabela e todos os seus dados.',
confirmEmptyTableTitle: "Esvaziar Tabela",
confirmEmptyTableMessage: 'Tem certeza de que deseja excluir todos os dados de "{name}"?',
confirmTruncateTableTitle: "Truncar Tabela",
@@ -1074,11 +1033,9 @@ export default {
batchDrop: "Remover selecionados ({count})",
executeProcedure: "Executar Procedimento",
confirmExecuteProcedureTitle: "Executar Procedimento",
- confirmExecuteProcedureMessage:
- 'Executar o procedimento "{name}"? Você pode preencher ou ajustar os valores dos parâmetros primeiro.',
+ confirmExecuteProcedureMessage: 'Executar o procedimento "{name}"? Você pode preencher ou ajustar os valores dos parâmetros primeiro.',
loadingProcedureParameters: "Carregando parâmetros...",
- procedureParametersUnavailable:
- "Não foi possível carregar os metadados dos parâmetros. Você ainda pode editar o SQL abaixo e executá-lo.",
+ procedureParametersUnavailable: "Não foi possível carregar os metadados dos parâmetros. Você ainda pode editar o SQL abaixo e executá-lo.",
noProcedureParameters: "Nenhum parâmetro foi encontrado. O SQL atual será executado como exibido.",
inputParameters: "{count} parâmetros de entrada",
outputParameters: "{count} parâmetros de saída",
@@ -1088,8 +1045,7 @@ export default {
parameterValue: "Valor",
parameterNull: "NULL",
parameterDefault: "DEFAULT",
- parameterDefaultHint:
- "Quando DEFAULT está marcado, o DBX omite esse argumento para que o banco de dados use o padrão do procedimento.",
+ parameterDefaultHint: "Quando DEFAULT está marcado, o DBX omite esse argumento para que o banco de dados use o padrão do procedimento.",
parameterValuePlaceholder: "Digite o valor",
outputOnly: "Apenas saída",
sqlPreview: "Pré-visualização do SQL",
@@ -1107,8 +1063,7 @@ export default {
confirmDropTriggerTitle: "Remover Gatilho",
confirmDropTableChildObjectMessage: 'Tem certeza de que deseja remover "{name}" de "{table}"?',
confirmBatchDropTitle: "Remover Objetos Selecionados",
- confirmBatchDropMessage:
- "Tem certeza de que deseja remover {count} objetos selecionados? Esta ação não pode ser desfeita.",
+ confirmBatchDropMessage: "Tem certeza de que deseja remover {count} objetos selecionados? Esta ação não pode ser desfeita.",
confirmDropProcedureTitle: "Remover Procedimento",
confirmDropProcedureMessage: 'Tem certeza de que deseja remover o procedimento "{name}"?',
confirmDropFunctionTitle: "Remover Função",
@@ -1128,12 +1083,10 @@ export default {
createDuckDbFile: "Criar Arquivo de Banco de Dados",
dropDatabase: "Remover Banco de Dados",
confirmDropDatabaseTitle: "Remover Banco de Dados",
- confirmDropDatabaseMessage:
- 'Tem certeza de que deseja remover o banco de dados "{name}"? Isso excluirá permanentemente o banco de dados e todos os seus dados.',
+ confirmDropDatabaseMessage: 'Tem certeza de que deseja remover o banco de dados "{name}"? Isso excluirá permanentemente o banco de dados e todos os seus dados.',
createDatabaseSuccess: 'Banco de dados "{name}" criado',
createDuckDbFileSuccess: 'Arquivo de banco de dados DuckDB "{name}" criado e anexado',
- createDuckDbFileDesktopOnly:
- "A criação de arquivos de banco de dados DuckDB só está disponível no aplicativo desktop",
+ createDuckDbFileDesktopOnly: "A criação de arquivos de banco de dados DuckDB só está disponível no aplicativo desktop",
dropDatabaseSuccess: 'Banco de dados "{name}" removido',
createDatabaseNamePlaceholder: "Nome do banco de dados",
createDatabaseCharset: "Conjunto de caracteres",
@@ -1143,8 +1096,7 @@ export default {
createSchema: "Criar Schema",
dropSchema: "Remover Schema",
confirmDropSchemaTitle: "Remover Schema",
- confirmDropSchemaMessage:
- 'Tem certeza de que deseja remover o schema "{name}"? Isso excluirá permanentemente o schema e todos os seus objetos.',
+ confirmDropSchemaMessage: 'Tem certeza de que deseja remover o schema "{name}"? Isso excluirá permanentemente o schema e todos os seus objetos.',
createSchemaSuccess: 'Schema "{name}" criado',
dropSchemaSuccess: 'Schema "{name}" removido',
createSchemaNamePlaceholder: "Nome do schema",
@@ -1215,8 +1167,7 @@ export default {
dropSelected: "Remover selecionados",
clearSelection: "Limpar seleção",
confirmBatchDropTitle: "Remover tabelas selecionadas",
- confirmBatchDropMessage:
- "Tem certeza de que deseja remover {count} tabelas selecionadas? Esta ação não pode ser desfeita.",
+ confirmBatchDropMessage: "Tem certeza de que deseja remover {count} tabelas selecionadas? Esta ação não pode ser desfeita.",
batchDropSuccess: "{count} tabelas removidas",
},
structureEditor: {
@@ -1340,8 +1291,7 @@ export default {
columnValue: "Valor",
columnSize: "Tamanho",
columnTTL: "TTL",
- binaryStringReadonlyHint:
- "Valores de string binária são exibidos como texto escapado no modo somente leitura; a edição de bytes brutos não é suportada.",
+ binaryStringReadonlyHint: "Valores de string binária são exibidos como texto escapado no modo somente leitura; a edição de bytes brutos não é suportada.",
selectedKeys: "Chaves selecionadas",
deleteGroup: "Excluir grupo",
deleteGroupDetails: "{target}\n{count} chaves",
@@ -1480,14 +1430,12 @@ export default {
},
dangerDialog: {
title: "Operação perigosa",
- message:
- "Esta instrução SQL pode modificar ou excluir dados de forma irreversível. Tem certeza de que deseja executá-la?",
+ message: "Esta instrução SQL pode modificar ou excluir dados de forma irreversível. Tem certeza de que deseja executá-la?",
suppressFuturePrompts: "Não perguntar novamente para SQL perigoso",
deleteMessage: "Esta operação de exclusão pode ser irreversível. Continuar?",
deleteConfirm: "Confirmar exclusão",
deleteRowMessage: "Esta linha será marcada para exclusão e removida do banco de dados após salvar. Continuar?",
- deleteRowsMessage:
- "Estas {count} linhas serão marcadas para exclusão e removidas do banco de dados após salvar. Continuar?",
+ deleteRowsMessage: "Estas {count} linhas serão marcadas para exclusão e removidas do banco de dados após salvar. Continuar?",
deleteRowDetails: "Tabela: {table}",
deleteRowDetailsNoTable: "Linha de resultado atual",
redisKeyDetails: "Chave Redis: {key}",
@@ -1629,22 +1577,19 @@ export default {
selectedTables: "{selected}/{total} selecionadas",
selectAllTables: "Selecionar tudo",
deselectAllTables: "Desmarcar tudo",
- selectSourceTables:
- "Selecione primeiro a conexão e o banco de dados de origem, depois escolha as tabelas para comparar",
+ selectSourceTables: "Selecione primeiro a conexão e o banco de dados de origem, depois escolha as tabelas para comparar",
noTables: "Nenhuma tabela disponível para comparação",
autoMatchHint: "O modo em lote corresponde automaticamente as tabelas de destino pelo mesmo nome",
matchedTables: "{matched}/{total} tabelas correspondidas",
missingTargetTables: "Tabelas de destino de mesmo nome ausentes: {tables}",
keyColumns: "Colunas-Chave",
keyColumnsPlaceholder: "Colunas primárias ou únicas separadas por vírgula",
- keyColumnsAutoHint:
- "Deixe em branco para detectar automaticamente as chaves primárias na comparação de tabela única, ou por tabela na comparação em lote.",
+ keyColumnsAutoHint: "Deixe em branco para detectar automaticamente as chaves primárias na comparação de tabela única, ou por tabela na comparação em lote.",
rowCounts: "Origem com {source} linhas, destino com {target} linhas; comparação completa concluída",
previewLimitOption: "Pré-visualizar {count}",
compare: "Comparar Dados",
summary: "{added} adicionados, {removed} removidos, {modified} modificados",
- batchSummary:
- "{tables} tabelas comparadas: {different} diferentes, {same} idênticas, {failed} com falha; {added} adicionados, {removed} removidos, {modified} modificados",
+ batchSummary: "{tables} tabelas comparadas: {different} diferentes, {same} idênticas, {failed} com falha; {added} adicionados, {removed} removidos, {modified} modificados",
comparingTable: "Comparando {current}/{total}: {table}",
keyColumnsInline: "Colunas-chave: {columns}",
selectedInline: "Selecionados {selected}/{total}",
@@ -1735,8 +1680,7 @@ export default {
languageTitle: "Idioma / 语言",
fontSize: "Tamanho da fonte",
uiScale: "Escala da UI",
- uiScaleDescription:
- "Dimensione toda a UI do desktop para telas de alta resolução (high-DPI). As alterações são aplicadas imediatamente e restauradas na próxima inicialização.",
+ uiScaleDescription: "Dimensione toda a UI do desktop para telas de alta resolução (high-DPI). As alterações são aplicadas imediatamente e restauradas na próxima inicialização.",
theme: "Tema",
selectTheme: "Selecionar tema...",
followAppTheme: "Seguir o tema do app",
@@ -1751,14 +1695,11 @@ export default {
iconThemeBlack: "Preto",
iconThemeBlackDescription: "Usar a marca DBX em preto na janela, na bandeja e no logo.",
showTrayIcon: "Mostrar ícone na bandeja/barra de menus",
- showTrayIconDescription:
- "Quando desativado, nenhum ícone é exibido, mas fechar a janela ainda oculta o DBX em segundo plano como antes.",
+ showTrayIconDescription: "Quando desativado, nenhum ícone é exibido, mas fechar a janela ainda oculta o DBX em segundo plano como antes.",
updateNotificationsEnabled: "Ativar lembretes de atualização",
- updateNotificationsEnabledDescription:
- "Quando desativado, o DBX não verificará automaticamente atualizações do app ou dos drivers nem mostrará indicadores. Verificações manuais continuam disponíveis.",
+ updateNotificationsEnabledDescription: "Quando desativado, o DBX não verificará automaticamente atualizações do app ou dos drivers nem mostrará indicadores. Verificações manuais continuam disponíveis.",
debugLoggingEnabled: "Ativar logs de depuração",
- debugLoggingEnabledDescription:
- "Registra logs locais de diagnóstico do lado do usuário ao investigar relatos. Desativado por padrão.",
+ debugLoggingEnabledDescription: "Registra logs locais de diagnóstico do lado do usuário ao investigar relatos. Desativado por padrão.",
debugLogsCopy: "Copiar logs",
debugLogsCopied: "Copiado",
debugLogsDownload: "Baixar logs",
@@ -1766,14 +1707,11 @@ export default {
debugLogsClear: "Limpar logs",
dataGridDisplay: "Exibição da grade de dados",
showColumnCommentsInHeader: "Mostrar comentários de coluna sob os nomes",
- showColumnCommentsInHeaderDescription:
- "Exibir comentários de colunas da tabela diretamente abaixo dos nomes das colunas da grade.",
+ showColumnCommentsInHeaderDescription: "Exibir comentários de colunas da tabela diretamente abaixo dos nomes das colunas da grade.",
showColumnTypesInHeader: "Mostrar tipos de coluna sob os nomes",
- showColumnTypesInHeaderDescription:
- "Exibir o tipo de dado de cada coluna diretamente abaixo dos nomes das colunas da grade.",
+ showColumnTypesInHeaderDescription: "Exibir o tipo de dado de cada coluna diretamente abaixo dos nomes das colunas da grade.",
compactColumnHeaderActions: "Ferramentas compactas no cabeçalho da coluna",
- compactColumnHeaderActionsDescription:
- "Mover as ferramentas de formatação e filtro local para um menu de mais opções para que os nomes das colunas tenham prioridade.",
+ compactColumnHeaderActionsDescription: "Mover as ferramentas de formatação e filtro local para um menu de mais opções para que os nomes das colunas tenham prioridade.",
sidebarActivation: "Ativação da barra lateral",
sidebarActivationSingle: "Clique único",
sidebarActivationSingleDescription: "Abrir itens acionáveis da barra lateral com um clique.",
@@ -1781,38 +1719,28 @@ export default {
sidebarActivationDoubleDescription: "Clique único seleciona linhas; clique duplo abre itens.",
sidebarObjectDisplay: "Layout de objetos da barra lateral",
sidebarObjectDisplayGrouped: "Visualização avançada",
- sidebarObjectDisplayGroupedDescription:
- "Agrupar objetos por tabelas, views, procedures e funções para bancos de dados com mais tipos de objetos.",
+ sidebarObjectDisplayGroupedDescription: "Agrupar objetos por tabelas, views, procedures e funções para bancos de dados com mais tipos de objetos.",
sidebarObjectDisplaySimple: "Visualização simples",
- sidebarObjectDisplaySimpleDescription:
- "Listar tabelas e views diretamente sob cada banco de dados ou schema para reduzir os níveis intermediários.",
+ sidebarObjectDisplaySimpleDescription: "Listar tabelas e views diretamente sob cada banco de dados ou schema para reduzir os níveis intermediários.",
autoSelectActiveSidebarNode: "Sempre selecionar o item aberto",
- autoSelectActiveSidebarNodeDescription:
- "Ao alternar abas, selecionar a tabela, coleção ou arquivo SQL correspondente visível na barra lateral.",
+ autoSelectActiveSidebarNodeDescription: "Ao alternar abas, selecionar a tabela, coleção ou arquivo SQL correspondente visível na barra lateral.",
disconnectTabHandlingMode: "Abas após desconectar",
- disconnectTabHandlingModeDescription:
- "Escolha como as abas relacionadas devem ser tratadas após fechar uma conexão ou banco de dados.",
+ disconnectTabHandlingModeDescription: "Escolha como as abas relacionadas devem ser tratadas após fechar uma conexão ou banco de dados.",
disconnectTabHandlingModeCloseTabs: "Fechar todas as abas",
disconnectTabHandlingModeCloseTabsDescription: "Fechar todas as abas relacionadas à conexão ou ao banco de dados.",
disconnectTabHandlingModeKeepTabsClearResults: "Fechar abas de objetos, manter abas SQL",
- disconnectTabHandlingModeKeepTabsClearResultsDescription:
- "Fechar abas de dados de tabela, navegador de objetos e estrutura, mantendo as abas de consultas SQL e o texto SQL, e também limpar o estado de execução e as sessões de resultados.",
+ disconnectTabHandlingModeKeepTabsClearResultsDescription: "Fechar abas de dados de tabela, navegador de objetos e estrutura, mantendo as abas de consultas SQL e o texto SQL, e também limpar o estado de execução e as sessões de resultados.",
disconnectTabHandlingModeKeepTabsKeepResults: "Não fechar abas relacionadas",
- disconnectTabHandlingModeKeepTabsKeepResultsDescription:
- "Manter abas relacionadas, texto SQL e resultados atuais sem limpeza adicional.",
+ disconnectTabHandlingModeKeepTabsKeepResultsDescription: "Manter abas relacionadas, texto SQL e resultados atuais sem limpeza adicional.",
reuseDataTab: "Reutilizar aba de dados",
- reuseDataTabDescription:
- "Ao clicar em uma tabela na barra lateral, reutilizar a aba de dados existente em vez de criar uma nova a cada vez.",
+ reuseDataTabDescription: "Ao clicar em uma tabela na barra lateral, reutilizar a aba de dados existente em vez de criar uma nova a cada vez.",
sidebarHiddenTablePrefixes: "Prefixos de nome de tabela ocultos",
- sidebarHiddenTablePrefixesDescription:
- "Um prefixo por linha. Apenas os rótulos de tabela, view e coleção da barra lateral são encurtados; tooltips e ações ainda usam o nome completo.",
+ sidebarHiddenTablePrefixesDescription: "Um prefixo por linha. Apenas os rótulos de tabela, view e coleção da barra lateral são encurtados; tooltips e ações ainda usam o nome completo.",
sidebarHiddenTablePrefixesPlaceholder: "Exemplo:\nODS_\nT8Y2_LONG_",
sidebarHideTableComments: "Ocultar comentários de tabela na barra lateral",
- sidebarHideTableCommentsDescription:
- "Ocultar os comentários inline de tabela/view exibidos ao lado dos nomes na árvore da barra lateral para economizar espaço horizontal.",
+ sidebarHideTableCommentsDescription: "Ocultar os comentários inline de tabela/view exibidos ao lado dos nomes na árvore da barra lateral para economizar espaço horizontal.",
sidebarAllowHorizontalScroll: "Permitir rolagem horizontal da barra lateral",
- sidebarAllowHorizontalScrollDescription:
- "Mostrar nomes longos de tabelas, views e coleções por completo, permitindo a rolagem horizontal da barra lateral.",
+ sidebarAllowHorizontalScrollDescription: "Mostrar nomes longos de tabelas, views e coleções por completo, permitindo a rolagem horizontal da barra lateral.",
snippetsDescription: "Personalize os modelos de snippets SQL acionados no editor.",
snippetsAdd: "Adicionar snippet",
snippetsLabel: "Rótulo",
@@ -1825,8 +1753,7 @@ export default {
snippetsAddTitle: "Adicionar snippet",
snippetsEditTitle: "Editar snippet",
syncWebDavTitle: "Sincronização WebDAV",
- syncWebDavDescription:
- "Envie ou restaure um snapshot do DBX a partir de um serviço de armazenamento compatível com WebDAV.",
+ syncWebDavDescription: "Envie ou restaure um snapshot do DBX a partir de um serviço de armazenamento compatível com WebDAV.",
syncEndpoint: "URL do WebDAV",
syncUsername: "Nome de usuário",
syncPassword: "Senha",
@@ -1834,18 +1761,14 @@ export default {
syncClearSavedPassword: "Limpar senha salva",
syncRememberWebDavPassword: "Lembrar senha do app WebDAV",
syncSavedPassword: "(salva)",
- syncRememberWebDavPasswordDescription:
- "A senha é criptografada e armazenada apenas neste dispositivo. Ela não é sincronizada para o WebDAV e não substitui a senha de sincronização.",
+ syncRememberWebDavPasswordDescription: "A senha é criptografada e armazenada apenas neste dispositivo. Ela não é sincronizada para o WebDAV e não substitui a senha de sincronização.",
syncRemotePath: "Caminho remoto do snapshot",
syncRemotePathDescription: "O DBX criará as pastas pai ausentes ao enviar.",
- syncSecretNotice:
- "Por padrão, o DBX sincroniza apenas detalhes de conexão e configurações. Senhas de banco de dados, senhas SSH, senhas de proxy, strings de conexão e chaves de API de IA permanecem locais.",
+ syncSecretNotice: "Por padrão, o DBX sincroniza apenas detalhes de conexão e configurações. Senhas de banco de dados, senhas SSH, senhas de proxy, strings de conexão e chaves de API de IA permanecem locais.",
syncSecrets: "Sincronizar segredos criptografados",
- syncSecretsDescription:
- "Quando ativado, o DBX criptografa senhas de banco de dados, senhas SSH e chaves de API de IA antes de enviá-las para o WebDAV.",
+ syncSecretsDescription: "Quando ativado, o DBX criptografa senhas de banco de dados, senhas SSH e chaves de API de IA antes de enviá-las para o WebDAV.",
syncSecretsPassphrase: "Senha de sincronização",
- syncSecretsPassphraseDescription:
- "Esta senha é usada apenas para criptografar e restaurar dados sensíveis. O DBX não a salva; digite-a novamente em cada dispositivo.",
+ syncSecretsPassphraseDescription: "Esta senha é usada apenas para criptografar e restaurar dados sensíveis. O DBX não a salva; digite-a novamente em cada dispositivo.",
syncTest: "Testar",
syncUpload: "Enviar",
syncDownload: "Baixar",
@@ -1854,8 +1777,7 @@ export default {
syncDownloadSuccess: "Baixados e aplicados {bytes} bytes de {path}.",
syncSecretsApplied: "Os segredos criptografados foram restaurados.",
syncSecretsSkipped: "Havia segredos criptografados, mas não foram restaurados.",
- syncDownloadConfirm:
- "Baixar e aplicar o snapshot remoto do DBX? Os metadados locais e os SQL salvos serão substituídos.",
+ syncDownloadConfirm: "Baixar e aplicar o snapshot remoto do DBX? Os metadados locais e os SQL salvos serão substituídos.",
apply: "Aplicar",
applyAndClose: "Aplicar e fechar",
reset: "Redefinir",
@@ -1868,8 +1790,7 @@ export default {
wordWrap: "Quebra de linha",
wordWrapDescription: "Quebrar linhas SQL longas dentro da largura do editor",
confirmDangerousSqlExecution: "Confirmar antes de SQL perigoso",
- confirmDangerousSqlExecutionDescription:
- "Quando desativado, ALTER, DROP, DELETE, TRUNCATE e outros SQL perigosos são executados sem a caixa de diálogo de aviso.",
+ confirmDangerousSqlExecutionDescription: "Quando desativado, ALTER, DROP, DELETE, TRUNCATE e outros SQL perigosos são executados sem a caixa de diálogo de aviso.",
redisScanPageSize: "Contagem de scan do Redis",
redisScanPageSizeDescription: "Chaves solicitadas por página do Redis SCAN ao navegar pelas chaves.",
redisScanPageSizeOption: "{count} chaves",
@@ -1950,8 +1871,7 @@ export default {
jdbcDeleteSuccess: "Driver removido",
jdbcNoDrivers: "Nenhum driver JDBC importado ainda.",
mcpTitle: "Servidor MCP",
- mcpDescription:
- "Verifique a instalação e a versão do Servidor MCP do DBX usado pelo Claude Code, Cursor e outros agentes.",
+ mcpDescription: "Verifique a instalação e a versão do Servidor MCP do DBX usado pelo Claude Code, Cursor e outros agentes.",
mcpChecking: "Verificando",
mcpStatusUnknown: "Não verificado",
mcpStatusError: "Falha na verificação",
@@ -1971,15 +1891,11 @@ export default {
mcpCodexConfig: "Configuração do Codex",
mcpCodexConfigPath: "O Codex pode usar ~/.codex/config.toml ou um .codex/config.toml no nível do projeto.",
mcpReadonlyMode: "Modo somente leitura",
- mcpReadonlyModeDescription:
- "Adiciona DBX_MCP_ALLOW_WRITES=0 à configuração de exemplo para que a sessão MCP permaneça apenas para consultas.",
+ mcpReadonlyModeDescription: "Adiciona DBX_MCP_ALLOW_WRITES=0 à configuração de exemplo para que a sessão MCP permaneça apenas para consultas.",
mcpAllowDangerous: "Permitir SQL perigoso",
- mcpAllowDangerousDescription:
- "Adiciona DBX_MCP_ALLOW_DANGEROUS_SQL=1 à configuração de exemplo para que instruções como DROP, TRUNCATE, ALTER e similares sejam permitidas.",
- mcpDetectionTiming:
- "O DBX verifica automaticamente quando esta página é aberta; use Verificar novamente para atualizar.",
- mcpNpmBoundary:
- "O DBX apenas verifica e explica o status do MCP; a instalação e as atualizações ainda são feitas pelo npm.",
+ mcpAllowDangerousDescription: "Adiciona DBX_MCP_ALLOW_DANGEROUS_SQL=1 à configuração de exemplo para que instruções como DROP, TRUNCATE, ALTER e similares sejam permitidas.",
+ mcpDetectionTiming: "O DBX verifica automaticamente quando esta página é aberta; use Verificar novamente para atualizar.",
+ mcpNpmBoundary: "O DBX apenas verifica e explica o status do MCP; a instalação e as atualizações ainda são feitas pelo npm.",
mcpRefresh: "Verificar novamente",
mcpGuide: "Guia do MCP",
aboutDescription: "Uma ferramenta de gerenciamento de banco de dados leve e de código aberto.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 8a3434da98..5d2a9eafba 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -54,8 +54,7 @@ export default {
rateLimited: "GitHub 更新检查暂时触发频率限制。你仍然可以打开下载页手动查看。",
openRelease: "打开下载页",
downloadAndInstall: "下载并安装",
- portableManualUpdate:
- "便携版不能使用应用内安装器更新。请从 release 下载便携版 ZIP,并解压覆盖当前 DBX 目录,以保留 portable.dbx 和 data。",
+ portableManualUpdate: "便携版不能使用应用内安装器更新。请从 release 下载便携版 ZIP,并解压覆盖当前 DBX 目录,以保留 portable.dbx 和 data。",
downloading: "下载中 {progress}%",
downloadFailed: "更新下载失败:{error}",
restart: "退出并重启",
@@ -146,8 +145,7 @@ export default {
memoryDatabasePathHint: "输入 :memory: 可创建 SQLite 或 DuckDB 内存数据库。",
sqliteExtensions: "SQLite 扩展库",
sqliteExtensionsPlaceholder: "/path/to/regexp.dylib\n/path/to/text.dylib|sqlite3_text_init",
- sqliteExtensionsHint:
- "每行一个 .dylib/.so/.dll;需要入口函数时使用“路径|入口函数”。连接时加载,加载后会关闭 load_extension。",
+ sqliteExtensionsHint: "每行一个 .dylib/.so/.dll;需要入口函数时使用“路径|入口函数”。连接时加载,加载后会关闭 load_extension。",
sqliteExtensionBrowse: "选择 SQLite 扩展库",
user: "用户名",
password: "密码",
@@ -319,8 +317,7 @@ export default {
jdbcPluginHint: "先安装 DBX JDBC 插件,再导入数据库厂商提供的 JDBC 驱动 JAR。",
dmCompatHint: "需要在系统上安装达梦 DM8 ODBC 驱动程序。",
dmDownload: "前往达梦官网下载",
- mongoLegacyHint:
- "MongoDB 4.2 以下版本需安装 MongoDB (Legacy) 驱动。若账号创建在 admin 且认证失败,请将认证库设为 admin。",
+ mongoLegacyHint: "MongoDB 4.2 以下版本需安装 MongoDB (Legacy) 驱动。若账号创建在 admin 且认证失败,请将认证库设为 admin。",
compatible: "兼容",
mainstream: "主流",
color: "颜色",
@@ -706,8 +703,7 @@ export default {
transactionSaveHint: "在事务中提交 {count} 项待保存更改。",
nonTransactionalSaveHint: "逐条保存 {count} 项更改;如果中途失败,前面已成功的更改不会回滚。",
keylessEditWarning: "无主键定位",
- keylessEditWarningHint:
- "这张表没有主键。保存更新或删除时会使用整行原始值作为 WHERE 条件;如果存在完全重复的行,可能会影响多行。",
+ keylessEditWarningHint: "这张表没有主键。保存更新或删除时会使用整行原始值作为 WHERE 条件;如果存在完全重复的行,可能会影响多行。",
queryEditReady: "可编辑",
queryEditReadyHint: "这是来自“{table}”的单表结果,可直接修改、删除或新增行,最后点击待保存按钮保存。",
queryEditReadOnly: "只读结果",
@@ -750,8 +746,7 @@ export default {
},
welcome: {
title: "数据库工作台",
- subtitle:
- "选择左侧连接开始浏览结构,或直接创建查询标签页。DBX 支持多种数据库、查询历史、数据表格编辑和 AI SQL 助手。",
+ subtitle: "选择左侧连接开始浏览结构,或直接创建查询标签页。DBX 支持多种数据库、查询历史、数据表格编辑和 AI SQL 助手。",
connections: "连接",
connected: "已连接",
databaseTypes: "数据库类型",
@@ -965,8 +960,7 @@ export default {
enableThinking: "Thinking",
enableThinkingOn: "已启用",
enableThinkingOff: "已禁用",
- enableThinkingHint:
- "此选项仅对 /chat/completions API 且部分支持的模型生效。设为禁用后可大幅节省 token,但生成结果质量可能会略微下降。",
+ enableThinkingHint: "此选项仅对 /chat/completions API 且部分支持的模型生效。设为禁用后可大幅节省 token,但生成结果质量可能会略微下降。",
actions: {
generate: "生成 SQL",
explain: "解释 SQL",
@@ -1695,8 +1689,7 @@ export default {
previewLimitOption: "预览 {count}",
compare: "开始比较数据",
summary: "新增 {added} 行,删除 {removed} 行,修改 {modified} 行",
- batchSummary:
- "已比较 {tables} 张表:存在差异 {different} 张,一致 {same} 张,失败 {failed} 张;累计新增 {added} 行,删除 {removed} 行,修改 {modified} 行",
+ batchSummary: "已比较 {tables} 张表:存在差异 {different} 张,一致 {same} 张,失败 {failed} 张;累计新增 {added} 行,删除 {removed} 行,修改 {modified} 行",
comparingTable: "正在比较 {current}/{total}:{table}",
keyColumnsInline: "匹配字段:{columns}",
selectedInline: "已选择 {selected}/{total}",
@@ -1804,8 +1797,7 @@ export default {
showTrayIcon: "显示系统托盘/菜单栏图标",
showTrayIconDescription: "关闭后不显示图标,但关闭窗口仍会像之前一样隐藏到后台。",
updateNotificationsEnabled: "启用更新提醒",
- updateNotificationsEnabledDescription:
- "关闭后,DBX 不会自动检查应用和驱动更新,也不会显示更新红点;仍可手动检查更新。",
+ updateNotificationsEnabledDescription: "关闭后,DBX 不会自动检查应用和驱动更新,也不会显示更新红点;仍可手动检查更新。",
debugLoggingEnabled: "启用调试日志",
debugLoggingEnabledDescription: "开启后在本机记录更详细的用户侧诊断日志,反馈问题时可临时开启;默认关闭。",
debugLogsCopy: "复制日志",
@@ -1837,15 +1829,13 @@ export default {
disconnectTabHandlingModeCloseTabs: "关闭全部页签",
disconnectTabHandlingModeCloseTabsDescription: "直接关闭对应连接或数据库下的全部相关页签。",
disconnectTabHandlingModeKeepTabsClearResults: "关闭表格页签,保留 SQL 页签",
- disconnectTabHandlingModeKeepTabsClearResultsDescription:
- "关闭表数据、对象浏览和结构等页签,保留 SQL 查询页签和 SQL 文本,同时清理执行状态与结果会话。",
+ disconnectTabHandlingModeKeepTabsClearResultsDescription: "关闭表数据、对象浏览和结构等页签,保留 SQL 查询页签和 SQL 文本,同时清理执行状态与结果会话。",
disconnectTabHandlingModeKeepTabsKeepResults: "不关闭相关页签",
disconnectTabHandlingModeKeepTabsKeepResultsDescription: "保留相关页签、SQL 文本和当前结果,不做额外处理。",
reuseDataTab: "复用数据标签页",
reuseDataTabDescription: "单击侧边栏表名时,复用已有的数据标签页而不是创建新标签页,避免打开过多标签。",
sidebarHiddenTablePrefixes: "隐藏表名前缀",
- sidebarHiddenTablePrefixesDescription:
- "每行一个前缀,仅影响侧边栏表、视图和集合的显示名称,悬浮提示和实际操作仍使用完整名称。",
+ sidebarHiddenTablePrefixesDescription: "每行一个前缀,仅影响侧边栏表、视图和集合的显示名称,悬浮提示和实际操作仍使用完整名称。",
sidebarHiddenTablePrefixesPlaceholder: "例如:\nODS_\nT8Y2_LONG_",
sidebarHideTableComments: "隐藏侧边栏表注释",
sidebarHideTableCommentsDescription: "隐藏侧边栏中表名旁边显示的表/视图注释,以节省横向空间。",
@@ -2003,8 +1993,7 @@ export default {
mcpReadonlyMode: "只读模式",
mcpReadonlyModeDescription: "开启后会为示例配置附加 DBX_MCP_ALLOW_WRITES=0,MCP 会话只允许查询。",
mcpAllowDangerous: "允许危险 SQL",
- mcpAllowDangerousDescription:
- "开启后会为示例配置附加 DBX_MCP_ALLOW_DANGEROUS_SQL=1,允许 DROP、TRUNCATE、ALTER 等语句。",
+ mcpAllowDangerousDescription: "开启后会为示例配置附加 DBX_MCP_ALLOW_DANGEROUS_SQL=1,允许 DROP、TRUNCATE、ALTER 等语句。",
mcpDetectionTiming: "打开此页时会自动检测,点击重新检查可刷新。",
mcpNpmBoundary: "DBX 只检测和提示 MCP 状态;安装与升级仍由 npm 完成。",
mcpRefresh: "重新检查",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 59b0f58a71..f5e5803bd5 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -54,8 +54,7 @@ export default {
rateLimited: "GitHub 更新檢查暫時觸發頻率限制。你仍然可以開啟下載頁手動檢視。",
openRelease: "開啟下載頁",
downloadAndInstall: "下載並安裝",
- portableManualUpdate:
- "可攜版無法使用應用程式內建安裝器更新。請從發行頁下載可攜版 ZIP,並解壓縮覆蓋目前的 DBX 目錄,以保留 portable.dbx 和 data。",
+ portableManualUpdate: "可攜版無法使用應用程式內建安裝器更新。請從發行頁下載可攜版 ZIP,並解壓縮覆蓋目前的 DBX 目錄,以保留 portable.dbx 和 data。",
downloading: "下載中 {progress}%",
downloadFailed: "更新下載失敗:{error}",
restart: "結束並重新啟動",
@@ -145,8 +144,7 @@ export default {
memoryDatabasePathHint: "輸入 :memory: 可建立 SQLite 或 DuckDB 記憶體資料庫。",
sqliteExtensions: "SQLite 擴充庫",
sqliteExtensionsPlaceholder: "/path/to/regexp.dylib\n/path/to/text.dylib|sqlite3_text_init",
- sqliteExtensionsHint:
- "每行一個 .dylib/.so/.dll;需要入口函式時使用「路徑|入口函式」。連線時載入,載入後會關閉 load_extension。",
+ sqliteExtensionsHint: "每行一個 .dylib/.so/.dll;需要入口函式時使用「路徑|入口函式」。連線時載入,載入後會關閉 load_extension。",
sqliteExtensionBrowse: "選擇 SQLite 擴充庫",
user: "使用者名稱",
password: "密碼",
@@ -307,8 +305,7 @@ export default {
jdbcPluginHint: "先安裝 DBX JDBC 外掛程式,再匯入資料庫廠商提供的 JDBC 驅動程式 JAR。",
dmCompatHint: "需要在系統上安裝達夢 DM8 ODBC 驅動程式。",
dmDownload: "前往達夢官網下載",
- mongoLegacyHint:
- "MongoDB 4.2 以下版本需安裝 MongoDB (Legacy) 驅動程式。若帳號建立在 admin 且認證失敗,請將認證庫設為 admin。",
+ mongoLegacyHint: "MongoDB 4.2 以下版本需安裝 MongoDB (Legacy) 驅動程式。若帳號建立在 admin 且認證失敗,請將認證庫設為 admin。",
compatible: "相容",
mainstream: "熱門",
color: "顏色",
@@ -675,8 +672,7 @@ export default {
transactionSaveHint: "在事務中提交 {count} 項待儲存更改。",
nonTransactionalSaveHint: "逐條儲存 {count} 項更改;如果中途失敗,前面已成功的更改不會回溯。",
keylessEditWarning: "無主鍵定位",
- keylessEditWarningHint:
- "此資料表沒有主鍵。更新與刪除會在 WHERE 子句中使用所有原始資料列值;完全重複的資料列可能會一起受到影響。",
+ keylessEditWarningHint: "此資料表沒有主鍵。更新與刪除會在 WHERE 子句中使用所有原始資料列值;完全重複的資料列可能會一起受到影響。",
queryEditReady: "可編輯",
queryEditReadyHint: "這是來自「{table}」的單一資料表結果,可直接修改、刪除或新增資料列,最後點選待儲存按鈕儲存。",
queryEditReadOnly: "唯讀結果",
@@ -913,8 +909,7 @@ export default {
enableThinking: "Thinking",
enableThinkingOn: "已啟用",
enableThinkingOff: "已停用",
- enableThinkingHint:
- "此選項僅對 /chat/completions API 且部分支援的模型生效。設為停用後可大幅節省 token,但產生結果品質可能會略微下降。",
+ enableThinkingHint: "此選項僅對 /chat/completions API 且部分支援的模型生效。設為停用後可大幅節省 token,但產生結果品質可能會略微下降。",
actions: {
generate: "產生 SQL",
explain: "解釋 SQL",
@@ -1571,8 +1566,7 @@ export default {
previewLimitOption: "預覽 {count}",
compare: "開始比較資料",
summary: "新增 {added} 列,刪除 {removed} 列,修改 {modified} 列",
- batchSummary:
- "已比較 {tables} 張資料表:{different} 張有差異,{same} 張一致,{failed} 張失敗;新增 {added} 列,刪除 {removed} 列,修改 {modified} 列",
+ batchSummary: "已比較 {tables} 張資料表:{different} 張有差異,{same} 張一致,{failed} 張失敗;新增 {added} 列,刪除 {removed} 列,修改 {modified} 列",
comparingTable: "正在比較 {current}/{total}:{table}",
keyColumnsInline: "鍵欄位:{columns}",
selectedInline: "已選擇 {selected}/{total}",
@@ -1678,8 +1672,7 @@ export default {
showTrayIcon: "顯示系統匣/選單欄圖示",
showTrayIconDescription: "關閉後不顯示圖示,但關閉視窗仍會像之前一樣隱藏到後台。",
updateNotificationsEnabled: "啟用更新提醒",
- updateNotificationsEnabledDescription:
- "關閉後,DBX 不會自動檢查應用程式和驅動程式更新,也不會顯示更新紅點;仍可手動檢查更新。",
+ updateNotificationsEnabledDescription: "關閉後,DBX 不會自動檢查應用程式和驅動程式更新,也不會顯示更新紅點;仍可手動檢查更新。",
debugLoggingEnabled: "啟用偵錯日誌",
debugLoggingEnabledDescription: "開啟後在本機記錄更詳細的使用者側診斷日誌,回報問題時可暫時開啟;預設關閉。",
debugLogsCopy: "複製日誌",
@@ -1711,15 +1704,13 @@ export default {
disconnectTabHandlingModeCloseTabs: "關閉全部分頁",
disconnectTabHandlingModeCloseTabsDescription: "直接關閉對應連線或資料庫下的全部相關分頁。",
disconnectTabHandlingModeKeepTabsClearResults: "關閉物件分頁,保留 SQL 分頁",
- disconnectTabHandlingModeKeepTabsClearResultsDescription:
- "關閉資料表資料、物件瀏覽和結構等分頁,保留 SQL 查詢分頁與 SQL 文字,同時清理執行狀態與結果工作階段。",
+ disconnectTabHandlingModeKeepTabsClearResultsDescription: "關閉資料表資料、物件瀏覽和結構等分頁,保留 SQL 查詢分頁與 SQL 文字,同時清理執行狀態與結果工作階段。",
disconnectTabHandlingModeKeepTabsKeepResults: "不關閉相關分頁",
disconnectTabHandlingModeKeepTabsKeepResultsDescription: "保留相關分頁、SQL 文字與目前結果,不另外做清理。",
reuseDataTab: "重複使用資料分頁",
reuseDataTabDescription: "點擊側邊欄資料表名稱時,重複使用現有的資料分頁而不是建立新分頁,避免開啟過多分頁。",
sidebarHiddenTablePrefixes: "隱藏資料表名稱字首",
- sidebarHiddenTablePrefixesDescription:
- "每行一個字首。只縮短側邊欄中的資料表、檢視和集合標籤;工具提示和實際操作仍使用完整名稱。",
+ sidebarHiddenTablePrefixesDescription: "每行一個字首。只縮短側邊欄中的資料表、檢視和集合標籤;工具提示和實際操作仍使用完整名稱。",
sidebarHiddenTablePrefixesPlaceholder: "範例:\nODS_\nT8Y2_LONG_",
sidebarHideTableComments: "隱藏側邊欄資料表註解",
sidebarHideTableCommentsDescription: "隱藏側邊欄樹狀清單中名稱旁的資料表/檢視註解,以節省橫向空間。",
@@ -1748,8 +1739,7 @@ export default {
syncRememberWebDavPasswordDescription: "密碼會加密儲存在本機,不會同步到 WebDAV,也不會取代同步密碼。",
syncRemotePath: "遠端快照路徑",
syncRemotePathDescription: "上傳時 DBX 會自動建立缺失的父目錄。",
- syncSecretNotice:
- "預設只同步連線詳細資料和設定。資料庫密碼、SSH 密碼、代理伺服器密碼、連線字串和 AI API Key 會保留在本機。",
+ syncSecretNotice: "預設只同步連線詳細資料和設定。資料庫密碼、SSH 密碼、代理伺服器密碼、連線字串和 AI API Key 會保留在本機。",
syncSecrets: "同步加密後的敏感資訊",
syncSecretsDescription: "開啟後,DBX 會先加密資料庫密碼、SSH 密碼和 AI API Key,再上傳到 WebDAV。",
syncSecretsPassphrase: "同步密碼",
diff --git a/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts b/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts
index a949fcdfb9..58dfea6787 100644
--- a/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts
@@ -22,16 +22,12 @@ describe("buildSnippetItems", () => {
});
it("does not keep matching a renamed snippet by its old short label prefix", () => {
- const items = buildSnippetItemsForTest("sel", [
- { id: "1", label: "select all", prefix: "fff", body: "SELECT *\nFROM my_table;" },
- ]);
+ const items = buildSnippetItemsForTest("sel", [{ id: "1", label: "select all", prefix: "fff", body: "SELECT *\nFROM my_table;" }]);
expect(items).toEqual([]);
});
it("still matches a renamed snippet by label when typing a longer descriptive query", () => {
- const items = buildSnippetItemsForTest("select", [
- { id: "1", label: "select all", prefix: "fff", body: "SELECT *\nFROM my_table;" },
- ]);
+ const items = buildSnippetItemsForTest("select", [{ id: "1", label: "select all", prefix: "fff", body: "SELECT *\nFROM my_table;" }]);
expect(items).toHaveLength(1);
expect(items[0].label).toBe("select all");
});
diff --git a/apps/desktop/src/lib/actionActivation.ts b/apps/desktop/src/lib/actionActivation.ts
index 4ba72d1ded..1664dd8534 100644
--- a/apps/desktop/src/lib/actionActivation.ts
+++ b/apps/desktop/src/lib/actionActivation.ts
@@ -12,11 +12,7 @@ function nowMs(): number {
return Date.now();
}
-export function shouldSuppressRepeatedActivation(
- guard: ActionActivationGuard,
- now = nowMs(),
- windowMs = DEFAULT_REPEATED_ACTIVATION_WINDOW_MS,
-): boolean {
+export function shouldSuppressRepeatedActivation(guard: ActionActivationGuard, now = nowMs(), windowMs = DEFAULT_REPEATED_ACTIVATION_WINDOW_MS): boolean {
if (guard.lastActivatedAt !== undefined && now - guard.lastActivatedAt < windowMs) {
return true;
}
diff --git a/apps/desktop/src/lib/agentDriverInstallHint.ts b/apps/desktop/src/lib/agentDriverInstallHint.ts
index 981ec73625..ffd1874559 100644
--- a/apps/desktop/src/lib/agentDriverInstallHint.ts
+++ b/apps/desktop/src/lib/agentDriverInstallHint.ts
@@ -6,11 +6,7 @@ export interface AgentDriverInstallState {
installed: boolean;
}
-export function showAgentDriverInstallHint(
- dbType: DatabaseType | undefined,
- drivers: readonly AgentDriverInstallState[],
- driverProfile?: string,
-): boolean {
+export function showAgentDriverInstallHint(dbType: DatabaseType | undefined, drivers: readonly AgentDriverInstallState[], driverProfile?: string): boolean {
if (!supportsDriverManagement(dbType)) return false;
const driverKey = driverProfile && driverProfile !== dbType ? driverProfile : dbType;
return drivers.find((driver) => driver.db_type === driverKey)?.installed !== true;
diff --git a/apps/desktop/src/lib/agentDriverUpdateBadge.ts b/apps/desktop/src/lib/agentDriverUpdateBadge.ts
index 9366f20988..c04fc9637a 100644
--- a/apps/desktop/src/lib/agentDriverUpdateBadge.ts
+++ b/apps/desktop/src/lib/agentDriverUpdateBadge.ts
@@ -10,9 +10,6 @@ export interface JdbcPluginUpdateBadgeState {
update_available?: boolean | null;
}
-export function countAvailableDriverUpdates(
- drivers: readonly AgentDriverUpdateBadgeState[],
- jdbcPlugin?: JdbcPluginUpdateBadgeState | null,
-): number {
+export function countAvailableDriverUpdates(drivers: readonly AgentDriverUpdateBadgeState[], jdbcPlugin?: JdbcPluginUpdateBadgeState | null): number {
return countAvailableAgentDriverUpdates(drivers) + (jdbcPlugin?.update_available ? 1 : 0);
}
diff --git a/apps/desktop/src/lib/ai.ts b/apps/desktop/src/lib/ai.ts
index 02339453fb..c6aa8e3efa 100644
--- a/apps/desktop/src/lib/ai.ts
+++ b/apps/desktop/src/lib/ai.ts
@@ -1,14 +1,6 @@
import type { AiConfig } from "@/stores/settingsStore";
import { uuid } from "@/lib/utils";
-import type {
- ColumnInfo,
- ConnectionConfig,
- DatabaseType,
- ForeignKeyInfo,
- IndexInfo,
- QueryResult,
- QueryTab,
-} from "@/types/database";
+import type { ColumnInfo, ConnectionConfig, DatabaseType, ForeignKeyInfo, IndexInfo, QueryResult, QueryTab } from "@/types/database";
import * as api from "@/lib/api";
import { currentLocale, type Locale } from "@/i18n";
import { aiTableMentionKey, type AiTableMention } from "@/lib/aiTableMentions";
@@ -57,13 +49,7 @@ export async function runAiAction(input: AiRequestInput, history?: api.AiMessage
const skill = aiSkillForAction(input.action);
const systemPrompt = buildSystemPrompt(input.action, input.context, input.mode);
const instruction = isZh ? skill.userInstruction.zh : skill.userInstruction.en;
- const userPrompt = [
- `Action: ${input.action}`,
- instruction,
- "",
- "User request:",
- input.instruction.trim() || "(No extra instruction provided.)",
- ].join("\n");
+ const userPrompt = [`Action: ${input.action}`, instruction, "", "User request:", input.instruction.trim() || "(No extra instruction provided.)"].join("\n");
const messages: api.AiMessage[] = [...(history || []), { role: "user", content: userPrompt }];
@@ -77,24 +63,12 @@ export async function runAiAction(input: AiRequestInput, history?: api.AiMessage
});
}
-export async function runAiStream(
- input: AiRequestInput,
- history: api.AiMessage[] | undefined,
- onDelta: (delta: string) => void,
- sessionId?: string,
- onReasoningDelta?: (delta: string) => void,
-): Promise<void> {
+export async function runAiStream(input: AiRequestInput, history: api.AiMessage[] | undefined, onDelta: (delta: string) => void, sessionId?: string, onReasoningDelta?: (delta: string) => void): Promise<void> {
const isZh = isChineseLocale(currentLocale());
const skill = aiSkillForAction(input.action);
const systemPrompt = buildSystemPrompt(input.action, input.context, input.mode);
const instruction = isZh ? skill.userInstruction.zh : skill.userInstruction.en;
- const userPrompt = [
- `Action: ${input.action}`,
- instruction,
- "",
- "User request:",
- input.instruction.trim() || "(No extra instruction provided.)",
- ].join("\n");
+ const userPrompt = [`Action: ${input.action}`, instruction, "", "User request:", input.instruction.trim() || "(No extra instruction provided.)"].join("\n");
const messages: api.AiMessage[] = [...(history || []), { role: "user", content: userPrompt }];
@@ -145,11 +119,7 @@ export function buildSystemPrompt(action: AiAction, context: AiContext, mode: Ai
const isZh = isChineseLocale(currentLocale());
- const lines: string[] = [
- ...buildBasePromptLines(isZh),
- ...buildModePromptLines(mode, isZh),
- ...buildActionPromptLines(action, isZh),
- ];
+ const lines: string[] = [...buildBasePromptLines(isZh), ...buildModePromptLines(mode, isZh), ...buildActionPromptLines(action, isZh)];
if (schemaScope === "focused_table") {
lines.push(
@@ -166,9 +136,7 @@ export function buildSystemPrompt(action: AiAction, context: AiContext, mode: Ai
}
lines.push(
- isZh
- ? "返回 SQL 时放在 ```sql 代码块中。额外说明简短实用。"
- : "Put SQL in a fenced ```sql code block. Keep extra explanation short and practical.",
+ isZh ? "返回 SQL 时放在 ```sql 代码块中。额外说明简短实用。" : "Put SQL in a fenced ```sql code block. Keep extra explanation short and practical.",
"",
`Database type: ${context.databaseType}`,
`Connection: ${context.connectionName}`,
@@ -187,81 +155,49 @@ export function buildSystemPrompt(action: AiAction, context: AiContext, mode: Ai
function buildBasePromptLines(isZh: boolean): string[] {
return [
isZh ? "你是 DBX 内置的数据库助手。用中文回复。" : "You are DBX's built-in database assistant. Reply in English.",
- isZh
- ? "精确、保守,根据当前数据库方言生成 SQL。"
- : "Be precise, conservative, and adapt SQL to the active database dialect.",
- isZh
- ? "严格使用当前数据库方言;标识符引用、分页、日期函数、字符串拼接、LIMIT/TOP/OFFSET 语法必须匹配数据库类型。"
- : "Strictly use the active database dialect; identifier quoting, pagination, date functions, string concatenation, and LIMIT/TOP/OFFSET syntax must match the database type.",
+ isZh ? "精确、保守,根据当前数据库方言生成 SQL。" : "Be precise, conservative, and adapt SQL to the active database dialect.",
+ isZh ? "严格使用当前数据库方言;标识符引用、分页、日期函数、字符串拼接、LIMIT/TOP/OFFSET 语法必须匹配数据库类型。" : "Strictly use the active database dialect; identifier quoting, pagination, date functions, string concatenation, and LIMIT/TOP/OFFSET syntax must match the database type.",
isZh
? "对于普通数据查询,优先使用下面已加载的 Schema 上下文,不要为了重复确认已给出的结构而查询 information_schema 或系统表。"
: "For ordinary data queries, prefer the loaded schema context below. Do not query information_schema or system tables merely to rediscover structure already provided.",
isZh
? "例外:当用户明确询问当前有哪些表/Schema、某张表是否存在、或需要盘点数据库对象时,应生成符合当前方言的只读元数据查询(例如 SHOW TABLES、information_schema、sqlite_master 等)。"
: "Exception: when the user explicitly asks what tables/schemas exist, whether a table exists, or asks for database object inventory, generate a read-only metadata query appropriate for the active dialect (for example SHOW TABLES, information_schema, sqlite_master).",
- isZh
- ? "表注释和列注释是语义别名;当用户用中文业务名描述表或字段时,优先根据注释匹配真实表名和字段名。"
- : "Table and column comments are semantic aliases; when the user describes tables or fields by business names, prefer matching those comments to the real table and column names.",
- isZh
- ? "当用户要求分析或查看某个表时,生成 SELECT 查询获取数据,而不是查询元数据。"
- : "When the user asks to 'analyze' or 'look at' a table, generate a SELECT query to retrieve data, not a metadata query.",
+ isZh ? "表注释和列注释是语义别名;当用户用中文业务名描述表或字段时,优先根据注释匹配真实表名和字段名。" : "Table and column comments are semantic aliases; when the user describes tables or fields by business names, prefer matching those comments to the real table and column names.",
+ isZh ? "当用户要求分析或查看某个表时,生成 SELECT 查询获取数据,而不是查询元数据。" : "When the user asks to 'analyze' or 'look at' a table, generate a SELECT query to retrieve data, not a metadata query.",
isZh ? "不要编造 Schema 中不存在的表或列。" : "Never invent tables or columns that are not in the schema context.",
- isZh
- ? "用户输入中的 @schema.table 或 @table 表示用户明确提到的表;这些表已优先放入 Schema 上下文。"
- : "User input may contain @schema.table or @table mentions. Treat them as explicit table references; mentioned tables are prioritized in the schema context.",
- isZh
- ? "不要生成多语句 SQL,除非用户明确要求。不要在同一个回答里混合 SELECT 和写操作。"
- : "Do not generate multi-statement SQL unless the user explicitly asks for it. Do not mix SELECT statements and write operations in the same answer.",
- isZh
- ? "对于 DROP、DELETE、TRUNCATE、ALTER 或没有 WHERE 的 UPDATE,简要警告并优先提供安全的 SELECT 预览。"
- : "For destructive statements (DROP, DELETE, TRUNCATE, ALTER, UPDATE without WHERE), warn briefly and prefer a safer SELECT preview.",
- isZh
- ? "对于 UPDATE 或 DELETE,必须带 WHERE 并说明影响范围;生产库写操作只给建议,不主动建议执行。"
- : "For UPDATE or DELETE, require a WHERE clause and explain the affected scope; for production writes, provide guidance but do not proactively suggest execution.",
+ isZh ? "用户输入中的 @schema.table 或 @table 表示用户明确提到的表;这些表已优先放入 Schema 上下文。" : "User input may contain @schema.table or @table mentions. Treat them as explicit table references; mentioned tables are prioritized in the schema context.",
+ isZh ? "不要生成多语句 SQL,除非用户明确要求。不要在同一个回答里混合 SELECT 和写操作。" : "Do not generate multi-statement SQL unless the user explicitly asks for it. Do not mix SELECT statements and write operations in the same answer.",
+ isZh ? "对于 DROP、DELETE、TRUNCATE、ALTER 或没有 WHERE 的 UPDATE,简要警告并优先提供安全的 SELECT 预览。" : "For destructive statements (DROP, DELETE, TRUNCATE, ALTER, UPDATE without WHERE), warn briefly and prefer a safer SELECT preview.",
+ isZh ? "对于 UPDATE 或 DELETE,必须带 WHERE 并说明影响范围;生产库写操作只给建议,不主动建议执行。" : "For UPDATE or DELETE, require a WHERE clause and explain the affected scope; for production writes, provide guidance but do not proactively suggest execution.",
];
}
function buildModePromptLines(mode: AiAssistantMode, isZh: boolean): string[] {
if (mode === "agent") {
return [
- isZh
- ? "你处于 Agent 模式。用户表达查询意图时,优先生成一个可直接执行的只读 SQL。"
- : "You are in Agent mode. When the user expresses query intent, prioritize one directly executable read-only SQL statement.",
- isZh
- ? "第一个 ```sql 代码块只能包含最终推荐执行的 SQL;不要把解释性 SQL、备选 SQL、危险 SQL 放在第一个代码块。"
- : "The first ```sql code block must contain only the final SQL recommended for execution; do not put explanatory SQL, alternatives, or risky SQL in the first code block.",
- isZh
- ? "如果安全执行条件不满足,先说明原因,再给只读预览或澄清问题。"
- : "If safe execution requirements are not met, explain why first, then provide a read-only preview or a clarifying question.",
+ isZh ? "你处于 Agent 模式。用户表达查询意图时,优先生成一个可直接执行的只读 SQL。" : "You are in Agent mode. When the user expresses query intent, prioritize one directly executable read-only SQL statement.",
+ isZh ? "第一个 ```sql 代码块只能包含最终推荐执行的 SQL;不要把解释性 SQL、备选 SQL、危险 SQL 放在第一个代码块。" : "The first ```sql code block must contain only the final SQL recommended for execution; do not put explanatory SQL, alternatives, or risky SQL in the first code block.",
+ isZh ? "如果安全执行条件不满足,先说明原因,再给只读预览或澄清问题。" : "If safe execution requirements are not met, explain why first, then provide a read-only preview or a clarifying question.",
isZh
? "当用户问“有哪些表”“当前表列表”“表是否存在”这类元数据问题时,优先返回一个可执行的只读元数据 SQL,让系统执行后再基于结果回答。"
: "When the user asks metadata questions such as what tables exist, the current table list, or whether a table exists, prefer returning one executable read-only metadata SQL so the system can run it before answering from results.",
];
}
- return [
- isZh
- ? "你处于 Ask 模式。只生成 SQL 和说明,不要暗示已经执行或即将自动执行。"
- : "You are in Ask mode. Generate SQL and explanations only; do not imply that anything has run or will auto-run.",
- ];
+ return [isZh ? "你处于 Ask 模式。只生成 SQL 和说明,不要暗示已经执行或即将自动执行。" : "You are in Ask mode. Generate SQL and explanations only; do not imply that anything has run or will auto-run."];
}
function schemaCoverageLine(context: AiContext, isZh: boolean): string {
if (context.schemaScope === "focused_table") {
- return isZh
- ? "Schema context scope: focused table only; not a complete database table list."
- : "Schema context scope: focused table only; not a complete database table list.";
+ return isZh ? "Schema context scope: focused table only; not a complete database table list." : "Schema context scope: focused table only; not a complete database table list.";
}
- return context.truncated
- ? "Schema context is truncated."
- : "Schema context is complete for the loaded database scope.";
+ return context.truncated ? "Schema context is truncated." : "Schema context is complete for the loaded database scope.";
}
function buildActionPromptLines(action: AiAction, isZh: boolean): string[] {
const skill = aiSkillForAction(action);
- return isZh
- ? [...skill.systemRules.zh, ...skill.outputContract.zh]
- : [...skill.systemRules.en, ...skill.outputContract.en];
+ return isZh ? [...skill.systemRules.zh, ...skill.outputContract.zh] : [...skill.systemRules.en, ...skill.outputContract.en];
}
function formatSchema(context: AiContext): string {
@@ -275,18 +211,9 @@ function formatSchema(context: AiContext): string {
if (tableComment) lines.push(` Comment: ${tableComment}`);
for (const column of table.columns) {
- const flags = [
- column.is_primary_key ? "PK" : "",
- column.is_nullable ? "nullable" : "NOT NULL",
- column.column_default ? `default ${column.column_default}` : "",
- column.extra || "",
- ]
- .filter(Boolean)
- .join(", ");
+ const flags = [column.is_primary_key ? "PK" : "", column.is_nullable ? "nullable" : "NOT NULL", column.column_default ? `default ${column.column_default}` : "", column.extra || ""].filter(Boolean).join(", ");
const columnComment = column.comment?.trim();
- lines.push(
- ` - ${column.name}: ${column.data_type}${flags ? ` (${flags})` : ""}${columnComment ? ` -- ${columnComment}` : ""}`,
- );
+ lines.push(` - ${column.name}: ${column.data_type}${flags ? ` (${flags})` : ""}${columnComment ? ` -- ${columnComment}` : ""}`);
}
if (table.indexes?.length) {
@@ -308,11 +235,7 @@ function formatSchema(context: AiContext): string {
.join("\n\n");
}
-export async function buildAiContext(
- tab: QueryTab,
- connection: ConnectionConfig,
- options: { maxTables?: number; maxColumnsPerTable?: number; mentionedTables?: AiTableMention[] } = {},
-): Promise<AiContext> {
+export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig, options: { maxTables?: number; maxColumnsPerTable?: number; mentionedTables?: AiTableMention[] } = {}): Promise<AiContext> {
const maxTables = options.maxTables ?? 50;
const maxColumnsPerTable = options.maxColumnsPerTable ?? 40;
const tables: AiSchemaTable[] = [];
@@ -324,10 +247,7 @@ export async function buildAiContext(
schemaScope = "focused_table";
const s = tab.tableMeta.schema ?? "";
const tName = tab.tableMeta.tableName;
- const [indexes, foreignKeys] = await Promise.all([
- api.listIndexes(tab.connectionId, tab.database, s, tName).catch(() => [] as IndexInfo[]),
- api.listForeignKeys(tab.connectionId, tab.database, s, tName).catch(() => [] as ForeignKeyInfo[]),
- ]);
+ const [indexes, foreignKeys] = await Promise.all([api.listIndexes(tab.connectionId, tab.database, s, tName).catch(() => [] as IndexInfo[]), api.listForeignKeys(tab.connectionId, tab.database, s, tName).catch(() => [] as ForeignKeyInfo[])]);
const tableComment = await loadTableComment(tab.connectionId, tab.database, s, tName).catch(() => undefined);
tables.push({
schema: tab.tableMeta.schema,
@@ -364,9 +284,7 @@ export async function buildAiContext(
Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, table.name),
api.listIndexes(tab.connectionId, tab.database, schema, table.name).catch(() => [] as IndexInfo[]),
- api
- .listForeignKeys(tab.connectionId, tab.database, schema, table.name)
- .catch(() => [] as ForeignKeyInfo[]),
+ api.listForeignKeys(tab.connectionId, tab.database, schema, table.name).catch(() => [] as ForeignKeyInfo[]),
]).then(([columns, indexes, foreignKeys]) => ({
schema: schema === tab.database && !isSchemaAware(connection.db_type) ? undefined : schema,
name: table.name,
@@ -408,12 +326,7 @@ export async function buildAiContext(
};
}
-async function loadMentionedTableContext(
- tab: QueryTab,
- connection: ConnectionConfig,
- mention: AiTableMention,
- maxColumnsPerTable: number,
-): Promise<AiSchemaTable | undefined> {
+async function loadMentionedTableContext(tab: QueryTab, connection: ConnectionConfig, mention: AiTableMention, maxColumnsPerTable: number): Promise<AiSchemaTable | undefined> {
const schema = await resolveMentionedTableSchema(tab, connection, mention);
const [columns, indexes, foreignKeys, tableComment] = await Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, mention.table),
@@ -432,21 +345,12 @@ async function loadMentionedTableContext(
};
}
-async function loadTableComment(
- connectionId: string,
- database: string,
- schema: string,
- tableName: string,
-): Promise<string | undefined> {
+async function loadTableComment(connectionId: string, database: string, schema: string, tableName: string): Promise<string | undefined> {
const tables = await api.listTables(connectionId, database, schema, tableName, 10);
return tables.find((table) => table.name.toLowerCase() === tableName.toLowerCase())?.comment?.trim() || undefined;
}
-async function resolveMentionedTableSchema(
- tab: QueryTab,
- connection: ConnectionConfig,
- mention: AiTableMention,
-): Promise<string> {
+async function resolveMentionedTableSchema(tab: QueryTab, connection: ConnectionConfig, mention: AiTableMention): Promise<string> {
if (mention.schema) return mention.schema;
if (tab.tableMeta?.tableName.toLowerCase() === mention.table.toLowerCase() && tab.tableMeta.schema) {
return tab.tableMeta.schema;
diff --git a/apps/desktop/src/lib/aiAgentPlan.ts b/apps/desktop/src/lib/aiAgentPlan.ts
index c1358a1fca..0803f4a634 100644
--- a/apps/desktop/src/lib/aiAgentPlan.ts
+++ b/apps/desktop/src/lib/aiAgentPlan.ts
@@ -1,10 +1,5 @@
import type { AiAction, AiAssistantMode } from "@/lib/ai";
-import {
- classifyAiSqlExecution,
- shouldAttemptAiAutoExecute,
- stripAiSqlComments,
- type AiSqlExecutionDecision,
-} from "@/lib/aiSqlExecutionPolicy";
+import { classifyAiSqlExecution, shouldAttemptAiAutoExecute, stripAiSqlComments, type AiSqlExecutionDecision } from "@/lib/aiSqlExecutionPolicy";
import type { ConnectionConfig } from "@/types/database";
export type AiAgentStep =
@@ -18,13 +13,7 @@ export type AiAgentStep =
| {
kind: "execute_sql";
status: "skipped";
- reason:
- | "ask_mode"
- | "no_sql"
- | "no_execution_intent"
- | "unsupported_action"
- | "blocked_by_policy"
- | "requires_confirmation";
+ reason: "ask_mode" | "no_sql" | "no_execution_intent" | "unsupported_action" | "blocked_by_policy" | "requires_confirmation";
};
export interface AiAgentPlanInput {
diff --git a/apps/desktop/src/lib/aiCodeHighlighter.ts b/apps/desktop/src/lib/aiCodeHighlighter.ts
index 9702506780..57c1d4778e 100644
--- a/apps/desktop/src/lib/aiCodeHighlighter.ts
+++ b/apps/desktop/src/lib/aiCodeHighlighter.ts
@@ -11,26 +11,7 @@ const SHIKI_THEMES = {
light: "github-light",
} as const;
-const SHIKI_LANGUAGES = [
- "bash",
- "css",
- "go",
- "html",
- "java",
- "javascript",
- "json",
- "markdown",
- "php",
- "python",
- "rust",
- "shellscript",
- "sql",
- "tsx",
- "typescript",
- "vue",
- "xml",
- "yaml",
-] as const;
+const SHIKI_LANGUAGES = ["bash", "css", "go", "html", "java", "javascript", "json", "markdown", "php", "python", "rust", "shellscript", "sql", "tsx", "typescript", "vue", "xml", "yaml"] as const;
const SHIKI_LANG_BY_AI_LABEL: Record<string, (typeof SHIKI_LANGUAGES)[number] | "text"> = {
BASH: "bash",
@@ -83,30 +64,7 @@ function getAiShikiHighlighter(): Promise<ShikiHighlighter> {
}
async function loadAiShikiHighlighter(): Promise<ShikiHighlighter> {
- const [
- { createHighlighterCore },
- { createJavaScriptRegexEngine },
- githubDark,
- githubLight,
- bash,
- css,
- go,
- html,
- java,
- javascript,
- json,
- markdown,
- php,
- python,
- rust,
- shellscript,
- sql,
- tsx,
- typescript,
- vue,
- xml,
- yaml,
- ] = await Promise.all([
+ const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, bash, css, go, html, java, javascript, json, markdown, php, python, rust, shellscript, sql, tsx, typescript, vue, xml, yaml] = await Promise.all([
import("shiki/core"),
import("shiki/engine/javascript"),
import("shiki/themes/github-dark.mjs"),
@@ -133,26 +91,7 @@ async function loadAiShikiHighlighter(): Promise<ShikiHighlighter> {
return createHighlighterCore({
engine: createJavaScriptRegexEngine(),
- langs: [
- bash.default,
- css.default,
- go.default,
- html.default,
- java.default,
- javascript.default,
- json.default,
- markdown.default,
- php.default,
- python.default,
- rust.default,
- shellscript.default,
- sql.default,
- tsx.default,
- typescript.default,
- vue.default,
- xml.default,
- yaml.default,
- ],
+ langs: [bash.default, css.default, go.default, html.default, java.default, javascript.default, json.default, markdown.default, php.default, python.default, rust.default, shellscript.default, sql.default, tsx.default, typescript.default, vue.default, xml.default, yaml.default],
themes: [githubDark.default, githubLight.default],
});
}
diff --git a/apps/desktop/src/lib/aiSkills.ts b/apps/desktop/src/lib/aiSkills.ts
index 276a028dae..77d966dce6 100644
--- a/apps/desktop/src/lib/aiSkills.ts
+++ b/apps/desktop/src/lib/aiSkills.ts
@@ -1,14 +1,7 @@
import type { AiAction } from "@/lib/ai";
export type AiSkillRiskPolicy = "readonly" | "readonly_preferred" | "confirmed_write" | "sample_write";
-export type AiSkillContextNeed =
- | "currentSql"
- | "schema"
- | "indexes"
- | "foreignKeys"
- | "lastError"
- | "lastResultPreview"
- | "databaseDialect";
+export type AiSkillContextNeed = "currentSql" | "schema" | "indexes" | "foreignKeys" | "lastError" | "lastResultPreview" | "databaseDialect";
export interface LocalizedAiSkillText {
en: string;
@@ -50,9 +43,7 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: ["利用外键关系推断 JOIN 条件。生成操作优先返回 SQL,避免长篇解释。"],
},
outputContract: {
- en: [
- "Output format: put only the final recommended SQL in the first ```sql code block; add at most 3 practical notes after it. If required information is missing, ask one clarifying question first.",
- ],
+ en: ["Output format: put only the final recommended SQL in the first ```sql code block; add at most 3 practical notes after it. If required information is missing, ask one clarifying question first."],
zh: ["输出格式:第一个 ```sql 代码块只放最终推荐 SQL;SQL 后最多 3 条实用说明。信息不足时先提出一个澄清问题。"],
},
},
@@ -70,15 +61,11 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: "逐步解释当前 SQL。指出危险操作、隐含假设和潜在性能问题。结合 Schema 中的索引和外键信息分析。",
},
systemRules: {
- en: [
- "Explain what the SQL does without changing it. Reference schema, indexes, foreign keys, result preview, and risky assumptions when relevant.",
- ],
+ en: ["Explain what the SQL does without changing it. Reference schema, indexes, foreign keys, result preview, and risky assumptions when relevant."],
zh: ["解释当前 SQL 的作用,不要改写 SQL。必要时结合 Schema、索引、外键、结果预览和风险假设说明。"],
},
outputContract: {
- en: [
- "Output format: summarize the SQL purpose first, then explain execution logic, risks, and performance notes step by step.",
- ],
+ en: ["Output format: summarize the SQL purpose first, then explain execution logic, risks, and performance notes step by step."],
zh: ["输出格式:先概括 SQL 目的,再按步骤解释执行逻辑、风险点和性能注意事项。"],
},
},
@@ -96,9 +83,7 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: "重写或优化当前 SQL。先在 ```sql 代码块中返回优化后的 SQL,然后简要说明改动。利用 Schema 中的索引信息建议索引友好的优化(如避免全表扫描、利用现有索引)。",
},
systemRules: {
- en: [
- "Use the index information in the schema to suggest optimizations. Point out which conditions hit indexes and which cause full table scans.",
- ],
+ en: ["Use the index information in the schema to suggest optimizations. Point out which conditions hit indexes and which cause full table scans."],
zh: ["利用 Schema 中的索引信息建议优化。指出哪些查询条件可以命中索引、哪些会导致全表扫描。"],
},
outputContract: {
@@ -120,9 +105,7 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: "根据报错信息和结果上下文修复当前 SQL。先在 ```sql 代码块中返回修正后的 SQL,再简要说明根因。",
},
systemRules: {
- en: [
- "Carefully analyze the error message to identify the root cause. Return the corrected SQL first, then briefly explain.",
- ],
+ en: ["Carefully analyze the error message to identify the root cause. Return the corrected SQL first, then briefly explain."],
zh: ["仔细分析错误信息,定位根因。先返回修正后的 SQL,再简要解释。"],
},
outputContract: {
@@ -144,15 +127,11 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: "将当前 SQL 转换为用户指定的目标方言。先在 ```sql 代码块中返回转换后的 SQL,再说明语法差异。",
},
systemRules: {
- en: [
- "Convert only to the target dialect requested by the user. Preserve the query intent and call out syntax that cannot be converted safely.",
- ],
+ en: ["Convert only to the target dialect requested by the user. Preserve the query intent and call out syntax that cannot be converted safely."],
zh: ["只转换到用户指定的目标方言。保持查询意图,并指出无法安全转换的语法。"],
},
outputContract: {
- en: [
- "Output format: provide the converted SQL first, then note important target-dialect syntax differences or incompatibilities.",
- ],
+ en: ["Output format: provide the converted SQL first, then note important target-dialect syntax differences or incompatibilities."],
zh: ["输出格式:先给转换后的 SQL,再说明目标方言下的重要语法差异或不兼容点。"],
},
},
@@ -170,9 +149,7 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: "为当前 Schema 生成安全的示例 INSERT 语句或模拟数据。不使用真实生产数据。在 ```sql 代码块中返回 SQL。",
},
systemRules: {
- en: [
- "Generate mock data only. Do not use or imply real production data, credentials, personal data, or secrets.",
- ],
+ en: ["Generate mock data only. Do not use or imply real production data, credentials, personal data, or secrets."],
zh: ["只生成模拟数据。不要使用或暗示真实生产数据、凭据、个人数据或密钥。"],
},
outputContract: {
diff --git a/apps/desktop/src/lib/aiSqlExecutionPolicy.ts b/apps/desktop/src/lib/aiSqlExecutionPolicy.ts
index 7f8e7967b1..0fc4677df2 100644
--- a/apps/desktop/src/lib/aiSqlExecutionPolicy.ts
+++ b/apps/desktop/src/lib/aiSqlExecutionPolicy.ts
@@ -20,11 +20,9 @@ const BLOCK_RE = /^(DROP|TRUNCATE|ALTER|RENAME)\b/i;
const SCHEMA_RE = /^(CREATE)\b/i;
const PRODUCTION_RE = /\b(prod|prd|production)\b|生产|正式/i;
-const NON_PRODUCTION_RE =
- /\b(local|localhost|dev|develop|development|test|testing|stage|staging|sandbox|demo)\b|本地|开发|测试|预发/i;
+const NON_PRODUCTION_RE = /\b(local|localhost|dev|develop|development|test|testing|stage|staging|sandbox|demo)\b|本地|开发|测试|预发/i;
const LOCAL_HOST_RE = /^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|::1)$/i;
-const NEGATIVE_EXECUTION_RE =
- /(不要|别|不用|禁止|只生成|仅生成|只写|仅写).{0,12}(执行|运行|跑)|do\s+not\s+execute|don't\s+execute|dont\s+execute|without\s+executing|only\s+(generate|write|return)/i;
+const NEGATIVE_EXECUTION_RE = /(不要|别|不用|禁止|只生成|仅生成|只写|仅写).{0,12}(执行|运行|跑)|do\s+not\s+execute|don't\s+execute|dont\s+execute|without\s+executing|only\s+(generate|write|return)/i;
export function stripAiSqlComments(sql: string): string {
return sql
diff --git a/apps/desktop/src/lib/binaryCellDownload.ts b/apps/desktop/src/lib/binaryCellDownload.ts
index e6a6e6b132..b21cc07136 100644
--- a/apps/desktop/src/lib/binaryCellDownload.ts
+++ b/apps/desktop/src/lib/binaryCellDownload.ts
@@ -20,8 +20,7 @@ export const BINARY_CELL_DOWNLOAD_MODES: BinaryCellDownloadMode[] = ["binary", "
const HEX_VALUE_RE = /^(?:0[xX]|\\x)([0-9a-fA-F\s]+)$/;
const BARE_HEX_RE = /^[0-9a-fA-F\s]+$/;
const HEX_ESCAPE_RE = /^(?:\\x[0-9a-fA-F]{2}|\s)+$/;
-const BINARY_TYPE_RE =
- /^(?:blob|tinyblob|mediumblob|longblob|bytea|bytes|binary|varbinary|image|raw|long\s+raw)(?:\b|\()/i;
+const BINARY_TYPE_RE = /^(?:blob|tinyblob|mediumblob|longblob|bytea|bytes|binary|varbinary|image|raw|long\s+raw)(?:\b|\()/i;
function copyBytesForBlob(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
return new Uint8Array(bytes);
@@ -114,11 +113,7 @@ function formatBinaryCellByteSize(bytes: number): string {
return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
}
-export function binaryCellDownloadPayload(
- value: unknown,
- mode: BinaryCellDownloadMode,
- columnType?: string,
-): BinaryCellDownloadPayload {
+export function binaryCellDownloadPayload(value: unknown, mode: BinaryCellDownloadMode, columnType?: string): BinaryCellDownloadPayload {
const bytes = parseBinaryCellBytes(value, columnType);
if (!bytes) {
throw new Error("Cell value is not a downloadable binary value.");
@@ -140,12 +135,7 @@ export function binaryCellDownloadPayload(
};
}
-export function binaryCellDownloadFileName(options: {
- column: string;
- rowNumber: number;
- mode: BinaryCellDownloadMode;
- extension: string;
-}): string {
+export function binaryCellDownloadFileName(options: { column: string; rowNumber: number; mode: BinaryCellDownloadMode; extension: string }): string {
const column = options.column
.trim()
.replace(/[\\/:*?"<>|]+/g, "-")
@@ -156,10 +146,7 @@ export function binaryCellDownloadFileName(options: {
return `${safeColumn}-row-${options.rowNumber}${suffix}.${options.extension}`;
}
-export async function downloadBinaryCellPayload(
- payload: BinaryCellDownloadPayload,
- fileName: string,
-): Promise<BinaryCellDownloadResult> {
+export async function downloadBinaryCellPayload(payload: BinaryCellDownloadPayload, fileName: string): Promise<BinaryCellDownloadResult> {
if (isTauriRuntime()) {
const [{ save }, fs] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
const path = await save({
diff --git a/apps/desktop/src/lib/canvasDataGridRenderer.ts b/apps/desktop/src/lib/canvasDataGridRenderer.ts
index ccef705dd8..9cff8fdb9c 100644
--- a/apps/desktop/src/lib/canvasDataGridRenderer.ts
+++ b/apps/desktop/src/lib/canvasDataGridRenderer.ts
@@ -1,10 +1,6 @@
import type { CellValue } from "@/lib/cellValue";
import type { RowStatus } from "@/lib/gridRowStatus";
-import {
- DATA_GRID_DARK_SEARCH_COLORS,
- resolveDataGridPaintTheme,
- type DataGridPaintTheme,
-} from "@/lib/dataGridPaintTheme";
+import { DATA_GRID_DARK_SEARCH_COLORS, resolveDataGridPaintTheme, type DataGridPaintTheme } from "@/lib/dataGridPaintTheme";
export const CANVAS_DATA_GRID_ROW_HEIGHT = 26;
@@ -124,13 +120,7 @@ function fitCanvasText(ctx: CanvasRenderingContext2D, text: string, maxWidth: nu
return result;
}
-function canvasFont(style: {
- family: string;
- sizePx: number;
- style?: string;
- weight?: string | number;
- lineHeight?: string;
-}): string {
+function canvasFont(style: { family: string; sizePx: number; style?: string; weight?: string | number; lineHeight?: string }): string {
const fontStyle = style.style && style.style !== "normal" ? `${style.style} ` : "";
const fontWeight = style.weight && style.weight !== "400" && style.weight !== "normal" ? `${style.weight} ` : "";
const lineHeight = style.lineHeight && style.lineHeight !== "normal" ? `/${style.lineHeight}` : "";
@@ -171,8 +161,7 @@ function resolveCanvasRenderState(canvas: HTMLCanvasElement, isDark: boolean, st
if (cached?.cacheKey === cacheKey) return cached;
const canvasStyle = getComputedStyle(canvas);
- const fontFamily =
- canvasStyle.fontFamily || `"Geist Variable", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif`;
+ const fontFamily = canvasStyle.fontFamily || `"Geist Variable", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif`;
const fontSize = Number.parseFloat(canvasStyle.fontSize) || 12;
const lineHeight = canvasStyle.lineHeight;
const normalFont = canvasFont({
@@ -259,16 +248,7 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, width, height);
- const {
- normalFont,
- tabularFont,
- semiboldFont,
- italicFont,
- theme,
- searchFill,
- currentSearchFill,
- currentSearchBorder,
- } = resolveCanvasRenderState(canvas, isDark, styleKey);
+ const { normalFont, tabularFont, semiboldFont, italicFont, theme, searchFill, currentSearchFill, currentSearchBorder } = resolveCanvasRenderState(canvas, isDark, styleKey);
const scrollTop = scroller.scrollTop;
const scrollLeft = scroller.scrollLeft;
@@ -294,37 +274,17 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
if (!item) continue;
const y = rowIndex * CANVAS_DATA_GRID_ROW_HEIGHT - scrollTop;
const rowIsActive = isRowActive(item.displayIndex);
- const rowBase = item.isDeleted
- ? theme.rowDeleted
- : item.isNew && !rowIsActive
- ? theme.rowNew
- : item.displayIndex % 2 === 1 && !rowIsActive
- ? theme.rowMuted
- : theme.background;
+ const rowBase = item.isDeleted ? theme.rowDeleted : item.isNew && !rowIsActive ? theme.rowNew : item.displayIndex % 2 === 1 && !rowIsActive ? theme.rowMuted : theme.background;
ctx.globalAlpha = item.isDeleted ? 0.7 : 1;
ctx.fillStyle = rowBase;
ctx.fillRect(0, y, width, CANVAS_DATA_GRID_ROW_HEIGHT);
- let rowNumberFill =
- item.status === "new"
- ? theme.rowNumberNew
- : item.status === "edited"
- ? theme.rowNumberEdited
- : item.status === "deleted"
- ? theme.rowNumberDeleted
- : theme.rowNumberDefault;
+ let rowNumberFill = item.status === "new" ? theme.rowNumberNew : item.status === "edited" ? theme.rowNumberEdited : item.status === "deleted" ? theme.rowNumberDeleted : theme.rowNumberDefault;
if (rowIsActive && !item.isDeleted) rowNumberFill = theme.rowNumberActive;
if (isRowSelected(item.id) && item.status === "clean") rowNumberFill = theme.rowNumberSelected;
ctx.fillStyle = rowNumberFill;
ctx.fillRect(0, y, rowNumberWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
- if (
- hoverCell?.rowIndex === item.displayIndex &&
- hoverCell.visibleColIdx < 0 &&
- !isScrolling &&
- item.status === "clean" &&
- !rowIsActive &&
- !isRowSelected(item.id)
- ) {
+ if (hoverCell?.rowIndex === item.displayIndex && hoverCell.visibleColIdx < 0 && !isScrolling && item.status === "clean" && !rowIsActive && !isRowSelected(item.id)) {
ctx.fillStyle = theme.cellHover;
ctx.fillRect(0, y, rowNumberWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
@@ -334,16 +294,7 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
ctx.lineTo(rowNumberBorderX, y + CANVAS_DATA_GRID_ROW_HEIGHT);
ctx.stroke();
- const rowNumberText =
- item.status === "new"
- ? theme.rowNumberTextNew
- : item.status === "edited"
- ? theme.rowNumberTextEdited
- : item.status === "deleted"
- ? theme.rowNumberTextDeleted
- : isRowSelected(item.id)
- ? theme.primary
- : theme.rowNumberTextClean;
+ const rowNumberText = item.status === "new" ? theme.rowNumberTextNew : item.status === "edited" ? theme.rowNumberTextEdited : item.status === "deleted" ? theme.rowNumberTextDeleted : isRowSelected(item.id) ? theme.primary : theme.rowNumberTextClean;
ctx.fillStyle = rowNumberText;
ctx.font = item.status === "new" || item.status === "edited" || isRowSelected(item.id) ? semiboldFont : normalFont;
ctx.textAlign = "center";
@@ -369,18 +320,12 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
if (x + colWidth >= rowNumberWidth) {
const selectedCell = cellIsSelected(item.displayIndex, visibleColIdx);
const rowSelectionVisual = rowCellsUseSelectionVisual(item.id);
- const isSingleSelectedCell =
- singleSelectedCell?.rowIndex === item.displayIndex && singleSelectedCell.visibleColIdx === visibleColIdx;
+ const isSingleSelectedCell = singleSelectedCell?.rowIndex === item.displayIndex && singleSelectedCell.visibleColIdx === visibleColIdx;
const isDirtyCell = item.isDirtyCol[actualColIdx];
- const selectedFillVisual =
- rowSelectionVisual ||
- (selectedCell && (!isSingleSelectedCell || isDirtyCell) && (!rowIsActive || isDirtyCell));
+ const selectedFillVisual = rowSelectionVisual || (selectedCell && (!isSingleSelectedCell || isDirtyCell) && (!rowIsActive || isDirtyCell));
const selectedBorderVisual = rowSelectionVisual || selectedCell;
const isSearchMatch = paintSearchMatches && searchMatchKeys.has(`${item.displayIndex}:${actualColIdx}`);
- const isCurrentSearchMatch =
- paintSearchMatches &&
- currentSearchMatch?.displayRow === item.displayIndex &&
- currentSearchMatch.col === actualColIdx;
+ const isCurrentSearchMatch = paintSearchMatches && currentSearchMatch?.displayRow === item.displayIndex && currentSearchMatch.col === actualColIdx;
const clippedX = Math.max(x, rowNumberWidth);
const cellPaintWidth = colWidth - Math.max(0, clippedX - x);
@@ -388,15 +333,7 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
ctx.fillStyle = theme.cellDirty;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
- if (
- hoverCell?.rowIndex === item.displayIndex &&
- hoverCell.visibleColIdx === visibleColIdx &&
- !isScrolling &&
- !isSearchMatch &&
- !isCurrentSearchMatch &&
- !isDirtyCell &&
- cellCanHover(item, actualColIdx)
- ) {
+ if (hoverCell?.rowIndex === item.displayIndex && hoverCell.visibleColIdx === visibleColIdx && !isScrolling && !isSearchMatch && !isCurrentSearchMatch && !isDirtyCell && cellCanHover(item, actualColIdx)) {
ctx.fillStyle = theme.cellHover;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
diff --git a/apps/desktop/src/lib/clipboard.ts b/apps/desktop/src/lib/clipboard.ts
index 70c9ce1a85..da60ce809c 100644
--- a/apps/desktop/src/lib/clipboard.ts
+++ b/apps/desktop/src/lib/clipboard.ts
@@ -37,9 +37,7 @@ export interface ClipboardEnvironment {
document?: ClipboardDocument;
}
-export async function readTextFromClipboard(
- env: ClipboardEnvironment = globalThis as unknown as ClipboardEnvironment,
-): Promise<string> {
+export async function readTextFromClipboard(env: ClipboardEnvironment = globalThis as unknown as ClipboardEnvironment): Promise<string> {
if (isTauriRuntime(env as unknown as Record<string, unknown>)) {
try {
const { readText } = await import("@tauri-apps/plugin-clipboard-manager");
@@ -56,10 +54,7 @@ export async function readTextFromClipboard(
throw new Error("Clipboard API is not available");
}
-export async function copyToClipboard(
- text: string,
- env: ClipboardEnvironment = globalThis as unknown as ClipboardEnvironment,
-): Promise<void> {
+export async function copyToClipboard(text: string, env: ClipboardEnvironment = globalThis as unknown as ClipboardEnvironment): Promise<void> {
if (isTauriRuntime(env as unknown as Record<string, unknown>)) {
try {
const { writeText } = await import("@tauri-apps/plugin-clipboard-manager");
diff --git a/apps/desktop/src/lib/codemirrorSelectionMatches.ts b/apps/desktop/src/lib/codemirrorSelectionMatches.ts
index 4b8e56195a..3db640621d 100644
--- a/apps/desktop/src/lib/codemirrorSelectionMatches.ts
+++ b/apps/desktop/src/lib/codemirrorSelectionMatches.ts
@@ -73,17 +73,13 @@ class SelectionMatchScrollbar {
private render(view: EditorView) {
const markers = buildSelectionMatchMarkers(view.state);
const lineCount = view.state.doc.lines;
- const signature = markers
- .map((marker) => `${marker.lineNumber}:${marker.from}:${marker.to}:${marker.selected}`)
- .join("|");
+ const signature = markers.map((marker) => `${marker.lineNumber}:${marker.from}:${marker.to}:${marker.selected}`).join("|");
if (signature === this.signature) return;
this.signature = signature;
this.layer.replaceChildren(
...markers.map((marker) => {
const el = document.createElement("div");
- el.className = marker.selected
- ? "cm-selectionMatchScrollbarMark cm-selectionMatchScrollbarMark-selected"
- : "cm-selectionMatchScrollbarMark";
+ el.className = marker.selected ? "cm-selectionMatchScrollbarMark cm-selectionMatchScrollbarMark-selected" : "cm-selectionMatchScrollbarMark";
const ratio = lineCount <= 1 ? 0 : (marker.lineNumber - 1) / (lineCount - 1);
el.style.top = `${Math.max(0, Math.min(1, ratio)) * 100}%`;
return el;
diff --git a/apps/desktop/src/lib/codemirrorTrimmedSelectionLayer.ts b/apps/desktop/src/lib/codemirrorTrimmedSelectionLayer.ts
index 16befe1d96..4fc7a9d369 100644
--- a/apps/desktop/src/lib/codemirrorTrimmedSelectionLayer.ts
+++ b/apps/desktop/src/lib/codemirrorTrimmedSelectionLayer.ts
@@ -14,11 +14,7 @@ type TrimmedSelectionRect = {
type PositionRect = ReturnType<EditorView["coordsAtPos"]>;
-function visualLineVerticalBounds(
- view: EditorView,
- start: NonNullable<PositionRect>,
- end: NonNullable<PositionRect>,
-): { top: number; bottom: number } {
+function visualLineVerticalBounds(view: EditorView, start: NonNullable<PositionRect>, end: NonNullable<PositionRect>): { top: number; bottom: number } {
const top = Math.min(start.top, end.top);
const bottom = Math.max(start.bottom, end.bottom);
const height = Math.max(bottom - top, view.defaultLineHeight);
@@ -37,15 +33,7 @@ function layerBase(view: EditorView) {
};
}
-function markerForLineRange(
- view: EditorView,
- from: number,
- to: number,
- lineFrom: number,
- lineTo: number,
- includesLineBreak: boolean,
- base: { left: number; top: number },
-): TrimmedSelectionRect | null {
+function markerForLineRange(view: EditorView, from: number, to: number, lineFrom: number, lineTo: number, includesLineBreak: boolean, base: { left: number; top: number }): TrimmedSelectionRect | null {
const start = view.coordsAtPos(from, 1);
const end = from < to ? view.coordsAtPos(to, -1) : start;
const lineStart = view.coordsAtPos(lineFrom, 1) ?? start;
@@ -74,12 +62,7 @@ function sameVisualLine(a: NonNullable<PositionRect>, b: NonNullable<PositionRec
return Math.abs(aMid - bMid) <= Math.max(2, Math.min(a.bottom - a.top, b.bottom - b.top) / 2);
}
-function lastPositionOnVisualLine(
- view: EditorView,
- from: number,
- to: number,
- start: NonNullable<PositionRect>,
-): number {
+function lastPositionOnVisualLine(view: EditorView, from: number, to: number, start: NonNullable<PositionRect>): number {
let low = from + 1;
let high = to;
let best = from;
@@ -98,15 +81,7 @@ function lastPositionOnVisualLine(
return best > from ? best : Math.min(to, from + 1);
}
-function markerRectsForLineRange(
- view: EditorView,
- from: number,
- to: number,
- lineFrom: number,
- lineTo: number,
- includesLineBreak: boolean,
- base: { left: number; top: number },
-): TrimmedSelectionRect[] {
+function markerRectsForLineRange(view: EditorView, from: number, to: number, lineFrom: number, lineTo: number, includesLineBreak: boolean, base: { left: number; top: number }): TrimmedSelectionRect[] {
const start = view.coordsAtPos(from, 1);
const end = from < to ? view.coordsAtPos(to, -1) : start;
if (!start || !end) return [];
@@ -121,15 +96,7 @@ function markerRectsForLineRange(
const segmentStart = view.coordsAtPos(segmentFrom, 1);
if (!segmentStart) break;
const segmentTo = lastPositionOnVisualLine(view, segmentFrom, to, segmentStart);
- const rect = markerForLineRange(
- view,
- segmentFrom,
- segmentTo,
- lineFrom,
- lineTo,
- includesLineBreak && segmentTo >= to,
- base,
- );
+ const rect = markerForLineRange(view, segmentFrom, segmentTo, lineFrom, lineTo, includesLineBreak && segmentTo >= to, base);
if (rect) rects.push(rect);
if (segmentTo <= segmentFrom) break;
segmentFrom = segmentTo;
diff --git a/apps/desktop/src/lib/columnFormatter.ts b/apps/desktop/src/lib/columnFormatter.ts
index f8b42a7a26..77abf18a81 100644
--- a/apps/desktop/src/lib/columnFormatter.ts
+++ b/apps/desktop/src/lib/columnFormatter.ts
@@ -8,12 +8,7 @@ export interface CustomColumnFormatterConfig {
template: string;
}
-export type ColumnFormatterConfig =
- | { kind: "datetime"; unit: DateTimeFormatterUnit }
- | { kind: "json-path"; path: string }
- | { kind: "mask"; prefix: number; suffix: number }
- | { kind: "custom-template"; template: string }
- | { kind: "custom-ref"; formatterId: string };
+export type ColumnFormatterConfig = { kind: "datetime"; unit: DateTimeFormatterUnit } | { kind: "json-path"; path: string } | { kind: "mask"; prefix: number; suffix: number } | { kind: "custom-template"; template: string } | { kind: "custom-ref"; formatterId: string };
export interface ColumnFormatterKeyParts {
connectionId: string;
@@ -32,15 +27,11 @@ export function normalizeColumnFormatter(value: unknown): ColumnFormatterConfig
const config = value as Record<string, unknown>;
if (config.kind === "datetime") {
- return config.unit === "seconds" || config.unit === "milliseconds" || config.unit === "auto"
- ? { kind: "datetime", unit: config.unit }
- : undefined;
+ return config.unit === "seconds" || config.unit === "milliseconds" || config.unit === "auto" ? { kind: "datetime", unit: config.unit } : undefined;
}
if (config.kind === "json-path") {
- return typeof config.path === "string" && isSupportedJsonPath(config.path)
- ? { kind: "json-path", path: config.path }
- : undefined;
+ return typeof config.path === "string" && isSupportedJsonPath(config.path) ? { kind: "json-path", path: config.path } : undefined;
}
if (config.kind === "mask") {
@@ -50,15 +41,11 @@ export function normalizeColumnFormatter(value: unknown): ColumnFormatterConfig
}
if (config.kind === "custom-template") {
- return typeof config.template === "string" && config.template.trim()
- ? { kind: "custom-template", template: config.template.slice(0, 500) }
- : undefined;
+ return typeof config.template === "string" && config.template.trim() ? { kind: "custom-template", template: config.template.slice(0, 500) } : undefined;
}
if (config.kind === "custom-ref") {
- return typeof config.formatterId === "string" && config.formatterId.trim()
- ? { kind: "custom-ref", formatterId: config.formatterId }
- : undefined;
+ return typeof config.formatterId === "string" && config.formatterId.trim() ? { kind: "custom-ref", formatterId: config.formatterId } : undefined;
}
return undefined;
@@ -77,10 +64,7 @@ export function normalizeCustomColumnFormatter(value: unknown): CustomColumnForm
};
}
-export function resolveColumnFormatter(
- formatter: ColumnFormatterConfig | undefined,
- customFormatters: Record<string, CustomColumnFormatterConfig>,
-): ColumnFormatterConfig | undefined {
+export function resolveColumnFormatter(formatter: ColumnFormatterConfig | undefined, customFormatters: Record<string, CustomColumnFormatterConfig>): ColumnFormatterConfig | undefined {
if (!formatter) return undefined;
if (formatter.kind !== "custom-ref") return formatter;
const customFormatter = customFormatters[formatter.formatterId];
@@ -106,8 +90,7 @@ function formatDateTime(value: CellValue, unit: DateTimeFormatterUnit): string {
if (typeof value === "string" && !isTimestampString(value, unit)) return displayCellValue(value);
const numeric = typeof value === "number" ? value : Number(String(value).trim());
if (!Number.isFinite(numeric)) return displayCellValue(value);
- const timestamp =
- unit === "seconds" || (unit === "auto" && Math.abs(numeric) < 100_000_000_000) ? numeric * 1000 : numeric;
+ const timestamp = unit === "seconds" || (unit === "auto" && Math.abs(numeric) < 100_000_000_000) ? numeric * 1000 : numeric;
const date = new Date(timestamp);
return Number.isNaN(date.getTime()) ? displayCellValue(value) : date.toLocaleString();
}
@@ -150,18 +133,12 @@ function formatMask(value: CellValue, formatter: Extract<ColumnFormatterConfig,
const text = displayCellValue(value);
const visibleCount = formatter.prefix + formatter.suffix;
if (text.length <= visibleCount) return "*".repeat(text.length);
- return `${text.slice(0, formatter.prefix)}${"*".repeat(text.length - visibleCount)}${text.slice(
- text.length - formatter.suffix,
- )}`;
+ return `${text.slice(0, formatter.prefix)}${"*".repeat(text.length - visibleCount)}${text.slice(text.length - formatter.suffix)}`;
}
function formatCustomTemplate(value: CellValue, template: string): string {
const text = displayCellValue(value);
- return template
- .replaceAll("${value}", text)
- .replaceAll("${upper}", text.toUpperCase())
- .replaceAll("${lower}", text.toLowerCase())
- .replaceAll("${length}", String(text.length));
+ return template.replaceAll("${value}", text).replaceAll("${upper}", text.toUpperCase()).replaceAll("${lower}", text.toLowerCase()).replaceAll("${length}", String(text.length));
}
function isSupportedJsonPath(path: string): boolean {
diff --git a/apps/desktop/src/lib/configCrypto.ts b/apps/desktop/src/lib/configCrypto.ts
index c79b96b4ee..d9a5c8c357 100644
--- a/apps/desktop/src/lib/configCrypto.ts
+++ b/apps/desktop/src/lib/configCrypto.ts
@@ -33,13 +33,7 @@ async function deriveKey(passphrase: string, salt: Uint8Array<ArrayBuffer>): Pro
const encoder = new TextEncoder();
const subtle = getSubtleCrypto();
const baseKey = await subtle.importKey("raw", encoder.encode(passphrase), "PBKDF2", false, ["deriveKey"]);
- return subtle.deriveKey(
- { name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
- baseKey,
- { name: "AES-GCM", length: 256 },
- false,
- ["encrypt", "decrypt"],
- );
+ return subtle.deriveKey({ name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" }, baseKey, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
}
function toBase64(data: ArrayBuffer | Uint8Array<ArrayBuffer>): string {
@@ -104,11 +98,5 @@ export async function decryptConfig(payload: EncryptedPayload, passphrase: strin
export function isEncryptedConfig(data: unknown): data is EncryptedPayload {
if (typeof data !== "object" || data === null) return false;
const obj = data as Record<string, unknown>;
- return (
- obj.format === "dbx-encrypted" &&
- obj.version === 1 &&
- typeof obj.salt === "string" &&
- typeof obj.iv === "string" &&
- typeof obj.data === "string"
- );
+ return obj.format === "dbx-encrypted" && obj.version === 1 && typeof obj.salt === "string" && typeof obj.iv === "string" && typeof obj.data === "string";
}
diff --git a/apps/desktop/src/lib/connectionAttemptTimeout.ts b/apps/desktop/src/lib/connectionAttemptTimeout.ts
index 8730293edb..e63342ac32 100644
--- a/apps/desktop/src/lib/connectionAttemptTimeout.ts
+++ b/apps/desktop/src/lib/connectionAttemptTimeout.ts
@@ -8,10 +8,7 @@ function positiveSeconds(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
}
-export function connectionAttemptTimeoutMs(
- config: Pick<ConnectionConfig, "connect_timeout_secs" | "transport_layers"> &
- Partial<Pick<ConnectionConfig, "db_type">>,
-): number {
+export function connectionAttemptTimeoutMs(config: Pick<ConnectionConfig, "connect_timeout_secs" | "transport_layers"> & Partial<Pick<ConnectionConfig, "db_type">>): number {
const timeouts = [positiveSeconds(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS)];
for (const layer of config.transport_layers ?? []) {
if (layer.type === "ssh") {
diff --git a/apps/desktop/src/lib/connectionHealth.ts b/apps/desktop/src/lib/connectionHealth.ts
index 51b75f1492..91e1b47890 100644
--- a/apps/desktop/src/lib/connectionHealth.ts
+++ b/apps/desktop/src/lib/connectionHealth.ts
@@ -1,12 +1,4 @@
-const CONNECTION_ERROR_PATTERNS = [
- "connection",
- "broken pipe",
- "reset by peer",
- "timed out",
- "closed",
- "eof",
- "i/o error",
-];
+const CONNECTION_ERROR_PATTERNS = ["connection", "broken pipe", "reset by peer", "timed out", "closed", "eof", "i/o error"];
export function staleConnectionMessage(error: unknown): string {
if (error instanceof Error) return error.message;
diff --git a/apps/desktop/src/lib/connectionPresentation.ts b/apps/desktop/src/lib/connectionPresentation.ts
index e65a44dfcb..b3a1bf7652 100644
--- a/apps/desktop/src/lib/connectionPresentation.ts
+++ b/apps/desktop/src/lib/connectionPresentation.ts
@@ -1,9 +1,6 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
-type ConnectionPresentationConfig = Pick<
- ConnectionConfig,
- "db_type" | "driver_profile" | "driver_label" | "host" | "port" | "database"
->;
+type ConnectionPresentationConfig = Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "host" | "port" | "database">;
type ConnectionNamePresentationConfig = ConnectionPresentationConfig & Pick<ConnectionConfig, "name">;
const LOCAL_DATABASE_TYPES = new Set(["sqlite", "duckdb", "access"]);
@@ -31,15 +28,12 @@ function redactConnectionHost(host: string): string {
const normalizedHost = host.trim();
if (!normalizedHost) return "";
- const unwrappedHost =
- normalizedHost.startsWith("[") && normalizedHost.endsWith("]") ? normalizedHost.slice(1, -1) : normalizedHost;
+ const unwrappedHost = normalizedHost.startsWith("[") && normalizedHost.endsWith("]") ? normalizedHost.slice(1, -1) : normalizedHost;
const separator = unwrappedHost.includes(":") ? ":" : ".";
const segments = unwrappedHost.split(separator).filter(Boolean);
if (segments.length >= 3) {
- return [segments[0], ...segments.slice(1, -1).map(() => REDACTED_HOST_SEGMENT), segments[segments.length - 1]].join(
- separator,
- );
+ return [segments[0], ...segments.slice(1, -1).map(() => REDACTED_HOST_SEGMENT), segments[segments.length - 1]].join(separator);
}
if (segments.length === 2) {
@@ -66,13 +60,7 @@ export function connectionRedactedEndpointLabel(connection?: ConnectionPresentat
export function connectionRedactedNameLabel(connection?: ConnectionNamePresentationConfig): string {
const name = connection?.name.trim() || "";
- if (
- !connection ||
- !name ||
- LOCAL_DATABASE_TYPES.has(connection.db_type) ||
- (connection.db_type === "h2" && connection.port === 0)
- )
- return name;
+ if (!connection || !name || LOCAL_DATABASE_TYPES.has(connection.db_type) || (connection.db_type === "h2" && connection.port === 0)) return name;
const host = connection.host.trim();
if (!host) return name;
diff --git a/apps/desktop/src/lib/connectionUrl.ts b/apps/desktop/src/lib/connectionUrl.ts
index 53b2332c8c..a570a3c21f 100644
--- a/apps/desktop/src/lib/connectionUrl.ts
+++ b/apps/desktop/src/lib/connectionUrl.ts
@@ -115,9 +115,7 @@ function parseMongoUrl(source: string): ParsedConnectionUrl | null {
if (firstHost.startsWith("[")) {
const bracketEnd = firstHost.indexOf("]");
host = firstHost.substring(1, bracketEnd);
- port = firstHost.substring(bracketEnd + 1).startsWith(":")
- ? Number(firstHost.substring(bracketEnd + 2)) || profile.defaultPort
- : profile.defaultPort;
+ port = firstHost.substring(bracketEnd + 1).startsWith(":") ? Number(firstHost.substring(bracketEnd + 2)) || profile.defaultPort : profile.defaultPort;
} else if (firstHost.includes(":")) {
const colonIdx = firstHost.lastIndexOf(":");
host = firstHost.substring(0, colonIdx);
@@ -191,9 +189,7 @@ function urlParamsRequireTls(dbType: DatabaseType, params: string): boolean {
if (dbType === "mysql") {
const requireSsl = queryParamValue(params, "require_ssl")?.toLowerCase();
if (requireSsl === "true" || requireSsl === "1" || requireSsl === "yes") return true;
- const sslMode = (queryParamValue(params, "ssl-mode") || queryParamValue(params, "sslmode") || "")
- .toLowerCase()
- .replace("-", "_");
+ const sslMode = (queryParamValue(params, "ssl-mode") || queryParamValue(params, "sslmode") || "").toLowerCase().replace("-", "_");
return sslMode === "required" || sslMode === "require" || sslMode === "verify_ca" || sslMode === "verify_identity";
}
@@ -345,10 +341,7 @@ function parseJdbcUCanAccessUrl(source: string): ParsedConnectionUrl | null {
}
function parseJdbcGbase8sUrl(source: string): ParsedConnectionUrl | null {
- const match =
- /^jdbc:gbasedbt-sqli:\/\/(?:(?<userinfo>[^@/?#]*)@)?(?<host>\[[^\]]+\]|[^:/?#]+)(?::(?<port>\d+))?\/(?<database>[^:?#]*)(?::(?<params>[^?#]*))?/i.exec(
- source,
- );
+ const match = /^jdbc:gbasedbt-sqli:\/\/(?:(?<userinfo>[^@/?#]*)@)?(?<host>\[[^\]]+\]|[^:/?#]+)(?::(?<port>\d+))?\/(?<database>[^:?#]*)(?::(?<params>[^?#]*))?/i.exec(source);
if (!match?.groups) return null;
const rawUserInfo = match.groups.userinfo || "";
@@ -403,12 +396,8 @@ export function parseConnectionUrl(value: string, preferredProfile?: string): Pa
const urlParams = parsed.search.replace(/^\?/, "");
const normalizedFragment = decodeUrlPart(parsed.hash.replace(/^#/, "")).trim().toLowerCase();
- const parsedUrlParams =
- profile.type === "redis" && normalizedFragment === "insecure"
- ? [urlParams, "insecure=true"].filter(Boolean).join("&")
- : urlParams;
- const mysqlCredentials =
- isJdbcUrl && profile.type === "mysql" ? extractMysqlCredentialParams(parsedUrlParams) : undefined;
+ const parsedUrlParams = profile.type === "redis" && normalizedFragment === "insecure" ? [urlParams, "insecure=true"].filter(Boolean).join("&") : urlParams;
+ const mysqlCredentials = isJdbcUrl && profile.type === "mysql" ? extractMysqlCredentialParams(parsedUrlParams) : undefined;
const effectiveUrlParams = mysqlCredentials?.urlParams ?? parsedUrlParams;
if (profile.type === "mongodb") {
return {
@@ -437,18 +426,11 @@ export function parseConnectionUrl(value: string, preferredProfile?: string): Pa
password: mysqlCredentials?.password ?? decodeUrlPart(parsed.password),
database: databaseFromPath(parsed.pathname),
urlParams: effectiveUrlParams,
- ssl:
- scheme === "rediss" ||
- scheme === "https" ||
- urlParamsRequireTls(profile.type, effectiveUrlParams) ||
- (profile.type === "mysql" && isTidbCloudHost(parsed.hostname)),
+ ssl: scheme === "rediss" || scheme === "https" || urlParamsRequireTls(profile.type, effectiveUrlParams) || (profile.type === "mysql" && isTidbCloudHost(parsed.hostname)),
};
}
-export function applyParsedConnectionUrl(
- config: Omit<ConnectionConfig, "id">,
- parsed: ParsedConnectionUrl,
-): Omit<ConnectionConfig, "id"> {
+export function applyParsedConnectionUrl(config: Omit<ConnectionConfig, "id">, parsed: ParsedConnectionUrl): Omit<ConnectionConfig, "id"> {
return {
...config,
db_type: parsed.dbType,
diff --git a/apps/desktop/src/lib/connectionVisibleDatabases.ts b/apps/desktop/src/lib/connectionVisibleDatabases.ts
index b31041560b..2c4f6dedfd 100644
--- a/apps/desktop/src/lib/connectionVisibleDatabases.ts
+++ b/apps/desktop/src/lib/connectionVisibleDatabases.ts
@@ -7,47 +7,25 @@ const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["elasticsearch
type VisibleDatabaseConnectionFields = Pick<
ConnectionConfig,
- | "db_type"
- | "driver_profile"
- | "host"
- | "port"
- | "username"
- | "database"
- | "connection_string"
- | "url_params"
- | "redis_connection_mode"
- | "redis_sentinel_master"
- | "redis_sentinel_nodes"
- | "redis_cluster_nodes"
- | "etcd_endpoints"
- | "jdbc_driver_class"
+ "db_type" | "driver_profile" | "host" | "port" | "username" | "database" | "connection_string" | "url_params" | "redis_connection_mode" | "redis_sentinel_master" | "redis_sentinel_nodes" | "redis_cluster_nodes" | "etcd_endpoints" | "jdbc_driver_class"
>;
export function buildDraftVisibleDatabasesConnectionId(seed: string): string {
return `${DRAFT_VISIBLE_DATABASES_PREFIX}${seed}`;
}
-export function connectionCanChooseVisibleDatabases(
- connection: Pick<ConnectionConfig, "db_type"> | undefined,
-): boolean {
+export function connectionCanChooseVisibleDatabases(connection: Pick<ConnectionConfig, "db_type"> | undefined): boolean {
return !!connection?.db_type && !UNSUPPORTED_VISIBLE_DATABASE_TYPES.has(connection.db_type);
}
-export function initialVisibleDatabaseSelection(
- databaseNames: string[],
- visibleDatabases: string[] | undefined,
- connection?: Pick<ConnectionConfig, "db_type" | "driver_profile" | "visible_databases">,
-): string[] {
+export function initialVisibleDatabaseSelection(databaseNames: string[], visibleDatabases: string[] | undefined, connection?: Pick<ConnectionConfig, "db_type" | "driver_profile" | "visible_databases">): string[] {
if (Array.isArray(visibleDatabases)) {
return normalizeVisibleDatabaseSelection(visibleDatabases, databaseNames);
}
return filterDatabaseNamesForConnection(databaseNames, connection);
}
-export function visibleDatabaseSelectionIsStale(
- previous: VisibleDatabaseConnectionFields,
- current: VisibleDatabaseConnectionFields,
-): boolean {
+export function visibleDatabaseSelectionIsStale(previous: VisibleDatabaseConnectionFields, current: VisibleDatabaseConnectionFields): boolean {
return visibleDatabaseFingerprint(previous) !== visibleDatabaseFingerprint(current);
}
diff --git a/apps/desktop/src/lib/createDatabaseSql.ts b/apps/desktop/src/lib/createDatabaseSql.ts
index af31abb12d..c80e931993 100644
--- a/apps/desktop/src/lib/createDatabaseSql.ts
+++ b/apps/desktop/src/lib/createDatabaseSql.ts
@@ -1,15 +1,7 @@
import type { DatabaseType } from "@/types/database";
import * as api from "@/lib/api";
-const MYSQL_COMPATIBLE_PROFILES = new Set([
- "mysql",
- "mariadb",
- "tidb",
- "oceanbase",
- "doris",
- "starrocks",
- "custom_mysql",
-]);
+const MYSQL_COMPATIBLE_PROFILES = new Set(["mysql", "mariadb", "tidb", "oceanbase", "doris", "starrocks", "custom_mysql"]);
const MYSQL_COMPATIBLE_TYPES = new Set<DatabaseType>(["mysql", "doris", "starrocks", "goldendb"]);
export interface CreateDatabaseSqlOptions {
@@ -21,10 +13,7 @@ export interface CreateDatabaseSqlOptions {
}
export function supportsCreateDatabaseCharset(databaseType?: DatabaseType, driverProfile?: string | null): boolean {
- return (
- MYSQL_COMPATIBLE_TYPES.has(databaseType as DatabaseType) ||
- (!!driverProfile && MYSQL_COMPATIBLE_PROFILES.has(driverProfile))
- );
+ return MYSQL_COMPATIBLE_TYPES.has(databaseType as DatabaseType) || (!!driverProfile && MYSQL_COMPATIBLE_PROFILES.has(driverProfile));
}
export function buildCreateDatabaseSql(options: CreateDatabaseSqlOptions): Promise<string> {
diff --git a/apps/desktop/src/lib/dataGridCellCoercion.ts b/apps/desktop/src/lib/dataGridCellCoercion.ts
index eb7e9e9d74..e89d2cd38a 100644
--- a/apps/desktop/src/lib/dataGridCellCoercion.ts
+++ b/apps/desktop/src/lib/dataGridCellCoercion.ts
@@ -24,11 +24,7 @@ export function coerceDataGridCellValue(options: CoerceDataGridCellValueOptions)
return normalizeSmartQuotedJsonInput(value);
}
-export function dataGridCellEditorText(options: {
- value: GridCellValue | undefined;
- databaseType: DatabaseType | undefined;
- columnInfo: Pick<ColumnInfo, "data_type"> | undefined;
-}): string {
+export function dataGridCellEditorText(options: { value: GridCellValue | undefined; databaseType: DatabaseType | undefined; columnInfo: Pick<ColumnInfo, "data_type"> | undefined }): string {
const value = options.value ?? null;
if (value === null) return "";
if (Array.isArray(value) && options.databaseType === "postgres" && isPostgresArrayColumn(options.columnInfo, value)) {
@@ -37,16 +33,8 @@ export function dataGridCellEditorText(options: {
return typeof value === "object" ? JSON.stringify(value) : String(value);
}
-export function dataGridCellDisplayText(options: {
- value: GridCellValue;
- databaseType: DatabaseType | undefined;
- columnInfo: Pick<ColumnInfo, "data_type"> | undefined;
-}): string | undefined {
- if (
- Array.isArray(options.value) &&
- options.databaseType === "postgres" &&
- isPostgresArrayColumn(options.columnInfo, options.value)
- ) {
+export function dataGridCellDisplayText(options: { value: GridCellValue; databaseType: DatabaseType | undefined; columnInfo: Pick<ColumnInfo, "data_type"> | undefined }): string | undefined {
+ if (Array.isArray(options.value) && options.databaseType === "postgres" && isPostgresArrayColumn(options.columnInfo, options.value)) {
return formatPostgresArrayText(options.value);
}
return undefined;
@@ -85,10 +73,7 @@ function deepEqual(a: unknown, b: unknown): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
-function isPostgresArrayColumn(
- columnInfo: Pick<ColumnInfo, "data_type"> | undefined,
- oldValue: GridCellValue | undefined,
-): boolean {
+function isPostgresArrayColumn(columnInfo: Pick<ColumnInfo, "data_type"> | undefined, oldValue: GridCellValue | undefined): boolean {
if (Array.isArray(oldValue)) return true;
const dataType = columnInfo?.data_type.trim().toLowerCase() ?? "";
return dataType === "array" || dataType.endsWith("[]") || dataType.startsWith("_");
diff --git a/apps/desktop/src/lib/dataGridColumnFilter.ts b/apps/desktop/src/lib/dataGridColumnFilter.ts
index f883d97902..5d3ee0db44 100644
--- a/apps/desktop/src/lib/dataGridColumnFilter.ts
+++ b/apps/desktop/src/lib/dataGridColumnFilter.ts
@@ -3,12 +3,7 @@ import type { DataGridColumnInfo, DataGridContextFilterMode, GridCellValue } fro
import { buildDataGridColumnValueFilterCondition } from "@/lib/dataGridSql";
import { normalizeWhereInput } from "@/lib/tableSelectSql";
-export function buildColumnValueFilterCondition(options: {
- databaseType?: DatabaseType;
- columnName: string;
- columnInfo?: Pick<ColumnInfo, "data_type">;
- rawValue: string;
-}): Promise<string | undefined> {
+export function buildColumnValueFilterCondition(options: { databaseType?: DatabaseType; columnName: string; columnInfo?: Pick<ColumnInfo, "data_type">; rawValue: string }): Promise<string | undefined> {
return buildDataGridColumnValueFilterCondition({
databaseType: options.databaseType,
columnName: options.columnName,
@@ -23,10 +18,7 @@ export function buildColumnValueFilterCondition(options: {
});
}
-export function appendColumnValueFilterCondition(
- whereInput: string | undefined,
- condition: string | undefined,
-): string {
+export function appendColumnValueFilterCondition(whereInput: string | undefined, condition: string | undefined): string {
if (!condition) return normalizeWhereInput(whereInput);
const existing = normalizeWhereInput(whereInput);
return existing ? `(${existing}) AND (${condition})` : condition;
@@ -77,22 +69,7 @@ function unwrapMatchingQuotes(text: string): string {
}
function isNumericType(dataType: string): boolean {
- return [
- "int",
- "integer",
- "bigint",
- "smallint",
- "tinyint",
- "mediumint",
- "serial",
- "number",
- "numeric",
- "decimal",
- "float",
- "double",
- "real",
- "money",
- ].some((part) => dataType.split(/[^a-z0-9]+/).includes(part));
+ return ["int", "integer", "bigint", "smallint", "tinyint", "mediumint", "serial", "number", "numeric", "decimal", "float", "double", "real", "money"].some((part) => dataType.split(/[^a-z0-9]+/).includes(part));
}
function isBooleanType(dataType: string): boolean {
diff --git a/apps/desktop/src/lib/dataGridColumnType.ts b/apps/desktop/src/lib/dataGridColumnType.ts
index 8da5fe07c1..9d9f52901a 100644
--- a/apps/desktop/src/lib/dataGridColumnType.ts
+++ b/apps/desktop/src/lib/dataGridColumnType.ts
@@ -20,11 +20,7 @@ export interface HeaderColumnTypeSources {
actualColIdx: number;
}
-export function resolveHeaderColumnType({
- tableColumnType,
- resultColumnTypes,
- actualColIdx,
-}: HeaderColumnTypeSources): string | undefined {
+export function resolveHeaderColumnType({ tableColumnType, resultColumnTypes, actualColIdx }: HeaderColumnTypeSources): string | undefined {
const fromMeta = tableColumnType?.trim();
if (fromMeta) return fromMeta;
diff --git a/apps/desktop/src/lib/dataGridColumnVisibility.ts b/apps/desktop/src/lib/dataGridColumnVisibility.ts
index 183eaf6891..6d7cbe1044 100644
--- a/apps/desktop/src/lib/dataGridColumnVisibility.ts
+++ b/apps/desktop/src/lib/dataGridColumnVisibility.ts
@@ -5,24 +5,15 @@ export interface ColumnVisibilityOption {
export function filterColumnVisibilityOptions(columns: string[], query: string): ColumnVisibilityOption[] {
const normalizedQuery = query.trim().toLowerCase();
- return columns
- .map((column, index) => ({ column, index }))
- .filter(({ column }) => !normalizedQuery || column.toLowerCase().includes(normalizedQuery));
+ return columns.map((column, index) => ({ column, index })).filter(({ column }) => !normalizedQuery || column.toLowerCase().includes(normalizedQuery));
}
-export function visibleColumnIndexesForFilter(
- availableIndexes: number[],
- hiddenIndexes: ReadonlySet<number>,
-): number[] {
+export function visibleColumnIndexesForFilter(availableIndexes: number[], hiddenIndexes: ReadonlySet<number>): number[] {
const visibleIndexes = availableIndexes.filter((index) => !hiddenIndexes.has(index));
return visibleIndexes.length > 0 ? visibleIndexes : availableIndexes;
}
-export function nextHiddenColumnIndexes(options: {
- columnIndex: number;
- hiddenIndexes: ReadonlySet<number>;
- totalColumns: number;
-}): Set<number> {
+export function nextHiddenColumnIndexes(options: { columnIndex: number; hiddenIndexes: ReadonlySet<number>; totalColumns: number }): Set<number> {
const next = new Set(options.hiddenIndexes);
if (next.has(options.columnIndex)) {
next.delete(options.columnIndex);
@@ -34,10 +25,7 @@ export function nextHiddenColumnIndexes(options: {
return next;
}
-export function invertedHiddenColumnIndexes(
- availableIndexes: number[],
- hiddenIndexes: ReadonlySet<number>,
-): Set<number> {
+export function invertedHiddenColumnIndexes(availableIndexes: number[], hiddenIndexes: ReadonlySet<number>): Set<number> {
const next = new Set(availableIndexes.filter((index) => !hiddenIndexes.has(index)));
if (next.size === availableIndexes.length && availableIndexes.length > 0) {
next.delete(availableIndexes[0]);
@@ -45,19 +33,12 @@ export function invertedHiddenColumnIndexes(
return next;
}
-export function allNullColumnIndexes(
- rows: ReadonlyArray<ReadonlyArray<unknown>>,
- availableIndexes: number[],
-): number[] {
+export function allNullColumnIndexes(rows: ReadonlyArray<ReadonlyArray<unknown>>, availableIndexes: number[]): number[] {
if (rows.length === 0) return [];
return availableIndexes.filter((index) => rows.every((row) => row[index] === null));
}
-export function hiddenColumnIndexesWithAllNullColumns(options: {
- availableIndexes: number[];
- hiddenIndexes: ReadonlySet<number>;
- allNullIndexes: ReadonlySet<number>;
-}): { hiddenIndexes: Set<number>; autoHiddenIndexes: Set<number> } {
+export function hiddenColumnIndexesWithAllNullColumns(options: { availableIndexes: number[]; hiddenIndexes: ReadonlySet<number>; allNullIndexes: ReadonlySet<number> }): { hiddenIndexes: Set<number>; autoHiddenIndexes: Set<number> } {
const next = new Set(options.hiddenIndexes);
const autoHidden = new Set<number>();
const available = new Set(options.availableIndexes);
@@ -70,8 +51,7 @@ export function hiddenColumnIndexesWithAllNullColumns(options: {
const hasVisibleColumn = options.availableIndexes.some((index) => !next.has(index));
if (!hasVisibleColumn && options.availableIndexes.length > 0) {
- const restoredIndex =
- options.availableIndexes.find((index) => autoHidden.has(index)) ?? options.availableIndexes[0];
+ const restoredIndex = options.availableIndexes.find((index) => autoHidden.has(index)) ?? options.availableIndexes[0];
next.delete(restoredIndex);
autoHidden.delete(restoredIndex);
}
@@ -79,10 +59,7 @@ export function hiddenColumnIndexesWithAllNullColumns(options: {
return { hiddenIndexes: next, autoHiddenIndexes: autoHidden };
}
-export function removeAutoHiddenColumnIndexes(
- hiddenIndexes: ReadonlySet<number>,
- autoHiddenIndexes: ReadonlySet<number>,
-): Set<number> {
+export function removeAutoHiddenColumnIndexes(hiddenIndexes: ReadonlySet<number>, autoHiddenIndexes: ReadonlySet<number>): Set<number> {
const next = new Set(hiddenIndexes);
for (const index of autoHiddenIndexes) {
next.delete(index);
diff --git a/apps/desktop/src/lib/dataGridColumnWidth.ts b/apps/desktop/src/lib/dataGridColumnWidth.ts
index 439ac1e285..2f9745c091 100644
--- a/apps/desktop/src/lib/dataGridColumnWidth.ts
+++ b/apps/desktop/src/lib/dataGridColumnWidth.ts
@@ -16,10 +16,7 @@ function displaySampleValue(value: CellValue): string | null {
return typeof value === "object" ? JSON.stringify(value) : String(value);
}
-export function calculateDataGridColumnWidth(options: {
- columnName: string;
- sampleValues: readonly CellValue[];
-}): number {
+export function calculateDataGridColumnWidth(options: { columnName: string; sampleValues: readonly CellValue[] }): number {
let maxWidth = estimateTextWidth(options.columnName, DATA_GRID_HEADER_CONTROL_WIDTH);
for (const value of options.sampleValues.slice(0, DATA_GRID_SAMPLE_ROWS)) {
diff --git a/apps/desktop/src/lib/dataGridDetail.ts b/apps/desktop/src/lib/dataGridDetail.ts
index 5cf81adfe8..836edb53b8 100644
--- a/apps/desktop/src/lib/dataGridDetail.ts
+++ b/apps/desktop/src/lib/dataGridDetail.ts
@@ -100,8 +100,7 @@ export function buildDataGridCellDetail(options: BuildDataGridCellDetailOptions)
rawValuePreview,
displayValue,
displayValuePreview,
- isValuePreviewTruncated:
- rawValuePreview.length < rawValue.length || displayValuePreview.length < displayValue.length,
+ isValuePreviewTruncated: rawValuePreview.length < rawValue.length || displayValuePreview.length < displayValue.length,
imagePreviewUrl: rawValue.length <= CELL_DETAIL_VALUE_PREVIEW_MAX_LENGTH ? cellImagePreviewUrl(value) : null,
length: value === null ? 0 : String(value).length,
formattedJson,
@@ -192,13 +191,7 @@ export function dataGridColumnDetailTsv(detail: DataGridColumnDetail): string {
export function filterDataGridDetailFields<T extends DataGridCellDetail>(fields: readonly T[], keyword: string): T[] {
if (keyword.trim() === "") return [...fields];
const kw = keyword.trim().toLowerCase();
- return fields.filter(
- (field) =>
- field.column.toLowerCase().includes(kw) ||
- field.rawValuePreview.toLowerCase().includes(kw) ||
- field.displayValuePreview.toLowerCase().includes(kw) ||
- String(field.rowNumber).includes(kw),
- );
+ return fields.filter((field) => field.column.toLowerCase().includes(kw) || field.rawValuePreview.toLowerCase().includes(kw) || field.displayValuePreview.toLowerCase().includes(kw) || String(field.rowNumber).includes(kw));
}
function looksLikeJsonContainer(text: string): boolean {
diff --git a/apps/desktop/src/lib/dataGridPagination.ts b/apps/desktop/src/lib/dataGridPagination.ts
index c0f3edf22a..8fac6c158f 100644
--- a/apps/desktop/src/lib/dataGridPagination.ts
+++ b/apps/desktop/src/lib/dataGridPagination.ts
@@ -15,10 +15,7 @@ export function canGoNextDataGridPage(options: CanGoNextDataGridPageOptions): bo
if (options.hasMore === true) return true;
const pageSize = Math.max(1, options.pageSize);
- const currentOffset =
- typeof options.pageOffset === "number" && options.pageOffset >= 0
- ? options.pageOffset
- : Math.max(0, (options.currentPage ?? 1) - 1) * pageSize;
+ const currentOffset = typeof options.pageOffset === "number" && options.pageOffset >= 0 ? options.pageOffset : Math.max(0, (options.currentPage ?? 1) - 1) * pageSize;
const totalRowCount = options.totalRowCount;
if (typeof totalRowCount === "number" && Number.isFinite(totalRowCount) && totalRowCount >= 0) {
diff --git a/apps/desktop/src/lib/dataGridPaintTheme.ts b/apps/desktop/src/lib/dataGridPaintTheme.ts
index d8b2137b8b..7cea2ca0cc 100644
--- a/apps/desktop/src/lib/dataGridPaintTheme.ts
+++ b/apps/desktop/src/lib/dataGridPaintTheme.ts
@@ -89,9 +89,7 @@ function parseRgbColor(value: string): RgbaColor | null {
const rgb = value.match(/^rgba?\((.+)\)$/i)?.[1]?.trim();
if (!rgb) return null;
- const parts = rgb.includes(",")
- ? rgb.split(",").map((part) => part.trim())
- : rgb.replace(/\s+\/\s+/, " / ").split(/\s+/);
+ const parts = rgb.includes(",") ? rgb.split(",").map((part) => part.trim()) : rgb.replace(/\s+\/\s+/, " / ").split(/\s+/);
const slashIndex = parts.indexOf("/");
const channels = slashIndex >= 0 ? parts.slice(0, slashIndex) : parts.slice(0, 3);
const alpha = slashIndex >= 0 ? parts[slashIndex + 1] : parts[3];
@@ -186,8 +184,7 @@ function toCanvasSafeColor(value: string, fallback: string): string {
const rgb = parseRgbColor(trimmed);
if (rgb) return formatRgb(rgb);
if (CANVAS_SAFE_COLOR_RE.test(trimmed)) return trimmed;
- if (ADVANCED_COLOR_RE.test(trimmed))
- return normalizeCssColorWithBrowser(trimmed) ?? parseColorMix(trimmed) ?? fallback;
+ if (ADVANCED_COLOR_RE.test(trimmed)) return normalizeCssColorWithBrowser(trimmed) ?? parseColorMix(trimmed) ?? fallback;
return `hsl(${trimmed})`;
}
@@ -209,18 +206,11 @@ function paintToken(getVar: (name: string) => string, name: string, fallback: st
return toCanvasSafeColor(value, fallback);
}
-export function resolveDataGridPaintTheme(options: {
- getVar: (name: string) => string;
- isDark: boolean;
-}): DataGridPaintTheme {
+export function resolveDataGridPaintTheme(options: { getVar: (name: string) => string; isDark: boolean }): DataGridPaintTheme {
const { getVar, isDark } = options;
const background = cssVarColor(getVar, "--background", isDark ? "rgb(19, 20, 22)" : "rgb(255, 255, 255)");
const foreground = cssVarColor(getVar, "--foreground", isDark ? "rgb(215, 215, 219)" : "rgb(10, 10, 10)");
- const mutedForeground = cssVarColor(
- getVar,
- "--muted-foreground",
- isDark ? "rgb(151, 152, 157)" : "rgb(115, 115, 115)",
- );
+ const mutedForeground = cssVarColor(getVar, "--muted-foreground", isDark ? "rgb(151, 152, 157)" : "rgb(115, 115, 115)");
const primary = cssVarColor(getVar, "--primary", isDark ? "rgb(208, 208, 214)" : "rgb(23, 23, 23)");
const destructive = cssVarColor(getVar, "--destructive", isDark ? "rgb(243, 98, 95)" : "rgb(231, 0, 11)");
const accent = cssVarColor(getVar, "--accent", isDark ? "rgb(46, 47, 51)" : "rgb(245, 245, 245)");
@@ -237,9 +227,7 @@ export function resolveDataGridPaintTheme(options: {
const cellSearch = isDark ? DATA_GRID_DARK_SEARCH_COLORS.match : "rgb(253, 245, 184)";
const cellCurrentSearch = isDark ? DATA_GRID_DARK_SEARCH_COLORS.current : "rgba(253, 224, 71, 0.52)";
const cellCurrentSearchBorder = isDark ? DATA_GRID_DARK_SEARCH_COLORS.currentBorder : "rgba(234, 179, 8, 0.82)";
- const rowNumberDefault = isDark
- ? DATA_GRID_DARK_ROW_NUMBER_BG
- : paintToken(getVar, "--data-grid-row-number-default-bg", "rgb(255, 255, 255)");
+ const rowNumberDefault = isDark ? DATA_GRID_DARK_ROW_NUMBER_BG : paintToken(getVar, "--data-grid-row-number-default-bg", "rgb(255, 255, 255)");
const rowNumberNew = isDark ? DATA_GRID_DARK_ROW_NUMBER_NEW_BG : DATA_GRID_LIGHT_ROW_NUMBER_NEW_BG;
const rowNumberEdited = isDark ? DATA_GRID_DARK_ROW_NUMBER_EDITED_BG : DATA_GRID_LIGHT_ROW_NUMBER_EDITED_BG;
const rowNumberDeleted = isDark ? DATA_GRID_DARK_ROW_NUMBER_DELETED_BG : DATA_GRID_LIGHT_ROW_NUMBER_DELETED_BG;
diff --git a/apps/desktop/src/lib/dataGridSaveUi.ts b/apps/desktop/src/lib/dataGridSaveUi.ts
index 38472b33fb..e67ecf9415 100644
--- a/apps/desktop/src/lib/dataGridSaveUi.ts
+++ b/apps/desktop/src/lib/dataGridSaveUi.ts
@@ -4,10 +4,7 @@ export interface DataGridSaveActionMode {
secondaryActionKey: "grid.rollback" | "grid.discard";
}
-export function dataGridSaveActionMode(options: {
- pendingChangeCount: number;
- useTransaction: boolean;
-}): DataGridSaveActionMode {
+export function dataGridSaveActionMode(options: { pendingChangeCount: number; useTransaction: boolean }): DataGridSaveActionMode {
return {
labelKey: options.useTransaction ? "grid.commit" : "grid.save",
tooltipKey: options.useTransaction ? "grid.transactionSaveHint" : "grid.nonTransactionalSaveHint",
@@ -20,12 +17,7 @@ export interface DataGridSaveToolbarState {
actionsDisabled: boolean;
}
-export function dataGridSaveToolbarState(options: {
- editable: boolean;
- hasSaveTarget: boolean;
- hasPendingChanges: boolean;
- isSaving: boolean;
-}): DataGridSaveToolbarState {
+export function dataGridSaveToolbarState(options: { editable: boolean; hasSaveTarget: boolean; hasPendingChanges: boolean; isSaving: boolean }): DataGridSaveToolbarState {
const showActions = options.editable && options.hasSaveTarget;
return {
showActions,
diff --git a/apps/desktop/src/lib/dataGridSearchSplit.ts b/apps/desktop/src/lib/dataGridSearchSplit.ts
index 3236eaa5ef..c5ccf42746 100644
--- a/apps/desktop/src/lib/dataGridSearchSplit.ts
+++ b/apps/desktop/src/lib/dataGridSearchSplit.ts
@@ -1,13 +1,7 @@
export const DEFAULT_SEARCH_SPLIT_RATIO = 0.5;
export const MIN_SEARCH_SPLIT_PANE_WIDTH = 180;
-export function clampSearchSplitWidth({
- containerWidth,
- desiredWidth,
-}: {
- containerWidth: number;
- desiredWidth?: number;
-}): number {
+export function clampSearchSplitWidth({ containerWidth, desiredWidth }: { containerWidth: number; desiredWidth?: number }): number {
const fallback = containerWidth * DEFAULT_SEARCH_SPLIT_RATIO;
if (containerWidth <= MIN_SEARCH_SPLIT_PANE_WIDTH * 2) return fallback;
diff --git a/apps/desktop/src/lib/dataGridSort.ts b/apps/desktop/src/lib/dataGridSort.ts
index 6140b0da5b..2a3890521c 100644
--- a/apps/desktop/src/lib/dataGridSort.ts
+++ b/apps/desktop/src/lib/dataGridSort.ts
@@ -6,11 +6,7 @@ export interface DataGridSortState {
direction: DataGridSortDirection;
}
-export function nextDataGridSortState(
- current: DataGridSortState,
- column: string,
- columnIndex: number,
-): DataGridSortState {
+export function nextDataGridSortState(current: DataGridSortState, column: string, columnIndex: number): DataGridSortState {
if (current.column === column && current.columnIndex === columnIndex) {
if (current.direction === "asc") {
return { column, columnIndex, direction: "desc" };
diff --git a/apps/desktop/src/lib/dataGridSql.ts b/apps/desktop/src/lib/dataGridSql.ts
index 52545e3a93..cf66ac3248 100644
--- a/apps/desktop/src/lib/dataGridSql.ts
+++ b/apps/desktop/src/lib/dataGridSql.ts
@@ -47,15 +47,7 @@ export interface DataGridCopyInsertStatementOptions {
excludePrimaryKeys?: boolean;
}
-export type DataGridContextFilterMode =
- | "equals"
- | "not-equals"
- | "is-null"
- | "is-not-null"
- | "like"
- | "not-like"
- | "less-than"
- | "greater-than";
+export type DataGridContextFilterMode = "equals" | "not-equals" | "is-null" | "is-not-null" | "like" | "not-like" | "less-than" | "greater-than";
export interface DataGridContextFilterConditionOptions {
databaseType?: DatabaseType;
@@ -89,21 +81,15 @@ export function buildDataGridCopyUpdateStatements(options: DataGridCopyUpdateSta
return api.buildDataGridCopyUpdateStatements(options);
}
-export function buildDataGridCopyInsertStatement(
- options: DataGridCopyInsertStatementOptions,
-): Promise<string | undefined> {
+export function buildDataGridCopyInsertStatement(options: DataGridCopyInsertStatementOptions): Promise<string | undefined> {
return api.buildDataGridCopyInsertStatement(options);
}
-export function buildDataGridContextFilterCondition(
- options: DataGridContextFilterConditionOptions,
-): Promise<string | undefined> {
+export function buildDataGridContextFilterCondition(options: DataGridContextFilterConditionOptions): Promise<string | undefined> {
return api.buildDataGridContextFilterCondition(options);
}
-export function buildDataGridColumnValueFilterCondition(
- options: DataGridColumnValueFilterConditionOptions,
-): Promise<string | undefined> {
+export function buildDataGridColumnValueFilterCondition(options: DataGridColumnValueFilterConditionOptions): Promise<string | undefined> {
return api.buildDataGridColumnValueFilterCondition(options);
}
diff --git a/apps/desktop/src/lib/dataGridTemporalEditor.ts b/apps/desktop/src/lib/dataGridTemporalEditor.ts
index 9c1e7206d2..4428e5c1b3 100644
--- a/apps/desktop/src/lib/dataGridTemporalEditor.ts
+++ b/apps/desktop/src/lib/dataGridTemporalEditor.ts
@@ -2,10 +2,7 @@ import type { DatabaseType } from "@/types/database";
export type TemporalCellEditorKind = "date" | "time" | "datetime";
-export function temporalCellEditorKind(
- dataType: string | undefined,
- _databaseType?: DatabaseType,
-): TemporalCellEditorKind | undefined {
+export function temporalCellEditorKind(dataType: string | undefined, _databaseType?: DatabaseType): TemporalCellEditorKind | undefined {
const normalized = normalizeTemporalType(dataType);
if (!normalized) return undefined;
if (/\b(?:datetime|datetime2|datetime64|smalldatetime|datetimeoffset|timestamp|timestamptz)\b/.test(normalized)) {
@@ -16,10 +13,7 @@ export function temporalCellEditorKind(
return undefined;
}
-export function formatTemporalInputValue(
- value: string | number | boolean | null,
- kind: TemporalCellEditorKind,
-): string {
+export function formatTemporalInputValue(value: string | number | boolean | null, kind: TemporalCellEditorKind): string {
if (value === null || value === undefined) return "";
const text = String(value).trim();
if (!text) return "";
diff --git a/apps/desktop/src/lib/dataGridTranspose.ts b/apps/desktop/src/lib/dataGridTranspose.ts
index e4d838b87b..8430fe6c0a 100644
--- a/apps/desktop/src/lib/dataGridTranspose.ts
+++ b/apps/desktop/src/lib/dataGridTranspose.ts
@@ -99,11 +99,7 @@ export interface TransposeRecordIndexesForModeOptions {
visibleRecordIndexes: number[];
}
-export function nextTransposeState(
- showTranspose: boolean,
- transposeRowIndex: number | null,
- requestedRowIndex: number,
-): DataGridTransposeState {
+export function nextTransposeState(showTranspose: boolean, transposeRowIndex: number | null, requestedRowIndex: number): DataGridTransposeState {
if (showTranspose && transposeRowIndex === requestedRowIndex) {
return { showTranspose: false, transposeRowIndex: null };
}
@@ -128,11 +124,7 @@ export function nextAppendedTransposeState(showTranspose: boolean, totalRecords:
return { showTranspose: true, transposeRowIndex: totalRecords - 1 };
}
-export function nextTransposeStateForRecordCount(
- showTranspose: boolean,
- transposeRowIndex: number | null,
- totalRecords: number,
-): DataGridTransposeState {
+export function nextTransposeStateForRecordCount(showTranspose: boolean, transposeRowIndex: number | null, totalRecords: number): DataGridTransposeState {
if (!showTranspose || totalRecords <= 0) return { showTranspose: false, transposeRowIndex: null };
const requestedRowIndex = transposeRowIndex ?? 0;
return {
@@ -159,9 +151,7 @@ export function buildTransposeRows<T>(options: BuildTransposeRowsOptions<T>): Ar
});
}
-export function buildVisibleTransposeRows<T>(
- options: BuildVisibleTransposeRowsOptions<T>,
-): Array<DataGridVisibleTransposeRow<T>> {
+export function buildVisibleTransposeRows<T>(options: BuildVisibleTransposeRowsOptions<T>): Array<DataGridVisibleTransposeRow<T>> {
return options.columns.map((column, columnIndex) => {
return {
id: `${columnIndex}:${column}`,
@@ -195,10 +185,7 @@ export function visibleTransposeRecordWindow(options: TransposeRecordWindowOptio
const recordScrollLeft = Math.max(0, options.scrollLeft - options.pinnedWidth);
const recordViewportWidth = Math.max(0, options.viewportWidth - options.pinnedWidth);
const start = Math.max(0, Math.floor(recordScrollLeft / options.recordWidth) - overscan);
- const end = Math.min(
- options.totalRecords,
- Math.ceil((recordScrollLeft + recordViewportWidth) / options.recordWidth) + overscan + 1,
- );
+ const end = Math.min(options.totalRecords, Math.ceil((recordScrollLeft + recordViewportWidth) / options.recordWidth) + overscan + 1);
return {
start,
@@ -223,12 +210,7 @@ export function transposeAnchorRowIndex(options: TransposeAnchorOptions): number
}
const range = options.selectedRange;
- if (
- range &&
- range.startRow !== range.endRow &&
- options.requestedRowIndex >= range.startRow &&
- options.requestedRowIndex <= range.endRow
- ) {
+ if (range && range.startRow !== range.endRow && options.requestedRowIndex >= range.startRow && options.requestedRowIndex <= range.endRow) {
return range.startRow;
}
diff --git a/apps/desktop/src/lib/databaseCapabilitySets.ts b/apps/desktop/src/lib/databaseCapabilitySets.ts
index 6257fec308..245487835b 100644
--- a/apps/desktop/src/lib/databaseCapabilitySets.ts
+++ b/apps/desktop/src/lib/databaseCapabilitySets.ts
@@ -115,29 +115,7 @@ export const DATABASE_SEARCH_SUPPORTED_TYPES = new Set<DatabaseType>([
"iris",
]);
-export const TABLE_IMPORT_SUPPORTED_TYPES = new Set<DatabaseType>([
- "mysql",
- "postgres",
- "sqlite",
- "rqlite",
- "turso",
- "duckdb",
- "clickhouse",
- "sqlserver",
- "oracle",
- "doris",
- "starrocks",
- "redshift",
- "dameng",
- "gaussdb",
- "kwdb",
- "kingbase",
- "highgo",
- "vastbase",
- "goldendb",
- "yashandb",
- "access",
-]);
+export const TABLE_IMPORT_SUPPORTED_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlite", "rqlite", "turso", "duckdb", "clickhouse", "sqlserver", "oracle", "doris", "starrocks", "redshift", "dameng", "gaussdb", "kwdb", "kingbase", "highgo", "vastbase", "goldendb", "yashandb", "access"]);
export const TABLE_STRUCTURE_SUPPORTED_TYPES = new Set<DatabaseType>([
"mysql",
@@ -167,44 +145,11 @@ export const TABLE_STRUCTURE_SUPPORTED_TYPES = new Set<DatabaseType>([
"access",
]);
-export const CREATE_DATABASE_SUPPORTED_TYPES = new Set<DatabaseType>([
- "mysql",
- "postgres",
- "sqlserver",
- "clickhouse",
- "oracle",
- "gaussdb",
- "kwdb",
- "opengauss",
- "oceanbase-oracle",
- "doris",
- "starrocks",
- "redshift",
-]);
+export const CREATE_DATABASE_SUPPORTED_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlserver", "clickhouse", "oracle", "gaussdb", "kwdb", "opengauss", "oceanbase-oracle", "doris", "starrocks", "redshift"]);
-export const FIELD_LINEAGE_SUPPORTED_TYPES = new Set<DatabaseType>([
- "mysql",
- "postgres",
- "sqlite",
- "rqlite",
- "turso",
- "sqlserver",
- "oracle",
- "redshift",
- "dameng",
- "gaussdb",
- "kwdb",
- "opengauss",
- "oceanbase-oracle",
-]);
+export const FIELD_LINEAGE_SUPPORTED_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlite", "rqlite", "turso", "sqlserver", "oracle", "redshift", "dameng", "gaussdb", "kwdb", "opengauss", "oceanbase-oracle"]);
-export const SINGLE_DATABASE_TYPES = new Set<DatabaseType>([
- "oracle",
- "dameng",
- "firebird",
- "oceanbase-oracle",
- "access",
-]);
+export const SINGLE_DATABASE_TYPES = new Set<DatabaseType>(["oracle", "dameng", "firebird", "oceanbase-oracle", "access"]);
export const FETCH_FIRST_TYPES = new Set<DatabaseType>(["oracle", "dameng"]);
@@ -279,37 +224,6 @@ export const AGENT_DRIVER_TYPES = new Set<DatabaseType>([
"etcd",
]);
-export const TRANSFER_SQL_TYPES = new Set<DatabaseType>([
- "mysql",
- "postgres",
- "sqlite",
- "rqlite",
- "turso",
- "sqlserver",
- "oracle",
- "clickhouse",
- "duckdb",
- "hive",
- "mongodb",
- "dameng",
- "gaussdb",
- "kwdb",
- "opengauss",
- "oceanbase-oracle",
-]);
+export const TRANSFER_SQL_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlite", "rqlite", "turso", "sqlserver", "oracle", "clickhouse", "duckdb", "hive", "mongodb", "dameng", "gaussdb", "kwdb", "opengauss", "oceanbase-oracle"]);
-export const DIAGRAM_SQL_TYPES = new Set<DatabaseType>([
- "mysql",
- "postgres",
- "sqlite",
- "rqlite",
- "turso",
- "sqlserver",
- "oracle",
- "redshift",
- "dameng",
- "gaussdb",
- "kwdb",
- "opengauss",
- "oceanbase-oracle",
-]);
+export const DIAGRAM_SQL_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlite", "rqlite", "turso", "sqlserver", "oracle", "redshift", "dameng", "gaussdb", "kwdb", "opengauss", "oceanbase-oracle"]);
diff --git a/apps/desktop/src/lib/databaseFeatureSupport.ts b/apps/desktop/src/lib/databaseFeatureSupport.ts
index 6bac2ba6a7..23d6233c24 100644
--- a/apps/desktop/src/lib/databaseFeatureSupport.ts
+++ b/apps/desktop/src/lib/databaseFeatureSupport.ts
@@ -29,20 +29,12 @@ export function usesDatabaseObjectTreeMode(dbType?: DatabaseType): boolean {
return !!dbType && DATABASE_OBJECT_TREE_TYPES.has(dbType);
}
-export function databaseObjectTreeQuerySchema(
- dbType: DatabaseType | undefined,
- database: string,
- schema?: string,
-): string {
+export function databaseObjectTreeQuerySchema(dbType: DatabaseType | undefined, database: string, schema?: string): string {
if (usesDatabaseObjectTreeMode(dbType)) return "";
return schema || database;
}
-export function databaseObjectTreeNodeSchema(
- dbType: DatabaseType | undefined,
- database: string,
- schema?: string,
-): string | undefined {
+export function databaseObjectTreeNodeSchema(dbType: DatabaseType | undefined, database: string, schema?: string): string | undefined {
if (usesDatabaseObjectTreeMode(dbType)) return undefined;
if (schema) return schema;
return isSchemaAware(dbType) ? database : undefined;
diff --git a/apps/desktop/src/lib/databaseObjectCapabilities.ts b/apps/desktop/src/lib/databaseObjectCapabilities.ts
index 18734a7e04..4551408bd4 100644
--- a/apps/desktop/src/lib/databaseObjectCapabilities.ts
+++ b/apps/desktop/src/lib/databaseObjectCapabilities.ts
@@ -13,24 +13,7 @@ const ROUTINE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUN
const POSTGRES_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE"];
const ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"];
-const TABLE_VIEW_ONLY_TYPES = new Set<DatabaseType>([
- "sqlite",
- "rqlite",
- "turso",
- "duckdb",
- "clickhouse",
- "doris",
- "starrocks",
- "databend",
- "hive",
- "trino",
- "cassandra",
- "bigquery",
- "kylin",
- "tdengine",
- "iotdb",
- "neo4j",
-]);
+const TABLE_VIEW_ONLY_TYPES = new Set<DatabaseType>(["sqlite", "rqlite", "turso", "duckdb", "clickhouse", "doris", "starrocks", "databend", "hive", "trino", "cassandra", "bigquery", "kylin", "tdengine", "iotdb", "neo4j"]);
const ORACLE_PACKAGE_TYPES = new Set<DatabaseType>(["oracle", "oceanbase-oracle"]);
const POSTGRES_SEQUENCE_TYPES = new Set<DatabaseType>(["postgres", "gaussdb", "kwdb", "opengauss"]);
diff --git a/apps/desktop/src/lib/databaseOptionSearch.ts b/apps/desktop/src/lib/databaseOptionSearch.ts
index d7bb0247d1..93ac176e77 100644
--- a/apps/desktop/src/lib/databaseOptionSearch.ts
+++ b/apps/desktop/src/lib/databaseOptionSearch.ts
@@ -1,8 +1,4 @@
-export function filterDatabaseOptions(
- options: string[],
- query: string,
- displayName: (option: string) => string = (option) => option,
-): string[] {
+export function filterDatabaseOptions(options: string[], query: string, displayName: (option: string) => string = (option) => option): string[] {
const normalizedQuery = query.trim().toLowerCase();
if (!normalizedQuery) return options;
diff --git a/apps/desktop/src/lib/databaseSearch.ts b/apps/desktop/src/lib/databaseSearch.ts
index e812acb3f4..bf5b9d7f5d 100644
--- a/apps/desktop/src/lib/databaseSearch.ts
+++ b/apps/desktop/src/lib/databaseSearch.ts
@@ -63,12 +63,7 @@ function columnByName(columns: ColumnInfo[], name: string): ColumnInfo | undefin
return columns.find((column) => column.name.toLowerCase() === name.toLowerCase());
}
-export function findMatchedSearchColumns(
- resultColumns: string[],
- row: unknown[],
- columns: ColumnInfo[],
- term: string,
-): string[] {
+export function findMatchedSearchColumns(resultColumns: string[], row: unknown[], columns: ColumnInfo[], term: string): string[] {
const query = cleanTerm(term).toLowerCase();
const numericTerm = parseNumericTerm(term);
if (!query) return [];
diff --git a/apps/desktop/src/lib/databaseTree.ts b/apps/desktop/src/lib/databaseTree.ts
index a0dc5edbf6..feb9bc1ec5 100644
--- a/apps/desktop/src/lib/databaseTree.ts
+++ b/apps/desktop/src/lib/databaseTree.ts
@@ -3,10 +3,7 @@ import { DEFAULT_DATABASE_TREE_LABEL } from "./treeNodeContext";
const sidebarNameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
-export function shouldIncludeDefaultDatabaseNode(
- connection: Pick<ConnectionConfig, "db_type"> | undefined,
- databases: DatabaseInfo[],
-): boolean {
+export function shouldIncludeDefaultDatabaseNode(connection: Pick<ConnectionConfig, "db_type"> | undefined, databases: DatabaseInfo[]): boolean {
return connection?.db_type === "mysql" && databases.some((database) => !database.name.trim());
}
@@ -18,11 +15,7 @@ export function sortSidebarDatabases(databases: readonly DatabaseInfo[]): Databa
return [...databases].sort((left, right) => sidebarNameCollator.compare(left.name, right.name));
}
-export function buildDatabaseTreeNodes(
- connectionId: string,
- databases: DatabaseInfo[],
- options: { includeDefaultWhenEmpty?: boolean } = {},
-): TreeNode[] {
+export function buildDatabaseTreeNodes(connectionId: string, databases: DatabaseInfo[], options: { includeDefaultWhenEmpty?: boolean } = {}): TreeNode[] {
const nodes = sortSidebarDatabases(databases).flatMap((db) => {
const name = db.name.trim();
if (!name) return [];
@@ -54,11 +47,7 @@ export function buildDatabaseTreeNodes(
];
}
-export function buildDuckDbConnectionTreeNodes(
- connectionId: string,
- databases: DatabaseInfo[],
- primarySchemas: string[],
-): TreeNode[] {
+export function buildDuckDbConnectionTreeNodes(connectionId: string, databases: DatabaseInfo[], primarySchemas: string[]): TreeNode[] {
const schemaNodes = sortSidebarNames(primarySchemas).flatMap((schema) => {
const name = schema.trim();
if (!name) return [];
diff --git a/apps/desktop/src/lib/databaseUserAdmin.ts b/apps/desktop/src/lib/databaseUserAdmin.ts
index 6cbf91f903..572c1a6335 100644
--- a/apps/desktop/src/lib/databaseUserAdmin.ts
+++ b/apps/desktop/src/lib/databaseUserAdmin.ts
@@ -45,44 +45,13 @@ export interface DatabaseUserAdminProvider {
}
export const MYSQL_USER_ADMIN_TYPES = new Set<DatabaseType>(["mysql", "goldendb"]);
-export const POSTGRES_USER_ADMIN_TYPES = new Set<DatabaseType>([
- "postgres",
- "gaussdb",
- "highgo",
- "kingbase",
- "kwdb",
- "opengauss",
- "vastbase",
-]);
-
-export const MYSQL_COMMON_PRIVILEGES = [
- "SELECT",
- "INSERT",
- "UPDATE",
- "DELETE",
- "CREATE",
- "DROP",
- "ALTER",
- "INDEX",
- "REFERENCES",
- "EXECUTE",
- "SHOW VIEW",
- "TRIGGER",
- "EVENT",
- "CREATE TEMPORARY TABLES",
-] as const;
+export const POSTGRES_USER_ADMIN_TYPES = new Set<DatabaseType>(["postgres", "gaussdb", "highgo", "kingbase", "kwdb", "opengauss", "vastbase"]);
+
+export const MYSQL_COMMON_PRIVILEGES = ["SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER", "INDEX", "REFERENCES", "EXECUTE", "SHOW VIEW", "TRIGGER", "EVENT", "CREATE TEMPORARY TABLES"] as const;
export const POSTGRES_DATABASE_PRIVILEGES = ["CONNECT", "CREATE", "TEMPORARY"] as const;
export const POSTGRES_SCHEMA_PRIVILEGES = ["USAGE", "CREATE"] as const;
-export const POSTGRES_TABLE_PRIVILEGES = [
- "SELECT",
- "INSERT",
- "UPDATE",
- "DELETE",
- "TRUNCATE",
- "REFERENCES",
- "TRIGGER",
-] as const;
+export const POSTGRES_TABLE_PRIVILEGES = ["SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER"] as const;
export function supportsDatabaseUserAdmin(dbType: DatabaseType | undefined): boolean {
return !!getDatabaseUserAdminProvider(dbType);
@@ -162,16 +131,12 @@ export function mysqlPrivilegeTargetSql(database: string, table = "*"): string {
export function mysqlGrantPrivilegesSql(input: PrivilegeChangeInput): string {
const privileges = normalizePrivileges(input.privileges).join(", ");
const grantOption = input.grantOption ? " WITH GRANT OPTION" : "";
- return `GRANT ${privileges} ON ${mysqlPrivilegeTargetSql(input.database, input.table)} TO ${mysqlUserAccount(
- input.user,
- )}${grantOption};`;
+ return `GRANT ${privileges} ON ${mysqlPrivilegeTargetSql(input.database, input.table)} TO ${mysqlUserAccount(input.user)}${grantOption};`;
}
export function mysqlRevokePrivilegesSql(input: PrivilegeChangeInput): string {
const privileges = normalizePrivileges(input.privileges).join(", ");
- return `REVOKE ${privileges} ON ${mysqlPrivilegeTargetSql(input.database, input.table)} FROM ${mysqlUserAccount(
- input.user,
- )};`;
+ return `REVOKE ${privileges} ON ${mysqlPrivilegeTargetSql(input.database, input.table)} FROM ${mysqlUserAccount(input.user)};`;
}
export function normalizePrivileges(privileges: string[], fallback = "SELECT"): string[] {
@@ -319,14 +284,10 @@ export function postgresPrivilegeTargetSql(input: Pick<PrivilegeChangeInput, "sc
export function postgresGrantPrivilegesSql(input: PrivilegeChangeInput): string {
if (input.scope === "role") {
- return `GRANT ${quotePostgresIdentifier(input.role?.trim() || "")} TO ${quotePostgresIdentifier(input.user.user)}${
- input.grantOption ? " WITH ADMIN OPTION" : ""
- };`;
+ return `GRANT ${quotePostgresIdentifier(input.role?.trim() || "")} TO ${quotePostgresIdentifier(input.user.user)}${input.grantOption ? " WITH ADMIN OPTION" : ""};`;
}
const privileges = normalizePrivileges(input.privileges, postgresDefaultPrivilege(input.scope)).join(", ");
- return `GRANT ${privileges} ON ${postgresPrivilegeTargetSql(input)} TO ${quotePostgresIdentifier(input.user.user)}${
- input.grantOption ? " WITH GRANT OPTION" : ""
- };`;
+ return `GRANT ${privileges} ON ${postgresPrivilegeTargetSql(input)} TO ${quotePostgresIdentifier(input.user.user)}${input.grantOption ? " WITH GRANT OPTION" : ""};`;
}
export function postgresRevokePrivilegesSql(input: PrivilegeChangeInput): string {
diff --git a/apps/desktop/src/lib/datagripImport.ts b/apps/desktop/src/lib/datagripImport.ts
index 273e5ddbf0..6a59e965f6 100644
--- a/apps/desktop/src/lib/datagripImport.ts
+++ b/apps/desktop/src/lib/datagripImport.ts
@@ -107,10 +107,7 @@ function getText(element: Element, tagName: string): string {
function expandPathMacros(value: string): string {
if (typeof window !== "undefined") {
- const home =
- (typeof process !== "undefined" && process.env?.HOME) ||
- (typeof process !== "undefined" && process.env?.USERPROFILE) ||
- "";
+ const home = (typeof process !== "undefined" && process.env?.HOME) || (typeof process !== "undefined" && process.env?.USERPROFILE) || "";
if (home) return value.replace(/\$USER_HOME\$/g, home);
}
return value.replace(/\$USER_HOME\$/g, "~");
@@ -325,10 +322,7 @@ function parseDataSourcesLocalXml(xml: string): Map<string, Partial<DataSourceFr
return result;
}
-function mergeFragments(
- shared: Map<string, Partial<DataSourceFragment>>,
- local: Map<string, Partial<DataSourceFragment>>,
-): DataSourceFragment[] {
+function mergeFragments(shared: Map<string, Partial<DataSourceFragment>>, local: Map<string, Partial<DataSourceFragment>>): DataSourceFragment[] {
const merged = new Map<string, Partial<DataSourceFragment>>();
// Shared first (has driver-ref, jdbc-url, group-name)
@@ -399,8 +393,7 @@ function buildConnection(fragment: DataSourceFragment): ConnectionConfig {
query_timeout_secs: 30,
ssl: false,
oracle_connection_type: profile.dbType === "oracle" ? parsed.oracleConnectionType || "service_name" : undefined,
- connection_string:
- profile.dbType === "jdbc" || profile.dbType === "mongodb" ? fragment.jdbcUrl.replace(/^jdbc:/i, "") : undefined,
+ connection_string: profile.dbType === "jdbc" || profile.dbType === "mongodb" ? fragment.jdbcUrl.replace(/^jdbc:/i, "") : undefined,
jdbc_driver_class: profile.dbType === "jdbc" ? fragment.driverClass || undefined : undefined,
jdbc_driver_paths: [],
};
@@ -448,12 +441,7 @@ export function getDataGripUuidMap(payload: DataGripImportPayload): Map<string,
const seen = new Set<string>();
for (const fragment of fragments) {
- const profile = inferProfile(
- fragment.driverRef,
- extractSubprotocol(fragment.jdbcUrl),
- fragment.driverClass,
- fragment.product,
- );
+ const profile = inferProfile(fragment.driverRef, extractSubprotocol(fragment.jdbcUrl), fragment.driverClass, fragment.product);
const parsed = parseJdbcUrl(fragment.jdbcUrl);
const host = parsed.host || (profile.dbType === "sqlite" ? "" : "127.0.0.1");
const port = parsed.port || profile.port;
diff --git a/apps/desktop/src/lib/dbeaverImport.ts b/apps/desktop/src/lib/dbeaverImport.ts
index 2f84cd66b3..8baf339fe4 100644
--- a/apps/desktop/src/lib/dbeaverImport.ts
+++ b/apps/desktop/src/lib/dbeaverImport.ts
@@ -82,9 +82,7 @@ function base64ToBytes(value: string) {
return bytes;
}
-async function decryptCredentialsFile(
- base64?: string,
-): Promise<Record<string, Record<string, Record<string, string>>>> {
+async function decryptCredentialsFile(base64?: string): Promise<Record<string, Record<string, Record<string, string>>>> {
if (!base64) return {};
const bytes = base64ToBytes(base64);
if (bytes.length <= 16) return {};
@@ -100,10 +98,7 @@ async function decryptCredentialsFile(
}
}
-function readCredentials(
- entry: DbeaverConnectionEntry,
- credentials: Record<string, Record<string, Record<string, string>>>,
-) {
+function readCredentials(entry: DbeaverConnectionEntry, credentials: Record<string, Record<string, Record<string, string>>>) {
const secure = credentials[entry.id]?.["#connection"] || {};
const inline = entry.configuration?.credentials || {};
return {
@@ -185,9 +180,7 @@ function extractConnections(parsed: any): DbeaverConnectionEntry[] {
if (!source || typeof source !== "object") return [];
if (Array.isArray(source)) {
- return source
- .filter((entry) => entry && typeof entry === "object")
- .map((entry) => ({ ...entry, id: getString(entry.id || entry.uuid || entry.name) }));
+ return source.filter((entry) => entry && typeof entry === "object").map((entry) => ({ ...entry, id: getString(entry.id || entry.uuid || entry.name) }));
}
return Object.entries(source)
@@ -195,17 +188,12 @@ function extractConnections(parsed: any): DbeaverConnectionEntry[] {
.map(([id, entry]) => ({ ...(entry as Record<string, any>), id: getString((entry as any).id || id) }));
}
-function buildConnection(
- entry: DbeaverConnectionEntry,
- credentials: ReturnType<typeof readCredentials>,
-): ConnectionConfig | null {
+function buildConnection(entry: DbeaverConnectionEntry, credentials: ReturnType<typeof readCredentials>): ConnectionConfig | null {
const profile = inferProfile(entry);
const config = entry.configuration || {};
const url = getString(config.url);
const parsedUrl = parseJdbcUrl(url, profile);
- const host = getString(
- config.host || config["host-name"] || parsedUrl.host || (profile.dbType === "sqlite" ? "" : "127.0.0.1"),
- );
+ const host = getString(config.host || config["host-name"] || parsedUrl.host || (profile.dbType === "sqlite" ? "" : "127.0.0.1"));
const database = getString(config.database || config["database-name"] || config.schema || parsedUrl.database);
const name = getString(entry.name || database || host || profile.label);
if (!entry.id || !name) return null;
@@ -228,8 +216,7 @@ function buildConnection(
ssl: false,
oracle_connection_type: profile.dbType === "oracle" ? parsedUrl.oracleConnectionType || "service_name" : undefined,
connection_string: profile.dbType === "jdbc" || profile.dbType === "mongodb" ? url || undefined : undefined,
- jdbc_driver_class:
- profile.dbType === "jdbc" ? getString(config["driver-class"] || entry.driver) || undefined : undefined,
+ jdbc_driver_class: profile.dbType === "jdbc" ? getString(config["driver-class"] || entry.driver) || undefined : undefined,
jdbc_driver_paths: [],
};
diff --git a/apps/desktop/src/lib/debugLog.ts b/apps/desktop/src/lib/debugLog.ts
index dbfe6074c3..76ba18126a 100644
--- a/apps/desktop/src/lib/debugLog.ts
+++ b/apps/desktop/src/lib/debugLog.ts
@@ -53,12 +53,7 @@ function readEntries(): DebugLogEntry[] {
}
function redactSensitiveText(value: string): string {
- return value
- .replace(
- /("(?:password|passphrase|apiKey|api_key|token|secret|connectionString|connection_string)"\s*:\s*")([^"]*)(")/gi,
- "$1[redacted]$3",
- )
- .replace(/\b(password|passphrase|apiKey|api_key|token|secret)=([^&\s]+)/gi, "$1=[redacted]");
+ return value.replace(/("(?:password|passphrase|apiKey|api_key|token|secret|connectionString|connection_string)"\s*:\s*")([^"]*)(")/gi, "$1[redacted]$3").replace(/\b(password|passphrase|apiKey|api_key|token|secret)=([^&\s]+)/gi, "$1=[redacted]");
}
function formatValue(value: unknown, seen = new WeakSet<object>()): string {
@@ -116,14 +111,7 @@ export function clearDebugLogs() {
export function getDebugLogText(): string {
const entries = readEntries();
- const header = [
- `DBX debug log`,
- `Exported: ${new Date().toISOString()}`,
- `User agent: ${navigator.userAgent}`,
- `Platform: ${navigator.platform}`,
- `Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown"}`,
- "",
- ];
+ const header = [`DBX debug log`, `Exported: ${new Date().toISOString()}`, `User agent: ${navigator.userAgent}`, `Platform: ${navigator.platform}`, `Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown"}`, ""];
const body = entries.map((entry) => `[${entry.timestamp}] [${entry.level.toUpperCase()}] ${entry.message}`);
return [...header, ...body].join("\n");
}
@@ -132,10 +120,7 @@ export async function downloadDebugLogs() {
const text = await getDebugLogBundleText();
const filename = `dbx-debug-log-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`;
if (typeof window !== "undefined" && isTauriRuntimeLike()) {
- const [{ save }, { writeTextFile }] = await Promise.all([
- import("@tauri-apps/plugin-dialog"),
- import("@tauri-apps/plugin-fs"),
- ]);
+ const [{ save }, { writeTextFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
const path = await save({
defaultPath: filename,
filters: [{ name: "Text", extensions: ["txt", "log"] }],
@@ -249,37 +234,15 @@ function installPerformanceCapture() {
}
function interactiveElement(target: HTMLElement): HTMLElement | null {
- return target.closest(
- [
- "button",
- "a[href]",
- "input",
- "select",
- "textarea",
- "[role='button']",
- "[role='menuitem']",
- "[role='tab']",
- "[data-debug-id]",
- ].join(","),
- );
+ return target.closest(["button", "a[href]", "input", "select", "textarea", "[role='button']", "[role='menuitem']", "[role='tab']", "[data-debug-id]"].join(","));
}
function isFormControl(target: HTMLElement): boolean {
- return (
- target instanceof HTMLInputElement ||
- target instanceof HTMLSelectElement ||
- target instanceof HTMLTextAreaElement ||
- target.getAttribute("role") === "switch"
- );
+ return target instanceof HTMLInputElement || target instanceof HTMLSelectElement || target instanceof HTMLTextAreaElement || target.getAttribute("role") === "switch";
}
function describeElement(element: HTMLElement): Record<string, string> {
- const label =
- element.getAttribute("data-debug-id") ||
- element.getAttribute("aria-label") ||
- element.getAttribute("title") ||
- element.textContent ||
- "";
+ const label = element.getAttribute("data-debug-id") || element.getAttribute("aria-label") || element.getAttribute("title") || element.textContent || "";
const attrs: Record<string, string> = {
tag: element.tagName.toLowerCase(),
};
diff --git a/apps/desktop/src/lib/defaultDatabase.ts b/apps/desktop/src/lib/defaultDatabase.ts
index 18891d184c..ef081898e3 100644
--- a/apps/desktop/src/lib/defaultDatabase.ts
+++ b/apps/desktop/src/lib/defaultDatabase.ts
@@ -19,19 +19,12 @@ export function decodeSelectableDatabaseValue(dbType: DatabaseType | undefined,
return value === TREE_SCHEMA_DEFAULT_DATABASE_SELECT_VALUE && usesTreeSchemaMode(dbType) ? "" : value;
}
-export function formatDatabaseLabel(
- connection: Pick<ConnectionConfig, "db_type"> | undefined,
- database: string,
- labels: { defaultDatabase: string; noDatabase: string },
-): string {
+export function formatDatabaseLabel(connection: Pick<ConnectionConfig, "db_type"> | undefined, database: string, labels: { defaultDatabase: string; noDatabase: string }): string {
if (connection?.db_type === "redis" && database !== "") return `db${database}`;
if (isTreeSchemaDefaultDatabase(connection?.db_type, database)) return labels.defaultDatabase;
return database || labels.noDatabase;
}
-export function isDefaultDatabase(
- connection: Pick<ConnectionConfig, "database"> | undefined,
- database: string,
-): boolean {
+export function isDefaultDatabase(connection: Pick<ConnectionConfig, "database"> | undefined, database: string): boolean {
return !!connection?.database && !!database && connection.database === database;
}
diff --git a/apps/desktop/src/lib/diagramSvgExport.ts b/apps/desktop/src/lib/diagramSvgExport.ts
index 339b420abb..e0979b74c7 100644
--- a/apps/desktop/src/lib/diagramSvgExport.ts
+++ b/apps/desktop/src/lib/diagramSvgExport.ts
@@ -23,12 +23,7 @@ export interface TableDiagramSvgOptions {
}
function escapeXml(value: string | number): string {
- return String(value)
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/"/g, "&quot;")
- .replace(/'/g, "&apos;");
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
function svgNumber(value: number): string {
@@ -36,10 +31,7 @@ function svgNumber(value: number): string {
}
function svgHeader(canvas: DiagramCanvas): string {
- return [
- `<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(canvas.width)}" height="${svgNumber(canvas.height)}" viewBox="0 0 ${svgNumber(canvas.width)} ${svgNumber(canvas.height)}">`,
- '<rect width="100%" height="100%" fill="#fafafa"/>',
- ].join("");
+ return [`<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(canvas.width)}" height="${svgNumber(canvas.height)}" viewBox="0 0 ${svgNumber(canvas.width)} ${svgNumber(canvas.height)}">`, '<rect width="100%" height="100%" fill="#fafafa"/>'].join("");
}
function svgText(
@@ -55,14 +47,7 @@ function svgText(
decoration?: string;
} = {},
): string {
- const attrs = [
- `x="${svgNumber(x)}"`,
- `y="${svgNumber(y)}"`,
- `fill="${options.fill ?? "#18181b"}"`,
- `font-size="${options.size ?? 12}"`,
- `font-family="${options.family ?? "Arial, Helvetica, sans-serif"}"`,
- 'dominant-baseline="middle"',
- ];
+ const attrs = [`x="${svgNumber(x)}"`, `y="${svgNumber(y)}"`, `fill="${options.fill ?? "#18181b"}"`, `font-size="${options.size ?? 12}"`, `font-family="${options.family ?? "Arial, Helvetica, sans-serif"}"`, 'dominant-baseline="middle"'];
if (options.weight) attrs.push(`font-weight="${options.weight}"`);
if (options.anchor) attrs.push(`text-anchor="${options.anchor}"`);
if (options.decoration) attrs.push(`text-decoration="${options.decoration}"`);
@@ -72,22 +57,11 @@ function svgText(
function tableHeight(table: DiagramTable, options: TableDiagramSvgOptions): number {
const visibleCount = Math.min(table.columns.length, options.maxVisibleColumns);
const overflowHeight = table.columns.length > options.maxVisibleColumns ? options.columnRowHeight : 0;
- return (
- options.cardHeaderHeight +
- visibleCount * options.columnRowHeight +
- overflowHeight +
- (options.cardBottomPadding ?? 12)
- );
+ return options.cardHeaderHeight + visibleCount * options.columnRowHeight + overflowHeight + (options.cardBottomPadding ?? 12);
}
function tableDiagramDefs(): string {
- return [
- "<defs>",
- '<marker id="dbx-diagram-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto" markerUnits="strokeWidth">',
- '<path d="M 0 0 L 8 4 L 0 8 z" fill="#2563eb"/>',
- "</marker>",
- "</defs>",
- ].join("");
+ return ["<defs>", '<marker id="dbx-diagram-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto" markerUnits="strokeWidth">', '<path d="M 0 0 L 8 4 L 0 8 z" fill="#2563eb"/>', "</marker>", "</defs>"].join("");
}
function isForeignKeyColumn(table: DiagramTable, columnName: string): boolean {
@@ -95,20 +69,12 @@ function isForeignKeyColumn(table: DiagramTable, columnName: string): boolean {
}
export function buildTableDiagramSvg(options: TableDiagramSvgOptions): string {
- const parts = [
- svgHeader(options.canvas),
- tableDiagramDefs(),
- '<g fill="none" stroke="#2563eb" stroke-opacity="0.58" stroke-width="1.6">',
- ];
+ const parts = [svgHeader(options.canvas), tableDiagramDefs(), '<g fill="none" stroke="#2563eb" stroke-opacity="0.58" stroke-width="1.6">'];
for (const relationship of options.relationships) {
const path = options.relationshipPaths[relationship.id];
if (!path) continue;
- parts.push(
- `<path d="${escapeXml(path)}" marker-end="url(#dbx-diagram-arrow)">` +
- `<title>${escapeXml(`${relationship.sourceTable}.${relationship.sourceColumn} -> ${relationship.targetTable}.${relationship.targetColumn}`)}</title>` +
- "</path>",
- );
+ parts.push(`<path d="${escapeXml(path)}" marker-end="url(#dbx-diagram-arrow)">` + `<title>${escapeXml(`${relationship.sourceTable}.${relationship.sourceColumn} -> ${relationship.targetTable}.${relationship.targetColumn}`)}</title>` + "</path>");
}
parts.push("</g>");
@@ -118,9 +84,7 @@ export function buildTableDiagramSvg(options: TableDiagramSvgOptions): string {
const visibleColumns = table.columns.slice(0, options.maxVisibleColumns);
const hiddenCount = Math.max(0, table.columns.length - options.maxVisibleColumns);
parts.push(`<g transform="translate(${svgNumber(position.x)} ${svgNumber(position.y)})">`);
- parts.push(
- `<rect width="${options.cardWidth}" height="${svgNumber(height)}" rx="6" fill="#ffffff" stroke="#d4d4d8"/>`,
- );
+ parts.push(`<rect width="${options.cardWidth}" height="${svgNumber(height)}" rx="6" fill="#ffffff" stroke="#d4d4d8"/>`);
parts.push(`<rect width="${options.cardWidth}" height="${options.cardHeaderHeight}" rx="6" fill="#f4f4f5"/>`);
parts.push(`<path d="M 0 ${options.cardHeaderHeight} H ${options.cardWidth}" stroke="#e4e4e7"/>`);
parts.push(svgText(table.name, 36, options.cardHeaderHeight / 2, { size: 13, weight: "600" }));
@@ -152,8 +116,7 @@ export function buildTableDiagramSvg(options: TableDiagramSvgOptions): string {
});
if (hiddenCount > 0) {
- const y =
- options.cardHeaderHeight + visibleColumns.length * options.columnRowHeight + options.columnRowHeight / 2;
+ const y = options.cardHeaderHeight + visibleColumns.length * options.columnRowHeight + options.columnRowHeight / 2;
parts.push(
svgText(options.moreColumnsLabel?.(hiddenCount) ?? `+ ${hiddenCount} columns`, 12, y, {
size: 11,
@@ -195,21 +158,15 @@ export function buildEngineeringDiagramSvg(diagram: EngineeringDiagram): string
const from = centers.get(attribute.tableName);
if (!from) continue;
const to = nodeCenter(attribute);
- parts.push(
- `<line x1="${svgNumber(from.x)}" y1="${svgNumber(from.y)}" x2="${svgNumber(to.x)}" y2="${svgNumber(to.y)}"/>`,
- );
+ parts.push(`<line x1="${svgNumber(from.x)}" y1="${svgNumber(from.y)}" x2="${svgNumber(to.x)}" y2="${svgNumber(to.y)}"/>`);
}
for (const relationship of diagram.relationships) {
const source = centers.get(relationship.sourceTable);
const target = centers.get(relationship.targetTable);
if (!source || !target) continue;
const middle = nodeCenter(relationship);
- parts.push(
- `<line x1="${svgNumber(source.x)}" y1="${svgNumber(source.y)}" x2="${svgNumber(middle.x)}" y2="${svgNumber(middle.y)}"/>`,
- );
- parts.push(
- `<line x1="${svgNumber(middle.x)}" y1="${svgNumber(middle.y)}" x2="${svgNumber(target.x)}" y2="${svgNumber(target.y)}"/>`,
- );
+ parts.push(`<line x1="${svgNumber(source.x)}" y1="${svgNumber(source.y)}" x2="${svgNumber(middle.x)}" y2="${svgNumber(middle.y)}"/>`);
+ parts.push(`<line x1="${svgNumber(middle.x)}" y1="${svgNumber(middle.y)}" x2="${svgNumber(target.x)}" y2="${svgNumber(target.y)}"/>`);
const sourceLabel = cardinalityPoint(middle, source);
const targetLabel = cardinalityPoint(middle, target);
parts.push(
@@ -230,10 +187,7 @@ export function buildEngineeringDiagramSvg(diagram: EngineeringDiagram): string
parts.push("</g>");
for (const attribute of diagram.attributes) {
- parts.push(
- `<ellipse cx="${svgNumber(attribute.x + attribute.width / 2)}" cy="${svgNumber(attribute.y + attribute.height / 2)}" ` +
- `rx="${svgNumber(attribute.width / 2)}" ry="${svgNumber(attribute.height / 2)}" fill="#dcfce7" stroke="#16a34a" stroke-opacity="0.65"/>`,
- );
+ parts.push(`<ellipse cx="${svgNumber(attribute.x + attribute.width / 2)}" cy="${svgNumber(attribute.y + attribute.height / 2)}" ` + `rx="${svgNumber(attribute.width / 2)}" ry="${svgNumber(attribute.height / 2)}" fill="#dcfce7" stroke="#16a34a" stroke-opacity="0.65"/>`);
parts.push(
svgText(attribute.label, attribute.x + attribute.width / 2, attribute.y + attribute.height / 2, {
size: 11,
@@ -268,9 +222,7 @@ export function buildEngineeringDiagramSvg(diagram: EngineeringDiagram): string
}
for (const entity of diagram.entities) {
- parts.push(
- `<rect x="${svgNumber(entity.x)}" y="${svgNumber(entity.y)}" width="${entity.width}" height="${entity.height}" fill="#dbeafe" stroke="#3b82f6" stroke-opacity="0.7"/>`,
- );
+ parts.push(`<rect x="${svgNumber(entity.x)}" y="${svgNumber(entity.y)}" width="${entity.width}" height="${entity.height}" fill="#dbeafe" stroke="#3b82f6" stroke-opacity="0.7"/>`);
parts.push(
svgText(entity.name, entity.x + entity.width / 2, entity.y + entity.height / 2, {
size: 13,
diff --git a/apps/desktop/src/lib/driverInstallProgressUi.ts b/apps/desktop/src/lib/driverInstallProgressUi.ts
index 0f5fe72523..827730d1a8 100644
--- a/apps/desktop/src/lib/driverInstallProgressUi.ts
+++ b/apps/desktop/src/lib/driverInstallProgressUi.ts
@@ -31,10 +31,7 @@ export function removeDriverInstallQueue(queue: string[], dbType: string): strin
return queue.filter((queuedDbType) => queuedDbType !== dbType);
}
-export function takeNextDriverInstallQueue(
- queue: string[],
- isInstallable: (dbType: string) => boolean,
-): { next: string | null; queue: string[] } {
+export function takeNextDriverInstallQueue(queue: string[], isInstallable: (dbType: string) => boolean): { next: string | null; queue: string[] } {
const remaining = [...queue];
while (remaining.length > 0) {
const next = remaining.shift() ?? null;
diff --git a/apps/desktop/src/lib/editorThemes.ts b/apps/desktop/src/lib/editorThemes.ts
index 25a7846e69..95d8f9ac96 100644
--- a/apps/desktop/src/lib/editorThemes.ts
+++ b/apps/desktop/src/lib/editorThemes.ts
@@ -11,12 +11,8 @@ export const EDITOR_FONT_SIZE_CSS_VAR = "--dbx-editor-font-size";
export const EDITOR_FONT_FAMILY_CSS_VAR = "--dbx-editor-font-family";
const EDITOR_SELECTION_BACKGROUND_CSS_VAR = "--dbx-editor-selection-background";
-const SUPPORTS_COLOR_MIX =
- typeof CSS !== "undefined" &&
- typeof CSS.supports === "function" &&
- CSS.supports("color", "color-mix(in oklch, black 50%, white)");
-const SUPPORTS_OKLCH =
- typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("color", "oklch(0.62 0.19 255)");
+const SUPPORTS_COLOR_MIX = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("color", "color-mix(in oklch, black 50%, white)");
+const SUPPORTS_OKLCH = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("color", "oklch(0.62 0.19 255)");
// ==================== 自定义主题配置 ====================
// 在这里修改你喜欢的颜色!
@@ -54,15 +50,9 @@ const customThemeColors = {
};
/** 创建自定义 CodeMirror 主题 */
-function createCustomTheme(
- EditorView: typeof import("@codemirror/view").EditorView,
- colors?: CustomThemeColors,
- isDark: boolean = true,
-): Extension {
+function createCustomTheme(EditorView: typeof import("@codemirror/view").EditorView, colors?: CustomThemeColors, isDark: boolean = true): Extension {
// 根据系统主题设置默认背景色和前景色
- const defaultColors = isDark
- ? { background: "#1e1e2e", foreground: "#cdd6f4" }
- : { background: "#fafafa", foreground: "#242424" };
+ const defaultColors = isDark ? { background: "#1e1e2e", foreground: "#cdd6f4" } : { background: "#fafafa", foreground: "#242424" };
const c = { ...defaultColors, ...customThemeColors, ...(colors || {}) };
@@ -91,10 +81,9 @@ function createCustomTheme(
".cm-cursor": {
borderLeftColor: c.cursor,
},
- "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
- {
- backgroundColor: c.selection,
- },
+ "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
+ backgroundColor: c.selection,
+ },
".cm-activeLine": {
backgroundColor: c.activeLine,
},
@@ -219,9 +208,7 @@ const FUNCTION_ICON: LucideIconNode = [
["path", { d: "M4 4v7a4 4 0 0 0 4 4h12" }],
];
-const SCHEMA_ICON: LucideIconNode = [
- ["path", { d: "M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2v11z" }],
-];
+const SCHEMA_ICON: LucideIconNode = [["path", { d: "M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2v11z" }]];
function encodeSvgIcon(iconNode: LucideIconNode): string {
const body = iconNode
@@ -262,11 +249,7 @@ export function resolveEditorTheme(theme: EditorTheme, appAppearance: AppThemeAp
}
/** Load a CodeMirror theme extension by theme name. */
-export async function loadEditorTheme(
- theme: EditorTheme,
- appAppearance: AppThemeAppearance = "dark",
- customColors?: CustomThemeColors,
-): Promise<Extension> {
+export async function loadEditorTheme(theme: EditorTheme, appAppearance: AppThemeAppearance = "dark", customColors?: CustomThemeColors): Promise<Extension> {
const resolvedTheme = resolveEditorTheme(theme, appAppearance);
switch (resolvedTheme) {
case "one-dark":
@@ -294,10 +277,7 @@ export async function loadEditorTheme(
}
}
-export function buildEditorFontThemeRules(
- opts?: { fixedHeight?: boolean; scrollable?: boolean },
- defaults?: { size?: number; family?: string },
-): CodeMirrorStyleSpec {
+export function buildEditorFontThemeRules(opts?: { fixedHeight?: boolean; scrollable?: boolean }, defaults?: { size?: number; family?: string }): CodeMirrorStyleSpec {
return {
"&": {
...(opts?.fixedHeight ? { height: "100%" } : {}),
@@ -362,12 +342,7 @@ export function buildEditorFontThemeRules(
}
/** Build a CodeMirror theme extension for font size + font family. */
-export function editorFontTheme(
- EditorView: typeof import("@codemirror/view").EditorView,
- size: number,
- family: string,
- opts?: { fixedHeight?: boolean; scrollable?: boolean },
-): Extension {
+export function editorFontTheme(EditorView: typeof import("@codemirror/view").EditorView, size: number, family: string, opts?: { fixedHeight?: boolean; scrollable?: boolean }): Extension {
return EditorView.theme(buildEditorFontThemeRules(opts, { size, family }));
}
@@ -376,10 +351,7 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
".cm-tooltip.cm-tooltip-autocomplete": {
background: "var(--popover)",
backgroundClip: "padding-box",
- border: colorMixValue(
- "1px solid var(--border)",
- "1px solid color-mix(in oklch, var(--border) 82%, var(--foreground) 18%)",
- ),
+ border: colorMixValue("1px solid var(--border)", "1px solid color-mix(in oklch, var(--border) 82%, var(--foreground) 18%)"),
borderRadius: "8px",
boxShadow: "0 8px 18px rgb(0 0 0 / 0.14)",
color: "var(--popover-foreground)",
@@ -398,10 +370,7 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
minWidth: "min(280px, calc(100vw - 24px))",
overflowX: "hidden",
padding: "0 4px 0 !important",
- scrollbarColor: colorMixValue(
- "var(--muted-foreground) transparent",
- "color-mix(in oklch, var(--muted-foreground) 44%, transparent) transparent",
- ),
+ scrollbarColor: colorMixValue("var(--muted-foreground) transparent", "color-mix(in oklch, var(--muted-foreground) 44%, transparent) transparent"),
scrollbarWidth: "thin",
},
".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
@@ -423,10 +392,7 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
".cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]": {
background: `${colorMixValue("var(--accent)", "color-mix(in oklch, var(--primary) 14%, var(--popover))")} !important`,
color: "var(--popover-foreground) !important",
- outline: colorMixValue(
- "1px solid var(--border)",
- "1px solid color-mix(in oklch, var(--primary) 22%, transparent)",
- ),
+ outline: colorMixValue("1px solid var(--border)", "1px solid color-mix(in oklch, var(--primary) 22%, transparent)"),
},
".cm-completionIcon": {
alignItems: "center",
@@ -465,38 +431,23 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
...lucideCompletionIconMask(TABLE_ICON),
},
".cm-completionIcon-column": {
- color: colorMixValue(
- "var(--blue-500, #3b82f6)",
- "color-mix(in oklch, var(--blue-500, #3b82f6) 92%, var(--popover-foreground))",
- ),
+ color: colorMixValue("var(--blue-500, #3b82f6)", "color-mix(in oklch, var(--blue-500, #3b82f6) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(COLUMNS_ICON),
},
".cm-completionIcon-keyword": {
- color: colorMixValue(
- "var(--orange-500, #f97316)",
- "color-mix(in oklch, var(--orange-500, #f97316) 92%, var(--popover-foreground))",
- ),
+ color: colorMixValue("var(--orange-500, #f97316)", "color-mix(in oklch, var(--orange-500, #f97316) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(KEYWORD_ICON),
},
".cm-completionIcon-snippet": {
- color: colorMixValue(
- "var(--violet-500, #8b5cf6)",
- "color-mix(in oklch, var(--violet-500, #8b5cf6) 92%, var(--popover-foreground))",
- ),
+ color: colorMixValue("var(--violet-500, #8b5cf6)", "color-mix(in oklch, var(--violet-500, #8b5cf6) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(SNIPPET_ICON),
},
".cm-completionIcon-function": {
- color: colorMixValue(
- "var(--emerald-500, #10b981)",
- "color-mix(in oklch, var(--emerald-500, #10b981) 92%, var(--popover-foreground))",
- ),
+ color: colorMixValue("var(--emerald-500, #10b981)", "color-mix(in oklch, var(--emerald-500, #10b981) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(FUNCTION_ICON),
},
".cm-completionIcon-schema": {
- color: colorMixValue(
- "var(--amber-500, #f59e0b)",
- "color-mix(in oklch, var(--amber-500, #f59e0b) 92%, var(--popover-foreground))",
- ),
+ color: colorMixValue("var(--amber-500, #f59e0b)", "color-mix(in oklch, var(--amber-500, #f59e0b) 92%, var(--popover-foreground))"),
...lucideCompletionIconMask(SCHEMA_ICON),
},
".cm-completionLabel": {
@@ -517,10 +468,7 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
textDecoration: "none",
},
".cm-completionDetail": {
- color: colorMixValue(
- "var(--muted-foreground)",
- "color-mix(in oklch, var(--popover-foreground) 68%, var(--popover))",
- ),
+ color: colorMixValue("var(--muted-foreground)", "color-mix(in oklch, var(--popover-foreground) 68%, var(--popover))"),
fontSize: `clamp(11px, calc(var(${EDITOR_FONT_SIZE_CSS_VAR}, 13px) - 1px), 13px)`,
fontWeight: "500",
fontStyle: "normal",
diff --git a/apps/desktop/src/lib/elasticsearchCompletion.ts b/apps/desktop/src/lib/elasticsearchCompletion.ts
index d31c961f7f..161b0a7ba4 100644
--- a/apps/desktop/src/lib/elasticsearchCompletion.ts
+++ b/apps/desktop/src/lib/elasticsearchCompletion.ts
@@ -52,28 +52,7 @@ const INDEX_ENDPOINTS = [
{ label: "_refresh", apply: "_refresh", method: "POST", detail: "Refresh index" },
];
-const JSON_KEYWORDS = [
- "query",
- "bool",
- "must",
- "should",
- "must_not",
- "filter",
- "match",
- "match_all",
- "term",
- "terms",
- "range",
- "exists",
- "sort",
- "aggs",
- "aggregations",
- "size",
- "from",
- "_source",
- "fields",
- "track_total_hits",
-];
+const JSON_KEYWORDS = ["query", "bool", "must", "should", "must_not", "filter", "match", "match_all", "term", "terms", "range", "exists", "sort", "aggs", "aggregations", "size", "from", "_source", "fields", "track_total_hits"];
const JSON_SNIPPETS = [
{
@@ -147,19 +126,12 @@ export function getElasticsearchCompletionContext(text: string, cursor: number):
};
}
-export function buildElasticsearchCompletionItems(
- text: string,
- cursor: number,
- input: ElasticsearchCompletionInput = {},
-): ElasticsearchCompletionItem[] {
+export function buildElasticsearchCompletionItems(text: string, cursor: number, input: ElasticsearchCompletionInput = {}): ElasticsearchCompletionItem[] {
const context = getElasticsearchCompletionContext(text, cursor);
return buildElasticsearchCompletionItemsFromContext(context, input);
}
-export function buildElasticsearchCompletionItemsFromContext(
- context: ElasticsearchCompletionContext,
- input: ElasticsearchCompletionInput = {},
-): ElasticsearchCompletionItem[] {
+export function buildElasticsearchCompletionItemsFromContext(context: ElasticsearchCompletionContext, input: ElasticsearchCompletionInput = {}): ElasticsearchCompletionItem[] {
if (context.mode === "method") return methodItems(context.prefix);
if (context.mode === "json") return jsonItems(context.prefix);
return pathItems(context, input.indices ?? []);
@@ -224,15 +196,13 @@ function indexItems(prefix: string, indices: string[]): ElasticsearchCompletionI
function rootEndpointItems(prefix: string): ElasticsearchCompletionItem[] {
const normalizedPrefix = prefix.startsWith("/") ? prefix.slice(1) : prefix;
- return ROOT_ENDPOINTS.filter((endpoint) => matchesFuzzyPrefix(endpoint.label.slice(1), normalizedPrefix)).map(
- (endpoint) => ({
- label: endpoint.label,
- type: endpoint.apply.includes("\n") ? ("snippet" as const) : ("property" as const),
- detail: `${endpoint.method} ${endpoint.detail}`,
- apply: endpoint.apply,
- boost: 95,
- }),
- );
+ return ROOT_ENDPOINTS.filter((endpoint) => matchesFuzzyPrefix(endpoint.label.slice(1), normalizedPrefix)).map((endpoint) => ({
+ label: endpoint.label,
+ type: endpoint.apply.includes("\n") ? ("snippet" as const) : ("property" as const),
+ detail: `${endpoint.method} ${endpoint.detail}`,
+ apply: endpoint.apply,
+ boost: 95,
+ }));
}
function indexEndpointItems(prefix: string): ElasticsearchCompletionItem[] {
@@ -254,15 +224,13 @@ function jsonItems(prefix: string): ElasticsearchCompletionItem[] {
apply: `"${key}"`,
boost: key.startsWith(normalizedPrefix) ? 95 : 70,
}));
- const snippetItems = JSON_SNIPPETS.filter((snippet) => matchesFuzzyPrefix(snippet.label, normalizedPrefix)).map(
- (snippet) => ({
- label: snippet.label,
- type: "snippet" as const,
- detail: snippet.detail,
- apply: snippet.apply,
- boost: 105,
- }),
- );
+ const snippetItems = JSON_SNIPPETS.filter((snippet) => matchesFuzzyPrefix(snippet.label, normalizedPrefix)).map((snippet) => ({
+ label: snippet.label,
+ type: "snippet" as const,
+ detail: snippet.detail,
+ apply: snippet.apply,
+ boost: 105,
+ }));
return dedupeAndSort([...snippetItems, ...keyItems]);
}
diff --git a/apps/desktop/src/lib/engineeringDiagram.ts b/apps/desktop/src/lib/engineeringDiagram.ts
index 6bc82685de..2185522c32 100644
--- a/apps/desktop/src/lib/engineeringDiagram.ts
+++ b/apps/desktop/src/lib/engineeringDiagram.ts
@@ -198,14 +198,7 @@ function buildEngineeringCluster(table: DiagramTable): EngineeringCluster {
});
groups.right.forEach((item, index) => {
- attributes.push(
- localAttributeNode(
- table,
- item,
- centerX + centerWidth + rightGap + (rightSize.width - item.width) / 2,
- centerY + (centerHeight - rightSize.height) / 2 + index * (ENGINEERING_ATTRIBUTE_HEIGHT + ATTRIBUTE_GAP_Y),
- ),
- );
+ attributes.push(localAttributeNode(table, item, centerX + centerWidth + rightGap + (rightSize.width - item.width) / 2, centerY + (centerHeight - rightSize.height) / 2 + index * (ENGINEERING_ATTRIBUTE_HEIGHT + ATTRIBUTE_GAP_Y)));
});
chunkAttributes(groups.bottom, HORIZONTAL_ATTRIBUTE_COLUMNS).forEach((row, rowIndex) => {
@@ -218,14 +211,7 @@ function buildEngineeringCluster(table: DiagramTable): EngineeringCluster {
});
groups.left.forEach((item, index) => {
- attributes.push(
- localAttributeNode(
- table,
- item,
- (leftSize.width - item.width) / 2,
- centerY + (centerHeight - leftSize.height) / 2 + index * (ENGINEERING_ATTRIBUTE_HEIGHT + ATTRIBUTE_GAP_Y),
- ),
- );
+ attributes.push(localAttributeNode(table, item, (leftSize.width - item.width) / 2, centerY + (centerHeight - leftSize.height) / 2 + index * (ENGINEERING_ATTRIBUTE_HEIGHT + ATTRIBUTE_GAP_Y)));
});
return {
@@ -251,9 +237,7 @@ function orderedTableRows(tables: DiagramTable[], positions: Record<string, Diag
y: Math.floor(fallbackIndex / columnsPerRow),
},
}));
- const ys = [...new Set(ordered.map((item) => positionKey(item.position.y)))].sort(
- (left, right) => Number(left) - Number(right),
- );
+ const ys = [...new Set(ordered.map((item) => positionKey(item.position.y)))].sort((left, right) => Number(left) - Number(right));
return ys.map((y) =>
ordered
@@ -299,11 +283,7 @@ function normalizeDiagram(diagram: Omit<EngineeringDiagram, "canvas">): Engineer
};
}
-export function buildEngineeringDiagram(
- tables: DiagramTable[],
- relationships: DiagramRelationship[],
- positions: Record<string, DiagramPosition>,
-): EngineeringDiagram {
+export function buildEngineeringDiagram(tables: DiagramTable[], relationships: DiagramRelationship[], positions: Record<string, DiagramPosition>): EngineeringDiagram {
const clusters = new Map(tables.map((table) => [table.name, buildEngineeringCluster(table)]));
const rows = orderedTableRows(tables, positions);
const entities: EngineeringEntityNode[] = [];
@@ -311,9 +291,7 @@ export function buildEngineeringDiagram(
let nextRowY = 0;
rows.forEach((row) => {
- const rowClusters = row
- .map((table) => clusters.get(table.name))
- .filter((cluster): cluster is EngineeringCluster => cluster !== undefined);
+ const rowClusters = row.map((table) => clusters.get(table.name)).filter((cluster): cluster is EngineeringCluster => cluster !== undefined);
const rowHeight = Math.max(...rowClusters.map((cluster) => cluster.height), ENGINEERING_ENTITY_HEIGHT);
let nextX = 0;
@@ -343,9 +321,7 @@ export function buildEngineeringDiagram(
nextRowY += rowHeight + ENGINEERING_CLUSTER_GAP_Y;
});
const entityMap = new Map(entities.map((entity) => [entity.name, entity]));
- const orderedEntities = tables
- .map((table) => entityMap.get(table.name))
- .filter((entity): entity is EngineeringEntityNode => entity !== undefined);
+ const orderedEntities = tables.map((table) => entityMap.get(table.name)).filter((entity): entity is EngineeringEntityNode => entity !== undefined);
const relationshipNodes: EngineeringRelationshipNode[] = relationships.flatMap((relationship) => {
const source = entityMap.get(relationship.sourceTable);
diff --git a/apps/desktop/src/lib/erDiagram.ts b/apps/desktop/src/lib/erDiagram.ts
index cfb49a46e0..4a73651937 100644
--- a/apps/desktop/src/lib/erDiagram.ts
+++ b/apps/desktop/src/lib/erDiagram.ts
@@ -56,26 +56,12 @@ export function filterDiagramTables(tables: DiagramTable[], query: string): Diag
return tables.filter((table) => {
if (table.name.toLowerCase().includes(q)) return true;
- if (
- table.columns.some(
- (column) => column.name.toLowerCase().includes(q) || column.data_type.toLowerCase().includes(q),
- )
- )
- return true;
- return table.foreignKeys.some(
- (fk) =>
- fk.name.toLowerCase().includes(q) ||
- fk.column.toLowerCase().includes(q) ||
- fk.ref_table.toLowerCase().includes(q) ||
- fk.ref_column.toLowerCase().includes(q),
- );
+ if (table.columns.some((column) => column.name.toLowerCase().includes(q) || column.data_type.toLowerCase().includes(q))) return true;
+ return table.foreignKeys.some((fk) => fk.name.toLowerCase().includes(q) || fk.column.toLowerCase().includes(q) || fk.ref_table.toLowerCase().includes(q) || fk.ref_column.toLowerCase().includes(q));
});
}
-export function layoutDiagramTables(
- tables: Pick<DiagramTable, "name" | "columns">[],
- options: DiagramLayoutOptions = {},
-): Record<string, DiagramPosition> {
+export function layoutDiagramTables(tables: Pick<DiagramTable, "name" | "columns">[], options: DiagramLayoutOptions = {}): Record<string, DiagramPosition> {
const columnsPerRow = Math.max(1, options.columnsPerRow ?? Math.ceil(Math.sqrt(Math.max(tables.length, 1))));
const cardWidth = options.cardWidth ?? 260;
const rowHeight = options.rowHeight ?? 220;
diff --git a/apps/desktop/src/lib/etcdKeyTree.ts b/apps/desktop/src/lib/etcdKeyTree.ts
index 2b8cd68160..47d13bd258 100644
--- a/apps/desktop/src/lib/etcdKeyTree.ts
+++ b/apps/desktop/src/lib/etcdKeyTree.ts
@@ -115,11 +115,7 @@ export function collectEtcdGroupIds(nodes: EtcdKeyTreeNode[]): Set<string> {
return ids;
}
-export function flattenVisibleEtcdKeyTree(
- nodes: EtcdKeyTreeNode[],
- expandedGroupIds: ReadonlySet<string>,
- depth = 0,
-): EtcdKeyTreeRow[] {
+export function flattenVisibleEtcdKeyTree(nodes: EtcdKeyTreeNode[], expandedGroupIds: ReadonlySet<string>, depth = 0): EtcdKeyTreeRow[] {
const rows: EtcdKeyTreeRow[] = [];
for (const node of nodes) {
rows.push({ node, depth });
diff --git a/apps/desktop/src/lib/explainPlan.ts b/apps/desktop/src/lib/explainPlan.ts
index c5ef85428e..754a926e83 100644
--- a/apps/desktop/src/lib/explainPlan.ts
+++ b/apps/desktop/src/lib/explainPlan.ts
@@ -20,9 +20,7 @@ export interface ParsedExplainPlan {
nodes: ExplainPlanNode[];
}
-export type BuildExplainSqlResult =
- | { ok: true; sql: string }
- | { ok: false; reason: "unsupported" | "empty" | "unsafe" };
+export type BuildExplainSqlResult = { ok: true; sql: string } | { ok: false; reason: "unsupported" | "empty" | "unsafe" };
const SUPPORTED_EXPLAIN_TYPES = new Set<DatabaseType>(["mysql", "postgres", "dameng"]);
export function supportsExplainPlan(databaseType?: DatabaseType): databaseType is "mysql" | "postgres" | "dameng" {
@@ -33,10 +31,7 @@ export function buildExplainSql(databaseType: DatabaseType | undefined, sql: str
return api.buildExplainSql({ databaseType, sql }) as Promise<BuildExplainSqlResult>;
}
-export function parseExplainResult(
- databaseType: "mysql" | "postgres" | "dameng",
- result: QueryResult,
-): ParsedExplainPlan {
+export function parseExplainResult(databaseType: "mysql" | "postgres" | "dameng", result: QueryResult): ParsedExplainPlan {
if (databaseType === "dameng") {
return parseDamengExplain(result);
}
@@ -103,10 +98,8 @@ export function parseDamengExplainText(planText: string): ParsedExplainPlan {
const depth = Math.max(0, Math.round((indent - baseIndent) / 2));
while (parentStack.length > depth) parentStack.pop();
- const childIndex =
- parentStack.length === 0 ? rootNodes.length + 1 : parentStack[parentStack.length - 1].children.length + 1;
- const id =
- parentStack.length === 0 ? String(childIndex) : `${parentStack[parentStack.length - 1].id}.${childIndex}`;
+ const childIndex = parentStack.length === 0 ? rootNodes.length + 1 : parentStack[parentStack.length - 1].children.length + 1;
+ const id = parentStack.length === 0 ? String(childIndex) : `${parentStack[parentStack.length - 1].id}.${childIndex}`;
const details: string[] = [];
if (nodeInfo.props) details.push(nodeInfo.props);
@@ -315,8 +308,7 @@ function buildColumnIndex(columns: string[]): Record<string, number> {
if (name === "objectName") return lower.findIndex((c) => c.includes("object_name"));
if (name === "objectType") return lower.findIndex((c) => c.includes("object_type"));
if (name === "cost") return lower.findIndex((c) => c === "cost" || c === "total_cost");
- if (name === "cardinality")
- return lower.findIndex((c) => c === "cardinality" || c.includes("cardinality") || c === "rows");
+ if (name === "cardinality") return lower.findIndex((c) => c === "cardinality" || c.includes("cardinality") || c === "rows");
return -1;
};
return {
@@ -446,11 +438,7 @@ function parsePostgresNode(plan: Record<string, unknown> | null, id: string): Ex
cost: [startupCost, totalCost].every(Boolean) ? `${startupCost}..${totalCost}` : totalCost,
rows,
width,
- details: [
- joinType ? `Join: ${joinType}` : "",
- filter ? `Filter: ${filter}` : "",
- sortKey ? `Sort: ${sortKey}` : "",
- ].filter(Boolean),
+ details: [joinType ? `Join: ${joinType}` : "", filter ? `Filter: ${filter}` : "", sortKey ? `Sort: ${sortKey}` : ""].filter(Boolean),
children,
};
}
@@ -485,13 +473,7 @@ function parseMysqlBlock(block: Record<string, unknown>, id: string, nodeType: s
});
}
- [
- "ordering_operation",
- "grouping_operation",
- "duplicates_removal",
- "union_result",
- "materialized_from_subquery",
- ].forEach((key) => {
+ ["ordering_operation", "grouping_operation", "duplicates_removal", "union_result", "materialized_from_subquery"].forEach((key) => {
const child = objectValue(block[key]);
if (child) children.push(parseMysqlBlock(child, `${id}.${children.length}`, key));
});
@@ -512,13 +494,8 @@ function parseMysqlTable(table: Record<string, unknown>, id: string): ExplainPla
const accessType = stringValue(table.access_type) || "table";
const costInfo = objectValue(table.cost_info);
const rows = numberLike(table.rows_examined_per_scan) || numberLike(table.rows_produced_per_join);
- const cost =
- stringValue(costInfo?.query_cost) || stringValue(costInfo?.read_cost) || stringValue(costInfo?.eval_cost);
- const details = [
- stringValue(table.attached_condition) ? `Condition: ${stringValue(table.attached_condition)}` : "",
- arrayValue(table.used_columns)?.length ? `Columns: ${arrayValue(table.used_columns)!.map(String).join(", ")}` : "",
- table.using_index === true ? "Using index" : "",
- ].filter(Boolean);
+ const cost = stringValue(costInfo?.query_cost) || stringValue(costInfo?.read_cost) || stringValue(costInfo?.eval_cost);
+ const details = [stringValue(table.attached_condition) ? `Condition: ${stringValue(table.attached_condition)}` : "", arrayValue(table.used_columns)?.length ? `Columns: ${arrayValue(table.used_columns)!.map(String).join(", ")}` : "", table.using_index === true ? "Using index" : ""].filter(Boolean);
return {
id,
@@ -536,9 +513,7 @@ function parseMysqlTable(table: Record<string, unknown>, id: string): ExplainPla
// ── Helpers ───────────────────────────────────────────────────────────
function objectValue(value: unknown): Record<string, unknown> | null {
- return value !== null && typeof value === "object" && !Array.isArray(value)
- ? (value as Record<string, unknown>)
- : null;
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}
function arrayValue(value: unknown): unknown[] | null {
diff --git a/apps/desktop/src/lib/fieldLineage.ts b/apps/desktop/src/lib/fieldLineage.ts
index 6773227505..9dde674924 100644
--- a/apps/desktop/src/lib/fieldLineage.ts
+++ b/apps/desktop/src/lib/fieldLineage.ts
@@ -47,19 +47,9 @@ export interface FieldLineageResult {
items: FieldLineageItem[];
}
-export function analyzeFieldLineage(options: {
- target: FieldLineageTarget;
- tables?: FieldLineageTable[];
- views?: FieldLineageView[];
- histories?: FieldLineageHistory[];
-}): FieldLineageResult {
+export function analyzeFieldLineage(options: { target: FieldLineageTarget; tables?: FieldLineageTable[]; views?: FieldLineageView[]; histories?: FieldLineageHistory[] }): FieldLineageResult {
const target = normalizeTarget(options.target);
- const items: FieldLineageItem[] = [
- ...foreignKeyLineage(target, options.tables ?? []),
- ...viewLineage(target, options.views ?? []),
- ...historyLineage(target, options.histories ?? []),
- ...sameNameLineage(target, options.tables ?? []),
- ];
+ const items: FieldLineageItem[] = [...foreignKeyLineage(target, options.tables ?? []), ...viewLineage(target, options.views ?? []), ...historyLineage(target, options.histories ?? []), ...sameNameLineage(target, options.tables ?? [])];
return { target: options.target, items };
}
@@ -74,11 +64,7 @@ export function summarizeLineageCounts(items: FieldLineageItem[]) {
export function identifierInSql(sql: string, identifier: string): boolean {
const escaped = escapeRegExp(identifier);
- const quoted = [
- `"${escapeRegExp(identifier)}"`,
- `\`${escapeRegExp(identifier)}\``,
- `\\[${escapeRegExp(identifier)}\\]`,
- ];
+ const quoted = [`"${escapeRegExp(identifier)}"`, `\`${escapeRegExp(identifier)}\``, `\\[${escapeRegExp(identifier)}\\]`];
const pattern = `(?:${quoted.join("|")}|(?<![\\w$])${escaped}(?![\\w$]))`;
return new RegExp(pattern, "i").test(sql);
}
@@ -131,10 +117,7 @@ function viewLineage(target: Required<FieldLineageTarget>, views: FieldLineageVi
confidence,
direction: "reference" as const,
title: `${view.name} references ${target.column}`,
- description:
- confidence === "likely"
- ? `View definition mentions both ${target.table} and ${target.column}.`
- : `View definition mentions ${target.column}.`,
+ description: confidence === "likely" ? `View definition mentions both ${target.table} and ${target.column}.` : `View definition mentions ${target.column}.`,
schema: view.schema,
table: view.name,
sqlSnippet: snippetAround(view.ddl, target.column),
@@ -172,8 +155,7 @@ function sameNameLineage(target: Required<FieldLineageTarget>, tables: FieldLine
confidence: "possible",
direction: "reference",
title: `${table.name}.${column}`,
- description:
- "Another field has the same name. This is a possible semantic relationship, not a verified dependency.",
+ description: "Another field has the same name. This is a possible semantic relationship, not a verified dependency.",
schema: table.schema,
table: table.name,
column,
diff --git a/apps/desktop/src/lib/geometryPreview.ts b/apps/desktop/src/lib/geometryPreview.ts
index ae5a6b4897..4afd23318d 100644
--- a/apps/desktop/src/lib/geometryPreview.ts
+++ b/apps/desktop/src/lib/geometryPreview.ts
@@ -107,12 +107,7 @@ function extractCoords(g: GeometryGroup): Coord[] {
}
// Draw polygon exterior + holes from a group structure
-function drawPolygonRings(
- ctx: CanvasRenderingContext2D,
- group: GeometryGroup,
- mapX: (v: number) => number,
- mapY: (v: number) => number,
-) {
+function drawPolygonRings(ctx: CanvasRenderingContext2D, group: GeometryGroup, mapX: (v: number) => number, mapY: (v: number) => number) {
// group.children contains ring groups
const rings = group.children.length > 0 ? group.children : [group];
let ringIndex = 0;
@@ -131,13 +126,7 @@ function drawPolygonRings(
}
}
-function drawGroups(
- ctx: CanvasRenderingContext2D,
- groups: GeometryGroup[],
- type: string,
- mapX: (v: number) => number,
- mapY: (v: number) => number,
-) {
+function drawGroups(ctx: CanvasRenderingContext2D, groups: GeometryGroup[], type: string, mapX: (v: number) => number, mapY: (v: number) => number) {
if (type === "POINT" || type === "MULTIPOINT") {
const allCoords = flattenCoords(groups);
for (const [x, y] of allCoords) {
diff --git a/apps/desktop/src/lib/gridSelection.ts b/apps/desktop/src/lib/gridSelection.ts
index 7912a599fa..acbf6c12bd 100644
--- a/apps/desktop/src/lib/gridSelection.ts
+++ b/apps/desktop/src/lib/gridSelection.ts
@@ -36,11 +36,7 @@ export function normalizeSelectionRange(anchor: CellPosition, focus: CellPositio
};
}
-export function rowSelectionRange(
- rowIndex: number,
- columnCount: number,
- endRowIndex = rowIndex,
-): CellSelectionRange | null {
+export function rowSelectionRange(rowIndex: number, columnCount: number, endRowIndex = rowIndex): CellSelectionRange | null {
if (rowIndex < 0 || endRowIndex < 0 || columnCount <= 0) return null;
return {
startRow: Math.min(rowIndex, endRowIndex),
@@ -50,11 +46,7 @@ export function rowSelectionRange(
};
}
-export function columnSelectionRange(
- rowCount: number,
- colIndex: number,
- endColIndex = colIndex,
-): CellSelectionRange | null {
+export function columnSelectionRange(rowCount: number, colIndex: number, endColIndex = colIndex): CellSelectionRange | null {
if (rowCount <= 0 || colIndex < 0 || endColIndex < 0) return null;
return {
startRow: 0,
@@ -71,34 +63,20 @@ export function allCellsSelectionRange(rowCount: number, columnCount: number): C
export function isCellInSelection(rowIndex: number, colIndex: number, range: CellSelectionRange | null): boolean {
if (!range) return false;
- return (
- rowIndex >= range.startRow && rowIndex <= range.endRow && colIndex >= range.startCol && colIndex <= range.endCol
- );
+ return rowIndex >= range.startRow && rowIndex <= range.endRow && colIndex >= range.startCol && colIndex <= range.endCol;
}
-export function extractSelection(
- columns: readonly string[],
- rows: readonly GridCellValue[][],
- range: CellSelectionRange | null,
-): SelectionData {
+export function extractSelection(columns: readonly string[], rows: readonly GridCellValue[][], range: CellSelectionRange | null): SelectionData {
if (!range) return { columns: [], rows: [] };
const selectedColumns = columns.slice(range.startCol, range.endCol + 1);
- const selectedRows = rows
- .slice(range.startRow, range.endRow + 1)
- .map((row) => row.slice(range.startCol, range.endCol + 1));
+ const selectedRows = rows.slice(range.startRow, range.endRow + 1).map((row) => row.slice(range.startCol, range.endCol + 1));
return { columns: selectedColumns, rows: selectedRows };
}
-export function extractColumnsSelection(
- columns: readonly string[],
- rows: readonly GridCellValue[][],
- selectedColumnIndexes: Iterable<number>,
-): SelectionData {
- const normalizedIndexes = normalizeSelectedColumnIndexes(selectedColumnIndexes).filter(
- (index) => index < columns.length,
- );
+export function extractColumnsSelection(columns: readonly string[], rows: readonly GridCellValue[][], selectedColumnIndexes: Iterable<number>): SelectionData {
+ const normalizedIndexes = normalizeSelectedColumnIndexes(selectedColumnIndexes).filter((index) => index < columns.length);
if (normalizedIndexes.length === 0) return { columns: [], rows: [] };
return {
diff --git a/apps/desktop/src/lib/historyAiAnalysis.ts b/apps/desktop/src/lib/historyAiAnalysis.ts
index 121b866931..bdab77c6ce 100644
--- a/apps/desktop/src/lib/historyAiAnalysis.ts
+++ b/apps/desktop/src/lib/historyAiAnalysis.ts
@@ -16,9 +16,7 @@ export type HistoryAiAnalysisEntry = {
details_json?: string | null;
};
-export function canRollbackHistoryEntry(
- entry: Pick<HistoryAiAnalysisEntry, "connection_id" | "database" | "rollback_sql">,
-) {
+export function canRollbackHistoryEntry(entry: Pick<HistoryAiAnalysisEntry, "connection_id" | "database" | "rollback_sql">) {
return !!entry.connection_id?.trim() && !!entry.database?.trim() && !!entry.rollback_sql?.trim();
}
diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.ts
index 2c276c68ec..a3ce75eec3 100644
--- a/apps/desktop/src/lib/http.ts
+++ b/apps/desktop/src/lib/http.ts
@@ -72,43 +72,17 @@ import type {
DroppedFilePreviewSqlOptions,
} from "./tauri";
import type { QueryEditability } from "@/lib/sqlAnalysis";
-import type {
- DataGridColumnValueFilterConditionOptions,
- DataGridContextFilterConditionOptions,
- DataGridCountSqlOptions,
- DataGridCopyInsertStatementOptions,
- DataGridCopyUpdateStatementOptions,
- DataGridSaveStatementOptions,
- HiveTablePropertiesSqlOptions,
-} from "@/lib/dataGridSql";
-import type {
- BuildTableStructureChangeSqlOptions,
- BuildSingleColumnAlterSqlOptions,
- TableStructureChangeSql,
-} from "@/lib/tableStructureEditorSql";
+import type { DataGridColumnValueFilterConditionOptions, DataGridContextFilterConditionOptions, DataGridCountSqlOptions, DataGridCopyInsertStatementOptions, DataGridCopyUpdateStatementOptions, DataGridSaveStatementOptions, HiveTablePropertiesSqlOptions } from "@/lib/dataGridSql";
+import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, TableStructureChangeSql } from "@/lib/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/databaseSearch";
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/objectSourceEditor";
import type { BuildViewDdlInput } from "@/lib/viewDdl";
import type { BuildRenameObjectSqlOptions } from "@/lib/objectRenameSql";
import type { CreateDatabaseSqlOptions } from "@/lib/createDatabaseSql";
-import type {
- DatabaseNameSqlOptions,
- DropTableChildObjectSqlOptions,
- DropObjectSqlOptions,
- DuplicateTableStructureSqlOptions,
- SchemaNameSqlOptions,
- TableAdminSqlOptions,
-} from "@/lib/dbAdminSql";
+import type { DatabaseNameSqlOptions, DropTableChildObjectSqlOptions, DropObjectSqlOptions, DuplicateTableStructureSqlOptions, SchemaNameSqlOptions, TableAdminSqlOptions } from "@/lib/dbAdminSql";
import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions } from "@/lib/databaseExport";
-import type {
- DataCompareFromTablesOptions,
- DataCompareFromTablesPreparation,
- DataCompareSyncPlan,
- DataCompareSyncPlanOptions,
- DataComparePreparation,
- DataComparePreparationOptions,
-} from "@/lib/dataCompare";
+import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataCompare";
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff } from "@/lib/schemaDiff";
import type { DataGridSavePreparation } from "./tauri";
@@ -341,9 +315,7 @@ export async function uninstallJre(jreKey: string): Promise<void> {
await post("/api/agents/uninstall-jre", { jreKey });
}
-export async function listenAgentInstallProgress(
- handler: (progress: DriverInstallProgress) => void,
-): Promise<() => void> {
+export async function listenAgentInstallProgress(handler: (progress: DriverInstallProgress) => void): Promise<() => void> {
const es = new EventSource("/api/agents/progress/global");
es.onmessage = (event) => {
try {
@@ -411,22 +383,11 @@ export async function listSchemas(connectionId: string, database: string): Promi
return get(`/api/schema/schemas?${qs({ connection_id: connectionId, database })}`);
}
-export async function listTables(
- connectionId: string,
- database: string,
- schema: string,
- filter?: string,
- limit?: number,
-): Promise<TableInfo[]> {
+export async function listTables(connectionId: string, database: string, schema: string, filter?: string, limit?: number): Promise<TableInfo[]> {
return get(`/api/schema/tables?${qs({ connection_id: connectionId, database, schema, filter, limit })}`);
}
-export async function listObjects(
- connectionId: string,
- database: string,
- schema: string,
- objectTypes?: SidebarObjectKind[],
-): Promise<ObjectInfo[]> {
+export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: SidebarObjectKind[]): Promise<ObjectInfo[]> {
return get(
`/api/schema/objects?${qs({
connection_id: connectionId,
@@ -437,68 +398,31 @@ export async function listObjects(
);
}
-export async function listCompletionObjects(
- connectionId: string,
- database: string,
- schema: string,
-): Promise<ObjectInfo[]> {
+export async function listCompletionObjects(connectionId: string, database: string, schema: string): Promise<ObjectInfo[]> {
return get(`/api/schema/completion-objects?${qs({ connection_id: connectionId, database, schema })}`);
}
-export async function getObjectSource(
- connectionId: string,
- database: string,
- schema: string,
- name: string,
- objectType: ObjectSourceKind,
-): Promise<ObjectSource> {
- return get(
- `/api/schema/object-source?${qs({ connection_id: connectionId, database, schema, table: name, object_type: objectType })}`,
- );
+export async function getObjectSource(connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind): Promise<ObjectSource> {
+ return get(`/api/schema/object-source?${qs({ connection_id: connectionId, database, schema, table: name, object_type: objectType })}`);
}
-export async function getColumns(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<ColumnInfo[]> {
+export async function getColumns(connectionId: string, database: string, schema: string, table: string): Promise<ColumnInfo[]> {
return get(`/api/schema/columns?${qs({ connection_id: connectionId, database, schema, table })}`);
}
-export async function listIndexes(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<IndexInfo[]> {
+export async function listIndexes(connectionId: string, database: string, schema: string, table: string): Promise<IndexInfo[]> {
return get(`/api/schema/indexes?${qs({ connection_id: connectionId, database, schema, table })}`);
}
-export async function listForeignKeys(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<ForeignKeyInfo[]> {
+export async function listForeignKeys(connectionId: string, database: string, schema: string, table: string): Promise<ForeignKeyInfo[]> {
return get(`/api/schema/foreign-keys?${qs({ connection_id: connectionId, database, schema, table })}`);
}
-export async function listTriggers(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<TriggerInfo[]> {
+export async function listTriggers(connectionId: string, database: string, schema: string, table: string): Promise<TriggerInfo[]> {
return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table })}`);
}
-export async function getTableDdl(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<string> {
+export async function getTableDdl(connectionId: string, database: string, schema: string, table: string): Promise<string> {
return get(`/api/schema/ddl?${qs({ connection_id: connectionId, database, schema, table })}`);
}
@@ -506,11 +430,7 @@ export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions):
return post("/api/schema-diff/prepare", options);
}
-export async function generateSchemaSyncSql(
- diffs: TableDiff[],
- databaseType: DatabaseType,
- targetSchema?: string,
-): Promise<string> {
+export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string): Promise<string> {
return post("/api/schema-diff/generate-sync-sql", { diffs, databaseType, targetSchema });
}
@@ -554,47 +474,23 @@ export async function executeMulti(
return post("/api/query/execute-multi", { connectionId, database, sql, schema, executionId, ...options });
}
-export async function closeQuerySession(
- connectionId: string,
- database: string,
- sessionId: string,
- clientSessionId?: string,
-): Promise<boolean> {
+export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string): Promise<boolean> {
return post("/api/query/close-session", { connectionId, database, sessionId, clientSessionId });
}
-export async function closeClientConnectionSession(
- connectionId: string,
- database: string,
- clientSessionId: string,
-): Promise<boolean> {
+export async function closeClientConnectionSession(connectionId: string, database: string, clientSessionId: string): Promise<boolean> {
return post("/api/query/close-client-session", { connectionId, database, clientSessionId });
}
-export async function executeBatch(
- connectionId: string,
- database: string,
- statements: string[],
- schema?: string,
-): Promise<QueryResult> {
+export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string): Promise<QueryResult> {
return post("/api/query/execute-batch", { connectionId, database, statements, schema });
}
-export async function executeScript(
- connectionId: string,
- database: string,
- sql: string,
- schema?: string,
-): Promise<QueryResult> {
+export async function executeScript(connectionId: string, database: string, sql: string, schema?: string): Promise<QueryResult> {
return post("/api/query/execute-script", { connectionId, database, sql, schema });
}
-export async function executeInTransaction(
- connectionId: string,
- database: string,
- statements: string[],
- schema?: string,
-): Promise<QueryResult> {
+export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string): Promise<QueryResult> {
return post("/api/query/execute-in-transaction", { connectionId, database, statements, schema });
}
@@ -606,17 +502,11 @@ export async function analyzeSqlReferences(sql: string, dialect?: string): Promi
return post("/api/query/analyze-sql-references", { sql, dialect });
}
-export async function findStatementAtCursor(
- sql: string,
- cursorPos: number,
- databaseType?: DatabaseType,
-): Promise<string> {
+export async function findStatementAtCursor(sql: string, cursorPos: number, databaseType?: DatabaseType): Promise<string> {
return post("/api/query/find-statement-at-cursor", { sql, cursorPos, databaseType });
}
-export async function prepareQueryPaginationExecutionPlan(
- options: QueryPaginationExecutionPlanOptions,
-): Promise<QueryPaginationExecutionPlan> {
+export async function prepareQueryPaginationExecutionPlan(options: QueryPaginationExecutionPlanOptions): Promise<QueryPaginationExecutionPlan> {
return post("/api/query/prepare-pagination-plan", { options });
}
@@ -632,13 +522,7 @@ export async function buildCreateUserSql(username: string, password: string, tab
return post("/api/query/build-create-user-sql", { username, password, tablespace });
}
-export async function getExplainInfo(
- connectionId: string,
- database: string | undefined,
- schema: string | undefined,
- sql: string,
- mode: string,
-): Promise<string | undefined> {
+export async function getExplainInfo(connectionId: string, database: string | undefined, schema: string | undefined, sql: string, mode: string): Promise<string | undefined> {
try {
const result = await post<string>("/api/query/get-explain-info", { connectionId, database, schema, sql, mode });
return result;
@@ -712,9 +596,7 @@ export async function buildDuplicateTableStructureSql(options: DuplicateTableStr
return post("/api/query/build-duplicate-table-structure-sql", { options });
}
-export async function buildExecutableObjectSourceStatements(
- input: BuildEditableObjectSourceSqlInput,
-): Promise<string[]> {
+export async function buildExecutableObjectSourceStatements(input: BuildEditableObjectSourceSqlInput): Promise<string[]> {
return post("/api/query/build-executable-object-source-statements", { input });
}
@@ -722,9 +604,7 @@ export async function buildExecutableObjectSourceSql(input: BuildEditableObjectS
return post("/api/query/build-executable-object-source-sql", { input });
}
-export async function buildRoutineRenameObjectSourceStatements(
- input: BuildRoutineRenameObjectSourceInput,
-): Promise<string[]> {
+export async function buildRoutineRenameObjectSourceStatements(input: BuildRoutineRenameObjectSourceInput): Promise<string[]> {
return post("/api/query/build-routine-rename-object-source-statements", { input });
}
@@ -732,21 +612,15 @@ export async function buildViewDdlSql(input: BuildViewDdlInput): Promise<string>
return post("/api/query/build-view-ddl-sql", { input });
}
-export async function buildTableStructureChangeSql(
- options: BuildTableStructureChangeSqlOptions,
-): Promise<TableStructureChangeSql> {
+export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
return post("/api/query/build-table-structure-change-sql", { options });
}
-export async function buildCreateTableSql(
- options: BuildTableStructureChangeSqlOptions,
-): Promise<TableStructureChangeSql> {
+export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
return post("/api/query/build-create-table-sql", { options });
}
-export async function buildSingleColumnAlterSql(
- options: BuildSingleColumnAlterSqlOptions,
-): Promise<TableStructureChangeSql> {
+export async function buildSingleColumnAlterSql(options: BuildSingleColumnAlterSqlOptions): Promise<TableStructureChangeSql> {
return post("/api/query/build-single-column-alter-sql", { options });
}
@@ -758,29 +632,21 @@ export async function prepareDataGridSave(options: DataGridSaveStatementOptions)
return post("/api/query/prepare-data-grid-save", { options });
}
-export async function buildDataGridCopyUpdateStatements(
- options: DataGridCopyUpdateStatementOptions,
-): Promise<string[]> {
+export async function buildDataGridCopyUpdateStatements(options: DataGridCopyUpdateStatementOptions): Promise<string[]> {
return post("/api/query/build-data-grid-copy-update-statements", { options });
}
-export async function buildDataGridCopyInsertStatement(
- options: DataGridCopyInsertStatementOptions,
-): Promise<string | undefined> {
+export async function buildDataGridCopyInsertStatement(options: DataGridCopyInsertStatementOptions): Promise<string | undefined> {
const result = await post<string | null>("/api/query/build-data-grid-copy-insert-statement", { options });
return result ?? undefined;
}
-export async function buildDataGridContextFilterCondition(
- options: DataGridContextFilterConditionOptions,
-): Promise<string | undefined> {
+export async function buildDataGridContextFilterCondition(options: DataGridContextFilterConditionOptions): Promise<string | undefined> {
const result = await post<string | null>("/api/query/build-data-grid-context-filter-condition", { options });
return result ?? undefined;
}
-export async function buildDataGridColumnValueFilterCondition(
- options: DataGridColumnValueFilterConditionOptions,
-): Promise<string | undefined> {
+export async function buildDataGridColumnValueFilterCondition(options: DataGridColumnValueFilterConditionOptions): Promise<string | undefined> {
const result = await post<string | null>("/api/query/build-data-grid-column-value-filter-condition", { options });
return result ?? undefined;
}
@@ -809,15 +675,11 @@ export async function prepareDataCompare(options: DataComparePreparationOptions)
return post("/api/data-compare/prepare", options);
}
-export async function prepareDataCompareFromTables(
- options: DataCompareFromTablesOptions,
-): Promise<DataCompareFromTablesPreparation> {
+export async function prepareDataCompareFromTables(options: DataCompareFromTablesOptions): Promise<DataCompareFromTablesPreparation> {
return post("/api/data-compare/prepare-from-tables", options);
}
-export async function prepareDataCompareMissingTarget(
- options: import("@/lib/dataCompare").DataCompareMissingTargetOptions,
-): Promise<DataCompareFromTablesPreparation> {
+export async function prepareDataCompareMissingTarget(options: import("@/lib/dataCompare").DataCompareMissingTargetOptions): Promise<DataCompareFromTablesPreparation> {
return post("/api/data-compare/prepare-missing-target", options);
}
@@ -833,11 +695,7 @@ export async function aiComplete(request: AiCompletionRequest): Promise<string>
return post("/api/ai/complete", { request });
}
-export async function aiStream(
- sessionId: string,
- request: AiCompletionRequest,
- onChunk: (chunk: AiStreamChunk) => void,
-): Promise<void> {
+export async function aiStream(sessionId: string, request: AiCompletionRequest, onChunk: (chunk: AiStreamChunk) => void): Promise<void> {
const res = await fetch("/api/ai/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -946,18 +804,11 @@ export async function forgetWebdavSavedPassword(_config: WebDavConfig): Promise<
throw new Error("WebDAV sync is only available in the desktop app.");
}
-export async function webdavSyncUpload(
- _config: WebDavConfig,
- _editorSettings?: unknown,
- _secretsPassphrase?: string,
-): Promise<WebDavSyncSummary> {
+export async function webdavSyncUpload(_config: WebDavConfig, _editorSettings?: unknown, _secretsPassphrase?: string): Promise<WebDavSyncSummary> {
throw new Error("WebDAV sync is only available in the desktop app.");
}
-export async function webdavSyncDownload(
- _config: WebDavConfig,
- _secretsPassphrase?: string,
-): Promise<WebDavDownloadResult> {
+export async function webdavSyncDownload(_config: WebDavConfig, _secretsPassphrase?: string): Promise<WebDavDownloadResult> {
throw new Error("WebDAV sync is only available in the desktop app.");
}
@@ -1035,10 +886,7 @@ export async function readExternalSqlFile(_path: string): Promise<string> {
// Data Transfer
// ---------------------------------------------------------------------------
-export async function startTransfer(
- request: TransferRequest,
- onProgress: (progress: TransferProgress) => void,
-): Promise<void> {
+export async function startTransfer(request: TransferRequest, onProgress: (progress: TransferProgress) => void): Promise<void> {
// 1. POST to start the transfer
const res = await fetch("/api/transfer/start", {
method: "POST",
@@ -1084,10 +932,7 @@ export async function previewTableImportFile(fileOrPath: string | File): Promise
return res.json();
}
-export async function importTableFile(
- request: TableImportRequest,
- onProgress: (progress: TableImportProgress) => void,
-): Promise<TableImportSummary> {
+export async function importTableFile(request: TableImportRequest, onProgress: (progress: TableImportProgress) => void): Promise<TableImportSummary> {
// 1. POST to start the import
const res = await fetch("/api/import/execute", {
method: "POST",
@@ -1131,10 +976,7 @@ export async function cancelTableImport(importId: string): Promise<boolean> {
// Database Export
// ---------------------------------------------------------------------------
-export async function exportDatabaseSql(
- request: DatabaseExportRequest,
- onProgress: (progress: ExportProgress) => void,
-): Promise<void> {
+export async function exportDatabaseSql(request: DatabaseExportRequest, onProgress: (progress: ExportProgress) => void): Promise<void> {
// 1. POST to start the export
const res = await fetch("/api/export/database", {
method: "POST",
@@ -1167,10 +1009,7 @@ export async function cancelDatabaseExport(exportId: string): Promise<void> {
// --- Table Export ---
-export async function startTableExport(
- request: TableExportRequest,
- onProgress: (progress: TableExportProgress) => void,
-): Promise<TableExportProgress> {
+export async function startTableExport(request: TableExportRequest, onProgress: (progress: TableExportProgress) => void): Promise<TableExportProgress> {
const { exportId } = request;
return new Promise((resolve, reject) => {
@@ -1227,11 +1066,7 @@ export async function cancelTableExport(exportId: string): Promise<void> {
return post("/api/export/table/cancel", { exportId });
}
-export async function exportQueryResultCsv(
- filePath: string,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultCsv(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
const { formatCsv } = await import("./exportFormats");
const content = formatCsv(columns, rows as (string | number | boolean | null)[][]);
const fileName = filePath.split(/[\\/]/).pop() || "export.csv";
@@ -1259,12 +1094,7 @@ function downloadTextFile(filePath: string, fallbackFileName: string, content: s
URL.revokeObjectURL(url);
}
-export async function exportQueryResultXlsx(
- filePath: string,
- sheetName: string | undefined,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultXlsx(filePath: string, sheetName: string | undefined, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
const { buildXlsxWorkbook } = await import("./xlsxExport");
const workbook = buildXlsxWorkbook({
sheetName: sheetName || "Export",
@@ -1283,20 +1113,12 @@ export async function exportQueryResultXlsx(
URL.revokeObjectURL(url);
}
-export async function exportQueryResultJson(
- filePath: string,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultJson(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
const result = await post<{ content: string }>("/api/export/query-result-json", { columns, rows });
downloadTextFile(filePath, "export.json", result.content, "application/json;charset=utf-8");
}
-export async function exportQueryResultMarkdown(
- filePath: string,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultMarkdown(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
const result = await post<{ content: string }>("/api/export/query-result-markdown", { columns, rows });
downloadTextFile(filePath, "export.md", result.content, "text/markdown;charset=utf-8");
}
@@ -1309,24 +1131,11 @@ export async function redisListDatabases(connectionId: string): Promise<RedisDat
return post("/api/redis/list-databases", { connectionId });
}
-export async function redisScanKeys(
- connectionId: string,
- db: number,
- cursor: number,
- pattern: string,
- count: number,
-): Promise<RedisScanResult> {
+export async function redisScanKeys(connectionId: string, db: number, cursor: number, pattern: string, count: number): Promise<RedisScanResult> {
return post("/api/redis/scan-keys", { connectionId, db, cursor, pattern, count });
}
-export async function redisScanValues(
- connectionId: string,
- db: number,
- cursor: number,
- pattern: string,
- query: string,
- count: number,
-): Promise<RedisScanResult> {
+export async function redisScanValues(connectionId: string, db: number, cursor: number, pattern: string, query: string, count: number): Promise<RedisScanResult> {
return post("/api/redis/scan-values", { connectionId, db, cursor, pattern, query, count });
}
@@ -1334,13 +1143,7 @@ export async function redisGetValue(connectionId: string, db: number, keyRaw: st
return post("/api/redis/get-value", { connectionId, db, keyRaw });
}
-export async function redisSetString(
- connectionId: string,
- db: number,
- keyRaw: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisSetString(connectionId: string, db: number, keyRaw: string, value: string, ttl?: number): Promise<void> {
return post("/api/redis/set-string", { connectionId, db, keyRaw, value, ttl });
}
@@ -1348,14 +1151,7 @@ export async function redisDeleteKey(connectionId: string, db: number, keyRaw: s
return post("/api/redis/delete-key", { connectionId, db, keyRaw });
}
-export async function redisHashSet(
- connectionId: string,
- db: number,
- keyRaw: string,
- field: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisHashSet(connectionId: string, db: number, keyRaw: string, field: string, value: string, ttl?: number): Promise<void> {
return post("/api/redis/hash-set", { connectionId, db, keyRaw, field, value, ttl });
}
@@ -1363,23 +1159,11 @@ export async function redisHashDel(connectionId: string, db: number, keyRaw: str
return post("/api/redis/hash-del", { connectionId, db, keyRaw, field });
}
-export async function redisListPush(
- connectionId: string,
- db: number,
- keyRaw: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisListPush(connectionId: string, db: number, keyRaw: string, value: string, ttl?: number): Promise<void> {
return post("/api/redis/list-push", { connectionId, db, keyRaw, value, ttl });
}
-export async function redisListSet(
- connectionId: string,
- db: number,
- keyRaw: string,
- index: number,
- value: string,
-): Promise<void> {
+export async function redisListSet(connectionId: string, db: number, keyRaw: string, index: number, value: string): Promise<void> {
return post("/api/redis/list-set", { connectionId, db, keyRaw, index, value });
}
@@ -1387,13 +1171,7 @@ export async function redisListRemove(connectionId: string, db: number, keyRaw:
return post("/api/redis/list-remove", { connectionId, db, keyRaw, index });
}
-export async function redisSetAdd(
- connectionId: string,
- db: number,
- keyRaw: string,
- member: string,
- ttl?: number,
-): Promise<void> {
+export async function redisSetAdd(connectionId: string, db: number, keyRaw: string, member: string, ttl?: number): Promise<void> {
return post("/api/redis/set-add", { connectionId, db, keyRaw, member, ttl });
}
@@ -1401,14 +1179,7 @@ export async function redisSetRemove(connectionId: string, db: number, keyRaw: s
return post("/api/redis/set-remove", { connectionId, db, keyRaw, member });
}
-export async function redisZadd(
- connectionId: string,
- db: number,
- keyRaw: string,
- member: string,
- score: number,
- ttl?: number,
-): Promise<void> {
+export async function redisZadd(connectionId: string, db: number, keyRaw: string, member: string, score: number, ttl?: number): Promise<void> {
return post("/api/redis/zadd", { connectionId, db, keyRaw, member, score, ttl });
}
@@ -1416,24 +1187,11 @@ export async function redisZrem(connectionId: string, db: number, keyRaw: string
return post("/api/redis/zrem", { connectionId, db, keyRaw, member });
}
-export async function redisStreamAdd(
- connectionId: string,
- db: number,
- keyRaw: string,
- entryId: string,
- fields: [string, string][],
- ttl?: number,
-): Promise<void> {
+export async function redisStreamAdd(connectionId: string, db: number, keyRaw: string, entryId: string, fields: [string, string][], ttl?: number): Promise<void> {
return post("/api/redis/stream-add", { connectionId, db, keyRaw, entryId, fields, ttl });
}
-export async function redisJsonSet(
- connectionId: string,
- db: number,
- keyRaw: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisJsonSet(connectionId: string, db: number, keyRaw: string, value: string, ttl?: number): Promise<void> {
return post("/api/redis/json-set", { connectionId, db, keyRaw, value, ttl });
}
@@ -1453,22 +1211,11 @@ export async function redisFlushDb(connectionId: string, db: number): Promise<vo
return post("/api/redis/flush-db", { connectionId, db });
}
-export async function redisExecuteCommand(
- connectionId: string,
- db: number,
- command: string,
-): Promise<RedisCommandResult> {
+export async function redisExecuteCommand(connectionId: string, db: number, command: string): Promise<RedisCommandResult> {
return post("/api/redis/execute-command", { connectionId, db, command });
}
-export async function redisLoadMore(
- connectionId: string,
- db: number,
- keyRaw: string,
- keyType: string,
- cursor: number,
- count: number,
-): Promise<RedisValue> {
+export async function redisLoadMore(connectionId: string, db: number, keyRaw: string, keyType: string, cursor: number, count: number): Promise<RedisValue> {
return post("/api/redis/load-more", { connectionId, db, keyRaw, keyType, cursor, count });
}
@@ -1476,12 +1223,7 @@ export async function redisLoadMore(
// etcd
// ---------------------------------------------------------------------------
-export async function etcdListPrefix(
- connectionId: string,
- prefix: string,
- limit: number,
- continuation?: string | null,
-): Promise<KvListPrefixResponse> {
+export async function etcdListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null): Promise<KvListPrefixResponse> {
return post("/api/etcd/list-prefix", { connectionId, prefix, limit, continuation });
}
@@ -1489,12 +1231,7 @@ export async function etcdGet(connectionId: string, key: string): Promise<KvGetR
return post("/api/etcd/get", { connectionId, key });
}
-export async function etcdPut(
- connectionId: string,
- key: string,
- value: KvValue,
- lease?: number | null,
-): Promise<KvPutResponse> {
+export async function etcdPut(connectionId: string, key: string, value: KvValue, lease?: number | null): Promise<KvPutResponse> {
return post("/api/etcd/put", { connectionId, key, value, lease });
}
@@ -1514,83 +1251,35 @@ export async function mongoListCollections(connectionId: string, database: strin
return post("/api/mongo/list-collections", { connectionId, database });
}
-export async function mongoFindDocuments(
- connectionId: string,
- database: string,
- collection: string,
- skip: number,
- limit: number,
- filter?: string,
- sort?: string,
-): Promise<MongoDocumentResult> {
+export async function mongoFindDocuments(connectionId: string, database: string, collection: string, skip: number, limit: number, filter?: string, sort?: string): Promise<MongoDocumentResult> {
return post("/api/mongo/find-documents", { connectionId, database, collection, skip, limit, filter, sort });
}
-export async function mongoAggregateDocuments(
- connectionId: string,
- database: string,
- collection: string,
- pipelineJson: string,
- maxRows?: number,
-): Promise<MongoDocumentResult> {
+export async function mongoAggregateDocuments(connectionId: string, database: string, collection: string, pipelineJson: string, maxRows?: number): Promise<MongoDocumentResult> {
return post("/api/mongo/aggregate-documents", { connectionId, database, collection, pipelineJson, maxRows });
}
-export async function mongoInsertDocument(
- connectionId: string,
- database: string,
- collection: string,
- docJson: string,
-): Promise<string> {
+export async function mongoInsertDocument(connectionId: string, database: string, collection: string, docJson: string): Promise<string> {
return post("/api/mongo/insert-document", { connectionId, database, collection, docJson });
}
-export async function mongoInsertDocuments(
- connectionId: string,
- database: string,
- collection: string,
- docsJson: string,
-): Promise<{ affected_rows: number }> {
+export async function mongoInsertDocuments(connectionId: string, database: string, collection: string, docsJson: string): Promise<{ affected_rows: number }> {
return post("/api/mongo/insert-documents", { connectionId, database, collection, docsJson });
}
-export async function mongoUpdateDocument(
- connectionId: string,
- database: string,
- collection: string,
- id: string,
- docJson: string,
-): Promise<number> {
+export async function mongoUpdateDocument(connectionId: string, database: string, collection: string, id: string, docJson: string): Promise<number> {
return post("/api/mongo/update-document", { connectionId, database, collection, id, docJson });
}
-export async function mongoUpdateDocuments(
- connectionId: string,
- database: string,
- collection: string,
- filterJson: string,
- updateJson: string,
- many: boolean,
-): Promise<{ affected_rows: number }> {
+export async function mongoUpdateDocuments(connectionId: string, database: string, collection: string, filterJson: string, updateJson: string, many: boolean): Promise<{ affected_rows: number }> {
return post("/api/mongo/update-documents", { connectionId, database, collection, filterJson, updateJson, many });
}
-export async function mongoDeleteDocument(
- connectionId: string,
- database: string,
- collection: string,
- id: string,
-): Promise<number> {
+export async function mongoDeleteDocument(connectionId: string, database: string, collection: string, id: string): Promise<number> {
return post("/api/mongo/delete-document", { connectionId, database, collection, id });
}
-export async function mongoDeleteDocuments(
- connectionId: string,
- database: string,
- collection: string,
- filterJson: string,
- many: boolean,
-): Promise<{ affected_rows: number }> {
+export async function mongoDeleteDocuments(connectionId: string, database: string, collection: string, filterJson: string, many: boolean): Promise<{ affected_rows: number }> {
return post("/api/mongo/delete-documents", { connectionId, database, collection, filterJson, many });
}
diff --git a/apps/desktop/src/lib/httpSqlFileProgress.ts b/apps/desktop/src/lib/httpSqlFileProgress.ts
index f7d0720647..722452e386 100644
--- a/apps/desktop/src/lib/httpSqlFileProgress.ts
+++ b/apps/desktop/src/lib/httpSqlFileProgress.ts
@@ -1,9 +1,6 @@
import type { SqlFileProgress } from "./tauri";
-export function listenSqlFileProgressById(
- executionId: string,
- handler: (progress: SqlFileProgress) => void,
-): () => void {
+export function listenSqlFileProgressById(executionId: string, handler: (progress: SqlFileProgress) => void): () => void {
const es = new EventSource(`/api/sql-file/progress/${executionId}`);
es.onmessage = (e) => {
const progress: SqlFileProgress = JSON.parse(e.data);
diff --git a/apps/desktop/src/lib/imagePreviewViewer.ts b/apps/desktop/src/lib/imagePreviewViewer.ts
index 7e6b942c14..7c696bd473 100644
--- a/apps/desktop/src/lib/imagePreviewViewer.ts
+++ b/apps/desktop/src/lib/imagePreviewViewer.ts
@@ -14,19 +14,8 @@ export function nextImagePreviewScale(scale: number, direction: ImagePreviewZoom
return clampImagePreviewScale(scale + delta);
}
-export function imagePreviewFitScale(options: {
- imageWidth: number;
- imageHeight: number;
- viewportWidth: number;
- viewportHeight: number;
- paddingRatio?: number;
-}): number {
- if (
- options.imageWidth <= 0 ||
- options.imageHeight <= 0 ||
- options.viewportWidth <= 0 ||
- options.viewportHeight <= 0
- ) {
+export function imagePreviewFitScale(options: { imageWidth: number; imageHeight: number; viewportWidth: number; viewportHeight: number; paddingRatio?: number }): number {
+ if (options.imageWidth <= 0 || options.imageHeight <= 0 || options.viewportWidth <= 0 || options.viewportHeight <= 0) {
return 1;
}
const paddingRatio = options.paddingRatio ?? 0.9;
diff --git a/apps/desktop/src/lib/jdbcDialect.ts b/apps/desktop/src/lib/jdbcDialect.ts
index 4df3d4d3a6..5ffa39d7d3 100644
--- a/apps/desktop/src/lib/jdbcDialect.ts
+++ b/apps/desktop/src/lib/jdbcDialect.ts
@@ -17,28 +17,20 @@ const JDBC_DIALECT_MATCHERS: Array<{ type: DatabaseType; patterns: RegExp[] }> =
{ type: "informix", patterns: [/jdbc:informix/i, /informix/i] },
];
-export function inferJdbcDialect(
- connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">,
-): DatabaseType | undefined {
+export function inferJdbcDialect(connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">): DatabaseType | undefined {
if (!connection || connection.db_type !== "jdbc") return undefined;
- const haystack = [connection.connection_string, connection.jdbc_driver_class, ...(connection.jdbc_driver_paths ?? [])]
- .filter(Boolean)
- .join("\n");
+ const haystack = [connection.connection_string, connection.jdbc_driver_class, ...(connection.jdbc_driver_paths ?? [])].filter(Boolean).join("\n");
if (!haystack) return undefined;
return JDBC_DIALECT_MATCHERS.find((matcher) => matcher.patterns.some((pattern) => pattern.test(haystack)))?.type;
}
-export function effectiveDatabaseTypeForConnection(
- connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">,
-): DatabaseType | undefined {
+export function effectiveDatabaseTypeForConnection(connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">): DatabaseType | undefined {
if (!connection) return undefined;
if (connection.db_type !== "jdbc") return connection.db_type;
return inferJdbcDialect(connection) ?? "jdbc";
}
-export function connectionUsesDatabaseObjectTreeMode(
- connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">,
-): boolean {
+export function connectionUsesDatabaseObjectTreeMode(connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">): boolean {
if (!connection) return false;
if (connection.db_type !== "jdbc") return usesDatabaseObjectTreeMode(connection.db_type);
const dialect = inferJdbcDialect(connection);
@@ -46,31 +38,17 @@ export function connectionUsesDatabaseObjectTreeMode(
return true;
}
-export function connectionUsesSchemaExecutionContext(
- connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">,
-): boolean {
+export function connectionUsesSchemaExecutionContext(connection?: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">): boolean {
return connection?.db_type === "jdbc" && inferJdbcDialect(connection) === "databend";
}
-export function connectionObjectTreeQuerySchema(
- connection:
- | Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">
- | undefined,
- database: string,
- schema?: string,
-): string {
+export function connectionObjectTreeQuerySchema(connection: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths"> | undefined, database: string, schema?: string): string {
if (connection?.db_type === "jdbc" && inferJdbcDialect(connection) === "databend") return schema || database;
if (connectionUsesDatabaseObjectTreeMode(connection)) return "";
return schema || database;
}
-export function connectionObjectTreeNodeSchema(
- connection:
- | Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths">
- | undefined,
- database: string,
- schema?: string,
-): string | undefined {
+export function connectionObjectTreeNodeSchema(connection: Pick<ConnectionConfig, "db_type" | "connection_string" | "jdbc_driver_class" | "jdbc_driver_paths"> | undefined, database: string, schema?: string): string | undefined {
if (connection?.db_type === "jdbc" && inferJdbcDialect(connection) === "databend") return schema || database;
if (connectionUsesDatabaseObjectTreeMode(connection)) return undefined;
if (schema) return schema;
diff --git a/apps/desktop/src/lib/keyboardShortcuts.ts b/apps/desktop/src/lib/keyboardShortcuts.ts
index 7fd9cb41d0..8d2adc9eb5 100644
--- a/apps/desktop/src/lib/keyboardShortcuts.ts
+++ b/apps/desktop/src/lib/keyboardShortcuts.ts
@@ -1,9 +1,4 @@
-import {
- DEFAULT_SHORTCUT_SETTINGS,
- normalizeShortcutSettings,
- type ShortcutActionId,
- type ShortcutSettings,
-} from "@/lib/shortcutRegistry";
+import { DEFAULT_SHORTCUT_SETTINGS, normalizeShortcutSettings, type ShortcutActionId, type ShortcutSettings } from "@/lib/shortcutRegistry";
export interface ShortcutLikeEvent {
key: string;
@@ -129,9 +124,7 @@ export function isAcceptCompletionShortcut(event: ShortcutLikeEvent, shortcuts?:
return matchesShortcut(event, actionShortcut("acceptCompletion", shortcuts));
}
-export function isObjectSourceSaveShortcutTarget(
- target: { closest(selector: string): unknown } | null | undefined,
-): boolean {
+export function isObjectSourceSaveShortcutTarget(target: { closest(selector: string): unknown } | null | undefined): boolean {
return !!target?.closest("[data-object-source-editor], [data-object-source-preview]");
}
diff --git a/apps/desktop/src/lib/mongoShellCommand.ts b/apps/desktop/src/lib/mongoShellCommand.ts
index 2bd6ef4e95..43fe015bde 100644
--- a/apps/desktop/src/lib/mongoShellCommand.ts
+++ b/apps/desktop/src/lib/mongoShellCommand.ts
@@ -22,10 +22,7 @@ export interface MongoGetIndexesCommand {
collection: string;
}
-export type MongoWriteCommand =
- | { kind: "insert"; collection: string; docsJson: string }
- | { kind: "update"; collection: string; filter: string; update: string; many: boolean }
- | { kind: "delete"; collection: string; filter: string; many: boolean };
+export type MongoWriteCommand = { kind: "insert"; collection: string; docsJson: string } | { kind: "update"; collection: string; filter: string; update: string; many: boolean } | { kind: "delete"; collection: string; filter: string; many: boolean };
export interface MongoAggregateSafetyOptions {
allowWrites?: boolean;
@@ -149,9 +146,7 @@ export function parseMongoWriteCommand(input: string): MongoWriteCommand | null
if (!args || args.length !== 1) return null;
const docs = normalizeJsonArgument(args[0]);
if (!docs) return null;
- return Array.isArray(JSON.parse(docs))
- ? { kind: "insert", collection: insertMany.collection, docsJson: docs }
- : null;
+ return Array.isArray(JSON.parse(docs)) ? { kind: "insert", collection: insertMany.collection, docsJson: docs } : null;
}
for (const method of ["updateOne", "updateMany"] as const) {
@@ -193,10 +188,7 @@ export function mongoAggregateWriteStage(pipelineJson: string): "$out" | "$merge
return null;
}
-export function evaluateMongoAggregateSafety(
- command: MongoAggregateCommand,
- options: MongoAggregateSafetyOptions,
-): { allowed: boolean; reason?: string } {
+export function evaluateMongoAggregateSafety(command: MongoAggregateCommand, options: MongoAggregateSafetyOptions): { allowed: boolean; reason?: string } {
const writeStage = mongoAggregateWriteStage(command.pipeline);
if (!writeStage) return { allowed: true };
if (!options.allowWrites) {
@@ -274,14 +266,7 @@ export function mongoIndexesToQueryResult(
): QueryResult {
return {
columns: ["name", "columns", "unique", "primary", "type", "filter"],
- rows: indexes.map((index) => [
- index.name,
- index.columns.join(", "),
- index.is_unique,
- index.is_primary,
- index.index_type ?? null,
- index.filter ?? null,
- ]),
+ rows: indexes.map((index) => [index.name, index.columns.join(", "), index.is_unique, index.is_primary, index.index_type ?? null, index.filter ?? null]),
affected_rows: indexes.length,
execution_time_ms: Math.max(0, Math.round(executionTimeMs)),
};
@@ -296,10 +281,7 @@ function parseFindTarget(source: string): { collection: string; findCallIndex: n
return null;
}
-function parseCollectionMethodTarget(
- source: string,
- method: string,
-): { collection: string; methodCallIndex: number } | null {
+function parseCollectionMethodTarget(source: string, method: string): { collection: string; methodCallIndex: number } | null {
const escapedMethod = escapeRegExp(method);
const direct = new RegExp(`^db\\.([A-Za-z_$][\\w$]*)\\.${escapedMethod}\\s*\\(`).exec(source);
if (direct) {
@@ -309,9 +291,7 @@ function parseCollectionMethodTarget(
};
}
- const getCollection = new RegExp(
- `^db\\.getCollection\\s*\\(\\s*(["'])(.*?)\\1\\s*\\)\\.${escapedMethod}\\s*\\(`,
- ).exec(source);
+ const getCollection = new RegExp(`^db\\.getCollection\\s*\\(\\s*(["'])(.*?)\\1\\s*\\)\\.${escapedMethod}\\s*\\(`).exec(source);
if (getCollection) {
return {
collection: getCollection[2],
@@ -325,9 +305,7 @@ function parseCollectionMethodTarget(
function normalizeJsonArgument(value: string): string | null {
const trimmed = value.trim();
if (!trimmed) return "{}";
- const preprocessed = quoteUnquotedObjectKeys(
- convertSingleQuotedStrings(trimmed.replace(/ObjectId\s*\(\s*["']([^"']+)["']\s*\)/g, '{"$oid":"$1"}')),
- );
+ const preprocessed = quoteUnquotedObjectKeys(convertSingleQuotedStrings(trimmed.replace(/ObjectId\s*\(\s*["']([^"']+)["']\s*\)/g, '{"$oid":"$1"}')));
try {
JSON.parse(preprocessed);
return preprocessed;
diff --git a/apps/desktop/src/lib/navicatImport.ts b/apps/desktop/src/lib/navicatImport.ts
index 399732f973..1beec96ec3 100644
--- a/apps/desktop/src/lib/navicatImport.ts
+++ b/apps/desktop/src/lib/navicatImport.ts
@@ -151,27 +151,14 @@ async function parseConnection(node: ParsedNode): Promise<ConnectionConfig | nul
const profile = inferProfile(rawType, node.tag, port);
if (!profile) {
const name = getAny(node.values, ["name", "connectionName", "connName", "caption", "title"]) || "(unnamed)";
- console.warn(
- `[Navicat Import] 跳过无法识别类型的连接: "${name}" (type="${rawType}", tag="${node.tag}", port=${port ?? "N/A"})`,
- );
+ console.warn(`[Navicat Import] 跳过无法识别类型的连接: "${name}" (type="${rawType}", tag="${node.tag}", port=${port ?? "N/A"})`);
return null;
}
- const name =
- getAny(node.values, ["name", "connectionName", "connName", "caption", "title"]) ||
- getAny(node.values, ["host", "server", "hostname"]) ||
- profile.label;
- const host =
- getAny(node.values, ["host", "server", "hostname", "serverHost", "address"]) ||
- getAny(node.values, ["databaseFile", "filename", "path", "databasePath"]) ||
- (profile.dbType === "sqlite" ? "" : "127.0.0.1");
+ const name = getAny(node.values, ["name", "connectionName", "connName", "caption", "title"]) || getAny(node.values, ["host", "server", "hostname"]) || profile.label;
+ const host = getAny(node.values, ["host", "server", "hostname", "serverHost", "address"]) || getAny(node.values, ["databaseFile", "filename", "path", "databasePath"]) || (profile.dbType === "sqlite" ? "" : "127.0.0.1");
const database = getAny(node.values, ["database", "databaseName", "initialDatabase", "serviceName", "sid", "schema"]);
- const oracleConnectionType =
- profile.dbType === "oracle" && getAny(node.values, ["sid"])
- ? "sid"
- : profile.dbType === "oracle"
- ? "service_name"
- : undefined;
+ const oracleConnectionType = profile.dbType === "oracle" && getAny(node.values, ["sid"]) ? "sid" : profile.dbType === "oracle" ? "service_name" : undefined;
const username = getAny(node.values, ["user", "username", "userName", "uid"]) || profile.user;
const password = await decryptNavicatPassword(getAny(node.values, ["password"]));
diff --git a/apps/desktop/src/lib/newQueryContext.ts b/apps/desktop/src/lib/newQueryContext.ts
index 4981f9aa52..f60d6f544e 100644
--- a/apps/desktop/src/lib/newQueryContext.ts
+++ b/apps/desktop/src/lib/newQueryContext.ts
@@ -36,9 +36,7 @@ export function resolveNewQueryTarget(input: ResolveNewQueryTargetInput): NewQue
const secondaryTarget = targetFromContext(secondaryContext, input.connections);
if (secondaryTarget) return secondaryTarget;
- const activeConnection = input.activeConnectionId
- ? input.connections.find((connection) => connection.id === input.activeConnectionId)
- : undefined;
+ const activeConnection = input.activeConnectionId ? input.connections.find((connection) => connection.id === input.activeConnectionId) : undefined;
const fallbackConnection = activeConnection || input.connections[0];
return fallbackConnection
? {
@@ -49,10 +47,7 @@ export function resolveNewQueryTarget(input: ResolveNewQueryTargetInput): NewQue
: null;
}
-function targetFromContext(
- context: Pick<QueryTab | TreeNode, "connectionId" | "database" | "schema"> | undefined,
- connections: Pick<ConnectionConfig, "id" | "database">[],
-): NewQueryTarget | null {
+function targetFromContext(context: Pick<QueryTab | TreeNode, "connectionId" | "database" | "schema"> | undefined, connections: Pick<ConnectionConfig, "id" | "database">[]): NewQueryTarget | null {
if (!context?.connectionId) return null;
const connection = connections.find((item) => item.id === context.connectionId);
if (!connection) return null;
diff --git a/apps/desktop/src/lib/objectBrowserRows.ts b/apps/desktop/src/lib/objectBrowserRows.ts
index bd8ee8721c..4ce9f4ee0c 100644
--- a/apps/desktop/src/lib/objectBrowserRows.ts
+++ b/apps/desktop/src/lib/objectBrowserRows.ts
@@ -30,12 +30,7 @@ export function normalizeObjectBrowserType(type: string): ObjectBrowserRow["type
return "TABLE";
}
-export function buildObjectBrowserRows(options: {
- objects: ObjectInfo[];
- database: string;
- fallbackSchema: string;
- needsSchema: boolean;
-}): ObjectBrowserRow[] {
+export function buildObjectBrowserRows(options: { objects: ObjectInfo[]; database: string; fallbackSchema: string; needsSchema: boolean }): ObjectBrowserRow[] {
const seen = new Map<string, number>();
const rows = options.objects.flatMap((object) => {
const name = normalizeDatabaseObjectName(object.name);
@@ -77,10 +72,7 @@ function markPartitionRows(rows: ObjectBrowserRow[], fallbackSchema: string) {
if (row.type !== "TABLE") continue;
const parentName = row.partitionParentName || partitionParentName(row.name);
if (!parentName) continue;
- const parentKey = objectKey(
- { ...row, schema: row.partitionParentSchema || row.schema, name: parentName },
- fallbackSchema,
- );
+ const parentKey = objectKey({ ...row, schema: row.partitionParentSchema || row.schema, name: parentName }, fallbackSchema);
const parent = tableByKey.get(parentKey);
if (!parent || parent.id === row.id) continue;
row.partitionParentId = parent.id;
@@ -106,27 +98,16 @@ export function filterObjectBrowserRows(rows: ObjectBrowserRow[], query: string)
if (!q) return rows;
const regex = parseSlashDelimitedRegexQuery(query.trim());
if (regex) {
- return rows.filter((row) =>
- [row.name, row.type, row.comment].filter(Boolean).some((value) => regex.test(String(value))),
- );
+ return rows.filter((row) => [row.name, row.type, row.comment].filter(Boolean).some((value) => regex.test(String(value))));
}
- return rows.filter((row) =>
- [row.name, row.type, row.comment].filter(Boolean).some((value) => String(value).toLowerCase().includes(q)),
- );
+ return rows.filter((row) => [row.name, row.type, row.comment].filter(Boolean).some((value) => String(value).toLowerCase().includes(q)));
}
-export function sortObjectBrowserRows(
- rows: ObjectBrowserRow[],
- key: ObjectBrowserSortKey,
- direction: ObjectBrowserSortDirection,
-): ObjectBrowserRow[] {
+export function sortObjectBrowserRows(rows: ObjectBrowserRow[], key: ObjectBrowserSortKey, direction: ObjectBrowserSortDirection): ObjectBrowserRow[] {
const multiplier = direction === "asc" ? 1 : -1;
const compareNames = createDatabaseObjectNameComparator(rows.map((row) => row.name));
return [...rows].sort((left, right) => {
- const compared =
- key === "name"
- ? compareNames(left.name, right.name)
- : compareObjectBrowserValue(left[key], right[key], key, direction);
+ const compared = key === "name" ? compareNames(left.name, right.name) : compareObjectBrowserValue(left[key], right[key], key, direction);
if (compared !== 0) return compared * multiplier;
return compareNames(left.name, right.name);
});
@@ -145,12 +126,7 @@ export function formatObjectBrowserTimestamp(value: string | null | undefined):
.replace(/(?:Z|[+-]\d{2}(?::?\d{2})?)$/, "");
}
-function compareObjectBrowserValue(
- left: string | null | undefined,
- right: string | null | undefined,
- key: ObjectBrowserSortKey,
- direction: ObjectBrowserSortDirection,
-): number {
+function compareObjectBrowserValue(left: string | null | undefined, right: string | null | undefined, key: ObjectBrowserSortKey, direction: ObjectBrowserSortDirection): number {
const leftText = normalizeSortValue(left);
const rightText = normalizeSortValue(right);
if (!leftText && !rightText) return 0;
diff --git a/apps/desktop/src/lib/objectRenameSql.ts b/apps/desktop/src/lib/objectRenameSql.ts
index 8491d5bb56..7559b8804b 100644
--- a/apps/desktop/src/lib/objectRenameSql.ts
+++ b/apps/desktop/src/lib/objectRenameSql.ts
@@ -11,22 +11,11 @@ export interface BuildRenameObjectSqlOptions {
newName: string;
}
-const postgresLikeRenameTypes = new Set<DatabaseType>([
- "postgres",
- "redshift",
- "gaussdb",
- "kwdb",
- "kingbase",
- "highgo",
- "vastbase",
-]);
+const postgresLikeRenameTypes = new Set<DatabaseType>(["postgres", "redshift", "gaussdb", "kwdb", "kingbase", "highgo", "vastbase"]);
const oracleLikeRenameTypes = new Set<DatabaseType>(["oracle", "dameng"]);
-export function supportsObjectRename(
- databaseType: DatabaseType | undefined,
- objectType: RenameableObjectType,
-): boolean {
+export function supportsObjectRename(databaseType: DatabaseType | undefined, objectType: RenameableObjectType): boolean {
if (!databaseType) return false;
if (databaseType === "sqlserver") return true;
if (objectType === "PROCEDURE" || objectType === "FUNCTION") {
diff --git a/apps/desktop/src/lib/objectSourceEditor.ts b/apps/desktop/src/lib/objectSourceEditor.ts
index 7fac0cc876..c9c1a63556 100644
--- a/apps/desktop/src/lib/objectSourceEditor.ts
+++ b/apps/desktop/src/lib/objectSourceEditor.ts
@@ -15,34 +15,17 @@ export type BuildRoutineRenameObjectSourceInput = BuildEditableObjectSourceSqlIn
export type ObjectSourceSaveExecutionMode = "single" | "script";
-const postgresLikeRoutineRenameTypes = new Set<DatabaseType>([
- "postgres",
- "redshift",
- "gaussdb",
- "kwdb",
- "kingbase",
- "highgo",
- "vastbase",
-]);
+const postgresLikeRoutineRenameTypes = new Set<DatabaseType>(["postgres", "redshift", "gaussdb", "kwdb", "kingbase", "highgo", "vastbase"]);
const mysqlLikeRoutineRenameTypes = new Set<DatabaseType>(["mysql", "goldendb"]);
const oracleLikeRoutineRenameTypes = new Set<DatabaseType>(["oracle", "dameng"]);
-export function supportsSourceBackedRoutineRename(
- databaseType: DatabaseType | undefined,
- objectType: ObjectSourceKind,
-): boolean {
+export function supportsSourceBackedRoutineRename(databaseType: DatabaseType | undefined, objectType: ObjectSourceKind): boolean {
if (objectType !== "FUNCTION" && objectType !== "PROCEDURE") return false;
if (!databaseType || databaseType === "sqlserver") return false;
- return (
- mysqlLikeRoutineRenameTypes.has(databaseType) ||
- postgresLikeRoutineRenameTypes.has(databaseType) ||
- oracleLikeRoutineRenameTypes.has(databaseType)
- );
+ return mysqlLikeRoutineRenameTypes.has(databaseType) || postgresLikeRoutineRenameTypes.has(databaseType) || oracleLikeRoutineRenameTypes.has(databaseType);
}
-export function buildRoutineRenameObjectSourceStatements(
- input: BuildRoutineRenameObjectSourceInput,
-): Promise<string[]> {
+export function buildRoutineRenameObjectSourceStatements(input: BuildRoutineRenameObjectSourceInput): Promise<string[]> {
return api.buildRoutineRenameObjectSourceStatements(input);
}
diff --git a/apps/desktop/src/lib/openTabsPersistence.ts b/apps/desktop/src/lib/openTabsPersistence.ts
index 01d95fed75..1a86a656d0 100644
--- a/apps/desktop/src/lib/openTabsPersistence.ts
+++ b/apps/desktop/src/lib/openTabsPersistence.ts
@@ -61,29 +61,17 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
objectSource: tab.objectSource,
tableMeta: tab.tableMeta,
...(tab.mode !== "data" && tab.resultEvicted ? { resultEvicted: true } : {}),
- ...(tab.mode !== "data" && tab.resultEvicted && tab.resultCacheKey !== undefined
- ? { resultCacheKey: tab.resultCacheKey }
- : {}),
+ ...(tab.mode !== "data" && tab.resultEvicted && tab.resultCacheKey !== undefined ? { resultCacheKey: tab.resultCacheKey } : {}),
}));
}
function isSavedOpenTab(value: unknown): value is SavedOpenTab {
if (!value || typeof value !== "object") return false;
const tab = value as Record<string, unknown>;
- return (
- typeof tab.id === "string" &&
- typeof tab.title === "string" &&
- typeof tab.connectionId === "string" &&
- typeof tab.database === "string" &&
- typeof tab.sql === "string"
- );
+ return typeof tab.id === "string" && typeof tab.title === "string" && typeof tab.connectionId === "string" && typeof tab.database === "string" && typeof tab.sql === "string";
}
-export function restoreOpenTabsState(
- rawTabs: string | null,
- rawActiveTabId: string | null,
- options: { queryOnly?: boolean } = {},
-): RestoredOpenTabs {
+export function restoreOpenTabsState(rawTabs: string | null, rawActiveTabId: string | null, options: { queryOnly?: boolean } = {}): RestoredOpenTabs {
if (!rawTabs) return { tabs: [], activeTabId: null };
try {
diff --git a/apps/desktop/src/lib/paginationPageSize.ts b/apps/desktop/src/lib/paginationPageSize.ts
index 1a6ebb2295..4228c48e27 100644
--- a/apps/desktop/src/lib/paginationPageSize.ts
+++ b/apps/desktop/src/lib/paginationPageSize.ts
@@ -4,10 +4,7 @@ export const MIN_RESULT_PAGE_SIZE = 1;
export const MAX_RESULT_PAGE_SIZE = 100000;
export function normalizeResultPageSize(value: unknown, fallback = DEFAULT_RESULT_PAGE_SIZE): number {
- const fallbackValue =
- Number.isFinite(fallback) && fallback >= MIN_RESULT_PAGE_SIZE
- ? Math.min(Math.floor(fallback), MAX_RESULT_PAGE_SIZE)
- : DEFAULT_RESULT_PAGE_SIZE;
+ const fallbackValue = Number.isFinite(fallback) && fallback >= MIN_RESULT_PAGE_SIZE ? Math.min(Math.floor(fallback), MAX_RESULT_PAGE_SIZE) : DEFAULT_RESULT_PAGE_SIZE;
const parsed = Number(value);
if (!Number.isFinite(parsed)) return fallbackValue;
const rounded = Math.floor(parsed);
diff --git a/apps/desktop/src/lib/queryEditorTableDrop.ts b/apps/desktop/src/lib/queryEditorTableDrop.ts
index 1e15052da3..23e4e22915 100644
--- a/apps/desktop/src/lib/queryEditorTableDrop.ts
+++ b/apps/desktop/src/lib/queryEditorTableDrop.ts
@@ -21,13 +21,7 @@ export interface QueryEditorTableReferenceDropDetail {
let activeTableReferencePayload: QueryEditorTableReferencePayload | null = null;
-export function createTableReferencePayload(options: {
- connectionId?: string;
- database?: string;
- schema?: string;
- tableName?: string;
- databaseType?: DatabaseType;
-}): QueryEditorTableReferencePayload | null {
+export function createTableReferencePayload(options: { connectionId?: string; database?: string; schema?: string; tableName?: string; databaseType?: DatabaseType }): QueryEditorTableReferencePayload | null {
if (!options.connectionId || options.database == null || !options.tableName) return null;
const payload: QueryEditorTableReferencePayload = {
kind: "dbx-table-reference",
@@ -48,14 +42,7 @@ export function parseTableReferencePayload(value: string | undefined | null): Qu
if (!value) return null;
try {
const parsed = JSON.parse(value) as Partial<QueryEditorTableReferencePayload>;
- if (
- parsed.kind !== "dbx-table-reference" ||
- typeof parsed.connectionId !== "string" ||
- typeof parsed.database !== "string" ||
- typeof parsed.tableName !== "string" ||
- !parsed.connectionId ||
- !parsed.tableName
- ) {
+ if (parsed.kind !== "dbx-table-reference" || typeof parsed.connectionId !== "string" || typeof parsed.database !== "string" || typeof parsed.tableName !== "string" || !parsed.connectionId || !parsed.tableName) {
return null;
}
const payload: QueryEditorTableReferencePayload = {
@@ -98,10 +85,7 @@ export function createTableReferenceDropEvent(detail: QueryEditorTableReferenceD
return new CustomEvent<QueryEditorTableReferenceDropDetail>(DBX_TABLE_REFERENCE_DROP_EVENT, { detail });
}
-export function tableReferenceInsertText(
- payload: QueryEditorTableReferencePayload,
- fallbackDatabaseType?: DatabaseType,
-): string {
+export function tableReferenceInsertText(payload: QueryEditorTableReferencePayload, fallbackDatabaseType?: DatabaseType): string {
return qualifiedTableName({
databaseType: payload.databaseType ?? fallbackDatabaseType,
schema: payload.schema,
diff --git a/apps/desktop/src/lib/queryExecutionState.ts b/apps/desktop/src/lib/queryExecutionState.ts
index a6f194cbe5..c87a7fa709 100644
--- a/apps/desktop/src/lib/queryExecutionState.ts
+++ b/apps/desktop/src/lib/queryExecutionState.ts
@@ -8,8 +8,6 @@ export function canCancelQueryExecution(state: QueryExecutionStateLike): boolean
return state.isExecuting && !!state.executionId && !state.isCancelling;
}
-export function queryExecutionLabelKey(
- state: Pick<QueryExecutionStateLike, "isCancelling">,
-): "common.loading" | "common.stopping" {
+export function queryExecutionLabelKey(state: Pick<QueryExecutionStateLike, "isCancelling">): "common.loading" | "common.stopping" {
return state.isCancelling ? "common.stopping" : "common.loading";
}
diff --git a/apps/desktop/src/lib/queryTimeout.ts b/apps/desktop/src/lib/queryTimeout.ts
index 45e29f589c..7f90a869cb 100644
--- a/apps/desktop/src/lib/queryTimeout.ts
+++ b/apps/desktop/src/lib/queryTimeout.ts
@@ -2,9 +2,7 @@ import type { ConnectionConfig } from "@/types/database";
export const DEFAULT_QUERY_TIMEOUT_SECS = 30;
-export function queryTimeoutSecsForConnection(
- connection?: Pick<ConnectionConfig, "query_timeout_secs"> | null,
-): number {
+export function queryTimeoutSecsForConnection(connection?: Pick<ConnectionConfig, "query_timeout_secs"> | null): number {
const value = Number(connection?.query_timeout_secs);
return Number.isFinite(value) && value >= 0 ? value : DEFAULT_QUERY_TIMEOUT_SECS;
}
diff --git a/apps/desktop/src/lib/redisCommandSafety.ts b/apps/desktop/src/lib/redisCommandSafety.ts
index 781e74d258..4d12c1827b 100644
--- a/apps/desktop/src/lib/redisCommandSafety.ts
+++ b/apps/desktop/src/lib/redisCommandSafety.ts
@@ -1,20 +1,6 @@
export type RedisCommandSafety = "allowed" | "confirm" | "blocked";
-const BLOCKED_COMMANDS = new Set([
- "KEYS",
- "FLUSHALL",
- "SHUTDOWN",
- "CONFIG",
- "SAVE",
- "BGSAVE",
- "SLAVEOF",
- "REPLICAOF",
- "MIGRATE",
- "MODULE",
- "SCRIPT",
- "EVAL",
- "EVALSHA",
-]);
+const BLOCKED_COMMANDS = new Set(["KEYS", "FLUSHALL", "SHUTDOWN", "CONFIG", "SAVE", "BGSAVE", "SLAVEOF", "REPLICAOF", "MIGRATE", "MODULE", "SCRIPT", "EVAL", "EVALSHA"]);
const CONFIRM_COMMANDS = new Set([
"DEL",
diff --git a/apps/desktop/src/lib/redisJsonHighlighter.ts b/apps/desktop/src/lib/redisJsonHighlighter.ts
index 7e53ecb8b4..51dffa3819 100644
--- a/apps/desktop/src/lib/redisJsonHighlighter.ts
+++ b/apps/desktop/src/lib/redisJsonHighlighter.ts
@@ -15,9 +15,7 @@ type ShikiHighlighter = Awaited<ReturnType<typeof import("shiki/core").createHig
let highlighterPromise: Promise<ShikiHighlighter> | undefined;
-export async function createRedisShikiJsonHighlighter(
- options: RedisShikiJsonHighlighterOptions,
-): Promise<RedisJsonHighlighter> {
+export async function createRedisShikiJsonHighlighter(options: RedisShikiJsonHighlighterOptions): Promise<RedisJsonHighlighter> {
const highlighter = await getRedisShikiHighlighter();
return (content, appearance = options.appearance()) =>
highlighter.codeToHtml(content, {
@@ -33,15 +31,7 @@ function getRedisShikiHighlighter(): Promise<ShikiHighlighter> {
}
async function loadRedisShikiHighlighter(): Promise<ShikiHighlighter> {
- const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, json] = await Promise.all(
- [
- import("shiki/core"),
- import("shiki/engine/javascript"),
- import("shiki/themes/github-dark.mjs"),
- import("shiki/themes/github-light.mjs"),
- import("shiki/langs/json.mjs"),
- ],
- );
+ const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, json] = await Promise.all([import("shiki/core"), import("shiki/engine/javascript"), import("shiki/themes/github-dark.mjs"), import("shiki/themes/github-light.mjs"), import("shiki/langs/json.mjs")]);
return createHighlighterCore({
engine: createJavaScriptRegexEngine(),
diff --git a/apps/desktop/src/lib/redisKeyTree.ts b/apps/desktop/src/lib/redisKeyTree.ts
index f1414fe0d1..fb3892e4db 100644
--- a/apps/desktop/src/lib/redisKeyTree.ts
+++ b/apps/desktop/src/lib/redisKeyTree.ts
@@ -64,12 +64,7 @@ export function buildRedisKeyTree(keys: RedisKeyInfo[], db: number): RedisKeyTre
return sortRedisTreeNodes(root);
}
-function insertKeyIntoTree(
- root: RedisKeyTreeNode[],
- groupMap: Map<string, RedisKeyTreeGroupNode>,
- key: RedisKeyInfo,
- db: number,
-): void {
+function insertKeyIntoTree(root: RedisKeyTreeNode[], groupMap: Map<string, RedisKeyTreeGroupNode>, key: RedisKeyInfo, db: number): void {
const pathSegments = key.key_display.split(":");
if (pathSegments.length === 1) {
root.push({
@@ -139,11 +134,7 @@ function rebuildGroupMap(tree: RedisKeyTreeNode[]): Map<string, RedisKeyTreeGrou
return groupMap;
}
-export function mergeKeysIntoRedisKeyTree(
- existingTree: RedisKeyTreeNode[],
- newKeys: RedisKeyInfo[],
- db: number,
-): RedisKeyTreeNode[] {
+export function mergeKeysIntoRedisKeyTree(existingTree: RedisKeyTreeNode[], newKeys: RedisKeyInfo[], db: number): RedisKeyTreeNode[] {
if (existingTree.length === 0) return buildRedisKeyTree(newKeys, db);
const groupMap = rebuildGroupMap(existingTree);
@@ -199,11 +190,7 @@ export function collectRedisGroupKeyRaws(group: RedisKeyTreeGroupNode): string[]
return keyRaws;
}
-export function flattenVisibleRedisKeyTree(
- nodes: RedisKeyTreeNode[],
- expandedGroupIds: ReadonlySet<string>,
- depth = 0,
-): RedisKeyTreeRow[] {
+export function flattenVisibleRedisKeyTree(nodes: RedisKeyTreeNode[], expandedGroupIds: ReadonlySet<string>, depth = 0): RedisKeyTreeRow[] {
const rows: RedisKeyTreeRow[] = [];
for (const node of nodes) {
diff --git a/apps/desktop/src/lib/redisValuePresentation.ts b/apps/desktop/src/lib/redisValuePresentation.ts
index 3710e2dbb7..092b0c786e 100644
--- a/apps/desktop/src/lib/redisValuePresentation.ts
+++ b/apps/desktop/src/lib/redisValuePresentation.ts
@@ -24,18 +24,13 @@ export function canEditRedisMemberDetail(kind: RedisMemberDetailKind): boolean {
export function clampRedisMemberDetailSheetWidth(width: number, viewportWidth: number): number {
const viewportMax = Math.max(REDIS_MEMBER_DETAIL_SHEET_MIN_WIDTH, viewportWidth - 32);
- return Math.min(
- Math.min(REDIS_MEMBER_DETAIL_SHEET_MAX_WIDTH, viewportMax),
- Math.max(REDIS_MEMBER_DETAIL_SHEET_MIN_WIDTH, width),
- );
+ return Math.min(Math.min(REDIS_MEMBER_DETAIL_SHEET_MAX_WIDTH, viewportMax), Math.max(REDIS_MEMBER_DETAIL_SHEET_MIN_WIDTH, width));
}
export function formatRedisMemberDetail(value: unknown): RedisMemberDetail {
if (typeof value === "string") {
const json = parseRedisJsonDetail(value);
- return json
- ? { text: json.formattedText, rawText: value, format: "json", json }
- : { text: value, rawText: value, format: "text" };
+ return json ? { text: json.formattedText, rawText: value, format: "json", json } : { text: value, rawText: value, format: "text" };
}
try {
@@ -100,14 +95,11 @@ export function getRedisMemberSelectionKey(title: string, value: unknown): strin
export function highlightRedisJsonDetail(json: string): string {
const escaped = json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
- return escaped.replace(
- /("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g,
- (match) => {
- let cls = "json-number";
- if (match.startsWith('"')) cls = match.endsWith(":") ? "json-key" : "json-string";
- else if (match === "true" || match === "false") cls = "json-boolean";
- else if (match === "null") cls = "json-null";
- return `<span class="${cls}">${match}</span>`;
- },
- );
+ return escaped.replace(/("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g, (match) => {
+ let cls = "json-number";
+ if (match.startsWith('"')) cls = match.endsWith(":") ? "json-key" : "json-string";
+ else if (match === "true" || match === "false") cls = "json-boolean";
+ else if (match === "null") cls = "json-null";
+ return `<span class="${cls}">${match}</span>`;
+ });
}
diff --git a/apps/desktop/src/lib/routineExecutionSql.ts b/apps/desktop/src/lib/routineExecutionSql.ts
index 6a0303dcd2..11c1bcaac8 100644
--- a/apps/desktop/src/lib/routineExecutionSql.ts
+++ b/apps/desktop/src/lib/routineExecutionSql.ts
@@ -37,27 +37,16 @@ export function buildProcedureExecutionSql(options: BuildRoutineExecutionSqlOpti
return buildProcedureExecutionSqlFromValues({ ...options, parameters: [] });
}
-export function buildProcedureExecutionSqlFromValues(
- options: BuildRoutineExecutionSqlOptions & { parameters: RoutineParameterValue[] },
-): string {
+export function buildProcedureExecutionSqlFromValues(options: BuildRoutineExecutionSqlOptions & { parameters: RoutineParameterValue[] }): string {
const routine = qualifiedRoutineName(options);
const sortedParameters = [...options.parameters].sort((a, b) => a.ordinal - b.ordinal);
const values = sortedParameters.filter((parameter) => shouldIncludeParameter(parameter));
const useNamedArguments = shouldUseNamedArguments(options.databaseType, sortedParameters);
if (options.databaseType === "sqlserver") {
- const args = values
- .map(
- (parameter) =>
- `${sqlServerParameterName(parameter.name)} = ${routineParameterSqlValue(options.databaseType, parameter)}`,
- )
- .join(", ");
+ const args = values.map((parameter) => `${sqlServerParameterName(parameter.name)} = ${routineParameterSqlValue(options.databaseType, parameter)}`).join(", ");
return args ? `EXEC ${routine} ${args};` : `EXEC ${routine};`;
}
- if (
- options.databaseType === "oracle" ||
- options.databaseType === "dameng" ||
- options.databaseType === "oceanbase-oracle"
- ) {
+ if (options.databaseType === "oracle" || options.databaseType === "dameng" || options.databaseType === "oceanbase-oracle") {
return `BEGIN\n ${routine}(${values.map((parameter) => routineArgumentSql(options.databaseType, parameter, useNamedArguments)).join(", ")});\nEND;`;
}
return `CALL ${routine}(${values.map((parameter) => routineArgumentSql(options.databaseType, parameter, useNamedArguments)).join(", ")});`;
@@ -72,10 +61,7 @@ export function acceptsRoutineInput(parameter: Pick<RoutineParameterValue, "mode
return parameter.mode === "IN" || parameter.mode === "INOUT" || parameter.mode === "UNKNOWN";
}
-export function routineParameterSqlValue(
- databaseType: DatabaseType | undefined,
- parameter: RoutineParameterValue,
-): string {
+export function routineParameterSqlValue(databaseType: DatabaseType | undefined, parameter: RoutineParameterValue): string {
if (parameter.useNull) return "NULL";
const raw = parameter.value;
if (raw.trim() === "") return "NULL";
@@ -88,26 +74,14 @@ function sqlServerParameterName(name: string): string {
return name.startsWith("@") ? name : `@${name}`;
}
-function routineArgumentSql(
- databaseType: DatabaseType | undefined,
- parameter: RoutineParameterValue,
- useNamedArguments: boolean,
-): string {
+function routineArgumentSql(databaseType: DatabaseType | undefined, parameter: RoutineParameterValue, useNamedArguments: boolean): string {
const value = routineParameterSqlValue(databaseType, parameter);
if (!useNamedArguments) return value;
return `${quoteTableIdentifier(databaseType, parameter.name)} => ${value}`;
}
-function shouldUseNamedArguments(
- databaseType: DatabaseType | undefined,
- sortedParameters: RoutineParameterValue[],
-): boolean {
- if (
- databaseType !== "postgres" &&
- databaseType !== "oracle" &&
- databaseType !== "dameng" &&
- databaseType !== "oceanbase-oracle"
- ) {
+function shouldUseNamedArguments(databaseType: DatabaseType | undefined, sortedParameters: RoutineParameterValue[]): boolean {
+ if (databaseType !== "postgres" && databaseType !== "oracle" && databaseType !== "dameng" && databaseType !== "oceanbase-oracle") {
return false;
}
let omittedDefault = false;
@@ -126,9 +100,7 @@ function quoteSqlString(value: string): string {
}
function looksLikeNumericType(dataType: string): boolean {
- return /\b(bigint|int|integer|smallint|tinyint|serial|number|numeric|decimal|dec|float|double|real|money)\b/i.test(
- dataType,
- );
+ return /\b(bigint|int|integer|smallint|tinyint|serial|number|numeric|decimal|dec|float|double|real|money)\b/i.test(dataType);
}
function looksLikeBooleanType(dataType: string): boolean {
@@ -137,10 +109,8 @@ function looksLikeBooleanType(dataType: string): boolean {
function normalizeBooleanLiteral(value: string, databaseType: DatabaseType | undefined): string {
const normalized = value.trim().toLowerCase();
- const truthy =
- normalized === "true" || normalized === "t" || normalized === "yes" || normalized === "y" || normalized === "1";
- const falsy =
- normalized === "false" || normalized === "f" || normalized === "no" || normalized === "n" || normalized === "0";
+ const truthy = normalized === "true" || normalized === "t" || normalized === "yes" || normalized === "y" || normalized === "1";
+ const falsy = normalized === "false" || normalized === "f" || normalized === "no" || normalized === "n" || normalized === "0";
if (!truthy && !falsy) return quoteSqlString(value);
if (databaseType === "sqlserver") return truthy ? "1" : "0";
return truthy ? "TRUE" : "FALSE";
diff --git a/apps/desktop/src/lib/routineParameters.ts b/apps/desktop/src/lib/routineParameters.ts
index da7d4e2dc6..1699269e0c 100644
--- a/apps/desktop/src/lib/routineParameters.ts
+++ b/apps/desktop/src/lib/routineParameters.ts
@@ -21,28 +21,12 @@ export async function loadRoutineParameters(options: LoadRoutineParametersOption
}
export function supportsRoutineParameterMetadata(databaseType?: DatabaseType): boolean {
- return (
- databaseType === "postgres" ||
- databaseType === "mysql" ||
- databaseType === "doris" ||
- databaseType === "starrocks" ||
- databaseType === "sqlserver" ||
- databaseType === "oracle" ||
- databaseType === "dameng" ||
- databaseType === "oceanbase-oracle"
- );
+ return databaseType === "postgres" || databaseType === "mysql" || databaseType === "doris" || databaseType === "starrocks" || databaseType === "sqlserver" || databaseType === "oracle" || databaseType === "dameng" || databaseType === "oceanbase-oracle";
}
-export function routineParametersQuery(
- options: Pick<LoadRoutineParametersOptions, "database" | "databaseType" | "schema" | "routineName">,
-): string | null {
+export function routineParametersQuery(options: Pick<LoadRoutineParametersOptions, "database" | "databaseType" | "schema" | "routineName">): string | null {
if (!supportsRoutineParameterMetadata(options.databaseType)) return null;
- const effectiveSchema =
- options.schema ||
- (options.databaseType === "postgres" ? "public" : "") ||
- (options.databaseType === "mysql" || options.databaseType === "doris" || options.databaseType === "starrocks"
- ? options.database
- : "");
+ const effectiveSchema = options.schema || (options.databaseType === "postgres" ? "public" : "") || (options.databaseType === "mysql" || options.databaseType === "doris" || options.databaseType === "starrocks" ? options.database : "");
const schema = quoteSqlLiteral(effectiveSchema);
const name = quoteSqlLiteral(options.routineName);
if (options.databaseType === "postgres") {
@@ -112,11 +96,7 @@ WHERE o.type IN ('P', 'PC')
AND o.name = ${name}
ORDER BY p.parameter_id;`.trim();
}
- if (
- options.databaseType === "oracle" ||
- options.databaseType === "dameng" ||
- options.databaseType === "oceanbase-oracle"
- ) {
+ if (options.databaseType === "oracle" || options.databaseType === "dameng" || options.databaseType === "oceanbase-oracle") {
return `
SELECT
ARGUMENT_NAME AS name,
diff --git a/apps/desktop/src/lib/schemaTreeCache.ts b/apps/desktop/src/lib/schemaTreeCache.ts
index ebe7ae5124..f13329a51f 100644
--- a/apps/desktop/src/lib/schemaTreeCache.ts
+++ b/apps/desktop/src/lib/schemaTreeCache.ts
@@ -19,11 +19,7 @@ export function encodeSchemaTreeCache<T>(children: T, nowMs = Date.now()): Schem
};
}
-export function decodeSchemaTreeCache<T>(
- payload: unknown,
- nowMs = Date.now(),
- ttlMs = SCHEMA_TREE_CACHE_TTL_MS,
-): DecodedSchemaTreeCache<T> | null {
+export function decodeSchemaTreeCache<T>(payload: unknown, nowMs = Date.now(), ttlMs = SCHEMA_TREE_CACHE_TTL_MS): DecodedSchemaTreeCache<T> | null {
if (Array.isArray(payload)) {
return { children: payload as T, isStale: true };
}
diff --git a/apps/desktop/src/lib/shortcutRegistry.ts b/apps/desktop/src/lib/shortcutRegistry.ts
index dd24befc3f..7b7a5cdee7 100644
--- a/apps/desktop/src/lib/shortcutRegistry.ts
+++ b/apps/desktop/src/lib/shortcutRegistry.ts
@@ -140,19 +140,10 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
},
];
-export const DEFAULT_SHORTCUT_SETTINGS: ShortcutSettings = Object.fromEntries(
- SHORTCUT_DEFINITIONS.map((definition) => [definition.id, definition.defaultShortcut]),
-) as ShortcutSettings;
+export const DEFAULT_SHORTCUT_SETTINGS: ShortcutSettings = Object.fromEntries(SHORTCUT_DEFINITIONS.map((definition) => [definition.id, definition.defaultShortcut])) as ShortcutSettings;
export function normalizeShortcutSettings(settings?: Partial<ShortcutSettings>): ShortcutSettings {
- return Object.fromEntries(
- SHORTCUT_DEFINITIONS.map((definition) => [
- definition.id,
- typeof settings?.[definition.id] === "string" && settings[definition.id]?.trim()
- ? settings[definition.id]
- : definition.defaultShortcut,
- ]),
- ) as ShortcutSettings;
+ return Object.fromEntries(SHORTCUT_DEFINITIONS.map((definition) => [definition.id, typeof settings?.[definition.id] === "string" && settings[definition.id]?.trim() ? settings[definition.id] : definition.defaultShortcut])) as ShortcutSettings;
}
export function shortcutToCodeMirrorKey(shortcut: string): string {
@@ -174,16 +165,10 @@ export function formatShortcut(shortcut: string, platform = globalThis.navigator
.join("+");
}
-export function findShortcutConflict(
- actionId: ShortcutActionId,
- shortcut: string,
- shortcuts: ShortcutSettings,
-): ShortcutActionId | null {
+export function findShortcutConflict(actionId: ShortcutActionId, shortcut: string, shortcuts: ShortcutSettings): ShortcutActionId | null {
const definition = SHORTCUT_DEFINITIONS.find((item) => item.id === actionId);
if (!definition) return null;
- const conflict = SHORTCUT_DEFINITIONS.find(
- (item) => item.id !== actionId && item.scope === definition.scope && shortcuts[item.id] === shortcut,
- );
+ const conflict = SHORTCUT_DEFINITIONS.find((item) => item.id !== actionId && item.scope === definition.scope && shortcuts[item.id] === shortcut);
return conflict?.id ?? null;
}
diff --git a/apps/desktop/src/lib/sidebarActiveTabTarget.ts b/apps/desktop/src/lib/sidebarActiveTabTarget.ts
index fda77fb801..36b8b0c5cf 100644
--- a/apps/desktop/src/lib/sidebarActiveTabTarget.ts
+++ b/apps/desktop/src/lib/sidebarActiveTabTarget.ts
@@ -84,22 +84,12 @@ function schemaMatches(node: TreeNode, schema: string | undefined): boolean {
export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): boolean {
if (target.type === "mongo-collection") {
- return (
- node.type === "mongo-collection" &&
- node.connectionId === target.connectionId &&
- node.database === target.database &&
- node.label === target.collectionName
- );
+ return node.type === "mongo-collection" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.collectionName;
}
if (target.type === "query-context") {
if (target.schema) {
- return (
- node.type === "schema" &&
- node.connectionId === target.connectionId &&
- node.database === target.database &&
- node.label === target.schema
- );
+ return node.type === "schema" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.schema;
}
return node.type === "database" && node.connectionId === target.connectionId && node.label === target.database;
}
@@ -112,43 +102,21 @@ export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): b
return node.type === "saved-sql-file" && node.savedSqlId === target.savedSqlId;
}
- return (
- (node.type === "table" || node.type === "view") &&
- node.connectionId === target.connectionId &&
- node.database === target.database &&
- schemaMatches(node, target.schema) &&
- node.label === target.tableName
- );
+ return (node.type === "table" || node.type === "view") && node.connectionId === target.connectionId && node.database === target.database && schemaMatches(node, target.schema) && node.label === target.tableName;
}
-export function findSidebarNodeForActiveTab(
- tab: QueryTab | undefined | null,
- flatNodes: readonly FlatTreeNode[],
-): FlatTreeNode | null {
+export function findSidebarNodeForActiveTab(tab: QueryTab | undefined | null, flatNodes: readonly FlatTreeNode[]): FlatTreeNode | null {
const target = activeTabSidebarTarget(tab);
if (!target) return null;
return flatNodes.find((item) => matchesTarget(item.node, target)) ?? null;
}
-export function shouldScrollActiveSidebarSelection(options: {
- activeTabId: string | null | undefined;
- previousActiveTabId: string | null | undefined;
- autoSelectEnabled: boolean;
- previousAutoSelectEnabled: boolean | undefined;
-}): boolean {
+export function shouldScrollActiveSidebarSelection(options: { activeTabId: string | null | undefined; previousActiveTabId: string | null | undefined; autoSelectEnabled: boolean; previousAutoSelectEnabled: boolean | undefined }): boolean {
if (!options.autoSelectEnabled) return false;
- return (
- options.activeTabId !== options.previousActiveTabId ||
- (options.autoSelectEnabled && options.previousAutoSelectEnabled === false)
- );
+ return options.activeTabId !== options.previousActiveTabId || (options.autoSelectEnabled && options.previousAutoSelectEnabled === false);
}
-export function scrollTopForSidebarNode(options: {
- index: number;
- currentScrollTop: number;
- viewportHeight: number;
- rowHeight?: number;
-}): number {
+export function scrollTopForSidebarNode(options: { index: number; currentScrollTop: number; viewportHeight: number; rowHeight?: number }): number {
const rowHeight = options.rowHeight ?? SIDEBAR_TREE_ROW_HEIGHT;
if (options.index < 0 || options.viewportHeight <= 0) return options.currentScrollTop;
@@ -162,20 +130,13 @@ export function scrollTopForSidebarNode(options: {
return options.currentScrollTop;
}
-export function findNodePathForActiveTab(
- tab: QueryTab | undefined | null,
- treeNodes: readonly TreeNode[],
-): TreeNode[] | null {
+export function findNodePathForActiveTab(tab: QueryTab | undefined | null, treeNodes: readonly TreeNode[]): TreeNode[] | null {
const target = activeTabSidebarTarget(tab);
if (!target) return null;
return findPath(treeNodes, (node) => matchesTarget(node, target));
}
-function findPath(
- nodes: readonly TreeNode[],
- predicate: (node: TreeNode) => boolean,
- path: TreeNode[] = [],
-): TreeNode[] | null {
+function findPath(nodes: readonly TreeNode[], predicate: (node: TreeNode) => boolean, path: TreeNode[] = []): TreeNode[] | null {
for (const node of nodes) {
const currentPath = [...path, node];
if (predicate(node)) return currentPath;
diff --git a/apps/desktop/src/lib/sidebarConnectionSelection.ts b/apps/desktop/src/lib/sidebarConnectionSelection.ts
index a0cdb5b1a0..bd75fd627b 100644
--- a/apps/desktop/src/lib/sidebarConnectionSelection.ts
+++ b/apps/desktop/src/lib/sidebarConnectionSelection.ts
@@ -6,10 +6,7 @@ function isConnectionNode(node: TreeNode): node is ConnectionTreeNode {
return node.type === "connection" && !!node.connectionId;
}
-export function selectedConnectionDeleteTargets(
- currentNode: TreeNode,
- selectedNodes: TreeNode[],
-): ConnectionTreeNode[] {
+export function selectedConnectionDeleteTargets(currentNode: TreeNode, selectedNodes: TreeNode[]): ConnectionTreeNode[] {
if (!isConnectionNode(currentNode)) return [];
const selectedContainsCurrent = selectedNodes.some((node) => node.id === currentNode.id);
if (selectedNodes.length > 1 && selectedContainsCurrent && selectedNodes.every(isConnectionNode)) {
diff --git a/apps/desktop/src/lib/sidebarLayout.ts b/apps/desktop/src/lib/sidebarLayout.ts
index e0820952e0..2b66dd4da2 100644
--- a/apps/desktop/src/lib/sidebarLayout.ts
+++ b/apps/desktop/src/lib/sidebarLayout.ts
@@ -67,11 +67,7 @@ function orderPinnedFirst(nodes: TreeNode[]): TreeNode[] {
return [...pinned, ...unpinned];
}
-export function buildTreeNodesFromLayout(
- layout: SidebarLayout,
- connections: ConnectionConfig[],
- pinnedIds: Set<string>,
-): TreeNode[] {
+export function buildTreeNodesFromLayout(layout: SidebarLayout, connections: ConnectionConfig[], pinnedIds: Set<string>): TreeNode[] {
const configMap = new Map(connections.map((c) => [c.id, c]));
const groupMap = new Map(layout.groups.map((g) => [g.id, g]));
@@ -101,10 +97,7 @@ export function buildTreeNodesFromLayout(
return orderPinnedFirst(nodes);
}
-export function findConnectionLocation(
- layout: SidebarLayout,
- connectionId: string,
-): { entryIndex: number; groupId?: string; innerIndex?: number } | null {
+export function findConnectionLocation(layout: SidebarLayout, connectionId: string): { entryIndex: number; groupId?: string; innerIndex?: number } | null {
for (let i = 0; i < layout.order.length; i++) {
const entry = layout.order[i];
if (entry.type === "connection" && entry.id === connectionId) {
@@ -132,11 +125,7 @@ function removeConnectionFromLayout(order: SidebarOrderEntry[], connectionId: st
.filter(Boolean) as SidebarOrderEntry[];
}
-export function moveConnectionToGroup(
- layout: SidebarLayout,
- connectionId: string,
- targetGroupId: string | null,
-): SidebarLayout {
+export function moveConnectionToGroup(layout: SidebarLayout, connectionId: string, targetGroupId: string | null): SidebarLayout {
const order = removeConnectionFromLayout([...layout.order], connectionId);
if (targetGroupId) {
@@ -153,12 +142,7 @@ export function moveConnectionToGroup(
export type DropPosition = "before" | "after" | "inside";
-export function reorderEntry(
- layout: SidebarLayout,
- draggedId: string,
- targetId: string,
- position: DropPosition,
-): SidebarLayout {
+export function reorderEntry(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
if (draggedId === targetId) return layout;
const isDraggedGroup = layout.order.some((e) => e.type === "group" && e.id === draggedId);
@@ -175,21 +159,14 @@ export function reorderEntry(
return reorderConnection(layout, draggedId, targetId, position);
}
-function reorderGroup(
- layout: SidebarLayout,
- draggedId: string,
- targetId: string,
- position: DropPosition,
-): SidebarLayout {
+function reorderGroup(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
const order = [...layout.order];
const draggedIndex = order.findIndex((e) => e.type === "group" && e.id === draggedId);
if (draggedIndex < 0) return layout;
const [dragged] = order.splice(draggedIndex, 1);
- let targetIndex = order.findIndex(
- (e) => (e.type === "group" && e.id === targetId) || (e.type === "connection" && e.id === targetId),
- );
+ let targetIndex = order.findIndex((e) => (e.type === "group" && e.id === targetId) || (e.type === "connection" && e.id === targetId));
if (targetIndex < 0) {
order.push(dragged);
} else {
@@ -200,12 +177,7 @@ function reorderGroup(
return { ...layout, order };
}
-function reorderConnection(
- layout: SidebarLayout,
- draggedId: string,
- targetId: string,
- position: DropPosition,
-): SidebarLayout {
+function reorderConnection(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
const order = removeConnectionFromLayout([...layout.order], draggedId);
const targetLoc = findConnectionLocation({ ...layout, order }, targetId);
@@ -281,20 +253,12 @@ export function removeConnectionFromSidebarLayout(layout: SidebarLayout, connect
return { ...layout, order: removeConnectionFromLayout(layout.order, connectionId) };
}
-export function appendConnectionToLayout(
- layout: SidebarLayout,
- connectionId: string,
- groupId?: string | null,
-): SidebarLayout {
+export function appendConnectionToLayout(layout: SidebarLayout, connectionId: string, groupId?: string | null): SidebarLayout {
if (groupId && layout.groups.some((group) => group.id === groupId)) {
return {
...layout,
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, collapsed: false } : group)),
- order: layout.order.map((entry) =>
- entry.type === "group" && entry.id === groupId
- ? { ...entry, connectionIds: [...entry.connectionIds, connectionId] }
- : entry,
- ),
+ order: layout.order.map((entry) => (entry.type === "group" && entry.id === groupId ? { ...entry, connectionIds: [...entry.connectionIds, connectionId] } : entry)),
};
}
return { ...layout, order: [...layout.order, { type: "connection" as const, id: connectionId }] };
diff --git a/apps/desktop/src/lib/sidebarNodeOrdering.ts b/apps/desktop/src/lib/sidebarNodeOrdering.ts
index 0089920c82..33f570d854 100644
--- a/apps/desktop/src/lib/sidebarNodeOrdering.ts
+++ b/apps/desktop/src/lib/sidebarNodeOrdering.ts
@@ -8,9 +8,7 @@ function sortByLabel(nodes: readonly TreeNode[]): TreeNode[] {
function sortRecursive(node: TreeNode, databaseType?: DatabaseType): TreeNode {
const children = node.children ? sortSidebarTreeChildrenForParent(node, node.children, databaseType) : node.children;
- const hiddenChildren = node.hiddenChildren
- ? sortSidebarTreeChildrenForParent(node, node.hiddenChildren, databaseType)
- : node.hiddenChildren;
+ const hiddenChildren = node.hiddenChildren ? sortSidebarTreeChildrenForParent(node, node.hiddenChildren, databaseType) : node.hiddenChildren;
if (children === node.children && hiddenChildren === node.hiddenChildren) return node;
return {
...node,
@@ -19,11 +17,7 @@ function sortRecursive(node: TreeNode, databaseType?: DatabaseType): TreeNode {
};
}
-export function sortSidebarTreeChildrenForParent(
- parent: Pick<TreeNode, "type">,
- children: readonly TreeNode[],
- databaseType?: DatabaseType,
-): TreeNode[] {
+export function sortSidebarTreeChildrenForParent(parent: Pick<TreeNode, "type">, children: readonly TreeNode[], databaseType?: DatabaseType): TreeNode[] {
const normalized = children.map((child) => sortRecursive(child, databaseType));
if (parent.type === "mongo-db") {
@@ -33,9 +27,7 @@ export function sortSidebarTreeChildrenForParent(
if (parent.type === "connection") {
const savedSqlNodes = normalized.filter((child) => child.type === "saved-sql-root");
const userAdminNodes = normalized.filter((child) => child.type === "user-admin");
- const regularChildren = normalized.filter(
- (child) => child.type !== "user-admin" && child.type !== "saved-sql-root",
- );
+ const regularChildren = normalized.filter((child) => child.type !== "user-admin" && child.type !== "saved-sql-root");
const withConnectionUtilityOrder = (children: TreeNode[]) => [...savedSqlNodes, ...children, ...userAdminNodes];
if (databaseType === "mongodb" || databaseType === "elasticsearch") {
diff --git a/apps/desktop/src/lib/sidebarRenameFocus.ts b/apps/desktop/src/lib/sidebarRenameFocus.ts
index 6400f4ed2c..8e1b9df8b0 100644
--- a/apps/desktop/src/lib/sidebarRenameFocus.ts
+++ b/apps/desktop/src/lib/sidebarRenameFocus.ts
@@ -9,10 +9,7 @@ const scheduleAnimationFrame: FrameScheduler = (callback) => {
return setTimeout(callback, 0) as unknown as number;
};
-export function focusSidebarRenameInput(
- getInput: () => RenameInput | undefined,
- schedule: FrameScheduler = scheduleAnimationFrame,
-) {
+export function focusSidebarRenameInput(getInput: () => RenameInput | undefined, schedule: FrameScheduler = scheduleAnimationFrame) {
schedule(() => {
const input = getInput();
input?.focus();
diff --git a/apps/desktop/src/lib/sidebarSearch.ts b/apps/desktop/src/lib/sidebarSearch.ts
index ff4de14bdb..cb9ab8fe1e 100644
--- a/apps/desktop/src/lib/sidebarSearch.ts
+++ b/apps/desktop/src/lib/sidebarSearch.ts
@@ -1,13 +1,6 @@
import { parseSlashDelimitedRegexQuery } from "@/lib/searchPattern";
-export type SidebarSearchMatchKind =
- | "exact"
- | "prefix"
- | "word-prefix"
- | "substring"
- | "abbreviation"
- | "fuzzy"
- | "regex";
+export type SidebarSearchMatchKind = "exact" | "prefix" | "word-prefix" | "substring" | "abbreviation" | "fuzzy" | "regex";
export interface SidebarSearchMatch {
kind: SidebarSearchMatchKind;
diff --git a/apps/desktop/src/lib/sidebarSearchTree.ts b/apps/desktop/src/lib/sidebarSearchTree.ts
index 5ee91e8cc8..f5c880de28 100644
--- a/apps/desktop/src/lib/sidebarSearchTree.ts
+++ b/apps/desktop/src/lib/sidebarSearchTree.ts
@@ -14,28 +14,16 @@ function normalizedLabel(node: TreeNode): string {
return normalized;
}
-export function filterSidebarTree(
- nodes: TreeNode[],
- query: string,
- collapsedIds: ReadonlySet<string>,
- searchableNodeTypes?: ReadonlySet<TreeNodeType>,
-): TreeNode[] {
+export function filterSidebarTree(nodes: TreeNode[], query: string, collapsedIds: ReadonlySet<string>, searchableNodeTypes?: ReadonlySet<TreeNodeType>): TreeNode[] {
return filterSidebarTreeWithMatcher(nodes, createSidebarLabelMatcher(query), collapsedIds, searchableNodeTypes);
}
-function filterSidebarTreeWithMatcher(
- nodes: TreeNode[],
- matchLabel: SidebarLabelMatcher,
- collapsedIds: ReadonlySet<string>,
- searchableNodeTypes?: ReadonlySet<TreeNodeType>,
-): TreeNode[] {
+function filterSidebarTreeWithMatcher(nodes: TreeNode[], matchLabel: SidebarLabelMatcher, collapsedIds: ReadonlySet<string>, searchableNodeTypes?: ReadonlySet<TreeNodeType>): TreeNode[] {
const filteredNodes: { node: TreeNode; score: number }[] = [];
for (const node of nodes) {
if (node.type === "object-browser" && node.hiddenChildren) {
- const matches = node.hiddenChildren
- .map((child) => ({ node: child, score: matchLabel(normalizedLabel(child))?.score ?? 0 }))
- .filter((match) => match.score > 0);
+ const matches = node.hiddenChildren.map((child) => ({ node: child, score: matchLabel(normalizedLabel(child))?.score ?? 0 })).filter((match) => match.score > 0);
filteredNodes.push(...matches);
continue;
}
@@ -44,11 +32,7 @@ function filterSidebarTreeWithMatcher(
const canSelfMatch = !searchableNodeTypes || searchableNodeTypes.has(node.type);
const selfMatch = canSelfMatch ? matchLabel(label) : null;
const preservesSubtree = !!selfMatch && preserveMatchedSubtreeTypes.has(node.type);
- const filteredChildren = preservesSubtree
- ? node.children
- : node.children
- ? filterSidebarTreeWithMatcher(node.children, matchLabel, collapsedIds, searchableNodeTypes)
- : undefined;
+ const filteredChildren = preservesSubtree ? node.children : node.children ? filterSidebarTreeWithMatcher(node.children, matchLabel, collapsedIds, searchableNodeTypes) : undefined;
if (selfMatch || (filteredChildren && filteredChildren.length > 0)) {
if (!node.children) {
@@ -71,10 +55,7 @@ function filterSidebarTreeWithMatcher(
return filteredNodes.map((match) => match.node);
}
-export function filterSidebarSearchRootsByConnectionState(
- nodes: TreeNode[],
- connectedIds: ReadonlySet<string>,
-): TreeNode[] {
+export function filterSidebarSearchRootsByConnectionState(nodes: TreeNode[], connectedIds: ReadonlySet<string>): TreeNode[] {
return nodes.filter((node) => {
if (node.type === "connection-group" || node.type === "connection") return true;
return node.connectionId ? connectedIds.has(node.connectionId) : true;
diff --git a/apps/desktop/src/lib/sidebarTableNameDisplay.ts b/apps/desktop/src/lib/sidebarTableNameDisplay.ts
index 266187f846..ce2746ae49 100644
--- a/apps/desktop/src/lib/sidebarTableNameDisplay.ts
+++ b/apps/desktop/src/lib/sidebarTableNameDisplay.ts
@@ -1,10 +1,5 @@
export function normalizeSidebarHiddenTablePrefixes(value: unknown): string[] {
- const rawPrefixes =
- typeof value === "string"
- ? value.split(/\r?\n/)
- : Array.isArray(value)
- ? value.filter((item) => typeof item === "string")
- : [];
+ const rawPrefixes = typeof value === "string" ? value.split(/\r?\n/) : Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
const seen = new Set<string>();
const prefixes: string[] = [];
@@ -19,8 +14,6 @@ export function normalizeSidebarHiddenTablePrefixes(value: unknown): string[] {
}
export function sidebarDisplayTableName(name: string, prefixes: readonly string[]): string {
- const prefix = [...prefixes]
- .sort((a, b) => b.length - a.length)
- .find((item) => name.startsWith(item) && name.length > item.length);
+ const prefix = [...prefixes].sort((a, b) => b.length - a.length).find((item) => name.startsWith(item) && name.length > item.length);
return prefix ? `...${name.slice(prefix.length)}` : name;
}
diff --git a/apps/desktop/src/lib/sidebarTreeItemLayout.ts b/apps/desktop/src/lib/sidebarTreeItemLayout.ts
index f92000ba4b..a53840a5e1 100644
--- a/apps/desktop/src/lib/sidebarTreeItemLayout.ts
+++ b/apps/desktop/src/lib/sidebarTreeItemLayout.ts
@@ -1,20 +1,6 @@
import type { TreeNodeType } from "@/types/database";
-const leafTypes: Set<TreeNodeType> = new Set([
- "column",
- "index",
- "fkey",
- "trigger",
- "procedure",
- "function",
- "package",
- "package-body",
- "object-browser",
- "redis-db",
- "mongo-collection",
- "user-admin",
- "saved-sql-file",
-]);
+const leafTypes: Set<TreeNodeType> = new Set(["column", "index", "fkey", "trigger", "procedure", "function", "package", "package-body", "object-browser", "redis-db", "mongo-collection", "user-admin", "saved-sql-file"]);
const fullWidthLabelTypes: Set<TreeNodeType> = new Set(["table", "view", "mongo-collection"]);
diff --git a/apps/desktop/src/lib/sidebarTreeSelection.ts b/apps/desktop/src/lib/sidebarTreeSelection.ts
index 6ae95529bf..164cb931d5 100644
--- a/apps/desktop/src/lib/sidebarTreeSelection.ts
+++ b/apps/desktop/src/lib/sidebarTreeSelection.ts
@@ -6,24 +6,14 @@ export function selectedTreeNodesInVisibleOrder(visibleNodes: TreeNode[], select
return visibleNodes.filter((node) => ids.has(node.id));
}
-export function treeSelectionRangeIdsByIndex(
- visibleNodes: TreeNode[],
- currentIndex: number,
- anchorIndex: number,
- currentId?: string,
-): string[] {
+export function treeSelectionRangeIdsByIndex(visibleNodes: TreeNode[], currentIndex: number, anchorIndex: number, currentId?: string): string[] {
if (anchorIndex < 0 || currentIndex < 0) return currentId ? [currentId] : [];
const start = Math.min(anchorIndex, currentIndex);
const end = Math.max(anchorIndex, currentIndex);
return visibleNodes.slice(start, end + 1).map((node) => node.id);
}
-export function treeSelectionRangeIds(
- visibleNodes: TreeNode[],
- currentId: string,
- anchorId?: string | null,
- selectedId?: string | null,
-): string[] {
+export function treeSelectionRangeIds(visibleNodes: TreeNode[], currentId: string, anchorId?: string | null, selectedId?: string | null): string[] {
const anchor = anchorId || selectedId || currentId;
const anchorIndex = visibleNodes.findIndex((node) => node.id === anchor);
const currentIndex = visibleNodes.findIndex((node) => node.id === currentId);
diff --git a/apps/desktop/src/lib/sqlAnalysis.ts b/apps/desktop/src/lib/sqlAnalysis.ts
index 341ed6ded6..3e6e591984 100644
--- a/apps/desktop/src/lib/sqlAnalysis.ts
+++ b/apps/desktop/src/lib/sqlAnalysis.ts
@@ -1,17 +1,5 @@
// Binary column types that should not be edited inline
-export const BINARY_TYPES = new Set([
- "blob",
- "clob",
- "bytea",
- "varbinary",
- "binary",
- "image",
- "longblob",
- "mediumblob",
- "tinyblob",
- "blob sub_type 2004",
- "blob sub_type 2005",
-]);
+export const BINARY_TYPES = new Set(["blob", "clob", "bytea", "varbinary", "binary", "image", "longblob", "mediumblob", "tinyblob", "blob sub_type 2004", "blob sub_type 2005"]);
export function isBinaryType(dataType: string): boolean {
const lower = dataType
@@ -38,23 +26,9 @@ export interface EditableQueryColumn {
expression: string;
}
-export type QueryEditabilityReason =
- | "not-select"
- | "cte"
- | "set-operation"
- | "aggregation"
- | "external-source"
- | "complex-source"
- | "computed-columns"
- | "no-table"
- | "no-primary-key"
- | "primary-key-not-returned"
- | "aliased-columns"
- | "metadata-unavailable";
-
-export type QueryEditability =
- | { editable: true; analysis: EditableQueryInfo }
- | { editable: false; reason: QueryEditabilityReason };
+export type QueryEditabilityReason = "not-select" | "cte" | "set-operation" | "aggregation" | "external-source" | "complex-source" | "computed-columns" | "no-table" | "no-primary-key" | "primary-key-not-returned" | "aliased-columns" | "metadata-unavailable";
+
+export type QueryEditability = { editable: true; analysis: EditableQueryInfo } | { editable: false; reason: QueryEditabilityReason };
/**
* Parse a SELECT statement to determine if it's editable.
@@ -214,9 +188,7 @@ function isSelectStar(body: string, alias: string | undefined): boolean {
return new RegExp(`^${escapeRegExp(alias)}\\s*\\.\\s*\\*$`, "i").test(trimmed);
}
-function parseFromSource(
- body: string,
-): { schema?: string; schemaQuoted?: boolean; tableName: string; tableNameQuoted?: boolean; alias?: string } | null {
+function parseFromSource(body: string): { schema?: string; schemaQuoted?: boolean; tableName: string; tableNameQuoted?: boolean; alias?: string } | null {
if (!body || /[,()]/.test(body) || /\bJOIN\b/i.test(body)) return null;
const ident = parseQualifiedIdentifier(body);
if (!ident || ident.parts.length < 1 || ident.parts.length > 2) return null;
@@ -240,9 +212,7 @@ function isExternalFromSource(body: string): boolean {
return /^'(?:''|[^'])*'(?:\s+(?:AS\s+)?[A-Za-z_][\w$]*)?$/i.test(trimmed) || /^[A-Za-z_][\w$]*\s*\(/.test(trimmed);
}
-function parseQualifiedIdentifier(
- text: string,
-): { parts: string[]; quoted: boolean[]; end: number; rest: string; done: boolean } | null {
+function parseQualifiedIdentifier(text: string): { parts: string[]; quoted: boolean[]; end: number; rest: string; done: boolean } | null {
const parts: string[] = [];
const quoted: boolean[] = [];
let pos = 0;
@@ -341,15 +311,9 @@ function escapeRegExp(value: string): string {
* Check if all primary key columns are present in the result set columns.
* Comparison is case-insensitive.
*/
-export function allPrimaryKeysPresent(
- primaryKeys: string[],
- resultColumns: string[],
- analysis?: EditableQueryInfo,
-): boolean {
+export function allPrimaryKeysPresent(primaryKeys: string[], resultColumns: string[], analysis?: EditableQueryInfo): boolean {
if (analysis && !analysis.selectStar) {
- const sourceColumns = new Set(
- analysis.columns.flatMap((column) => (column.sourceName ? [column.sourceName.toLowerCase()] : [])),
- );
+ const sourceColumns = new Set(analysis.columns.flatMap((column) => (column.sourceName ? [column.sourceName.toLowerCase()] : [])));
return primaryKeys.every((pk) => sourceColumns.has(pk.toLowerCase()));
}
const colSet = new Set(resultColumns.map((c) => c.toLowerCase()));
@@ -365,14 +329,9 @@ export function allEditableColumnsWriteable(analysis: EditableQueryInfo, resultC
});
}
-export function sourceColumnsForResult(
- analysis: EditableQueryInfo,
- resultColumns: string[],
-): Array<string | undefined> | undefined {
+export function sourceColumnsForResult(analysis: EditableQueryInfo, resultColumns: string[]): Array<string | undefined> | undefined {
if (analysis.selectStar) return undefined;
const sourceByResult = new Map(analysis.columns.map((column) => [column.resultName.toLowerCase(), column]));
const sourceColumns = resultColumns.map((resultColumn) => sourceByResult.get(resultColumn.toLowerCase())?.sourceName);
- return resultColumns.every((resultColumn) => sourceByResult.has(resultColumn.toLowerCase()))
- ? sourceColumns
- : undefined;
+ return resultColumns.every((resultColumn) => sourceByResult.has(resultColumn.toLowerCase())) ? sourceColumns : undefined;
}
diff --git a/apps/desktop/src/lib/sqlCompletion.ts b/apps/desktop/src/lib/sqlCompletion.ts
index 3b603a6daa..68f1ae78ef 100644
--- a/apps/desktop/src/lib/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sqlCompletion.ts
@@ -416,36 +416,9 @@ const MYSQL_SQL_KEYWORDS = [
"DATE_FORMAT",
];
-const SQLITE_SQL_KEYWORDS = [
- "AUTOINCREMENT",
- "INTEGER",
- "BLOB",
- "BOOLEAN",
- "WITHOUT ROWID",
- "VACUUM",
- "PRAGMA",
- "JSON_EXTRACT",
- "JSON_SET",
- "STRFTIME",
-];
+const SQLITE_SQL_KEYWORDS = ["AUTOINCREMENT", "INTEGER", "BLOB", "BOOLEAN", "WITHOUT ROWID", "VACUUM", "PRAGMA", "JSON_EXTRACT", "JSON_SET", "STRFTIME"];
-const SQLSERVER_SQL_KEYWORDS = [
- "TOP",
- "IDENTITY",
- "UNIQUEIDENTIFIER",
- "NVARCHAR",
- "DATETIME2",
- "DATETIMEOFFSET",
- "BIT",
- "GO",
- "MERGE",
- "OUTPUT",
- "TRY_CAST",
- "TRY_CONVERT",
- "OPENJSON",
- "JSON_VALUE",
- "JSON_QUERY",
-];
+const SQLSERVER_SQL_KEYWORDS = ["TOP", "IDENTITY", "UNIQUEIDENTIFIER", "NVARCHAR", "DATETIME2", "DATETIMEOFFSET", "BIT", "GO", "MERGE", "OUTPUT", "TRY_CAST", "TRY_CONVERT", "OPENJSON", "JSON_VALUE", "JSON_QUERY"];
const DATABASE_SQL_KEYWORDS: Partial<Record<DatabaseType, string[]>> = {
mysql: MYSQL_SQL_KEYWORDS,
@@ -595,16 +568,7 @@ const DATA_TYPE_KEYWORDS = new Set([
]);
// Window functions that should use OVER() completion
-const WINDOW_FUNCTIONS = new Set([
- "ROW_NUMBER",
- "RANK",
- "DENSE_RANK",
- "LAG",
- "LEAD",
- "FIRST_VALUE",
- "LAST_VALUE",
- "NTILE",
-]);
+const WINDOW_FUNCTIONS = new Set(["ROW_NUMBER", "RANK", "DENSE_RANK", "LAG", "LEAD", "FIRST_VALUE", "LAST_VALUE", "NTILE"]);
function getFunctionDescriptions(t?: SqlCompletionTranslations): Map<string, string> {
const d = t?.functionDescriptions ?? {};
@@ -1021,40 +985,20 @@ export function buildSqlCompletionItemsFromContext(
return dedupeAndSort(buildMongoCompletionItems(context.prefix));
}
- if (
- !context.exclusiveTableSuggestions &&
- !context.exclusiveColumnSuggestions &&
- !context.exclusiveRoutineSuggestions
- ) {
+ if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions) {
items.push(...buildSnippetItems(context.prefix, input.snippets ?? DEFAULT_SQL_SNIPPETS));
items.push(...buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(t), databaseType));
}
- if (
- !context.exclusiveTableSuggestions &&
- !context.exclusiveColumnSuggestions &&
- !context.exclusiveRoutineSuggestions &&
- context.prioritizeSelectAliases
- ) {
+ if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions && context.prioritizeSelectAliases) {
items.push(...buildSelectAliasItems(context));
}
- if (
- !context.exclusiveTableSuggestions &&
- !context.exclusiveColumnSuggestions &&
- !context.exclusiveRoutineSuggestions &&
- context.isGroupBy &&
- context.nonAggregatedSelectColumns.length > 0
- ) {
+ if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions && context.isGroupBy && context.nonAggregatedSelectColumns.length > 0) {
items.push(...buildNonAggregatedColumnItems(context, input.columnsByTable, dialect));
}
- if (
- !context.exclusiveTableSuggestions &&
- !context.exclusiveColumnSuggestions &&
- !context.exclusiveRoutineSuggestions &&
- context.suggestJoinConditions
- ) {
+ if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions && context.suggestJoinConditions) {
items.push(...buildJoinConditionItems(context, input.columnsByTable, input.foreignKeysByTable, dialect));
}
@@ -1103,12 +1047,7 @@ export function shouldAutoOpenSqlCompletion(sql: string, cursor: number): boolea
if (/\bcall\s+(?:[A-Za-z_][\w$]*\.)?$/i.test(sql.slice(0, cursor))) return true;
if (/[,;()[\]]/.test(previousChar)) return false;
const context = getSqlCompletionContext(sql, cursor);
- if (
- context.exclusiveTableSuggestions ||
- context.exclusiveColumnSuggestions ||
- context.exclusiveRoutineSuggestions ||
- context.suggestTables
- ) {
+ if (context.exclusiveTableSuggestions || context.exclusiveColumnSuggestions || context.exclusiveRoutineSuggestions || context.suggestTables) {
return true;
}
return /[\w$.@]/.test(previousChar);
@@ -1273,10 +1212,7 @@ function detectStatementKind(previousStatements: string): SqlStatementKind {
}
function isCallRoutineContext(beforeToken: string): boolean {
- return (
- /\bcall\s+(?:[A-Za-z_][\w$]*\.)?$/i.test(beforeToken) ||
- /\bcall\s+(?:[A-Za-z_][\w$]*\.)?[A-Za-z_][\w$]*$/i.test(beforeToken)
- );
+ return /\bcall\s+(?:[A-Za-z_][\w$]*\.)?$/i.test(beforeToken) || /\bcall\s+(?:[A-Za-z_][\w$]*\.)?[A-Za-z_][\w$]*$/i.test(beforeToken);
}
export function getSqlCompletionContext(sql: string, cursor: number): SqlCompletionContext {
@@ -1320,14 +1256,8 @@ export function getSqlCompletionContext(sql: string, cursor: number): SqlComplet
// Detect INSERT INTO table (column list) context
const insertInfo = detectInsertColumnListContext(beforeCursor);
- const afterTableTrigger =
- TABLE_TRIGGER_KEYWORDS.has(lastWord) ||
- (JOIN_MODIFIERS.has(lastWord) && isFollowedByJoin(beforeToken)) ||
- isInTableListContext(beforeToken);
- const exclusiveTableSuggestions =
- EXCLUSIVE_TABLE_TRIGGER_KEYWORDS.has(lastWord) ||
- (JOIN_MODIFIERS.has(lastWord) && isFollowedByJoin(beforeToken)) ||
- isInTableListContext(beforeToken);
+ const afterTableTrigger = TABLE_TRIGGER_KEYWORDS.has(lastWord) || (JOIN_MODIFIERS.has(lastWord) && isFollowedByJoin(beforeToken)) || isInTableListContext(beforeToken);
+ const exclusiveTableSuggestions = EXCLUSIVE_TABLE_TRIGGER_KEYWORDS.has(lastWord) || (JOIN_MODIFIERS.has(lastWord) && isFollowedByJoin(beforeToken)) || isInTableListContext(beforeToken);
const exclusiveColumnSuggestions = !!qualifier && !exclusiveTableSuggestions && !insertInfo;
// Check if we're in a context where columns are expected
@@ -1344,9 +1274,7 @@ export function getSqlCompletionContext(sql: string, cursor: number): SqlComplet
suggestTables: insertInfo ? false : afterTableTrigger,
suggestColumns: !!qualifier || (inColumnContext && referencedTables.length > 0),
suggestKeywords: !exclusiveTableSuggestions && !exclusiveColumnSuggestions && !insertInfo && !inCallRoutineContext,
- suggestRoutines:
- inCallRoutineContext ||
- (!exclusiveTableSuggestions && !exclusiveColumnSuggestions && !insertInfo && prefix.length >= 2),
+ suggestRoutines: inCallRoutineContext || (!exclusiveTableSuggestions && !exclusiveColumnSuggestions && !insertInfo && prefix.length >= 2),
suggestJoinConditions: insertInfo ? false : inJoinConditionContext && referencedTables.length >= 2,
exclusiveTableSuggestions: insertInfo ? false : exclusiveTableSuggestions,
exclusiveColumnSuggestions: exclusiveColumnSuggestions || !!insertInfo,
@@ -1514,8 +1442,7 @@ function isInGroupByContext(beforeCursor: string): boolean {
return !/\b(?:where|having|limit|offset|union|intersect|except|join|from)\b/.test(segment);
}
-const AGGREGATE_FUNCTION_PATTERN =
- /^(COUNT|SUM|AVG|MIN|MAX|GROUP_CONCAT|STRING_AGG|ARRAY_AGG|JSON_ARRAYAGG|JSON_OBJECTAGG)\s*\(/i;
+const AGGREGATE_FUNCTION_PATTERN = /^(COUNT|SUM|AVG|MIN|MAX|GROUP_CONCAT|STRING_AGG|ARRAY_AGG|JSON_ARRAYAGG|JSON_OBJECTAGG)\s*\(/i;
function extractNonAggregatedSelectColumns(sql: string): string[] {
const selectList = extractSelectList(sql);
@@ -1670,8 +1597,7 @@ function extractReferencedTables(sql: string): SqlCompletionReferencedTable[] {
"respect",
]);
- const pattern =
- /\b(?:from|join|update|into|apply)\s+((?:"[^"]+"|`[^`]+`|[^\s,;()]+)(?:\.(?:"[^"]+"|`[^`]+`|[^\s,;()]+))?)(?:\s+(?:as\s+)?([A-Za-z_][\w$]*))?/gi;
+ const pattern = /\b(?:from|join|update|into|apply)\s+((?:"[^"]+"|`[^`]+`|[^\s,;()]+)(?:\.(?:"[^"]+"|`[^`]+`|[^\s,;()]+))?)(?:\s+(?:as\s+)?([A-Za-z_][\w$]*))?/gi;
const referenced: SqlCompletionReferencedTable[] = [];
for (const match of sql.matchAll(pattern)) {
const rawName = match[1];
@@ -1735,12 +1661,7 @@ function extractSelectList(sql: string): string | null {
if (inSingleQuote || inDoubleQuote) continue;
if (ch === "(") depth++;
else if (ch === ")") depth = Math.max(0, depth - 1);
- else if (
- depth === 0 &&
- lower.slice(i, i + "from".length) === "from" &&
- !isIdentifierPart(sql[i - 1]) &&
- !isIdentifierPart(sql[i + "from".length])
- ) {
+ else if (depth === 0 && lower.slice(i, i + "from".length) === "from" && !isIdentifierPart(sql[i - 1]) && !isIdentifierPart(sql[i + "from".length])) {
return sql.slice(selectIndex + "select".length, i).trim();
}
}
@@ -1909,36 +1830,7 @@ function extractSubqueryReferences(sql: string): SqlCompletionReferencedTable[]
return refs;
}
-const ALIAS_BLACKLIST_FOR_REF = new Set([
- "where",
- "group",
- "order",
- "having",
- "limit",
- "offset",
- "union",
- "intersect",
- "except",
- "and",
- "or",
- "not",
- "is",
- "like",
- "in",
- "between",
- "exists",
- "select",
- "on",
- "set",
- "left",
- "right",
- "inner",
- "outer",
- "cross",
- "full",
- "natural",
- "join",
-]);
+const ALIAS_BLACKLIST_FOR_REF = new Set(["where", "group", "order", "having", "limit", "offset", "union", "intersect", "except", "and", "or", "not", "is", "like", "in", "between", "exists", "select", "on", "set", "left", "right", "inner", "outer", "cross", "full", "natural", "join"]);
function splitTopLevel(text: string, separator: string): string[] {
const parts: string[] = [];
@@ -2019,15 +1911,9 @@ function requiresPostgresIdentifierQuote(identifier: string): boolean {
return POSTGRES_IDENTIFIER_KEYWORDS.has(identifier);
}
-const POSTGRES_IDENTIFIER_KEYWORDS = new Set(
- SQL_KEYWORDS.map((keyword) => keyword.toLowerCase()).concat(["current_user", "session_user", "user"]),
-);
+const POSTGRES_IDENTIFIER_KEYWORDS = new Set(SQL_KEYWORDS.map((keyword) => keyword.toLowerCase()).concat(["current_user", "session_user", "user"]));
-function buildTableItems(
- prefix: string,
- tables: SqlCompletionTable[],
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildTableItems(prefix: string, tables: SqlCompletionTable[], dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
return tables
.filter((table) => matchesPrefix(table.name, prefix))
.map((table) => ({
@@ -2041,11 +1927,7 @@ function buildTableItems(
.slice(0, MAX_TABLE_COMPLETION_ITEMS);
}
-function buildSchemaItems(
- prefix: string,
- schemas: string[],
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildSchemaItems(prefix: string, schemas: string[], dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
return schemas
.filter((schema) => matchesPrefix(schema, prefix))
.slice(0, 50)
@@ -2058,27 +1940,14 @@ function buildSchemaItems(
}));
}
-function buildObjectItems(
- context: SqlCompletionContext,
- objects: SqlCompletionObject[],
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildObjectItems(context: SqlCompletionContext, objects: SqlCompletionObject[], dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
const onlyProcedures = context.exclusiveRoutineSuggestions;
return objects
.filter((object) => (!onlyProcedures || object.type === "procedure") && matchesPrefix(object.name, context.prefix))
.map((object) => {
const applyName =
- context.qualifier && object.schema?.toLowerCase() === context.qualifier.toLowerCase()
- ? quoteSqlIdentifier(object.name, dialect)
- : object.schema
- ? `${quoteSqlIdentifier(object.schema, dialect)}.${quoteSqlIdentifier(object.name, dialect)}`
- : quoteSqlIdentifier(object.name, dialect);
- const detail =
- object.type === "trigger" && object.parentName
- ? `trigger on ${object.parentName}`
- : object.schema
- ? `${object.type} in ${object.schema}`
- : object.type;
+ context.qualifier && object.schema?.toLowerCase() === context.qualifier.toLowerCase() ? quoteSqlIdentifier(object.name, dialect) : object.schema ? `${quoteSqlIdentifier(object.schema, dialect)}.${quoteSqlIdentifier(object.name, dialect)}` : quoteSqlIdentifier(object.name, dialect);
+ const detail = object.type === "trigger" && object.parentName ? `trigger on ${object.parentName}` : object.schema ? `${object.type} in ${object.schema}` : object.type;
return {
label: object.name,
type: "function" as const,
@@ -2091,11 +1960,7 @@ function buildObjectItems(
.slice(0, MAX_TABLE_COMPLETION_ITEMS);
}
-function buildStarExpansionItem(
- columnsByTable: Map<string, SqlCompletionColumn[]>,
- t?: SqlCompletionTranslations,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem | null {
+function buildStarExpansionItem(columnsByTable: Map<string, SqlCompletionColumn[]>, t?: SqlCompletionTranslations, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem | null {
const allColumns: string[] = [];
const seen = new Set<string>();
for (const [, cols] of columnsByTable) {
@@ -2116,11 +1981,7 @@ function buildStarExpansionItem(
};
}
-function buildComparisonValueItems(
- context: SqlCompletionContext,
- columnsByTable: Map<string, SqlCompletionColumn[]>,
- t?: SqlCompletionTranslations,
-): SqlCompletionItem[] {
+function buildComparisonValueItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, t?: SqlCompletionTranslations): SqlCompletionItem[] {
const colName = context.comparisonLeftColumn!;
const parts = colName.split(".");
const unqualified = parts.length > 1 ? parts[parts.length - 1]! : colName;
@@ -2140,11 +2001,7 @@ function buildComparisonValueItems(
if (col.name.toLowerCase() === unqualified.toLowerCase()) {
if (qualifier) {
const qualLower = qualifier.toLowerCase();
- if (
- col.table.toLowerCase() === qualLower ||
- col.schema?.toLowerCase() === qualLower ||
- col.table.toLowerCase() === resolvedTable
- ) {
+ if (col.table.toLowerCase() === qualLower || col.schema?.toLowerCase() === qualLower || col.table.toLowerCase() === resolvedTable) {
dataType = col.dataType;
break;
}
@@ -2198,17 +2055,7 @@ function buildComparisonValueItems(
}
// Numeric types: suggest number placeholder
- if (
- dt.includes("int") ||
- dt.includes("decimal") ||
- dt.includes("numeric") ||
- dt.includes("float") ||
- dt.includes("real") ||
- dt.includes("money") ||
- dt === "bigint" ||
- dt === "smallint" ||
- dt === "tinyint"
- ) {
+ if (dt.includes("int") || dt.includes("decimal") || dt.includes("numeric") || dt.includes("float") || dt.includes("real") || dt.includes("money") || dt === "bigint" || dt === "smallint" || dt === "tinyint") {
if (matchesPrefix("0", prefix) || !prefix) {
items.push({
label: "0",
@@ -2222,10 +2069,7 @@ function buildComparisonValueItems(
// Boolean-ish: tinyint or bit
if (dt === "bit" || dt === "boolean" || dt === "bool") {
- items.push(
- { label: "TRUE", type: "keyword" as const, detail: t?.booleanValue ?? "Boolean value", boost: 1700 },
- { label: "FALSE", type: "keyword" as const, detail: t?.booleanValue ?? "Boolean value", boost: 1650 },
- );
+ items.push({ label: "TRUE", type: "keyword" as const, detail: t?.booleanValue ?? "Boolean value", boost: 1700 }, { label: "FALSE", type: "keyword" as const, detail: t?.booleanValue ?? "Boolean value", boost: 1650 });
}
return items;
@@ -2276,11 +2120,7 @@ function isInTableListContext(beforeToken: string): boolean {
return /,\s*$/.test(beforeToken) && /\b(?:from|join|update|into)\b/i.test(beforeToken);
}
-function buildColumnItems(
- context: SqlCompletionContext,
- columnsByTable: Map<string, SqlCompletionColumn[]>,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildColumnItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
// Collect all columns from the map (all tables have been fetched)
const allColumns: Array<SqlCompletionColumn & { key: string }> = [];
for (const [key, cols] of columnsByTable.entries()) {
@@ -2295,24 +2135,14 @@ function buildColumnItems(
const tableLower = context.insertTable.toLowerCase();
if (context.insertSchema) {
const schemaLower = context.insertSchema.toLowerCase();
- relevantCols = allColumns.filter(
- (c) =>
- c.table.toLowerCase() === tableLower &&
- (c.schema?.toLowerCase() === schemaLower || c.key.toLowerCase() === `${schemaLower}.${tableLower}`),
- );
+ relevantCols = allColumns.filter((c) => c.table.toLowerCase() === tableLower && (c.schema?.toLowerCase() === schemaLower || c.key.toLowerCase() === `${schemaLower}.${tableLower}`));
} else {
relevantCols = allColumns.filter((c) => c.table.toLowerCase() === tableLower);
}
} else if (context.qualifier) {
const q = context.qualifier;
const qLower = q.toLowerCase();
- const relatedTables = context.referencedTables.filter(
- (table) =>
- table.alias === q ||
- table.alias?.toLowerCase() === qLower ||
- table.name === q ||
- table.name.toLowerCase() === qLower,
- );
+ const relatedTables = context.referencedTables.filter((table) => table.alias === q || table.alias?.toLowerCase() === qLower || table.name === q || table.name.toLowerCase() === qLower);
const tableNameSet = new Set(relatedTables.map((t) => t.name.toLowerCase()));
const tableKeys = new Set<string>();
for (const table of relatedTables) {
@@ -2369,11 +2199,7 @@ function buildColumnItems(
.sort(compareCompletionItems);
}
-function buildColumnApply(
- column: SqlCompletionColumn & { displayLabel: string },
- context: SqlCompletionContext,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): string {
+function buildColumnApply(column: SqlCompletionColumn & { displayLabel: string }, context: SqlCompletionContext, dialect?: "mysql" | "postgres" | "sqlserver"): string {
if (context.qualifier || column.displayLabel === column.name || !column.displayLabel.includes(".")) {
return quoteSqlIdentifier(column.name, dialect);
}
@@ -2408,12 +2234,7 @@ function buildColumnInfo(column: SqlCompletionColumn): string | undefined {
return parts.length > 1 ? parts.join("\n") : undefined;
}
-function buildJoinConditionItems(
- context: SqlCompletionContext,
- columnsByTable: Map<string, SqlCompletionColumn[]>,
- foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildJoinConditionItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
const refs = context.referencedTables;
if (refs.length < 2) return [];
@@ -2424,19 +2245,13 @@ function buildJoinConditionItems(
for (const previous of previousRefs) {
const previousColumns = columnsForReferencedTable(previous, columnsByTable);
const latestColumns = columnsForReferencedTable(latest, columnsByTable);
- items.push(
- ...buildForeignKeyJoinConditionItemsForPair(previous, latest, foreignKeysByTable, context.prefix, dialect),
- ...buildJoinConditionItemsForPair(previous, previousColumns, latest, latestColumns, context.prefix, dialect),
- );
+ items.push(...buildForeignKeyJoinConditionItemsForPair(previous, latest, foreignKeysByTable, context.prefix, dialect), ...buildJoinConditionItemsForPair(previous, previousColumns, latest, latestColumns, context.prefix, dialect));
}
return items;
}
-function columnsForReferencedTable(
- table: SqlCompletionReferencedTable,
- columnsByTable: Map<string, SqlCompletionColumn[]>,
-): SqlCompletionColumn[] {
+function columnsForReferencedTable(table: SqlCompletionReferencedTable, columnsByTable: Map<string, SqlCompletionColumn[]>): SqlCompletionColumn[] {
const keys = table.schema ? [`${table.schema}.${table.name}`, table.name] : [table.name];
for (const key of keys) {
const columns = columnsByTable.get(key);
@@ -2445,10 +2260,7 @@ function columnsForReferencedTable(
return [];
}
-function foreignKeysForReferencedTable(
- table: SqlCompletionReferencedTable,
- foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>,
-): SqlCompletionForeignKey[] {
+function foreignKeysForReferencedTable(table: SqlCompletionReferencedTable, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>): SqlCompletionForeignKey[] {
if (!foreignKeysByTable) return [];
const keys = table.schema ? [`${table.schema}.${table.name}`, table.name] : [table.name];
for (const key of keys) {
@@ -2458,49 +2270,18 @@ function foreignKeysForReferencedTable(
return [];
}
-function buildForeignKeyJoinConditionItemsForPair(
- left: SqlCompletionReferencedTable,
- right: SqlCompletionReferencedTable,
- foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>,
- prefix = "",
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildForeignKeyJoinConditionItemsForPair(left: SqlCompletionReferencedTable, right: SqlCompletionReferencedTable, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>, prefix = "", dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
if (!foreignKeysByTable) return [];
- return [
- ...buildDirectionalForeignKeyJoinConditionItems(
- left,
- right,
- foreignKeysForReferencedTable(left, foreignKeysByTable),
- prefix,
- dialect,
- ),
- ...buildDirectionalForeignKeyJoinConditionItems(
- right,
- left,
- foreignKeysForReferencedTable(right, foreignKeysByTable),
- prefix,
- dialect,
- ),
- ];
-}
-
-function buildDirectionalForeignKeyJoinConditionItems(
- owner: SqlCompletionReferencedTable,
- referenced: SqlCompletionReferencedTable,
- foreignKeys: SqlCompletionForeignKey[],
- prefix: string,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
- const matchingForeignKeys = foreignKeys.filter((foreignKey) =>
- referencedTableMatchesName(referenced, foreignKey.ref_table, foreignKey.ref_schema),
- );
+ return [...buildDirectionalForeignKeyJoinConditionItems(left, right, foreignKeysForReferencedTable(left, foreignKeysByTable), prefix, dialect), ...buildDirectionalForeignKeyJoinConditionItems(right, left, foreignKeysForReferencedTable(right, foreignKeysByTable), prefix, dialect)];
+}
+
+function buildDirectionalForeignKeyJoinConditionItems(owner: SqlCompletionReferencedTable, referenced: SqlCompletionReferencedTable, foreignKeys: SqlCompletionForeignKey[], prefix: string, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
+ const matchingForeignKeys = foreignKeys.filter((foreignKey) => referencedTableMatchesName(referenced, foreignKey.ref_table, foreignKey.ref_schema));
const groups = groupForeignKeysByConstraint(matchingForeignKeys);
const items: SqlCompletionItem[] = [];
for (const group of groups) {
- const parts = group.map((foreignKey) =>
- buildJoinConditionPart(owner, foreignKey.column, referenced, foreignKey.ref_column, dialect),
- );
+ const parts = group.map((foreignKey) => buildJoinConditionPart(owner, foreignKey.column, referenced, foreignKey.ref_column, dialect));
const label = parts.map((part) => part.label).join(" AND ");
if (!label || (prefix && !matchesPrefix(label, prefix))) continue;
const apply = parts.map((part) => part.apply).join(" AND ");
@@ -2516,13 +2297,7 @@ function buildDirectionalForeignKeyJoinConditionItems(
return items;
}
-function buildJoinConditionPart(
- owner: SqlCompletionReferencedTable,
- ownerColumn: string,
- referenced: SqlCompletionReferencedTable,
- referencedColumn: string,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): { label: string; apply: string } {
+function buildJoinConditionPart(owner: SqlCompletionReferencedTable, ownerColumn: string, referenced: SqlCompletionReferencedTable, referencedColumn: string, dialect?: "mysql" | "postgres" | "sqlserver"): { label: string; apply: string } {
const ownerRef = owner.alias || owner.name;
const referencedRef = referenced.alias || referenced.name;
const ownerApplyRef = owner.alias ? owner.alias : quoteSqlIdentifier(owner.name, dialect);
@@ -2543,11 +2318,7 @@ function groupForeignKeysByConstraint(foreignKeys: SqlCompletionForeignKey[]): S
return [...groups.values()];
}
-function referencedTableMatchesName(
- table: SqlCompletionReferencedTable,
- candidate: string,
- candidateSchema?: string | null,
-): boolean {
+function referencedTableMatchesName(table: SqlCompletionReferencedTable, candidate: string, candidateSchema?: string | null): boolean {
const normalizedCandidate = normalizeTableName(candidate);
if (normalizeTableName(table.name) !== normalizedCandidate) return false;
if (!candidateSchema || !table.schema) return true;
@@ -2567,14 +2338,7 @@ function normalizeIdentifierPart(name: string): string {
return name.replace(/^["`[]|["`\]]$/g, "").toLowerCase();
}
-function buildJoinConditionItemsForPair(
- left: SqlCompletionReferencedTable,
- leftColumns: SqlCompletionColumn[],
- right: SqlCompletionReferencedTable,
- rightColumns: SqlCompletionColumn[],
- prefix: string,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildJoinConditionItemsForPair(left: SqlCompletionReferencedTable, leftColumns: SqlCompletionColumn[], right: SqlCompletionReferencedTable, rightColumns: SqlCompletionColumn[], prefix: string, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
const items: SqlCompletionItem[] = [];
const leftRef = left.alias || left.name;
const rightRef = right.alias || right.name;
@@ -2587,11 +2351,7 @@ function buildJoinConditionItemsForPair(
const rightByName = indexColumnsByLowerName(rightColumns);
const emittedPairs = new Set<string>();
- const addPair = (
- leftColumn: SqlCompletionColumn | undefined,
- rightColumn: SqlCompletionColumn | undefined,
- boost: number,
- ) => {
+ const addPair = (leftColumn: SqlCompletionColumn | undefined, rightColumn: SqlCompletionColumn | undefined, boost: number) => {
if (!leftColumn || !rightColumn || !areJoinColumnTypesCompatible(leftColumn, rightColumn)) return;
const key = `${leftColumn.name.toLowerCase()}:${rightColumn.name.toLowerCase()}`;
if (emittedPairs.has(key)) return;
@@ -2646,9 +2406,7 @@ function buildJoinConditionItemsForPair(
if (rightName !== "id" && rightName.endsWith("_id")) addPair(leftId, rightColumn, 1650);
}
- items.push(
- ...buildCompositeHeuristicJoinConditionItems(left, leftColumns, right, leftByName, rightByName, prefix, dialect),
- );
+ items.push(...buildCompositeHeuristicJoinConditionItems(left, leftColumns, right, leftByName, rightByName, prefix, dialect));
return items;
}
@@ -2677,8 +2435,7 @@ function buildCompositeHeuristicJoinConditionItems(
const rightId = rightByName.get("id")?.[0];
const leftTableKey = singularTableName(left.name);
const rightTableKey = singularTableName(right.name);
- const candidates: Array<{ parent: "left" | "right"; parentId: SqlCompletionColumn; childFk: SqlCompletionColumn }> =
- [];
+ const candidates: Array<{ parent: "left" | "right"; parentId: SqlCompletionColumn; childFk: SqlCompletionColumn }> = [];
const rightNamedFk = rightByName.get(`${leftTableKey}_id`)?.[0];
const leftNamedFk = leftByName.get(`${rightTableKey}_id`)?.[0];
if (leftId && rightNamedFk && areJoinColumnTypesCompatible(leftId, rightNamedFk)) {
@@ -2709,33 +2466,11 @@ function buildCompositeHeuristicJoinConditionItems(
const items: SqlCompletionItem[] = [];
for (const candidate of candidates.slice(0, 2)) {
- const parts = sharedScopeColumns.map(({ leftColumn, rightColumn }) =>
- buildHeuristicJoinConditionPart(leftRef, leftApplyRef, leftColumn, rightRef, rightApplyRef, rightColumn, dialect),
- );
+ const parts = sharedScopeColumns.map(({ leftColumn, rightColumn }) => buildHeuristicJoinConditionPart(leftRef, leftApplyRef, leftColumn, rightRef, rightApplyRef, rightColumn, dialect));
if (candidate.parent === "left") {
- parts.push(
- buildHeuristicJoinConditionPart(
- leftRef,
- leftApplyRef,
- candidate.parentId,
- rightRef,
- rightApplyRef,
- candidate.childFk,
- dialect,
- ),
- );
+ parts.push(buildHeuristicJoinConditionPart(leftRef, leftApplyRef, candidate.parentId, rightRef, rightApplyRef, candidate.childFk, dialect));
} else {
- parts.push(
- buildHeuristicJoinConditionPart(
- leftRef,
- leftApplyRef,
- candidate.childFk,
- rightRef,
- rightApplyRef,
- candidate.parentId,
- dialect,
- ),
- );
+ parts.push(buildHeuristicJoinConditionPart(leftRef, leftApplyRef, candidate.childFk, rightRef, rightApplyRef, candidate.parentId, dialect));
}
const label = parts.map((part) => part.label).join(" AND ");
if (prefix && !matchesPrefix(label, prefix)) continue;
@@ -2751,15 +2486,7 @@ function buildCompositeHeuristicJoinConditionItems(
return items;
}
-function buildHeuristicJoinConditionPart(
- leftRef: string,
- leftApplyRef: string,
- leftColumn: SqlCompletionColumn,
- rightRef: string,
- rightApplyRef: string,
- rightColumn: SqlCompletionColumn,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): { label: string; apply: string } {
+function buildHeuristicJoinConditionPart(leftRef: string, leftApplyRef: string, leftColumn: SqlCompletionColumn, rightRef: string, rightApplyRef: string, rightColumn: SqlCompletionColumn, dialect?: "mysql" | "postgres" | "sqlserver"): { label: string; apply: string } {
return {
label: `${leftRef}.${leftColumn.name} = ${rightRef}.${rightColumn.name}`,
apply: `${leftApplyRef}.${quoteSqlIdentifier(leftColumn.name, dialect)} = ${rightApplyRef}.${quoteSqlIdentifier(rightColumn.name, dialect)}`,
@@ -2767,16 +2494,7 @@ function buildHeuristicJoinConditionPart(
}
function isLikelyScopeColumnName(name: string): boolean {
- return (
- name !== "id" &&
- (name.endsWith("_id") ||
- name === "tenant" ||
- name === "tenant_id" ||
- name === "account_id" ||
- name === "workspace_id" ||
- name === "organization_id" ||
- name === "org_id")
- );
+ return name !== "id" && (name.endsWith("_id") || name === "tenant" || name === "tenant_id" || name === "account_id" || name === "workspace_id" || name === "organization_id" || name === "org_id");
}
function areJoinColumnTypesCompatible(left: SqlCompletionColumn, right: SqlCompletionColumn): boolean {
@@ -2863,9 +2581,7 @@ function buildSnippetItems(prefix: string, snippets: SqlSnippet[]): SqlCompletio
}
function activeFunctionSignatures(databaseType?: DatabaseType): Map<string, string[]> {
- const signatures = databaseType
- ? new Map(Array.from(SQL_FUNCTION_SIGNATURES.entries()).filter(([name]) => COMMON_SQL_FUNCTION_NAMES.has(name)))
- : new Map(SQL_FUNCTION_SIGNATURES);
+ const signatures = databaseType ? new Map(Array.from(SQL_FUNCTION_SIGNATURES.entries()).filter(([name]) => COMMON_SQL_FUNCTION_NAMES.has(name))) : new Map(SQL_FUNCTION_SIGNATURES);
const databaseSignatures = databaseType ? DATABASE_FUNCTION_SIGNATURES[databaseType] : undefined;
if (databaseSignatures) {
for (const [name, parameters] of databaseSignatures) signatures.set(name, parameters);
@@ -2873,11 +2589,7 @@ function activeFunctionSignatures(databaseType?: DatabaseType): Map<string, stri
return signatures;
}
-function buildFunctionSnippetItems(
- prefix: string,
- functionDescriptions: Map<string, string>,
- databaseType?: DatabaseType,
-): SqlCompletionItem[] {
+function buildFunctionSnippetItems(prefix: string, functionDescriptions: Map<string, string>, databaseType?: DatabaseType): SqlCompletionItem[] {
const items: SqlCompletionItem[] = [];
for (const [name, parameters] of activeFunctionSignatures(databaseType).entries()) {
@@ -2951,11 +2663,7 @@ function buildSelectAliasItems(context: SqlCompletionContext): SqlCompletionItem
}));
}
-function buildNonAggregatedColumnItems(
- context: SqlCompletionContext,
- columnsByTable: Map<string, SqlCompletionColumn[]>,
- dialect?: "mysql" | "postgres" | "sqlserver",
-): SqlCompletionItem[] {
+function buildNonAggregatedColumnItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
const nonAggSet = new Set(context.nonAggregatedSelectColumns.map((c) => c.toLowerCase()));
const seen = new Set<string>();
@@ -2982,21 +2690,11 @@ function buildNonAggregatedColumnItems(
function activeSqlKeywords(databaseType?: DatabaseType): string[] {
if (databaseType === "mongodb") return [];
const databaseKeywords = databaseType ? DATABASE_SQL_KEYWORDS[databaseType] : undefined;
- return databaseType
- ? Array.from(new Set([...COMMON_SQL_KEYWORDS, ...(databaseKeywords ?? [])]))
- : Array.from(new Set(SQL_KEYWORDS));
+ return databaseType ? Array.from(new Set([...COMMON_SQL_KEYWORDS, ...(databaseKeywords ?? [])])) : Array.from(new Set(SQL_KEYWORDS));
}
-function buildKeywordItems(
- prefix: string,
- context: SqlCompletionContext,
- databaseType?: DatabaseType,
-): SqlCompletionItem[] {
- const isDml =
- context.statementKind === "select" ||
- context.statementKind === "insert" ||
- context.statementKind === "update" ||
- context.statementKind === "delete";
+function buildKeywordItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType): SqlCompletionItem[] {
+ const isDml = context.statementKind === "select" || context.statementKind === "insert" || context.statementKind === "update" || context.statementKind === "delete";
const showDdl = !isDml || context.suggestTables;
return activeSqlKeywords(databaseType)
diff --git a/apps/desktop/src/lib/sqlDiagnostics.ts b/apps/desktop/src/lib/sqlDiagnostics.ts
index 303a0a9c93..ab56e98448 100644
--- a/apps/desktop/src/lib/sqlDiagnostics.ts
+++ b/apps/desktop/src/lib/sqlDiagnostics.ts
@@ -11,9 +11,7 @@ function toZeroBased(value: string | undefined): number | null {
}
export function parseSqlErrorLocation(message: string): SqlErrorLocation | null {
- const lineColumn =
- /\bline\s+(\d+)\s*[,:\s]\s*column\s+(\d+)\b/i.exec(message) ??
- /\bline\s+(\d+)\b[\s\S]{0,80}?\bcol(?:umn)?\s+(\d+)\b/i.exec(message);
+ const lineColumn = /\bline\s+(\d+)\s*[,:\s]\s*column\s+(\d+)\b/i.exec(message) ?? /\bline\s+(\d+)\b[\s\S]{0,80}?\bcol(?:umn)?\s+(\d+)\b/i.exec(message);
if (lineColumn) {
const line = toZeroBased(lineColumn[1]);
const column = toZeroBased(lineColumn[2]);
diff --git a/apps/desktop/src/lib/sqlExecutionTarget.ts b/apps/desktop/src/lib/sqlExecutionTarget.ts
index 2e5e861258..7a13e678e7 100644
--- a/apps/desktop/src/lib/sqlExecutionTarget.ts
+++ b/apps/desktop/src/lib/sqlExecutionTarget.ts
@@ -3,11 +3,7 @@ import type { DatabaseType } from "@/types/database";
export type ExecuteMode = "all" | "current";
-export function resolveExecutableSql(
- fullSql: string,
- selectedSql: string,
- options?: { mode?: ExecuteMode; cursorPos?: number },
-): string {
+export function resolveExecutableSql(fullSql: string, selectedSql: string, options?: { mode?: ExecuteMode; cursorPos?: number }): string {
const trimmedSelection = selectedSql.trim();
if (trimmedSelection) return trimmedSelection;
@@ -18,11 +14,7 @@ export function resolveExecutableSql(
return fullSql;
}
-export async function resolveExecutableSqlWithBackend(
- fullSql: string,
- selectedSql: string,
- options?: { mode?: ExecuteMode; cursorPos?: number; databaseType?: DatabaseType },
-): Promise<string> {
+export async function resolveExecutableSqlWithBackend(fullSql: string, selectedSql: string, options?: { mode?: ExecuteMode; cursorPos?: number; databaseType?: DatabaseType }): Promise<string> {
const trimmedSelection = selectedSql.trim();
if (trimmedSelection) return trimmedSelection;
diff --git a/apps/desktop/src/lib/sqlFormatter.ts b/apps/desktop/src/lib/sqlFormatter.ts
index d54147dd77..3714f55e44 100644
--- a/apps/desktop/src/lib/sqlFormatter.ts
+++ b/apps/desktop/src/lib/sqlFormatter.ts
@@ -1,8 +1,4 @@
-import {
- DEFAULT_SQL_FORMATTER_SETTINGS,
- sqlFormatterOptions,
- type SqlFormatterSettings,
-} from "@/lib/sqlFormatterConfig";
+import { DEFAULT_SQL_FORMATTER_SETTINGS, sqlFormatterOptions, type SqlFormatterSettings } from "@/lib/sqlFormatterConfig";
export type SqlFormatDialect = "mysql" | "postgres" | "sqlite" | "sqlserver" | "generic";
@@ -23,11 +19,7 @@ function formatterLanguage(dialect: SqlFormatDialect) {
}
}
-export async function formatSqlText(
- sql: string,
- dialect: SqlFormatDialect = "generic",
- settings: SqlFormatterSettings = DEFAULT_SQL_FORMATTER_SETTINGS,
-): Promise<string> {
+export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "generic", settings: SqlFormatterSettings = DEFAULT_SQL_FORMATTER_SETTINGS): Promise<string> {
if (!sql.trim()) return sql;
if (sql.length > MAX_SQL_FORMAT_CHARS) {
throw new Error("SQL is too large to format safely.");
diff --git a/apps/desktop/src/lib/sqlFormatterConfig.ts b/apps/desktop/src/lib/sqlFormatterConfig.ts
index 005b0a5c33..b60cd5a5c6 100644
--- a/apps/desktop/src/lib/sqlFormatterConfig.ts
+++ b/apps/desktop/src/lib/sqlFormatterConfig.ts
@@ -32,9 +32,7 @@ export interface SqlFormatterConfigFile {
options: SqlFormatterSettings;
}
-export type SqlFormatterConfigParseResult =
- | { ok: true; settings: SqlFormatterSettings }
- | { ok: false; message: string };
+export type SqlFormatterConfigParseResult = { ok: true; settings: SqlFormatterSettings } | { ok: false; message: string };
export const DEFAULT_SQL_FORMATTER_SETTINGS: SqlFormatterSettings = {
keywordCase: "upper",
@@ -49,18 +47,7 @@ export const DEFAULT_SQL_FORMATTER_SETTINGS: SqlFormatterSettings = {
newlineBeforeSemicolon: false,
};
-const SQL_FORMATTER_OPTION_KEYS = new Set<keyof SqlFormatterSettings>([
- "keywordCase",
- "dataTypeCase",
- "functionCase",
- "useTabs",
- "tabWidth",
- "logicalOperatorNewline",
- "expressionWidth",
- "linesBetweenQueries",
- "denseOperators",
- "newlineBeforeSemicolon",
-]);
+const SQL_FORMATTER_OPTION_KEYS = new Set<keyof SqlFormatterSettings>(["keywordCase", "dataTypeCase", "functionCase", "useTabs", "tabWidth", "logicalOperatorNewline", "expressionWidth", "linesBetweenQueries", "denseOperators", "newlineBeforeSemicolon"]);
const SQL_FORMATTER_OPTION_VALIDATORS: Record<keyof SqlFormatterSettings, (value: unknown) => boolean> = {
keywordCase: (value) => isStringChoice(value, CASE_VALUES),
@@ -107,26 +94,11 @@ export function normalizeSqlFormatterSettings(value: unknown): SqlFormatterSetti
functionCase: normalizeChoice(input.functionCase, CASE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.functionCase),
useTabs: normalizeBoolean(input.useTabs, DEFAULT_SQL_FORMATTER_SETTINGS.useTabs),
tabWidth: normalizeNumberChoice(input.tabWidth, TAB_WIDTH_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.tabWidth),
- logicalOperatorNewline: normalizeChoice(
- input.logicalOperatorNewline,
- LOGICAL_OPERATOR_NEWLINE_VALUES,
- DEFAULT_SQL_FORMATTER_SETTINGS.logicalOperatorNewline,
- ),
- expressionWidth: normalizeNumberChoice(
- input.expressionWidth,
- EXPRESSION_WIDTH_VALUES,
- DEFAULT_SQL_FORMATTER_SETTINGS.expressionWidth,
- ),
- linesBetweenQueries: normalizeNumberChoice(
- input.linesBetweenQueries,
- LINES_BETWEEN_QUERIES_VALUES,
- DEFAULT_SQL_FORMATTER_SETTINGS.linesBetweenQueries,
- ),
+ logicalOperatorNewline: normalizeChoice(input.logicalOperatorNewline, LOGICAL_OPERATOR_NEWLINE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.logicalOperatorNewline),
+ expressionWidth: normalizeNumberChoice(input.expressionWidth, EXPRESSION_WIDTH_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.expressionWidth),
+ linesBetweenQueries: normalizeNumberChoice(input.linesBetweenQueries, LINES_BETWEEN_QUERIES_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.linesBetweenQueries),
denseOperators: normalizeBoolean(input.denseOperators, DEFAULT_SQL_FORMATTER_SETTINGS.denseOperators),
- newlineBeforeSemicolon: normalizeBoolean(
- input.newlineBeforeSemicolon,
- DEFAULT_SQL_FORMATTER_SETTINGS.newlineBeforeSemicolon,
- ),
+ newlineBeforeSemicolon: normalizeBoolean(input.newlineBeforeSemicolon, DEFAULT_SQL_FORMATTER_SETTINGS.newlineBeforeSemicolon),
};
}
@@ -155,9 +127,7 @@ export function parseSqlFormatterConfig(text: string): SqlFormatterConfigParseRe
if (parsed.formatter !== SQL_FORMATTER_CONFIG_FORMATTER) return { ok: false, message: "Unsupported formatter." };
if (!isObject(parsed.options)) return { ok: false, message: "Config options must be a JSON object." };
- const unknownOption = Object.keys(parsed.options).find(
- (key) => !SQL_FORMATTER_OPTION_KEYS.has(key as keyof SqlFormatterSettings),
- );
+ const unknownOption = Object.keys(parsed.options).find((key) => !SQL_FORMATTER_OPTION_KEYS.has(key as keyof SqlFormatterSettings));
if (unknownOption) return { ok: false, message: `Unknown formatter option: ${unknownOption}.` };
const invalidOption = Object.entries(parsed.options).find(([key, value]) => {
@@ -169,10 +139,7 @@ export function parseSqlFormatterConfig(text: string): SqlFormatterConfigParseRe
return { ok: true, settings: normalizeSqlFormatterSettings(parsed.options) };
}
-export function syncSqlFormatterConfigDraft(
- text: string,
- syncSettings: (settings: SqlFormatterSettings) => void,
-): SqlFormatterConfigParseResult {
+export function syncSqlFormatterConfigDraft(text: string, syncSettings: (settings: SqlFormatterSettings) => void): SqlFormatterConfigParseResult {
const result = parseSqlFormatterConfig(text);
if (result.ok) syncSettings(result.settings);
return result;
diff --git a/apps/desktop/src/lib/sqlFormatterConfigEditor.ts b/apps/desktop/src/lib/sqlFormatterConfigEditor.ts
index 79ae56afc0..8e173d38c9 100644
--- a/apps/desktop/src/lib/sqlFormatterConfigEditor.ts
+++ b/apps/desktop/src/lib/sqlFormatterConfigEditor.ts
@@ -16,10 +16,7 @@ export interface SqlFormatterConfigEditorActions {
formatJson: Command;
}
-export function createSqlFormatterConfigKeymap(
- commands: SqlFormatterConfigEditorCommands,
- actions: SqlFormatterConfigEditorActions,
-): KeyBinding[] {
+export function createSqlFormatterConfigKeymap(commands: SqlFormatterConfigEditorCommands, actions: SqlFormatterConfigEditorActions): KeyBinding[] {
return [
{ key: "Tab", run: commands.indentMore },
{ key: "Shift-Tab", run: commands.indentLess },
@@ -49,9 +46,7 @@ function altLabel(platform = globalThis.navigator?.platform || ""): "Option" | "
return platform.toLowerCase().includes("mac") ? "Option" : "Alt";
}
-export function sqlFormatterConfigShortcutRows(
- platform = globalThis.navigator?.platform || "",
-): SqlFormatterConfigShortcutRow[] {
+export function sqlFormatterConfigShortcutRows(platform = globalThis.navigator?.platform || ""): SqlFormatterConfigShortcutRow[] {
const isMac = platform.toLowerCase().includes("mac");
const mod = modLabel(platform);
const alt = altLabel(platform);
diff --git a/apps/desktop/src/lib/sqlHighlighter.ts b/apps/desktop/src/lib/sqlHighlighter.ts
index e6f8ca0440..d7b4cc8f1e 100644
--- a/apps/desktop/src/lib/sqlHighlighter.ts
+++ b/apps/desktop/src/lib/sqlHighlighter.ts
@@ -31,13 +31,7 @@ function getShikiSqlHighlighter(): Promise<ShikiHighlighter> {
}
async function loadShikiSqlHighlighter(): Promise<ShikiHighlighter> {
- const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, sql] = await Promise.all([
- import("shiki/core"),
- import("shiki/engine/javascript"),
- import("shiki/themes/github-dark.mjs"),
- import("shiki/themes/github-light.mjs"),
- import("shiki/langs/sql.mjs"),
- ]);
+ const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, sql] = await Promise.all([import("shiki/core"), import("shiki/engine/javascript"), import("shiki/themes/github-dark.mjs"), import("shiki/themes/github-light.mjs"), import("shiki/langs/sql.mjs")]);
return createHighlighterCore({
engine: createJavaScriptRegexEngine(),
diff --git a/apps/desktop/src/lib/sqlMetadataRefresh.ts b/apps/desktop/src/lib/sqlMetadataRefresh.ts
index d48fa9b75e..81b43e09cd 100644
--- a/apps/desktop/src/lib/sqlMetadataRefresh.ts
+++ b/apps/desktop/src/lib/sqlMetadataRefresh.ts
@@ -1,17 +1,12 @@
export type SqlMetadataRefreshScope = "none" | "connection" | "database";
-export type SqlMetadataRefreshTarget =
- | { scope: "none" }
- | { scope: "connection" }
- | { scope: "database"; schema?: string };
+export type SqlMetadataRefreshTarget = { scope: "none" } | { scope: "connection" } | { scope: "database"; schema?: string };
const DATABASE_DDL_RE = /\b(CREATE|DROP)\s+DATABASE\b/i;
const SCHEMA_DDL_RE = /\b(CREATE|DROP)\s+SCHEMA\b/i;
-const OBJECT_DDL_RE =
- /\b(CREATE|ALTER|DROP|RENAME)\s+(OR\s+REPLACE\s+)?(((GLOBAL|LOCAL)\s+)?TEMP(ORARY)?\s+)?(MATERIALIZED\s+)?(TABLE|VIEW|INDEX|SEQUENCE|PROCEDURE|FUNCTION|TRIGGER|TYPE)\b/i;
+const OBJECT_DDL_RE = /\b(CREATE|ALTER|DROP|RENAME)\s+(OR\s+REPLACE\s+)?(((GLOBAL|LOCAL)\s+)?TEMP(ORARY)?\s+)?(MATERIALIZED\s+)?(TABLE|VIEW|INDEX|SEQUENCE|PROCEDURE|FUNCTION|TRIGGER|TYPE)\b/i;
const OBJECT_NAME_DDL_RE =
/\b(?:CREATE|ALTER|DROP|RENAME)\s+(?:OR\s+REPLACE\s+)?(?:(?:(?:GLOBAL|LOCAL)\s+)?TEMP(?:ORARY)?\s+)?(?:MATERIALIZED\s+)?(?:TABLE|VIEW|SEQUENCE|PROCEDURE|FUNCTION|TRIGGER|TYPE)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*)\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*))/i;
-const INDEX_TABLE_DDL_RE =
- /\bCREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*)\s+ON\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*)\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*))/i;
+const INDEX_TABLE_DDL_RE = /\bCREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*)\s+ON\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*)\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*))/i;
function stripSqlMetadataComments(sql: string): string {
return sql
@@ -33,11 +28,7 @@ function splitSqlMetadataStatements(sql: string): string[] {
function unquoteIdentifier(identifier: string): string {
const trimmed = identifier.trim();
- if (
- (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
- (trimmed.startsWith("`") && trimmed.endsWith("`")) ||
- (trimmed.startsWith("[") && trimmed.endsWith("]"))
- ) {
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("`") && trimmed.endsWith("`")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
return trimmed.slice(1, -1);
}
return trimmed;
diff --git a/apps/desktop/src/lib/sqlNavigation.ts b/apps/desktop/src/lib/sqlNavigation.ts
index 9e626a4d1a..66dcb55dda 100644
--- a/apps/desktop/src/lib/sqlNavigation.ts
+++ b/apps/desktop/src/lib/sqlNavigation.ts
@@ -165,10 +165,7 @@ export function isSqlKeyword(identifier: string): boolean {
}
/** Match identifier against known table names (case-insensitive). */
-export function matchTable(
- identifier: string,
- tables: Array<{ name: string; schema?: string }>,
-): { name: string; schema?: string } | null {
+export function matchTable(identifier: string, tables: Array<{ name: string; schema?: string }>): { name: string; schema?: string } | null {
const lower = identifier.toLowerCase();
return tables.find((t) => t.name.toLowerCase() === lower) ?? null;
}
diff --git a/apps/desktop/src/lib/sqlSemanticDiagnostics.ts b/apps/desktop/src/lib/sqlSemanticDiagnostics.ts
index a4fd2a553b..eb2c9905fb 100644
--- a/apps/desktop/src/lib/sqlSemanticDiagnostics.ts
+++ b/apps/desktop/src/lib/sqlSemanticDiagnostics.ts
@@ -1,12 +1,6 @@
import type { SqlCompletionColumn, SqlCompletionTable } from "@/lib/sqlCompletion";
import { getSqlCompletionContext } from "@/lib/sqlCompletion";
-import type {
- DatabaseType,
- SqlColumnReference,
- SqlReferenceAnalysis,
- SqlTableReference,
- SqlTextSpan,
-} from "@/types/database";
+import type { DatabaseType, SqlColumnReference, SqlReferenceAnalysis, SqlTableReference, SqlTextSpan } from "@/types/database";
export interface SqlSemanticDiagnostic {
span: SqlTextSpan;
@@ -19,10 +13,7 @@ export interface SqlSemanticDiagnosticSchema {
columnsByTable: Map<string, SqlCompletionColumn[]>;
}
-export function buildSqlSemanticDiagnostics(
- analysis: SqlReferenceAnalysis,
- schema: SqlSemanticDiagnosticSchema,
-): SqlSemanticDiagnostic[] {
+export function buildSqlSemanticDiagnostics(analysis: SqlReferenceAnalysis, schema: SqlSemanticDiagnosticSchema): SqlSemanticDiagnostic[] {
const diagnostics: SqlSemanticDiagnostic[] = [];
const tables = analysis.tables.filter((table) => table.name.trim());
const knownTables = new Map<string, SqlTableReference>();
@@ -80,30 +71,15 @@ export function buildSqlParserErrorDiagnostic(error: unknown, sql: string): SqlS
};
}
-export function areSqlSemanticDiagnosticsEqual(
- left: readonly SqlSemanticDiagnostic[],
- right: readonly SqlSemanticDiagnostic[],
-): boolean {
+export function areSqlSemanticDiagnosticsEqual(left: readonly SqlSemanticDiagnostic[], right: readonly SqlSemanticDiagnostic[]): boolean {
if (left.length !== right.length) return false;
return left.every((item, index) => {
const other = right[index];
- return (
- !!other &&
- item.message === other.message &&
- item.severity === other.severity &&
- item.span.start_line === other.span.start_line &&
- item.span.start_column === other.span.start_column &&
- item.span.end_line === other.span.end_line &&
- item.span.end_column === other.span.end_column
- );
+ return !!other && item.message === other.message && item.severity === other.severity && item.span.start_line === other.span.start_line && item.span.start_column === other.span.start_column && item.span.end_line === other.span.end_line && item.span.end_column === other.span.end_column;
});
}
-export function shouldRunSqlSemanticDiagnostics(
- sql: string,
- cursor: number,
- options: { databaseType?: DatabaseType } = {},
-): boolean {
+export function shouldRunSqlSemanticDiagnostics(sql: string, cursor: number, options: { databaseType?: DatabaseType } = {}): boolean {
if (options.databaseType === "mongodb" || options.databaseType === "elasticsearch") return false;
const context = getSqlCompletionContext(sql, cursor);
if (context.suggestTables || context.exclusiveTableSuggestions || context.exclusiveColumnSuggestions) return false;
@@ -111,11 +87,7 @@ export function shouldRunSqlSemanticDiagnostics(
return true;
}
-function resolveColumnTable(
- column: SqlColumnReference,
- tables: SqlTableReference[],
- knownTables: Map<string, SqlTableReference>,
-): SqlTableReference | null {
+function resolveColumnTable(column: SqlColumnReference, tables: SqlTableReference[], knownTables: Map<string, SqlTableReference>): SqlTableReference | null {
if (column.qualifier) {
return knownTables.get(normalizeName(column.qualifier)) ?? null;
}
@@ -123,10 +95,7 @@ function resolveColumnTable(
return tables[0];
}
-function columnsForTable(
- table: SqlTableReference,
- columnsByTable: Map<string, SqlCompletionColumn[]>,
-): SqlCompletionColumn[] | null {
+function columnsForTable(table: SqlTableReference, columnsByTable: Map<string, SqlCompletionColumn[]>): SqlCompletionColumn[] | null {
const keys = table.schema ? [`${table.schema}.${table.name}`, table.name] : [table.name];
for (const key of keys) {
const columns = columnsByTable.get(key) ?? columnsByTable.get(normalizeName(key));
diff --git a/apps/desktop/src/lib/sqlServerTree.ts b/apps/desktop/src/lib/sqlServerTree.ts
index d66234ff25..497e82a2ef 100644
--- a/apps/desktop/src/lib/sqlServerTree.ts
+++ b/apps/desktop/src/lib/sqlServerTree.ts
@@ -1,11 +1,6 @@
import type { ObjectInfo, TreeNode } from "@/types/database";
import { sortSidebarNames } from "@/lib/databaseTree";
-import {
- buildGroupedObjectTreeNodes,
- buildObjectGroupPlaceholderNodes,
- buildSimpleObjectTreeNodes,
- type DatabaseObjectTreeKind,
-} from "@/lib/tableTree";
+import { buildGroupedObjectTreeNodes, buildObjectGroupPlaceholderNodes, buildSimpleObjectTreeNodes, type DatabaseObjectTreeKind } from "@/lib/tableTree";
export const SQLSERVER_DEFAULT_SCHEMA = "dbo";
@@ -13,13 +8,7 @@ function isDefaultSchema(schema: string): boolean {
return schema.toLowerCase() === SQLSERVER_DEFAULT_SCHEMA;
}
-export function buildSqlServerDatabaseTreeNodes(
- connectionId: string,
- database: string,
- schemas: string[],
- defaultSchemaObjects: ObjectInfo[],
- options: { lazyObjectTypes?: DatabaseObjectTreeKind[]; simpleObjectDisplay?: boolean } = {},
-): TreeNode[] {
+export function buildSqlServerDatabaseTreeNodes(connectionId: string, database: string, schemas: string[], defaultSchemaObjects: ObjectInfo[], options: { lazyObjectTypes?: DatabaseObjectTreeKind[]; simpleObjectDisplay?: boolean } = {}): TreeNode[] {
const databaseNodeId = `${connectionId}:${database}`;
const defaultSchema = schemas.find(isDefaultSchema) || SQLSERVER_DEFAULT_SCHEMA;
diff --git a/apps/desktop/src/lib/tabCloseActions.ts b/apps/desktop/src/lib/tabCloseActions.ts
index 71ad1ea145..3c7bc5276b 100644
--- a/apps/desktop/src/lib/tabCloseActions.ts
+++ b/apps/desktop/src/lib/tabCloseActions.ts
@@ -7,20 +7,13 @@ export interface TabCloseState<T extends TabLike> {
activeTabId: string | null;
}
-export function closeOtherTabsState<T extends TabLike>(
- tabs: readonly T[],
- activeTabId: string | null,
- targetTabId: string,
-): TabCloseState<T> {
+export function closeOtherTabsState<T extends TabLike>(tabs: readonly T[], activeTabId: string | null, targetTabId: string): TabCloseState<T> {
const target = tabs.find((tab) => tab.id === targetTabId);
if (!target) return { tabs: [...tabs], activeTabId };
return { tabs: [target], activeTabId: target.id };
}
-export function closeAllTabsState<T extends TabLike>(
- _tabs: readonly T[],
- _activeTabId: string | null,
-): TabCloseState<T> {
+export function closeAllTabsState<T extends TabLike>(_tabs: readonly T[], _activeTabId: string | null): TabCloseState<T> {
return { tabs: [], activeTabId: null };
}
diff --git a/apps/desktop/src/lib/tabPresentation.ts b/apps/desktop/src/lib/tabPresentation.ts
index ba0432e49c..f5adef25fe 100644
--- a/apps/desktop/src/lib/tabPresentation.ts
+++ b/apps/desktop/src/lib/tabPresentation.ts
@@ -39,10 +39,7 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
if (isPreviewTab(tab)) return tab.title;
if (tab.mode === "data" && tab.tableMeta?.tableName) {
if (compact) return tab.tableMeta.tableName;
- const suffix =
- tab.tableMeta.schema && tab.tableMeta.schema !== tab.database
- ? `@${database}.${tab.tableMeta.schema}`
- : `@${database}`;
+ const suffix = tab.tableMeta.schema && tab.tableMeta.schema !== tab.database ? `@${database}.${tab.tableMeta.schema}` : `@${database}`;
return `${tab.tableMeta.tableName}${suffix}`;
}
if (tab.mode === "query") {
@@ -97,9 +94,7 @@ export function tabTooltipLines(tab: QueryTab, t: Translate): { label: string; v
return lines;
}
-export function tabularResultItems(
- results: QueryResult[] | undefined,
-): { result: QueryResult; index: number; n: number }[] {
+export function tabularResultItems(results: QueryResult[] | undefined): { result: QueryResult; index: number; n: number }[] {
if (!results) return [];
return results
.map((result, index) => ({ result, index }))
diff --git a/apps/desktop/src/lib/tabResultCache.ts b/apps/desktop/src/lib/tabResultCache.ts
index f5d01cd708..42e910800c 100644
--- a/apps/desktop/src/lib/tabResultCache.ts
+++ b/apps/desktop/src/lib/tabResultCache.ts
@@ -143,9 +143,7 @@ function toColumnarResult(result: QueryResult | undefined): ColumnarQueryResult
function fromColumnarResult(result: ColumnarQueryResult | undefined): QueryResult | undefined {
if (!result) return undefined;
- const rows = Array.from({ length: result.rowCount }, (_, rowIndex) =>
- result.columnValues.map((values) => values[rowIndex] ?? null),
- );
+ const rows = Array.from({ length: result.rowCount }, (_, rowIndex) => result.columnValues.map((values) => values[rowIndex] ?? null));
return {
columns: [...result.columns],
column_types: result.column_types ? [...result.column_types] : undefined,
@@ -199,16 +197,10 @@ function base64ToBytes(value: string): Uint8Array {
}
function canUseRemoteRuntimeCache(): boolean {
- return (
- typeof btoa !== "undefined" && typeof atob !== "undefined" && (isTauriRuntime() || typeof fetch !== "undefined")
- );
+ return typeof btoa !== "undefined" && typeof atob !== "undefined" && (isTauriRuntime() || typeof fetch !== "undefined");
}
-async function writeRemoteRuntimeCache(
- key: string,
- bytes: Uint8Array,
- stats: { rowCount: number; columnCount: number },
-): Promise<boolean> {
+async function writeRemoteRuntimeCache(key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }): Promise<boolean> {
if (!canUseRemoteRuntimeCache()) return false;
try {
if (isTauriRuntime()) {
@@ -270,12 +262,7 @@ async function deleteRemoteRuntimeCache(key: string): Promise<void> {
}
}
-function scheduleRemoteRuntimeCacheWrite(
- key: string,
- bytes: Uint8Array,
- stats: { rowCount: number; columnCount: number },
- version: number,
-) {
+function scheduleRemoteRuntimeCacheWrite(key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }, version: number) {
window.setTimeout(async () => {
if (!isCurrentCacheKeyVersion(key, version)) return;
await writeRemoteRuntimeCache(key, bytes, stats);
diff --git a/apps/desktop/src/lib/tableDataExport.ts b/apps/desktop/src/lib/tableDataExport.ts
index caffc0f228..0ff90443c4 100644
--- a/apps/desktop/src/lib/tableDataExport.ts
+++ b/apps/desktop/src/lib/tableDataExport.ts
@@ -9,14 +9,7 @@ export interface FetchTableDataForExportOptions {
tableName: string;
columns?: string[];
pageSize?: number;
- buildPageSql?: (options: {
- databaseType?: DatabaseType;
- schema?: string;
- tableName: string;
- columns?: string[];
- limit: number;
- offset: number;
- }) => Promise<string> | string;
+ buildPageSql?: (options: { databaseType?: DatabaseType; schema?: string; tableName: string; columns?: string[]; limit: number; offset: number }) => Promise<string> | string;
executePage: (sql: string) => Promise<QueryResult>;
}
diff --git a/apps/desktop/src/lib/tableEditing.ts b/apps/desktop/src/lib/tableEditing.ts
index b29bebebe1..c2c6b84d13 100644
--- a/apps/desktop/src/lib/tableEditing.ts
+++ b/apps/desktop/src/lib/tableEditing.ts
@@ -29,17 +29,12 @@ export function usesKeylessRowPredicate(databaseType: DatabaseType | undefined):
return !!getDatabaseCapability(databaseType).tableData.keylessRowPredicate;
}
-export function canEditExistingTableRows(
- databaseType: DatabaseType | undefined,
- hiveTableTransactional?: boolean,
- primaryKeys?: string[],
-): boolean {
+export function canEditExistingTableRows(databaseType: DatabaseType | undefined, hiveTableTransactional?: boolean, primaryKeys?: string[]): boolean {
const tableData = getDatabaseCapability(databaseType).tableData;
if (tableData.readonly) return false;
if (tableData.existingRowsReadonly) return false;
if (tableData.requiresTransactionalTableForExistingRows && hiveTableTransactional !== true) return false;
- if (databaseType === "tdengine" && !primaryKeys?.some((key) => key.toLowerCase() === DBX_TDENGINE_TBNAME_COLUMN))
- return false;
+ if (databaseType === "tdengine" && !primaryKeys?.some((key) => key.toLowerCase() === DBX_TDENGINE_TBNAME_COLUMN)) return false;
if (tableData.updateRequiresPrimaryKey && primaryKeys && primaryKeys.length === 0) return false;
return true;
}
@@ -57,27 +52,15 @@ export function hiveTablePropertiesIndicateTransactional(result: { rows: readonl
}
export function usesSyntheticRowIdKey(databaseType: DatabaseType | undefined, primaryKeys: string[]): boolean {
- return (
- primaryKeys.length === 1 &&
- ((databaseType === "oracle" && primaryKeys[0].toUpperCase() === DBX_ROWID_COLUMN) ||
- (databaseType === "neo4j" && primaryKeys[0] === DBX_NEO4J_ELEMENT_ID_COLUMN))
- );
+ return primaryKeys.length === 1 && ((databaseType === "oracle" && primaryKeys[0].toUpperCase() === DBX_ROWID_COLUMN) || (databaseType === "neo4j" && primaryKeys[0] === DBX_NEO4J_ELEMENT_ID_COLUMN));
}
-export function isHiddenGridColumn(
- databaseType: DatabaseType | undefined,
- column: string,
- primaryKeys: string[],
-): boolean {
+export function isHiddenGridColumn(databaseType: DatabaseType | undefined, column: string, primaryKeys: string[]): boolean {
if (databaseType === "neo4j" && column === DBX_NEO4J_ELEMENT_ID_COLUMN) return true;
return usesSyntheticRowIdKey(databaseType, primaryKeys) && column.toUpperCase() === DBX_ROWID_COLUMN;
}
-export function isTdengineExistingRowReadonlyColumn(
- databaseType: DatabaseType | undefined,
- column: string,
- columns: ColumnInfo[],
-): boolean {
+export function isTdengineExistingRowReadonlyColumn(databaseType: DatabaseType | undefined, column: string, columns: ColumnInfo[]): boolean {
if (databaseType !== "tdengine") return false;
if (column.toLowerCase() === DBX_TDENGINE_TBNAME_COLUMN) return true;
const columnInfo = columns.find((info) => info.name.toLowerCase() === column.toLowerCase());
diff --git a/apps/desktop/src/lib/tableImport.ts b/apps/desktop/src/lib/tableImport.ts
index 394aff64ff..0edf0dba65 100644
--- a/apps/desktop/src/lib/tableImport.ts
+++ b/apps/desktop/src/lib/tableImport.ts
@@ -8,10 +8,5 @@ export function autoMapImportColumns(sourceColumns: string[], targetColumns: str
const exactTargets = new Map(targetColumns.map((column) => [column, column]));
const normalizedTargets = new Map(targetColumns.map((column) => [normalizeImportColumnName(column), column]));
- return Object.fromEntries(
- sourceColumns.map((source) => [
- source,
- exactTargets.get(source) ?? normalizedTargets.get(normalizeImportColumnName(source)) ?? IMPORT_SKIP_TARGET,
- ]),
- );
+ return Object.fromEntries(sourceColumns.map((source) => [source, exactTargets.get(source) ?? normalizedTargets.get(normalizeImportColumnName(source)) ?? IMPORT_SKIP_TARGET]));
}
diff --git a/apps/desktop/src/lib/tableSelectSql.ts b/apps/desktop/src/lib/tableSelectSql.ts
index 0e6500b380..f409648d96 100644
--- a/apps/desktop/src/lib/tableSelectSql.ts
+++ b/apps/desktop/src/lib/tableSelectSql.ts
@@ -19,14 +19,7 @@ export interface BuildTableSelectSqlOptions {
export function quoteTableIdentifier(databaseType: DatabaseType | undefined, name: string): string {
if (databaseType === "iotdb") return name;
if (databaseType === "jdbc") return quoteJdbcIdentifier(name);
- if (
- databaseType === "mysql" ||
- databaseType === "hive" ||
- databaseType === "databend" ||
- databaseType === "tdengine" ||
- databaseType === "access"
- )
- return `\`${name.replace(/`/g, "``")}\``;
+ if (databaseType === "mysql" || databaseType === "hive" || databaseType === "databend" || databaseType === "tdengine" || databaseType === "access") return `\`${name.replace(/`/g, "``")}\``;
if (databaseType === "informix" && /^[A-Za-z_][A-Za-z0-9_$]*$/.test(name)) return name;
if (databaseType === "neo4j") return quoteCypherIdentifier(name);
if (databaseType === "sqlserver") return `[${name.replace(/\]/g, "]]")}]`;
@@ -42,9 +35,7 @@ function quoteJdbcIdentifier(name: string): string {
return `\`${name.replace(/`/g, "``")}\``;
}
-export function qualifiedTableName(
- options: Pick<BuildTableSelectSqlOptions, "databaseType" | "schema" | "tableName">,
-): string {
+export function qualifiedTableName(options: Pick<BuildTableSelectSqlOptions, "databaseType" | "schema" | "tableName">): string {
const { databaseType, schema, tableName } = options;
if (databaseType === "iotdb") {
const trimmedSchema = schema?.trim();
diff --git a/apps/desktop/src/lib/tableStructureCapabilities.ts b/apps/desktop/src/lib/tableStructureCapabilities.ts
index 1920e3c630..34199a0af4 100644
--- a/apps/desktop/src/lib/tableStructureCapabilities.ts
+++ b/apps/desktop/src/lib/tableStructureCapabilities.ts
@@ -1,15 +1,6 @@
import type { DatabaseType } from "@/types/database";
-export type TableStructureDialect =
- | "mysql"
- | "postgres"
- | "sqlite"
- | "duckdb"
- | "sqlserver"
- | "oracle"
- | "h2"
- | "clickhouse"
- | "unsupported";
+export type TableStructureDialect = "mysql" | "postgres" | "sqlite" | "duckdb" | "sqlserver" | "oracle" | "h2" | "clickhouse" | "unsupported";
export interface TableStructureCapabilities {
dialect: TableStructureDialect;
diff --git a/apps/desktop/src/lib/tableStructureEditorState.ts b/apps/desktop/src/lib/tableStructureEditorState.ts
index 0ec8847b26..1702da4f2d 100644
--- a/apps/desktop/src/lib/tableStructureEditorState.ts
+++ b/apps/desktop/src/lib/tableStructureEditorState.ts
@@ -297,15 +297,7 @@ export function parseExtraToColumnExtra(extra: string | null | undefined, databa
if (lower.includes("on update current_timestamp")) {
result.onUpdateCurrentTimestamp = true;
}
- } else if (
- databaseType === "postgres" ||
- databaseType === "gaussdb" ||
- databaseType === "kwdb" ||
- databaseType === "opengauss" ||
- databaseType === "highgo" ||
- databaseType === "vastbase" ||
- databaseType === "kingbase"
- ) {
+ } else if (databaseType === "postgres" || databaseType === "gaussdb" || databaseType === "kwdb" || databaseType === "opengauss" || databaseType === "highgo" || databaseType === "vastbase" || databaseType === "kingbase") {
const identityMatch = lower.match(/generated\s+(by\s+default|always)\s+as\s+identity/i);
if (identityMatch) {
const sequenceMatch = lower.match(/start\s+with\s*(-?\d+)\s+increment\s+by\s*(-?\d+)/i);
@@ -414,14 +406,7 @@ function isTemporalPrecisionType(dbType: DatabaseType | undefined, baseType: str
case "vastbase":
case "kingbase":
case "redshift":
- return [
- "time",
- "time without time zone",
- "time with time zone",
- "timestamp",
- "timestamp without time zone",
- "timestamp with time zone",
- ].includes(normalized);
+ return ["time", "time without time zone", "time with time zone", "timestamp", "timestamp without time zone", "timestamp with time zone"].includes(normalized);
case "sqlserver":
return ["time", "datetime2", "datetimeoffset"].includes(normalized);
case "oracle":
@@ -445,12 +430,7 @@ export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseT
return DEFAULT_TYPE_LENGTHS[key] ?? "";
}
-export function buildStructureTargetLabel(
- connectionName: string | undefined,
- database: string | undefined,
- schema: string | undefined,
- tableName: string | undefined,
-): string {
+export function buildStructureTargetLabel(connectionName: string | undefined, database: string | undefined, schema: string | undefined, tableName: string | undefined): string {
const parts = [connectionName, database];
if (schema && schema !== database) parts.push(schema);
if (tableName) parts.push(tableName);
diff --git a/apps/desktop/src/lib/tableTree.ts b/apps/desktop/src/lib/tableTree.ts
index a224ca11f0..43214316dd 100644
--- a/apps/desktop/src/lib/tableTree.ts
+++ b/apps/desktop/src/lib/tableTree.ts
@@ -7,19 +7,7 @@ export function normalizeDatabaseObjectName(name: string): string {
return name.trim();
}
-export function buildTableTreeNodes({
- nodeId,
- connectionId,
- database,
- schema,
- tables,
-}: {
- nodeId: string;
- connectionId: string;
- database: string;
- schema?: string;
- tables: TableInfo[];
-}): TreeNode[] {
+export function buildTableTreeNodes({ nodeId, connectionId, database, schema, tables }: { nodeId: string; connectionId: string; database: string; schema?: string; tables: TableInfo[] }): TreeNode[] {
const entries = tables.flatMap((table) => {
const name = normalizeDatabaseObjectName(table.name);
if (!name) return [];
@@ -213,11 +201,7 @@ export function sortDatabaseObjectsByName<T>(items: readonly T[], getName: (item
return [...items].sort((left, right) => databaseObjectNameCollator.compare(getName(left), getName(right)));
}
-export function mergeTableInfosIntoObjects(
- objects: readonly ObjectInfo[],
- tables: readonly TableInfo[],
- schema?: string,
-): ObjectInfo[] {
+export function mergeTableInfosIntoObjects(objects: readonly ObjectInfo[], tables: readonly TableInfo[], schema?: string): ObjectInfo[] {
const merged = [...objects];
const seen = new Set(
merged.map((obj) => {
@@ -237,8 +221,7 @@ export function mergeTableInfosIntoObjects(
if (objName.toLowerCase() !== name.toLowerCase()) return false;
return normalizeObjectType(obj.object_type) === objectType;
});
- const tableSchema =
- schema ?? (matchingObject?.schema ? normalizeDatabaseObjectName(matchingObject.schema) : undefined);
+ const tableSchema = schema ?? (matchingObject?.schema ? normalizeDatabaseObjectName(matchingObject.schema) : undefined);
const key = `${objectType}\0${(tableSchema || "").toLowerCase()}\0${name.toLowerCase()}`;
if (seen.has(key)) continue;
seen.add(key);
@@ -318,21 +301,7 @@ export function hasTablePartitionGroups(node: TreeNode): boolean {
export type DatabaseObjectTreeKind = SidebarObjectKind;
-function buildObjectTreeEntries({
- nodeId,
- connectionId,
- database,
- schema,
- objects,
- objectType,
-}: {
- nodeId: string;
- connectionId: string;
- database: string;
- schema?: string;
- objects: ObjectInfo[];
- objectType: "TABLE" | "VIEW";
-}): TreeNode[] {
+function buildObjectTreeEntries({ nodeId, connectionId, database, schema, objects, objectType }: { nodeId: string; connectionId: string; database: string; schema?: string; objects: ObjectInfo[]; objectType: "TABLE" | "VIEW" }): TreeNode[] {
const entries = objects.flatMap((obj) => {
const name = normalizeDatabaseObjectName(obj.name);
if (!name) return [];
@@ -355,19 +324,7 @@ function buildObjectTreeEntries({
return buildPartitionTree(entries, connectionId, database);
}
-export function buildSimpleObjectTreeNodes({
- nodeId,
- connectionId,
- database,
- schema,
- objects,
-}: {
- nodeId: string;
- connectionId: string;
- database: string;
- schema?: string;
- objects: ObjectInfo[];
-}): TreeNode[] {
+export function buildSimpleObjectTreeNodes({ nodeId, connectionId, database, schema, objects }: { nodeId: string; connectionId: string; database: string; schema?: string; objects: ObjectInfo[] }): TreeNode[] {
const seen = new Set<string>();
const tableEntries: TableTreeEntry[] = [];
const objectNodes: TreeNode[] = [];
@@ -402,10 +359,7 @@ export function buildSimpleObjectTreeNodes({
} else {
const simpleNodeType = simpleObjectNodeType(objectType);
objectNodes.push({
- id:
- objectType === "VIEW"
- ? entry.node.id
- : `${nodeId}:${childSchema ? `${childSchema}:` : ""}${name}:${objectType}`,
+ id: objectType === "VIEW" ? entry.node.id : `${nodeId}:${childSchema ? `${childSchema}:` : ""}${name}:${objectType}`,
label: name,
type: simpleNodeType,
comment: obj.comment,
@@ -418,10 +372,7 @@ export function buildSimpleObjectTreeNodes({
}
}
- return [
- ...buildPartitionTree(tableEntries, connectionId, database),
- ...sortDatabaseObjectsByName(objectNodes, (node) => node.label),
- ];
+ return [...buildPartitionTree(tableEntries, connectionId, database), ...sortDatabaseObjectsByName(objectNodes, (node) => node.label)];
}
function simpleObjectNodeType(objectType: DatabaseObjectTreeKind): TreeNodeType {
@@ -477,28 +428,9 @@ const groupDefs: Array<{
},
];
-const objectGroupNodeTypes = new Set<TreeNodeType>([
- "group-tables",
- "group-views",
- "group-procedures",
- "group-functions",
- "group-sequences",
- "group-packages",
-]);
+const objectGroupNodeTypes = new Set<TreeNodeType>(["group-tables", "group-views", "group-procedures", "group-functions", "group-sequences", "group-packages"]);
-export function buildObjectGroupPlaceholderNodes({
- nodeId,
- connectionId,
- database,
- schema,
- objectTypes,
-}: {
- nodeId: string;
- connectionId: string;
- database: string;
- schema?: string;
- objectTypes: DatabaseObjectTreeKind[];
-}): TreeNode[] {
+export function buildObjectGroupPlaceholderNodes({ nodeId, connectionId, database, schema, objectTypes }: { nodeId: string; connectionId: string; database: string; schema?: string; objectTypes: DatabaseObjectTreeKind[] }): TreeNode[] {
const supported = new Set(objectTypes);
return groupDefs
.filter((def) => def.objectTypes.some((objectType) => supported.has(objectType)))
@@ -525,19 +457,7 @@ export function objectTypesForGroupNode(type: TreeNodeType): DatabaseObjectTreeK
return groupDefs.find((def) => def.nodeType === type)?.objectTypes ?? null;
}
-export function buildGroupedObjectTreeNodes({
- nodeId,
- connectionId,
- database,
- schema,
- objects,
-}: {
- nodeId: string;
- connectionId: string;
- database: string;
- schema?: string;
- objects: ObjectInfo[];
-}): TreeNode[] {
+export function buildGroupedObjectTreeNodes({ nodeId, connectionId, database, schema, objects }: { nodeId: string; connectionId: string; database: string; schema?: string; objects: ObjectInfo[] }): TreeNode[] {
const buckets = new Map<string, ObjectInfo[]>();
const seen = new Set<string>();
for (const obj of objects) {
diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts
index 7504d09979..10952b8b1e 100644
--- a/apps/desktop/src/lib/tauri.ts
+++ b/apps/desktop/src/lib/tauri.ts
@@ -24,43 +24,17 @@ import type {
import type { SidebarObjectKind } from "@/lib/databaseObjectCapabilities";
import type { AiConfig } from "@/stores/settingsStore";
import type { QueryEditability } from "@/lib/sqlAnalysis";
-import type {
- DataGridColumnValueFilterConditionOptions,
- DataGridContextFilterConditionOptions,
- DataGridCountSqlOptions,
- DataGridCopyInsertStatementOptions,
- DataGridCopyUpdateStatementOptions,
- DataGridSaveStatementOptions,
- HiveTablePropertiesSqlOptions,
-} from "@/lib/dataGridSql";
-import type {
- DataCompareFromTablesOptions,
- DataCompareFromTablesPreparation,
- DataCompareSyncPlan,
- DataCompareSyncPlanOptions,
- DataComparePreparation,
- DataComparePreparationOptions,
-} from "@/lib/dataCompare";
+import type { DataGridColumnValueFilterConditionOptions, DataGridContextFilterConditionOptions, DataGridCountSqlOptions, DataGridCopyInsertStatementOptions, DataGridCopyUpdateStatementOptions, DataGridSaveStatementOptions, HiveTablePropertiesSqlOptions } from "@/lib/dataGridSql";
+import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataCompare";
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff } from "@/lib/schemaDiff";
-import type {
- BuildTableStructureChangeSqlOptions,
- BuildSingleColumnAlterSqlOptions,
- TableStructureChangeSql,
-} from "@/lib/tableStructureEditorSql";
+import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, TableStructureChangeSql } from "@/lib/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/databaseSearch";
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/objectSourceEditor";
import type { BuildViewDdlInput } from "@/lib/viewDdl";
import type { BuildRenameObjectSqlOptions } from "@/lib/objectRenameSql";
import type { CreateDatabaseSqlOptions } from "@/lib/createDatabaseSql";
-import type {
- DatabaseNameSqlOptions,
- DropTableChildObjectSqlOptions,
- DropObjectSqlOptions,
- DuplicateTableStructureSqlOptions,
- SchemaNameSqlOptions,
- TableAdminSqlOptions,
-} from "@/lib/dbAdminSql";
+import type { DatabaseNameSqlOptions, DropTableChildObjectSqlOptions, DropObjectSqlOptions, DuplicateTableStructureSqlOptions, SchemaNameSqlOptions, TableAdminSqlOptions } from "@/lib/dbAdminSql";
import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions } from "@/lib/databaseExport";
export interface AgentDriverInfo {
@@ -284,11 +258,7 @@ export interface AiStreamChunk {
done: boolean;
}
-export async function aiStream(
- sessionId: string,
- request: AiCompletionRequest,
- onChunk: (chunk: AiStreamChunk) => void,
-): Promise<void> {
+export async function aiStream(sessionId: string, request: AiCompletionRequest, onChunk: (chunk: AiStreamChunk) => void): Promise<void> {
const unlisten: UnlistenFn = await listen<AiStreamChunk>("ai-stream-chunk", (event) => {
if (event.payload.session_id === sessionId) {
onChunk(event.payload);
@@ -347,18 +317,11 @@ export async function forgetWebdavSavedPassword(config: WebDavConfig): Promise<v
return invoke("forget_webdav_saved_password", { config });
}
-export async function webdavSyncUpload(
- config: WebDavConfig,
- editorSettings?: unknown,
- secretsPassphrase?: string,
-): Promise<WebDavSyncSummary> {
+export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string): Promise<WebDavSyncSummary> {
return invoke("webdav_sync_upload", { config, editorSettings, secretsPassphrase });
}
-export async function webdavSyncDownload(
- config: WebDavConfig,
- secretsPassphrase?: string,
-): Promise<WebDavDownloadResult> {
+export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string): Promise<WebDavDownloadResult> {
return invoke("webdav_sync_download", { config, secretsPassphrase });
}
@@ -456,40 +419,19 @@ export async function deleteSchemaCachePrefix(prefix: string): Promise<void> {
return invoke("delete_schema_cache_prefix", { prefix });
}
-export async function listTables(
- connectionId: string,
- database: string,
- schema: string,
- filter?: string,
- limit?: number,
-): Promise<TableInfo[]> {
+export async function listTables(connectionId: string, database: string, schema: string, filter?: string, limit?: number): Promise<TableInfo[]> {
return invoke("list_tables", { connectionId, database, schema, filter, limit });
}
-export async function listObjects(
- connectionId: string,
- database: string,
- schema: string,
- objectTypes?: SidebarObjectKind[],
-): Promise<ObjectInfo[]> {
+export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: SidebarObjectKind[]): Promise<ObjectInfo[]> {
return invoke("list_objects", { connectionId, database, schema, objectTypes });
}
-export async function listCompletionObjects(
- connectionId: string,
- database: string,
- schema: string,
-): Promise<ObjectInfo[]> {
+export async function listCompletionObjects(connectionId: string, database: string, schema: string): Promise<ObjectInfo[]> {
return invoke("list_completion_objects", { connectionId, database, schema });
}
-export async function getObjectSource(
- connectionId: string,
- database: string,
- schema: string,
- name: string,
- objectType: ObjectSourceKind,
-): Promise<ObjectSource> {
+export async function getObjectSource(connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind): Promise<ObjectSource> {
return invoke("get_object_source", { connectionId, database, schema, name, objectType });
}
@@ -497,12 +439,7 @@ export async function listSchemas(connectionId: string, database: string): Promi
return invoke("list_schemas", { connectionId, database });
}
-export async function getColumns(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<ColumnInfo[]> {
+export async function getColumns(connectionId: string, database: string, schema: string, table: string): Promise<ColumnInfo[]> {
return invoke("get_columns", { connectionId, database, schema, table });
}
@@ -550,48 +487,23 @@ export async function cancelQuery(executionId: string): Promise<boolean> {
return invoke("cancel_query", { executionId });
}
-export async function closeQuerySession(
- connectionId: string,
- database: string,
- sessionId: string,
- clientSessionId?: string,
-): Promise<boolean> {
+export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string): Promise<boolean> {
return invoke("close_query_session", { connectionId, database, sessionId, clientSessionId });
}
-export async function closeClientConnectionSession(
- connectionId: string,
- database: string,
- clientSessionId: string,
-): Promise<boolean> {
+export async function closeClientConnectionSession(connectionId: string, database: string, clientSessionId: string): Promise<boolean> {
return invoke("close_client_connection_session", { connectionId, database, clientSessionId });
}
-export async function executeBatch(
- connectionId: string,
- database: string,
- statements: string[],
- schema?: string,
- timeoutSecs?: number,
-): Promise<QueryResult> {
+export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number): Promise<QueryResult> {
return invoke("execute_batch", { connectionId, database, statements, schema, timeoutSecs });
}
-export async function executeScript(
- connectionId: string,
- database: string,
- sql: string,
- schema?: string,
-): Promise<QueryResult> {
+export async function executeScript(connectionId: string, database: string, sql: string, schema?: string): Promise<QueryResult> {
return invoke("execute_script", { connectionId, database, sql, schema });
}
-export async function executeInTransaction(
- connectionId: string,
- database: string,
- statements: string[],
- schema?: string,
-): Promise<QueryResult> {
+export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string): Promise<QueryResult> {
return invoke("execute_in_transaction", { connectionId, database, statements, schema });
}
@@ -599,17 +511,11 @@ export async function analyzeSqlReferences(sql: string, dialect?: string): Promi
return invoke("analyze_sql_references", { sql, dialect });
}
-export async function findStatementAtCursor(
- sql: string,
- cursorPos: number,
- databaseType?: DatabaseType,
-): Promise<string> {
+export async function findStatementAtCursor(sql: string, cursorPos: number, databaseType?: DatabaseType): Promise<string> {
return invoke("find_statement_at_cursor", { sql, cursorPos, databaseType });
}
-export async function prepareQueryPaginationExecutionPlan(
- options: QueryPaginationExecutionPlanOptions,
-): Promise<QueryPaginationExecutionPlan> {
+export async function prepareQueryPaginationExecutionPlan(options: QueryPaginationExecutionPlanOptions): Promise<QueryPaginationExecutionPlan> {
return invoke("prepare_query_pagination_execution_plan", { options });
}
@@ -625,13 +531,7 @@ export async function buildCreateUserSql(username: string, password: string, tab
return invoke("build_create_user_sql", { username, password, tablespace });
}
-export async function getExplainInfo(
- connectionId: string,
- database: string | undefined,
- schema: string | undefined,
- sql: string,
- mode: string,
-): Promise<string | undefined> {
+export async function getExplainInfo(connectionId: string, database: string | undefined, schema: string | undefined, sql: string, mode: string): Promise<string | undefined> {
try {
const result = await invoke<string>("get_explain_info", { connectionId, database, schema, sql, mode });
return result;
@@ -706,9 +606,7 @@ export async function buildDuplicateTableStructureSql(options: DuplicateTableStr
return invoke("build_duplicate_table_structure_sql", { options });
}
-export async function buildExecutableObjectSourceStatements(
- input: BuildEditableObjectSourceSqlInput,
-): Promise<string[]> {
+export async function buildExecutableObjectSourceStatements(input: BuildEditableObjectSourceSqlInput): Promise<string[]> {
return invoke("build_executable_object_source_statements", { input });
}
@@ -716,9 +614,7 @@ export async function buildExecutableObjectSourceSql(input: BuildEditableObjectS
return invoke("build_executable_object_source_sql", { input });
}
-export async function buildRoutineRenameObjectSourceStatements(
- input: BuildRoutineRenameObjectSourceInput,
-): Promise<string[]> {
+export async function buildRoutineRenameObjectSourceStatements(input: BuildRoutineRenameObjectSourceInput): Promise<string[]> {
return invoke("build_routine_rename_object_source_statements", { input });
}
@@ -726,21 +622,15 @@ export async function buildViewDdlSql(input: BuildViewDdlInput): Promise<string>
return invoke("build_view_ddl_sql", { input });
}
-export async function buildTableStructureChangeSql(
- options: BuildTableStructureChangeSqlOptions,
-): Promise<TableStructureChangeSql> {
+export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
return invoke("build_table_structure_change_sql", { options });
}
-export async function buildCreateTableSql(
- options: BuildTableStructureChangeSqlOptions,
-): Promise<TableStructureChangeSql> {
+export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
return invoke("build_create_table_sql", { options });
}
-export async function buildSingleColumnAlterSql(
- options: BuildSingleColumnAlterSqlOptions,
-): Promise<TableStructureChangeSql> {
+export async function buildSingleColumnAlterSql(options: BuildSingleColumnAlterSqlOptions): Promise<TableStructureChangeSql> {
return invoke("build_single_column_alter_sql", { options });
}
@@ -759,29 +649,21 @@ export async function prepareDataGridSave(options: DataGridSaveStatementOptions)
return invoke("prepare_data_grid_save", { options });
}
-export async function buildDataGridCopyUpdateStatements(
- options: DataGridCopyUpdateStatementOptions,
-): Promise<string[]> {
+export async function buildDataGridCopyUpdateStatements(options: DataGridCopyUpdateStatementOptions): Promise<string[]> {
return invoke("build_data_grid_copy_update_statements", { options });
}
-export async function buildDataGridCopyInsertStatement(
- options: DataGridCopyInsertStatementOptions,
-): Promise<string | undefined> {
+export async function buildDataGridCopyInsertStatement(options: DataGridCopyInsertStatementOptions): Promise<string | undefined> {
const result = await invoke<string | null>("build_data_grid_copy_insert_statement", { options });
return result ?? undefined;
}
-export async function buildDataGridContextFilterCondition(
- options: DataGridContextFilterConditionOptions,
-): Promise<string | undefined> {
+export async function buildDataGridContextFilterCondition(options: DataGridContextFilterConditionOptions): Promise<string | undefined> {
const result = await invoke<string | null>("build_data_grid_context_filter_condition", { options });
return result ?? undefined;
}
-export async function buildDataGridColumnValueFilterCondition(
- options: DataGridColumnValueFilterConditionOptions,
-): Promise<string | undefined> {
+export async function buildDataGridColumnValueFilterCondition(options: DataGridColumnValueFilterConditionOptions): Promise<string | undefined> {
const result = await invoke<string | null>("build_data_grid_column_value_filter_condition", { options });
return result ?? undefined;
}
@@ -810,15 +692,11 @@ export async function prepareDataCompare(options: DataComparePreparationOptions)
return invoke("prepare_data_compare", { options });
}
-export async function prepareDataCompareFromTables(
- options: DataCompareFromTablesOptions,
-): Promise<DataCompareFromTablesPreparation> {
+export async function prepareDataCompareFromTables(options: DataCompareFromTablesOptions): Promise<DataCompareFromTablesPreparation> {
return invoke("prepare_data_compare_from_tables", { options });
}
-export async function prepareDataCompareMissingTarget(
- options: import("@/lib/dataCompare").DataCompareMissingTargetOptions,
-): Promise<DataCompareFromTablesPreparation> {
+export async function prepareDataCompareMissingTarget(options: import("@/lib/dataCompare").DataCompareMissingTargetOptions): Promise<DataCompareFromTablesPreparation> {
return invoke("prepare_data_compare_missing_target", { options });
}
@@ -826,39 +704,19 @@ export async function buildDataCompareSyncPlan(options: DataCompareSyncPlanOptio
return invoke("build_data_compare_sync_plan", { options });
}
-export async function listIndexes(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<IndexInfo[]> {
+export async function listIndexes(connectionId: string, database: string, schema: string, table: string): Promise<IndexInfo[]> {
return invoke("list_indexes", { connectionId, database, schema, table });
}
-export async function listForeignKeys(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<ForeignKeyInfo[]> {
+export async function listForeignKeys(connectionId: string, database: string, schema: string, table: string): Promise<ForeignKeyInfo[]> {
return invoke("list_foreign_keys", { connectionId, database, schema, table });
}
-export async function listTriggers(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<TriggerInfo[]> {
+export async function listTriggers(connectionId: string, database: string, schema: string, table: string): Promise<TriggerInfo[]> {
return invoke("list_triggers", { connectionId, database, schema, table });
}
-export async function getTableDdl(
- connectionId: string,
- database: string,
- schema: string,
- table: string,
-): Promise<string> {
+export async function getTableDdl(connectionId: string, database: string, schema: string, table: string): Promise<string> {
return invoke("get_table_ddl", { connectionId, database, schema, table });
}
@@ -866,11 +724,7 @@ export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions):
return invoke("prepare_schema_diff", { options });
}
-export async function generateSchemaSyncSql(
- diffs: TableDiff[],
- databaseType: DatabaseType,
- targetSchema?: string,
-): Promise<string> {
+export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string): Promise<string> {
return invoke("generate_schema_sync_sql", { diffs, databaseType, targetSchema });
}
@@ -1007,9 +861,7 @@ export async function uninstallJre(jreKey: string): Promise<void> {
return invoke("uninstall_jre", { jreKey });
}
-export async function listenAgentInstallProgress(
- handler: (progress: DriverInstallProgress) => void,
-): Promise<UnlistenFn> {
+export async function listenAgentInstallProgress(handler: (progress: DriverInstallProgress) => void): Promise<UnlistenFn> {
return listen<DriverInstallProgress>("agent-install-progress", (event) => handler(event.payload));
}
@@ -1138,24 +990,11 @@ export async function redisListDatabases(connectionId: string): Promise<RedisDat
return invoke("redis_list_databases", { connectionId });
}
-export async function redisScanKeys(
- connectionId: string,
- db: number,
- cursor: number,
- pattern: string,
- count: number,
-): Promise<RedisScanResult> {
+export async function redisScanKeys(connectionId: string, db: number, cursor: number, pattern: string, count: number): Promise<RedisScanResult> {
return invoke("redis_scan_keys", { connectionId, db, cursor, pattern, count });
}
-export async function redisScanValues(
- connectionId: string,
- db: number,
- cursor: number,
- pattern: string,
- query: string,
- count: number,
-): Promise<RedisScanResult> {
+export async function redisScanValues(connectionId: string, db: number, cursor: number, pattern: string, query: string, count: number): Promise<RedisScanResult> {
return invoke("redis_scan_values", { connectionId, db, cursor, pattern, query, count });
}
@@ -1163,13 +1002,7 @@ export async function redisGetValue(connectionId: string, db: number, keyRaw: st
return invoke("redis_get_value", { connectionId, db, keyRaw });
}
-export async function redisSetString(
- connectionId: string,
- db: number,
- keyRaw: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisSetString(connectionId: string, db: number, keyRaw: string, value: string, ttl?: number): Promise<void> {
return invoke("redis_set_string", { connectionId, db, keyRaw, value, ttl });
}
@@ -1177,14 +1010,7 @@ export async function redisDeleteKey(connectionId: string, db: number, keyRaw: s
return invoke("redis_delete_key", { connectionId, db, keyRaw });
}
-export async function redisHashSet(
- connectionId: string,
- db: number,
- keyRaw: string,
- field: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisHashSet(connectionId: string, db: number, keyRaw: string, field: string, value: string, ttl?: number): Promise<void> {
return invoke("redis_hash_set", { connectionId, db, keyRaw, field, value, ttl });
}
@@ -1192,23 +1018,11 @@ export async function redisHashDel(connectionId: string, db: number, keyRaw: str
return invoke("redis_hash_del", { connectionId, db, keyRaw, field });
}
-export async function redisListPush(
- connectionId: string,
- db: number,
- keyRaw: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisListPush(connectionId: string, db: number, keyRaw: string, value: string, ttl?: number): Promise<void> {
return invoke("redis_list_push", { connectionId, db, keyRaw, value, ttl });
}
-export async function redisListSet(
- connectionId: string,
- db: number,
- keyRaw: string,
- index: number,
- value: string,
-): Promise<void> {
+export async function redisListSet(connectionId: string, db: number, keyRaw: string, index: number, value: string): Promise<void> {
return invoke("redis_list_set", { connectionId, db, keyRaw, index, value });
}
@@ -1216,13 +1030,7 @@ export async function redisListRemove(connectionId: string, db: number, keyRaw:
return invoke("redis_list_remove", { connectionId, db, keyRaw, index });
}
-export async function redisSetAdd(
- connectionId: string,
- db: number,
- keyRaw: string,
- member: string,
- ttl?: number,
-): Promise<void> {
+export async function redisSetAdd(connectionId: string, db: number, keyRaw: string, member: string, ttl?: number): Promise<void> {
return invoke("redis_set_add", { connectionId, db, keyRaw, member, ttl });
}
@@ -1230,14 +1038,7 @@ export async function redisSetRemove(connectionId: string, db: number, keyRaw: s
return invoke("redis_set_remove", { connectionId, db, keyRaw, member });
}
-export async function redisZadd(
- connectionId: string,
- db: number,
- keyRaw: string,
- member: string,
- score: number,
- ttl?: number,
-): Promise<void> {
+export async function redisZadd(connectionId: string, db: number, keyRaw: string, member: string, score: number, ttl?: number): Promise<void> {
return invoke("redis_zadd", { connectionId, db, keyRaw, member, score, ttl });
}
@@ -1245,24 +1046,11 @@ export async function redisZrem(connectionId: string, db: number, keyRaw: string
return invoke("redis_zrem", { connectionId, db, keyRaw, member });
}
-export async function redisStreamAdd(
- connectionId: string,
- db: number,
- keyRaw: string,
- entryId: string,
- fields: [string, string][],
- ttl?: number,
-): Promise<void> {
+export async function redisStreamAdd(connectionId: string, db: number, keyRaw: string, entryId: string, fields: [string, string][], ttl?: number): Promise<void> {
return invoke("redis_stream_add", { connectionId, db, keyRaw, entryId, fields, ttl });
}
-export async function redisJsonSet(
- connectionId: string,
- db: number,
- keyRaw: string,
- value: string,
- ttl?: number,
-): Promise<void> {
+export async function redisJsonSet(connectionId: string, db: number, keyRaw: string, value: string, ttl?: number): Promise<void> {
return invoke("redis_json_set", { connectionId, db, keyRaw, value, ttl });
}
@@ -1282,22 +1070,11 @@ export async function redisFlushDb(connectionId: string, db: number): Promise<vo
return invoke("redis_flush_db", { connectionId, db });
}
-export async function redisExecuteCommand(
- connectionId: string,
- db: number,
- command: string,
-): Promise<RedisCommandResult> {
+export async function redisExecuteCommand(connectionId: string, db: number, command: string): Promise<RedisCommandResult> {
return invoke("redis_execute_command", { connectionId, db, command });
}
-export async function redisLoadMore(
- connectionId: string,
- db: number,
- keyRaw: string,
- keyType: string,
- cursor: number,
- count: number,
-): Promise<RedisValue> {
+export async function redisLoadMore(connectionId: string, db: number, keyRaw: string, keyType: string, cursor: number, count: number): Promise<RedisValue> {
return invoke("redis_load_more", { connectionId, db, keyRaw, keyType, cursor, count });
}
@@ -1343,12 +1120,7 @@ export interface KvDeleteResponse {
revision?: number | null;
}
-export async function etcdListPrefix(
- connectionId: string,
- prefix: string,
- limit: number,
- continuation?: string | null,
-): Promise<KvListPrefixResponse> {
+export async function etcdListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null): Promise<KvListPrefixResponse> {
return invoke("etcd_list_prefix", { connectionId, prefix, limit, continuation });
}
@@ -1356,12 +1128,7 @@ export async function etcdGet(connectionId: string, key: string): Promise<KvGetR
return invoke("etcd_get", { connectionId, key });
}
-export async function etcdPut(
- connectionId: string,
- key: string,
- value: KvValue,
- lease?: number | null,
-): Promise<KvPutResponse> {
+export async function etcdPut(connectionId: string, key: string, value: KvValue, lease?: number | null): Promise<KvPutResponse> {
return invoke("etcd_put", { connectionId, key, value, lease });
}
@@ -1383,65 +1150,28 @@ export async function mongoListCollections(connectionId: string, database: strin
return invoke("mongo_list_collections", { connectionId, database });
}
-export async function mongoFindDocuments(
- connectionId: string,
- database: string,
- collection: string,
- skip: number,
- limit: number,
- filter?: string,
- sort?: string,
-): Promise<MongoDocumentResult> {
+export async function mongoFindDocuments(connectionId: string, database: string, collection: string, skip: number, limit: number, filter?: string, sort?: string): Promise<MongoDocumentResult> {
return invoke("mongo_find_documents", { connectionId, database, collection, skip, limit, filter, sort });
}
-export async function mongoAggregateDocuments(
- connectionId: string,
- database: string,
- collection: string,
- pipelineJson: string,
- maxRows?: number,
-): Promise<MongoDocumentResult> {
+export async function mongoAggregateDocuments(connectionId: string, database: string, collection: string, pipelineJson: string, maxRows?: number): Promise<MongoDocumentResult> {
return invoke("mongo_aggregate_documents", { connectionId, database, collection, pipelineJson, maxRows });
}
-export async function mongoInsertDocument(
- connectionId: string,
- database: string,
- collection: string,
- docJson: string,
-): Promise<string> {
+export async function mongoInsertDocument(connectionId: string, database: string, collection: string, docJson: string): Promise<string> {
return invoke("mongo_insert_document", { connectionId, database, collection, docJson });
}
-export async function mongoInsertDocuments(
- connectionId: string,
- database: string,
- collection: string,
- docsJson: string,
-): Promise<{ affected_rows: number }> {
+export async function mongoInsertDocuments(connectionId: string, database: string, collection: string, docsJson: string): Promise<{ affected_rows: number }> {
const affectedRows = await invoke<number>("mongo_insert_documents", { connectionId, database, collection, docsJson });
return { affected_rows: affectedRows };
}
-export async function mongoUpdateDocument(
- connectionId: string,
- database: string,
- collection: string,
- id: string,
- docJson: string,
-): Promise<number> {
+export async function mongoUpdateDocument(connectionId: string, database: string, collection: string, id: string, docJson: string): Promise<number> {
return invoke("mongo_update_document", { connectionId, database, collection, id, docJson });
}
-export async function mongoUpdateDocuments(
- connectionId: string,
- database: string,
- collection: string,
- filterJson: string,
- updateJson: string,
- many: boolean,
-): Promise<{ affected_rows: number }> {
+export async function mongoUpdateDocuments(connectionId: string, database: string, collection: string, filterJson: string, updateJson: string, many: boolean): Promise<{ affected_rows: number }> {
const affectedRows = await invoke<number>("mongo_update_documents", {
connectionId,
database,
@@ -1453,22 +1183,11 @@ export async function mongoUpdateDocuments(
return { affected_rows: affectedRows };
}
-export async function mongoDeleteDocument(
- connectionId: string,
- database: string,
- collection: string,
- id: string,
-): Promise<number> {
+export async function mongoDeleteDocument(connectionId: string, database: string, collection: string, id: string): Promise<number> {
return invoke("mongo_delete_document", { connectionId, database, collection, id });
}
-export async function mongoDeleteDocuments(
- connectionId: string,
- database: string,
- collection: string,
- filterJson: string,
- many: boolean,
-): Promise<{ affected_rows: number }> {
+export async function mongoDeleteDocuments(connectionId: string, database: string, collection: string, filterJson: string, many: boolean): Promise<{ affected_rows: number }> {
const affectedRows = await invoke<number>("mongo_delete_documents", {
connectionId,
database,
@@ -1524,14 +1243,7 @@ export async function deleteHistoryEntry(id: string): Promise<void> {
}
// --- SQL File Execution ---
-export type SqlFileStatus =
- | "started"
- | "running"
- | "statementDone"
- | "statementFailed"
- | "done"
- | "error"
- | "cancelled";
+export type SqlFileStatus = "started" | "running" | "statementDone" | "statementFailed" | "done" | "error" | "cancelled";
export interface SqlFileRequest {
executionId: string;
@@ -1604,10 +1316,7 @@ export interface TransferProgress {
error: string | null;
}
-export async function startTransfer(
- request: TransferRequest,
- onProgress: (progress: TransferProgress) => void,
-): Promise<void> {
+export async function startTransfer(request: TransferRequest, onProgress: (progress: TransferProgress) => void): Promise<void> {
return new Promise((resolve, reject) => {
let unlisten: UnlistenFn | null = null;
void (async () => {
@@ -1683,10 +1392,7 @@ export async function previewTableImportFile(filePath: string): Promise<TableImp
return invoke("preview_table_import_file", { filePath });
}
-export async function importTableFile(
- request: TableImportRequest,
- onProgress: (progress: TableImportProgress) => void,
-): Promise<TableImportSummary> {
+export async function importTableFile(request: TableImportRequest, onProgress: (progress: TableImportProgress) => void): Promise<TableImportSummary> {
const unlisten: UnlistenFn = await listen<TableImportProgress>("table-import-progress", (event) => {
if (event.payload.importId === request.importId) {
onProgress(event.payload);
@@ -1773,10 +1479,7 @@ export interface TableExportProgress {
errorMessage?: string;
}
-export async function startTableExport(
- request: TableExportRequest,
- onProgress: (progress: TableExportProgress) => void,
-): Promise<TableExportProgress> {
+export async function startTableExport(request: TableExportRequest, onProgress: (progress: TableExportProgress) => void): Promise<TableExportProgress> {
let unlisten: UnlistenFn | undefined;
let settled = false;
let resolveTerminal: (progress: TableExportProgress) => void = () => {};
@@ -1821,10 +1524,7 @@ export async function cancelTableExport(exportId: string): Promise<void> {
return invoke("cancel_table_export", { exportId });
}
-export async function exportDatabaseSql(
- request: DatabaseExportRequest,
- onProgress: (progress: ExportProgress) => void,
-): Promise<void> {
+export async function exportDatabaseSql(request: DatabaseExportRequest, onProgress: (progress: ExportProgress) => void): Promise<void> {
const unlisten: UnlistenFn = await listen<ExportProgress>("database-export-progress", (event) => {
if (event.payload.exportId === request.exportId) {
onProgress(event.payload);
@@ -1845,11 +1545,7 @@ export async function cancelDatabaseExport(exportId: string): Promise<void> {
await invoke("cancel_database_export", { exportId });
}
-export async function exportQueryResultCsv(
- filePath: string,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultCsv(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
return invoke("export_query_result_csv", {
request: {
filePath,
@@ -1863,12 +1559,7 @@ export async function exportTableDataCsv(options: TableCsvExportOptions): Promis
return invoke("export_table_data_csv", { request: options });
}
-export async function exportQueryResultXlsx(
- filePath: string,
- sheetName: string | undefined,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultXlsx(filePath: string, sheetName: string | undefined, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
return invoke("export_query_result_xlsx", {
request: {
filePath,
@@ -1879,11 +1570,7 @@ export async function exportQueryResultXlsx(
});
}
-export async function exportQueryResultJson(
- filePath: string,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultJson(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
return invoke("export_query_result_json", {
request: {
filePath,
@@ -1893,11 +1580,7 @@ export async function exportQueryResultJson(
});
}
-export async function exportQueryResultMarkdown(
- filePath: string,
- columns: string[],
- rows: readonly (readonly XlsxCellValue[])[],
-): Promise<void> {
+export async function exportQueryResultMarkdown(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[]): Promise<void> {
return invoke("export_query_result_markdown", {
request: {
filePath,
diff --git a/apps/desktop/src/lib/transferProgressState.ts b/apps/desktop/src/lib/transferProgressState.ts
index 6f9257981e..7dabd3326c 100644
--- a/apps/desktop/src/lib/transferProgressState.ts
+++ b/apps/desktop/src/lib/transferProgressState.ts
@@ -8,10 +8,7 @@ export interface TransferStatusLike {
status: "running" | "tableDone" | "done" | "error" | "cancelled";
}
-export function nextTransferTerminalState(
- state: TransferTerminalState,
- progress: TransferStatusLike,
-): TransferTerminalState {
+export function nextTransferTerminalState(state: TransferTerminalState, progress: TransferStatusLike): TransferTerminalState {
if (progress.status === "done") return { ...state, done: true };
if (progress.status === "cancelled") return { ...state, cancelled: true };
return state;
diff --git a/apps/desktop/src/lib/treeNodeClick.ts b/apps/desktop/src/lib/treeNodeClick.ts
index 204b7ce586..cbe32f6057 100644
--- a/apps/desktop/src/lib/treeNodeClick.ts
+++ b/apps/desktop/src/lib/treeNodeClick.ts
@@ -2,14 +2,7 @@ import type { ObjectSourceKind, TreeNode, TreeNodeType } from "@/types/database"
import { matchesShortcut, type ShortcutLikeEvent } from "@/lib/keyboardShortcuts";
export type TreeNodeRowAction = "open-data" | "toggle" | "none";
-export type TreeNodeRowDoubleClickAction =
- | "open-data"
- | "open-object-browser"
- | "open-object-browser-and-expand"
- | "open-source"
- | "open-saved-sql"
- | "toggle"
- | "none";
+export type TreeNodeRowDoubleClickAction = "open-data" | "open-object-browser" | "open-object-browser-and-expand" | "open-source" | "open-saved-sql" | "toggle" | "none";
export type SidebarSelectionCopyAction = "copy-name" | "none";
export type SidebarActivation = "single" | "double";
@@ -18,21 +11,8 @@ const toggleLeafNodeTypes = new Set<TreeNodeType>(["redis-db", "mongo-collection
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser"]);
const sourceNodeTypes = new Set<TreeNodeType>(["procedure", "function", "sequence", "package", "package-body"]);
const savedSqlNodeTypes = new Set<TreeNodeType>(["saved-sql-file"]);
-const tableChildGroupNodeTypes = new Set<TreeNodeType>([
- "group-columns",
- "group-indexes",
- "group-fkeys",
- "group-triggers",
- "group-partitions",
-]);
-const databaseChildGroupNodeTypes = new Set<TreeNodeType>([
- "group-tables",
- "group-views",
- "group-procedures",
- "group-functions",
- "group-sequences",
- "group-packages",
-]);
+const tableChildGroupNodeTypes = new Set<TreeNodeType>(["group-columns", "group-indexes", "group-fkeys", "group-triggers", "group-partitions"]);
+const databaseChildGroupNodeTypes = new Set<TreeNodeType>(["group-tables", "group-views", "group-procedures", "group-functions", "group-sequences", "group-packages"]);
export function objectSourceKindForTreeNode(type: TreeNodeType): ObjectSourceKind | null {
if (type === "view") return "VIEW";
@@ -44,11 +24,7 @@ export function objectSourceKindForTreeNode(type: TreeNodeType): ObjectSourceKin
return null;
}
-export function treeNodeRowAction(
- type: TreeNodeType,
- canExpand: boolean,
- activation: SidebarActivation = "single",
-): TreeNodeRowAction {
+export function treeNodeRowAction(type: TreeNodeType, canExpand: boolean, activation: SidebarActivation = "single"): TreeNodeRowAction {
if (activation === "double") return "none";
if (dataNodeTypes.has(type)) return "open-data";
if (toggleLeafNodeTypes.has(type)) return "toggle";
@@ -56,12 +32,7 @@ export function treeNodeRowAction(
return "none";
}
-export function treeNodeRowDoubleClickAction(
- type: TreeNodeType,
- canOpenObjectBrowser: boolean,
- activation: SidebarActivation = "single",
- canExpand = false,
-): TreeNodeRowDoubleClickAction {
+export function treeNodeRowDoubleClickAction(type: TreeNodeType, canOpenObjectBrowser: boolean, activation: SidebarActivation = "single", canExpand = false): TreeNodeRowDoubleClickAction {
if (activation === "double") {
if (dataNodeTypes.has(type)) return "open-data";
if (sourceNodeTypes.has(type)) return "open-source";
diff --git a/apps/desktop/src/lib/treeNodeContext.ts b/apps/desktop/src/lib/treeNodeContext.ts
index b1259fae10..3536716542 100644
--- a/apps/desktop/src/lib/treeNodeContext.ts
+++ b/apps/desktop/src/lib/treeNodeContext.ts
@@ -27,10 +27,7 @@ export function treeNodeSchemaCachePrefix(node: TreeNode): string | null {
export function normalizeCataloglessDatabaseNodes(nodes: TreeNode[]): TreeNode[] {
return nodes.map((node) => {
- const normalized =
- node.type === "database" && node.database === "" && !node.label.trim()
- ? { ...node, label: DEFAULT_DATABASE_TREE_LABEL }
- : node;
+ const normalized = node.type === "database" && node.database === "" && !node.label.trim() ? { ...node, label: DEFAULT_DATABASE_TREE_LABEL } : node;
return normalized.children
? {
diff --git a/apps/desktop/src/lib/visibleDatabases.ts b/apps/desktop/src/lib/visibleDatabases.ts
index f3d9ce0991..1c616b5963 100644
--- a/apps/desktop/src/lib/visibleDatabases.ts
+++ b/apps/desktop/src/lib/visibleDatabases.ts
@@ -51,15 +51,7 @@ const SYSTEM_DATABASE_RULES: Partial<Record<DatabaseType, ReadonlySet<string>>>
]),
dameng: new Set(["ctisys", "dba", "sys", "sysauditor", "sysdba", "syssso", "system"]),
saphana: new Set(["_sys_afl", "_sys_bi", "_sys_bic", "_sys_repo", "_sys_statistics", "sys"]),
- cassandra: new Set([
- "system",
- "system_auth",
- "system_distributed",
- "system_schema",
- "system_traces",
- "system_views",
- "system_virtual_schema",
- ]),
+ cassandra: new Set(["system", "system_auth", "system_distributed", "system_schema", "system_traces", "system_views", "system_virtual_schema"]),
neo4j: new Set(["system"]),
snowflake: new Set(["snowflake", "snowflake_sample_data"]),
};
@@ -93,10 +85,7 @@ export function isSystemDatabaseName(databaseType: DatabaseType | undefined, dat
return SYSTEM_DATABASE_RULES[databaseType]?.has(databaseName.toLowerCase()) ?? false;
}
-export function filterDatabaseNamesForConnection(
- databaseNames: string[],
- connection: Pick<ConnectionConfig, "db_type" | "driver_profile" | "visible_databases"> | undefined,
-): string[] {
+export function filterDatabaseNamesForConnection(databaseNames: string[], connection: Pick<ConnectionConfig, "db_type" | "driver_profile" | "visible_databases"> | undefined): string[] {
const visibleDatabases = connection?.visible_databases;
if (visibleDatabaseFilterIsEnabled(visibleDatabases)) {
return filterVisibleDatabaseNames(databaseNames, visibleDatabases);
diff --git a/apps/desktop/src/lib/xlsxExport.ts b/apps/desktop/src/lib/xlsxExport.ts
index 654c941fc2..2e043bd067 100644
--- a/apps/desktop/src/lib/xlsxExport.ts
+++ b/apps/desktop/src/lib/xlsxExport.ts
@@ -82,9 +82,7 @@ function normalizeSheetName(value?: string): string {
function estimateColumnWidths(columns: readonly string[], rows: readonly (readonly XlsxCellValue[])[]): number[] {
return columns.map((column, colIndex) => {
const values = rows.slice(0, 100).map((row) => row[colIndex]);
- const maxLen = [column, ...values.map((value) => (value == null ? "" : String(value)))]
- .map((value) => Math.min(value.length, 60))
- .reduce((max, length) => Math.max(max, length), 8);
+ const maxLen = [column, ...values.map((value) => (value == null ? "" : String(value)))].map((value) => Math.min(value.length, 60)).reduce((max, length) => Math.max(max, length), 8);
return Math.max(10, Math.min(60, maxLen + 2));
});
}
@@ -108,9 +106,7 @@ function worksheetXml(data: XlsxWorksheetData): string {
const totalRows = rows.length + 1;
const range = sheetRange(columns.length, totalRows);
const widths = estimateColumnWidths(columns, rows);
- const colsXml = widths
- .map((width, index) => `<col min="${index + 1}" max="${index + 1}" width="${width}" customWidth="1"/>`)
- .join("");
+ const colsXml = widths.map((width, index) => `<col min="${index + 1}" max="${index + 1}" width="${width}" customWidth="1"/>`).join("");
const headerXml = `<row r="1">${columns.map((column, index) => cellXml(column, 0, index, 1)).join("")}</row>`;
const bodyXml = rows
.map((row, rowIndex) => {
@@ -210,20 +206,7 @@ function createZip(files: Array<{ path: string; content: string }>): Uint8Array
const path = encoder.encode(file.path);
const data = encoder.encode(file.content);
const crc = crc32(data);
- const localHeader = concatBytes([
- uint32(0x04034b50),
- uint16(20),
- uint16(0),
- uint16(0),
- uint16(0),
- uint16(0),
- uint32(crc),
- uint32(data.length),
- uint32(data.length),
- uint16(path.length),
- uint16(0),
- path,
- ]);
+ const localHeader = concatBytes([uint32(0x04034b50), uint16(20), uint16(0), uint16(0), uint16(0), uint16(0), uint32(crc), uint32(data.length), uint32(data.length), uint16(path.length), uint16(0), path]);
entries.push({ path: file.path, data, crc, localHeaderOffset: offset });
localParts.push(localHeader, data);
offset += localHeader.length + data.length;
@@ -233,40 +216,12 @@ function createZip(files: Array<{ path: string; content: string }>): Uint8Array
for (const entry of entries) {
const path = encoder.encode(entry.path);
centralParts.push(
- concatBytes([
- uint32(0x02014b50),
- uint16(20),
- uint16(20),
- uint16(0),
- uint16(0),
- uint16(0),
- uint16(0),
- uint32(entry.crc),
- uint32(entry.data.length),
- uint32(entry.data.length),
- uint16(path.length),
- uint16(0),
- uint16(0),
- uint16(0),
- uint16(0),
- uint32(0),
- uint32(entry.localHeaderOffset),
- path,
- ]),
+ concatBytes([uint32(0x02014b50), uint16(20), uint16(20), uint16(0), uint16(0), uint16(0), uint16(0), uint32(entry.crc), uint32(entry.data.length), uint32(entry.data.length), uint16(path.length), uint16(0), uint16(0), uint16(0), uint16(0), uint32(0), uint32(entry.localHeaderOffset), path]),
);
}
const central = concatBytes(centralParts);
- const end = concatBytes([
- uint32(0x06054b50),
- uint16(0),
- uint16(0),
- uint16(entries.length),
- uint16(entries.length),
- uint32(central.length),
- uint32(offset),
- uint16(0),
- ]);
+ const end = concatBytes([uint32(0x06054b50), uint16(0), uint16(0), uint16(entries.length), uint16(entries.length), uint32(central.length), uint32(offset), uint16(0)]);
return concatBytes([...localParts, central, end]);
}
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 87450b2b85..0a1ed84692 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -19,26 +19,9 @@ function renderStartupError(error: unknown) {
if (!root) return;
root.innerHTML = "";
const panel = document.createElement("div");
- panel.style.cssText = [
- "display:flex",
- "min-height:100vh",
- "align-items:center",
- "justify-content:center",
- "background:#ffffff",
- "color:#111827",
- "padding:24px",
- "font-family:ui-sans-serif,system-ui,sans-serif",
- ].join(";");
+ panel.style.cssText = ["display:flex", "min-height:100vh", "align-items:center", "justify-content:center", "background:#ffffff", "color:#111827", "padding:24px", "font-family:ui-sans-serif,system-ui,sans-serif"].join(";");
const card = document.createElement("div");
- card.style.cssText = [
- "max-width:760px",
- "width:100%",
- "border:1px solid #e5e7eb",
- "border-radius:12px",
- "padding:20px",
- "box-shadow:0 10px 30px rgba(0,0,0,0.08)",
- "background:#fff",
- ].join(";");
+ card.style.cssText = ["max-width:760px", "width:100%", "border:1px solid #e5e7eb", "border-radius:12px", "padding:20px", "box-shadow:0 10px 30px rgba(0,0,0,0.08)", "background:#fff"].join(";");
const title = document.createElement("h1");
title.textContent = "DBX startup failed";
title.style.cssText = "margin:0 0 12px;font-size:18px;font-weight:700;";
@@ -47,17 +30,7 @@ function renderStartupError(error: unknown) {
text.style.cssText = "margin:0 0 12px;font-size:13px;line-height:1.5;color:#4b5563;";
const pre = document.createElement("pre");
pre.textContent = message;
- pre.style.cssText = [
- "margin:0",
- "white-space:pre-wrap",
- "word-break:break-word",
- "font-size:12px",
- "line-height:1.5",
- "background:#f9fafb",
- "border-radius:8px",
- "padding:12px",
- "overflow:auto",
- ].join(";");
+ pre.style.cssText = ["margin:0", "white-space:pre-wrap", "word-break:break-word", "font-size:12px", "line-height:1.5", "background:#f9fafb", "border-radius:8px", "padding:12px", "overflow:auto"].join(";");
card.append(title, text, pre);
panel.append(card);
root.append(panel);
@@ -74,10 +47,7 @@ function installStartupErrorHandlers() {
async function bootstrap() {
console.log("[STARTUP] frontend bootstrap begin");
- const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([
- import("./i18n"),
- import("./App.vue"),
- ]);
+ const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([import("./i18n"), import("./App.vue")]);
console.log("[STARTUP] frontend modules loaded");
await loadSavedLocale();
console.log("[STARTUP] locale ready");
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 6ab29c3913..8a3236ad1e 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -20,33 +20,14 @@ import {
import type { SqlCompletionColumn, SqlCompletionObject, SqlCompletionTable } from "@/lib/sqlCompletion";
import * as api from "@/lib/api";
import { isTauriRuntime } from "@/lib/tauriRuntime";
-import {
- isSchemaAware,
- normalizeSidebarObjectKind,
- sidebarObjectKindsForDatabase,
- usesTreeSchemaMode,
-} from "@/lib/databaseCapabilities";
-import {
- connectionObjectTreeNodeSchema,
- connectionObjectTreeQuerySchema,
- connectionUsesDatabaseObjectTreeMode,
- effectiveDatabaseTypeForConnection,
-} from "@/lib/jdbcDialect";
-import {
- buildDatabaseTreeNodes,
- buildDuckDbConnectionTreeNodes,
- sortSidebarNames,
- shouldIncludeDefaultDatabaseNode,
-} from "@/lib/databaseTree";
+import { isSchemaAware, normalizeSidebarObjectKind, sidebarObjectKindsForDatabase, usesTreeSchemaMode } from "@/lib/databaseCapabilities";
+import { connectionObjectTreeNodeSchema, connectionObjectTreeQuerySchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
+import { buildDatabaseTreeNodes, buildDuckDbConnectionTreeNodes, sortSidebarNames, shouldIncludeDefaultDatabaseNode } from "@/lib/databaseTree";
import { buildSqlServerDatabaseTreeNodes, SQLSERVER_DEFAULT_SCHEMA } from "@/lib/sqlServerTree";
import { findDatabaseTreeNode } from "@/lib/treeRefreshTarget";
import { shouldMarkDisconnected } from "@/lib/connectionHealth";
import { connectionAttemptTimeoutMessage, connectionAttemptTimeoutMs } from "@/lib/connectionAttemptTimeout";
-import {
- filterDatabaseNamesForConnection,
- filterVisibleDatabaseNames,
- normalizeVisibleDatabaseSelection,
-} from "@/lib/visibleDatabases";
+import { filterDatabaseNamesForConnection, filterVisibleDatabaseNames, normalizeVisibleDatabaseSelection } from "@/lib/visibleDatabases";
import {
buildObjectGroupPlaceholderNodes,
buildGroupedObjectTreeNodes,
@@ -59,11 +40,7 @@ import {
tablePartitionGroups,
type DatabaseObjectTreeKind,
} from "@/lib/tableTree";
-import {
- hasTreeNodeDatabaseContext,
- normalizeCataloglessDatabaseNodes,
- treeNodeSchemaCachePrefix,
-} from "@/lib/treeNodeContext";
+import { hasTreeNodeDatabaseContext, normalizeCataloglessDatabaseNodes, treeNodeSchemaCachePrefix } from "@/lib/treeNodeContext";
import { decodeSchemaTreeCache, encodeSchemaTreeCache } from "@/lib/schemaTreeCache";
import { sortSidebarTreeChildrenForParent } from "@/lib/sidebarNodeOrdering";
import { prunePinnedTreeNodeIdsForConnection } from "@/lib/pinnedTreeNodeIds";
@@ -305,9 +282,7 @@ export const useConnectionStore = defineStore("connection", () => {
driver_profile: profile,
driver_label: config.driver_label || labelMap[profile] || config.db_type,
url_params: config.url_params || "",
- attached_databases: Array.isArray(config.attached_databases)
- ? config.attached_databases.filter((database) => database.name?.trim() && database.path?.trim())
- : [],
+ attached_databases: Array.isArray(config.attached_databases) ? config.attached_databases.filter((database) => database.name?.trim() && database.path?.trim()) : [],
transport_layers: Array.isArray(config.transport_layers) ? config.transport_layers : [],
connect_timeout_secs: config.connect_timeout_secs || 5,
query_timeout_secs: config.query_timeout_secs ?? 30,
@@ -395,11 +370,7 @@ export const useConnectionStore = defineStore("connection", () => {
};
}
- function withConnectionUtilityNodes(
- connectionId: string,
- children: TreeNode[],
- existingConnectionNode?: TreeNode,
- ): TreeNode[] {
+ function withConnectionUtilityNodes(connectionId: string, children: TreeNode[], existingConnectionNode?: TreeNode): TreeNode[] {
const nonUtilityChildren = children.filter((child) => child.type !== "user-admin");
const userAdminNode = buildUserAdminNode(connectionId, existingConnectionNode);
return [...nonUtilityChildren, userAdminNode].filter(Boolean) as TreeNode[];
@@ -432,17 +403,8 @@ export const useConnectionStore = defineStore("connection", () => {
const payload = await api.loadSchemaCache<unknown>(cacheKey).catch(() => null);
const decoded = decodeSchemaTreeCache<TreeNode[]>(payload);
if (!decoded) return { hit: false, isStale: false };
- const normalizedChildren = sortSidebarTreeChildrenForParent(
- node,
- normalizeCataloglessDatabaseNodes(expandCachedObjectBrowserNodes(decoded.children)),
- node.connectionId ? getConfig(node.connectionId)?.db_type : undefined,
- );
- setChildren(
- node,
- node.type === "connection" && node.connectionId
- ? withSavedSqlRoot(node.connectionId, normalizedChildren, node)
- : normalizedChildren,
- );
+ const normalizedChildren = sortSidebarTreeChildrenForParent(node, normalizeCataloglessDatabaseNodes(expandCachedObjectBrowserNodes(decoded.children)), node.connectionId ? getConfig(node.connectionId)?.db_type : undefined);
+ setChildren(node, node.type === "connection" && node.connectionId ? withSavedSqlRoot(node.connectionId, normalizedChildren, node) : normalizedChildren);
node.isExpanded = true;
return { hit: true, isStale: decoded.isStale };
}
@@ -454,11 +416,7 @@ export const useConnectionStore = defineStore("connection", () => {
function useCachedChildren(node: TreeNode, options?: LoadTreeOptions): boolean {
if (options?.force || !loadedTreeNodeChildrenIds.value.has(node.id)) return false;
if (node.type === "connection" && node.connectionId) {
- const normalizedChildren = sortSidebarTreeChildrenForParent(
- node,
- withSavedSqlRoot(node.connectionId, node.children || [], node),
- getConfig(node.connectionId)?.db_type,
- );
+ const normalizedChildren = sortSidebarTreeChildrenForParent(node, withSavedSqlRoot(node.connectionId, node.children || [], node), getConfig(node.connectionId)?.db_type);
setChildren(node, normalizedChildren);
}
node.isExpanded = true;
@@ -480,9 +438,7 @@ export const useConnectionStore = defineStore("connection", () => {
if (rawPrefix === encodedPrefix) {
api.deleteSchemaCachePrefix(rawPrefix).catch(() => undefined);
} else {
- Promise.all([api.deleteSchemaCachePrefix(rawPrefix), api.deleteSchemaCachePrefix(encodedPrefix)]).catch(
- () => undefined,
- );
+ Promise.all([api.deleteSchemaCachePrefix(rawPrefix), api.deleteSchemaCachePrefix(encodedPrefix)]).catch(() => undefined);
}
}
@@ -517,9 +473,7 @@ export const useConnectionStore = defineStore("connection", () => {
const node = findNode(treeNodes.value, id);
if (node) node.pinned = next.has(id);
- const isConnectionOrGroup =
- treeNodes.value.some((n) => n.id === id) ||
- treeNodes.value.some((n) => n.type === "connection-group" && n.children?.some((c) => c.id === id));
+ const isConnectionOrGroup = treeNodes.value.some((n) => n.id === id) || treeNodes.value.some((n) => n.type === "connection-group" && n.children?.some((c) => c.id === id));
if (isConnectionOrGroup) {
rebuildTreeNodes();
} else {
@@ -832,15 +786,8 @@ export const useConnectionStore = defineStore("connection", () => {
return;
}
}
- const [databases, schemas] = await Promise.all([
- api.listDatabases(connectionId),
- api.listSchemas(connectionId, "main"),
- ]);
- const children = withSavedSqlRoot(
- connectionId,
- buildDuckDbConnectionTreeNodes(connectionId, databases, schemas),
- node,
- );
+ const [databases, schemas] = await Promise.all([api.listDatabases(connectionId), api.listSchemas(connectionId, "main")]);
+ const children = withSavedSqlRoot(connectionId, buildDuckDbConnectionTreeNodes(connectionId, databases, schemas), node);
setChildren(node, children);
await savePersistedTreeChildren(cacheKey, children);
} else if (config?.db_type === "dameng" || config?.db_type === "oracle") {
@@ -886,8 +833,7 @@ export const useConnectionStore = defineStore("connection", () => {
const children = withSavedSqlRoot(
connectionId,
buildDatabaseTreeNodes(connectionId, visibleDatabases, {
- includeDefaultWhenEmpty:
- usesTreeSchemaMode(config?.db_type) || shouldIncludeDefaultDatabaseNode(config, visibleDatabases),
+ includeDefaultWhenEmpty: usesTreeSchemaMode(config?.db_type) || shouldIncludeDefaultDatabaseNode(config, visibleDatabases),
}),
node,
);
@@ -980,11 +926,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
}
- function updateRedisDbKeyStats(
- connectionId: string,
- db: number,
- stats: { loaded?: number; total?: number; totalDelta?: number },
- ) {
+ function updateRedisDbKeyStats(connectionId: string, db: number, stats: { loaded?: number; total?: number; totalDelta?: number }) {
const node = findNode(treeNodes.value, `${connectionId}:db${db}`);
if (!node || node.type !== "redis-db") return;
if (stats.loaded != null) node.loadedKeyCount = stats.loaded;
@@ -1106,11 +1048,7 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureConnected(connectionId);
if (useCachedChildren(node, options)) return;
const simpleObjectDisplay = useSettingsStore().editorSettings.sidebarObjectDisplay === "simple";
- const cacheKey = schemaCacheKey(
- connectionId,
- database,
- simpleObjectDisplay ? "sqlserver-objects-simple-v2" : "sqlserver-objects-grouped-v2",
- );
+ const cacheKey = schemaCacheKey(connectionId, database, simpleObjectDisplay ? "sqlserver-objects-simple-v2" : "sqlserver-objects-grouped-v2");
if (!options?.force) {
const cached = await loadPersistedTreeChildren(node, cacheKey);
if (cached.hit) {
@@ -1121,9 +1059,7 @@ export const useConnectionStore = defineStore("connection", () => {
const config = getConfig(connectionId);
const schemas = await api.listSchemas(connectionId, database);
- const defaultSchemaObjects = simpleObjectDisplay
- ? await api.listObjects(connectionId, database, SQLSERVER_DEFAULT_SCHEMA)
- : [];
+ const defaultSchemaObjects = simpleObjectDisplay ? await api.listObjects(connectionId, database, SQLSERVER_DEFAULT_SCHEMA) : [];
const children = buildSqlServerDatabaseTreeNodes(connectionId, database, schemas, defaultSchemaObjects, {
lazyObjectTypes: simpleObjectDisplay ? undefined : supportedSidebarObjectTypes(config),
simpleObjectDisplay,
@@ -1148,12 +1084,7 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureConnected(connectionId);
if (useCachedChildren(node, options)) return;
const simpleObjectDisplay = useSettingsStore().editorSettings.sidebarObjectDisplay === "simple";
- const cacheKey = schemaCacheKey(
- connectionId,
- database,
- schema || "",
- simpleObjectDisplay ? "objects-simple-v2" : "objects-grouped-v2",
- );
+ const cacheKey = schemaCacheKey(connectionId, database, schema || "", simpleObjectDisplay ? "objects-simple-v2" : "objects-grouped-v2");
if (!options?.force) {
const cached = await loadPersistedTreeChildren(node, cacheKey);
if (cached.hit) {
@@ -1168,10 +1099,7 @@ export const useConnectionStore = defineStore("connection", () => {
let children: TreeNode[];
if (simpleObjectDisplay) {
try {
- const [objects, tables] = await Promise.all([
- api.listObjects(connectionId, database, querySchema),
- api.listTables(connectionId, database, querySchema),
- ]);
+ const [objects, tables] = await Promise.all([api.listObjects(connectionId, database, querySchema), api.listTables(connectionId, database, querySchema)]);
children = buildSimpleObjectTreeNodes({
nodeId,
connectionId,
@@ -1226,13 +1154,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
const wantsOnlyTablesOrViews = objectTypes.every((objectType) => objectType === "TABLE" || objectType === "VIEW");
- const objects = wantsOnlyTablesOrViews
- ? mergeTableInfosIntoObjects(
- [],
- await api.listTables(node.connectionId, node.database, querySchema),
- effectiveSchema,
- )
- : await api.listObjects(node.connectionId, node.database, querySchema, objectTypes);
+ const objects = wantsOnlyTablesOrViews ? mergeTableInfosIntoObjects([], await api.listTables(node.connectionId, node.database, querySchema), effectiveSchema) : await api.listObjects(node.connectionId, node.database, querySchema, objectTypes);
const grouped = buildGroupedObjectTreeNodes({
nodeId: parentNodeId,
connectionId: node.connectionId,
@@ -1258,15 +1180,8 @@ export const useConnectionStore = defineStore("connection", () => {
return normalizeSidebarObjectKind(type);
}
- async function loadTableGroups(
- connectionId: string,
- database: string,
- table: string,
- schema?: string,
- nodeId?: string,
- ) {
- const parentId =
- nodeId ?? (schema ? `${connectionId}:${database}:${schema}:${table}` : `${connectionId}:${database}:${table}`);
+ async function loadTableGroups(connectionId: string, database: string, table: string, schema?: string, nodeId?: string) {
+ const parentId = nodeId ?? (schema ? `${connectionId}:${database}:${schema}:${table}` : `${connectionId}:${database}:${table}`);
const node = findNode(treeNodes.value, parentId);
if (!node) return;
@@ -1328,11 +1243,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
async function loadColumns(connectionId: string, database: string, table: string, schema?: string, nodeId?: string) {
- const parentId =
- nodeId ??
- (schema
- ? `${connectionId}:${database}:${schema}:${table}:__columns`
- : `${connectionId}:${database}:${table}:__columns`);
+ const parentId = nodeId ?? (schema ? `${connectionId}:${database}:${schema}:${table}:__columns` : `${connectionId}:${database}:${table}:__columns`);
const node = findNode(treeNodes.value, parentId);
if (!node) return;
@@ -1363,11 +1274,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
async function loadIndexes(connectionId: string, database: string, table: string, schema?: string, nodeId?: string) {
- const parentId =
- nodeId ??
- (schema
- ? `${connectionId}:${database}:${schema}:${table}:__indexes`
- : `${connectionId}:${database}:${table}:__indexes`);
+ const parentId = nodeId ?? (schema ? `${connectionId}:${database}:${schema}:${table}:__indexes` : `${connectionId}:${database}:${table}:__indexes`);
const node = findNode(treeNodes.value, parentId);
if (!node) return;
@@ -1397,18 +1304,8 @@ export const useConnectionStore = defineStore("connection", () => {
}
}
- async function loadForeignKeys(
- connectionId: string,
- database: string,
- table: string,
- schema?: string,
- nodeId?: string,
- ) {
- const parentId =
- nodeId ??
- (schema
- ? `${connectionId}:${database}:${schema}:${table}:__fkeys`
- : `${connectionId}:${database}:${table}:__fkeys`);
+ async function loadForeignKeys(connectionId: string, database: string, table: string, schema?: string, nodeId?: string) {
+ const parentId = nodeId ?? (schema ? `${connectionId}:${database}:${schema}:${table}:__fkeys` : `${connectionId}:${database}:${table}:__fkeys`);
const node = findNode(treeNodes.value, parentId);
if (!node) return;
@@ -1439,11 +1336,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
async function loadTriggers(connectionId: string, database: string, table: string, schema?: string, nodeId?: string) {
- const parentId =
- nodeId ??
- (schema
- ? `${connectionId}:${database}:${schema}:${table}:__triggers`
- : `${connectionId}:${database}:${table}:__triggers`);
+ const parentId = nodeId ?? (schema ? `${connectionId}:${database}:${schema}:${table}:__triggers` : `${connectionId}:${database}:${table}:__triggers`);
const node = findNode(treeNodes.value, parentId);
if (!node) return;
@@ -1506,43 +1399,17 @@ export const useConnectionStore = defineStore("connection", () => {
}
} else if (node.type === "schema" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.schema) {
await loadTables(node.connectionId, node.database, node.schema, options);
- } else if (
- (node.type === "table" || node.type === "view") &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node)
- ) {
+ } else if ((node.type === "table" || node.type === "view") && node.connectionId && hasTreeNodeDatabaseContext(node)) {
await loadTableGroups(node.connectionId, node.database, node.label, node.schema, node.id);
- } else if (
- node.type === "group-columns" &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node) &&
- node.tableName
- ) {
+ } else if (node.type === "group-columns" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await loadColumns(node.connectionId, node.database, node.tableName, node.schema, node.id);
- } else if (
- node.type === "group-indexes" &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node) &&
- node.tableName
- ) {
+ } else if (node.type === "group-indexes" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await loadIndexes(node.connectionId, node.database, node.tableName, node.schema, node.id);
} else if (node.type === "group-fkeys" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await loadForeignKeys(node.connectionId, node.database, node.tableName, node.schema, node.id);
- } else if (
- node.type === "group-triggers" &&
- node.connectionId &&
- hasTreeNodeDatabaseContext(node) &&
- node.tableName
- ) {
+ } else if (node.type === "group-triggers" && node.connectionId && hasTreeNodeDatabaseContext(node) && node.tableName) {
await loadTriggers(node.connectionId, node.database, node.tableName, node.schema, node.id);
- } else if (
- node.type === "group-tables" ||
- node.type === "group-views" ||
- node.type === "group-procedures" ||
- node.type === "group-functions" ||
- node.type === "group-sequences" ||
- node.type === "group-packages"
- ) {
+ } else if (node.type === "group-tables" || node.type === "group-views" || node.type === "group-procedures" || node.type === "group-functions" || node.type === "group-sequences" || node.type === "group-packages") {
await loadObjectGroupChildren(node, options);
} else if (node.type === "group-partitions") {
node.isExpanded = true;
@@ -1631,12 +1498,7 @@ export const useConnectionStore = defineStore("connection", () => {
return `${completionScopeKey(connectionId, database, schema)}:${table.toLowerCase()}`;
}
- function touchCompletionIndex<T>(
- index: Map<string, { touched: number } & T>,
- key: string,
- value: T,
- max = COMPLETION_CACHE_MAX,
- ) {
+ function touchCompletionIndex<T>(index: Map<string, { touched: number } & T>, key: string, value: T, max = COMPLETION_CACHE_MAX) {
index.set(key, { ...value, touched: Date.now() });
if (index.size <= max) return;
const oldest = [...index.entries()].sort(([, a], [, b]) => a.touched - b.touched).slice(0, index.size - max);
@@ -1676,12 +1538,7 @@ export const useConnectionStore = defineStore("connection", () => {
return tableMatchScore(tableLike, filter, preferredSchema);
}
- function indexCompletionTables(
- connectionId: string,
- database: string,
- schema: string | undefined,
- tables: SqlCompletionTable[],
- ) {
+ function indexCompletionTables(connectionId: string, database: string, schema: string | undefined, tables: SqlCompletionTable[]) {
const groups = new Map<string, SqlCompletionTable[]>();
for (const table of tables) {
const tableSchema = table.schema ?? schema;
@@ -1698,12 +1555,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
}
- function indexCompletionObjects(
- connectionId: string,
- database: string,
- schema: string | undefined,
- objects: SqlCompletionObject[],
- ) {
+ function indexCompletionObjects(connectionId: string, database: string, schema: string | undefined, objects: SqlCompletionObject[]) {
const groups = new Map<string, SqlCompletionObject[]>();
for (const object of objects) {
const objectSchema = object.schema ?? schema;
@@ -1720,28 +1572,14 @@ export const useConnectionStore = defineStore("connection", () => {
}
}
- function indexCompletionColumns(
- connectionId: string,
- database: string,
- table: string,
- schema: string | undefined,
- columns: SqlCompletionColumn[],
- ) {
+ function indexCompletionColumns(connectionId: string, database: string, table: string, schema: string | undefined, columns: SqlCompletionColumn[]) {
touchCompletionIndex(completionColumnIndex, completionColumnsKey(connectionId, database, table, schema), {
columns,
});
}
- function lookupLocalCompletionTables(
- connectionId: string,
- database: string,
- filter = "",
- limit?: number,
- schema?: string,
- ): SqlCompletionTable[] {
- const allScopes = [...completionTableIndex.entries()]
- .filter(([key]) => key.startsWith(`${connectionId}:${database}:`))
- .map(([, entry]) => entry);
+ function lookupLocalCompletionTables(connectionId: string, database: string, filter = "", limit?: number, schema?: string): SqlCompletionTable[] {
+ const allScopes = [...completionTableIndex.entries()].filter(([key]) => key.startsWith(`${connectionId}:${database}:`)).map(([, entry]) => entry);
const preferred = schema ? completionTableIndex.get(completionScopeKey(connectionId, database, schema)) : undefined;
const scopes = preferred ? [preferred, ...allScopes.filter((entry) => entry !== preferred)] : allScopes;
const ranked = scopes
@@ -1752,19 +1590,9 @@ export const useConnectionStore = defineStore("connection", () => {
return dedupeCompletionTables(ranked.map((entry) => entry.table)).slice(0, limit ?? 200);
}
- function lookupLocalCompletionObjects(
- connectionId: string,
- database: string,
- filter = "",
- limit?: number,
- schema?: string,
- ): SqlCompletionObject[] {
- const allScopes = [...completionObjectIndex.entries()]
- .filter(([key]) => key.startsWith(`${connectionId}:${database}:`))
- .map(([, entry]) => entry);
- const preferred = schema
- ? completionObjectIndex.get(completionScopeKey(connectionId, database, schema))
- : undefined;
+ function lookupLocalCompletionObjects(connectionId: string, database: string, filter = "", limit?: number, schema?: string): SqlCompletionObject[] {
+ const allScopes = [...completionObjectIndex.entries()].filter(([key]) => key.startsWith(`${connectionId}:${database}:`)).map(([, entry]) => entry);
+ const preferred = schema ? completionObjectIndex.get(completionScopeKey(connectionId, database, schema)) : undefined;
const scopes = preferred ? [preferred, ...allScopes.filter((entry) => entry !== preferred)] : allScopes;
const ranked = scopes
.flatMap((entry) => entry?.objects ?? [])
@@ -1783,12 +1611,7 @@ export const useConnectionStore = defineStore("connection", () => {
.slice(0, limit);
}
- function lookupLocalCompletionColumns(
- connectionId: string,
- database: string,
- table: string,
- schema?: string,
- ): SqlCompletionColumn[] {
+ function lookupLocalCompletionColumns(connectionId: string, database: string, table: string, schema?: string): SqlCompletionColumn[] {
return completionColumnIndex.get(completionColumnsKey(connectionId, database, table, schema))?.columns ?? [];
}
@@ -1816,13 +1639,7 @@ export const useConnectionStore = defineStore("connection", () => {
return elasticsearchCompletionIndicesCache.value[cacheKey];
}
- async function listCompletionTables(
- connectionId: string,
- database: string,
- filter = "",
- limit?: number,
- schema?: string,
- ): Promise<SqlCompletionTable[]> {
+ async function listCompletionTables(connectionId: string, database: string, filter = "", limit?: number, schema?: string): Promise<SqlCompletionTable[]> {
const normalizedFilter = filter.trim().toLowerCase();
const relaxedFilter = relaxedCompletionTableFilter(normalizedFilter);
const cacheKey = `${connectionId}:${database}:${normalizedFilter}:${limit ?? ""}:${schema ?? ""}`;
@@ -1866,13 +1683,7 @@ export const useConnectionStore = defineStore("connection", () => {
const batchResults = await Promise.all(
batch.map(async (s) => {
try {
- const tables = await api.listTables(
- connectionId,
- database,
- s,
- relaxedFilter,
- expandedCompletionLimit(limit),
- );
+ const tables = await api.listTables(connectionId, database, s, relaxedFilter, expandedCompletionLimit(limit));
return tables.map((table) => ({
name: table.name,
schema: s,
@@ -1924,9 +1735,7 @@ export const useConnectionStore = defineStore("connection", () => {
name: table.name,
type: table.table_type === "VIEW" ? ("view" as const) : ("table" as const),
}));
- completionTablesCache.value[cacheKey] = limit
- ? completionTablesCache.value[cacheKey].slice(0, limit)
- : completionTablesCache.value[cacheKey];
+ completionTablesCache.value[cacheKey] = limit ? completionTablesCache.value[cacheKey].slice(0, limit) : completionTablesCache.value[cacheKey];
indexCompletionTables(connectionId, database, schema, completionTablesCache.value[cacheKey]);
evictOldestCacheEntries(completionTablesCache.value, COMPLETION_CACHE_MAX);
return completionTablesCache.value[cacheKey];
@@ -1955,41 +1764,25 @@ export const useConnectionStore = defineStore("connection", () => {
return deduped;
}
- async function listCompletionObjects(
- connectionId: string,
- database: string,
- filter = "",
- limit?: number,
- schema?: string,
- ): Promise<SqlCompletionObject[]> {
+ async function listCompletionObjects(connectionId: string, database: string, filter = "", limit?: number, schema?: string): Promise<SqlCompletionObject[]> {
const normalizedFilter = filter.trim().toLowerCase();
const cacheKey = `${connectionId}:${database}:${schema ?? ""}`;
if (!completionObjectsCache.value[cacheKey]) {
await withCompletionInFlight(`${cacheKey}:objects`, async () => {
await ensureConnected(connectionId);
- const objects = isSchemaAwareDatabase(connectionId)
- ? await listSchemaAwareCompletionObjects(connectionId, database, schema)
- : await api.listCompletionObjects(connectionId, database, schema || database);
- completionObjectsCache.value[cacheKey] = dedupeCompletionObjects(
- objects.map(toSqlCompletionObject).filter((object): object is SqlCompletionObject => object != null),
- );
+ const objects = isSchemaAwareDatabase(connectionId) ? await listSchemaAwareCompletionObjects(connectionId, database, schema) : await api.listCompletionObjects(connectionId, database, schema || database);
+ completionObjectsCache.value[cacheKey] = dedupeCompletionObjects(objects.map(toSqlCompletionObject).filter((object): object is SqlCompletionObject => object != null));
indexCompletionObjects(connectionId, database, schema, completionObjectsCache.value[cacheKey]);
evictOldestCacheEntries(completionObjectsCache.value, COMPLETION_CACHE_MAX);
});
}
const objects = completionObjectsCache.value[cacheKey];
- const filtered = normalizedFilter
- ? objects.filter((object) => fuzzyCompletionObjectMatch(object, normalizedFilter))
- : objects;
+ const filtered = normalizedFilter ? objects.filter((object) => fuzzyCompletionObjectMatch(object, normalizedFilter)) : objects;
return typeof limit === "number" ? filtered.slice(0, limit) : filtered;
}
- async function listSchemaAwareCompletionObjects(
- connectionId: string,
- database: string,
- schema?: string,
- ): Promise<ObjectInfo[]> {
+ async function listSchemaAwareCompletionObjects(connectionId: string, database: string, schema?: string): Promise<ObjectInfo[]> {
const schemas = schema ? [schema] : await listCompletionSchemas(connectionId, database);
const batchSize = 5;
const results: ObjectInfo[] = [];
@@ -2011,13 +1804,7 @@ export const useConnectionStore = defineStore("connection", () => {
function toSqlCompletionObject(object: ObjectInfo): SqlCompletionObject | null {
const objectType = object.object_type.toUpperCase();
- const type = objectType.includes("PROCEDURE")
- ? "procedure"
- : objectType.includes("FUNCTION")
- ? "function"
- : objectType.includes("TRIGGER")
- ? "trigger"
- : null;
+ const type = objectType.includes("PROCEDURE") ? "procedure" : objectType.includes("FUNCTION") ? "function" : objectType.includes("TRIGGER") ? "trigger" : null;
if (!type) return null;
return {
name: object.name,
@@ -2057,17 +1844,8 @@ export const useConnectionStore = defineStore("connection", () => {
return deduped;
}
- async function listCompletionColumns(
- connectionId: string,
- database: string,
- table: string,
- schema?: string,
- ): Promise<SqlCompletionColumn[]> {
- if (
- isSchemaAwareDatabase(connectionId) &&
- !connectionUsesDatabaseObjectTreeMode(getConfig(connectionId)) &&
- !schema
- ) {
+ async function listCompletionColumns(connectionId: string, database: string, table: string, schema?: string): Promise<SqlCompletionColumn[]> {
+ if (isSchemaAwareDatabase(connectionId) && !connectionUsesDatabaseObjectTreeMode(getConfig(connectionId)) && !schema) {
return [];
}
const cacheKey = `${connectionId}:${database}:${schema || ""}:${table}`;
@@ -2092,23 +1870,11 @@ export const useConnectionStore = defineStore("connection", () => {
return columns;
}
- function refreshCompletionTables(
- connectionId: string,
- database: string,
- filter = "",
- limit?: number,
- schema?: string,
- ): Promise<SqlCompletionTable[]> {
+ function refreshCompletionTables(connectionId: string, database: string, filter = "", limit?: number, schema?: string): Promise<SqlCompletionTable[]> {
return listCompletionTables(connectionId, database, filter, limit, schema);
}
- function refreshCompletionObjects(
- connectionId: string,
- database: string,
- filter = "",
- limit?: number,
- schema?: string,
- ): Promise<SqlCompletionObject[]> {
+ function refreshCompletionObjects(connectionId: string, database: string, filter = "", limit?: number, schema?: string): Promise<SqlCompletionObject[]> {
return listCompletionObjects(connectionId, database, filter, limit, schema);
}
@@ -2116,12 +1882,7 @@ export const useConnectionStore = defineStore("connection", () => {
return listCompletionSchemas(connectionId, database);
}
- function refreshCompletionColumns(
- connectionId: string,
- database: string,
- table: string,
- schema?: string,
- ): Promise<SqlCompletionColumn[]> {
+ function refreshCompletionColumns(connectionId: string, database: string, table: string, schema?: string): Promise<SqlCompletionColumn[]> {
return listCompletionColumns(connectionId, database, table, schema);
}
@@ -2244,9 +2005,7 @@ export const useConnectionStore = defineStore("connection", () => {
function siblingCredentialsPath(path: string) {
const fileName = path.split(/[\\/]/).pop() || "";
- const credentialsFile = fileName.startsWith("data-sources-")
- ? fileName.replace(/^data-sources/, "credentials-config")
- : "credentials-config.json";
+ const credentialsFile = fileName.startsWith("data-sources-") ? fileName.replace(/^data-sources/, "credentials-config") : "credentials-config.json";
return path.replace(/[^\\/]+$/, credentialsFile);
}
@@ -2285,9 +2044,7 @@ export const useConnectionStore = defineStore("connection", () => {
input.click();
});
const fileList = Array.from(files);
- const dataSourcesFile =
- fileList.find((file) => /^data-sources.*\.json$/i.test(file.name)) ||
- fileList.find((file) => !/^credentials-config.*\.json$/i.test(file.name));
+ const dataSourcesFile = fileList.find((file) => /^data-sources.*\.json$/i.test(file.name)) || fileList.find((file) => !/^credentials-config.*\.json$/i.test(file.name));
const credentialsFile = fileList.find((file) => /^credentials-config.*\.json$/i.test(file.name));
if (!dataSourcesFile) throw new Error("Select DBeaver data-sources.json");
dataSources = await dataSourcesFile.text();
@@ -2363,10 +2120,7 @@ export const useConnectionStore = defineStore("connection", () => {
const { open } = await import("@tauri-apps/plugin-dialog");
const { readTextFile } = await import("@tauri-apps/plugin-fs");
const path = await open({
- filters:
- source === "navicat"
- ? [{ name: "Navicat Connection Export", extensions: ["ncx", "xml"] }]
- : [{ name: "DBX JSON", extensions: ["json"] }],
+ filters: source === "navicat" ? [{ name: "Navicat Connection Export", extensions: ["ncx", "xml"] }] : [{ name: "DBX JSON", extensions: ["json"] }],
multiple: false,
});
if (!path) return null;
@@ -2400,10 +2154,7 @@ export const useConnectionStore = defineStore("connection", () => {
return { content, encrypted: isEncryptedConfig(parsed) };
}
- async function importConnectionsFromFile(
- content: string,
- passphrase: string | null,
- ): Promise<{ count: number; layout?: SidebarLayout }> {
+ async function importConnectionsFromFile(content: string, passphrase: string | null): Promise<{ count: number; layout?: SidebarLayout }> {
let imported: ConnectionConfig[] = [];
let importedLayout: SidebarLayout | undefined;
@@ -2461,9 +2212,7 @@ export const useConnectionStore = defineStore("connection", () => {
let count = 0;
for (const config of imported) {
- const duplicate = connections.value.find(
- (c) => c.name === config.name && c.host === config.host && c.port === config.port,
- );
+ const duplicate = connections.value.find((c) => c.name === config.name && c.host === config.host && c.port === config.port);
if (!duplicate) {
config.id = uuid();
const normalized = normalizeConnection(config);
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index ac2845bf35..ddda22995b 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -7,12 +7,7 @@ import { orderPinnedFirst } from "@/lib/pinnedItems";
import { canCancelQueryExecution } from "@/lib/queryExecutionState";
import { closeAllTabsState, closeOtherTabsState } from "@/lib/tabCloseActions";
import { buildExplainSql, parseExplainResult, parseDamengExplainText } from "@/lib/explainPlan";
-import {
- allEditableColumnsWriteable,
- allPrimaryKeysPresent,
- sourceColumnsForResult,
- type EditableQueryInfo,
-} from "@/lib/sqlAnalysis";
+import { allEditableColumnsWriteable, allPrimaryKeysPresent, sourceColumnsForResult, type EditableQueryInfo } from "@/lib/sqlAnalysis";
import { restoreOpenTabsState, serializeOpenTabs } from "@/lib/openTabsPersistence";
import {
evaluateMongoAggregateSafety,
@@ -32,20 +27,10 @@ import { editablePrimaryKeys } from "@/lib/tableEditing";
import { TABLE_DATA_EXPORT_PAGE_SIZE } from "@/lib/tableDataExport";
import { tableMetaForDataTab } from "@/lib/tableDataTabMeta";
import { quoteTableIdentifier } from "@/lib/tableSelectSql";
-import {
- connectionUsesDatabaseObjectTreeMode,
- connectionUsesSchemaExecutionContext,
- effectiveDatabaseTypeForConnection,
-} from "@/lib/jdbcDialect";
+import { connectionUsesDatabaseObjectTreeMode, connectionUsesSchemaExecutionContext, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
import { queryTimeoutSecsForConnection } from "@/lib/queryTimeout";
import { clearDataGridPendingSnapshotsForTab } from "@/composables/useDataGridEditor";
-import {
- buildTabResultSnapshot,
- deleteTabResultSnapshot,
- readTabResultSnapshot,
- tabResultCacheKey,
- writeTabResultSnapshot,
-} from "@/lib/tabResultCache";
+import { buildTabResultSnapshot, deleteTabResultSnapshot, readTabResultSnapshot, tabResultCacheKey, writeTabResultSnapshot } from "@/lib/tabResultCache";
import * as api from "@/lib/api";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
@@ -86,12 +71,7 @@ function normalizeOracleLikeMetadataIdentifier(dbType: string, identifier: strin
return identifier.toUpperCase();
}
-function normalizeOracleLikeQueryAnalysis(
- dbType: string,
- analysis: EditableQueryInfo,
- schema: string | undefined,
- tableName: string,
-): EditableQueryInfo {
+function normalizeOracleLikeQueryAnalysis(dbType: string, analysis: EditableQueryInfo, schema: string | undefined, tableName: string): EditableQueryInfo {
if (!ORACLE_LIKE_METADATA_TYPES.has(dbType)) return analysis;
return {
...analysis,
@@ -137,21 +117,11 @@ export const useQueryStore = defineStore("query", () => {
}
const tableStructureRefreshVersions = ref<Record<string, number>>({});
- function tableStructureKey(
- connectionId: string,
- database: string,
- schema: string | undefined,
- tableName: string,
- ): string {
+ function tableStructureKey(connectionId: string, database: string, schema: string | undefined, tableName: string): string {
return [connectionId, database, schema || "", tableName].map((part) => part.toLowerCase()).join("\u0000");
}
- function invalidateTableStructure(
- connectionId: string,
- database: string,
- schema: string | undefined,
- tableName: string,
- ) {
+ function invalidateTableStructure(connectionId: string, database: string, schema: string | undefined, tableName: string) {
if (!tableName) return;
const key = tableStructureKey(connectionId, database, schema, tableName);
tableStructureRefreshVersions.value = {
@@ -160,12 +130,7 @@ export const useQueryStore = defineStore("query", () => {
};
}
- function tableStructureRefreshVersion(
- connectionId: string,
- database: string,
- schema: string | undefined,
- tableName: string,
- ): number {
+ function tableStructureRefreshVersion(connectionId: string, database: string, schema: string | undefined, tableName: string): number {
return tableStructureRefreshVersions.value[tableStructureKey(connectionId, database, schema, tableName)] ?? 0;
}
const MAX_CACHED_RESULTS = 5;
@@ -270,30 +235,11 @@ export const useQueryStore = defineStore("query", () => {
{ flush: "post" },
);
- function findTabByIdentity(
- connectionId: string,
- database: string,
- title: string,
- mode: QueryTab["mode"],
- schema?: string,
- ) {
- return tabs.value.find(
- (tab) =>
- tab.connectionId === connectionId &&
- tab.database === database &&
- tab.title === title &&
- tab.mode === mode &&
- (tab.schema || "") === (schema || ""),
- );
+ function findTabByIdentity(connectionId: string, database: string, title: string, mode: QueryTab["mode"], schema?: string) {
+ return tabs.value.find((tab) => tab.connectionId === connectionId && tab.database === database && tab.title === title && tab.mode === mode && (tab.schema || "") === (schema || ""));
}
- function createTab(
- connectionId: string,
- database: string,
- title?: string,
- mode: QueryTab["mode"] = "query",
- schema?: string,
- ) {
+ function createTab(connectionId: string, database: string, title?: string, mode: QueryTab["mode"] = "query", schema?: string) {
if (title) {
const existing = findTabByIdentity(connectionId, database, title, mode, schema);
if (existing) {
@@ -323,13 +269,7 @@ export const useQueryStore = defineStore("query", () => {
function openObjectBrowser(connectionId: string, database: string, schema?: string) {
const title = schema ? `${schema} objects` : `${database} objects`;
- const existing = tabs.value.find(
- (tab) =>
- tab.mode === "objects" &&
- tab.connectionId === connectionId &&
- tab.database === database &&
- (tab.objectBrowser?.schema || "") === (schema || ""),
- );
+ const existing = tabs.value.find((tab) => tab.mode === "objects" && tab.connectionId === connectionId && tab.database === database && (tab.objectBrowser?.schema || "") === (schema || ""));
if (existing) {
activeTabId.value = existing.id;
return existing.id;
@@ -385,22 +325,14 @@ export const useQueryStore = defineStore("query", () => {
function openTableStructure(connectionId: string, database: string, schema?: string, tableName?: string) {
const resolvedTableName = tableName || "";
if (resolvedTableName) {
- const existing = tabs.value.find(
- (tab) =>
- tab.mode === "structure" &&
- tab.connectionId === connectionId &&
- tab.database === database &&
- (tab.structureTableName || "") === resolvedTableName,
- );
+ const existing = tabs.value.find((tab) => tab.mode === "structure" && tab.connectionId === connectionId && tab.database === database && (tab.structureTableName || "") === resolvedTableName);
if (existing) {
activeTabId.value = existing.id;
return existing.id;
}
}
- const title = resolvedTableName
- ? t("structureEditor.editTabTitle", { tableName: resolvedTableName })
- : t("structureEditor.createTitle");
+ const title = resolvedTableName ? t("structureEditor.editTabTitle", { tableName: resolvedTableName }) : t("structureEditor.createTitle");
const id = uuid();
const tab: QueryTab = {
id,
@@ -703,10 +635,7 @@ export const useQueryStore = defineStore("query", () => {
await executeTabSql(activeTabId.value, sql, { resultBaseSql: sql, resultSortedSql: undefined });
}
- type QueryMetadataPatch = Pick<
- QueryTab,
- "queryAnalysis" | "querySourceColumns" | "queryEditabilityReason" | "tableMeta"
- >;
+ type QueryMetadataPatch = Pick<QueryTab, "queryAnalysis" | "querySourceColumns" | "queryEditabilityReason" | "tableMeta">;
function applyQueryMetadataPatch(tab: QueryTab, patch: QueryMetadataPatch) {
tab.queryAnalysis = patch.queryAnalysis;
@@ -715,12 +644,7 @@ export const useQueryStore = defineStore("query", () => {
tab.tableMeta = patch.tableMeta;
}
- async function buildQueryMetadataPatch(
- tab: QueryTab,
- sql: string,
- traceId?: string,
- elapsed?: () => string,
- ): Promise<QueryMetadataPatch | undefined> {
+ async function buildQueryMetadataPatch(tab: QueryTab, sql: string, traceId?: string, elapsed?: () => string): Promise<QueryMetadataPatch | undefined> {
if (tab.mode !== "query") return;
if (!tab.result || !tab.result.columns.length) {
return {
@@ -767,23 +691,9 @@ export const useQueryStore = defineStore("query", () => {
if (dbType === "postgres" || dbType === "kwdb") schema = "public";
else schema = "";
}
- const metadataSchema =
- normalizeOracleLikeMetadataIdentifier(
- dbType,
- schema || undefined,
- analysis.schema ? analysis.schemaQuoted : false,
- ) || "";
- const metadataTableName = normalizeOracleLikeMetadataIdentifier(
- dbType,
- analysis.tableName,
- analysis.tableNameQuoted,
- )!;
- const metadataAnalysis = normalizeOracleLikeQueryAnalysis(
- dbType,
- analysis,
- metadataSchema || undefined,
- metadataTableName,
- );
+ const metadataSchema = normalizeOracleLikeMetadataIdentifier(dbType, schema || undefined, analysis.schema ? analysis.schemaQuoted : false) || "";
+ const metadataTableName = normalizeOracleLikeMetadataIdentifier(dbType, analysis.tableName, analysis.tableNameQuoted)!;
+ const metadataAnalysis = normalizeOracleLikeQueryAnalysis(dbType, analysis, metadataSchema || undefined, metadataTableName);
try {
console.info("[DBX][executeTabSql:metadata:get-columns:start]", {
@@ -850,13 +760,7 @@ export const useQueryStore = defineStore("query", () => {
}
}
- function analyzeQueryMetadataInBackground(
- tabId: string,
- sql: string,
- result: QueryResult,
- traceId: string,
- elapsed: () => string,
- ) {
+ function analyzeQueryMetadataInBackground(tabId: string, sql: string, result: QueryResult, traceId: string, elapsed: () => string) {
void (async () => {
const tab = tabs.value.find((t) => t.id === tabId);
if (!tab || tab.result !== result) return;
@@ -872,12 +776,7 @@ export const useQueryStore = defineStore("query", () => {
})();
}
- function setQueryTotalRowCountIfCurrent(
- tabId: string,
- executionId: string,
- result: QueryResult,
- totalRowCount: number | undefined,
- ) {
+ function setQueryTotalRowCountIfCurrent(tabId: string, executionId: string, result: QueryResult, totalRowCount: number | undefined) {
const current = tabs.value.find((t) => t.id === tabId);
if (current?.mode !== "query") return;
if (current.executionId !== executionId && current.result !== result) return;
@@ -885,20 +784,7 @@ export const useQueryStore = defineStore("query", () => {
current.resultTotalRowCountLoading = false;
}
- function countQueryTotalRowsInBackground(options: {
- tabId: string;
- connectionId: string;
- database: string;
- schema?: string;
- countSql?: string;
- result: QueryResult;
- pageLimit?: number;
- pageOffset?: number;
- executionId: string;
- traceId: string;
- elapsed: () => string;
- timeoutSecs: number;
- }) {
+ function countQueryTotalRowsInBackground(options: { tabId: string; connectionId: string; database: string; schema?: string; countSql?: string; result: QueryResult; pageLimit?: number; pageOffset?: number; executionId: string; traceId: string; elapsed: () => string; timeoutSecs: number }) {
const resultRowCount = options.result.rows.length;
if (!options.countSql || resultRowCount <= 0) {
setQueryTotalRowCountIfCurrent(options.tabId, options.executionId, options.result, undefined);
@@ -907,26 +793,14 @@ export const useQueryStore = defineStore("query", () => {
const countSql = options.countSql;
if (typeof options.pageLimit === "number" && resultRowCount < options.pageLimit) {
- setQueryTotalRowCountIfCurrent(
- options.tabId,
- options.executionId,
- options.result,
- (options.pageOffset ?? 0) + resultRowCount,
- );
+ setQueryTotalRowCountIfCurrent(options.tabId, options.executionId, options.result, (options.pageOffset ?? 0) + resultRowCount);
return;
}
void (async () => {
try {
console.info("[DBX][executeTabSql:count:start]", { traceId: options.traceId, elapsed: options.elapsed() });
- const countResult = await api.executeQuery(
- options.connectionId,
- options.database,
- countSql,
- options.schema,
- undefined,
- { timeoutSecs: options.timeoutSecs },
- );
+ const countResult = await api.executeQuery(options.connectionId, options.database, countSql, options.schema, undefined, { timeoutSecs: options.timeoutSecs });
const total = Number(countResult.rows?.[0]?.[0] ?? 0);
if (!Number.isFinite(total) || total < 0) {
setQueryTotalRowCountIfCurrent(options.tabId, options.executionId, options.result, undefined);
@@ -1029,15 +903,7 @@ export const useQueryStore = defineStore("query", () => {
if (mongoFind) {
await connStore.ensureConnected(tab.connectionId);
console.info("[DBX][executeTabSql:mongo-find:start]", { traceId, collection: mongoFind.collection });
- const result = await api.mongoFindDocuments(
- tab.connectionId,
- tab.database,
- mongoFind.collection,
- mongoFind.skip,
- mongoFind.limit,
- mongoFind.filter,
- mongoFind.sort,
- );
+ const result = await api.mongoFindDocuments(tab.connectionId, tab.database, mongoFind.collection, mongoFind.skip, mongoFind.limit, mongoFind.filter, mongoFind.sort);
console.info("[DBX][executeTabSql:mongo-find:done]", {
traceId,
rowCount: result.documents.length,
@@ -1048,9 +914,7 @@ export const useQueryStore = defineStore("query", () => {
if (current?.executionId === executionId) {
current.results = undefined;
current.activeResultIndex = undefined;
- current.result = markQueryResultRowsRaw(
- mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total),
- );
+ current.result = markQueryResultRowsRaw(mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total));
touchResult(current);
current.queryAnalysis = undefined;
current.querySourceColumns = undefined;
@@ -1065,14 +929,7 @@ export const useQueryStore = defineStore("query", () => {
if (mongoCount) {
await connStore.ensureConnected(tab.connectionId);
console.info("[DBX][executeTabSql:mongo-count:start]", { traceId, collection: mongoCount.collection });
- const result = await api.mongoFindDocuments(
- tab.connectionId,
- tab.database,
- mongoCount.collection,
- 0,
- 1,
- mongoCount.filter,
- );
+ const result = await api.mongoFindDocuments(tab.connectionId, tab.database, mongoCount.collection, 0, 1, mongoCount.filter);
console.info("[DBX][executeTabSql:mongo-count:done]", {
traceId,
total: result.total,
@@ -1102,13 +959,7 @@ export const useQueryStore = defineStore("query", () => {
}
await connStore.ensureConnected(tab.connectionId);
console.info("[DBX][executeTabSql:mongo-aggregate:start]", { traceId, collection: mongoAggregate.collection });
- const result = await api.mongoAggregateDocuments(
- tab.connectionId,
- tab.database,
- mongoAggregate.collection,
- mongoAggregate.pipeline,
- pageLimit,
- );
+ const result = await api.mongoAggregateDocuments(tab.connectionId, tab.database, mongoAggregate.collection, mongoAggregate.pipeline, pageLimit);
console.info("[DBX][executeTabSql:mongo-aggregate:done]", {
traceId,
rowCount: result.documents.length,
@@ -1119,9 +970,7 @@ export const useQueryStore = defineStore("query", () => {
if (current?.executionId === executionId) {
current.results = undefined;
current.activeResultIndex = undefined;
- current.result = markQueryResultRowsRaw(
- mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total),
- );
+ current.result = markQueryResultRowsRaw(mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total));
touchResult(current);
current.queryAnalysis = undefined;
current.querySourceColumns = undefined;
@@ -1169,31 +1018,13 @@ export const useQueryStore = defineStore("query", () => {
});
let affectedRows = 0;
if (mongoWrite.kind === "insert") {
- const result = await api.mongoInsertDocuments(
- tab.connectionId,
- tab.database,
- mongoWrite.collection,
- mongoWrite.docsJson,
- );
+ const result = await api.mongoInsertDocuments(tab.connectionId, tab.database, mongoWrite.collection, mongoWrite.docsJson);
affectedRows = result.affected_rows;
} else if (mongoWrite.kind === "update") {
- const result = await api.mongoUpdateDocuments(
- tab.connectionId,
- tab.database,
- mongoWrite.collection,
- mongoWrite.filter,
- mongoWrite.update,
- mongoWrite.many,
- );
+ const result = await api.mongoUpdateDocuments(tab.connectionId, tab.database, mongoWrite.collection, mongoWrite.filter, mongoWrite.update, mongoWrite.many);
affectedRows = result.affected_rows;
} else {
- const result = await api.mongoDeleteDocuments(
- tab.connectionId,
- tab.database,
- mongoWrite.collection,
- mongoWrite.filter,
- mongoWrite.many,
- );
+ const result = await api.mongoDeleteDocuments(tab.connectionId, tab.database, mongoWrite.collection, mongoWrite.filter, mongoWrite.many);
affectedRows = result.affected_rows;
}
console.info("[DBX][executeTabSql:mongo-write:done]", {
@@ -1233,27 +1064,10 @@ export const useQueryStore = defineStore("query", () => {
...(clientSessionId ? { clientSessionId } : {}),
timeoutSecs: queryTimeoutSecs,
};
- const executionSchema = connectionUsesSchemaExecutionContext(conn)
- ? tab.schema || tab.database
- : tab.mode === "data" || connectionUsesDatabaseObjectTreeMode(conn)
- ? undefined
- : tab.schema;
- const executionPromise = api.executeMulti(
- tab.connectionId,
- tab.database,
- sqlToExecute,
- executionSchema,
- executionId,
- executionOptions,
- );
+ const executionSchema = connectionUsesSchemaExecutionContext(conn) ? tab.schema || tab.database : tab.mode === "data" || connectionUsesDatabaseObjectTreeMode(conn) ? undefined : tab.schema;
+ const executionPromise = api.executeMulti(tab.connectionId, tab.database, sqlToExecute, executionSchema, executionId, executionOptions);
const frontendTimeoutSecs = Math.max(queryTimeoutSecs * 2, 60);
- const results = markQueryResultsRowsRaw(
- await withFrontendQueryTimeout(
- executionPromise,
- queryTimeoutSecs === 0 ? 0 : frontendTimeoutSecs,
- t("editor.queryTimeoutError", { seconds: frontendTimeoutSecs }),
- ),
- );
+ const results = markQueryResultsRowsRaw(await withFrontendQueryTimeout(executionPromise, queryTimeoutSecs === 0 ? 0 : frontendTimeoutSecs, t("editor.queryTimeoutError", { seconds: frontendTimeoutSecs })));
console.info("[DBX][executeTabSql:execute-multi:done]", {
traceId,
resultCount: results.length,
@@ -1289,13 +1103,7 @@ export const useQueryStore = defineStore("query", () => {
// the Elasticsearch driver) already reports the true match total via
// affected_rows. Use it directly so the result-grid can compute the
// page count without issuing a separate COUNT query.
- if (
- current.result &&
- current.mode === "query" &&
- typeof pageLimit === "number" &&
- !countSql &&
- typeof current.result.affected_rows === "number"
- ) {
+ if (current.result && current.mode === "query" && typeof pageLimit === "number" && !countSql && typeof current.result.affected_rows === "number") {
current.resultTotalRowCount = current.result.affected_rows;
current.resultTotalRowCountLoading = false;
}
@@ -1324,8 +1132,7 @@ export const useQueryStore = defineStore("query", () => {
backendMs: current.result?.execution_time_ms,
elapsed: elapsed(),
});
- if (current.mode === "query" && current.result)
- analyzeQueryMetadataInBackground(id, queryBaseSql, current.result, traceId, elapsed);
+ if (current.mode === "query" && current.result) analyzeQueryMetadataInBackground(id, queryBaseSql, current.result, traceId, elapsed);
} else {
console.warn("[DBX][executeTabSql:stale-result]", {
traceId,
@@ -1403,9 +1210,7 @@ export const useQueryStore = defineStore("query", () => {
}
try {
const mode = explainMode === "autotrace" ? "autotrace" : "explain";
- const planText = (await api.getExplainInfo(tab.connectionId, tab.database, tab.schema, sql, mode)) as
- | string
- | undefined;
+ const planText = (await api.getExplainInfo(tab.connectionId, tab.database, tab.schema, sql, mode)) as string | undefined;
const current = tabs.value.find((t) => t.id === id);
if (current?.explainExecutionId === executionId) {
if (planText && planText.length > 0) {
@@ -1536,9 +1341,7 @@ export const useQueryStore = defineStore("query", () => {
}
async function trimResultCache() {
- const inactive = tabs.value
- .filter((t) => t.id !== activeTabId.value && (t.result || t.results))
- .sort((a, b) => (a.resultAccessedAt ?? 0) - (b.resultAccessedAt ?? 0));
+ const inactive = tabs.value.filter((t) => t.id !== activeTabId.value && (t.result || t.results)).sort((a, b) => (a.resultAccessedAt ?? 0) - (b.resultAccessedAt ?? 0));
if (inactive.length > MAX_CACHED_RESULTS) {
const toEvict = inactive.slice(0, inactive.length - MAX_CACHED_RESULTS);
await Promise.all(toEvict.map((t) => evictCachedResult(t)));
@@ -1555,11 +1358,7 @@ export const useQueryStore = defineStore("query", () => {
const activeIndex = snapshot.activeResultIndex ?? 0;
tab.results = results;
tab.activeResultIndex = snapshot.activeResultIndex;
- tab.result = snapshot.result
- ? markQueryResultRowsRaw(snapshot.result)
- : results?.[activeIndex]
- ? markQueryResultRowsRaw(results[activeIndex])
- : undefined;
+ tab.result = snapshot.result ? markQueryResultRowsRaw(snapshot.result) : results?.[activeIndex] ? markQueryResultRowsRaw(results[activeIndex]) : undefined;
if (!tab.result && !tab.results) return false;
tab.queryAnalysis = snapshot.queryAnalysis;
@@ -1617,17 +1416,9 @@ export const useQueryStore = defineStore("query", () => {
const pageLimit = TABLE_DATA_EXPORT_PAGE_SIZE;
const effectiveDbType = effectiveDatabaseTypeForConnection(conn);
- const primaryKeys = tab.tableMeta
- ? editablePrimaryKeys(effectiveDbType, tab.tableMeta.columns)
- : tableMeta.primaryKeys;
- const fallbackOrderColumns =
- effectiveDbType === "sqlserver" && !primaryKeys.length
- ? tableMeta.columns.slice(0, 1).map((column) => column.name)
- : undefined;
- const sortOrder =
- tab.resultSortColumn && tab.resultSortDirection
- ? `${quoteTableIdentifier(effectiveDbType, tab.resultSortColumn)} ${tab.resultSortDirection.toUpperCase()}`
- : undefined;
+ const primaryKeys = tab.tableMeta ? editablePrimaryKeys(effectiveDbType, tab.tableMeta.columns) : tableMeta.primaryKeys;
+ const fallbackOrderColumns = effectiveDbType === "sqlserver" && !primaryKeys.length ? tableMeta.columns.slice(0, 1).map((column) => column.name) : undefined;
+ const sortOrder = tab.resultSortColumn && tab.resultSortDirection ? `${quoteTableIdentifier(effectiveDbType, tab.resultSortColumn)} ${tab.resultSortDirection.toUpperCase()}` : undefined;
const orderBy = tab.orderByInput?.trim() || sortOrder;
const queryTimeoutSecs = queryTimeoutSecsForConnection(conn);
const rows: QueryResult["rows"] = [];
@@ -1712,23 +1503,14 @@ export const useQueryStore = defineStore("query", () => {
timeoutSecs: queryTimeoutSecs,
}
: { maxRows: plan.pageLimit, fetchSize: plan.pageLimit, timeoutSecs: queryTimeoutSecs };
- const results = await api.executeMulti(
- tab.connectionId,
- tab.database,
- plan.sqlToExecute,
- tab.schema,
- undefined,
- executionOptions,
- );
+ const results = await api.executeMulti(tab.connectionId, tab.database, plan.sqlToExecute, tab.schema, undefined, executionOptions);
const result = results[0];
if (!result) break;
if (columns.length === 0) columns = result.columns;
rows.push(...result.rows);
executionTimeMs += result.execution_time_ms ?? 0;
sessionId = result.session_id ?? undefined;
- const shouldFetchNextPage = plan.useAgentResultSession
- ? result.has_more === true
- : result.rows.length >= plan.pageLimit;
+ const shouldFetchNextPage = plan.useAgentResultSession ? result.has_more === true : result.rows.length >= plan.pageLimit;
if (!shouldFetchNextPage) break;
offset += result.rows.length;
}
diff --git a/apps/desktop/src/stores/savedSqlStore.ts b/apps/desktop/src/stores/savedSqlStore.ts
index 663ddb0caa..63e9fd7e82 100644
--- a/apps/desktop/src/stores/savedSqlStore.ts
+++ b/apps/desktop/src/stores/savedSqlStore.ts
@@ -105,9 +105,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
}
function listFiles(connectionId: string, folderId?: string) {
- return sortFilesByOrder(
- files.value.filter((file) => file.connectionId === connectionId && (file.folderId || "") === (folderId || "")),
- );
+ return sortFilesByOrder(files.value.filter((file) => file.connectionId === connectionId && (file.folderId || "") === (folderId || "")));
}
function getFile(id: string) {
@@ -148,15 +146,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
await syncToLocalDirectory();
}
- async function saveFile(input: {
- id?: string;
- connectionId: string;
- folderId?: string;
- name: string;
- database: string;
- schema?: string;
- sql: string;
- }) {
+ async function saveFile(input: { id?: string; connectionId: string; folderId?: string; name: string; database: string; schema?: string; sql: string }) {
const timestamp = nowIso();
const existing = input.id ? getFile(input.id) : undefined;
const file: SavedSqlFile = existing
@@ -177,14 +167,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
database: input.database,
schema: input.schema,
sql: input.sql,
- orderIndex:
- maxOrderIndex(
- files.value.filter(
- (file) =>
- file.connectionId === input.connectionId &&
- (file.folderId || "") === (input.folderId || undefined || ""),
- ),
- ) + 1,
+ orderIndex: maxOrderIndex(files.value.filter((file) => file.connectionId === input.connectionId && (file.folderId || "") === (input.folderId || undefined || ""))) + 1,
createdAt: timestamp,
updatedAt: timestamp,
};
@@ -241,9 +224,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
const targetDir = settingsStore.desktopSettings.saved_sql_sync_dir?.trim();
if (!targetDir) return;
- const syncPromise =
- pendingSync?.catch(() => {}).then(() => api.syncSavedSqlDirectory({ targetDir, entries: syncEntries() })) ??
- api.syncSavedSqlDirectory({ targetDir, entries: syncEntries() });
+ const syncPromise = pendingSync?.catch(() => {}).then(() => api.syncSavedSqlDirectory({ targetDir, entries: syncEntries() })) ?? api.syncSavedSqlDirectory({ targetDir, entries: syncEntries() });
pendingSync = syncPromise;
try {
await syncPromise;
@@ -276,12 +257,8 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
if ((target.folderId || undefined) === targetFolderId) return;
const timestamp = nowIso();
- const sourceGroup = sortFilesByOrder(
- files.value.filter((file) => (file.folderId || "") === (target.folderId || "")),
- ).filter((file) => file.id !== fileId);
- const destinationGroup = sortFilesByOrder(
- files.value.filter((file) => file.id !== fileId && (file.folderId || "") === (targetFolderId || "")),
- );
+ const sourceGroup = sortFilesByOrder(files.value.filter((file) => (file.folderId || "") === (target.folderId || ""))).filter((file) => file.id !== fileId);
+ const destinationGroup = sortFilesByOrder(files.value.filter((file) => file.id !== fileId && (file.folderId || "") === (targetFolderId || "")));
const movedFile: SavedSqlFile = {
...target,
@@ -298,12 +275,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
updatedAt: timestamp,
}));
- const untouched = files.value.filter(
- (file) =>
- file.id !== fileId &&
- (file.folderId || "") !== (target.folderId || "") &&
- (file.folderId || "") !== (targetFolderId || ""),
- );
+ const untouched = files.value.filter((file) => file.id !== fileId && (file.folderId || "") !== (target.folderId || "") && (file.folderId || "") !== (targetFolderId || ""));
await persistFiles([...untouched, ...nextSource, ...nextDestination]);
}
@@ -331,22 +303,9 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
}));
const previousGroupId = dragged.folderId || undefined;
- const sourceGroup =
- previousGroupId === targetFolderId
- ? []
- : reindexFiles(
- sortFilesByOrder(
- files.value.filter((file) => file.id !== draggedId && (file.folderId || "") === (previousGroupId || "")),
- ),
- previousGroupId,
- ).map((file) => ({ ...file, updatedAt: draggedNext.updatedAt }));
-
- const untouched = files.value.filter(
- (file) =>
- file.id !== draggedId &&
- (file.folderId || "") !== (targetFolderId || "") &&
- (file.folderId || "") !== (previousGroupId || ""),
- );
+ const sourceGroup = previousGroupId === targetFolderId ? [] : reindexFiles(sortFilesByOrder(files.value.filter((file) => file.id !== draggedId && (file.folderId || "") === (previousGroupId || ""))), previousGroupId).map((file) => ({ ...file, updatedAt: draggedNext.updatedAt }));
+
+ const untouched = files.value.filter((file) => file.id !== draggedId && (file.folderId || "") !== (targetFolderId || "") && (file.folderId || "") !== (previousGroupId || ""));
await persistFiles([...untouched, ...sourceGroup, ...updatedGroup]);
}
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index a5090a4ef1..04bb6ce5d0 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -1,34 +1,17 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import * as api from "@/lib/api";
-import {
- normalizeColumnFormatter,
- normalizeCustomColumnFormatter,
- type ColumnFormatterConfig,
- type CustomColumnFormatterConfig,
-} from "@/lib/columnFormatter";
+import { normalizeColumnFormatter, normalizeCustomColumnFormatter, type ColumnFormatterConfig, type CustomColumnFormatterConfig } from "@/lib/columnFormatter";
import { normalizeShortcutSettings, type ShortcutSettings } from "@/lib/shortcutRegistry";
import { normalizeResultPageSize } from "@/lib/paginationPageSize";
import { normalizeSidebarHiddenTablePrefixes } from "@/lib/sidebarTableNameDisplay";
-import {
- DEFAULT_SQL_FORMATTER_SETTINGS,
- normalizeSqlFormatterSettings,
- type SqlFormatterSettings,
-} from "@/lib/sqlFormatterConfig";
+import { DEFAULT_SQL_FORMATTER_SETTINGS, normalizeSqlFormatterSettings, type SqlFormatterSettings } from "@/lib/sqlFormatterConfig";
import type { SidebarActivation } from "@/lib/treeNodeClick";
import type { SqlSnippet } from "@/types/database";
import { DEFAULT_SQL_SNIPPETS } from "@/lib/sqlCompletion";
import { setDebugLoggingEnabled } from "@/lib/debugLog";
-export type AiProvider =
- | "claude"
- | "openai"
- | "gemini"
- | "deepseek"
- | "qwen"
- | "ollama"
- | "openai-compatible"
- | "custom";
+export type AiProvider = "claude" | "openai" | "gemini" | "deepseek" | "qwen" | "ollama" | "openai-compatible" | "custom";
export type AiApiStyle = "completions" | "responses";
export interface AiConfig {
@@ -156,8 +139,7 @@ const defaultConfigs: Record<AiProvider, Omit<AiConfig, "apiKey">> = Object.from
) as Record<AiProvider, Omit<AiConfig, "apiKey">>;
export function normalizeAiConfig(config: Partial<AiConfig> | null | undefined): AiConfig {
- const provider =
- config?.provider && config.provider in AI_PROVIDER_PRESETS ? config.provider : inferAiProviderFromConfig(config);
+ const provider = config?.provider && config.provider in AI_PROVIDER_PRESETS ? config.provider : inferAiProviderFromConfig(config);
return {
...defaultConfigs[provider],
apiKey: config?.apiKey ?? "",
@@ -181,18 +163,7 @@ function inferAiProviderFromConfig(config: Partial<AiConfig> | null | undefined)
return "claude";
}
-export type EditorTheme =
- | "app"
- | "one-dark"
- | "vscode-dark"
- | "vscode-light"
- | "nord"
- | "okaidia"
- | "material"
- | "duotone-light"
- | "duotone-dark"
- | "xcode"
- | "custom";
+export type EditorTheme = "app" | "one-dark" | "vscode-dark" | "vscode-light" | "nord" | "okaidia" | "material" | "duotone-light" | "duotone-dark" | "xcode" | "custom";
const STRUCTURE_EDITOR_DENSITIES = ["compact", "standard", "comfortable"] as const;
export type StructureEditorDensity = (typeof STRUCTURE_EDITOR_DENSITIES)[number];
@@ -237,9 +208,7 @@ export interface CustomTheme {
colors: CustomThemeColors;
}
-export const DEFAULT_CUSTOM_THEMES: CustomTheme[] = [
- { id: "default", name: "Custom", colors: { ...DEFAULT_CUSTOM_THEME_COLORS } },
-];
+export const DEFAULT_CUSTOM_THEMES: CustomTheme[] = [{ id: "default", name: "Custom", colors: { ...DEFAULT_CUSTOM_THEME_COLORS } }];
export interface EditorSettings {
fontFamily: string;
@@ -365,27 +334,18 @@ function normalizeDrawerWidth(value: unknown, min: number, fallback: number): nu
}
function normalizeStructureEditorDensity(value: unknown): StructureEditorDensity {
- return STRUCTURE_EDITOR_DENSITIES.includes(value as StructureEditorDensity)
- ? (value as StructureEditorDensity)
- : DEFAULT_EDITOR_SETTINGS.structureEditorDensity;
+ return STRUCTURE_EDITOR_DENSITIES.includes(value as StructureEditorDensity) ? (value as StructureEditorDensity) : DEFAULT_EDITOR_SETTINGS.structureEditorDensity;
}
function normalizeCellDetailPanelLayout(value: unknown): CellDetailPanelLayout {
- return CELL_DETAIL_PANEL_LAYOUTS.includes(value as CellDetailPanelLayout)
- ? (value as CellDetailPanelLayout)
- : DEFAULT_EDITOR_SETTINGS.cellDetailPanelLayout;
+ return CELL_DETAIL_PANEL_LAYOUTS.includes(value as CellDetailPanelLayout) ? (value as CellDetailPanelLayout) : DEFAULT_EDITOR_SETTINGS.cellDetailPanelLayout;
}
function normalizeDataGridRenderMode(value: unknown): DataGridRenderMode {
- return DATA_GRID_RENDER_MODES.includes(value as DataGridRenderMode)
- ? (value as DataGridRenderMode)
- : DEFAULT_EDITOR_SETTINGS.dataGridRenderMode;
+ return DATA_GRID_RENDER_MODES.includes(value as DataGridRenderMode) ? (value as DataGridRenderMode) : DEFAULT_EDITOR_SETTINGS.dataGridRenderMode;
}
-function normalizeDisconnectTabHandlingMode(
- value: unknown,
- legacyCloseTabsOnDisconnect?: unknown,
-): DisconnectTabHandlingMode {
+function normalizeDisconnectTabHandlingMode(value: unknown, legacyCloseTabsOnDisconnect?: unknown): DisconnectTabHandlingMode {
if (DISCONNECT_TAB_HANDLING_MODES.includes(value as DisconnectTabHandlingMode)) {
return value as DisconnectTabHandlingMode;
}
@@ -422,17 +382,7 @@ function normalizeSqlSnippets(value: unknown, existing?: SqlSnippet[]): SqlSnipp
const valid: SqlSnippet[] = [];
const seenPrefixes = new Set<string>();
for (const item of value) {
- if (
- !item ||
- typeof item !== "object" ||
- typeof item.id !== "string" ||
- !item.id ||
- typeof item.label !== "string" ||
- !item.label ||
- typeof item.prefix !== "string" ||
- !item.prefix ||
- typeof item.body !== "string"
- ) {
+ if (!item || typeof item !== "object" || typeof item.id !== "string" || !item.id || typeof item.label !== "string" || !item.label || typeof item.prefix !== "string" || !item.prefix || typeof item.body !== "string") {
continue;
}
if (seenPrefixes.has(item.prefix)) continue;
@@ -473,63 +423,35 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
activeCustomThemeId: settings.activeCustomThemeId ?? "default",
executeMode: settings.executeMode ?? DEFAULT_EDITOR_SETTINGS.executeMode,
wordWrap: settings.wordWrap ?? DEFAULT_EDITOR_SETTINGS.wordWrap,
- confirmDangerousSqlExecution:
- settings.confirmDangerousSqlExecution ?? DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution,
+ confirmDangerousSqlExecution: settings.confirmDangerousSqlExecution ?? DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution,
compactTabTitle: settings.compactTabTitle ?? DEFAULT_EDITOR_SETTINGS.compactTabTitle,
appLayout: settings.appLayout ?? DEFAULT_EDITOR_SETTINGS.appLayout,
pageSize: normalizeResultPageSize(settings.pageSize),
redisScanPageSize: settings.redisScanPageSize ?? DEFAULT_EDITOR_SETTINGS.redisScanPageSize,
mongoViewMode: settings.mongoViewMode === "table" ? "table" : DEFAULT_EDITOR_SETTINGS.mongoViewMode,
- showColumnCommentsInHeader:
- settings.showColumnCommentsInHeader ?? DEFAULT_EDITOR_SETTINGS.showColumnCommentsInHeader,
+ showColumnCommentsInHeader: settings.showColumnCommentsInHeader ?? DEFAULT_EDITOR_SETTINGS.showColumnCommentsInHeader,
showColumnTypesInHeader: settings.showColumnTypesInHeader ?? DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader,
- compactColumnHeaderActions:
- settings.compactColumnHeaderActions ?? DEFAULT_EDITOR_SETTINGS.compactColumnHeaderActions,
+ compactColumnHeaderActions: settings.compactColumnHeaderActions ?? DEFAULT_EDITOR_SETTINGS.compactColumnHeaderActions,
dataGridRenderMode: normalizeDataGridRenderMode(settings.dataGridRenderMode),
structureEditorDensity: normalizeStructureEditorDensity(settings.structureEditorDensity),
- tableInfoDrawerWidth: normalizeDrawerWidth(
- settings.tableInfoDrawerWidth,
- 240,
- DEFAULT_EDITOR_SETTINGS.tableInfoDrawerWidth,
- ),
- cellDetailDrawerWidth: normalizeDrawerWidth(
- settings.cellDetailDrawerWidth,
- 260,
- DEFAULT_EDITOR_SETTINGS.cellDetailDrawerWidth,
- ),
+ tableInfoDrawerWidth: normalizeDrawerWidth(settings.tableInfoDrawerWidth, 240, DEFAULT_EDITOR_SETTINGS.tableInfoDrawerWidth),
+ cellDetailDrawerWidth: normalizeDrawerWidth(settings.cellDetailDrawerWidth, 260, DEFAULT_EDITOR_SETTINGS.cellDetailDrawerWidth),
cellDetailPanelLayout: normalizeCellDetailPanelLayout(settings.cellDetailPanelLayout),
shortcuts: normalizeShortcutSettings(settings.shortcuts),
sqlFormatter: normalizeSqlFormatterSettings(settings.sqlFormatter),
- sidebarActivation:
- settings.sidebarActivation === "single" || settings.sidebarActivation === "double"
- ? settings.sidebarActivation
- : DEFAULT_EDITOR_SETTINGS.sidebarActivation,
- sidebarObjectDisplay:
- settings.sidebarObjectDisplay === "simple" || settings.sidebarObjectDisplay === "grouped"
- ? settings.sidebarObjectDisplay
- : DEFAULT_EDITOR_SETTINGS.sidebarObjectDisplay,
- autoSelectActiveSidebarNode:
- settings.autoSelectActiveSidebarNode ?? DEFAULT_EDITOR_SETTINGS.autoSelectActiveSidebarNode,
- disconnectTabHandlingMode: normalizeDisconnectTabHandlingMode(
- (settings as Partial<EditorSettings>).disconnectTabHandlingMode,
- (settings as Partial<EditorSettings> & { closeQueryTabsOnDisconnect?: boolean }).closeQueryTabsOnDisconnect,
- ),
+ sidebarActivation: settings.sidebarActivation === "single" || settings.sidebarActivation === "double" ? settings.sidebarActivation : DEFAULT_EDITOR_SETTINGS.sidebarActivation,
+ sidebarObjectDisplay: settings.sidebarObjectDisplay === "simple" || settings.sidebarObjectDisplay === "grouped" ? settings.sidebarObjectDisplay : DEFAULT_EDITOR_SETTINGS.sidebarObjectDisplay,
+ autoSelectActiveSidebarNode: settings.autoSelectActiveSidebarNode ?? DEFAULT_EDITOR_SETTINGS.autoSelectActiveSidebarNode,
+ disconnectTabHandlingMode: normalizeDisconnectTabHandlingMode((settings as Partial<EditorSettings>).disconnectTabHandlingMode, (settings as Partial<EditorSettings> & { closeQueryTabsOnDisconnect?: boolean }).closeQueryTabsOnDisconnect),
reuseDataTab: settings.reuseDataTab ?? DEFAULT_EDITOR_SETTINGS.reuseDataTab,
- updateNotificationsEnabled:
- settings.updateNotificationsEnabled ?? DEFAULT_EDITOR_SETTINGS.updateNotificationsEnabled,
+ updateNotificationsEnabled: settings.updateNotificationsEnabled ?? DEFAULT_EDITOR_SETTINGS.updateNotificationsEnabled,
sidebarHiddenTablePrefixes: normalizeSidebarHiddenTablePrefixes(settings.sidebarHiddenTablePrefixes),
sidebarHideTableComments: settings.sidebarHideTableComments ?? DEFAULT_EDITOR_SETTINGS.sidebarHideTableComments,
- sidebarAllowHorizontalScroll:
- settings.sidebarAllowHorizontalScroll ?? DEFAULT_EDITOR_SETTINGS.sidebarAllowHorizontalScroll,
+ sidebarAllowHorizontalScroll: settings.sidebarAllowHorizontalScroll ?? DEFAULT_EDITOR_SETTINGS.sidebarAllowHorizontalScroll,
columnFormatters: normalizeColumnFormatters(settings.columnFormatters),
customColumnFormatters: normalizeCustomColumnFormatters(settings.customColumnFormatters),
snippets: normalizeSqlSnippets(settings.snippets, existing?.snippets),
- exportBatchSize:
- typeof settings.exportBatchSize === "number" &&
- settings.exportBatchSize >= 100 &&
- settings.exportBatchSize <= 100000
- ? Math.round(settings.exportBatchSize)
- : DEFAULT_EDITOR_SETTINGS.exportBatchSize,
+ exportBatchSize: typeof settings.exportBatchSize === "number" && settings.exportBatchSize >= 100 && settings.exportBatchSize <= 100000 ? Math.round(settings.exportBatchSize) : DEFAULT_EDITOR_SETTINGS.exportBatchSize,
};
}
@@ -640,9 +562,7 @@ export const useSettingsStore = defineStore("settings", () => {
};
}
if (partial.customThemes !== undefined) {
- editorSettings.value.customThemes = Array.isArray(partial.customThemes)
- ? partial.customThemes
- : editorSettings.value.customThemes;
+ editorSettings.value.customThemes = Array.isArray(partial.customThemes) ? partial.customThemes : editorSettings.value.customThemes;
}
if (partial.activeCustomThemeId !== undefined) {
editorSettings.value.activeCustomThemeId = partial.activeCustomThemeId;
@@ -657,58 +577,35 @@ export const useSettingsStore = defineStore("settings", () => {
}
if (partial.executeMode !== undefined) editorSettings.value.executeMode = partial.executeMode;
if (partial.wordWrap !== undefined) editorSettings.value.wordWrap = partial.wordWrap;
- if (partial.confirmDangerousSqlExecution !== undefined)
- editorSettings.value.confirmDangerousSqlExecution = partial.confirmDangerousSqlExecution;
+ if (partial.confirmDangerousSqlExecution !== undefined) editorSettings.value.confirmDangerousSqlExecution = partial.confirmDangerousSqlExecution;
if (partial.compactTabTitle !== undefined) editorSettings.value.compactTabTitle = partial.compactTabTitle;
if (partial.appLayout !== undefined) editorSettings.value.appLayout = partial.appLayout;
if (partial.pageSize !== undefined) editorSettings.value.pageSize = normalizeResultPageSize(partial.pageSize);
if (partial.redisScanPageSize !== undefined) editorSettings.value.redisScanPageSize = partial.redisScanPageSize;
if (partial.mongoViewMode !== undefined) editorSettings.value.mongoViewMode = partial.mongoViewMode;
- if (partial.showColumnCommentsInHeader !== undefined)
- editorSettings.value.showColumnCommentsInHeader = partial.showColumnCommentsInHeader;
- if (partial.showColumnTypesInHeader !== undefined)
- editorSettings.value.showColumnTypesInHeader = partial.showColumnTypesInHeader;
- if (partial.compactColumnHeaderActions !== undefined)
- editorSettings.value.compactColumnHeaderActions = partial.compactColumnHeaderActions;
- if (partial.dataGridRenderMode !== undefined)
- editorSettings.value.dataGridRenderMode = normalizeDataGridRenderMode(partial.dataGridRenderMode);
- if (partial.structureEditorDensity !== undefined)
- editorSettings.value.structureEditorDensity = normalizeStructureEditorDensity(partial.structureEditorDensity);
- if (partial.tableInfoDrawerWidth !== undefined)
- editorSettings.value.tableInfoDrawerWidth = normalizeDrawerWidth(partial.tableInfoDrawerWidth, 240, 320);
- if (partial.cellDetailDrawerWidth !== undefined)
- editorSettings.value.cellDetailDrawerWidth = normalizeDrawerWidth(partial.cellDetailDrawerWidth, 260, 320);
- if (partial.cellDetailPanelLayout !== undefined)
- editorSettings.value.cellDetailPanelLayout = normalizeCellDetailPanelLayout(partial.cellDetailPanelLayout);
+ if (partial.showColumnCommentsInHeader !== undefined) editorSettings.value.showColumnCommentsInHeader = partial.showColumnCommentsInHeader;
+ if (partial.showColumnTypesInHeader !== undefined) editorSettings.value.showColumnTypesInHeader = partial.showColumnTypesInHeader;
+ if (partial.compactColumnHeaderActions !== undefined) editorSettings.value.compactColumnHeaderActions = partial.compactColumnHeaderActions;
+ if (partial.dataGridRenderMode !== undefined) editorSettings.value.dataGridRenderMode = normalizeDataGridRenderMode(partial.dataGridRenderMode);
+ if (partial.structureEditorDensity !== undefined) editorSettings.value.structureEditorDensity = normalizeStructureEditorDensity(partial.structureEditorDensity);
+ if (partial.tableInfoDrawerWidth !== undefined) editorSettings.value.tableInfoDrawerWidth = normalizeDrawerWidth(partial.tableInfoDrawerWidth, 240, 320);
+ if (partial.cellDetailDrawerWidth !== undefined) editorSettings.value.cellDetailDrawerWidth = normalizeDrawerWidth(partial.cellDetailDrawerWidth, 260, 320);
+ if (partial.cellDetailPanelLayout !== undefined) editorSettings.value.cellDetailPanelLayout = normalizeCellDetailPanelLayout(partial.cellDetailPanelLayout);
if (partial.shortcuts !== undefined) editorSettings.value.shortcuts = normalizeShortcutSettings(partial.shortcuts);
- if (partial.sqlFormatter !== undefined)
- editorSettings.value.sqlFormatter = normalizeSqlFormatterSettings(partial.sqlFormatter);
+ if (partial.sqlFormatter !== undefined) editorSettings.value.sqlFormatter = normalizeSqlFormatterSettings(partial.sqlFormatter);
if (partial.sidebarActivation !== undefined) editorSettings.value.sidebarActivation = partial.sidebarActivation;
- if (partial.sidebarObjectDisplay !== undefined)
- editorSettings.value.sidebarObjectDisplay = partial.sidebarObjectDisplay;
- if (partial.autoSelectActiveSidebarNode !== undefined)
- editorSettings.value.autoSelectActiveSidebarNode = partial.autoSelectActiveSidebarNode;
- if (partial.disconnectTabHandlingMode !== undefined)
- editorSettings.value.disconnectTabHandlingMode = normalizeDisconnectTabHandlingMode(
- partial.disconnectTabHandlingMode,
- );
+ if (partial.sidebarObjectDisplay !== undefined) editorSettings.value.sidebarObjectDisplay = partial.sidebarObjectDisplay;
+ if (partial.autoSelectActiveSidebarNode !== undefined) editorSettings.value.autoSelectActiveSidebarNode = partial.autoSelectActiveSidebarNode;
+ if (partial.disconnectTabHandlingMode !== undefined) editorSettings.value.disconnectTabHandlingMode = normalizeDisconnectTabHandlingMode(partial.disconnectTabHandlingMode);
if (partial.reuseDataTab !== undefined) editorSettings.value.reuseDataTab = partial.reuseDataTab;
- if (partial.updateNotificationsEnabled !== undefined)
- editorSettings.value.updateNotificationsEnabled = partial.updateNotificationsEnabled;
- if (partial.sidebarHiddenTablePrefixes !== undefined)
- editorSettings.value.sidebarHiddenTablePrefixes = normalizeSidebarHiddenTablePrefixes(
- partial.sidebarHiddenTablePrefixes,
- );
- if (partial.sidebarHideTableComments !== undefined)
- editorSettings.value.sidebarHideTableComments = partial.sidebarHideTableComments;
- if (partial.sidebarAllowHorizontalScroll !== undefined)
- editorSettings.value.sidebarAllowHorizontalScroll = partial.sidebarAllowHorizontalScroll;
+ if (partial.updateNotificationsEnabled !== undefined) editorSettings.value.updateNotificationsEnabled = partial.updateNotificationsEnabled;
+ if (partial.sidebarHiddenTablePrefixes !== undefined) editorSettings.value.sidebarHiddenTablePrefixes = normalizeSidebarHiddenTablePrefixes(partial.sidebarHiddenTablePrefixes);
+ if (partial.sidebarHideTableComments !== undefined) editorSettings.value.sidebarHideTableComments = partial.sidebarHideTableComments;
+ if (partial.sidebarAllowHorizontalScroll !== undefined) editorSettings.value.sidebarAllowHorizontalScroll = partial.sidebarAllowHorizontalScroll;
if (partial.columnFormatters !== undefined) editorSettings.value.columnFormatters = partial.columnFormatters;
- if (partial.customColumnFormatters !== undefined)
- editorSettings.value.customColumnFormatters = partial.customColumnFormatters;
+ if (partial.customColumnFormatters !== undefined) editorSettings.value.customColumnFormatters = partial.customColumnFormatters;
if (partial.snippets !== undefined) editorSettings.value.snippets = normalizeSqlSnippets(partial.snippets);
- if (partial.exportBatchSize !== undefined)
- editorSettings.value.exportBatchSize = Math.min(100000, Math.max(100, Math.round(partial.exportBatchSize)));
+ if (partial.exportBatchSize !== undefined) editorSettings.value.exportBatchSize = Math.min(100000, Math.max(100, Math.round(partial.exportBatchSize)));
saveEditorSettings(editorSettings.value);
}
@@ -723,9 +620,7 @@ export const useSettingsStore = defineStore("settings", () => {
updateEditorSettings({ columnFormatters });
}
- function upsertCustomColumnFormatter(
- formatter: CustomColumnFormatterConfig,
- ): CustomColumnFormatterConfig | undefined {
+ function upsertCustomColumnFormatter(formatter: CustomColumnFormatterConfig): CustomColumnFormatterConfig | undefined {
const normalized = normalizeCustomColumnFormatter(formatter);
if (!normalized) return undefined;
updateEditorSettings({
diff --git a/apps/desktop/src/styles/globals.css b/apps/desktop/src/styles/globals.css
index f4537ee38a..1030d10462 100644
--- a/apps/desktop/src/styles/globals.css
+++ b/apps/desktop/src/styles/globals.css
@@ -4,9 +4,7 @@
font-display: swap;
font-weight: 100 900;
src: url("/fonts/geist-latin-ext-wght-normal.woff2") format("woff2-variations");
- unicode-range:
- U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF,
- U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
@@ -15,9 +13,7 @@
font-display: swap;
font-weight: 100 900;
src: url("/fonts/geist-latin-wght-normal.woff2") format("woff2-variations");
- unicode-range:
- U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F,
- U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
@@ -27,9 +23,7 @@
font-weight: 100 900;
font-feature-settings: "tnum";
src: url("/fonts/geist-latin-ext-wght-normal.woff2") format("woff2-variations");
- unicode-range:
- U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF,
- U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
@@ -39,9 +33,7 @@
font-weight: 100 900;
font-feature-settings: "tnum";
src: url("/fonts/geist-latin-wght-normal.woff2") format("woff2-variations");
- unicode-range:
- U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F,
- U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@import "tailwindcss";
@@ -54,8 +46,7 @@
@custom-variant dark (&:is(.dark *));
@theme inline {
- --font-sans:
- "Geist Variable", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
+ --font-sans: "Geist Variable", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
--font-heading: var(--font-sans);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index b3fc5deb8e..43599bc625 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -329,9 +329,7 @@ export interface ConnectionGroup {
collapsed: boolean;
}
-export type SidebarOrderEntry =
- | { type: "group"; id: string; connectionIds: string[] }
- | { type: "connection"; id: string };
+export type SidebarOrderEntry = { type: "group"; id: string; connectionIds: string[] } | { type: "connection"; id: string };
export interface SidebarLayout {
groups: ConnectionGroup[];
@@ -440,19 +438,7 @@ export interface QueryTab {
}[];
};
querySourceColumns?: Array<string | undefined>;
- queryEditabilityReason?:
- | "not-select"
- | "cte"
- | "set-operation"
- | "aggregation"
- | "external-source"
- | "complex-source"
- | "computed-columns"
- | "no-table"
- | "no-primary-key"
- | "primary-key-not-returned"
- | "aliased-columns"
- | "metadata-unavailable";
+ queryEditabilityReason?: "not-select" | "cte" | "set-operation" | "aggregation" | "external-source" | "complex-source" | "computed-columns" | "no-table" | "no-primary-key" | "primary-key-not-returned" | "aliased-columns" | "metadata-unavailable";
resultEvicted?: boolean;
whereInput?: string;
}
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index b0c3620814..268390ac27 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -6,15 +6,7 @@ import path from "path";
const host = process.env.TAURI_DEV_HOST;
const isTauri = !!host || !!process.env.TAURI_ENV_ARCH;
const manualChunks: Record<string, string[]> = {
- codemirror: [
- "codemirror",
- "@codemirror/lang-sql",
- "@codemirror/view",
- "@codemirror/state",
- "@codemirror/autocomplete",
- "@codemirror/commands",
- "@codemirror/theme-one-dark",
- ],
+ codemirror: ["codemirror", "@codemirror/lang-sql", "@codemirror/view", "@codemirror/state", "@codemirror/autocomplete", "@codemirror/commands", "@codemirror/theme-one-dark"],
"vue-echarts": ["vue-echarts"],
ui: ["reka-ui"],
marked: ["marked"],
diff --git a/crates/dbx-core/assets/agent-protocol-v1.json b/crates/dbx-core/assets/agent-protocol-v1.json
index fbd9adc429..4f4887954a 100644
--- a/crates/dbx-core/assets/agent-protocol-v1.json
+++ b/crates/dbx-core/assets/agent-protocol-v1.json
@@ -1,21 +1,8 @@
{
"protocolVersion": 1,
"handshakeMethod": "handshake",
- "handshakeResponseFields": [
- "protocolVersion",
- "agentProtocolVersion",
- "capabilities"
- ],
- "capabilities": [
- "connect",
- "test_connection",
- "metadata",
- "query",
- "paged_query",
- "transaction",
- "ddl",
- "kv"
- ],
+ "handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],
+ "capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv"],
"commonMethods": [
"handshake",
"connect",
@@ -39,18 +26,6 @@
"disconnect",
"shutdown"
],
- "mongoLegacyMethods": [
- "list_databases",
- "list_collections",
- "find_documents",
- "insert_document",
- "update_document",
- "delete_document"
- ],
- "kvMethods": [
- "kv_list_prefix",
- "kv_get",
- "kv_put",
- "kv_delete"
- ]
+ "mongoLegacyMethods": ["list_databases", "list_collections", "find_documents", "insert_document", "update_document", "delete_document"],
+ "kvMethods": ["kv_list_prefix", "kv_get", "kv_put", "kv_delete"]
}
diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.json
index 4a7261778a..f3a47e11da 100644
--- a/crates/dbx-core/assets/database-drivers.manifest.json
+++ b/crates/dbx-core/assets/database-drivers.manifest.json
@@ -339,9 +339,7 @@
"metadataConnectionScoped": false,
"skipTcpProbe": true,
"defaultPort": 5258,
- "driverProfiles": [
- { "profile": "gbase8s", "label": "GBase 8s", "agentKey": "gbase8s" }
- ]
+ "driverProfiles": [{ "profile": "gbase8s", "label": "GBase 8s", "agentKey": "gbase8s" }]
},
{
"dbType": "access",
diff --git a/docs/app/[lang]/api/search/route.ts b/docs/app/[lang]/api/search/route.ts
index feaae7751b..72b9282631 100644
--- a/docs/app/[lang]/api/search/route.ts
+++ b/docs/app/[lang]/api/search/route.ts
@@ -1,6 +1,6 @@
-import { createFromSource } from 'fumadocs-core/search/server';
-import { createCjkSearchTokenizer } from '@/lib/cjkSearchTokenizer';
-import { source } from '@/lib/source';
+import { createFromSource } from "fumadocs-core/search/server";
+import { createCjkSearchTokenizer } from "@/lib/cjkSearchTokenizer";
+import { source } from "@/lib/source";
export const revalidate = false;
export const { staticGET: GET } = createFromSource(source, {
@@ -10,5 +10,5 @@ export const { staticGET: GET } = createFromSource(source, {
});
export function generateStaticParams() {
- return [{ lang: 'en' }, { lang: 'cn' }];
+ return [{ lang: "en" }, { lang: "cn" }];
}
diff --git a/docs/app/[lang]/changelog/page.tsx b/docs/app/[lang]/changelog/page.tsx
index 34e28cf145..eb1cad4a6f 100644
--- a/docs/app/[lang]/changelog/page.tsx
+++ b/docs/app/[lang]/changelog/page.tsx
@@ -1,27 +1,23 @@
-import { LandingNav } from '@/components/landing/LandingNav';
-import { ChangelogRuntime } from '@/components/landing/ChangelogRuntime';
-import { fetchChangelog } from '@/lib/changelog';
-import { buildMetadata } from '@/lib/metadata';
-import type { Metadata } from 'next';
+import { LandingNav } from "@/components/landing/LandingNav";
+import { ChangelogRuntime } from "@/components/landing/ChangelogRuntime";
+import { fetchChangelog } from "@/lib/changelog";
+import { buildMetadata } from "@/lib/metadata";
+import type { Metadata } from "next";
const i18n = {
en: {
- title: 'Changelog',
- desc: 'Track every release — features, improvements, and fixes.',
+ title: "Changelog",
+ desc: "Track every release — features, improvements, and fixes.",
},
cn: {
- title: '更新日志',
- desc: '追踪每次发布 — 新功能、改进和修复。',
+ title: "更新日志",
+ desc: "追踪每次发布 — 新功能、改进和修复。",
},
};
-export async function generateMetadata({
- params,
-}: {
- params: Promise<{ lang: string }>;
-}): Promise<Metadata> {
+export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const t = i18n[l];
return buildMetadata({
@@ -34,7 +30,7 @@ export async function generateMetadata({
export default async function ChangelogPage({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const t = i18n[l];
const initialData = await fetchChangelog(l);
diff --git a/docs/app/[lang]/community/page.tsx b/docs/app/[lang]/community/page.tsx
index bc19507236..5351df5497 100644
--- a/docs/app/[lang]/community/page.tsx
+++ b/docs/app/[lang]/community/page.tsx
@@ -1,18 +1,18 @@
-import { LandingNav } from '@/components/landing/LandingNav';
-import { buildMetadata } from '@/lib/metadata';
-import type { Metadata } from 'next';
+import { LandingNav } from "@/components/landing/LandingNav";
+import { buildMetadata } from "@/lib/metadata";
+import type { Metadata } from "next";
const channels = [
{
- id: 'qq',
- color: '#EB1923',
- href: 'https://qm.qq.com/cgi-bin/qm/qr?k=&group_code=1087880322',
+ id: "qq",
+ color: "#EB1923",
+ href: "https://qm.qq.com/cgi-bin/qm/qr?k=&group_code=1087880322",
icon: <img src="/icons/community/qq.png" alt="QQ" width={24} height={24} />,
},
{
- id: 'wechat',
- color: '#07C160',
- href: 'https://docs.qq.com/doc/DVVhMY0h1ekJqc0tz',
+ id: "wechat",
+ color: "#07C160",
+ href: "https://docs.qq.com/doc/DVVhMY0h1ekJqc0tz",
icon: (
<svg width={24} height={24} viewBox="0 0 24 24" fill="currentColor">
<path d="M9.5 4C5.36 4 2 6.69 2 10c0 1.89 1.08 3.56 2.78 4.66l-.7 2.1 2.46-1.23c.87.27 1.8.42 2.78.42.24 0 .48-.01.71-.03A5.93 5.93 0 0110 14c0-3.31 3.13-6 7-6 .34 0 .67.03 1 .07C17.27 5.56 13.72 4 9.5 4zm-3 4.5a1 1 0 110-2 1 1 0 010 2zm5 0a1 1 0 110-2 1 1 0 010 2zM22 14c0-2.76-2.69-5-6-5s-6 2.24-6 5 2.69 5 6 5c.73 0 1.43-.11 2.09-.3l1.72.86-.49-1.46C20.94 17.07 22 15.64 22 14zm-7.5-.5a.75.75 0 110-1.5.75.75 0 010 1.5zm4 0a.75.75 0 110-1.5.75.75 0 010 1.5z" />
@@ -20,9 +20,9 @@ const channels = [
),
},
{
- id: 'discord',
- color: '#5865F2',
- href: 'https://discord.gg/W7NyVDRt6a',
+ id: "discord",
+ color: "#5865F2",
+ href: "https://discord.gg/W7NyVDRt6a",
icon: (
<svg width={24} height={24} viewBox="0 0 24 24" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 00.031.057 19.9 19.9 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
@@ -30,9 +30,9 @@ const channels = [
),
},
{
- id: 'github',
- color: '#f0f0f0',
- href: 'https://github.com/t8y2/dbx/discussions',
+ id: "github",
+ color: "#f0f0f0",
+ href: "https://github.com/t8y2/dbx/discussions",
icon: (
<svg width={24} height={24} viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
@@ -43,30 +43,26 @@ const channels = [
const i18n = {
en: {
- title: 'Community',
- desc: 'Join the DBX community — ask questions, share feedback, and connect with other users.',
- discord: { name: 'Discord', desc: 'Real-time chat, Q&A, and feature discussions.' },
- qq: { name: 'QQ Group', desc: 'Group number: 1087880322' },
- wechat: { name: 'WeChat Group', desc: 'Join via Tencent Docs invite link.' },
- github: { name: 'GitHub Discussions', desc: 'Bug reports, feature requests, and long-form discussions.' },
+ title: "Community",
+ desc: "Join the DBX community — ask questions, share feedback, and connect with other users.",
+ discord: { name: "Discord", desc: "Real-time chat, Q&A, and feature discussions." },
+ qq: { name: "QQ Group", desc: "Group number: 1087880322" },
+ wechat: { name: "WeChat Group", desc: "Join via Tencent Docs invite link." },
+ github: { name: "GitHub Discussions", desc: "Bug reports, feature requests, and long-form discussions." },
},
cn: {
- title: '交流群',
- desc: '加入 DBX 社区 — 提问、反馈、与其他用户交流。',
- discord: { name: 'Discord', desc: '实时聊天、问答和功能讨论。' },
- qq: { name: 'QQ 群', desc: '群号:1087880322' },
- wechat: { name: '微信群', desc: '通过腾讯文档链接加入。' },
- github: { name: 'GitHub Discussions', desc: 'Bug 反馈、功能建议和深度讨论。' },
+ title: "交流群",
+ desc: "加入 DBX 社区 — 提问、反馈、与其他用户交流。",
+ discord: { name: "Discord", desc: "实时聊天、问答和功能讨论。" },
+ qq: { name: "QQ 群", desc: "群号:1087880322" },
+ wechat: { name: "微信群", desc: "通过腾讯文档链接加入。" },
+ github: { name: "GitHub Discussions", desc: "Bug 反馈、功能建议和深度讨论。" },
},
};
-export async function generateMetadata({
- params,
-}: {
- params: Promise<{ lang: string }>;
-}): Promise<Metadata> {
+export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const t = i18n[l];
return buildMetadata({
@@ -79,7 +75,7 @@ export async function generateMetadata({
export default async function CommunityPage({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const t = i18n[l];
return (
@@ -96,34 +92,15 @@ export default async function CommunityPage({ params }: { params: Promise<{ lang
{channels.map((ch) => {
const meta = t[ch.id as keyof typeof t] as { name: string; desc: string };
return (
- <a
- key={ch.id}
- href={ch.href}
- target="_blank"
- rel="noopener noreferrer"
- className="group flex items-center gap-5 rounded-xl border border-landing-line bg-landing-panel px-6 py-5 transition-colors hover:border-[rgba(155,176,205,0.32)]"
- >
- <span
- className="grid place-items-center w-11 h-11 rounded-lg shrink-0"
- style={{ backgroundColor: `${ch.color}18`, color: ch.color }}
- >
+ <a key={ch.id} href={ch.href} target="_blank" rel="noopener noreferrer" className="group flex items-center gap-5 rounded-xl border border-landing-line bg-landing-panel px-6 py-5 transition-colors hover:border-[rgba(155,176,205,0.32)]">
+ <span className="grid place-items-center w-11 h-11 rounded-lg shrink-0" style={{ backgroundColor: `${ch.color}18`, color: ch.color }}>
{ch.icon}
</span>
<span className="grid gap-0.5 min-w-0">
<strong className="text-[15px] font-[700] leading-snug">{meta.name}</strong>
<span className="text-landing-muted text-[13px] leading-relaxed">{meta.desc}</span>
</span>
- <svg
- className="ml-auto shrink-0 text-landing-muted opacity-0 -translate-x-1 transition-all group-hover:opacity-100 group-hover:translate-x-0"
- width={16}
- height={16}
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- strokeLinecap="round"
- strokeLinejoin="round"
- >
+ <svg className="ml-auto shrink-0 text-landing-muted opacity-0 -translate-x-1 transition-all group-hover:opacity-100 group-hover:translate-x-0" width={16} height={16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
<path d="M5 12h14M12 5l7 7-7 7" />
</svg>
</a>
diff --git a/docs/app/[lang]/docs/[[...slug]]/page.tsx b/docs/app/[lang]/docs/[[...slug]]/page.tsx
index 4af45f99ec..671bdbed55 100644
--- a/docs/app/[lang]/docs/[[...slug]]/page.tsx
+++ b/docs/app/[lang]/docs/[[...slug]]/page.tsx
@@ -1,28 +1,19 @@
-import { source } from '@/lib/source';
-import { notFound } from 'next/navigation';
-import type { Metadata } from 'next';
-import {
- DocsPage,
- DocsBody,
- DocsTitle,
- DocsDescription,
-} from 'fumadocs-ui/page';
-import defaultMdxComponents from 'fumadocs-ui/mdx';
-import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
-import { Step, Steps } from 'fumadocs-ui/components/steps';
-import { Callout } from 'fumadocs-ui/components/callout';
-import { Card, Cards } from 'fumadocs-ui/components/card';
-import { ImageZoom } from 'fumadocs-ui/components/image-zoom';
-import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
-import type { MDXContent } from 'mdx/types';
-import type { TOCItemType } from 'fumadocs-core/toc';
-import { buildMetadata, SITE_URL } from '@/lib/metadata';
+import { source } from "@/lib/source";
+import { notFound } from "next/navigation";
+import type { Metadata } from "next";
+import { DocsPage, DocsBody, DocsTitle, DocsDescription } from "fumadocs-ui/page";
+import defaultMdxComponents from "fumadocs-ui/mdx";
+import { Tab, Tabs } from "fumadocs-ui/components/tabs";
+import { Step, Steps } from "fumadocs-ui/components/steps";
+import { Callout } from "fumadocs-ui/components/callout";
+import { Card, Cards } from "fumadocs-ui/components/card";
+import { ImageZoom } from "fumadocs-ui/components/image-zoom";
+import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
+import type { MDXContent } from "mdx/types";
+import type { TOCItemType } from "fumadocs-core/toc";
+import { buildMetadata, SITE_URL } from "@/lib/metadata";
-export async function generateMetadata({
- params,
-}: {
- params: Promise<{ lang: string; slug?: string[] }>;
-}): Promise<Metadata> {
+export async function generateMetadata({ params }: { params: Promise<{ lang: string; slug?: string[] }> }): Promise<Metadata> {
const { lang, slug } = await params;
const page = source.getPage(slug, lang);
if (!page) return {};
@@ -32,10 +23,10 @@ export async function generateMetadata({
return buildMetadata({
title,
- description: description ?? '',
- path: slug ? `/${lang}/docs/${slug.join('/')}` : `/${lang}/docs`,
+ description: description ?? "",
+ path: slug ? `/${lang}/docs/${slug.join("/")}` : `/${lang}/docs`,
lang,
- ogType: 'article',
+ ogType: "article",
});
}
@@ -53,11 +44,7 @@ const mdxComponents = {
Accordions,
};
-export default async function Page({
- params,
-}: {
- params: Promise<{ lang: string; slug?: string[] }>;
-}) {
+export default async function Page({ params }: { params: Promise<{ lang: string; slug?: string[] }> }) {
const { lang, slug } = await params;
const page = source.getPage(slug, lang);
if (!page) notFound();
@@ -68,48 +55,42 @@ export default async function Page({
};
const title = page.data.title as string;
- const description = (page.data.description as string) || '';
- const docPath = slug ? `/${lang}/docs/${slug.join('/')}` : `/${lang}/docs`;
+ const description = (page.data.description as string) || "";
+ const docPath = slug ? `/${lang}/docs/${slug.join("/")}` : `/${lang}/docs`;
const breadcrumbJsonLd = {
- '@context': 'https://schema.org',
- '@type': 'BreadcrumbList',
+ "@context": "https://schema.org",
+ "@type": "BreadcrumbList",
itemListElement: [
- { '@type': 'ListItem', position: 1, name: 'Home', item: SITE_URL },
- { '@type': 'ListItem', position: 2, name: 'Docs', item: `${SITE_URL}/${lang}/docs` },
+ { "@type": "ListItem", position: 1, name: "Home", item: SITE_URL },
+ { "@type": "ListItem", position: 2, name: "Docs", item: `${SITE_URL}/${lang}/docs` },
...(slug
? slug.map((segment, i) => ({
- '@type': 'ListItem' as const,
+ "@type": "ListItem" as const,
position: i + 3,
- name: segment.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
- item: `${SITE_URL}/${lang}/docs/${slug.slice(0, i + 1).join('/')}`,
+ name: segment.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
+ item: `${SITE_URL}/${lang}/docs/${slug.slice(0, i + 1).join("/")}`,
}))
: []),
],
};
const articleJsonLd = {
- '@context': 'https://schema.org',
- '@type': 'TechArticle',
+ "@context": "https://schema.org",
+ "@type": "TechArticle",
headline: title,
description,
- inLanguage: lang === 'cn' ? 'zh-CN' : 'en',
+ inLanguage: lang === "cn" ? "zh-CN" : "en",
isPartOf: {
- '@type': 'WebSite',
+ "@type": "WebSite",
url: SITE_URL,
},
};
return (
<DocsPage toc={toc}>
- <script
- type="application/ld+json"
- dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }}
- />
- <script
- type="application/ld+json"
- dangerouslySetInnerHTML={{ __html: JSON.stringify(articleJsonLd) }}
- />
+ <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }} />
+ <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(articleJsonLd) }} />
<DocsTitle>{title}</DocsTitle>
<DocsDescription>{description}</DocsDescription>
<DocsBody>
diff --git a/docs/app/[lang]/docs/layout.tsx b/docs/app/[lang]/docs/layout.tsx
index 5eb37ec573..82d1d13800 100644
--- a/docs/app/[lang]/docs/layout.tsx
+++ b/docs/app/[lang]/docs/layout.tsx
@@ -1,15 +1,9 @@
-import type { ReactNode } from 'react';
-import { DocsLayout } from 'fumadocs-ui/layouts/docs';
-import { DocsSidebarFooter, DocsSidebarLanguageButton } from '@/components/DocsSidebarFooter';
-import { source } from '@/lib/source';
+import type { ReactNode } from "react";
+import { DocsLayout } from "fumadocs-ui/layouts/docs";
+import { DocsSidebarFooter, DocsSidebarLanguageButton } from "@/components/DocsSidebarFooter";
+import { source } from "@/lib/source";
-export default async function Layout({
- params,
- children,
-}: {
- params: Promise<{ lang: string }>;
- children: ReactNode;
-}) {
+export default async function Layout({ params, children }: { params: Promise<{ lang: string }>; children: ReactNode }) {
const { lang } = await params;
return (
diff --git a/docs/app/[lang]/drivers/DriversClient.tsx b/docs/app/[lang]/drivers/DriversClient.tsx
index 95fb74088c..1149aeb5e9 100644
--- a/docs/app/[lang]/drivers/DriversClient.tsx
+++ b/docs/app/[lang]/drivers/DriversClient.tsx
@@ -3,26 +3,17 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { LandingNav } from "@/components/landing/LandingNav";
-import {
- buildDriverEntries,
- buildJreEntries,
- fetchAgentRegistry,
- formatSize,
- type AgentRegistry,
- type JreDisplayEntry,
-} from "@/lib/agentRegistry";
+import { buildDriverEntries, buildJreEntries, fetchAgentRegistry, formatSize, type AgentRegistry, type JreDisplayEntry } from "@/lib/agentRegistry";
import { AlertTriangle, Cpu, Database, Download, Loader2, Search, X } from "lucide-react";
const i18n = {
en: {
title: "Offline Driver Downloads",
- subtitle:
- "Download database drivers and JRE packages for offline use. Search for the exact resource your air-gapped environment needs.",
+ subtitle: "Download database drivers and JRE packages for offline use. Search for the exact resource your air-gapped environment needs.",
drivers: "Database Drivers",
driversDesc: "JDBC driver JAR files for each supported database type.",
jre: "Java Runtime (JRE)",
- jreDesc:
- "JRE packages used by agent-based database drivers. Required for Oracle, SQL Server, and other agent-managed connections.",
+ jreDesc: "JRE packages used by agent-based database drivers. Required for Oracle, SQL Server, and other agent-managed connections.",
loading: "Loading driver catalog...",
error: "Unable to load driver catalog. Please check your network connection.",
retry: "Retry",
@@ -36,8 +27,7 @@ const i18n = {
showing: "Showing",
of: "of",
clearSearch: "Clear search",
- downloadHint:
- "For air-gapped environments: download these files on an internet-connected machine, then transfer them to the offline machine and import them in DBX from Settings > Driver Manager.",
+ downloadHint: "For air-gapped environments: download these files on an internet-connected machine, then transfer them to the offline machine and import them in DBX from Settings > Driver Manager.",
},
cn: {
title: "离线驱动下载",
@@ -111,24 +101,9 @@ export function DriversClient() {
const jres = useMemo(() => (registry ? buildJreEntries(registry) : []), [registry]);
const normalizedSearch = searchQuery.trim().toLowerCase();
- const filteredDrivers = useMemo(
- () =>
- drivers.filter((d) =>
- matchesSearch([d.label, d.key, d.version, d.jre, formatSize(d.jar.size)], normalizedSearch),
- ),
- [drivers, normalizedSearch],
- );
+ const filteredDrivers = useMemo(() => drivers.filter((d) => matchesSearch([d.label, d.key, d.version, d.jre, formatSize(d.jar.size)], normalizedSearch)), [drivers, normalizedSearch]);
- const filteredJres = useMemo(
- () =>
- jres.filter((j) =>
- matchesSearch(
- [j.platformLabel, j.platformKey, j.jreVersion, j.jreKey, formatSize(j.info.size)],
- normalizedSearch,
- ),
- ),
- [jres, normalizedSearch],
- );
+ const filteredJres = useMemo(() => jres.filter((j) => matchesSearch([j.platformLabel, j.platformKey, j.jreVersion, j.jreKey, formatSize(j.info.size)], normalizedSearch)), [jres, normalizedSearch]);
const activeCount = activeTab === "drivers" ? filteredDrivers.length : filteredJres.length;
const activeTotal = activeTab === "drivers" ? drivers.length : jres.length;
@@ -140,9 +115,7 @@ export function DriversClient() {
<section className="pt-[100px] pb-8 max-[760px]:pt-[80px] max-[760px]:pb-6">
<div className="max-w-[1180px] mx-auto px-7 max-[760px]:px-[18px]">
<div className="grid justify-items-center max-w-[900px] mx-auto text-center">
- <p className="min-w-0 mx-auto text-[15px] font-[460] leading-[1.7] text-landing-muted max-w-[760px] max-[760px]:text-[13px] max-[760px]:whitespace-normal max-[760px]:max-w-[300px]">
- {t.subtitle}
- </p>
+ <p className="min-w-0 mx-auto text-[15px] font-[460] leading-[1.7] text-landing-muted max-w-[760px] max-[760px]:text-[13px] max-[760px]:whitespace-normal max-[760px]:max-w-[300px]">{t.subtitle}</p>
</div>
</div>
</section>
@@ -159,11 +132,7 @@ export function DriversClient() {
<div className="flex flex-col items-center gap-4 py-20">
<AlertTriangle size={28} className="text-yellow-500" />
<span className="text-landing-muted text-sm">{t.error}</span>
- <button
- type="button"
- onClick={loadRegistry}
- className="landing-nav-link rounded-[7px] px-4 py-2 text-sm font-medium border border-landing-line"
- >
+ <button type="button" onClick={loadRegistry} className="landing-nav-link rounded-[7px] px-4 py-2 text-sm font-medium border border-landing-line">
{t.retry}
</button>
</div>
@@ -177,22 +146,12 @@ export function DriversClient() {
<button
type="button"
onClick={() => setActiveTab("drivers")}
- className={`inline-flex h-8 cursor-pointer items-center gap-2 rounded-[6px] px-3 text-xs font-[650] transition-colors ${
- activeTab === "drivers"
- ? "bg-landing-blue text-white"
- : "text-landing-muted hover:text-landing-ink"
- }`}
+ className={`inline-flex h-8 cursor-pointer items-center gap-2 rounded-[6px] px-3 text-xs font-[650] transition-colors ${activeTab === "drivers" ? "bg-landing-blue text-white" : "text-landing-muted hover:text-landing-ink"}`}
>
<Database size={14} />
{t.drivers}
</button>
- <button
- type="button"
- onClick={() => setActiveTab("jre")}
- className={`inline-flex h-8 cursor-pointer items-center gap-2 rounded-[6px] px-3 text-xs font-[650] transition-colors ${
- activeTab === "jre" ? "bg-landing-blue text-white" : "text-landing-muted hover:text-landing-ink"
- }`}
- >
+ <button type="button" onClick={() => setActiveTab("jre")} className={`inline-flex h-8 cursor-pointer items-center gap-2 rounded-[6px] px-3 text-xs font-[650] transition-colors ${activeTab === "jre" ? "bg-landing-blue text-white" : "text-landing-muted hover:text-landing-ink"}`}>
<Cpu size={14} />
{t.jre}
</button>
@@ -200,10 +159,7 @@ export function DriversClient() {
<div className="flex min-w-[280px] flex-1 items-center gap-3 max-[760px]:min-w-full">
<div className="relative min-w-0 flex-1">
- <Search
- size={15}
- className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-landing-muted"
- />
+ <Search size={15} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-landing-muted" />
<input
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
@@ -211,12 +167,7 @@ export function DriversClient() {
className="h-9 w-full rounded-[8px] border border-landing-line bg-black/10 pl-9 pr-9 text-sm text-landing-ink outline-none transition-colors placeholder:text-landing-muted focus:border-landing-blue"
/>
{searchQuery && (
- <button
- type="button"
- onClick={() => setSearchQuery("")}
- className="absolute right-2 top-1/2 grid h-6 w-6 -translate-y-1/2 cursor-pointer place-items-center rounded-[6px] text-landing-muted hover:bg-landing-soft hover:text-landing-ink"
- aria-label={t.clearSearch}
- >
+ <button type="button" onClick={() => setSearchQuery("")} className="absolute right-2 top-1/2 grid h-6 w-6 -translate-y-1/2 cursor-pointer place-items-center rounded-[6px] text-landing-muted hover:bg-landing-soft hover:text-landing-ink" aria-label={t.clearSearch}>
<X size={14} />
</button>
)}
@@ -229,9 +180,7 @@ export function DriversClient() {
{activeTab === "drivers" && (
<>
- <p className="border-b border-landing-line px-5 py-3 text-sm text-landing-muted whitespace-nowrap max-[760px]:whitespace-normal max-[760px]:px-4">
- {t.driversDesc}
- </p>
+ <p className="border-b border-landing-line px-5 py-3 text-sm text-landing-muted whitespace-nowrap max-[760px]:whitespace-normal max-[760px]:px-4">{t.driversDesc}</p>
<table className="w-full table-auto border-collapse text-sm max-[760px]:block">
<thead className="bg-landing-panel text-xs font-medium text-landing-muted max-[760px]:hidden">
<tr className="border-b border-landing-line">
@@ -245,34 +194,21 @@ export function DriversClient() {
</thead>
<tbody className="max-[760px]:block">
{filteredDrivers.map((d) => (
- <tr
- key={d.key}
- className="border-b border-landing-line transition-colors last:border-b-0 hover:bg-landing-panel max-[760px]:grid max-[760px]:grid-cols-[1fr_auto] max-[760px]:items-center max-[760px]:gap-3 max-[760px]:px-4"
- >
+ <tr key={d.key} className="border-b border-landing-line transition-colors last:border-b-0 hover:bg-landing-panel max-[760px]:grid max-[760px]:grid-cols-[1fr_auto] max-[760px]:items-center max-[760px]:gap-3 max-[760px]:px-4">
<td className="min-w-0 px-5 py-3 font-medium text-landing-ink max-[760px]:px-0">
<div className="flex min-w-0 items-center gap-2">
<span className="min-w-0 truncate">{d.label}</span>
- <span className="hidden shrink-0 rounded-[5px] border border-landing-blue/35 bg-landing-blue/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-sky max-[760px]:inline">
- {d.key}
- </span>
+ <span className="hidden shrink-0 rounded-[5px] border border-landing-blue/35 bg-landing-blue/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-sky max-[760px]:inline">{d.key}</span>
</div>
</td>
<td className="px-5 py-3 max-[760px]:hidden">
- <span className="inline-flex rounded-[5px] border border-landing-blue/35 bg-landing-blue/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-sky">
- {d.key}
- </span>
+ <span className="inline-flex rounded-[5px] border border-landing-blue/35 bg-landing-blue/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-sky">{d.key}</span>
</td>
<td className="px-5 py-3 text-xs text-landing-muted max-[760px]:hidden">{d.version}</td>
<td className="px-5 py-3 text-xs text-landing-muted max-[760px]:hidden">{d.jre}</td>
- <td className="px-5 py-3 text-right text-xs text-landing-muted max-[760px]:hidden">
- {formatSize(d.jar.size)}
- </td>
+ <td className="px-5 py-3 text-right text-xs text-landing-muted max-[760px]:hidden">{formatSize(d.jar.size)}</td>
<td className="px-5 py-3 text-right max-[760px]:px-0">
- <a
- href={d.jar.url}
- download
- className="landing-nav-link inline-flex h-8 items-center gap-1 whitespace-nowrap rounded-[6px] border border-landing-line px-2.5 text-xs font-medium transition-colors hover:border-landing-blue"
- >
+ <a href={d.jar.url} download className="landing-nav-link inline-flex h-8 items-center gap-1 whitespace-nowrap rounded-[6px] border border-landing-line px-2.5 text-xs font-medium transition-colors hover:border-landing-blue">
<Download size={13} />
{t.download}
</a>
@@ -281,17 +217,13 @@ export function DriversClient() {
))}
</tbody>
</table>
- {filteredDrivers.length === 0 && (
- <div className="px-5 py-12 text-center text-sm text-landing-muted">{t.noResults}</div>
- )}
+ {filteredDrivers.length === 0 && <div className="px-5 py-12 text-center text-sm text-landing-muted">{t.noResults}</div>}
</>
)}
{activeTab === "jre" && (
<>
- <p className="border-b border-landing-line px-5 py-3 text-sm text-landing-muted whitespace-nowrap max-[760px]:whitespace-normal max-[760px]:px-4">
- {t.jreDesc}
- </p>
+ <p className="border-b border-landing-line px-5 py-3 text-sm text-landing-muted whitespace-nowrap max-[760px]:whitespace-normal max-[760px]:px-4">{t.jreDesc}</p>
<table className="w-full table-auto border-collapse text-sm max-[760px]:block">
<thead className="bg-landing-panel text-xs font-medium text-landing-muted max-[760px]:hidden">
<tr className="border-b border-landing-line">
@@ -306,33 +238,20 @@ export function DriversClient() {
{filteredJres.map((j) => {
const key = platformKey(j);
return (
- <tr
- key={key}
- className="border-b border-landing-line transition-colors last:border-b-0 hover:bg-landing-panel max-[760px]:grid max-[760px]:grid-cols-[1fr_auto] max-[760px]:items-center max-[760px]:gap-3 max-[760px]:px-4"
- >
+ <tr key={key} className="border-b border-landing-line transition-colors last:border-b-0 hover:bg-landing-panel max-[760px]:grid max-[760px]:grid-cols-[1fr_auto] max-[760px]:items-center max-[760px]:gap-3 max-[760px]:px-4">
<td className="min-w-0 px-5 py-3 font-medium text-landing-ink max-[760px]:px-0">
<div className="flex min-w-0 items-center gap-2">
<span className="min-w-0 truncate">{j.platformLabel}</span>
- <span className="hidden shrink-0 rounded-[5px] border border-landing-green/35 bg-landing-green/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-green max-[760px]:inline">
- JRE {j.jreKey}
- </span>
+ <span className="hidden shrink-0 rounded-[5px] border border-landing-green/35 bg-landing-green/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-green max-[760px]:inline">JRE {j.jreKey}</span>
</div>
</td>
<td className="px-5 py-3 max-[760px]:hidden">
- <span className="inline-flex rounded-[5px] border border-landing-green/35 bg-landing-green/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-green">
- JRE {j.jreKey}
- </span>
+ <span className="inline-flex rounded-[5px] border border-landing-green/35 bg-landing-green/10 px-1.5 py-0.5 font-mono text-[11px] text-landing-green">JRE {j.jreKey}</span>
</td>
<td className="px-5 py-3 text-xs text-landing-muted max-[760px]:hidden">{j.jreVersion}</td>
- <td className="px-5 py-3 text-right text-xs text-landing-muted max-[760px]:hidden">
- {formatSize(j.info.size)}
- </td>
+ <td className="px-5 py-3 text-right text-xs text-landing-muted max-[760px]:hidden">{formatSize(j.info.size)}</td>
<td className="px-5 py-3 text-right max-[760px]:px-0">
- <a
- href={j.info.url}
- download
- className="landing-nav-link inline-flex h-8 items-center gap-1 whitespace-nowrap rounded-[6px] border border-landing-line px-2.5 text-xs font-medium transition-colors hover:border-landing-blue"
- >
+ <a href={j.info.url} download className="landing-nav-link inline-flex h-8 items-center gap-1 whitespace-nowrap rounded-[6px] border border-landing-line px-2.5 text-xs font-medium transition-colors hover:border-landing-blue">
<Download size={13} />
{t.download}
</a>
@@ -342,9 +261,7 @@ export function DriversClient() {
})}
</tbody>
</table>
- {filteredJres.length === 0 && (
- <div className="px-5 py-12 text-center text-sm text-landing-muted">{t.noResults}</div>
- )}
+ {filteredJres.length === 0 && <div className="px-5 py-12 text-center text-sm text-landing-muted">{t.noResults}</div>}
</>
)}
</div>
diff --git a/docs/app/[lang]/drivers/page.tsx b/docs/app/[lang]/drivers/page.tsx
index bcfa21b407..d1f24e8c4b 100644
--- a/docs/app/[lang]/drivers/page.tsx
+++ b/docs/app/[lang]/drivers/page.tsx
@@ -5,21 +5,15 @@ import type { Metadata } from "next";
const pageMeta = {
en: {
title: "Offline Driver Downloads",
- description:
- "Download all database drivers and JRE packages for offline use. Supports 30+ database types across macOS, Linux, and Windows.",
+ description: "Download all database drivers and JRE packages for offline use. Supports 30+ database types across macOS, Linux, and Windows.",
},
cn: {
title: "离线驱动下载",
- description:
- "下载所有数据库驱动和 JRE 离线包,支持 30+ 种数据库类型,覆盖 macOS、Linux、Windows 平台。",
+ description: "下载所有数据库驱动和 JRE 离线包,支持 30+ 种数据库类型,覆盖 macOS、Linux、Windows 平台。",
},
};
-export async function generateMetadata({
- params,
-}: {
- params: Promise<{ lang: string }>;
-}): Promise<Metadata> {
+export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
const { lang } = await params;
const l = lang === "cn" ? "cn" : "en";
const meta = pageMeta[l];
diff --git a/docs/app/[lang]/layout.tsx b/docs/app/[lang]/layout.tsx
index e735122ea3..3c54878bea 100644
--- a/docs/app/[lang]/layout.tsx
+++ b/docs/app/[lang]/layout.tsx
@@ -1,30 +1,26 @@
-import type { ReactNode } from 'react';
-import type { Metadata } from 'next';
-import { RootProvider } from 'fumadocs-ui/provider/next';
-import { StaticSearchDialog } from '@/components/StaticSearchDialog';
-import { i18nUI } from '@/lib/i18n';
-import { SITE_URL, SITE_NAME, DEFAULT_DESCRIPTION } from '@/lib/metadata';
+import type { ReactNode } from "react";
+import type { Metadata } from "next";
+import { RootProvider } from "fumadocs-ui/provider/next";
+import { StaticSearchDialog } from "@/components/StaticSearchDialog";
+import { i18nUI } from "@/lib/i18n";
+import { SITE_URL, SITE_NAME, DEFAULT_DESCRIPTION } from "@/lib/metadata";
const LOCALE_MAP: Record<string, { locale: string; title: string; description: string }> = {
en: {
- locale: 'en_US',
- title: 'DBX - 15 MB to manage 40+ databases',
+ locale: "en_US",
+ title: "DBX - 15 MB to manage 40+ databases",
description: DEFAULT_DESCRIPTION,
},
cn: {
- locale: 'zh_CN',
- title: 'DBX - 15MB,管理40+种数据库',
- description: '25+ 种数据库,仅 15 MB。支持桌面与 Docker 自托管,内置 AI 助手。',
+ locale: "zh_CN",
+ title: "DBX - 15MB,管理40+种数据库",
+ description: "25+ 种数据库,仅 15 MB。支持桌面与 Docker 自托管,内置 AI 助手。",
},
};
-export async function generateMetadata({
- params,
-}: {
- params: Promise<{ lang: string }>;
-}): Promise<Metadata> {
+export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const meta = LOCALE_MAP[l];
return {
@@ -43,19 +39,13 @@ export async function generateMetadata({
languages: {
en: `${SITE_URL}/en`,
zh: `${SITE_URL}/cn`,
- 'x-default': `${SITE_URL}/en`,
+ "x-default": `${SITE_URL}/en`,
},
},
};
}
-export default async function LangLayout({
- params,
- children,
-}: {
- params: Promise<{ lang: string }>;
- children: ReactNode;
-}) {
+export default async function LangLayout({ params, children }: { params: Promise<{ lang: string }>; children: ReactNode }) {
const { lang } = await params;
return (
@@ -64,7 +54,7 @@ export default async function LangLayout({
search={{
SearchDialog: StaticSearchDialog,
}}
- theme={{ defaultTheme: 'system', enableSystem: true }}
+ theme={{ defaultTheme: "system", enableSystem: true }}
>
{children}
</RootProvider>
@@ -72,5 +62,5 @@ export default async function LangLayout({
}
export function generateStaticParams() {
- return [{ lang: 'en' }, { lang: 'cn' }];
+ return [{ lang: "en" }, { lang: "cn" }];
}
diff --git a/docs/app/[lang]/page.tsx b/docs/app/[lang]/page.tsx
index b7ae19edef..0ef0628a77 100644
--- a/docs/app/[lang]/page.tsx
+++ b/docs/app/[lang]/page.tsx
@@ -1,31 +1,19 @@
-import Link from 'next/link';
-import type { Metadata } from 'next';
-import type { CSSProperties } from 'react';
-import { HeroProductStage } from '@/components/aceternity/HeroProductStage';
-import { InfiniteMovingCards } from '@/components/aceternity/InfiniteMovingCards';
-import { Spotlight } from '@/components/aceternity/Spotlight';
-import { LandingNav } from '@/components/landing/LandingNav';
-import { InstallTabs } from '@/components/landing/InstallTabs';
-import { LandingLatestUpdates } from '@/components/landing/LandingLatestUpdates';
-import { RevealSection } from '@/components/landing/RevealSection';
-import { getAppVersion } from '@/lib/appVersion';
-import { fetchChangelog } from '@/lib/changelog';
-import { fetchLatestReleaseInfo } from '@/lib/latestRelease';
-import {
- ArrowRight,
- Bot,
- Database,
- FileCode,
- GitCompare,
- Network,
- Search,
- Shield,
- Table,
- Terminal,
- Zap,
-} from 'lucide-react';
+import Link from "next/link";
+import type { Metadata } from "next";
+import type { CSSProperties } from "react";
+import { HeroProductStage } from "@/components/aceternity/HeroProductStage";
+import { InfiniteMovingCards } from "@/components/aceternity/InfiniteMovingCards";
+import { Spotlight } from "@/components/aceternity/Spotlight";
+import { LandingNav } from "@/components/landing/LandingNav";
+import { InstallTabs } from "@/components/landing/InstallTabs";
+import { LandingLatestUpdates } from "@/components/landing/LandingLatestUpdates";
+import { RevealSection } from "@/components/landing/RevealSection";
+import { getAppVersion } from "@/lib/appVersion";
+import { fetchChangelog } from "@/lib/changelog";
+import { fetchLatestReleaseInfo } from "@/lib/latestRelease";
+import { ArrowRight, Bot, Database, FileCode, GitCompare, Network, Search, Shield, Table, Terminal, Zap } from "lucide-react";
-const fallbackStarLabel = '1.3k+';
+const fallbackStarLabel = "1.3k+";
function formatStars(count: number) {
if (count >= 1000) {
@@ -37,15 +25,15 @@ function formatStars(count: number) {
async function getGitHubStarLabel() {
try {
- const response = await fetch('https://api.github.com/repos/t8y2/dbx', {
- headers: { Accept: 'application/vnd.github+json' },
+ const response = await fetch("https://api.github.com/repos/t8y2/dbx", {
+ headers: { Accept: "application/vnd.github+json" },
next: { revalidate: 60 * 60 * 6 },
});
if (!response.ok) return fallbackStarLabel;
const data = (await response.json()) as { stargazers_count?: number };
- return typeof data.stargazers_count === 'number' ? formatStars(data.stargazers_count) : fallbackStarLabel;
+ return typeof data.stargazers_count === "number" ? formatStars(data.stargazers_count) : fallbackStarLabel;
} catch {
return fallbackStarLabel;
}
@@ -54,341 +42,332 @@ async function getGitHubStarLabel() {
function metrics(starLabel: string) {
return {
en: [
- { value: '~15 MB', label: 'desktop installer' },
- { value: '40+', label: 'database engines' },
- { value: '2 modes', label: 'desktop and Docker' },
- { value: starLabel, label: 'GitHub stars, fully open-source' },
+ { value: "~15 MB", label: "desktop installer" },
+ { value: "40+", label: "database engines" },
+ { value: "2 modes", label: "desktop and Docker" },
+ { value: starLabel, label: "GitHub stars, fully open-source" },
],
cn: [
- { value: '~15 MB', label: '桌面安装包' },
- { value: '40+', label: '数据库引擎' },
- { value: '2 种模式', label: '桌面与 Docker' },
- { value: starLabel, label: 'GitHub Star,完全开源' },
+ { value: "~15 MB", label: "桌面安装包" },
+ { value: "40+", label: "数据库引擎" },
+ { value: "2 种模式", label: "桌面与 Docker" },
+ { value: starLabel, label: "GitHub Star,完全开源" },
],
};
}
const databaseSupport = [
- { name: 'MySQL', icon: '/icons/database/mysql.svg', tone: '#4479a1' },
- { name: 'PostgreSQL', icon: '/icons/database/postgres.svg', tone: '#4169e1' },
- { name: 'SQLite', icon: '/icons/database/sqlite.svg', tone: '#5aa6d6' },
- { name: 'Redis', icon: '/icons/database/redis.svg', tone: '#ff4438' },
- { name: 'DuckDB', icon: '/icons/database/duckdb.svg', tone: '#fff000' },
- { name: 'ClickHouse', icon: '/icons/database/clickhouse.svg', tone: '#ffcc01' },
- { name: 'SQL Server', icon: '/icons/database/sqlserver.svg', tone: '#9ca3af' },
- { name: 'MongoDB', icon: '/icons/database/mongodb.svg', tone: '#47a248' },
- { name: 'Oracle', icon: '/icons/database/oracle.svg', tone: '#f80000' },
- { name: 'Elasticsearch', icon: '/icons/database/elasticsearch.svg', tone: '#00bfb3' },
- { name: 'Doris', icon: '/icons/database/doris.svg', tone: '#5b7cfa' },
- { name: 'StarRocks', icon: '/icons/database/starrocks.svg', tone: '#6750ff' },
- { name: 'Redshift', icon: '/icons/database/redshift.svg', tone: '#8c4fff' },
- { name: 'Dameng', icon: '/icons/database/dm.svg', tone: '#3857ff' },
- { name: 'GaussDB', icon: '/icons/database/gaussdb.svg', tone: '#ff5a3d' },
- { name: 'JDBC', initials: 'JDBC', tone: '#6ea8ff' },
- { name: 'TiDB', icon: '/icons/database/tidb.svg', tone: '#e60012' },
- { name: 'OceanBase', icon: '/icons/database/oceanbase.svg', tone: '#2285ff' },
- { name: 'SelectDB', icon: '/icons/database/selectdb.svg', tone: '#22c1c3' },
- { name: 'TDengine', icon: '/icons/database/tdengine.svg', tone: '#2f6fff' },
- { name: 'openGauss', icon: '/icons/database/opengauss.svg', tone: '#1488c9' },
- { name: 'KingBase', icon: '/icons/database/kingbase.svg', tone: '#e1212d' },
- { name: 'HighGo', initials: 'HG', tone: '#005bac' },
- { name: 'CockroachDB', icon: '/icons/database/cockroachdb.svg', tone: '#6933ff' },
- { name: 'More', initials: '···', tone: '#6ea8ff' },
+ { name: "MySQL", icon: "/icons/database/mysql.svg", tone: "#4479a1" },
+ { name: "PostgreSQL", icon: "/icons/database/postgres.svg", tone: "#4169e1" },
+ { name: "SQLite", icon: "/icons/database/sqlite.svg", tone: "#5aa6d6" },
+ { name: "Redis", icon: "/icons/database/redis.svg", tone: "#ff4438" },
+ { name: "DuckDB", icon: "/icons/database/duckdb.svg", tone: "#fff000" },
+ { name: "ClickHouse", icon: "/icons/database/clickhouse.svg", tone: "#ffcc01" },
+ { name: "SQL Server", icon: "/icons/database/sqlserver.svg", tone: "#9ca3af" },
+ { name: "MongoDB", icon: "/icons/database/mongodb.svg", tone: "#47a248" },
+ { name: "Oracle", icon: "/icons/database/oracle.svg", tone: "#f80000" },
+ { name: "Elasticsearch", icon: "/icons/database/elasticsearch.svg", tone: "#00bfb3" },
+ { name: "Doris", icon: "/icons/database/doris.svg", tone: "#5b7cfa" },
+ { name: "StarRocks", icon: "/icons/database/starrocks.svg", tone: "#6750ff" },
+ { name: "Redshift", icon: "/icons/database/redshift.svg", tone: "#8c4fff" },
+ { name: "Dameng", icon: "/icons/database/dm.svg", tone: "#3857ff" },
+ { name: "GaussDB", icon: "/icons/database/gaussdb.svg", tone: "#ff5a3d" },
+ { name: "JDBC", initials: "JDBC", tone: "#6ea8ff" },
+ { name: "TiDB", icon: "/icons/database/tidb.svg", tone: "#e60012" },
+ { name: "OceanBase", icon: "/icons/database/oceanbase.svg", tone: "#2285ff" },
+ { name: "SelectDB", icon: "/icons/database/selectdb.svg", tone: "#22c1c3" },
+ { name: "TDengine", icon: "/icons/database/tdengine.svg", tone: "#2f6fff" },
+ { name: "openGauss", icon: "/icons/database/opengauss.svg", tone: "#1488c9" },
+ { name: "KingBase", icon: "/icons/database/kingbase.svg", tone: "#e1212d" },
+ { name: "HighGo", initials: "HG", tone: "#005bac" },
+ { name: "CockroachDB", icon: "/icons/database/cockroachdb.svg", tone: "#6933ff" },
+ { name: "More", initials: "···", tone: "#6ea8ff" },
];
const workflows = {
en: [
{
icon: Terminal,
- title: 'Write and run SQL',
- desc: 'A CodeMirror 6 editor with metadata-aware completion, formatting, history, and selected SQL execution.',
- href: '/en/docs/query-editor',
+ title: "Write and run SQL",
+ desc: "A CodeMirror 6 editor with metadata-aware completion, formatting, history, and selected SQL execution.",
+ href: "/en/docs/query-editor",
},
{
icon: Table,
- title: 'Browse and edit data',
- desc: 'Virtualized grids, inline editing, WHERE/ORDER BY controls, SQL preview, and export tools.',
- href: '/en/docs/data-grid',
+ title: "Browse and edit data",
+ desc: "Virtualized grids, inline editing, WHERE/ORDER BY controls, SQL preview, and export tools.",
+ href: "/en/docs/data-grid",
},
{
icon: Search,
- title: 'Explore schemas',
- desc: 'Navigate databases, schemas, tables, columns, indexes, foreign keys, and triggers from a focused sidebar.',
- href: '/en/docs/schema-browser',
+ title: "Explore schemas",
+ desc: "Navigate databases, schemas, tables, columns, indexes, foreign keys, and triggers from a focused sidebar.",
+ href: "/en/docs/schema-browser",
},
{
icon: GitCompare,
- title: 'Compare and migrate',
- desc: 'Schema diff, table import, database export, SQL file execution, and cross-engine data transfer.',
- href: '/en/docs/schema-diff',
+ title: "Compare and migrate",
+ desc: "Schema diff, table import, database export, SQL file execution, and cross-engine data transfer.",
+ href: "/en/docs/schema-diff",
},
],
cn: [
{
icon: Terminal,
- title: '编写与执行 SQL',
- desc: 'CodeMirror 6 编辑器,支持元数据补全、格式化、查询历史和选中 SQL 执行。',
- href: '/cn/docs/query-editor',
+ title: "编写与执行 SQL",
+ desc: "CodeMirror 6 编辑器,支持元数据补全、格式化、查询历史和选中 SQL 执行。",
+ href: "/cn/docs/query-editor",
},
{
icon: Table,
- title: '浏览与编辑数据',
- desc: '虚拟滚动表格、行内编辑、WHERE/ORDER BY 控制、SQL 预览和导出工具。',
- href: '/cn/docs/data-grid',
+ title: "浏览与编辑数据",
+ desc: "虚拟滚动表格、行内编辑、WHERE/ORDER BY 控制、SQL 预览和导出工具。",
+ href: "/cn/docs/data-grid",
},
{
icon: Search,
- title: '浏览数据库结构',
- desc: '在侧边栏中查看数据库、Schema、表、字段、索引、外键和触发器。',
- href: '/cn/docs/schema-browser',
+ title: "浏览数据库结构",
+ desc: "在侧边栏中查看数据库、Schema、表、字段、索引、外键和触发器。",
+ href: "/cn/docs/schema-browser",
},
{
icon: GitCompare,
- title: '对比与迁移',
- desc: 'Schema 对比、表导入、数据库导出、SQL 文件执行和跨引擎数据传输。',
- href: '/cn/docs/schema-diff',
+ title: "对比与迁移",
+ desc: "Schema 对比、表导入、数据库导出、SQL 文件执行和跨引擎数据传输。",
+ href: "/cn/docs/schema-diff",
},
],
};
const capabilities = {
en: [
- { icon: Database, label: 'Native Rust drivers, no JDBC runtime' },
- { icon: Shield, label: 'SSH tunnels, encrypted config export, destructive action guards' },
- { icon: Bot, label: 'AI assistant plus MCP server for Claude Code, Cursor, and agents' },
- { icon: Network, label: 'ER diagrams, schema diff, and field lineage for deeper analysis' },
- { icon: FileCode, label: 'CSV, Excel, SQL files, full exports, and cross-engine transfer' },
- { icon: Zap, label: 'Desktop app and self-hosted web deployment from the same project' },
+ { icon: Database, label: "Native Rust drivers, no JDBC runtime" },
+ { icon: Shield, label: "SSH tunnels, encrypted config export, destructive action guards" },
+ { icon: Bot, label: "AI assistant plus MCP server for Claude Code, Cursor, and agents" },
+ { icon: Network, label: "ER diagrams, schema diff, and field lineage for deeper analysis" },
+ { icon: FileCode, label: "CSV, Excel, SQL files, full exports, and cross-engine transfer" },
+ { icon: Zap, label: "Desktop app and self-hosted web deployment from the same project" },
],
cn: [
- { icon: Database, label: 'Rust 原生驱动,不依赖 JDBC 运行时' },
- { icon: Shield, label: 'SSH 隧道、加密配置导出、危险操作确认' },
- { icon: Bot, label: '内置 AI 助手,以及面向 Claude Code、Cursor 的 MCP Server' },
- { icon: Network, label: 'ER 图、Schema 对比、字段血缘,覆盖更深层分析场景' },
- { icon: FileCode, label: 'CSV、Excel、SQL 文件、完整导出和跨引擎传输' },
- { icon: Zap, label: '桌面应用与自托管 Web 部署来自同一个项目' },
+ { icon: Database, label: "Rust 原生驱动,不依赖 JDBC 运行时" },
+ { icon: Shield, label: "SSH 隧道、加密配置导出、危险操作确认" },
+ { icon: Bot, label: "内置 AI 助手,以及面向 Claude Code、Cursor 的 MCP Server" },
+ { icon: Network, label: "ER 图、Schema 对比、字段血缘,覆盖更深层分析场景" },
+ { icon: FileCode, label: "CSV、Excel、SQL 文件、完整导出和跨引擎传输" },
+ { icon: Zap, label: "桌面应用与自托管 Web 部署来自同一个项目" },
],
};
const testimonials = {
en: [
{
- name: '@cyano',
- role: 'PostgreSQL and Redis workflows',
- avatar: '/avatars/cyano.jpg',
- quote: 'DBX keeps query work, schema checks, and Redis inspection in one small app. It feels focused instead of overloaded.',
+ name: "@cyano",
+ role: "PostgreSQL and Redis workflows",
+ avatar: "/avatars/cyano.jpg",
+ quote: "DBX keeps query work, schema checks, and Redis inspection in one small app. It feels focused instead of overloaded.",
},
{
- name: '@vbvb',
- role: 'Daily reporting',
- avatar: '/avatars/vbvb.png',
- quote: 'The data grid and export flow are the parts I reach for every day. Filters, previews, and edits stay close to the data.',
+ name: "@vbvb",
+ role: "Daily reporting",
+ avatar: "/avatars/vbvb.png",
+ quote: "The data grid and export flow are the parts I reach for every day. Filters, previews, and edits stay close to the data.",
},
{
- name: '@ar414',
- role: 'Self-hosted tooling',
- avatar: '/avatars/ar414.jpg',
- quote: 'Desktop mode is light enough for local work, and Docker mode makes it easy to give the team browser access.',
+ name: "@ar414",
+ role: "Self-hosted tooling",
+ avatar: "/avatars/ar414.jpg",
+ quote: "Desktop mode is light enough for local work, and Docker mode makes it easy to give the team browser access.",
},
{
- name: '@ryan',
- role: 'Multi-database projects',
- avatar: '/avatars/ryan.jpg',
- quote: 'I can jump between SQLite, MySQL, MongoDB, and DuckDB without changing tools or waiting on a heavy runtime.',
+ name: "@ryan",
+ role: "Multi-database projects",
+ avatar: "/avatars/ryan.jpg",
+ quote: "I can jump between SQLite, MySQL, MongoDB, and DuckDB without changing tools or waiting on a heavy runtime.",
},
{
- name: '@acane',
- role: 'Schema review',
- avatar: '/avatars/acane.png',
- quote: 'Schema browsing, ER diagrams, and diff tools make reviews faster because the important context is already connected.',
+ name: "@acane",
+ role: "Schema review",
+ avatar: "/avatars/acane.png",
+ quote: "Schema browsing, ER diagrams, and diff tools make reviews faster because the important context is already connected.",
},
{
- name: '@ydwang',
- role: 'Agent workflows',
- avatar: '/avatars/ydwang.png',
- quote: 'The MCP server is a practical touch. It lets coding agents inspect database context without inventing another bridge.',
+ name: "@ydwang",
+ role: "Agent workflows",
+ avatar: "/avatars/ydwang.png",
+ quote: "The MCP server is a practical touch. It lets coding agents inspect database context without inventing another bridge.",
},
{
- name: '@guangguang',
- role: 'Schema navigation',
- avatar: '/avatars/guangguang.jpg',
- quote: 'Sidebar search and grouped objects make large schemas manageable. I can find what I need without scrolling through hundreds of tables.',
+ name: "@guangguang",
+ role: "Schema navigation",
+ avatar: "/avatars/guangguang.jpg",
+ quote: "Sidebar search and grouped objects make large schemas manageable. I can find what I need without scrolling through hundreds of tables.",
},
{
- name: '@xuyuan',
- role: 'SQL editing',
- avatar: '/avatars/xuyuan.jpg',
- quote: 'Code completion in the SQL editor picks up column names and table aliases automatically. It saves a lot of tab-switching to check schema.',
+ name: "@xuyuan",
+ role: "SQL editing",
+ avatar: "/avatars/xuyuan.jpg",
+ quote: "Code completion in the SQL editor picks up column names and table aliases automatically. It saves a lot of tab-switching to check schema.",
},
{
- name: '@itkui',
- role: 'Data export',
- avatar: '/avatars/itkui.jpg',
+ name: "@itkui",
+ role: "Data export",
+ avatar: "/avatars/itkui.jpg",
quote: "Export options cover CSV, Excel, and SQL inserts. For daily data pulls, the workflow is quick and doesn't need extra scripting.",
},
{
- name: '@mebiuw',
- role: 'Secure connections',
- avatar: '/avatars/mebiuw.jpg',
- quote: 'SSH tunnel setup is straightforward — fill in the fields and connect. No need to manage port forwarding manually in a terminal.',
+ name: "@mebiuw",
+ role: "Secure connections",
+ avatar: "/avatars/mebiuw.jpg",
+ quote: "SSH tunnel setup is straightforward — fill in the fields and connect. No need to manage port forwarding manually in a terminal.",
},
{
- name: '@patrickz',
- role: 'Database design',
- avatar: '/avatars/patrickz.jpg',
- quote: 'ER diagrams give a clear picture of table relationships. Useful during design reviews when the team needs a shared visual reference.',
+ name: "@patrickz",
+ role: "Database design",
+ avatar: "/avatars/patrickz.jpg",
+ quote: "ER diagrams give a clear picture of table relationships. Useful during design reviews when the team needs a shared visual reference.",
},
{
- name: '@yanxuecan',
- role: 'AI-assisted queries',
- avatar: '/avatars/yanxuecan.jpg',
- quote: 'The AI assistant helps draft queries from natural language. It handles routine JOINs and aggregations well enough to speed things up.',
+ name: "@yanxuecan",
+ role: "AI-assisted queries",
+ avatar: "/avatars/yanxuecan.jpg",
+ quote: "The AI assistant helps draft queries from natural language. It handles routine JOINs and aggregations well enough to speed things up.",
},
],
cn: [
{
- name: '不剪发的Tony老师',
- role: 'PostgreSQL 与 Redis 工作流',
- avatar: '/avatars/dongxuyang85.jpg',
- quote: 'DBX 把查询、结构检查和 Redis 查看放在一个轻量工具里,日常数据库工作不会被复杂界面打断。',
+ name: "不剪发的Tony老师",
+ role: "PostgreSQL 与 Redis 工作流",
+ avatar: "/avatars/dongxuyang85.jpg",
+ quote: "DBX 把查询、结构检查和 Redis 查看放在一个轻量工具里,日常数据库工作不会被复杂界面打断。",
},
{
- name: 'Husky明夋',
- role: '报表与数据核对',
- avatar: '/avatars/husky.jpg',
- quote: '数据表格、过滤、预览和导出都离数据很近,用起来像是为高频操作专门整理过。',
+ name: "Husky明夋",
+ role: "报表与数据核对",
+ avatar: "/avatars/husky.jpg",
+ quote: "数据表格、过滤、预览和导出都离数据很近,用起来像是为高频操作专门整理过。",
},
{
- name: '孙志岗',
- role: '团队自托管工具',
- avatar: '/avatars/sunzhigang.jpg',
- quote: '本地桌面版足够轻,自托管 Web 版又方便团队共用,同一个项目覆盖了两种场景。',
+ name: "孙志岗",
+ role: "团队自托管工具",
+ avatar: "/avatars/sunzhigang.jpg",
+ quote: "本地桌面版足够轻,自托管 Web 版又方便团队共用,同一个项目覆盖了两种场景。",
},
{
- name: 'zhufeng',
- role: '多数据库项目',
- avatar: '/avatars/zhufeng.jpg',
- quote: 'SQLite、MySQL、MongoDB、DuckDB 来回切换不用换工具,也不用拖着很重的运行时。',
+ name: "zhufeng",
+ role: "多数据库项目",
+ avatar: "/avatars/zhufeng.jpg",
+ quote: "SQLite、MySQL、MongoDB、DuckDB 来回切换不用换工具,也不用拖着很重的运行时。",
},
{
- name: '樱桃小财主',
- role: '结构审查',
- avatar: '/avatars/yingtao.jpg',
- quote: '结构浏览、ER 图和 Schema 对比放在一起,做 review 时上下文更完整。',
+ name: "樱桃小财主",
+ role: "结构审查",
+ avatar: "/avatars/yingtao.jpg",
+ quote: "结构浏览、ER 图和 Schema 对比放在一起,做 review 时上下文更完整。",
},
{
- name: 'momo',
- role: 'Agent 数据库上下文',
- avatar: '/avatars/momo.jpg',
- quote: 'MCP Server 很实用,能让编码 Agent 读取数据库上下文,不需要再额外搭桥。',
+ name: "momo",
+ role: "Agent 数据库上下文",
+ avatar: "/avatars/momo.jpg",
+ quote: "MCP Server 很实用,能让编码 Agent 读取数据库上下文,不需要再额外搭桥。",
},
{
- name: '逛逛GitHub',
- role: '结构导航',
- avatar: '/avatars/guangguang.jpg',
- quote: '侧边栏搜索和分组浏览让大型 Schema 也不会迷路,不用在几百张表里翻来翻去。',
+ name: "逛逛GitHub",
+ role: "结构导航",
+ avatar: "/avatars/guangguang.jpg",
+ quote: "侧边栏搜索和分组浏览让大型 Schema 也不会迷路,不用在几百张表里翻来翻去。",
},
{
- name: '序员先生',
- role: 'SQL 编辑',
- avatar: '/avatars/xuyuan.jpg',
- quote: 'SQL 编辑器的补全能自动识别列名和别名,不用反复切到结构面板去确认字段。',
+ name: "序员先生",
+ role: "SQL 编辑",
+ avatar: "/avatars/xuyuan.jpg",
+ quote: "SQL 编辑器的补全能自动识别列名和别名,不用反复切到结构面板去确认字段。",
},
{
- name: 'IT老魁',
- role: '数据导出',
- avatar: '/avatars/itkui.jpg',
- quote: '导出支持 CSV、Excel 和 INSERT 语句,日常取数据很快,不用再额外写脚本。',
+ name: "IT老魁",
+ role: "数据导出",
+ avatar: "/avatars/itkui.jpg",
+ quote: "导出支持 CSV、Excel 和 INSERT 语句,日常取数据很快,不用再额外写脚本。",
},
{
- name: 'MebiuW',
- role: '安全连接',
- avatar: '/avatars/mebiuw.jpg',
- quote: 'SSH 隧道设置很直接,填好参数就能连,不用在终端里手动转发端口。',
+ name: "MebiuW",
+ role: "安全连接",
+ avatar: "/avatars/mebiuw.jpg",
+ quote: "SSH 隧道设置很直接,填好参数就能连,不用在终端里手动转发端口。",
},
{
- name: 'Patrick Zhang',
- role: '数据库设计',
- avatar: '/avatars/patrickz.jpg',
- quote: 'ER 图把表关系展示得很清楚,团队做设计评审时有个共同的可视化参考。',
+ name: "Patrick Zhang",
+ role: "数据库设计",
+ avatar: "/avatars/patrickz.jpg",
+ quote: "ER 图把表关系展示得很清楚,团队做设计评审时有个共同的可视化参考。",
},
{
- name: '闫学灿',
- role: 'AI 辅助查询',
- avatar: '/avatars/yanxuecan.jpg',
- quote: 'AI 助手能从自然语言生成查询,常规的 JOIN 和聚合写得不错,省了不少手敲时间。',
+ name: "闫学灿",
+ role: "AI 辅助查询",
+ avatar: "/avatars/yanxuecan.jpg",
+ quote: "AI 助手能从自然语言生成查询,常规的 JOIN 和聚合写得不错,省了不少手敲时间。",
},
],
};
const i18nText = {
en: {
- heroTitle: '15 MB to manage 40+ databases!',
- heroSubtitle:
- 'DBX brings connections, SQL editing, data grids, schema tools, AI assistance, and self-hosted access into one lightweight product.',
- download: 'Download DBX',
- downloadName: 'Download DBX',
- readDocs: 'Read the docs',
- docsStart: 'Start here',
- docsStartDesc: 'Install DBX, create your first connection, and learn the main workflow.',
- workflowsTitle: 'Core workflows',
- workflowsDesc: 'The docs are organized around what you actually do in a database client.',
- supportTitle: 'Supports many databases',
- supportDesc:
- 'Connect and manage SQL, NoSQL, embedded databases, and MySQL/PostgreSQL-compatible engines without switching tools.',
- testimonialsTitle: 'What DBX is good at',
- testimonialsDesc: 'A closer look at the everyday database workflows DBX is built to make smoother.',
- capabilitiesTitle: 'Built for real database work',
- footerTitle: 'Ready to try DBX?',
- footerDesc: 'Use the desktop app for local work, or deploy the Docker version for browser-based access.',
- release: 'Latest release',
- docker: 'Docker setup',
+ heroTitle: "15 MB to manage 40+ databases!",
+ heroSubtitle: "DBX brings connections, SQL editing, data grids, schema tools, AI assistance, and self-hosted access into one lightweight product.",
+ download: "Download DBX",
+ downloadName: "Download DBX",
+ readDocs: "Read the docs",
+ docsStart: "Start here",
+ docsStartDesc: "Install DBX, create your first connection, and learn the main workflow.",
+ workflowsTitle: "Core workflows",
+ workflowsDesc: "The docs are organized around what you actually do in a database client.",
+ supportTitle: "Supports many databases",
+ supportDesc: "Connect and manage SQL, NoSQL, embedded databases, and MySQL/PostgreSQL-compatible engines without switching tools.",
+ testimonialsTitle: "What DBX is good at",
+ testimonialsDesc: "A closer look at the everyday database workflows DBX is built to make smoother.",
+ capabilitiesTitle: "Built for real database work",
+ footerTitle: "Ready to try DBX?",
+ footerDesc: "Use the desktop app for local work, or deploy the Docker version for browser-based access.",
+ release: "Latest release",
+ docker: "Docker setup",
},
cn: {
- heroTitle: '15MB,管理40+种数据库!',
- heroSubtitle: 'DBX 将连接管理、SQL 编辑、数据表格、结构工具、AI 助手和自托管访问放进一个轻量产品里。',
- download: '下载 DBX',
- downloadName: '下载 DBX',
- readDocs: '查看文档',
- docsStart: '从这里开始',
- docsStartDesc: '安装 DBX、创建第一个连接,并了解主要工作流。',
- workflowsTitle: '核心工作流',
- workflowsDesc: '文档围绕数据库客户端里的真实任务组织,而不是堆功能清单。',
- supportTitle: '支持多种数据库',
- supportDesc:
- '告别频繁切换工具的烦恼。DBX 可以连接和管理多种数据库类型,让你更专注于查询、分析和数据本身。',
- testimonialsTitle: 'DBX 适合什么样的工作',
- testimonialsDesc: '从连接管理、数据浏览到 AI 辅助,DBX 围绕高频数据库工作流打磨体验。',
- capabilitiesTitle: '面向真实数据库工作的能力',
- footerTitle: '准备试试 DBX?',
- footerDesc: '本地工作使用桌面版,需要浏览器访问时部署 Docker 版。',
- release: '最新版本',
- docker: 'Docker 部署',
+ heroTitle: "15MB,管理40+种数据库!",
+ heroSubtitle: "DBX 将连接管理、SQL 编辑、数据表格、结构工具、AI 助手和自托管访问放进一个轻量产品里。",
+ download: "下载 DBX",
+ downloadName: "下载 DBX",
+ readDocs: "查看文档",
+ docsStart: "从这里开始",
+ docsStartDesc: "安装 DBX、创建第一个连接,并了解主要工作流。",
+ workflowsTitle: "核心工作流",
+ workflowsDesc: "文档围绕数据库客户端里的真实任务组织,而不是堆功能清单。",
+ supportTitle: "支持多种数据库",
+ supportDesc: "告别频繁切换工具的烦恼。DBX 可以连接和管理多种数据库类型,让你更专注于查询、分析和数据本身。",
+ testimonialsTitle: "DBX 适合什么样的工作",
+ testimonialsDesc: "从连接管理、数据浏览到 AI 辅助,DBX 围绕高频数据库工作流打磨体验。",
+ capabilitiesTitle: "面向真实数据库工作的能力",
+ footerTitle: "准备试试 DBX?",
+ footerDesc: "本地工作使用桌面版,需要浏览器访问时部署 Docker 版。",
+ release: "最新版本",
+ docker: "Docker 部署",
},
};
-import { buildMetadata } from '@/lib/metadata';
+import { buildMetadata } from "@/lib/metadata";
const landingMeta = {
en: {
- title: 'DBX - 15 MB to manage 40+ databases!',
- description:
- 'DBX brings connections, SQL editing, data grids, schema tools, AI assistance, and self-hosted access into one lightweight product.',
+ title: "DBX - 15 MB to manage 40+ databases!",
+ description: "DBX brings connections, SQL editing, data grids, schema tools, AI assistance, and self-hosted access into one lightweight product.",
},
cn: {
- title: 'DBX - 15MB,管理40+种数据库!',
- description:
- 'DBX 将连接管理、SQL 编辑、数据表格、结构工具、AI 助手和自托管访问放进一个轻量产品里。',
+ title: "DBX - 15MB,管理40+种数据库!",
+ description: "DBX 将连接管理、SQL 编辑、数据表格、结构工具、AI 助手和自托管访问放进一个轻量产品里。",
},
};
-export async function generateMetadata({
- params,
-}: {
- params: Promise<{ lang: string }>;
-}): Promise<Metadata> {
+export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const meta = landingMeta[l];
return buildMetadata({
@@ -396,17 +375,13 @@ export async function generateMetadata({
description: meta.description,
path: `/${l}`,
lang: l,
- ogType: 'website',
+ ogType: "website",
});
}
-export default async function LandingPage({
- params,
-}: {
- params: Promise<{ lang: string }>;
-}) {
+export default async function LandingPage({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params;
- const l = lang === 'cn' ? 'cn' : 'en';
+ const l = lang === "cn" ? "cn" : "en";
const t = i18nText[l];
const workflowItems = workflows[l];
const capabilityItems = capabilities[l];
@@ -427,12 +402,8 @@ export default async function LandingPage({
<Spotlight />
<div className="relative z-[1] max-w-[1180px] mx-auto px-7 max-[1040px]:max-w-[920px] max-[760px]:px-[18px]">
<div className="landing-hero-copy relative z-[6] grid justify-items-center max-w-[900px] mx-auto text-center max-[1040px]:max-w-[760px]">
- <h1 className="min-w-0 m-0 text-[clamp(36px,4.2vw,56px)] font-[820] leading-[1.06] text-landing-ink whitespace-nowrap max-[760px]:text-[clamp(26px,7vw,38px)]">
- {t.heroTitle}
- </h1>
- <p className="landing-hero-subtitle min-w-0 mt-5 mx-auto text-[17px] font-[460] leading-[1.8] whitespace-nowrap max-[760px]:text-[15px] max-[760px]:leading-[1.68] max-[760px]:whitespace-normal max-[760px]:max-w-[320px]">
- {t.heroSubtitle}
- </p>
+ <h1 className="min-w-0 m-0 text-[clamp(36px,4.2vw,56px)] font-[820] leading-[1.06] text-landing-ink whitespace-nowrap max-[760px]:text-[clamp(26px,7vw,38px)]">{t.heroTitle}</h1>
+ <p className="landing-hero-subtitle min-w-0 mt-5 mx-auto text-[17px] font-[460] leading-[1.8] whitespace-nowrap max-[760px]:text-[15px] max-[760px]:leading-[1.68] max-[760px]:whitespace-normal max-[760px]:max-w-[320px]">{t.heroSubtitle}</p>
<div className="w-full max-w-[520px] mt-10">
<InstallTabs lang={l} version={initialDownloadVersion} />
</div>
@@ -474,7 +445,7 @@ export default async function LandingPage({
<Link
key={item.title}
href={item.href}
- className={`landing-workflow-card min-h-[250px] p-6 border-r border-r-landing-line max-[760px]:min-h-0 max-[760px]:border-r-0 max-[760px]:border-b max-[760px]:border-b-landing-line max-[760px]:last:border-b-0 ${i === workflowItems.length - 1 ? 'border-r-0' : ''}`}
+ className={`landing-workflow-card min-h-[250px] p-6 border-r border-r-landing-line max-[760px]:min-h-0 max-[760px]:border-r-0 max-[760px]:border-b max-[760px]:border-b-landing-line max-[760px]:last:border-b-0 ${i === workflowItems.length - 1 ? "border-r-0" : ""}`}
target="_blank"
data-stagger
>
@@ -498,7 +469,7 @@ export default async function LandingPage({
</div>
<div className="grid grid-cols-8 gap-3 max-[760px]:grid-cols-2 max-[760px]:gap-2.5 max-[760px]:mt-[18px]">
{databaseSupport.map((db) => (
- <div className="landing-db-card grid place-items-center min-h-[126px] rounded-[10px] px-2.5 py-[18px] max-[760px]:min-h-[122px] max-[760px]:py-4" key={db.name} style={{ '--db-tone': db.tone } as CSSProperties} data-stagger>
+ <div className="landing-db-card grid place-items-center min-h-[126px] rounded-[10px] px-2.5 py-[18px] max-[760px]:min-h-[122px] max-[760px]:py-4" key={db.name} style={{ "--db-tone": db.tone } as CSSProperties} data-stagger>
<div className="landing-db-icon grid place-items-center w-12 h-12 mb-[15px]">
{db.icon ? <img src={db.icon} alt="" width={38} height={38} className="block w-[38px] h-[38px] object-contain" /> : <span className="grid place-items-center min-w-[46px] h-8 rounded-lg px-2 text-white text-xs font-[780]">{db.initials}</span>}
</div>
diff --git a/docs/app/global.css b/docs/app/global.css
index e470f6dbe4..b5203e517d 100644
--- a/docs/app/global.css
+++ b/docs/app/global.css
@@ -1,6 +1,6 @@
-@import 'tailwindcss';
-@import 'fumadocs-ui/css/ocean.css';
-@import 'fumadocs-ui/css/preset.css';
+@import "tailwindcss";
+@import "fumadocs-ui/css/ocean.css";
+@import "fumadocs-ui/css/preset.css";
@theme {
--color-landing-ink: #f7fbff;
@@ -201,7 +201,7 @@ article figure.shiki {
box-shadow: 0 12px 28px color-mix(in srgb, black 12%, transparent);
}
-article figure.shiki [role='region'] {
+article figure.shiki [role="region"] {
padding-top: 0.7rem;
padding-bottom: 0.7rem;
}
@@ -243,7 +243,7 @@ article a.flex.rounded-lg:hover {
box-shadow: 0 10px 28px color-mix(in srgb, black 7%, transparent);
}
-article [role='tablist'].not-prose {
+article [role="tablist"].not-prose {
border: 0;
border-bottom: 1px solid var(--dbx-line);
border-radius: 0;
@@ -251,26 +251,26 @@ article [role='tablist'].not-prose {
padding: 0 1rem;
}
-article [role='tablist'].not-prose [role='tab'] {
+article [role="tablist"].not-prose [role="tab"] {
border-radius: 0;
font-weight: 620;
}
-article [role='tablist'].not-prose [role='tab'][data-state='active'] {
+article [role="tablist"].not-prose [role="tab"][data-state="active"] {
background: transparent;
box-shadow: none;
}
-article [role='tabpanel'] {
+article [role="tabpanel"] {
border-color: var(--dbx-line);
}
-article div[class*='border'] {
+article div[class*="border"] {
border-color: var(--dbx-line);
}
-aside a[href*='/docs/'][class*='rounded-lg'][data-active='true'],
-aside a[href*='/docs/'][class*='rounded-lg'][aria-current='page'] {
+aside a[href*="/docs/"][class*="rounded-lg"][data-active="true"],
+aside a[href*="/docs/"][class*="rounded-lg"][aria-current="page"] {
background: color-mix(in srgb, var(--color-fd-primary) 5%, var(--color-fd-accent));
color: var(--color-fd-primary);
font-weight: 650;
@@ -305,20 +305,20 @@ aside a[href*='/docs/'][class*='rounded-lg'][aria-current='page'] {
box-shadow: 0 1px 2px color-mix(in srgb, black 5%, transparent);
}
-.dbx-docs-theme-switch [class*='size-6.5'] {
+.dbx-docs-theme-switch [class*="size-6.5"] {
width: 1.55rem;
height: 1.55rem;
padding: 0.33rem;
}
-.dbx-docs-theme-switch [class*='bg-fd-accent'] {
+.dbx-docs-theme-switch [class*="bg-fd-accent"] {
background: var(--color-fd-popover);
box-shadow:
0 1px 2px color-mix(in srgb, black 8%, transparent),
0 0 0 1px color-mix(in srgb, var(--color-fd-border) 64%, transparent);
}
-.dark .dbx-docs-theme-switch [class*='bg-fd-accent'] {
+.dark .dbx-docs-theme-switch [class*="bg-fd-accent"] {
background: color-mix(in srgb, var(--color-fd-accent) 72%, var(--color-fd-popover));
}
@@ -327,7 +327,6 @@ a {
-webkit-tap-highlight-color: transparent;
}
-
.landing {
--landing-max: 1180px;
min-height: 100vh;
@@ -338,7 +337,7 @@ a {
}
.landing::after {
- content: '';
+ content: "";
position: fixed;
inset: 0;
z-index: 0;
@@ -382,13 +381,27 @@ a {
transform: translateY(0);
}
-.landing-reveal.is-visible [data-stagger]:nth-child(2) { transition-delay: 70ms; }
-.landing-reveal.is-visible [data-stagger]:nth-child(3) { transition-delay: 120ms; }
-.landing-reveal.is-visible [data-stagger]:nth-child(4) { transition-delay: 170ms; }
-.landing-reveal.is-visible [data-stagger]:nth-child(8n+5) { transition-delay: 210ms; }
-.landing-reveal.is-visible [data-stagger]:nth-child(8n+6) { transition-delay: 250ms; }
-.landing-reveal.is-visible [data-stagger]:nth-child(8n+7) { transition-delay: 290ms; }
-.landing-reveal.is-visible [data-stagger]:nth-child(8n) { transition-delay: 330ms; }
+.landing-reveal.is-visible [data-stagger]:nth-child(2) {
+ transition-delay: 70ms;
+}
+.landing-reveal.is-visible [data-stagger]:nth-child(3) {
+ transition-delay: 120ms;
+}
+.landing-reveal.is-visible [data-stagger]:nth-child(4) {
+ transition-delay: 170ms;
+}
+.landing-reveal.is-visible [data-stagger]:nth-child(8n + 5) {
+ transition-delay: 210ms;
+}
+.landing-reveal.is-visible [data-stagger]:nth-child(8n + 6) {
+ transition-delay: 250ms;
+}
+.landing-reveal.is-visible [data-stagger]:nth-child(8n + 7) {
+ transition-delay: 290ms;
+}
+.landing-reveal.is-visible [data-stagger]:nth-child(8n) {
+ transition-delay: 330ms;
+}
/* Nav */
@@ -406,7 +419,7 @@ a {
}
.landing-nav::before {
- content: '';
+ content: "";
position: absolute;
inset: 0;
backdrop-filter: blur(18px);
@@ -448,24 +461,20 @@ a {
}
.landing-hero::before {
- content: '';
+ content: "";
position: absolute;
inset: 0;
background:
- radial-gradient(ellipse at 50% 34%, rgba(44, 88, 174, 0.48), transparent 52%),
- radial-gradient(ellipse at 18% 16%, rgba(82, 213, 255, 0.13), transparent 34%),
- radial-gradient(ellipse at 76% 22%, rgba(68, 209, 157, 0.1), transparent 30%),
+ radial-gradient(ellipse at 50% 34%, rgba(44, 88, 174, 0.48), transparent 52%), radial-gradient(ellipse at 18% 16%, rgba(82, 213, 255, 0.13), transparent 34%), radial-gradient(ellipse at 76% 22%, rgba(68, 209, 157, 0.1), transparent 30%),
linear-gradient(180deg, #0b1120 0%, #0c1528 48%, #0b1120 82%, #0b1120 100%);
z-index: -3;
}
.landing-hero::after {
- content: '';
+ content: "";
position: absolute;
inset: 134px -12vw -140px;
- background-image:
- linear-gradient(rgba(110, 168, 255, 0.08) 1px, transparent 1px),
- linear-gradient(90deg, rgba(110, 168, 255, 0.08) 1px, transparent 1px);
+ background-image: linear-gradient(rgba(110, 168, 255, 0.08) 1px, transparent 1px), linear-gradient(90deg, rgba(110, 168, 255, 0.08) 1px, transparent 1px);
background-size: 58px 58px;
mask-image: radial-gradient(ellipse at 50% 56%, black 0%, transparent 64%);
opacity: 0.5;
@@ -482,10 +491,7 @@ a {
width: min(980px, 82vw);
height: 720px;
border-radius: 999px;
- background:
- radial-gradient(circle at 50% 28%, rgba(255, 255, 255, 0.16), transparent 12%),
- radial-gradient(circle at 46% 38%, rgba(82, 213, 255, 0.2), transparent 34%),
- radial-gradient(circle at 58% 52%, rgba(110, 168, 255, 0.16), transparent 60%);
+ background: radial-gradient(circle at 50% 28%, rgba(255, 255, 255, 0.16), transparent 12%), radial-gradient(circle at 46% 38%, rgba(82, 213, 255, 0.2), transparent 34%), radial-gradient(circle at 58% 52%, rgba(110, 168, 255, 0.16), transparent 60%);
filter: blur(52px);
mix-blend-mode: screen;
pointer-events: none;
@@ -551,7 +557,7 @@ a {
/* Install dropdown */
.landing-install::after {
- content: '';
+ content: "";
position: absolute;
top: 100%;
left: 0;
@@ -561,9 +567,7 @@ a {
}
.landing-install-trigger {
- background:
- linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(239, 244, 250, 0.96)),
- #fff;
+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(239, 244, 250, 0.96)), #fff;
color: #070b12;
box-shadow:
0 18px 54px rgba(0, 0, 0, 0.24),
@@ -572,7 +576,7 @@ a {
}
.landing-install-trigger:hover,
-.landing-install[data-open='true'] .landing-install-trigger {
+.landing-install[data-open="true"] .landing-install-trigger {
box-shadow:
0 24px 68px rgba(0, 0, 0, 0.3),
0 0 0 1px rgba(255, 255, 255, 0.78) inset;
@@ -588,7 +592,7 @@ a {
transition: transform 0.16s ease;
}
-.landing-install[data-open='true'] .landing-install-trigger > svg:last-child {
+.landing-install[data-open="true"] .landing-install-trigger > svg:last-child {
transform: rotate(180deg);
}
@@ -608,7 +612,7 @@ a {
}
.landing-install:hover .landing-install-menu,
-.landing-install[data-open='true'] .landing-install-menu {
+.landing-install[data-open="true"] .landing-install-menu {
opacity: 1;
pointer-events: auto;
visibility: visible;
@@ -647,20 +651,12 @@ a {
}
.landing-product::before {
- content: '';
+ content: "";
position: absolute;
inset: 0;
border-radius: inherit;
padding: 1px;
- background: conic-gradient(
- from 180deg,
- transparent,
- rgba(110, 168, 255, 0.04),
- rgba(82, 213, 255, 0.28),
- rgba(68, 209, 157, 0.18),
- rgba(110, 168, 255, 0.04),
- transparent
- );
+ background: conic-gradient(from 180deg, transparent, rgba(110, 168, 255, 0.04), rgba(82, 213, 255, 0.28), rgba(68, 209, 157, 0.18), rgba(110, 168, 255, 0.04), transparent);
-webkit-mask:
linear-gradient(#000 0 0) content-box,
linear-gradient(#000 0 0);
@@ -671,7 +667,7 @@ a {
}
.landing-product::after {
- content: '';
+ content: "";
position: absolute;
inset: 34px 0 0;
background: radial-gradient(circle at 72% 18%, rgba(82, 213, 255, 0.1), transparent 18%);
@@ -692,7 +688,7 @@ a {
transition: opacity 0.45s ease;
}
-.landing-product-slide[data-active='true'] {
+.landing-product-slide[data-active="true"] {
opacity: 1;
}
@@ -711,7 +707,7 @@ a {
opacity 0.2s ease;
}
-.landing-product-dots button[aria-current='true'] {
+.landing-product-dots button[aria-current="true"] {
width: 28px;
background: color-mix(in srgb, var(--color-landing-sky) 84%, white);
}
@@ -729,10 +725,7 @@ a {
.landing-glass-card {
border: 1px solid rgba(155, 176, 205, 0.14);
- background:
- radial-gradient(circle at 78% 12%, rgba(110, 168, 255, 0.12), transparent 44%),
- linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)),
- rgba(12, 15, 22, 0.72);
+ background: radial-gradient(circle at 78% 12%, rgba(110, 168, 255, 0.12), transparent 44%), linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)), rgba(12, 15, 22, 0.72);
box-shadow:
0 18px 44px rgba(0, 0, 0, 0.14),
0 0 0 1px rgba(255, 255, 255, 0.02) inset;
@@ -740,10 +733,7 @@ a {
.landing-glass-card-green {
border: 1px solid rgba(155, 176, 205, 0.14);
- background:
- radial-gradient(circle at 78% 16%, rgba(68, 209, 157, 0.1), transparent 34%),
- linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)),
- rgba(12, 15, 22, 0.72);
+ background: radial-gradient(circle at 78% 16%, rgba(68, 209, 157, 0.1), transparent 34%), linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)), rgba(12, 15, 22, 0.72);
box-shadow:
0 18px 44px rgba(0, 0, 0, 0.14),
0 0 0 1px rgba(255, 255, 255, 0.02) inset;
@@ -798,10 +788,7 @@ a {
.landing-db-card {
border: 1px solid rgba(155, 176, 205, 0.14);
- background:
- radial-gradient(circle at 50% 112%, color-mix(in srgb, var(--db-tone) 20%, transparent), transparent 62%),
- linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)),
- rgba(12, 15, 22, 0.74);
+ background: radial-gradient(circle at 50% 112%, color-mix(in srgb, var(--db-tone) 20%, transparent), transparent 62%), linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)), rgba(12, 15, 22, 0.74);
box-shadow:
0 18px 44px rgba(0, 0, 0, 0.15),
0 0 0 1px rgba(255, 255, 255, 0.02) inset;
@@ -813,10 +800,7 @@ a {
.landing-db-card:hover {
border-color: color-mix(in srgb, var(--db-tone) 42%, rgba(155, 176, 205, 0.18));
- background:
- radial-gradient(circle at 50% 112%, color-mix(in srgb, var(--db-tone) 26%, transparent), transparent 62%),
- linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.024)),
- rgba(14, 18, 27, 0.9);
+ background: radial-gradient(circle at 50% 112%, color-mix(in srgb, var(--db-tone) 26%, transparent), transparent 62%), linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.024)), rgba(14, 18, 27, 0.9);
transform: translateY(-3px);
}
@@ -833,7 +817,7 @@ a {
.landing-testimonial-wall::before,
.landing-testimonial-wall::after {
- content: '';
+ content: "";
position: absolute;
top: 0;
bottom: 0;
@@ -852,11 +836,11 @@ a {
background: linear-gradient(270deg, #10151d, rgba(16, 21, 29, 0));
}
-.landing-testimonial-marquee[data-speed='slow'] {
+.landing-testimonial-marquee[data-speed="slow"] {
--testimonial-duration: 58s;
}
-.landing-testimonial-marquee[data-speed='normal'] {
+.landing-testimonial-marquee[data-speed="normal"] {
--testimonial-duration: 42s;
}
@@ -865,15 +849,13 @@ a {
animation-play-state: running !important;
}
-.landing-testimonial-marquee[data-direction='right'] .landing-testimonial-track {
+.landing-testimonial-marquee[data-direction="right"] .landing-testimonial-track {
animation-direction: reverse;
}
.landing-testimonial-card {
border: 1px solid rgba(155, 176, 205, 0.14);
- background:
- linear-gradient(180deg, rgba(255, 255, 255, 0.055), rgba(255, 255, 255, 0.025)),
- rgba(13, 18, 26, 0.78);
+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.055), rgba(255, 255, 255, 0.025)), rgba(13, 18, 26, 0.78);
box-shadow:
0 18px 45px rgba(0, 0, 0, 0.18),
0 0 0 1px rgba(255, 255, 255, 0.025) inset;
@@ -938,10 +920,7 @@ a {
.landing-hero::before {
right: 0;
- background:
- radial-gradient(circle at 50% 18%, rgba(82, 213, 255, 0.18), transparent 280px),
- radial-gradient(circle at 76% 26%, rgba(68, 209, 157, 0.08), transparent 220px),
- linear-gradient(180deg, #10151d 0%, #0c1528 44%, #10151d 94%);
+ background: radial-gradient(circle at 50% 18%, rgba(82, 213, 255, 0.18), transparent 280px), radial-gradient(circle at 76% 26%, rgba(68, 209, 157, 0.08), transparent 220px), linear-gradient(180deg, #10151d 0%, #0c1528 44%, #10151d 94%);
}
.landing-hero::after {
@@ -993,12 +972,17 @@ a {
}
@keyframes landing-grid-drift {
- from { background-position: 0 0; }
- to { background-position: 54px 54px; }
+ from {
+ background-position: 0 0;
+ }
+ to {
+ background-position: 54px 54px;
+ }
}
@keyframes landing-pulse {
- 0%, 100% {
+ 0%,
+ 100% {
border-color: rgba(155, 176, 205, 0.18);
box-shadow:
0 0 0 1px rgba(82, 213, 255, 0.04) inset,
@@ -1013,7 +997,8 @@ a {
}
@keyframes landing-cta-glow {
- 0%, 100% {
+ 0%,
+ 100% {
box-shadow:
0 14px 36px rgba(110, 168, 255, 0.18),
0 0 0 1px rgba(255, 255, 255, 0.4) inset;
@@ -1026,8 +1011,12 @@ a {
}
@keyframes landing-testimonial-scroll {
- from { transform: translateX(0); }
- to { transform: translateX(calc(-50% - 7px)); }
+ from {
+ transform: translateX(0);
+ }
+ to {
+ transform: translateX(calc(-50% - 7px));
+ }
}
@media (prefers-reduced-motion: reduce) {
diff --git a/docs/app/layout.tsx b/docs/app/layout.tsx
index 96426552f5..22ecdf2a41 100644
--- a/docs/app/layout.tsx
+++ b/docs/app/layout.tsx
@@ -1,7 +1,7 @@
-import './global.css';
-import type { ReactNode } from 'react';
-import type { Metadata } from 'next';
-import { SITE_URL, SITE_NAME, DEFAULT_DESCRIPTION, DEFAULT_OG_IMAGE } from '@/lib/metadata';
+import "./global.css";
+import type { ReactNode } from "react";
+import type { Metadata } from "next";
+import { SITE_URL, SITE_NAME, DEFAULT_DESCRIPTION, DEFAULT_OG_IMAGE } from "@/lib/metadata";
export const metadata: Metadata = {
title: {
@@ -11,16 +11,16 @@ export const metadata: Metadata = {
description: DEFAULT_DESCRIPTION,
metadataBase: new URL(SITE_URL),
icons: {
- icon: '/favicon.png',
- shortcut: '/favicon.png',
- apple: '/logo.png',
+ icon: "/favicon.png",
+ shortcut: "/favicon.png",
+ apple: "/logo.png",
},
openGraph: {
siteName: SITE_NAME,
images: [{ url: DEFAULT_OG_IMAGE }],
},
twitter: {
- card: 'summary_large_image',
+ card: "summary_large_image",
},
};
@@ -32,18 +32,18 @@ export default function RootLayout({ children }: { children: ReactNode }) {
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify({
- '@context': 'https://schema.org',
- '@type': 'WebSite',
+ "@context": "https://schema.org",
+ "@type": "WebSite",
name: SITE_NAME,
url: SITE_URL,
description: DEFAULT_DESCRIPTION,
potentialAction: {
- '@type': 'SearchAction',
+ "@type": "SearchAction",
target: {
- '@type': 'EntryPoint',
+ "@type": "EntryPoint",
urlTemplate: `${SITE_URL}/search?q={search_term_string}`,
},
- 'query-input': 'required name=search_term_string',
+ "query-input": "required name=search_term_string",
},
}),
}}
diff --git a/docs/app/page.tsx b/docs/app/page.tsx
index 25eacb7525..b6ec5978dd 100644
--- a/docs/app/page.tsx
+++ b/docs/app/page.tsx
@@ -1,5 +1,5 @@
-import { redirect } from 'next/navigation';
+import { redirect } from "next/navigation";
export default function Page() {
- redirect('/cn');
+ redirect("/cn");
}
diff --git a/docs/components/DocsSidebarFooter.tsx b/docs/components/DocsSidebarFooter.tsx
index 4559a1c878..94cdd161cd 100644
--- a/docs/components/DocsSidebarFooter.tsx
+++ b/docs/components/DocsSidebarFooter.tsx
@@ -1,11 +1,10 @@
-'use client';
+"use client";
-import { Languages } from 'lucide-react';
-import { LanguageSelect } from 'fumadocs-ui/layouts/shared/slots/language-select';
-import { ThemeSwitch } from 'fumadocs-ui/layouts/shared/slots/theme-switch';
+import { Languages } from "lucide-react";
+import { LanguageSelect } from "fumadocs-ui/layouts/shared/slots/language-select";
+import { ThemeSwitch } from "fumadocs-ui/layouts/shared/slots/theme-switch";
-const iconButton =
- 'inline-flex size-8 items-center justify-center rounded-md text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground';
+const iconButton = "inline-flex size-8 items-center justify-center rounded-md text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground";
function GithubIcon() {
return (
@@ -28,7 +27,10 @@ function QQIcon() {
<svg viewBox="0 0 120 145" fill="currentColor" className="size-4.5">
<path d="M60.503 142.237c-12.533 0-24.038-4.195-31.445-10.46-3.762 1.124-8.574 2.932-11.61 5.175-2.6 1.918-2.275 3.874-1.807 4.663 2.056 3.47 35.273 2.216 44.862 1.136zm0 0c12.535 0 24.039-4.195 31.447-10.46 3.76 1.124 8.573 2.932 11.61 5.175 2.598 1.918 2.274 3.874 1.805 4.663-2.056 3.47-35.272 2.216-44.862 1.136zm0 0" />
<path d="M60.576 67.119c20.698-.14 37.286-4.147 42.907-5.683 1.34-.367 2.056-1.024 2.056-1.024.005-.189.085-3.37.085-5.01C105.624 27.768 92.58.001 60.5 0 28.42.001 15.375 27.769 15.375 55.401c0 1.642.08 4.822.086 5.01 0 0 .583.615 1.65.913 5.19 1.444 22.09 5.65 43.312 5.795zm56.245 23.02c-1.283-4.129-3.034-8.944-4.808-13.568 0 0-1.02-.126-1.537.023-15.913 4.623-35.202 7.57-49.9 7.392h-.153c-14.616.175-33.774-2.737-49.634-7.315-.606-.175-1.802-.1-1.802-.1-1.774 4.624-3.525 9.44-4.808 13.568-6.119 19.69-4.136 27.838-2.627 28.02 3.239.392 12.606-14.821 12.606-14.821 0 15.459 13.957 39.195 45.918 39.413h.848c31.96-.218 45.917-23.954 45.917-39.413 0 0 9.368 15.213 12.607 14.822 1.508-.183 3.491-8.332-2.627-28.021" />
- <path fill="#fff" d="M49.085 40.824c-4.352.197-8.07-4.76-8.304-11.063-.236-6.305 3.098-11.576 7.45-11.773 4.347-.195 8.064 4.76 8.3 11.065.238 6.306-3.097 11.577-7.446 11.771m31.133-11.063c-.233 6.302-3.951 11.26-8.303 11.063-4.35-.195-7.684-5.465-7.446-11.77.236-6.305 3.952-11.26 8.3-11.066 4.352.197 7.686 5.468 7.449 11.773" />
+ <path
+ fill="#fff"
+ d="M49.085 40.824c-4.352.197-8.07-4.76-8.304-11.063-.236-6.305 3.098-11.576 7.45-11.773 4.347-.195 8.064 4.76 8.3 11.065.238 6.306-3.097 11.577-7.446 11.771m31.133-11.063c-.233 6.302-3.951 11.26-8.303 11.063-4.35-.195-7.684-5.465-7.446-11.77.236-6.305 3.952-11.26 8.3-11.066 4.352.197 7.686 5.468 7.449 11.773"
+ />
</svg>
);
}
@@ -56,40 +58,16 @@ export function DocsSidebarFooter() {
<div className="dbx-docs-sidebar-footer">
<div className="dbx-docs-sidebar-tools">
<div className="flex items-center gap-1">
- <a
- className={iconButton}
- href="https://github.com/t8y2/dbx"
- target="_blank"
- rel="noreferrer"
- aria-label="GitHub"
- >
+ <a className={iconButton} href="https://github.com/t8y2/dbx" target="_blank" rel="noreferrer" aria-label="GitHub">
<GithubIcon />
</a>
- <a
- className={iconButton}
- href="https://discord.gg/W7NyVDRt6a"
- target="_blank"
- rel="noreferrer"
- aria-label="Discord"
- >
+ <a className={iconButton} href="https://discord.gg/W7NyVDRt6a" target="_blank" rel="noreferrer" aria-label="Discord">
<DiscordIcon />
</a>
- <a
- className={iconButton}
- href="https://qm.qq.com/cgi-bin/qm/qr?k=&group_code=1087880322"
- target="_blank"
- rel="noreferrer"
- aria-label="QQ"
- >
+ <a className={iconButton} href="https://qm.qq.com/cgi-bin/qm/qr?k=&group_code=1087880322" target="_blank" rel="noreferrer" aria-label="QQ">
<QQIcon />
</a>
- <a
- className={iconButton}
- href="https://docs.qq.com/doc/DVVhMY0h1ekJqc0tz"
- target="_blank"
- rel="noreferrer"
- aria-label="WeChat"
- >
+ <a className={iconButton} href="https://docs.qq.com/doc/DVVhMY0h1ekJqc0tz" target="_blank" rel="noreferrer" aria-label="WeChat">
<WeChatIcon />
</a>
</div>
diff --git a/docs/components/StaticSearchDialog.tsx b/docs/components/StaticSearchDialog.tsx
index 2069b641bd..307f9e70b3 100644
--- a/docs/components/StaticSearchDialog.tsx
+++ b/docs/components/StaticSearchDialog.tsx
@@ -1,56 +1,41 @@
-'use client';
+"use client";
-import { create } from '@orama/orama';
-import { useDocsSearch } from 'fumadocs-core/search/client';
-import {
- SearchDialog,
- SearchDialogClose,
- SearchDialogContent,
- SearchDialogFooter,
- SearchDialogHeader,
- SearchDialogIcon,
- SearchDialogInput,
- SearchDialogList,
- SearchDialogOverlay,
-} from 'fumadocs-ui/components/dialog/search';
-import type { SharedProps } from 'fumadocs-ui/contexts/search';
-import { useI18n } from 'fumadocs-ui/contexts/i18n';
-import { useMemo, useState } from 'react';
-import { createCjkSearchTokenizer } from '@/lib/cjkSearchTokenizer';
+import { create } from "@orama/orama";
+import { useDocsSearch } from "fumadocs-core/search/client";
+import { SearchDialog, SearchDialogClose, SearchDialogContent, SearchDialogFooter, SearchDialogHeader, SearchDialogIcon, SearchDialogInput, SearchDialogList, SearchDialogOverlay } from "fumadocs-ui/components/dialog/search";
+import type { SharedProps } from "fumadocs-ui/contexts/search";
+import { useI18n } from "fumadocs-ui/contexts/i18n";
+import { useMemo, useState } from "react";
+import { createCjkSearchTokenizer } from "@/lib/cjkSearchTokenizer";
export function StaticSearchDialog(props: SharedProps) {
const { locale } = useI18n();
const [tag] = useState<string | undefined>();
- const api = `/${locale ?? 'en'}/api/search`;
+ const api = `/${locale ?? "en"}/api/search`;
const { search, setSearch, query } = useDocsSearch({
- type: 'static',
+ type: "static",
from: api,
locale,
tag,
delayMs: 100,
initOrama: (dbLocale) => {
- if (dbLocale === 'cn') {
+ if (dbLocale === "cn") {
return create({
- schema: { _: 'string' },
+ schema: { _: "string" },
components: { tokenizer: createCjkSearchTokenizer() },
});
}
return create({
- schema: { _: 'string' },
- language: 'english',
+ schema: { _: "string" },
+ language: "english",
});
},
});
const defaultItems = useMemo(() => null, []);
return (
- <SearchDialog
- search={search}
- onSearchChange={setSearch}
- isLoading={query.isLoading}
- {...props}
- >
+ <SearchDialog search={search} onSearchChange={setSearch} isLoading={query.isLoading} {...props}>
<SearchDialogOverlay />
<SearchDialogContent>
<SearchDialogHeader>
@@ -58,7 +43,7 @@ export function StaticSearchDialog(props: SharedProps) {
<SearchDialogInput />
<SearchDialogClose />
</SearchDialogHeader>
- <SearchDialogList items={query.data !== 'empty' ? query.data : defaultItems} />
+ <SearchDialogList items={query.data !== "empty" ? query.data : defaultItems} />
</SearchDialogContent>
<SearchDialogFooter />
</SearchDialog>
diff --git a/docs/components/aceternity/HeroProductStage.tsx b/docs/components/aceternity/HeroProductStage.tsx
index 2adb4ff171..597c894a62 100644
--- a/docs/components/aceternity/HeroProductStage.tsx
+++ b/docs/components/aceternity/HeroProductStage.tsx
@@ -1,28 +1,28 @@
-'use client';
+"use client";
-import { motion } from 'motion/react';
-import { useEffect, useState } from 'react';
+import { motion } from "motion/react";
+import { useEffect, useState } from "react";
const productSlides = [
{
- src: '/screenshot-dark.png',
- alt: 'DBX data grid and AI assistant screenshot',
- label: 'Data grid',
+ src: "/screenshot-dark.png",
+ alt: "DBX data grid and AI assistant screenshot",
+ label: "Data grid",
},
{
- src: '/screenshot-connections.jpg',
- alt: 'DBX connection management screenshot',
- label: 'Connections',
+ src: "/screenshot-connections.jpg",
+ alt: "DBX connection management screenshot",
+ label: "Connections",
},
{
- src: '/screenshot-grid.png',
- alt: 'DBX table data grid screenshot',
- label: 'Tables',
+ src: "/screenshot-grid.png",
+ alt: "DBX table data grid screenshot",
+ label: "Tables",
},
{
- src: '/screenshot-ai.jpg',
- alt: 'DBX AI assistant screenshot',
- label: 'AI',
+ src: "/screenshot-ai.jpg",
+ alt: "DBX AI assistant screenshot",
+ label: "AI",
},
];
@@ -46,27 +46,12 @@ export function HeroProductStage() {
>
<div className="relative aspect-[16/10] overflow-hidden">
{productSlides.map((slide, index) => (
- <img
- alt={slide.alt}
- aria-hidden={index !== activeSlide}
- className="landing-product-slide absolute inset-0 z-[1] w-full h-full object-cover object-left-top"
- data-active={index === activeSlide}
- key={slide.src}
- src={slide.src}
- />
+ <img alt={slide.alt} aria-hidden={index !== activeSlide} className="landing-product-slide absolute inset-0 z-[1] w-full h-full object-cover object-left-top" data-active={index === activeSlide} key={slide.src} src={slide.src} />
))}
</div>
<div className="landing-product-dots absolute right-[18px] bottom-4 z-[5] flex gap-[7px] items-center rounded-full p-1.5 max-[760px]:right-3 max-[760px]:bottom-[11px]" aria-label="DBX product screenshots">
{productSlides.map((slide, index) => (
- <button
- aria-current={index === activeSlide}
- aria-label={`Show ${slide.label} screenshot`}
- key={slide.src}
- onClick={() => setActiveSlide(index)}
- title={slide.label}
- type="button"
- className="block w-[9px] h-[9px] border-0 rounded-full p-0 cursor-pointer"
- >
+ <button aria-current={index === activeSlide} aria-label={`Show ${slide.label} screenshot`} key={slide.src} onClick={() => setActiveSlide(index)} title={slide.label} type="button" className="block w-[9px] h-[9px] border-0 rounded-full p-0 cursor-pointer">
<span>{slide.label}</span>
</button>
))}
diff --git a/docs/components/aceternity/InfiniteMovingCards.tsx b/docs/components/aceternity/InfiniteMovingCards.tsx
index 69b040c343..b6f54e43f6 100644
--- a/docs/components/aceternity/InfiniteMovingCards.tsx
+++ b/docs/components/aceternity/InfiniteMovingCards.tsx
@@ -1,4 +1,4 @@
-'use client';
+"use client";
type Testimonial = {
name: string;
@@ -9,20 +9,15 @@ type Testimonial = {
type InfiniteMovingCardsProps = {
items: Testimonial[];
- direction?: 'left' | 'right';
- speed?: 'slow' | 'normal';
+ direction?: "left" | "right";
+ speed?: "slow" | "normal";
};
-export function InfiniteMovingCards({ items, direction = 'left', speed = 'normal' }: InfiniteMovingCardsProps) {
+export function InfiniteMovingCards({ items, direction = "left", speed = "normal" }: InfiniteMovingCardsProps) {
const repeatedItems = [...items, ...items];
return (
- <div
- className="landing-testimonial-marquee flex overflow-hidden select-none"
- data-direction={direction}
- data-speed={speed}
- aria-label="Testimonials"
- >
+ <div className="landing-testimonial-marquee flex overflow-hidden select-none" data-direction={direction} data-speed={speed} aria-label="Testimonials">
<div className="landing-testimonial-track flex w-max min-w-full gap-3.5 px-[7px]">
{repeatedItems.map((item, index) => (
<figure className="landing-testimonial-card flex-[0_0_340px] min-h-[188px] rounded-[9px] m-0 p-[22px] max-[760px]:flex-[0_0_286px] max-[760px]:min-h-[210px] max-[760px]:p-[18px]" key={`${item.name}-${index}`}>
diff --git a/docs/components/aceternity/Spotlight.tsx b/docs/components/aceternity/Spotlight.tsx
index 3c7158787d..4eb1f3c343 100644
--- a/docs/components/aceternity/Spotlight.tsx
+++ b/docs/components/aceternity/Spotlight.tsx
@@ -1,19 +1,11 @@
-'use client';
+"use client";
-import { motion } from 'motion/react';
+import { motion } from "motion/react";
type SpotlightProps = {
className?: string;
};
-export function Spotlight({ className = '' }: SpotlightProps) {
- return (
- <motion.div
- aria-hidden="true"
- className={`aceternity-spotlight ${className}`}
- initial={{ opacity: 0, scale: 0.96 }}
- animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 1.1, ease: [0.16, 1, 0.3, 1] }}
- />
- );
+export function Spotlight({ className = "" }: SpotlightProps) {
+ return <motion.div aria-hidden="true" className={`aceternity-spotlight ${className}`} initial={{ opacity: 0, scale: 0.96 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 1.1, ease: [0.16, 1, 0.3, 1] }} />;
}
diff --git a/docs/components/landing/ChangelogList.tsx b/docs/components/landing/ChangelogList.tsx
index d102455bee..1f6997d9cd 100644
--- a/docs/components/landing/ChangelogList.tsx
+++ b/docs/components/landing/ChangelogList.tsx
@@ -1,31 +1,29 @@
-'use client';
+"use client";
-import { useState, useEffect, useRef } from 'react';
-import type { ChangelogRelease } from '@/lib/changelog';
-import { ChevronDown, Tag } from 'lucide-react';
+import { useState, useEffect, useRef } from "react";
+import type { ChangelogRelease } from "@/lib/changelog";
+import { ChevronDown, Tag } from "lucide-react";
const PAGE_SIZE = 5;
const sectionLabels: Record<string, Record<string, string>> = {
- added: { en: 'New Features', cn: '新功能' },
- improved: { en: 'Improvements', cn: '改进' },
- fixed: { en: 'Bug Fixes', cn: '问题修复' },
- changed: { en: 'Changes', cn: '变更' },
- removed: { en: 'Removed', cn: '移除' },
+ added: { en: "New Features", cn: "新功能" },
+ improved: { en: "Improvements", cn: "改进" },
+ fixed: { en: "Bug Fixes", cn: "问题修复" },
+ changed: { en: "Changes", cn: "变更" },
+ removed: { en: "Removed", cn: "移除" },
};
function formatDate(dateStr: string, lang: string) {
const d = new Date(dateStr);
- if (lang === 'cn') {
+ if (lang === "cn") {
return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
}
- return d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
+ return d.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
}
function ReleaseCard({ release, lang }: { release: ChangelogRelease; lang: string }) {
- const t = lang === 'cn'
- ? { publishedOn: '发布于', download: '下载', seeGitHub: '查看 GitHub Release 获取详情' }
- : { publishedOn: 'Published on', download: 'Download', seeGitHub: 'See GitHub Release for details' };
+ const t = lang === "cn" ? { publishedOn: "发布于", download: "下载", seeGitHub: "查看 GitHub Release 获取详情" } : { publishedOn: "Published on", download: "Download", seeGitHub: "See GitHub Release for details" };
return (
<div className="py-12 border-t border-[rgba(155,176,205,0.18)]">
@@ -34,40 +32,37 @@ function ReleaseCard({ release, lang }: { release: ChangelogRelease; lang: strin
<div className="flex items-center gap-4">
<span className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-full border border-[rgba(155,176,205,0.25)] text-sm font-semibold text-[#e2e8f0]">
<Tag size={13} className="text-[#6ea8ff]" />
- {release.tag.replace('v', '')}
+ {release.tag.replace("v", "")}
</span>
<span className="text-[15px] text-[#64748b]">
{t.publishedOn} {formatDate(release.date, lang)}
</span>
</div>
- <a
- href={`https://github.com/t8y2/dbx/releases/tag/${release.tag}`}
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-1.5 px-4 py-2 rounded-full border border-[rgba(155,176,205,0.25)] text-sm text-[#e2e8f0] hover:border-[rgba(155,176,205,0.4)] transition-colors"
- >
+ <a href={`https://github.com/t8y2/dbx/releases/tag/${release.tag}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1.5 px-4 py-2 rounded-full border border-[rgba(155,176,205,0.25)] text-sm text-[#e2e8f0] hover:border-[rgba(155,176,205,0.4)] transition-colors">
{t.download}
<ChevronDown size={14} />
</a>
</div>
{/* Title */}
- <h2 className="text-[28px] font-[720] text-[#f7fbff] mb-10">
- Release {release.tag}
- </h2>
+ <h2 className="text-[28px] font-[720] text-[#f7fbff] mb-10">Release {release.tag}</h2>
{/* Sections */}
{release.sections.map((section, si) => (
- <div key={si} className={si > 0 ? 'mt-10' : ''}>
- <h3 className="text-xl font-bold text-[#f7fbff] mb-5">
- {sectionLabels[section.type]?.[lang] || section.title}
- </h3>
+ <div key={si} className={si > 0 ? "mt-10" : ""}>
+ <h3 className="text-xl font-bold text-[#f7fbff] mb-5">{sectionLabels[section.type]?.[lang] || section.title}</h3>
<ul className="space-y-3">
{section.items.map((item, ii) => (
<li key={ii} className="flex gap-3 text-[15px] leading-relaxed text-[#b8c5d6]">
<span className="mt-2 w-1.5 h-1.5 rounded-full bg-[#475569] shrink-0" />
<span>
- {item.desc ? <>{item.title},{item.desc}</> : item.title}
+ {item.desc ? (
+ <>
+ {item.title},{item.desc}
+ </>
+ ) : (
+ item.title
+ )}
</span>
</li>
))}
@@ -75,9 +70,7 @@ function ReleaseCard({ release, lang }: { release: ChangelogRelease; lang: strin
</div>
))}
- {release.sections.length === 0 && (
- <p className="text-[15px] text-[#64748b] italic">{t.seeGitHub}</p>
- )}
+ {release.sections.length === 0 && <p className="text-[15px] text-[#64748b] italic">{t.seeGitHub}</p>}
</div>
);
}
@@ -96,7 +89,7 @@ export function ChangelogList({ releases, lang }: { releases: ChangelogRelease[]
setCount((c) => Math.min(c + PAGE_SIZE, releases.length));
}
},
- { rootMargin: '200px' },
+ { rootMargin: "200px" },
);
observer.observe(node);
@@ -113,7 +106,7 @@ export function ChangelogList({ releases, lang }: { releases: ChangelogRelease[]
))}
{hasMore && (
<div ref={sentinelRef} className="flex justify-center py-12 text-[#64748b] text-sm">
- {lang === 'cn' ? '加载更多版本…' : 'Loading more versions…'}
+ {lang === "cn" ? "加载更多版本…" : "Loading more versions…"}
</div>
)}
</>
diff --git a/docs/components/landing/ChangelogRuntime.tsx b/docs/components/landing/ChangelogRuntime.tsx
index 3ba1fc1a47..355613d24d 100644
--- a/docs/components/landing/ChangelogRuntime.tsx
+++ b/docs/components/landing/ChangelogRuntime.tsx
@@ -1,22 +1,22 @@
-'use client';
+"use client";
-import { useEffect, useState } from 'react';
-import { ChangelogList } from '@/components/landing/ChangelogList';
-import { fetchChangelog, type ChangelogRelease } from '@/lib/changelog';
+import { useEffect, useState } from "react";
+import { ChangelogList } from "@/components/landing/ChangelogList";
+import { fetchChangelog, type ChangelogRelease } from "@/lib/changelog";
type ChangelogRuntimeProps = {
- lang: 'en' | 'cn';
+ lang: "en" | "cn";
initialReleases?: ChangelogRelease[];
};
const text = {
en: {
- loading: 'Loading releases...',
- empty: 'No releases found.',
+ loading: "Loading releases...",
+ empty: "No releases found.",
},
cn: {
- loading: '正在加载版本记录...',
- empty: '暂无版本记录。',
+ loading: "正在加载版本记录...",
+ empty: "暂无版本记录。",
},
};
diff --git a/docs/components/landing/InstallTabs.tsx b/docs/components/landing/InstallTabs.tsx
index a600dccb13..1f1c8514cc 100644
--- a/docs/components/landing/InstallTabs.tsx
+++ b/docs/components/landing/InstallTabs.tsx
@@ -1,44 +1,44 @@
-'use client';
+"use client";
-import { ChevronDown, Download, Server } from 'lucide-react';
-import { useEffect, useMemo, useState } from 'react';
-import { createInstallOptions, type InstallOption } from '@/lib/downloadLinks';
-import { fetchLatestReleaseInfo } from '@/lib/latestRelease';
+import { ChevronDown, Download, Server } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { createInstallOptions, type InstallOption } from "@/lib/downloadLinks";
+import { fetchLatestReleaseInfo } from "@/lib/latestRelease";
type InstallTabsProps = {
- lang: 'en' | 'cn';
+ lang: "en" | "cn";
version: string;
};
-const downloadLabel = { en: 'Download DBX', cn: '下载 DBX' };
+const downloadLabel = { en: "Download DBX", cn: "下载 DBX" };
const platformIconPaths = {
dark: {
- 'linux-arm': '/icons/platform/linux.svg',
- linux: '/icons/platform/linux.svg',
- 'macos-arm': '/icons/platform/macos.png',
- 'macos-intel': '/icons/platform/macos.png',
- windows: '/icons/platform/windows.png',
+ "linux-arm": "/icons/platform/linux.svg",
+ linux: "/icons/platform/linux.svg",
+ "macos-arm": "/icons/platform/macos.png",
+ "macos-intel": "/icons/platform/macos.png",
+ windows: "/icons/platform/windows.png",
},
light: {
- 'linux-arm': '/icons/platform/linux.svg',
- linux: '/icons/platform/linux.svg',
- 'macos-arm': '/icons/platform/macos-white.png',
- 'macos-intel': '/icons/platform/macos-white.png',
- windows: '/icons/platform/windows.png',
+ "linux-arm": "/icons/platform/linux.svg",
+ linux: "/icons/platform/linux.svg",
+ "macos-arm": "/icons/platform/macos-white.png",
+ "macos-intel": "/icons/platform/macos-white.png",
+ windows: "/icons/platform/windows.png",
},
};
function detectPlatformId(): string {
- if (typeof navigator === 'undefined') return 'macos-arm';
+ if (typeof navigator === "undefined") return "macos-arm";
const ua = navigator.userAgent.toLowerCase();
- if (ua.includes('win')) return 'windows';
- if (ua.includes('linux')) return ua.includes('aarch64') || ua.includes('arm') ? 'linux-arm' : 'linux';
- return 'macos-arm';
+ if (ua.includes("win")) return "windows";
+ if (ua.includes("linux")) return ua.includes("aarch64") || ua.includes("arm") ? "linux-arm" : "linux";
+ return "macos-arm";
}
-function PlatformIcon({ id, size, variant }: { id: string; size: number; variant: 'dark' | 'light' }) {
- const src = platformIconPaths[variant][id as keyof (typeof platformIconPaths)['dark']];
+function PlatformIcon({ id, size, variant }: { id: string; size: number; variant: "dark" | "light" }) {
+ const src = platformIconPaths[variant][id as keyof (typeof platformIconPaths)["dark"]];
if (!src) return <Server size={size} />;
return <img alt="" aria-hidden="true" height={size} src={src} width={size} />;
}
@@ -47,7 +47,7 @@ export function InstallTabs({ lang, version }: InstallTabsProps) {
const [downloadVersion, setDownloadVersion] = useState(version);
const options = useMemo(() => createInstallOptions(lang, downloadVersion), [lang, downloadVersion]);
const [open, setOpen] = useState(false);
- const [platformId, setPlatformId] = useState('macos-arm');
+ const [platformId, setPlatformId] = useState("macos-arm");
useEffect(() => {
setPlatformId(detectPlatformId());
@@ -102,16 +102,10 @@ export function InstallTabs({ lang, version }: InstallTabsProps) {
className="landing-install-menu absolute z-30 top-[calc(100%+12px)] left-1/2 -translate-x-1/2 grid w-[min(300px,calc(100vw-48px))] border border-[rgba(155,176,205,0.17)] rounded-xl py-1.5"
id="landing-install-menu"
role="listbox"
- aria-label={lang === 'cn' ? '下载选项' : 'Download options'}
+ aria-label={lang === "cn" ? "下载选项" : "Download options"}
>
{menuOptions.map((item) => (
- <a
- aria-selected="false"
- className="landing-install-option grid grid-cols-[24px_minmax(0,1fr)_18px] gap-3 items-center min-w-0 border-0 px-[18px] py-3 bg-transparent text-left cursor-pointer"
- href={item.href}
- key={item.id}
- role="option"
- >
+ <a aria-selected="false" className="landing-install-option grid grid-cols-[24px_minmax(0,1fr)_18px] gap-3 items-center min-w-0 border-0 px-[18px] py-3 bg-transparent text-left cursor-pointer" href={item.href} key={item.id} role="option">
<PlatformIcon id={item.id} size={20} variant="light" />
<strong className="overflow-hidden text-sm font-[640] leading-[1.2] truncate">{item.label}</strong>
<Download size={15} aria-hidden="true" />
diff --git a/docs/components/landing/LandingLatestUpdates.tsx b/docs/components/landing/LandingLatestUpdates.tsx
index 8da05f5218..369fe04a34 100644
--- a/docs/components/landing/LandingLatestUpdates.tsx
+++ b/docs/components/landing/LandingLatestUpdates.tsx
@@ -1,15 +1,15 @@
-'use client';
+"use client";
-import Link from 'next/link';
-import { ArrowRight, CheckCircle2 } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { RevealSection } from '@/components/landing/RevealSection';
-import { fetchChangelog, type ChangelogRelease } from '@/lib/changelog';
-import { buildLandingLatestUpdates } from '@/lib/landingLatest';
-import { fetchLatestReleaseInfo, type LatestReleaseInfo } from '@/lib/latestRelease';
+import Link from "next/link";
+import { ArrowRight, CheckCircle2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { RevealSection } from "@/components/landing/RevealSection";
+import { fetchChangelog, type ChangelogRelease } from "@/lib/changelog";
+import { buildLandingLatestUpdates } from "@/lib/landingLatest";
+import { fetchLatestReleaseInfo, type LatestReleaseInfo } from "@/lib/latestRelease";
type LandingLatestUpdatesProps = {
- lang: 'en' | 'cn';
+ lang: "en" | "cn";
fallbackVersion: string;
initialRelease?: ChangelogRelease;
initialLatestRelease?: LatestReleaseInfo | null;
diff --git a/docs/components/landing/LandingNav.tsx b/docs/components/landing/LandingNav.tsx
index 9d1ee83d8a..913d4729c3 100644
--- a/docs/components/landing/LandingNav.tsx
+++ b/docs/components/landing/LandingNav.tsx
@@ -1,48 +1,42 @@
-'use client';
+"use client";
-import Link from 'next/link';
-import { useEffect, useRef } from 'react';
+import Link from "next/link";
+import { useEffect, useRef } from "react";
const i18n = {
en: {
- home: 'Home',
- docs: 'Docs',
- changelog: 'Changelog',
- community: 'Community',
- drivers: 'Offline Drivers',
- lang: '中文',
+ home: "Home",
+ docs: "Docs",
+ changelog: "Changelog",
+ community: "Community",
+ drivers: "Offline Drivers",
+ lang: "中文",
},
- cn: { home: '首页', docs: '文档', changelog: '更新日志', community: '交流群', drivers: '离线驱动', lang: 'English' },
+ cn: { home: "首页", docs: "文档", changelog: "更新日志", community: "交流群", drivers: "离线驱动", lang: "English" },
};
-export function LandingNav({
- lang,
- active,
-}: {
- lang: 'en' | 'cn';
- active?: 'home' | 'changelog' | 'community' | 'drivers';
-}) {
+export function LandingNav({ lang, active }: { lang: "en" | "cn"; active?: "home" | "changelog" | "community" | "drivers" }) {
const ref = useRef<HTMLElement>(null);
const t = i18n[lang];
- const otherLang = lang === 'cn' ? 'en' : 'cn';
+ const otherLang = lang === "cn" ? "en" : "cn";
const langHrefMap: Record<string, string> = {
changelog: `/${otherLang}/changelog`,
community: `/${otherLang}/community`,
drivers: `/${otherLang}/drivers`,
};
- const langHref = langHrefMap[active ?? ''] ?? `/${otherLang}`;
+ const langHref = langHrefMap[active ?? ""] ?? `/${otherLang}`;
useEffect(() => {
const node = ref.current;
if (!node) return;
function onScroll() {
- node!.classList.toggle('is-scrolled', window.scrollY > 60);
+ node!.classList.toggle("is-scrolled", window.scrollY > 60);
}
onScroll();
- window.addEventListener('scroll', onScroll, { passive: true });
- return () => window.removeEventListener('scroll', onScroll);
+ window.addEventListener("scroll", onScroll, { passive: true });
+ return () => window.removeEventListener("scroll", onScroll);
}, []);
return (
@@ -53,47 +47,25 @@ export function LandingNav({
<span>DBX</span>
</Link>
<div className="flex items-center gap-1">
- <Link
- href={`/${lang}`}
- className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === 'home' ? 'text-landing-ink' : 'text-landing-muted'}`}
- >
+ <Link href={`/${lang}`} className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === "home" ? "text-landing-ink" : "text-landing-muted"}`}>
{t.home}
</Link>
- <Link
- href={`/${lang}/docs/what-is-dbx`}
- className="landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden text-landing-muted"
- >
+ <Link href={`/${lang}/docs/what-is-dbx`} className="landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden text-landing-muted">
{t.docs}
</Link>
- <Link
- href={`/${lang}/changelog`}
- className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === 'changelog' ? 'text-landing-ink' : 'text-landing-muted'}`}
- >
+ <Link href={`/${lang}/changelog`} className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === "changelog" ? "text-landing-ink" : "text-landing-muted"}`}>
{t.changelog}
</Link>
- <Link
- href={`/${lang}/community`}
- className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === 'community' ? 'text-landing-ink' : 'text-landing-muted'}`}
- >
+ <Link href={`/${lang}/community`} className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === "community" ? "text-landing-ink" : "text-landing-muted"}`}>
{t.community}
</Link>
- <Link
- href={`/${lang}/drivers`}
- className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === 'drivers' ? 'text-landing-ink' : 'text-landing-muted'}`}
- >
+ <Link href={`/${lang}/drivers`} className={`landing-nav-link rounded-[7px] px-[11px] py-2 text-[13px] font-medium max-[760px]:hidden ${active === "drivers" ? "text-landing-ink" : "text-landing-muted"}`}>
{t.drivers}
</Link>
- <Link
- href="https://github.com/t8y2/dbx"
- target="_blank"
- className="landing-nav-link rounded-[7px] px-[11px] py-2 text-landing-muted text-[13px] font-medium max-[760px]:hidden"
- >
+ <Link href="https://github.com/t8y2/dbx" target="_blank" className="landing-nav-link rounded-[7px] px-[11px] py-2 text-landing-muted text-[13px] font-medium max-[760px]:hidden">
GitHub
</Link>
- <Link
- href={langHref}
- className="landing-nav-link rounded-[7px] px-[11px] py-2 text-landing-muted text-[13px] font-medium ml-1.5 border border-landing-line"
- >
+ <Link href={langHref} className="landing-nav-link rounded-[7px] px-[11px] py-2 text-landing-muted text-[13px] font-medium ml-1.5 border border-landing-line">
{t.lang}
</Link>
</div>
diff --git a/docs/components/landing/RevealSection.tsx b/docs/components/landing/RevealSection.tsx
index a1cdd7bd6c..d5d6207126 100644
--- a/docs/components/landing/RevealSection.tsx
+++ b/docs/components/landing/RevealSection.tsx
@@ -1,7 +1,7 @@
-'use client';
+"use client";
-import type { CSSProperties, ReactNode } from 'react';
-import { useEffect, useRef, useState } from 'react';
+import type { CSSProperties, ReactNode } from "react";
+import { useEffect, useRef, useState } from "react";
type RevealSectionProps = {
children: ReactNode;
@@ -9,7 +9,7 @@ type RevealSectionProps = {
delay?: number;
};
-export function RevealSection({ children, className = '', delay = 0 }: RevealSectionProps) {
+export function RevealSection({ children, className = "", delay = 0 }: RevealSectionProps) {
const ref = useRef<HTMLElement | null>(null);
const [visible, setVisible] = useState(false);
@@ -24,7 +24,7 @@ export function RevealSection({ children, className = '', delay = 0 }: RevealSec
observer.unobserve(entry.target);
}
},
- { rootMargin: '0px 0px -14% 0px', threshold: 0.18 },
+ { rootMargin: "0px 0px -14% 0px", threshold: 0.18 },
);
observer.observe(node);
@@ -32,11 +32,7 @@ export function RevealSection({ children, className = '', delay = 0 }: RevealSec
}, []);
return (
- <section
- ref={ref}
- className={`${className} landing-reveal${visible ? ' is-visible' : ''}`}
- style={{ '--reveal-delay': `${delay}ms` } as CSSProperties}
- >
+ <section ref={ref} className={`${className} landing-reveal${visible ? " is-visible" : ""}`} style={{ "--reveal-delay": `${delay}ms` } as CSSProperties}>
{children}
</section>
);
diff --git a/docs/content/docs/ai-assistant.cn.mdx b/docs/content/docs/ai-assistant.cn.mdx
index 7e0e8eb877..c350105358 100644
--- a/docs/content/docs/ai-assistant.cn.mdx
+++ b/docs/content/docs/ai-assistant.cn.mdx
@@ -5,9 +5,7 @@ description: 配置 AI 供应商后,在 DBX 中生成 SQL、解释查询、优
AI 助手用于辅助 SQL 工作。它会结合当前连接的数据库元数据理解表结构和字段,再根据你的描述生成 SQL、解释查询、给出优化建议或帮助修复错误。
-<Callout type="warn">
-AI 生成的 SQL 不会自动执行。请在执行前检查表名、字段名、筛选条件和影响范围,尤其是在生产环境连接上。
-</Callout>
+<Callout type="warn">AI 生成的 SQL 不会自动执行。请在执行前检查表名、字段名、筛选条件和影响范围,尤其是在生产环境连接上。</Callout>
## 配置
@@ -16,33 +14,35 @@ AI 生成的 SQL 不会自动执行。请在执行前检查表名、字段名、
### 打开设置
进入 DBX 设置页,找到 AI 相关配置。
+
</Step>
<Step>
### 选择供应商
选择 Anthropic、OpenAI 或兼容 OpenAI API 的自定义端点。
+
</Step>
<Step>
### 填写凭据
输入 API Key。使用自定义端点时,还需要填写接口地址和模型名称。
+
</Step>
<Step>
### 保存并测试
保存配置后回到编辑器,尝试用自然语言生成一条简单查询。
+
</Step>
</Steps>
-<Callout type="info">
-如果没有配置 API Key,AI 功能应向用户提示需要先完成设置,而不是静默失败。
-</Callout>
+<Callout type="info">如果没有配置 API Key,AI 功能应向用户提示需要先完成设置,而不是静默失败。</Callout>
## Ask 模式与 Agent 模式
-| 模式 | 行为 | 执行 |
-|---|---|---|
-| Ask | 生成 SQL、解释、修复、优化、方言转换或样例数据 | 不暗示已经执行 |
+| 模式 | 行为 | 执行 |
+| ----- | ------------------------------------------------ | ---------------------------------------- |
+| Ask | 生成 SQL、解释、修复、优化、方言转换或样例数据 | 不暗示已经执行 |
| Agent | 当用户明确要求查询数据时,优先生成一条可执行 SQL | DBX 会先评估生成 SQL,再决定是否尝试执行 |
## Thinking 模式
@@ -73,12 +73,12 @@ AI 提示可以包含当前数据库类型、连接名称、数据库、当前 S
## SQL 安全策略
-| SQL 类型 | DBX 行为 |
-|---|---|
+| SQL 类型 | DBX 行为 |
+| ------------------------------------------------------------------ | -------------------------------------------- |
| `SELECT`、`WITH`、`SHOW`、`DESCRIBE`、`DESC`、`EXPLAIN` 等只读语句 | 用户明确表达查询意图时,Agent 模式可自动执行 |
-| `INSERT` 或按键限定的 `UPDATE` 等低风险写入 | 只在明确非生产环境自动执行;其他情况需要确认 |
-| 多语句、`DELETE`、`MERGE`、`REPLACE`、`CREATE` 或未知 SQL | 执行前需要确认 |
-| `DROP`、`TRUNCATE`、`ALTER`、`RENAME` 或大范围 `UPDATE` 等危险语句 | 会被 AI 执行策略阻止 |
+| `INSERT` 或按键限定的 `UPDATE` 等低风险写入 | 只在明确非生产环境自动执行;其他情况需要确认 |
+| 多语句、`DELETE`、`MERGE`、`REPLACE`、`CREATE` 或未知 SQL | 执行前需要确认 |
+| `DROP`、`TRUNCATE`、`ALTER`、`RENAME` 或大范围 `UPDATE` 等危险语句 | 会被 AI 执行策略阻止 |
连接名、主机或数据库名看起来像生产环境时,DBX 会更保守。AI 生成的 SQL 仍然是模型输出,请像审查代码一样审查它。
@@ -129,9 +129,7 @@ AI 可以根据 SQL 和表结构给出优化方向,例如:
- 子查询是否可以改写为 `JOIN`
- 排序、去重或聚合是否可以减少
-<Callout type="info">
-AI 的优化建议是参考信息。真正的性能判断仍应结合数据库的执行计划、数据量和索引情况。
-</Callout>
+<Callout type="info">AI 的优化建议是参考信息。真正的性能判断仍应结合数据库的执行计划、数据量和索引情况。</Callout>
### 修复错误
@@ -160,6 +158,7 @@ AI 的优化建议是参考信息。真正的性能判断仍应结合数据库
- Endpoint URL
- API Key
- Model
+
</Tab>
</Tabs>
diff --git a/docs/content/docs/ai-assistant.mdx b/docs/content/docs/ai-assistant.mdx
index 0487713fd9..e6c870e4e3 100644
--- a/docs/content/docs/ai-assistant.mdx
+++ b/docs/content/docs/ai-assistant.mdx
@@ -5,9 +5,7 @@ description: Configure an AI provider to generate SQL, explain queries, suggest
The AI assistant helps with SQL work. It uses metadata from the active connection to understand tables and columns, then helps generate SQL, explain queries, suggest optimizations, or diagnose errors.
-<Callout type="warn">
-AI-generated SQL is not executed automatically. Review table names, columns, filters, and affected rows before running it, especially on production connections.
-</Callout>
+<Callout type="warn">AI-generated SQL is not executed automatically. Review table names, columns, filters, and affected rows before running it, especially on production connections.</Callout>
## Configuration
@@ -16,34 +14,36 @@ AI-generated SQL is not executed automatically. Review table names, columns, fil
### Open Settings
Open DBX settings and find the AI configuration section.
+
</Step>
<Step>
### Choose a Provider
Select Anthropic, OpenAI, or a custom endpoint compatible with the OpenAI API.
+
</Step>
<Step>
### Enter Credentials
Enter your API key. For custom endpoints, also enter the endpoint URL and model name.
+
</Step>
<Step>
### Save and Test
Save the configuration, return to the editor, and try generating a simple query from natural language.
+
</Step>
</Steps>
-<Callout type="info">
-When no API key is configured, AI features should prompt the user to complete setup instead of failing silently.
-</Callout>
+<Callout type="info">When no API key is configured, AI features should prompt the user to complete setup instead of failing silently.</Callout>
## Ask Mode And Agent Mode
-| Mode | Behavior | Execution |
-|---|---|---|
-| Ask | Generates SQL, explanations, fixes, optimizations, dialect conversions, or sample data | Does not imply anything has run |
-| Agent | Prioritizes one executable SQL statement when the user clearly asks DBX to query data | DBX evaluates the generated SQL before attempting execution |
+| Mode | Behavior | Execution |
+| ----- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
+| Ask | Generates SQL, explanations, fixes, optimizations, dialect conversions, or sample data | Does not imply anything has run |
+| Agent | Prioritizes one executable SQL statement when the user clearly asks DBX to query data | DBX evaluates the generated SQL before attempting execution |
## Thinking Mode
@@ -73,12 +73,12 @@ When a schema is large, DBX truncates context. Use table mentions to prioritize
## SQL Safety Policy
-| SQL Category | DBX Behavior |
-|---|---|
-| Read-only statements such as `SELECT`, `WITH`, `SHOW`, `DESCRIBE`, `DESC`, `EXPLAIN` | Can be auto-executed in Agent mode when the user clearly asks to query |
-| Scoped low-risk writes such as `INSERT` or keyed `UPDATE` | Auto-execute only in clearly non-production environments; otherwise confirm |
-| Multiple statements, `DELETE`, `MERGE`, `REPLACE`, `CREATE`, or unknown SQL | Confirm before execution |
-| Dangerous statements such as `DROP`, `TRUNCATE`, `ALTER`, `RENAME`, or broad `UPDATE` | Blocked by the AI execution policy |
+| SQL Category | DBX Behavior |
+| ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
+| Read-only statements such as `SELECT`, `WITH`, `SHOW`, `DESCRIBE`, `DESC`, `EXPLAIN` | Can be auto-executed in Agent mode when the user clearly asks to query |
+| Scoped low-risk writes such as `INSERT` or keyed `UPDATE` | Auto-execute only in clearly non-production environments; otherwise confirm |
+| Multiple statements, `DELETE`, `MERGE`, `REPLACE`, `CREATE`, or unknown SQL | Confirm before execution |
+| Dangerous statements such as `DROP`, `TRUNCATE`, `ALTER`, `RENAME`, or broad `UPDATE` | Blocked by the AI execution policy |
Production-like connection names, hosts, or database names make DBX more conservative. Generated SQL is still text from an AI model; review it like code before trusting it.
@@ -129,9 +129,7 @@ The assistant can suggest optimization directions, such as:
- Subqueries that may be rewritten as `JOIN`
- Sorting, deduplication, or aggregation that could be reduced
-<Callout type="info">
-AI optimization suggestions are advisory. Confirm performance with the database execution plan, data volume, and index design.
-</Callout>
+<Callout type="info">AI optimization suggestions are advisory. Confirm performance with the database execution plan, data volume, and index design.</Callout>
### Fix Errors
@@ -160,6 +158,7 @@ When SQL fails, send the error and query to the assistant for diagnosis. Common
- Endpoint URL
- API key
- Model
+
</Tab>
</Tabs>
diff --git a/docs/content/docs/cli.cn.mdx b/docs/content/docs/cli.cn.mdx
index 289be6999e..19ab141e4d 100644
--- a/docs/content/docs/cli.cn.mdx
+++ b/docs/content/docs/cli.cn.mdx
@@ -3,9 +3,7 @@ title: DBX CLI
description: 在终端、脚本、CI 和 Codex 中使用 DBX 连接。
---
-<Callout type="info">
-DBX CLI 是独立命令行包,适合终端、脚本和 AI 编程助手工作流。它与 MCP Server 共享 DBX 连接存储和 SQL 安全规则。
-</Callout>
+<Callout type="info">DBX CLI 是独立命令行包,适合终端、脚本和 AI 编程助手工作流。它与 MCP Server 共享 DBX 连接存储和 SQL 安全规则。</Callout>
## 安装
@@ -119,16 +117,16 @@ select 1"
CLI JSON 错误使用稳定错误码:
-| 错误码 | 含义 |
-|---|---|
-| `UNKNOWN_OPTION` | 使用了不支持的参数 |
-| `INVALID_OPTION` | 参数缺少值或值不合法 |
-| `INVALID_ARGUMENT` | 位置参数缺失或冲突 |
+| 错误码 | 含义 |
+| ------------------------ | ---------------------------- |
+| `UNKNOWN_OPTION` | 使用了不支持的参数 |
+| `INVALID_OPTION` | 参数缺少值或值不合法 |
+| `INVALID_ARGUMENT` | 位置参数缺失或冲突 |
| `CONNECTION_STORE_ERROR` | DBX 连接存储存在,但无法读取 |
-| `CONNECTION_NOT_FOUND` | 找不到指定的 DBX 连接 |
-| `SQL_BLOCKED` | SQL 被安全规则拦截 |
-| `DBX_NOT_RUNNING` | DBX 桌面端 bridge 不可用 |
-| `ERROR` | 未预期的运行时错误 |
+| `CONNECTION_NOT_FOUND` | 找不到指定的 DBX 连接 |
+| `SQL_BLOCKED` | SQL 被安全规则拦截 |
+| `DBX_NOT_RUNNING` | DBX 桌面端 bridge 不可用 |
+| `ERROR` | 未预期的运行时错误 |
## 桌面端 Deep Link
@@ -148,19 +146,19 @@ open 'dbx://connection/new?type=mysql&host=127.0.0.1&port=3306&user=root&passwor
支持的字段:
-| 字段 | 含义 |
-|---|---|
-| `type` | 数据库类型,例如 `mysql`、`postgres`、`redis`、`mongodb` |
-| `url` | 数据库 DSN,建议 URL encode |
-| `name` | DBX 中显示的连接名;未传时优先使用 `database`,其次使用 `host` |
-| `host` | 主机地址 |
-| `port` | 端口 |
-| `user` | 用户名 |
-| `password` | 密码 |
-| `database` | 数据库名;Redis 可传 DB index,例如 `0` |
-| `url_params` | 额外连接参数,例如 `sslmode=require` |
-| `ssl` | 是否启用 SSL,`true` 表示启用 |
-| `one_time` | `true` 时自动连接,断开后自动删除连接信息 |
+| 字段 | 含义 |
+| ------------ | -------------------------------------------------------------- |
+| `type` | 数据库类型,例如 `mysql`、`postgres`、`redis`、`mongodb` |
+| `url` | 数据库 DSN,建议 URL encode |
+| `name` | DBX 中显示的连接名;未传时优先使用 `database`,其次使用 `host` |
+| `host` | 主机地址 |
+| `port` | 端口 |
+| `user` | 用户名 |
+| `password` | 密码 |
+| `database` | 数据库名;Redis 可传 DB index,例如 `0` |
+| `url_params` | 额外连接参数,例如 `sslmode=require` |
+| `ssl` | 是否启用 SSL,`true` 表示启用 |
+| `one_time` | `true` 时自动连接,断开后自动删除连接信息 |
一次性连接示例:
@@ -168,9 +166,7 @@ open 'dbx://connection/new?type=mysql&host=127.0.0.1&port=3306&user=root&passwor
open 'dbx://connection/new?type=redis&host=127.0.0.1&port=6379&user=default&password=secret&database=0&one_time=true'
```
-<Callout type="info">
-测试系统级 `dbx://` 唤起前,请先安装并启动一次 DBX 桌面端,让系统注册 URL 协议。macOS 可使用 `open 'dbx://connection/new?...'` 测试。
-</Callout>
+<Callout type="info">测试系统级 `dbx://` 唤起前,请先安装并启动一次 DBX 桌面端,让系统注册 URL 协议。macOS 可使用 `open 'dbx://connection/new?...'` 测试。</Callout>
## Codex
diff --git a/docs/content/docs/cli.mdx b/docs/content/docs/cli.mdx
index 0833919a1d..a5c891e4d3 100644
--- a/docs/content/docs/cli.mdx
+++ b/docs/content/docs/cli.mdx
@@ -3,9 +3,7 @@ title: DBX CLI
description: Use DBX connections from terminals, scripts, CI, and Codex.
---
-<Callout type="info">
-DBX CLI is a dedicated command line package for terminal, script, and coding-agent workflows. It shares DBX connection storage and SQL safety rules with the MCP server.
-</Callout>
+<Callout type="info">DBX CLI is a dedicated command line package for terminal, script, and coding-agent workflows. It shares DBX connection storage and SQL safety rules with the MCP server.</Callout>
## Install
@@ -119,16 +117,16 @@ select 1"
CLI JSON errors use stable codes:
-| Code | Meaning |
-|---|---|
-| `UNKNOWN_OPTION` | An unsupported flag was provided |
-| `INVALID_OPTION` | A flag is missing a value or has an invalid value |
-| `INVALID_ARGUMENT` | Positional arguments are missing or conflicting |
+| Code | Meaning |
+| ------------------------ | --------------------------------------------------- |
+| `UNKNOWN_OPTION` | An unsupported flag was provided |
+| `INVALID_OPTION` | A flag is missing a value or has an invalid value |
+| `INVALID_ARGUMENT` | Positional arguments are missing or conflicting |
| `CONNECTION_STORE_ERROR` | DBX connection storage exists but could not be read |
-| `CONNECTION_NOT_FOUND` | No DBX connection matched the requested name |
-| `SQL_BLOCKED` | SQL safety rules blocked execution |
-| `DBX_NOT_RUNNING` | DBX Desktop bridge is unavailable |
-| `ERROR` | Unexpected runtime failure |
+| `CONNECTION_NOT_FOUND` | No DBX connection matched the requested name |
+| `SQL_BLOCKED` | SQL safety rules blocked execution |
+| `DBX_NOT_RUNNING` | DBX Desktop bridge is unavailable |
+| `ERROR` | Unexpected runtime failure |
## Desktop Deep Links
@@ -148,19 +146,19 @@ open 'dbx://connection/new?type=mysql&host=127.0.0.1&port=3306&user=root&passwor
Supported fields:
-| Field | Meaning |
-|---|---|
-| `type` | Database type, such as `mysql`, `postgres`, `redis`, or `mongodb` |
-| `url` | Database DSN; URL encoding is recommended |
-| `name` | Display name in DBX; when omitted, DBX uses `database`, then `host` |
-| `host` | Hostname or IP address |
-| `port` | Port |
-| `user` | Username |
-| `password` | Password |
-| `database` | Database name; for Redis this can be a DB index such as `0` |
-| `url_params` | Extra connection parameters, such as `sslmode=require` |
-| `ssl` | Enable SSL when set to `true` |
-| `one_time` | Automatically connect when set to `true`, then delete the connection after disconnecting |
+| Field | Meaning |
+| ------------ | ---------------------------------------------------------------------------------------- |
+| `type` | Database type, such as `mysql`, `postgres`, `redis`, or `mongodb` |
+| `url` | Database DSN; URL encoding is recommended |
+| `name` | Display name in DBX; when omitted, DBX uses `database`, then `host` |
+| `host` | Hostname or IP address |
+| `port` | Port |
+| `user` | Username |
+| `password` | Password |
+| `database` | Database name; for Redis this can be a DB index such as `0` |
+| `url_params` | Extra connection parameters, such as `sslmode=require` |
+| `ssl` | Enable SSL when set to `true` |
+| `one_time` | Automatically connect when set to `true`, then delete the connection after disconnecting |
One-time connection example:
@@ -168,9 +166,7 @@ One-time connection example:
open 'dbx://connection/new?type=redis&host=127.0.0.1&port=6379&user=default&password=secret&database=0&one_time=true'
```
-<Callout type="info">
-Before testing system-level `dbx://` launches, install and open DBX Desktop once so the operating system can register the URL scheme. On macOS, use `open 'dbx://connection/new?...'` to test it.
-</Callout>
+<Callout type="info">Before testing system-level `dbx://` launches, install and open DBX Desktop once so the operating system can register the URL scheme. On macOS, use `open 'dbx://connection/new?...'` to test it.</Callout>
## Codex
diff --git a/docs/content/docs/config-export.cn.mdx b/docs/content/docs/config-export.cn.mdx
index 0a5247c618..7e72fb5a74 100644
--- a/docs/content/docs/config-export.cn.mdx
+++ b/docs/content/docs/config-export.cn.mdx
@@ -3,42 +3,22 @@ title: 配置导出/导入
description: 导出数据库连接配置(AES-256-GCM 加密),安全地在不同电脑之间迁移。
---
-<Callout type="info">
-导出你的数据库连接配置(含加密密码),用 AES-256-GCM 加密保护,安全地在不同电脑之间迁移。
-</Callout>
+<Callout type="info">导出你的数据库连接配置(含加密密码),用 AES-256-GCM 加密保护,安全地在不同电脑之间迁移。</Callout>
## 导出
<Steps>
- <Step>
- ### 发起导出
- 点击侧边栏顶部的 **导出** 按钮。
- </Step>
- <Step>
- ### 设置加密密码
- 输入密码短语来加密连接密码。
- </Step>
- <Step>
- ### 保存文件
- 选择保存位置。导出文件包含所有连接及密码,已加密。
- </Step>
+ <Step>### 发起导出 点击侧边栏顶部的 **导出** 按钮。</Step>
+ <Step>### 设置加密密码 输入密码短语来加密连接密码。</Step>
+ <Step>### 保存文件 选择保存位置。导出文件包含所有连接及密码,已加密。</Step>
</Steps>
## 导入
<Steps>
- <Step>
- ### 发起导入
- 点击侧边栏顶部的 **导入** 按钮。
- </Step>
- <Step>
- ### 选择文件并解密
- 选择导出的文件,输入密码短语解密。
- </Step>
- <Step>
- ### 完成
- 连接导入完成,密码自动恢复。按 名称 + 主机 + 端口 自动去重。
- </Step>
+ <Step>### 发起导入 点击侧边栏顶部的 **导入** 按钮。</Step>
+ <Step>### 选择文件并解密 选择导出的文件,输入密码短语解密。</Step>
+ <Step>### 完成 连接导入完成,密码自动恢复。按 名称 + 主机 + 端口 自动去重。</Step>
</Steps>
## 安全性
@@ -55,11 +35,11 @@ description: 导出数据库连接配置(AES-256-GCM 加密),安全地在
## 包含哪些内容
-| 项目 | 是否包含 |
-|---|---|
-| 连接名称、类型、主机、端口、数据库、颜色 | 包含 |
-| URL 参数、SSL、SSH、代理、可见数据库设置 | 包含 |
-| 数据库密码、SSH 密码、SSH 密钥密码、连接字符串 | 包含,并在导出文件中加密 |
-| 厂商 JDBC 驱动 JAR 文件 | 不包含;目标机器需要重新安装或导入 |
+| 项目 | 是否包含 |
+| ---------------------------------------------- | ---------------------------------- |
+| 连接名称、类型、主机、端口、数据库、颜色 | 包含 |
+| URL 参数、SSL、SSH、代理、可见数据库设置 | 包含 |
+| 数据库密码、SSH 密码、SSH 密钥密码、连接字符串 | 包含,并在导出文件中加密 |
+| 厂商 JDBC 驱动 JAR 文件 | 不包含;目标机器需要重新安装或导入 |
如果要迁移 JDBC 连接,先在这里导出连接配置,再在目标机器通过 [JDBC 插件](/cn/docs/plugins) 安装插件并导入驱动 JAR。
diff --git a/docs/content/docs/config-export.mdx b/docs/content/docs/config-export.mdx
index 05aa7ed5c1..419780bc1b 100644
--- a/docs/content/docs/config-export.mdx
+++ b/docs/content/docs/config-export.mdx
@@ -3,42 +3,22 @@ title: Config Export/Import
description: Export database connections with AES-256-GCM encrypted passwords. Migrate securely between machines.
---
-<Callout type="info">
-Export your database connections with encrypted passwords (AES-256-GCM). Securely migrate between machines.
-</Callout>
+<Callout type="info">Export your database connections with encrypted passwords (AES-256-GCM). Securely migrate between machines.</Callout>
## Export
<Steps>
- <Step>
- ### Start Export
- Click the **Export** button in the sidebar header.
- </Step>
- <Step>
- ### Set Passphrase
- Enter a passphrase to encrypt your passwords.
- </Step>
- <Step>
- ### Save File
- Choose a save location. The exported file contains all connections with passwords, encrypted.
- </Step>
+ <Step>### Start Export Click the **Export** button in the sidebar header.</Step>
+ <Step>### Set Passphrase Enter a passphrase to encrypt your passwords.</Step>
+ <Step>### Save File Choose a save location. The exported file contains all connections with passwords, encrypted.</Step>
</Steps>
## Import
<Steps>
- <Step>
- ### Start Import
- Click the **Import** button in the sidebar header.
- </Step>
- <Step>
- ### Select File and Decrypt
- Select the exported file and enter the passphrase.
- </Step>
- <Step>
- ### Done
- Connections are imported with passwords restored. Deduplicated by name + host + port.
- </Step>
+ <Step>### Start Import Click the **Import** button in the sidebar header.</Step>
+ <Step>### Select File and Decrypt Select the exported file and enter the passphrase.</Step>
+ <Step>### Done Connections are imported with passwords restored. Deduplicated by name + host + port.</Step>
</Steps>
## Security
@@ -55,11 +35,11 @@ Import also supports plain JSON files from older versions (without passwords) an
## What Is Included
-| Item | Included |
-|---|---|
-| Connection name, type, host, port, database, color | Yes |
-| URL parameters, SSL, SSH, proxy, visible database settings | Yes |
-| Database password, SSH password, SSH key passphrase, connection string | Yes, encrypted in the export file |
-| Vendor JDBC driver JAR files | No; reinstall or re-import drivers on the target machine |
+| Item | Included |
+| ---------------------------------------------------------------------- | -------------------------------------------------------- |
+| Connection name, type, host, port, database, color | Yes |
+| URL parameters, SSL, SSH, proxy, visible database settings | Yes |
+| Database password, SSH password, SSH key passphrase, connection string | Yes, encrypted in the export file |
+| Vendor JDBC driver JAR files | No; reinstall or re-import drivers on the target machine |
For JDBC migrations, export the connection settings here, then use [JDBC Plugin](/en/docs/plugins) to install the plugin and import driver JARs on the destination machine.
diff --git a/docs/content/docs/connection-import.cn.mdx b/docs/content/docs/connection-import.cn.mdx
index 346c004ed8..b85b6cc257 100644
--- a/docs/content/docs/connection-import.cn.mdx
+++ b/docs/content/docs/connection-import.cn.mdx
@@ -7,55 +7,29 @@ DBX 可以从其他数据库工具导入连接,在切换工具时无需手动
## 支持的格式
-| 来源 | 格式 | 导入内容 |
-|---|---|---|
+| 来源 | 格式 | 导入内容 |
+| ------- | --------------- | ---------------------------------------- |
| Navicat | `.ncx` 导出文件 | 主机、端口、用户名、数据库类型、连接名称 |
-| DBeaver | 连接配置文件 | 主机、端口、用户名、数据库类型、连接名称 |
+| DBeaver | 连接配置文件 | 主机、端口、用户名、数据库类型、连接名称 |
-<Callout type="info">
-导入的连接保留原始连接名称和类型。其他工具以加密格式存储的密码无法解密——导入后需要重新输入密码。
-</Callout>
+<Callout type="info">导入的连接保留原始连接名称和类型。其他工具以加密格式存储的密码无法解密——导入后需要重新输入密码。</Callout>
## 导入 Navicat 连接
<Steps>
- <Step>
- ### 从 Navicat 导出
- 在 Navicat 中,选择要迁移的连接。使用**文件 → 导出连接**并保存 `.ncx` 文件。
- </Step>
- <Step>
- ### 打开导入对话框
- 在 DBX 中,前往**设置 → 导入连接**,或右键点击侧边栏分组标题选择**导入连接**。
- </Step>
- <Step>
- ### 选择 NCX 文件
- 选择从 Navicat 导出的 `.ncx` 文件。
- </Step>
- <Step>
- ### 检查并完成
- DBX 解析文件并列出所有找到的连接。检查列表,在需要处重新输入密码并保存。
- </Step>
+ <Step>### 从 Navicat 导出 在 Navicat 中,选择要迁移的连接。使用**文件 → 导出连接**并保存 `.ncx` 文件。</Step>
+ <Step>### 打开导入对话框 在 DBX 中,前往**设置 → 导入连接**,或右键点击侧边栏分组标题选择**导入连接**。</Step>
+ <Step>### 选择 NCX 文件 选择从 Navicat 导出的 `.ncx` 文件。</Step>
+ <Step>### 检查并完成 DBX 解析文件并列出所有找到的连接。检查列表,在需要处重新输入密码并保存。</Step>
</Steps>
## 导入 DBeaver 连接
<Steps>
- <Step>
- ### 找到 DBeaver 配置
- DBeaver 将连接存储在其工作区目录中。具体路径取决于操作系统和 DBeaver 版本。常见位置包括 `~/.local/share/DBeaverData/workspace6/General/.dbeaver/`。
- </Step>
- <Step>
- ### 打开导入对话框
- 在 DBX 中,前往**设置 → 导入连接**。
- </Step>
- <Step>
- ### 选择 DBeaver 文件
- 选择 DBeaver 连接配置文件(`.dbeaver-data-sources.xml` 或类似文件)。
- </Step>
- <Step>
- ### 检查并完成
- DBX 从配置中提取连接信息。重新输入无法解密的密码。
- </Step>
+ <Step>### 找到 DBeaver 配置 DBeaver 将连接存储在其工作区目录中。具体路径取决于操作系统和 DBeaver 版本。常见位置包括 `~/.local/share/DBeaverData/workspace6/General/.dbeaver/`。</Step>
+ <Step>### 打开导入对话框 在 DBX 中,前往**设置 → 导入连接**。</Step>
+ <Step>### 选择 DBeaver 文件 选择 DBeaver 连接配置文件(`.dbeaver-data-sources.xml` 或类似文件)。</Step>
+ <Step>### 检查并完成 DBX 从配置中提取连接信息。重新输入无法解密的密码。</Step>
</Steps>
## 导入后
@@ -70,9 +44,9 @@ DBX 可以从其他数据库工具导入连接,在切换工具时无需手动
## 无法导入的内容
-| 设置 | 原因 |
-|---|---|
-| 加密密码 | 每个工具使用各自的加密方式,密码需要重新输入 |
-| SSH 隧道密钥 | 密钥文件路径可能因机器而异,需要重新选择密钥文件 |
-| 自定义驱动配置 | 驱动路径和版本是工具特定的 |
-| 代理设置 | 在连接的代理标签页中重新配置 |
+| 设置 | 原因 |
+| -------------- | ------------------------------------------------ |
+| 加密密码 | 每个工具使用各自的加密方式,密码需要重新输入 |
+| SSH 隧道密钥 | 密钥文件路径可能因机器而异,需要重新选择密钥文件 |
+| 自定义驱动配置 | 驱动路径和版本是工具特定的 |
+| 代理设置 | 在连接的代理标签页中重新配置 |
diff --git a/docs/content/docs/connection-import.mdx b/docs/content/docs/connection-import.mdx
index 7188f5bd55..e85168367d 100644
--- a/docs/content/docs/connection-import.mdx
+++ b/docs/content/docs/connection-import.mdx
@@ -7,55 +7,29 @@ DBX can import connections from other database tools, saving you from manually r
## Supported Formats
-| Source | Format | What's Imported |
-|---|---|---|
-| Navicat | `.ncx` export files | Host, port, username, database type, connection name |
+| Source | Format | What's Imported |
+| ------- | ------------------------------ | ---------------------------------------------------- |
+| Navicat | `.ncx` export files | Host, port, username, database type, connection name |
| DBeaver | Connection configuration files | Host, port, username, database type, connection name |
-<Callout type="info">
-Imported connections preserve the original connection name and type. Passwords stored in encrypted format by other tools cannot be decrypted — you will need to re-enter passwords after import.
-</Callout>
+<Callout type="info">Imported connections preserve the original connection name and type. Passwords stored in encrypted format by other tools cannot be decrypted — you will need to re-enter passwords after import.</Callout>
## Import Navicat Connections
<Steps>
- <Step>
- ### Export from Navicat
- In Navicat, select the connections you want to migrate. Use **File → Export Connections** and save the `.ncx` file.
- </Step>
- <Step>
- ### Open Import Dialog
- In DBX, go to **Settings → Import Connections** or right-click the sidebar group header and choose **Import Connections**.
- </Step>
- <Step>
- ### Select the NCX File
- Choose the `.ncx` file you exported from Navicat.
- </Step>
- <Step>
- ### Review and Complete
- DBX parses the file and lists all found connections. Review the list, re-enter passwords where needed, and save.
- </Step>
+ <Step>### Export from Navicat In Navicat, select the connections you want to migrate. Use **File → Export Connections** and save the `.ncx` file.</Step>
+ <Step>### Open Import Dialog In DBX, go to **Settings → Import Connections** or right-click the sidebar group header and choose **Import Connections**.</Step>
+ <Step>### Select the NCX File Choose the `.ncx` file you exported from Navicat.</Step>
+ <Step>### Review and Complete DBX parses the file and lists all found connections. Review the list, re-enter passwords where needed, and save.</Step>
</Steps>
## Import DBeaver Connections
<Steps>
- <Step>
- ### Locate DBeaver Configuration
- DBeaver stores connections in its workspace directory. The exact path depends on your OS and DBeaver version. Common locations include `~/.local/share/DBeaverData/workspace6/General/.dbeaver/`.
- </Step>
- <Step>
- ### Open Import Dialog
- In DBX, go to **Settings → Import Connections**.
- </Step>
- <Step>
- ### Select DBeaver Files
- Choose the DBeaver connection configuration files (`.dbeaver-data-sources.xml` or similar).
- </Step>
- <Step>
- ### Review and Complete
- DBX extracts connection details from the configuration. Re-enter any passwords that could not be decrypted.
- </Step>
+ <Step>### Locate DBeaver Configuration DBeaver stores connections in its workspace directory. The exact path depends on your OS and DBeaver version. Common locations include `~/.local/share/DBeaverData/workspace6/General/.dbeaver/`.</Step>
+ <Step>### Open Import Dialog In DBX, go to **Settings → Import Connections**.</Step>
+ <Step>### Select DBeaver Files Choose the DBeaver connection configuration files (`.dbeaver-data-sources.xml` or similar).</Step>
+ <Step>### Review and Complete DBX extracts connection details from the configuration. Re-enter any passwords that could not be decrypted.</Step>
</Steps>
## After Import
@@ -70,9 +44,9 @@ Imported connections appear in the sidebar alongside manually created ones. You
## What Cannot Be Imported
-| Setting | Reason |
-|---|---|
-| Encrypted passwords | Each tool uses proprietary encryption; passwords must be re-entered |
-| SSH tunnel keys | Key file paths may differ between machines; re-select the key file |
-| Custom driver configurations | Driver paths and versions are tool-specific |
-| Proxy settings | Re-configure in the connection's Proxy tab |
+| Setting | Reason |
+| ---------------------------- | ------------------------------------------------------------------- |
+| Encrypted passwords | Each tool uses proprietary encryption; passwords must be re-entered |
+| SSH tunnel keys | Key file paths may differ between machines; re-select the key file |
+| Custom driver configurations | Driver paths and versions are tool-specific |
+| Proxy settings | Re-configure in the connection's Proxy tab |
diff --git a/docs/content/docs/data-grid.cn.mdx b/docs/content/docs/data-grid.cn.mdx
index bfabb80ce1..6901eb7cbe 100644
--- a/docs/content/docs/data-grid.cn.mdx
+++ b/docs/content/docs/data-grid.cn.mdx
@@ -19,15 +19,13 @@ DBX 使用虚拟滚动渲染表格,只渲染当前可视区域内的行。大
## 过滤与排序
-| 功能 | 适合场景 |
-|---|---|
-| 搜索 | 在当前结果中快速定位包含关键字的行 |
-| WHERE | 在数据库层面筛选数据,适合大表和精确条件 |
-| ORDER BY | 在数据库层面排序,适合稳定复现查询结果 |
+| 功能 | 适合场景 |
+| -------- | ---------------------------------------- |
+| 搜索 | 在当前结果中快速定位包含关键字的行 |
+| WHERE | 在数据库层面筛选数据,适合大表和精确条件 |
+| ORDER BY | 在数据库层面排序,适合稳定复现查询结果 |
-<Callout type="info">
-大表场景优先使用 `WHERE` 和 `ORDER BY`。它们在数据库层面执行,通常比客户端搜索更稳定。
-</Callout>
+<Callout type="info">大表场景优先使用 `WHERE` 和 `ORDER BY`。它们在数据库层面执行,通常比客户端搜索更稳定。</Callout>
## 行内编辑
@@ -44,18 +42,16 @@ DBX 使用虚拟滚动渲染表格,只渲染当前可视区域内的行。大
当 DBX 能识别目标表,并且有足够的键信息生成可审查的 `UPDATE`、`INSERT` 或 `DELETE` 语句时,结果才可编辑。直接打开表数据通常可以编辑;临时 join、聚合、表达式或没有可用主键/行标识的结果会视为只读。
-| 结果类型 | 通常行为 |
-|---|---|
-| 打开的表数据 | 数据库和表支持时可编辑 |
-| 简单 `SELECT * FROM table` | 有主键或行标识时通常可编辑 |
-| Join、聚合、计算列 | 只读结果 |
-| Redis 或 MongoDB 视图 | 使用对应专用编辑器,不走关系型行 SQL |
+| 结果类型 | 通常行为 |
+| -------------------------- | ------------------------------------ |
+| 打开的表数据 | 数据库和表支持时可编辑 |
+| 简单 `SELECT * FROM table` | 有主键或行标识时通常可编辑 |
+| Join、聚合、计算列 | 只读结果 |
+| Redis 或 MongoDB 视图 | 使用对应专用编辑器,不走关系型行 SQL |
## SQL 预览
-<Callout type="warn">
-数据修改不会在编辑后立即写入数据库。点击保存前,请先检查 SQL 预览,尤其是在生产环境连接上。
-</Callout>
+<Callout type="warn">数据修改不会在编辑后立即写入数据库。点击保存前,请先检查 SQL 预览,尤其是在生产环境连接上。</Callout>
SQL 预览会展示 `UPDATE`、`INSERT` 或 `DELETE` 语句。这个步骤可以帮助你确认:
@@ -129,14 +125,14 @@ SQL 预览会展示 `UPDATE`、`INSERT` 或 `DELETE` 语句。这个步骤可以
## 导出与复制
-| 格式 | 用途 |
-|---|---|
-| CSV | 给 Excel、Numbers 或其他表格工具使用 |
-| JSON | 给脚本、接口调试或程序处理使用 |
-| Markdown | 粘贴到 Issue、PR、文档或聊天中 |
-| INSERT | 将选中行复制为可执行的 `INSERT` 语句(支持单行或批量) |
-| UPDATE | 将选中行复制为可执行的 `UPDATE` 语句 |
-| XLSX | 从表格上下文菜单直接导出为 Excel 格式 |
+| 格式 | 用途 |
+| -------- | ------------------------------------------------------ |
+| CSV | 给 Excel、Numbers 或其他表格工具使用 |
+| JSON | 给脚本、接口调试或程序处理使用 |
+| Markdown | 粘贴到 Issue、PR、文档或聊天中 |
+| INSERT | 将选中行复制为可执行的 `INSERT` 语句(支持单行或批量) |
+| UPDATE | 将选中行复制为可执行的 `UPDATE` 语句 |
+| XLSX | 从表格上下文菜单直接导出为 Excel 格式 |
导出前建议先确认当前筛选和排序条件,避免导出范围和预期不一致。
diff --git a/docs/content/docs/data-grid.mdx b/docs/content/docs/data-grid.mdx
index d36fb1c974..db02c81012 100644
--- a/docs/content/docs/data-grid.mdx
+++ b/docs/content/docs/data-grid.mdx
@@ -19,15 +19,13 @@ Common browsing actions:
## Filter and Sort
-| Feature | Best For |
-|---|---|
-| Search | Finding rows in the current result set |
-| WHERE | Database-level filtering for large tables or precise conditions |
-| ORDER BY | Database-level ordering for reproducible results |
+| Feature | Best For |
+| -------- | --------------------------------------------------------------- |
+| Search | Finding rows in the current result set |
+| WHERE | Database-level filtering for large tables or precise conditions |
+| ORDER BY | Database-level ordering for reproducible results |
-<Callout type="info">
-For large tables, prefer `WHERE` and `ORDER BY`. They run in the database and are usually more reliable than client-side search.
-</Callout>
+<Callout type="info">For large tables, prefer `WHERE` and `ORDER BY`. They run in the database and are usually more reliable than client-side search.</Callout>
## Inline Editing
@@ -44,18 +42,16 @@ All changes are staged locally first. Before saving, DBX shows the SQL it is abo
Editing is available when DBX can identify the target table and enough key information to generate reviewable `UPDATE`, `INSERT`, or `DELETE` statements. Simple table browsing is usually editable. Ad-hoc joins, aggregates, expressions, or result sets without usable keys are treated as read-only.
-| Result Type | Typical Behavior |
-|---|---|
-| Opened table data | Editable when the database and table support edits |
-| Simple `SELECT * FROM table` | Often editable if primary key or row identity is available |
-| Joins, aggregates, computed columns | Read-only result set |
-| Redis or MongoDB views | Use their dedicated editors instead of relational row SQL |
+| Result Type | Typical Behavior |
+| ----------------------------------- | ---------------------------------------------------------- |
+| Opened table data | Editable when the database and table support edits |
+| Simple `SELECT * FROM table` | Often editable if primary key or row identity is available |
+| Joins, aggregates, computed columns | Read-only result set |
+| Redis or MongoDB views | Use their dedicated editors instead of relational row SQL |
## SQL Preview
-<Callout type="warn">
-Edits are not written to the database immediately. Before saving, review the SQL preview carefully, especially on production connections.
-</Callout>
+<Callout type="warn">Edits are not written to the database immediately. Before saving, review the SQL preview carefully, especially on production connections.</Callout>
The preview shows `UPDATE`, `INSERT`, or `DELETE` statements. Use it to confirm:
@@ -129,14 +125,14 @@ Column headers provide quick access to actions:
## Export and Copy
-| Format | Use Case |
-|---|---|
-| CSV | Excel, Numbers, or spreadsheet tools |
-| JSON | Scripts, API debugging, or programmatic processing |
-| Markdown | Issues, PRs, documentation, or chat |
-| INSERT | Copy selected rows as executable `INSERT` statements (single or batched) |
-| UPDATE | Copy selected rows as executable `UPDATE` statements |
-| XLSX | Export directly to Excel format from the table context menu |
+| Format | Use Case |
+| -------- | ------------------------------------------------------------------------ |
+| CSV | Excel, Numbers, or spreadsheet tools |
+| JSON | Scripts, API debugging, or programmatic processing |
+| Markdown | Issues, PRs, documentation, or chat |
+| INSERT | Copy selected rows as executable `INSERT` statements (single or batched) |
+| UPDATE | Copy selected rows as executable `UPDATE` statements |
+| XLSX | Export directly to Excel format from the table context menu |
Before exporting, check the active filters and sort order so the exported data matches what you expect.
diff --git a/docs/content/docs/data-transfer.cn.mdx b/docs/content/docs/data-transfer.cn.mdx
index 72784e420e..db27b03e83 100644
--- a/docs/content/docs/data-transfer.cn.mdx
+++ b/docs/content/docs/data-transfer.cn.mdx
@@ -12,9 +12,7 @@ description: 在不同连接或不同数据库引擎之间迁移表数据。
- 将多个数据源整理到同一个分析库
- 为测试环境准备一份可复现的数据集
-<Callout type="warn">
-跨引擎传输会涉及类型映射、默认值、约束和自增字段差异。传输完成后请抽样检查数据,重要迁移建议先在测试环境演练。
-</Callout>
+<Callout type="warn">跨引擎传输会涉及类型映射、默认值、约束和自增字段差异。传输完成后请抽样检查数据,重要迁移建议先在测试环境演练。</Callout>
## 使用流程
@@ -23,26 +21,31 @@ description: 在不同连接或不同数据库引擎之间迁移表数据。
### 选择源连接
源连接是数据读取的位置。确认账号有读取目标表的权限。
+
</Step>
<Step>
### 选择目标连接
目标连接是数据写入的位置。确认账号有写入权限,并确认目标库环境无误。
+
</Step>
<Step>
### 选择表
可以传输全部表,也可以只选择需要的表。大表建议分批处理。
+
</Step>
<Step>
### 开始传输
DBX 会按表读取数据,并根据所选模式写入目标数据库。可选择是否创建目标表。
+
</Step>
<Step>
### 检查结果
传输完成后检查行数、错误列表和关键字段。
+
</Step>
</Steps>
@@ -59,13 +62,13 @@ DBX 会在传输过程中展示:
## 传输选项
-| 选项 | 说明 |
-|---|---|
-| 创建目标表 | 目标库没有对应表时,尝试根据源表结构创建 |
-| 追加 | 将数据插入目标表现有数据之后 |
-| 覆盖 | 先清空目标表,再写入源数据 |
-| Upsert | 在目标数据库路径支持时使用基于键的写入行为 |
-| 批大小 | 控制每批写入的行数 |
+| 选项 | 说明 |
+| ---------- | ------------------------------------------ |
+| 创建目标表 | 目标库没有对应表时,尝试根据源表结构创建 |
+| 追加 | 将数据插入目标表现有数据之后 |
+| 覆盖 | 先清空目标表,再写入源数据 |
+| Upsert | 在目标数据库路径支持时使用基于键的写入行为 |
+| 批大小 | 控制每批写入的行数 |
## 数据库覆盖范围
@@ -73,13 +76,13 @@ DBX 会在传输过程中展示:
## 传输前检查
-| 检查项 | 原因 |
-|---|---|
-| 目标环境 | 避免误写生产库或错误环境 |
-| 表结构 | 字段名、类型、主键和唯一约束会影响写入 |
-| 数据量 | 大表可能需要更长时间,也可能触发超时 |
-| 约束 | 外键、唯一约束、非空字段可能导致写入失败 |
-| 敏感数据 | 从生产复制到低环境前,确认是否需要脱敏 |
+| 检查项 | 原因 |
+| -------- | ---------------------------------------- |
+| 目标环境 | 避免误写生产库或错误环境 |
+| 表结构 | 字段名、类型、主键和唯一约束会影响写入 |
+| 数据量 | 大表可能需要更长时间,也可能触发超时 |
+| 约束 | 外键、唯一约束、非空字段可能导致写入失败 |
+| 敏感数据 | 从生产复制到低环境前,确认是否需要脱敏 |
## 相关功能
diff --git a/docs/content/docs/data-transfer.mdx b/docs/content/docs/data-transfer.mdx
index 8221b2d701..a801bad875 100644
--- a/docs/content/docs/data-transfer.mdx
+++ b/docs/content/docs/data-transfer.mdx
@@ -12,9 +12,7 @@ Data Transfer copies table data from one connection to another. Use it for devel
- Consolidate multiple sources into an analysis database
- Prepare reproducible datasets for testing
-<Callout type="warn">
-Cross-engine transfer involves type mapping, defaults, constraints, and auto-increment differences. Validate transferred data afterward, and rehearse important migrations in a test environment first.
-</Callout>
+<Callout type="warn">Cross-engine transfer involves type mapping, defaults, constraints, and auto-increment differences. Validate transferred data afterward, and rehearse important migrations in a test environment first.</Callout>
## Workflow
@@ -23,26 +21,31 @@ Cross-engine transfer involves type mapping, defaults, constraints, and auto-inc
### Select the Source
The source connection is where data is read from. Confirm the account can read the selected tables.
+
</Step>
<Step>
### Select the Target
The target connection is where data is written. Confirm write permissions and verify the target environment.
+
</Step>
<Step>
### Choose Tables
Transfer all tables or select only the tables you need. For large tables, consider transferring in smaller batches.
+
</Step>
<Step>
### Start Transfer
DBX reads rows table by table and writes them to the target database using the selected mode. You can also choose whether target tables should be created.
+
</Step>
<Step>
### Check Results
After transfer, inspect row counts, errors, and key fields.
+
</Step>
</Steps>
@@ -59,13 +62,13 @@ If a table fails, the current transfer stops and shows the error. Fix the struct
## Transfer Options
-| Option | Details |
-|---|---|
+| Option | Details |
+| ------------------- | ------------------------------------------------------------------------------- |
| Create target table | Try to create the target table from the source structure when it does not exist |
-| Append | Insert data after existing target rows |
-| Overwrite | Clear the target table before writing source rows |
-| Upsert | Use key-aware write behavior where the target database path supports it |
-| Batch size | Control how many rows are written per batch |
+| Append | Insert data after existing target rows |
+| Overwrite | Clear the target table before writing source rows |
+| Upsert | Use key-aware write behavior where the target database path supports it |
+| Batch size | Control how many rows are written per batch |
## Database Coverage
@@ -73,13 +76,13 @@ SQL-based transfer is available for MySQL, PostgreSQL, SQLite, SQL Server, Oracl
## Before You Transfer
-| Check | Why It Matters |
-|---|---|
-| Target environment | Avoid writing to the wrong database |
-| Table structure | Field names, types, primary keys, and unique constraints affect inserts |
-| Data volume | Large tables may take longer or hit timeouts |
-| Constraints | Foreign keys, unique constraints, and NOT NULL fields may fail writes |
-| Sensitive data | Production data may need masking before copying into lower environments |
+| Check | Why It Matters |
+| ------------------ | ----------------------------------------------------------------------- |
+| Target environment | Avoid writing to the wrong database |
+| Table structure | Field names, types, primary keys, and unique constraints affect inserts |
+| Data volume | Large tables may take longer or hit timeouts |
+| Constraints | Foreign keys, unique constraints, and NOT NULL fields may fail writes |
+| Sensitive data | Production data may need masking before copying into lower environments |
## Related Features
diff --git a/docs/content/docs/database-export.cn.mdx b/docs/content/docs/database-export.cn.mdx
index 31588d020a..41e0669980 100644
--- a/docs/content/docs/database-export.cn.mdx
+++ b/docs/content/docs/database-export.cn.mdx
@@ -7,12 +7,12 @@ description: 将数据库结构和数据导出为 SQL 文件,用于备份、
## 导出内容
-| 内容 | 说明 |
-|---|---|
-| 表结构 | `CREATE TABLE`、字段、主键、索引、约束等 DDL |
-| 表数据 | 以 `INSERT` 语句形式导出 |
+| 内容 | 说明 |
+| -------- | ----------------------------------------------- |
+| 表结构 | `CREATE TABLE`、字段、主键、索引、约束等 DDL |
+| 表数据 | 以 `INSERT` 语句形式导出 |
| 批量插入 | 多行合并为一条 `INSERT`,减少文件体积和导入成本 |
-| 对象 | 数据库可提供源码时导出视图、存储过程和函数 |
+| 对象 | 数据库可提供源码时导出视图、存储过程和函数 |
示例:
@@ -30,21 +30,25 @@ INSERT INTO users (id, name, email) VALUES
### 选择连接和数据库
选择要导出的连接和数据库,确认当前环境无误。
+
</Step>
<Step>
### 设置导出选项
选择是否包含结构、数据和数据库对象。可以导出全部表,也可以只导出选中的表。
+
</Step>
<Step>
### 选择保存位置
选择 `.sql` 文件保存路径。
+
</Step>
<Step>
### 开始导出
DBX 会生成 SQL 文件,并展示当前对象、进度、行数、错误和取消状态。
+
</Step>
</Steps>
@@ -54,9 +58,7 @@ DBX 会分批读取表数据,并把生成的 `INSERT` 语句写入输出文件
选择部分表导出时,DBX 会先过滤表列表,再生成 DDL 和数据。视图、存储过程、函数等对象只会在启用对象导出且没有限定表子集时一起导出。
-<Callout type="info">
-MySQL 导出会在表内容前写入 `SET FOREIGN_KEY_CHECKS = 0`,并在文件末尾重新启用。
-</Callout>
+<Callout type="info">MySQL 导出会在表内容前写入 `SET FOREIGN_KEY_CHECKS = 0`,并在文件末尾重新启用。</Callout>
## 取消与错误
@@ -66,9 +68,7 @@ MySQL 导出会在表内容前写入 `SET FOREIGN_KEY_CHECKS = 0`,并在文件
导出的 `.sql` 文件可以通过 [SQL 文件执行](/cn/docs/sql-file) 导入到数据库中。
-<Callout type="warn">
-导出文件可能包含敏感数据、账号信息、业务标识或用户隐私。分享前请确认是否需要脱敏。
-</Callout>
+<Callout type="warn">导出文件可能包含敏感数据、账号信息、业务标识或用户隐私。分享前请确认是否需要脱敏。</Callout>
## 使用建议
diff --git a/docs/content/docs/database-export.mdx b/docs/content/docs/database-export.mdx
index 2bb1120f19..1a9735a10e 100644
--- a/docs/content/docs/database-export.mdx
+++ b/docs/content/docs/database-export.mdx
@@ -7,12 +7,12 @@ Database Export writes table structure and table data into a SQL file. Use it be
## What Gets Exported
-| Content | Details |
-|---|---|
-| Structure | `CREATE TABLE`, columns, primary keys, indexes, constraints, and other DDL |
-| Data | Rows exported as `INSERT` statements |
+| Content | Details |
+| --------------- | ------------------------------------------------------------------------------- |
+| Structure | `CREATE TABLE`, columns, primary keys, indexes, constraints, and other DDL |
+| Data | Rows exported as `INSERT` statements |
| Batched inserts | Multiple rows grouped into one `INSERT` to reduce file size and import overhead |
-| Objects | Views, procedures, and functions where the database exposes source definitions |
+| Objects | Views, procedures, and functions where the database exposes source definitions |
Example:
@@ -30,21 +30,25 @@ INSERT INTO users (id, name, email) VALUES
### Select Connection and Database
Choose the database to export and verify the environment.
+
</Step>
<Step>
### Configure Export Options
Choose whether to include structure, data, and database objects. You can export all tables or a selected table subset.
+
</Step>
<Step>
### Choose Output Location
Select where the `.sql` file should be saved.
+
</Step>
<Step>
### Start Export
DBX generates a SQL file and reports the current object, progress, row counts, errors, and cancellation state.
+
</Step>
</Steps>
@@ -54,9 +58,7 @@ DBX reads table data in batches and writes generated `INSERT` statements into th
Selected-table export filters the table list before generating DDL and data. Routine objects such as procedures and functions are included only when object export is enabled and the export is not limited to a table subset.
-<Callout type="info">
-For MySQL exports, DBX temporarily writes `SET FOREIGN_KEY_CHECKS = 0` before table content and re-enables it at the end of the file.
-</Callout>
+<Callout type="info">For MySQL exports, DBX temporarily writes `SET FOREIGN_KEY_CHECKS = 0` before table content and re-enables it at the end of the file.</Callout>
## Cancellation And Errors
@@ -66,9 +68,7 @@ You can cancel an export between objects or row batches. If a specific table or
The generated `.sql` file can be imported with [SQL File Execution](/en/docs/sql-file).
-<Callout type="warn">
-Export files may contain sensitive data, account information, business identifiers, or user privacy data. Mask data before sharing when needed.
-</Callout>
+<Callout type="warn">Export files may contain sensitive data, account information, business identifiers, or user privacy data. Mask data before sharing when needed.</Callout>
## Recommendations
diff --git a/docs/content/docs/databases.cn.mdx b/docs/content/docs/databases.cn.mdx
index 3668d08070..16f5061347 100644
--- a/docs/content/docs/databases.cn.mdx
+++ b/docs/content/docs/databases.cn.mdx
@@ -3,81 +3,75 @@ title: 数据库支持
description: 了解 DBX 可以连接哪些数据库,以及每类高级功能支持哪些引擎。
---
-<Callout type="info">
-DBX 主应用会尽量使用 Rust 原生驱动。部分数据库通过 MySQL 或 PostgreSQL 兼容协议连接,部分数据库通过 Agent 驱动或可选的 [JDBC 插件](/cn/docs/plugins) 扩展。
-</Callout>
+<Callout type="info">DBX 主应用会尽量使用 Rust 原生驱动。部分数据库通过 MySQL 或 PostgreSQL 兼容协议连接,部分数据库通过 Agent 驱动或可选的 [JDBC 插件](/cn/docs/plugins) 扩展。</Callout>
## 连接类型
新建连接窗口会提供带默认端口和驱动标签的预设类型。
-| 分组 | 类型 | 说明 |
-|---|---|---|
-| 核心 SQL 数据库 | MySQL、PostgreSQL、SQLite、DuckDB、ClickHouse、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB | 直接出现在 DBX 连接选择器中 |
-| 文档与键值数据库 | Redis、MongoDB、Elasticsearch | 根据数据模型使用专门浏览器或查询流程,不完全等同于关系型表格 |
-| MySQL 兼容类型 | MariaDB、TiDB、OceanBase、Doris、SelectDB、StarRocks、GoldenDB、自定义 MySQL | 复用 MySQL 风格连接能力 |
-| PostgreSQL 兼容类型 | KWDB、openGauss、KingBase、HighGo、Vastbase、CockroachDB、自定义 PostgreSQL | 复用 PostgreSQL 风格连接能力 |
-| 文件型数据库 | SQLite、DuckDB、Microsoft Access | 选择本地数据库文件,不填写主机和端口 |
-| Agent/JDBC 扩展类型 | H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、TDengine、虚谷 XuguDB、JDBC | 功能覆盖取决于对应驱动路径 |
+| 分组 | 类型 | 说明 |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
+| 核心 SQL 数据库 | MySQL、PostgreSQL、SQLite、DuckDB、ClickHouse、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB | 直接出现在 DBX 连接选择器中 |
+| 文档与键值数据库 | Redis、MongoDB、Elasticsearch | 根据数据模型使用专门浏览器或查询流程,不完全等同于关系型表格 |
+| MySQL 兼容类型 | MariaDB、TiDB、OceanBase、Doris、SelectDB、StarRocks、GoldenDB、自定义 MySQL | 复用 MySQL 风格连接能力 |
+| PostgreSQL 兼容类型 | KWDB、openGauss、KingBase、HighGo、Vastbase、CockroachDB、自定义 PostgreSQL | 复用 PostgreSQL 风格连接能力 |
+| 文件型数据库 | SQLite、DuckDB、Microsoft Access | 选择本地数据库文件,不填写主机和端口 |
+| Agent/JDBC 扩展类型 | H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、TDengine、虚谷 XuguDB、JDBC | 功能覆盖取决于对应驱动路径 |
## 默认端口
-| 类型 | 默认端口 |
-|---|---:|
-| MySQL / MariaDB / GoldenDB | 3306 |
-| PostgreSQL / openGauss / GaussDB / Vastbase | 5432 |
-| Redis | 6379 |
-| MongoDB | 27017 |
-| ClickHouse | 8123 |
-| SQL Server | 1433 |
-| Oracle | 1521 |
-| Elasticsearch | 9200 |
-| TiDB | 4000 |
-| OceanBase | 2881 |
-| Doris / SelectDB / StarRocks | 9030 |
-| Redshift | 5439 |
-| CockroachDB | 26257 |
-| DM | 5236 |
-| KingBase | 54321 |
-| HighGo | 5866 |
-| H2 | 9092 |
-| Snowflake | 443 |
-| Trino | 8080 |
-| Hive | 10000 |
-| DB2 | 50000 |
-| Informix | 9088 |
-| Neo4j | 7687 |
-| Cassandra | 9042 |
-| BigQuery | 443 |
-| Kylin | 7070 |
-| SunDB | 22000 |
-| TDengine | 6041 |
-| 虚谷 XuguDB | 5138 |
-| KWDB | 26257 |
-
-<Callout type="info">
-SQLite、DuckDB、Access 和 JDBC 在不需要网络端口时,会在连接模型中保存为端口 `0`。
-</Callout>
+| 类型 | 默认端口 |
+| ------------------------------------------- | -------: |
+| MySQL / MariaDB / GoldenDB | 3306 |
+| PostgreSQL / openGauss / GaussDB / Vastbase | 5432 |
+| Redis | 6379 |
+| MongoDB | 27017 |
+| ClickHouse | 8123 |
+| SQL Server | 1433 |
+| Oracle | 1521 |
+| Elasticsearch | 9200 |
+| TiDB | 4000 |
+| OceanBase | 2881 |
+| Doris / SelectDB / StarRocks | 9030 |
+| Redshift | 5439 |
+| CockroachDB | 26257 |
+| DM | 5236 |
+| KingBase | 54321 |
+| HighGo | 5866 |
+| H2 | 9092 |
+| Snowflake | 443 |
+| Trino | 8080 |
+| Hive | 10000 |
+| DB2 | 50000 |
+| Informix | 9088 |
+| Neo4j | 7687 |
+| Cassandra | 9042 |
+| BigQuery | 443 |
+| Kylin | 7070 |
+| SunDB | 22000 |
+| TDengine | 6041 |
+| 虚谷 XuguDB | 5138 |
+| KWDB | 26257 |
+
+<Callout type="info">SQLite、DuckDB、Access 和 JDBC 在不需要网络端口时,会在连接模型中保存为端口 `0`。</Callout>
## 功能矩阵
DBX 只会在具备足够元数据和 SQL 生成能力的数据库上启用高级功能。
-| 功能 | 支持类型 |
-|---|---|
-| Schema 感知树 | PostgreSQL、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、JDBC、H2、Snowflake、Trino、DB2、TDengine、虚谷 XuguDB |
-| ER 图 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、DB2 |
-| 数据库搜索 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DuckDB、ClickHouse、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、TDengine、虚谷 XuguDB |
-| 表数据导入 | MySQL、PostgreSQL、SQLite、DuckDB、ClickHouse、SQL Server、Oracle、Doris、StarRocks、Redshift、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、GoldenDB、Access |
-| 表结构编辑器 | MySQL、PostgreSQL、SQLite、SQL Server、KWDB |
-| 创建数据库 | MySQL、PostgreSQL、SQL Server、ClickHouse、Oracle、DM、GaussDB、KWDB、Doris、StarRocks、Redshift |
-| 字段血缘 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB |
-| 数据传输 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、ClickHouse、DuckDB、DM、GaussDB、KWDB |
-| 不支持 SQL 文件执行 | Redis、MongoDB、Elasticsearch |
-
-<Callout type="warn">
-如果某个数据库可以连接,但没有出现在某个功能行中,该功能可能会被隐藏或受限。这是为了避免 DBX 生成无法可靠审查的 SQL。
-</Callout>
+| 功能 | 支持类型 |
+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Schema 感知树 | PostgreSQL、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、JDBC、H2、Snowflake、Trino、DB2、TDengine、虚谷 XuguDB |
+| ER 图 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、DB2 |
+| 数据库搜索 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DuckDB、ClickHouse、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、TDengine、虚谷 XuguDB |
+| 表数据导入 | MySQL、PostgreSQL、SQLite、DuckDB、ClickHouse、SQL Server、Oracle、Doris、StarRocks、Redshift、DM、GaussDB、KWDB、KingBase、HighGo、Vastbase、GoldenDB、Access |
+| 表结构编辑器 | MySQL、PostgreSQL、SQLite、SQL Server、KWDB |
+| 创建数据库 | MySQL、PostgreSQL、SQL Server、ClickHouse、Oracle、DM、GaussDB、KWDB、Doris、StarRocks、Redshift |
+| 字段血缘 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM、GaussDB、KWDB |
+| 数据传输 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、ClickHouse、DuckDB、DM、GaussDB、KWDB |
+| 不支持 SQL 文件执行 | Redis、MongoDB、Elasticsearch |
+
+<Callout type="warn">如果某个数据库可以连接,但没有出现在某个功能行中,该功能可能会被隐藏或受限。这是为了避免 DBX 生成无法可靠审查的 SQL。</Callout>
## 连接选项
@@ -122,6 +116,7 @@ DM 通过 ODBC 路径连接,需要在运行 DBX 的机器上安装 DM ODBC 驱
Driver = /opt/dmdbms/bin/libdodbc.so
EOF
```
+
</Tab>
<Tab value="Windows">
DM 安装程序通常会自动注册 ODBC 驱动。
diff --git a/docs/content/docs/databases.mdx b/docs/content/docs/databases.mdx
index 5e52f405b3..9913cca91a 100644
--- a/docs/content/docs/databases.mdx
+++ b/docs/content/docs/databases.mdx
@@ -3,81 +3,75 @@ title: Database Support
description: Understand which databases DBX can connect to and which advanced features are available per engine.
---
-<Callout type="info">
-DBX uses native Rust drivers for the main app whenever possible. Some engines are compatibility profiles over MySQL or PostgreSQL protocols, and some are handled through Agent drivers or the optional [JDBC Plugin](/en/docs/plugins).
-</Callout>
+<Callout type="info">DBX uses native Rust drivers for the main app whenever possible. Some engines are compatibility profiles over MySQL or PostgreSQL protocols, and some are handled through Agent drivers or the optional [JDBC Plugin](/en/docs/plugins).</Callout>
## Connection Profiles
The connection dialog exposes ready-to-use profiles with default ports and driver labels.
-| Group | Profiles | Notes |
-|---|---|---|
-| Core SQL engines | MySQL, PostgreSQL, SQLite, DuckDB, ClickHouse, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB | Available directly in the DBX connection picker |
-| Document and key-value engines | Redis, MongoDB, Elasticsearch | Use dedicated browsers or query flows instead of the generic relational grid where appropriate |
-| MySQL-compatible profiles | MariaDB, TiDB, OceanBase, Doris, SelectDB, StarRocks, GoldenDB, custom MySQL | Reuse MySQL-style connection handling where the engine speaks a compatible protocol |
-| PostgreSQL-compatible profiles | KWDB, openGauss, KingBase, HighGo, Vastbase, CockroachDB, custom PostgreSQL | Reuse PostgreSQL-style connection handling where the engine speaks a compatible protocol |
-| File-based engines | SQLite, DuckDB, Microsoft Access | Choose a local database file instead of host and port |
-| Agent/JDBC-oriented engines | H2, Snowflake, Trino, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, TDengine, XuguDB, JDBC | Feature coverage depends on the driver path used by that engine |
+| Group | Profiles | Notes |
+| ------------------------------ | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
+| Core SQL engines | MySQL, PostgreSQL, SQLite, DuckDB, ClickHouse, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB | Available directly in the DBX connection picker |
+| Document and key-value engines | Redis, MongoDB, Elasticsearch | Use dedicated browsers or query flows instead of the generic relational grid where appropriate |
+| MySQL-compatible profiles | MariaDB, TiDB, OceanBase, Doris, SelectDB, StarRocks, GoldenDB, custom MySQL | Reuse MySQL-style connection handling where the engine speaks a compatible protocol |
+| PostgreSQL-compatible profiles | KWDB, openGauss, KingBase, HighGo, Vastbase, CockroachDB, custom PostgreSQL | Reuse PostgreSQL-style connection handling where the engine speaks a compatible protocol |
+| File-based engines | SQLite, DuckDB, Microsoft Access | Choose a local database file instead of host and port |
+| Agent/JDBC-oriented engines | H2, Snowflake, Trino, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, TDengine, XuguDB, JDBC | Feature coverage depends on the driver path used by that engine |
## Default Ports
-| Profile | Default Port |
-|---|---:|
-| MySQL / MariaDB / GoldenDB | 3306 |
-| PostgreSQL / openGauss / GaussDB / Vastbase | 5432 |
-| Redis | 6379 |
-| MongoDB | 27017 |
-| ClickHouse | 8123 |
-| SQL Server | 1433 |
-| Oracle | 1521 |
-| Elasticsearch | 9200 |
-| TiDB | 4000 |
-| OceanBase | 2881 |
-| Doris / SelectDB / StarRocks | 9030 |
-| Redshift | 5439 |
-| CockroachDB | 26257 |
-| DM | 5236 |
-| KingBase | 54321 |
-| HighGo | 5866 |
-| H2 | 9092 |
-| Snowflake | 443 |
-| Trino | 8080 |
-| Hive | 10000 |
-| DB2 | 50000 |
-| Informix | 9088 |
-| Neo4j | 7687 |
-| Cassandra | 9042 |
-| BigQuery | 443 |
-| Kylin | 7070 |
-| SunDB | 22000 |
-| TDengine | 6041 |
-| XuguDB | 5138 |
-| KWDB | 26257 |
-
-<Callout type="info">
-SQLite, DuckDB, Access, and JDBC profiles use port `0` in the saved connection model when a network port is not part of the connection.
-</Callout>
+| Profile | Default Port |
+| ------------------------------------------- | -----------: |
+| MySQL / MariaDB / GoldenDB | 3306 |
+| PostgreSQL / openGauss / GaussDB / Vastbase | 5432 |
+| Redis | 6379 |
+| MongoDB | 27017 |
+| ClickHouse | 8123 |
+| SQL Server | 1433 |
+| Oracle | 1521 |
+| Elasticsearch | 9200 |
+| TiDB | 4000 |
+| OceanBase | 2881 |
+| Doris / SelectDB / StarRocks | 9030 |
+| Redshift | 5439 |
+| CockroachDB | 26257 |
+| DM | 5236 |
+| KingBase | 54321 |
+| HighGo | 5866 |
+| H2 | 9092 |
+| Snowflake | 443 |
+| Trino | 8080 |
+| Hive | 10000 |
+| DB2 | 50000 |
+| Informix | 9088 |
+| Neo4j | 7687 |
+| Cassandra | 9042 |
+| BigQuery | 443 |
+| Kylin | 7070 |
+| SunDB | 22000 |
+| TDengine | 6041 |
+| XuguDB | 5138 |
+| KWDB | 26257 |
+
+<Callout type="info">SQLite, DuckDB, Access, and JDBC profiles use port `0` in the saved connection model when a network port is not part of the connection.</Callout>
## Feature Matrix
DBX intentionally enables advanced workflows only where the app has enough metadata and SQL-generation support.
-| Feature | Supported Types |
-|---|---|
-| Schema-aware tree | PostgreSQL, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, JDBC, H2, Snowflake, Trino, DB2, TDengine, XuguDB |
-| ER diagram | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, DB2 |
-| Database search | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DuckDB, ClickHouse, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, Snowflake, Trino, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, TDengine, XuguDB |
-| Table import | MySQL, PostgreSQL, SQLite, DuckDB, ClickHouse, SQL Server, Oracle, Doris, StarRocks, Redshift, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, GoldenDB, Access |
-| Table structure editor | MySQL, PostgreSQL, SQLite, SQL Server, KWDB |
-| Create database | MySQL, PostgreSQL, SQL Server, ClickHouse, Oracle, DM, GaussDB, KWDB, Doris, StarRocks, Redshift |
-| Field lineage | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB |
-| Data transfer | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, ClickHouse, DuckDB, DM, GaussDB, KWDB |
-| SQL file execution unavailable | Redis, MongoDB, Elasticsearch |
-
-<Callout type="warn">
-If a database can connect but does not appear in a feature row, that feature may be hidden or limited for that engine. This prevents DBX from generating SQL it cannot review reliably.
-</Callout>
+| Feature | Supported Types |
+| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Schema-aware tree | PostgreSQL, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, JDBC, H2, Snowflake, Trino, DB2, TDengine, XuguDB |
+| ER diagram | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, DB2 |
+| Database search | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DuckDB, ClickHouse, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, Snowflake, Trino, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, TDengine, XuguDB |
+| Table import | MySQL, PostgreSQL, SQLite, DuckDB, ClickHouse, SQL Server, Oracle, Doris, StarRocks, Redshift, DM, GaussDB, KWDB, KingBase, HighGo, Vastbase, GoldenDB, Access |
+| Table structure editor | MySQL, PostgreSQL, SQLite, SQL Server, KWDB |
+| Create database | MySQL, PostgreSQL, SQL Server, ClickHouse, Oracle, DM, GaussDB, KWDB, Doris, StarRocks, Redshift |
+| Field lineage | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, GaussDB, KWDB |
+| Data transfer | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, ClickHouse, DuckDB, DM, GaussDB, KWDB |
+| SQL file execution unavailable | Redis, MongoDB, Elasticsearch |
+
+<Callout type="warn">If a database can connect but does not appear in a feature row, that feature may be hidden or limited for that engine. This prevents DBX from generating SQL it cannot review reliably.</Callout>
## Connection Options
@@ -124,6 +118,7 @@ DM uses an ODBC-based path and requires the DM ODBC driver installed on the mach
Driver = /opt/dmdbms/bin/libdodbc.so
EOF
```
+
</Tab>
<Tab value="Windows">
The DM installer normally registers the ODBC driver automatically.
diff --git a/docs/content/docs/driver-management.cn.mdx b/docs/content/docs/driver-management.cn.mdx
index e0b076bcbd..6af9429fab 100644
--- a/docs/content/docs/driver-management.cn.mdx
+++ b/docs/content/docs/driver-management.cn.mdx
@@ -7,14 +7,12 @@ DBX 使用混合驱动架构:常用数据库使用内置原生驱动,需要
## 驱动架构
-| 驱动类型 | 工作方式 | 适用场景 |
-|---|---|---|
-| 原生(内置) | Rust 驱动编译进 DBX | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redis、MongoDB、DuckDB、ClickHouse 等 |
-| JDBC Agent | DBX 管理的 Java 子进程 | 提供 JDBC 驱动的数据库:GaussDB、openGauss、DM、KingBase、HighGo、Vastbase、Trino、Hive、DB2、Informix、Neo4j、TDengine、虚谷 XuguDB、YashanDB、GoldenDB、Kylin、SunDB 等 |
+| 驱动类型 | 工作方式 | 适用场景 |
+| ------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 原生(内置) | Rust 驱动编译进 DBX | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redis、MongoDB、DuckDB、ClickHouse 等 |
+| JDBC Agent | DBX 管理的 Java 子进程 | 提供 JDBC 驱动的数据库:GaussDB、openGauss、DM、KingBase、HighGo、Vastbase、Trino、Hive、DB2、Informix、Neo4j、TDengine、虚谷 XuguDB、YashanDB、GoldenDB、Kylin、SunDB 等 |
-<Callout type="info">
-原生驱动安装后立即可用。Agent 驱动需要一次性下载 JDBC 驱动和 JRE 设置,首次创建连接时 DBX 会自动处理。
-</Callout>
+<Callout type="info">原生驱动安装后立即可用。Agent 驱动需要一次性下载 JDBC 驱动和 JRE 设置,首次创建连接时 DBX 会自动处理。</Callout>
## 驱动商店
@@ -29,22 +27,10 @@ DBX 使用混合驱动架构:常用数据库使用内置原生驱动,需要
## 安装驱动
<Steps>
- <Step>
- ### 打开驱动商店
- 导航到**设置 → 驱动**或点击连接对话框中的驱动安装提示。
- </Step>
- <Step>
- ### 选择驱动
- 找到所需的数据库驱动。每个条目显示支持的数据库和驱动版本。
- </Step>
- <Step>
- ### 点击安装
- DBX 会下载 JDBC 驱动 JAR 及所需的依赖项。下载过程中显示进度。
- </Step>
- <Step>
- ### 创建连接
- 返回连接对话框。驱动此时即可使用。
- </Step>
+ <Step>### 打开驱动商店 导航到**设置 → 驱动**或点击连接对话框中的驱动安装提示。</Step>
+ <Step>### 选择驱动 找到所需的数据库驱动。每个条目显示支持的数据库和驱动版本。</Step>
+ <Step>### 点击安装 DBX 会下载 JDBC 驱动 JAR 及所需的依赖项。下载过程中显示进度。</Step>
+ <Step>### 创建连接 返回连接对话框。驱动此时即可使用。</Step>
</Steps>
## JRE 管理
@@ -80,9 +66,9 @@ DBX 会定期检查驱动更新:
## 故障排除
-| 问题 | 解决方案 |
-|---|---|
-| 驱动下载失败 | 检查网络连接和防火墙规则。尝试离线导入方法。 |
-| Agent 无法启动 | 在驱动商店中验证 JRE 安装。如需要,重新安装托管 JRE。 |
+| 问题 | 解决方案 |
+| ---------------------- | ----------------------------------------------------------- |
+| 驱动下载失败 | 检查网络连接和防火墙规则。尝试离线导入方法。 |
+| Agent 无法启动 | 在驱动商店中验证 JRE 安装。如需要,重新安装托管 JRE。 |
| 驱动安装后连接测试失败 | 确认 JDBC URL 格式与驱动的预期格式匹配。检查 SSH/代理设置。 |
-| 驱动版本错误 | 卸载当前驱动并从商店安装正确版本。 |
+| 驱动版本错误 | 卸载当前驱动并从商店安装正确版本。 |
diff --git a/docs/content/docs/driver-management.mdx b/docs/content/docs/driver-management.mdx
index a1eda4708e..a0e5670b2c 100644
--- a/docs/content/docs/driver-management.mdx
+++ b/docs/content/docs/driver-management.mdx
@@ -7,14 +7,12 @@ DBX uses a hybrid driver architecture: built-in native drivers for common databa
## Driver Architecture
-| Driver Type | How It Works | Best For |
-|---|---|---|
-| Native (built-in) | Rust drivers compiled into DBX | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redis, MongoDB, DuckDB, ClickHouse, and more |
-| JDBC Agent | Java subprocess managed by DBX | Databases that provide JDBC drivers: GaussDB, openGauss, DM, KingBase, HighGo, Vastbase, Trino, Hive, DB2, Informix, Neo4j, TDengine, XuguDB, YashanDB, GoldenDB, Kylin, SunDB, and more |
+| Driver Type | How It Works | Best For |
+| ----------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Native (built-in) | Rust drivers compiled into DBX | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redis, MongoDB, DuckDB, ClickHouse, and more |
+| JDBC Agent | Java subprocess managed by DBX | Databases that provide JDBC drivers: GaussDB, openGauss, DM, KingBase, HighGo, Vastbase, Trino, Hive, DB2, Informix, Neo4j, TDengine, XuguDB, YashanDB, GoldenDB, Kylin, SunDB, and more |
-<Callout type="info">
-Native drivers work immediately after installation. Agent drivers require a one-time JDBC driver download and JRE setup, which DBX handles automatically when you first create a connection.
-</Callout>
+<Callout type="info">Native drivers work immediately after installation. Agent drivers require a one-time JDBC driver download and JRE setup, which DBX handles automatically when you first create a connection.</Callout>
## Driver Store
@@ -29,22 +27,10 @@ Open the Driver Store from **Settings → Drivers** or click the driver hint tha
## Installing Drivers
<Steps>
- <Step>
- ### Open Driver Store
- Navigate to **Settings → Drivers** or click the driver install hint in the connection dialog.
- </Step>
- <Step>
- ### Choose a Driver
- Find the database driver you need. Each entry shows the supported database and driver version.
- </Step>
- <Step>
- ### Click Install
- DBX downloads the JDBC driver JAR and any required dependencies. Progress is shown during download.
- </Step>
- <Step>
- ### Create a Connection
- Return to the connection dialog. The driver is now ready for use.
- </Step>
+ <Step>### Open Driver Store Navigate to **Settings → Drivers** or click the driver install hint in the connection dialog.</Step>
+ <Step>### Choose a Driver Find the database driver you need. Each entry shows the supported database and driver version.</Step>
+ <Step>### Click Install DBX downloads the JDBC driver JAR and any required dependencies. Progress is shown during download.</Step>
+ <Step>### Create a Connection Return to the connection dialog. The driver is now ready for use.</Step>
</Steps>
## JRE Management
@@ -80,9 +66,9 @@ For databases supported by the [JDBC Plugin](/en/docs/plugins), DBX shows update
## Troubleshooting
-| Problem | Solution |
-|---|---|
-| Driver download fails | Check network connectivity and firewall rules. Try the offline import method. |
-| Agent won't start | Verify JRE installation in Driver Store. Reinstall the managed JRE if needed. |
+| Problem | Solution |
+| ------------------------------------------ | ------------------------------------------------------------------------------------------- |
+| Driver download fails | Check network connectivity and firewall rules. Try the offline import method. |
+| Agent won't start | Verify JRE installation in Driver Store. Reinstall the managed JRE if needed. |
| Connection test fails after driver install | Confirm the JDBC URL format matches the driver's expected format. Check SSH/proxy settings. |
-| Wrong driver version | Uninstall the current driver and install the correct version from the store. |
+| Wrong driver version | Uninstall the current driver and install the correct version from the store. |
diff --git a/docs/content/docs/field-lineage.cn.mdx b/docs/content/docs/field-lineage.cn.mdx
index 9c3cacf6e7..4301f9a8b3 100644
--- a/docs/content/docs/field-lineage.cn.mdx
+++ b/docs/content/docs/field-lineage.cn.mdx
@@ -5,9 +5,7 @@ description: 追踪字段之间的来源、引用和潜在关联,辅助理解
字段血缘用于回答一个常见问题:某个字段的数据从哪里来,又可能影响到哪里。它适合理解复杂库、排查影响范围和阅读历史结构。
-<Callout type="info">
-字段血缘目前支持 MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM 和 GaussDB。其他引擎可能无法提供足够的关系元数据,因此不会展示完整血缘。
-</Callout>
+<Callout type="info">字段血缘目前支持 MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM 和 GaussDB。其他引擎可能无法提供足够的关系元数据,因此不会展示完整血缘。</Callout>
## 能解决什么问题
@@ -18,16 +16,14 @@ description: 追踪字段之间的来源、引用和潜在关联,辅助理解
## 关系来源
-| 来源 | 可信度 | 说明 |
-|---|---|---|
-| 外键 | 高 | 数据库中已经声明的外键约束 |
-| 视图 | 高 | 从视图定义中分析字段映射 |
-| 查询历史 | 中 | 从执行过的 SQL 中分析 `JOIN`、`WHERE` 等引用关系 |
-| 同名字段 | 低到中 | 根据字段名称相似性推断可能关系 |
+| 来源 | 可信度 | 说明 |
+| -------- | ------ | ------------------------------------------------ |
+| 外键 | 高 | 数据库中已经声明的外键约束 |
+| 视图 | 高 | 从视图定义中分析字段映射 |
+| 查询历史 | 中 | 从执行过的 SQL 中分析 `JOIN`、`WHERE` 等引用关系 |
+| 同名字段 | 低到中 | 根据字段名称相似性推断可能关系 |
-<Callout type="info">
-字段血缘是辅助分析工具,不等同于数据治理平台里的强一致血缘。对关键结论,请结合数据库约束、视图定义和业务代码确认。
-</Callout>
+<Callout type="info">字段血缘是辅助分析工具,不等同于数据治理平台里的强一致血缘。对关键结论,请结合数据库约束、视图定义和业务代码确认。</Callout>
## 查看方式
diff --git a/docs/content/docs/field-lineage.mdx b/docs/content/docs/field-lineage.mdx
index 18e5422cab..929a7a9b54 100644
--- a/docs/content/docs/field-lineage.mdx
+++ b/docs/content/docs/field-lineage.mdx
@@ -5,9 +5,7 @@ description: Trace where columns come from, how they are referenced, and which r
Field Lineage helps answer a common question: where does a column's data come from, and what might depend on it? Use it to understand complex schemas, inspect impact, and read legacy structures.
-<Callout type="info">
-Field Lineage is enabled for MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, and GaussDB. Other engines may not expose enough relationship metadata for DBX to build useful lineage.
-</Callout>
+<Callout type="info">Field Lineage is enabled for MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, and GaussDB. Other engines may not expose enough relationship metadata for DBX to build useful lineage.</Callout>
## What It Helps With
@@ -18,16 +16,14 @@ Field Lineage is enabled for MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Reds
## Relationship Sources
-| Source | Confidence | Details |
-|---|---|---|
-| Foreign keys | High | Constraints declared in the database |
-| Views | High | Field mappings analyzed from view definitions |
-| Query history | Medium | Relationships inferred from executed SQL, including `JOIN` and `WHERE` usage |
-| Same-name columns | Low to medium | Possible relationships inferred from similar column names |
+| Source | Confidence | Details |
+| ----------------- | ------------- | ---------------------------------------------------------------------------- |
+| Foreign keys | High | Constraints declared in the database |
+| Views | High | Field mappings analyzed from view definitions |
+| Query history | Medium | Relationships inferred from executed SQL, including `JOIN` and `WHERE` usage |
+| Same-name columns | Low to medium | Possible relationships inferred from similar column names |
-<Callout type="info">
-Field Lineage is an analysis aid, not a strongly governed lineage platform. For critical decisions, confirm results with database constraints, view definitions, and application code.
-</Callout>
+<Callout type="info">Field Lineage is an analysis aid, not a strongly governed lineage platform. For critical decisions, confirm results with database constraints, view definitions, and application code.</Callout>
## Navigation
diff --git a/docs/content/docs/getting-started.cn.mdx b/docs/content/docs/getting-started.cn.mdx
index f9327f3603..7c52a5344c 100644
--- a/docs/content/docs/getting-started.cn.mdx
+++ b/docs/content/docs/getting-started.cn.mdx
@@ -26,6 +26,7 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
```
也可以从 [GitHub Releases](https://github.com/t8y2/dbx/releases) 下载 `.dmg` 安装包。
+
</Tab>
<Tab value="Windows">
使用 Scoop 安装:
@@ -42,6 +43,7 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
```
也可以从 [GitHub Releases](https://github.com/t8y2/dbx/releases) 下载 `.msi` 安装包。
+
</Tab>
<Tab value="Linux">
从 [GitHub Releases](https://github.com/t8y2/dbx/releases) 下载对应安装包:
@@ -56,6 +58,7 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
```bash
chmod +x DBX*.AppImage
```
+
</Tab>
<Tab value="Docker">
Docker 版本适合部署在服务器上,并通过浏览器访问:
@@ -85,19 +88,18 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
volumes:
dbx-data:
```
+
</Tab>
</Tabs>
## 桌面版还是 Docker
-| 模式 | 适合场景 | 后端路径 | 存储位置 |
-|---|---|---|---|
-| 桌面版 | 本机日常工作、本地文件、原生窗口、从 MCP 打开 DBX 界面 | Tauri 命令调用 Rust core | 本机应用数据目录 |
-| Docker / Web | 服务器自托管、浏览器访问 | HTTP 路由调用同一套 Rust core | Docker volume 或服务器数据目录 |
+| 模式 | 适合场景 | 后端路径 | 存储位置 |
+| ------------ | ------------------------------------------------------ | ----------------------------- | ------------------------------ |
+| 桌面版 | 本机日常工作、本地文件、原生窗口、从 MCP 打开 DBX 界面 | Tauri 命令调用 Rust core | 本机应用数据目录 |
+| Docker / Web | 服务器自托管、浏览器访问 | HTTP 路由调用同一套 Rust core | Docker volume 或服务器数据目录 |
-<Callout type="info">
-核心数据库能力保持一致,但通过 MCP 打开桌面窗口等集成需要 DBX 桌面版正在运行。
-</Callout>
+<Callout type="info">核心数据库能力保持一致,但通过 MCP 打开桌面窗口等集成需要 DBX 桌面版正在运行。</Callout>
## 创建第一个连接
@@ -106,37 +108,41 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
### 打开新建连接
在侧边栏或工具栏中点击 **新建连接**。
+
</Step>
<Step>
### 选择数据库类型
选择 MySQL、PostgreSQL、SQLite、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle,或 [数据库支持](/cn/docs/databases) 中列出的兼容类型、Agent/JDBC 类型。
+
</Step>
<Step>
### 填写连接信息
网络数据库需要填写主机、端口、用户名、密码和必要的默认数据库。SQLite、DuckDB、Access 这类文件型数据库需要选择本地数据库文件,不填写主机和端口。
+
</Step>
<Step>
### 有 URL 时直接粘贴
DBX 可以解析常见连接 URL,例如 MySQL、PostgreSQL、Redis、MongoDB、ClickHouse、SQL Server、Oracle、Elasticsearch、DM、GaussDB、openGauss、TDengine 和 Access。保存前请检查解析出的字段。
+
</Step>
<Step>
### 配置网络选项
如果数据库在内网或跳板机后面,可以启用 [SSH 隧道](/cn/docs/ssh-tunnel)。如果网络环境要求 SOCKS5 或 HTTP 代理,可以在代理页签中配置。
+
</Step>
<Step>
### 测试并保存
点击 **测试** 验证账号、网络和权限。测试通过后保存连接,并从侧边栏打开。
+
</Step>
</Steps>
-<Callout type="info">
-连接密码、SSH 密码、SSH 密钥密码和连接字符串会与普通连接 JSON 分开存储在 DBX 本地数据中。需要迁移加密连接配置时,使用 [配置导出/导入](/cn/docs/config-export)。
-</Callout>
+<Callout type="info">连接密码、SSH 密码、SSH 密钥密码和连接字符串会与普通连接 JSON 分开存储在 DBX 本地数据中。需要迁移加密连接配置时,使用 [配置导出/导入](/cn/docs/config-export)。</Callout>
## 降低生产误操作
@@ -161,12 +167,12 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
## 常见连接问题
-| 现象 | 检查项 |
-|---|---|
-| 连接超时 | 主机、端口、防火墙、安全组、VPN、Docker 主机网络或内网访问权限 |
-| 认证失败 | 用户名、密码、认证方式、SSL 要求、账号是否允许远程登录 |
-| 能连接但看不到表 | 默认数据库、Schema、权限、元数据读取权限、可见数据库过滤 |
-| 文件数据库打不开 | 文件路径、文件权限、Docker volume 挂载、文件扩展名是否支持 |
+| 现象 | 检查项 |
+| ------------------ | -------------------------------------------------------------- |
+| 连接超时 | 主机、端口、防火墙、安全组、VPN、Docker 主机网络或内网访问权限 |
+| 认证失败 | 用户名、密码、认证方式、SSL 要求、账号是否允许远程登录 |
+| 能连接但看不到表 | 默认数据库、Schema、权限、元数据读取权限、可见数据库过滤 |
+| 文件数据库打不开 | 文件路径、文件权限、Docker volume 挂载、文件扩展名是否支持 |
| 内网数据库无法访问 | 配置 SSH 隧道、代理、VPN,或让 Docker 部署机器能访问目标数据库 |
## 从源码运行
@@ -181,20 +187,10 @@ description: 安装 DBX、创建第一个连接,并了解桌面版、Docker
### 系统依赖
-<Tabs groupId="dev-platform" items={['macOS', 'Linux', 'Windows']}>
- <Tab value="macOS">
- ```bash
- brew install unixodbc
- ```
- </Tab>
- <Tab value="Linux">
- ```bash
- sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev unixodbc-dev
- ```
- </Tab>
- <Tab value="Windows">
- Windows 通常不需要额外安装系统依赖。
- </Tab>
+<Tabs groupId="dev-platform" items={["macOS", "Linux", "Windows"]}>
+ <Tab value="macOS">```bash brew install unixodbc ```</Tab>
+ <Tab value="Linux">```bash sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev unixodbc-dev ```</Tab>
+ <Tab value="Windows">Windows 通常不需要额外安装系统依赖。</Tab>
</Tabs>
### 启动开发环境
diff --git a/docs/content/docs/getting-started.mdx b/docs/content/docs/getting-started.mdx
index 83127ff4d2..b5bff71031 100644
--- a/docs/content/docs/getting-started.mdx
+++ b/docs/content/docs/getting-started.mdx
@@ -26,6 +26,7 @@ This guide gets you through three things:
```
You can also download a `.dmg` installer from [GitHub Releases](https://github.com/t8y2/dbx/releases).
+
</Tab>
<Tab value="Windows">
Install with Scoop:
@@ -42,6 +43,7 @@ This guide gets you through three things:
```
You can also download a `.msi` installer from [GitHub Releases](https://github.com/t8y2/dbx/releases).
+
</Tab>
<Tab value="Linux">
Download a package from [GitHub Releases](https://github.com/t8y2/dbx/releases):
@@ -56,6 +58,7 @@ This guide gets you through three things:
```bash
chmod +x DBX*.AppImage
```
+
</Tab>
<Tab value="Docker">
Docker is for self-hosting DBX on a server and opening it from a browser:
@@ -85,19 +88,18 @@ This guide gets you through three things:
volumes:
dbx-data:
```
+
</Tab>
</Tabs>
## Desktop Or Docker
-| Mode | Best For | Backend Path | Storage |
-|---|---|---|---|
-| Desktop | Daily local work, local files, native windows, DBX UI opened from MCP | Tauri commands calling the Rust core | Local app data directory |
-| Docker / Web | Self-hosted access from a server or browser | HTTP routes calling the same Rust core | Docker volume or server data directory |
+| Mode | Best For | Backend Path | Storage |
+| ------------ | --------------------------------------------------------------------- | -------------------------------------- | -------------------------------------- |
+| Desktop | Daily local work, local files, native windows, DBX UI opened from MCP | Tauri commands calling the Rust core | Local app data directory |
+| Docker / Web | Self-hosted access from a server or browser | HTTP routes calling the same Rust core | Docker volume or server data directory |
-<Callout type="info">
-The core database features are shared, but desktop-only integrations such as opening DBX windows from MCP require the desktop app to be running.
-</Callout>
+<Callout type="info">The core database features are shared, but desktop-only integrations such as opening DBX windows from MCP require the desktop app to be running.</Callout>
## Create Your First Connection
@@ -106,37 +108,41 @@ The core database features are shared, but desktop-only integrations such as ope
### Open New Connection
Click **New Connection** from the sidebar or toolbar.
+
</Step>
<Step>
### Pick A Database Type
Choose a built-in profile such as MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, or one of the compatibility and Agent/JDBC profiles listed in [Database Support](/en/docs/databases).
+
</Step>
<Step>
### Fill Connection Details
For network databases, enter host, port, username, password, and default database when needed. For SQLite, DuckDB, and Access, select a local database file instead of host and port.
+
</Step>
<Step>
### Paste A URL When Available
DBX can parse common connection URLs for engines such as MySQL, PostgreSQL, Redis, MongoDB, ClickHouse, SQL Server, Oracle, Elasticsearch, DM, GaussDB, openGauss, TDengine, and Access. Review the parsed fields before saving.
+
</Step>
<Step>
### Add Network Options
Enable [SSH Tunnel](/en/docs/ssh-tunnel) for databases behind private networks or bastion hosts. Use the proxy tab when your environment requires SOCKS5 or HTTP proxy access.
+
</Step>
<Step>
### Test And Save
Click **Test** to verify credentials, network access, and permissions. After the test passes, save the connection and open it from the sidebar.
+
</Step>
</Steps>
-<Callout type="info">
-Connection passwords, SSH passwords, SSH key passphrases, and connection strings are stored separately from the regular connection JSON in DBX's local storage. Use [Config Export/Import](/en/docs/config-export) when you need to migrate encrypted connection settings.
-</Callout>
+<Callout type="info">Connection passwords, SSH passwords, SSH key passphrases, and connection strings are stored separately from the regular connection JSON in DBX's local storage. Use [Config Export/Import](/en/docs/config-export) when you need to migrate encrypted connection settings.</Callout>
## Reduce Production Mistakes
@@ -161,13 +167,13 @@ Connection passwords, SSH passwords, SSH key passphrases, and connection strings
## Common Connection Problems
-| Symptom | Check |
-|---|---|
-| Timeout | Host, port, firewall, security group, VPN, Docker host reachability, or private network access |
-| Authentication failed | Username, password, auth mode, SSL requirement, remote login permission |
-| Connected but no tables | Default database, schema, permissions, metadata read access, visible database filter |
-| File database cannot open | File path, file permissions, mounted Docker volume, or unsupported file extension |
-| Private database unreachable | Configure SSH tunnel, proxy, VPN, or run Docker on a machine that can reach the database |
+| Symptom | Check |
+| ---------------------------- | ---------------------------------------------------------------------------------------------- |
+| Timeout | Host, port, firewall, security group, VPN, Docker host reachability, or private network access |
+| Authentication failed | Username, password, auth mode, SSL requirement, remote login permission |
+| Connected but no tables | Default database, schema, permissions, metadata read access, visible database filter |
+| File database cannot open | File path, file permissions, mounted Docker volume, or unsupported file extension |
+| Private database unreachable | Configure SSH tunnel, proxy, VPN, or run Docker on a machine that can reach the database |
## Run From Source
@@ -181,20 +187,10 @@ Use source mode when contributing or debugging DBX locally.
### System Dependencies
-<Tabs groupId="dev-platform" items={['macOS', 'Linux', 'Windows']}>
- <Tab value="macOS">
- ```bash
- brew install unixodbc
- ```
- </Tab>
- <Tab value="Linux">
- ```bash
- sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev unixodbc-dev
- ```
- </Tab>
- <Tab value="Windows">
- Windows usually needs no extra system dependency for local DBX development.
- </Tab>
+<Tabs groupId="dev-platform" items={["macOS", "Linux", "Windows"]}>
+ <Tab value="macOS">```bash brew install unixodbc ```</Tab>
+ <Tab value="Linux">```bash sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev unixodbc-dev ```</Tab>
+ <Tab value="Windows">Windows usually needs no extra system dependency for local DBX development.</Tab>
</Tabs>
### Start Development
diff --git a/docs/content/docs/keyboard-shortcuts.cn.mdx b/docs/content/docs/keyboard-shortcuts.cn.mdx
index 604e4a0639..561f275081 100644
--- a/docs/content/docs/keyboard-shortcuts.cn.mdx
+++ b/docs/content/docs/keyboard-shortcuts.cn.mdx
@@ -9,34 +9,34 @@ DBX 为常用操作提供可配置的键盘快捷键。使用默认快捷键或
### 查询编辑器
-| 快捷键 | 操作 |
-|---|---|
-| `Ctrl+Enter` / `Cmd+Enter` | 执行当前查询 |
-| `Ctrl+Shift+Enter` / `Cmd+Shift+Enter` | 执行所有查询 |
-| `Ctrl+/` / `Cmd+/` | 切换行注释 |
-| `Ctrl+F` / `Cmd+F` | 在编辑器中搜索 |
-| `Ctrl+S` / `Cmd+S` | 保存当前标签页 |
-| `Tab` | 缩进选中行 |
-| `Shift+Tab` | 取消缩进选中行 |
+| 快捷键 | 操作 |
+| -------------------------------------- | -------------- |
+| `Ctrl+Enter` / `Cmd+Enter` | 执行当前查询 |
+| `Ctrl+Shift+Enter` / `Cmd+Shift+Enter` | 执行所有查询 |
+| `Ctrl+/` / `Cmd+/` | 切换行注释 |
+| `Ctrl+F` / `Cmd+F` | 在编辑器中搜索 |
+| `Ctrl+S` / `Cmd+S` | 保存当前标签页 |
+| `Tab` | 缩进选中行 |
+| `Shift+Tab` | 取消缩进选中行 |
### 数据表格
-| 快捷键 | 操作 |
-|---|---|
-| `F5` | 刷新当前数据 |
-| `Ctrl+C` / `Cmd+C` | 复制选中单元格 |
-| `Ctrl+Shift+C` / `Cmd+Shift+C` | 将选中行复制为 INSERT |
-| `Delete` | 删除选中行(标记为待删除) |
+| 快捷键 | 操作 |
+| ------------------------------ | -------------------------- |
+| `F5` | 刷新当前数据 |
+| `Ctrl+C` / `Cmd+C` | 复制选中单元格 |
+| `Ctrl+Shift+C` / `Cmd+Shift+C` | 将选中行复制为 INSERT |
+| `Delete` | 删除选中行(标记为待删除) |
### 导航
-| 快捷键 | 操作 |
-|---|---|
-| `Ctrl+N` / `Cmd+N` | 新建查询标签页 |
+| 快捷键 | 操作 |
+| ------------------------------ | -------------- |
+| `Ctrl+N` / `Cmd+N` | 新建查询标签页 |
| `Ctrl+Shift+F` / `Cmd+Shift+F` | 聚焦侧边栏搜索 |
-| `Ctrl+,` / `Cmd+,` | 打开设置 |
-| `Ctrl+W` / `Cmd+W` | 关闭当前标签页 |
-| `鼠标中键`(点击标签页) | 关闭标签页 |
+| `Ctrl+,` / `Cmd+,` | 打开设置 |
+| `Ctrl+W` / `Cmd+W` | 关闭当前标签页 |
+| `鼠标中键`(点击标签页) | 关闭标签页 |
## 配置快捷键
@@ -47,9 +47,7 @@ DBX 为常用操作提供可配置的键盘快捷键。使用默认快捷键或
3. 按下新的按键组合
4. 新快捷键自动保存
-<Callout type="info">
-快捷键使用 Electron 风格的修饰键表示法:`Ctrl`(Windows/Linux 的 Control)、`Cmd`(macOS 的 Command)、`Shift` 和 `Alt`(macOS 的 Option)。
-</Callout>
+<Callout type="info">快捷键使用 Electron 风格的修饰键表示法:`Ctrl`(Windows/Linux 的 Control)、`Cmd`(macOS 的 Command)、`Shift` 和 `Alt`(macOS 的 Option)。</Callout>
## 复制快捷键
diff --git a/docs/content/docs/keyboard-shortcuts.mdx b/docs/content/docs/keyboard-shortcuts.mdx
index b6d007e48a..8a214f814a 100644
--- a/docs/content/docs/keyboard-shortcuts.mdx
+++ b/docs/content/docs/keyboard-shortcuts.mdx
@@ -9,34 +9,34 @@ DBX provides configurable keyboard shortcuts for common actions. Use the default
### Query Editor
-| Shortcut | Action |
-|---|---|
-| `Ctrl+Enter` / `Cmd+Enter` | Execute current query |
-| `Ctrl+Shift+Enter` / `Cmd+Shift+Enter` | Execute all queries |
-| `Ctrl+/` / `Cmd+/` | Toggle line comment |
-| `Ctrl+F` / `Cmd+F` | Search in editor |
-| `Ctrl+S` / `Cmd+S` | Save current tab |
-| `Tab` | Indent selected lines |
-| `Shift+Tab` | Outdent selected lines |
+| Shortcut | Action |
+| -------------------------------------- | ---------------------- |
+| `Ctrl+Enter` / `Cmd+Enter` | Execute current query |
+| `Ctrl+Shift+Enter` / `Cmd+Shift+Enter` | Execute all queries |
+| `Ctrl+/` / `Cmd+/` | Toggle line comment |
+| `Ctrl+F` / `Cmd+F` | Search in editor |
+| `Ctrl+S` / `Cmd+S` | Save current tab |
+| `Tab` | Indent selected lines |
+| `Shift+Tab` | Outdent selected lines |
### Data Grid
-| Shortcut | Action |
-|---|---|
-| `F5` | Refresh current data |
-| `Ctrl+C` / `Cmd+C` | Copy selected cells |
-| `Ctrl+Shift+C` / `Cmd+Shift+C` | Copy selected rows as INSERT |
-| `Delete` | Delete selected rows (mark for deletion) |
+| Shortcut | Action |
+| ------------------------------ | ---------------------------------------- |
+| `F5` | Refresh current data |
+| `Ctrl+C` / `Cmd+C` | Copy selected cells |
+| `Ctrl+Shift+C` / `Cmd+Shift+C` | Copy selected rows as INSERT |
+| `Delete` | Delete selected rows (mark for deletion) |
### Navigation
-| Shortcut | Action |
-|---|---|
-| `Ctrl+N` / `Cmd+N` | New query tab |
+| Shortcut | Action |
+| ------------------------------ | -------------------- |
+| `Ctrl+N` / `Cmd+N` | New query tab |
| `Ctrl+Shift+F` / `Cmd+Shift+F` | Focus sidebar search |
-| `Ctrl+,` / `Cmd+,` | Open settings |
-| `Ctrl+W` / `Cmd+W` | Close current tab |
-| `Middle Click` (on tab) | Close tab |
+| `Ctrl+,` / `Cmd+,` | Open settings |
+| `Ctrl+W` / `Cmd+W` | Close current tab |
+| `Middle Click` (on tab) | Close tab |
## Configuring Shortcuts
@@ -47,9 +47,7 @@ Open **Settings → Shortcuts** to customize key bindings:
3. Press the new key combination
4. The new shortcut is saved automatically
-<Callout type="info">
-Shortcuts use the Electron-style modifier key notation: `Ctrl` (Control on Windows/Linux), `Cmd` (Command on macOS), `Shift`, and `Alt` (Option on macOS).
-</Callout>
+<Callout type="info">Shortcuts use the Electron-style modifier key notation: `Ctrl` (Control on Windows/Linux), `Cmd` (Command on macOS), `Shift`, and `Alt` (Option on macOS).</Callout>
## Copy Shortcuts
diff --git a/docs/content/docs/mcp.cn.mdx b/docs/content/docs/mcp.cn.mdx
index ccbe62cff8..ce655b1d2e 100644
--- a/docs/content/docs/mcp.cn.mdx
+++ b/docs/content/docs/mcp.cn.mdx
@@ -3,9 +3,7 @@ title: MCP 集成
description: 通过 MCP 协议让 Claude Code、Cursor 等 AI 编程助手直接查询你的数据库。
---
-<Callout type="info">
-一行配置,让 AI 编程助手直接查询你的数据库。支持 Claude Code、Cursor、Windsurf、VS Code Copilot。
-</Callout>
+<Callout type="info">一行配置,让 AI 编程助手直接查询你的数据库。支持 Claude Code、Cursor、Windsurf、VS Code Copilot。</Callout>
## 什么是 MCP?
@@ -28,6 +26,7 @@ AI 助手 → MCP Server → 你的数据库 → 返回结果
```bash
npm install -g @dbx-app/mcp-server
```
+
</Step>
<Step>
### 配置 AI 助手
@@ -44,6 +43,7 @@ AI 助手 → MCP Server → 你的数据库 → 返回结果
}
}
```
+
</Step>
<Step>
### 开始使用
@@ -55,17 +55,18 @@ AI 助手 → MCP Server → 你的数据库 → 返回结果
- "查看 users 表的结构"
- "查询最近 7 天的订单数量"
- "打开 orders 表"(需要 DBX 运行中)
+
</Step>
</Steps>
## 支持的 AI 助手
-| 助手 | 配置方式 |
-|---|---|
-| Claude Code | `.mcp.json`(原生支持) |
-| Cursor | `.cursor/mcp.json` |
-| Windsurf | `.windsurfrules` |
-| VS Code + Copilot | MCP 扩展 |
+| 助手 | 配置方式 |
+| ----------------- | ----------------------- |
+| Claude Code | `.mcp.json`(原生支持) |
+| Cursor | `.cursor/mcp.json` |
+| Windsurf | `.windsurfrules` |
+| VS Code + Copilot | MCP 扩展 |
## 工具列表
@@ -76,9 +77,11 @@ DBX MCP Server 提供以下工具,AI 助手会根据你的需求自动调用
列出 DBX 中所有已配置的数据库连接。
**示例对话:**
+
> "列出我的数据库连接"
**返回:**
+
```
| Name | Type | Host | Port | Database |
| -------- | -------- | --------- | ---- | -------- |
@@ -90,22 +93,23 @@ DBX MCP Server 提供以下工具,AI 助手会根据你的需求自动调用
列出指定连接的表和视图。
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | DBX 连接名称 |
-| `schema` | 否 | Schema 名称(默认 public) |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | -------------------------- |
+| `connection_name` | 是 | DBX 连接名称 |
+| `schema` | 否 | Schema 名称(默认 public) |
### `dbx_describe_table`
获取表的列定义,AI 用它来理解你的数据结构。
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | DBX 连接名称 |
-| `table` | 是 | 表名 |
-| `schema` | 否 | Schema 名称(默认 public) |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | -------------------------- |
+| `connection_name` | 是 | DBX 连接名称 |
+| `table` | 是 | 表名 |
+| `schema` | 否 | Schema 名称(默认 public) |
**返回:**
+
```
| Column | Type | Nullable | Default | Comment |
| ----------- | --------- | -------- | ------- | ------- |
@@ -119,61 +123,63 @@ DBX MCP Server 提供以下工具,AI 助手会根据你的需求自动调用
执行 SQL 查询,返回结果(最多 100 行)。
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | DBX 连接名称 |
-| `sql` | 是 | SQL 查询语句 |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | ------------ |
+| `connection_name` | 是 | DBX 连接名称 |
+| `sql` | 是 | SQL 查询语句 |
### `dbx_get_schema_context`
返回用于生成 SQL 的紧凑表结构上下文。
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | DBX 连接名称 |
-| `schema` | 否 | Schema 名称 |
-| `tables` | 否 | 指定要包含的表名 |
-| `max_tables` | 否 | 最多包含多少张表,范围限制在 1 到 20 |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | ------------------------------------ |
+| `connection_name` | 是 | DBX 连接名称 |
+| `schema` | 否 | Schema 名称 |
+| `tables` | 否 | 指定要包含的表名 |
+| `max_tables` | 否 | 最多包含多少张表,范围限制在 1 到 20 |
### `dbx_add_connection`
添加新的数据库连接。
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `name` | 是 | 连接名称 |
-| `db_type` | 是 | 数据库类型(postgres、mysql、sqlite、redis 等) |
-| `host` | 是 | 数据库主机 |
-| `port` | 是 | 数据库端口 |
-| `username` | 否 | 用户名 |
-| `password` | 否 | 密码 |
-| `database` | 否 | 默认数据库名 |
-| `ssl` | 否 | 是否启用 SSL(默认 false) |
+| 参数 | 必填 | 说明 |
+| ---------- | ---- | ----------------------------------------------- |
+| `name` | 是 | 连接名称 |
+| `db_type` | 是 | 数据库类型(postgres、mysql、sqlite、redis 等) |
+| `host` | 是 | 数据库主机 |
+| `port` | 是 | 数据库端口 |
+| `username` | 否 | 用户名 |
+| `password` | 否 | 密码 |
+| `database` | 否 | 默认数据库名 |
+| `ssl` | 否 | 是否启用 SSL(默认 false) |
**示例对话:**
+
> "添加一个 PostgreSQL 连接,名称 prod-db,地址 db.example.com:5432"
### `dbx_remove_connection`
删除数据库连接。
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | 要删除的连接名称 |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | ---------------- |
+| `connection_name` | 是 | 要删除的连接名称 |
**示例对话:**
+
> "删除 test-db 连接"
### `dbx_open_table`
在 DBX 桌面端打开指定表。**需要 DBX 正在运行。**
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | DBX 连接名称 |
-| `table` | 是 | 表名 |
-| `database` | 否 | 数据库名 |
-| `schema` | 否 | Schema 名称 |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | ------------ |
+| `connection_name` | 是 | DBX 连接名称 |
+| `table` | 是 | 表名 |
+| `database` | 否 | 数据库名 |
+| `schema` | 否 | Schema 名称 |
DBX 会自动新开一个 tab 显示数据,窗口自动置前。
@@ -181,11 +187,11 @@ DBX 会自动新开一个 tab 显示数据,窗口自动置前。
在 DBX 桌面端执行 SQL 并展示结果。**需要 DBX 正在运行。**
-| 参数 | 必填 | 说明 |
-|---|---|---|
-| `connection_name` | 是 | DBX 连接名称 |
-| `sql` | 是 | SQL 查询语句 |
-| `database` | 否 | 数据库名 |
+| 参数 | 必填 | 说明 |
+| ----------------- | ---- | ------------ |
+| `connection_name` | 是 | DBX 连接名称 |
+| `sql` | 是 | SQL 查询语句 |
+| `database` | 否 | 数据库名 |
## 工作原理
@@ -193,11 +199,11 @@ DBX 会自动新开一个 tab 显示数据,窗口自动置前。
MCP Server 从 DBX 的 SQLite 数据库读取连接信息:
-| 平台 | 路径 |
-|---|---|
-| macOS | `~/Library/Application Support/com.dbx.app/dbx.db` |
-| Linux | `~/.config/com.dbx.app/dbx.db` |
-| Windows | `%APPDATA%\com.dbx.app\dbx.db` |
+| 平台 | 路径 |
+| ------- | -------------------------------------------------- |
+| macOS | `~/Library/Application Support/com.dbx.app/dbx.db` |
+| Linux | `~/.config/com.dbx.app/dbx.db` |
+| Windows | `%APPDATA%\com.dbx.app\dbx.db` |
### UI 联动
@@ -215,41 +221,31 @@ AI 助手 → MCP Server → HTTP localhost → DBX 后端 → Tauri 事件 →
MCP 查询执行默认非常保守:
-| 规则 | 默认行为 |
-|---|---|
-| 空 SQL 或无法识别的 SQL | 阻止 |
-| 多条 SQL 语句 | 允许;会逐条进行安全检查并依次执行 |
-| 非只读 SQL | 阻止,除非显式允许写入 |
-| `DROP`、`TRUNCATE`、`ALTER` | 阻止,除非显式允许危险 SQL |
-| 允许写入时没有 `WHERE` 的 `UPDATE` 或 `DELETE` | 阻止 |
+| 规则 | 默认行为 |
+| ---------------------------------------------- | ---------------------------------- |
+| 空 SQL 或无法识别的 SQL | 阻止 |
+| 多条 SQL 语句 | 允许;会逐条进行安全检查并依次执行 |
+| 非只读 SQL | 阻止,除非显式允许写入 |
+| `DROP`、`TRUNCATE`、`ALTER` | 阻止,除非显式允许危险 SQL |
+| 允许写入时没有 `WHERE` 的 `UPDATE` 或 `DELETE` | 阻止 |
设置 `DBX_MCP_ALLOW_WRITES=1` 可以允许写入语句。只有在受控环境并且确实需要破坏性 SQL 时,才设置 `DBX_MCP_ALLOW_DANGEROUS_SQL=1`。
### 桌面模式与 Web 模式
-| 模式 | 如何选择 | 说明 |
-|---|---|---|
-| 桌面本地模式 | 默认 | 读取 DBX 桌面端连接存储,并可调用桌面专属 UI bridge 工具 |
-| Web 模式 | 设置 `DBX_WEB_URL` | 不读取本机桌面存储,而是把请求发给 DBX Web 后端 |
+| 模式 | 如何选择 | 说明 |
+| ------------ | ------------------ | -------------------------------------------------------- |
+| 桌面本地模式 | 默认 | 读取 DBX 桌面端连接存储,并可调用桌面专属 UI bridge 工具 |
+| Web 模式 | 设置 `DBX_WEB_URL` | 不读取本机桌面存储,而是把请求发给 DBX Web 后端 |
## 常见问题
<Accordions>
- <Accordion title="MCP Server 连不上数据库">
- 检查 DBX 中该连接是否能正常连接。MCP Server 使用相同的连接配置和密码。确认数据库服务正在运行,网络可达。
- </Accordion>
- <Accordion title="dbx_open_table 报 'DBX is not running'">
- 需要先启动 DBX 桌面应用。UI 联动功能依赖 DBX 运行时的本地 HTTP 服务(端口 4224)。
- </Accordion>
- <Accordion title="连接名称找不到">
- 连接名称匹配不区分大小写,但需要和 DBX 中配置的名称一致。用 `dbx_list_connections` 查看所有可用名称。
- </Accordion>
- <Accordion title="查询超时">
- MCP Server 的查询超时为 30 秒。如果查询较慢,考虑添加索引或简化查询。也可以让 AI 助手先用 `dbx_describe_table` 了解表结构,再生成优化后的查询。
- </Accordion>
- <Accordion title="Docker 环境下如何使用 MCP?">
- Docker 部署的 DBX 同样支持 MCP。MCP Server 会读取 Docker 容器内的连接配置。确保 MCP Server 能访问到 DBX 的配置目录。
- </Accordion>
+ <Accordion title="MCP Server 连不上数据库">检查 DBX 中该连接是否能正常连接。MCP Server 使用相同的连接配置和密码。确认数据库服务正在运行,网络可达。</Accordion>
+ <Accordion title="dbx_open_table 报 'DBX is not running'">需要先启动 DBX 桌面应用。UI 联动功能依赖 DBX 运行时的本地 HTTP 服务(端口 4224)。</Accordion>
+ <Accordion title="连接名称找不到">连接名称匹配不区分大小写,但需要和 DBX 中配置的名称一致。用 `dbx_list_connections` 查看所有可用名称。</Accordion>
+ <Accordion title="查询超时">MCP Server 的查询超时为 30 秒。如果查询较慢,考虑添加索引或简化查询。也可以让 AI 助手先用 `dbx_describe_table` 了解表结构,再生成优化后的查询。</Accordion>
+ <Accordion title="Docker 环境下如何使用 MCP?">Docker 部署的 DBX 同样支持 MCP。MCP Server 会读取 Docker 容器内的连接配置。确保 MCP Server 能访问到 DBX 的配置目录。</Accordion>
</Accordions>
## 系统要求
diff --git a/docs/content/docs/mcp.mdx b/docs/content/docs/mcp.mdx
index 005c96986a..73238258dc 100644
--- a/docs/content/docs/mcp.mdx
+++ b/docs/content/docs/mcp.mdx
@@ -3,9 +3,7 @@ title: MCP Integration
description: Let AI coding agents query your databases through the Model Context Protocol.
---
-<Callout type="info">
-One line of config to let AI coding agents query your databases directly. Works with Claude Code, Cursor, Windsurf, and VS Code Copilot.
-</Callout>
+<Callout type="info">One line of config to let AI coding agents query your databases directly. Works with Claude Code, Cursor, Windsurf, and VS Code Copilot.</Callout>
## What is MCP?
@@ -28,6 +26,7 @@ AI Agent → MCP Server → Your Database → Results
```bash
npm install -g @dbx-app/mcp-server
```
+
</Step>
<Step>
### Configure Your AI Agent
@@ -44,6 +43,7 @@ AI Agent → MCP Server → Your Database → Results
}
}
```
+
</Step>
<Step>
### Start Using
@@ -55,17 +55,18 @@ AI Agent → MCP Server → Your Database → Results
- "Describe the users table"
- "Query the average salary from employees"
- "Open the orders table" (requires DBX running)
+
</Step>
</Steps>
## Supported AI Agents
-| Agent | Configuration |
-|---|---|
-| Claude Code | `.mcp.json` (native support) |
-| Cursor | `.cursor/mcp.json` |
-| Windsurf | `.windsurfrules` |
-| VS Code + Copilot | MCP extension |
+| Agent | Configuration |
+| ----------------- | ---------------------------- |
+| Claude Code | `.mcp.json` (native support) |
+| Cursor | `.cursor/mcp.json` |
+| Windsurf | `.windsurfrules` |
+| VS Code + Copilot | MCP extension |
## Tools
@@ -76,9 +77,11 @@ DBX MCP Server provides the following tools. Your AI agent calls them automatica
List all database connections configured in DBX.
**Example:**
+
> "List my database connections"
**Response:**
+
```
| Name | Type | Host | Port | Database |
| -------- | -------- | --------- | ---- | -------- |
@@ -90,22 +93,23 @@ List all database connections configured in DBX.
List tables and views for a connection.
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | DBX connection name |
-| `schema` | No | Schema name (default: public) |
+| Parameter | Required | Description |
+| ----------------- | -------- | ----------------------------- |
+| `connection_name` | Yes | DBX connection name |
+| `schema` | No | Schema name (default: public) |
### `dbx_describe_table`
Get column definitions for a table. The AI uses this to understand your data structure before generating queries.
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | DBX connection name |
-| `table` | Yes | Table name |
-| `schema` | No | Schema name (default: public) |
+| Parameter | Required | Description |
+| ----------------- | -------- | ----------------------------- |
+| `connection_name` | Yes | DBX connection name |
+| `table` | Yes | Table name |
+| `schema` | No | Schema name (default: public) |
**Response:**
+
```
| Column | Type | Nullable | Default | Comment |
| ----------- | --------- | -------- | ------- | ---------- |
@@ -119,61 +123,63 @@ Get column definitions for a table. The AI uses this to understand your data str
Execute a SQL query and return results (max 100 rows).
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | DBX connection name |
-| `sql` | Yes | SQL query |
+| Parameter | Required | Description |
+| ----------------- | -------- | ------------------- |
+| `connection_name` | Yes | DBX connection name |
+| `sql` | Yes | SQL query |
### `dbx_get_schema_context`
Return compact table and column context for SQL generation.
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | DBX connection name |
-| `schema` | No | Schema name |
-| `tables` | No | Specific table names to include |
-| `max_tables` | No | Maximum number of tables to include; capped between 1 and 20 |
+| Parameter | Required | Description |
+| ----------------- | -------- | ------------------------------------------------------------ |
+| `connection_name` | Yes | DBX connection name |
+| `schema` | No | Schema name |
+| `tables` | No | Specific table names to include |
+| `max_tables` | No | Maximum number of tables to include; capped between 1 and 20 |
### `dbx_add_connection`
Add a new database connection to DBX.
-| Parameter | Required | Description |
-|---|---|---|
-| `name` | Yes | Connection name |
-| `db_type` | Yes | Database type (postgres, mysql, sqlite, redis, etc.) |
-| `host` | Yes | Database host |
-| `port` | Yes | Database port |
-| `username` | No | Username |
-| `password` | No | Password |
-| `database` | No | Default database name |
-| `ssl` | No | Enable SSL (default: false) |
+| Parameter | Required | Description |
+| ---------- | -------- | ---------------------------------------------------- |
+| `name` | Yes | Connection name |
+| `db_type` | Yes | Database type (postgres, mysql, sqlite, redis, etc.) |
+| `host` | Yes | Database host |
+| `port` | Yes | Database port |
+| `username` | No | Username |
+| `password` | No | Password |
+| `database` | No | Default database name |
+| `ssl` | No | Enable SSL (default: false) |
**Example:**
+
> "Add a PostgreSQL connection named prod-db on db.example.com:5432"
### `dbx_remove_connection`
Remove a database connection from DBX.
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | Name of the connection to remove |
+| Parameter | Required | Description |
+| ----------------- | -------- | -------------------------------- |
+| `connection_name` | Yes | Name of the connection to remove |
**Example:**
+
> "Remove the test-db connection"
### `dbx_open_table`
Open a table in DBX desktop app UI. **Requires DBX to be running.**
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | DBX connection name |
-| `table` | Yes | Table name |
-| `database` | No | Database name |
-| `schema` | No | Schema name |
+| Parameter | Required | Description |
+| ----------------- | -------- | ------------------- |
+| `connection_name` | Yes | DBX connection name |
+| `table` | Yes | Table name |
+| `database` | No | Database name |
+| `schema` | No | Schema name |
DBX opens a new tab with the table data and brings the window to front.
@@ -181,11 +187,11 @@ DBX opens a new tab with the table data and brings the window to front.
Execute a SQL query in DBX desktop app UI. **Requires DBX to be running.**
-| Parameter | Required | Description |
-|---|---|---|
-| `connection_name` | Yes | DBX connection name |
-| `sql` | Yes | SQL query |
-| `database` | No | Database name |
+| Parameter | Required | Description |
+| ----------------- | -------- | ------------------- |
+| `connection_name` | Yes | DBX connection name |
+| `sql` | Yes | SQL query |
+| `database` | No | Database name |
## How It Works
@@ -193,11 +199,11 @@ Execute a SQL query in DBX desktop app UI. **Requires DBX to be running.**
The MCP Server reads DBX's SQLite database:
-| Platform | Path |
-|---|---|
-| macOS | `~/Library/Application Support/com.dbx.app/dbx.db` |
-| Linux | `~/.config/com.dbx.app/dbx.db` |
-| Windows | `%APPDATA%\com.dbx.app\dbx.db` |
+| Platform | Path |
+| -------- | -------------------------------------------------- |
+| macOS | `~/Library/Application Support/com.dbx.app/dbx.db` |
+| Linux | `~/.config/com.dbx.app/dbx.db` |
+| Windows | `%APPDATA%\com.dbx.app\dbx.db` |
### UI Integration
@@ -215,41 +221,31 @@ MCP query support in desktop local mode is implemented for PostgreSQL, MySQL, an
MCP query execution is intentionally conservative:
-| Rule | Default |
-|---|---|
-| Empty or unrecognized SQL | Blocked |
-| Multiple SQL statements | Allowed; each statement is checked and executed separately |
-| Non-read SQL | Blocked unless writes are explicitly allowed |
-| `DROP`, `TRUNCATE`, or `ALTER` | Blocked unless dangerous SQL is explicitly allowed |
-| `UPDATE` or `DELETE` without `WHERE` when writes are allowed | Blocked |
+| Rule | Default |
+| ------------------------------------------------------------ | ---------------------------------------------------------- |
+| Empty or unrecognized SQL | Blocked |
+| Multiple SQL statements | Allowed; each statement is checked and executed separately |
+| Non-read SQL | Blocked unless writes are explicitly allowed |
+| `DROP`, `TRUNCATE`, or `ALTER` | Blocked unless dangerous SQL is explicitly allowed |
+| `UPDATE` or `DELETE` without `WHERE` when writes are allowed | Blocked |
Set `DBX_MCP_ALLOW_WRITES=1` to allow write statements. Set `DBX_MCP_ALLOW_DANGEROUS_SQL=1` only in controlled environments where destructive SQL is expected.
### Desktop And Web Mode
-| Mode | How It Is Selected | Notes |
-|---|---|---|
-| Desktop local mode | Default | Reads DBX desktop connection storage and can call desktop-only UI bridge tools |
-| Web mode | Set `DBX_WEB_URL` | Sends requests to the DBX web backend instead of reading local desktop storage |
+| Mode | How It Is Selected | Notes |
+| ------------------ | ------------------ | ------------------------------------------------------------------------------ |
+| Desktop local mode | Default | Reads DBX desktop connection storage and can call desktop-only UI bridge tools |
+| Web mode | Set `DBX_WEB_URL` | Sends requests to the DBX web backend instead of reading local desktop storage |
## FAQ
<Accordions>
- <Accordion title="MCP Server can't connect to my database">
- Check that the connection works in DBX first. The MCP Server uses the same config and credentials. Make sure the database is running and network-reachable.
- </Accordion>
- <Accordion title="dbx_open_table says 'DBX is not running'">
- Start the DBX desktop app first. UI integration requires DBX's local HTTP service (port 4224).
- </Accordion>
- <Accordion title="Connection name not found">
- Connection name matching is case-insensitive but must match the name configured in DBX. Use `dbx_list_connections` to see all available names.
- </Accordion>
- <Accordion title="Query timeout">
- MCP Server has a 30-second query timeout. Consider adding indexes or simplifying your query. You can also ask the AI to use `dbx_describe_table` first to understand the schema, then generate an optimized query.
- </Accordion>
- <Accordion title="How to use MCP with Docker?">
- DBX deployed via Docker also supports MCP. The MCP Server reads connection configs from inside the Docker container. Make sure the MCP Server can access DBX's config directory.
- </Accordion>
+ <Accordion title="MCP Server can't connect to my database">Check that the connection works in DBX first. The MCP Server uses the same config and credentials. Make sure the database is running and network-reachable.</Accordion>
+ <Accordion title="dbx_open_table says 'DBX is not running'">Start the DBX desktop app first. UI integration requires DBX's local HTTP service (port 4224).</Accordion>
+ <Accordion title="Connection name not found">Connection name matching is case-insensitive but must match the name configured in DBX. Use `dbx_list_connections` to see all available names.</Accordion>
+ <Accordion title="Query timeout">MCP Server has a 30-second query timeout. Consider adding indexes or simplifying your query. You can also ask the AI to use `dbx_describe_table` first to understand the schema, then generate an optimized query.</Accordion>
+ <Accordion title="How to use MCP with Docker?">DBX deployed via Docker also supports MCP. The MCP Server reads connection configs from inside the Docker container. Make sure the MCP Server can access DBX's config directory.</Accordion>
</Accordions>
## Requirements
diff --git a/docs/content/docs/mongodb.cn.mdx b/docs/content/docs/mongodb.cn.mdx
index 6f0296e591..362eb3a15f 100644
--- a/docs/content/docs/mongodb.cn.mdx
+++ b/docs/content/docs/mongodb.cn.mdx
@@ -14,9 +14,7 @@ MongoDB 数据库和集合与关系型数据库一同显示在侧边栏中。浏
- 集合文档的分页浏览
- 文档查询的过滤和排序支持
-<Callout type="info">
-MongoDB 连接同时支持标准连接字符串和旧版连接格式。对于副本集,请使用标准的 `mongodb://` 连接 URL 并指定副本集名称。
-</Callout>
+<Callout type="info">MongoDB 连接同时支持标准连接字符串和旧版连接格式。对于副本集,请使用标准的 `mongodb://` 连接 URL 并指定副本集名称。</Callout>
## 表格视图
@@ -57,12 +55,12 @@ DBX 通过内置驱动支持 MongoDB 4.2 及以上版本。对于 4.2 之前版
## 功能覆盖
-| 功能 | 支持情况 |
-|---|---|
-| 列出数据库和集合 | 所有版本 |
-| 分页文档浏览 | 所有版本 |
-| 扁平化字段表格视图 | 所有版本 |
-| 过滤和排序 | MongoDB 4.2+ |
-| 内联编辑 | 所有版本 |
-| JSON 文档编辑器 | 所有版本 |
-| SSH 隧道 | 标准连接 |
+| 功能 | 支持情况 |
+| ------------------ | ------------ |
+| 列出数据库和集合 | 所有版本 |
+| 分页文档浏览 | 所有版本 |
+| 扁平化字段表格视图 | 所有版本 |
+| 过滤和排序 | MongoDB 4.2+ |
+| 内联编辑 | 所有版本 |
+| JSON 文档编辑器 | 所有版本 |
+| SSH 隧道 | 标准连接 |
diff --git a/docs/content/docs/mongodb.mdx b/docs/content/docs/mongodb.mdx
index a3fd8f0b2a..b3945a8463 100644
--- a/docs/content/docs/mongodb.mdx
+++ b/docs/content/docs/mongodb.mdx
@@ -14,9 +14,7 @@ MongoDB databases and collections appear in the sidebar alongside relational dat
- Paginated document browsing within collections
- Filter and sort support for document queries
-<Callout type="info">
-MongoDB connections support both standard connection strings and legacy connection formats. For replica sets, use the standard `mongodb://` connection URL with the replica set name.
-</Callout>
+<Callout type="info">MongoDB connections support both standard connection strings and legacy connection formats. For replica sets, use the standard `mongodb://` connection URL with the replica set name.</Callout>
## Table View
@@ -57,12 +55,12 @@ DBX supports MongoDB 4.2 and later through the built-in driver. For pre-4.2 Mong
## Feature Coverage
-| Feature | Support |
-|---|---|
-| List databases and collections | All versions |
-| Document browsing with pagination | All versions |
-| Table view with flattened fields | All versions |
-| Filter and sort | MongoDB 4.2+ |
-| Inline editing | All versions |
-| JSON document editor | All versions |
-| SSH tunnel | Standard connections |
+| Feature | Support |
+| --------------------------------- | -------------------- |
+| List databases and collections | All versions |
+| Document browsing with pagination | All versions |
+| Table view with flattened fields | All versions |
+| Filter and sort | MongoDB 4.2+ |
+| Inline editing | All versions |
+| JSON document editor | All versions |
+| SSH tunnel | Standard connections |
diff --git a/docs/content/docs/object-browser.cn.mdx b/docs/content/docs/object-browser.cn.mdx
index a0824ab515..22a3a4c8a2 100644
--- a/docs/content/docs/object-browser.cn.mdx
+++ b/docs/content/docs/object-browser.cn.mdx
@@ -7,17 +7,15 @@ description: 浏览视图、存储过程、函数以及表与结构之外的数
## 对象浏览器展示的内容
-| 对象类型 | 展示信息 |
-|---|---|
-| 视图 | 视图定义(DDL)、列列表、Schema |
-| 存储过程 | 源代码、参数、语言 |
-| 函数 | 返回类型、参数、源代码 |
-| 触发器 | 时机、事件、关联表、源代码 |
-| 例程 | 存储过程和函数的合并视图 |
-
-<Callout type="info">
-对象浏览器的可用性取决于数据库引擎及其元数据支持。并非所有数据库都能通过标准 SQL 暴露源代码或例程元数据。
-</Callout>
+| 对象类型 | 展示信息 |
+| -------- | ------------------------------- |
+| 视图 | 视图定义(DDL)、列列表、Schema |
+| 存储过程 | 源代码、参数、语言 |
+| 函数 | 返回类型、参数、源代码 |
+| 触发器 | 时机、事件、关联表、源代码 |
+| 例程 | 存储过程和函数的合并视图 |
+
+<Callout type="info">对象浏览器的可用性取决于数据库引擎及其元数据支持。并非所有数据库都能通过标准 SQL 暴露源代码或例程元数据。</Callout>
## 打开对象浏览器
@@ -43,9 +41,7 @@ description: 浏览视图、存储过程、函数以及表与结构之外的数
- DBX 会生成适当的 `CREATE OR REPLACE` 或 `ALTER` 语句
- 在应用更改前检查生成的 SQL
-<Callout type="warn">
-在数据库中直接编辑对象可能会影响正在运行的应用程序。在保存更改前请验证对象的使用情况,尤其是在生产数据库上。
-</Callout>
+<Callout type="warn">在数据库中直接编辑对象可能会影响正在运行的应用程序。在保存更改前请验证对象的使用情况,尤其是在生产数据库上。</Callout>
## 对象时间戳
diff --git a/docs/content/docs/object-browser.mdx b/docs/content/docs/object-browser.mdx
index 49e86cedfb..18068bcae4 100644
--- a/docs/content/docs/object-browser.mdx
+++ b/docs/content/docs/object-browser.mdx
@@ -7,17 +7,15 @@ The Object Browser extends the sidebar beyond tables and collections. It surface
## What the Object Browser Shows
-| Object Type | Information Shown |
-|---|---|
-| Views | View definition (DDL), column list, schema |
-| Procedures | Source code, parameters, language |
-| Functions | Return type, parameters, source code |
-| Triggers | Timing, event, table, source |
-| Routines | Combined view of procedures and functions |
-
-<Callout type="info">
-Object Browser availability depends on the database engine and its metadata support. Not all databases expose source code or routine metadata through standard SQL.
-</Callout>
+| Object Type | Information Shown |
+| ----------- | ------------------------------------------ |
+| Views | View definition (DDL), column list, schema |
+| Procedures | Source code, parameters, language |
+| Functions | Return type, parameters, source code |
+| Triggers | Timing, event, table, source |
+| Routines | Combined view of procedures and functions |
+
+<Callout type="info">Object Browser availability depends on the database engine and its metadata support. Not all databases expose source code or routine metadata through standard SQL.</Callout>
## Opening the Object Browser
@@ -43,9 +41,7 @@ For databases that support `CREATE OR REPLACE` semantics, you can edit object so
- DBX generates the appropriate `CREATE OR REPLACE` or `ALTER` statement
- Review the generated SQL before applying changes
-<Callout type="warn">
-Editing database objects in place may affect running applications. Verify the object's usage before saving changes, especially on production databases.
-</Callout>
+<Callout type="warn">Editing database objects in place may affect running applications. Verify the object's usage before saving changes, especially on production databases.</Callout>
## Object Timestamps
diff --git a/docs/content/docs/plugins.cn.mdx b/docs/content/docs/plugins.cn.mdx
index 626df01004..3b512ef665 100644
--- a/docs/content/docs/plugins.cn.mdx
+++ b/docs/content/docs/plugins.cn.mdx
@@ -5,9 +5,7 @@ description: 安装 DBX JDBC 插件、导入数据库厂商驱动 JAR,并创
DBX 默认使用 Rust 原生数据库驱动。JDBC 是可选能力:当你需要连接 DBX 暂未内置支持的数据库,或希望使用数据库厂商提供的 JDBC 驱动时,可以安装 JDBC 插件。
-<Callout type="info">
-JDBC 插件不会打包进 DBX 主应用,也不包含任何数据库厂商的 JDBC 驱动。你需要先安装 DBX JDBC 插件,再导入对应数据库的 JDBC driver JAR。
-</Callout>
+<Callout type="info">JDBC 插件不会打包进 DBX 主应用,也不包含任何数据库厂商的 JDBC 驱动。你需要先安装 DBX JDBC 插件,再导入对应数据库的 JDBC driver JAR。</Callout>
## 什么时候需要 JDBC
@@ -22,14 +20,14 @@ JDBC 插件不会打包进 DBX 主应用,也不包含任何数据库厂商的
## 需要准备什么
-| 项目 | 是否必需 | 说明 |
-|---|---:|---|
-| DBX JDBC 插件 | 必需 | 在 DBX 设置中一键安装,用来让 DBX 调用 JDBC |
-| Java Runtime | 必需 | 本机需要能运行 `java`;建议 Java 17 或更高版本 |
-| 数据库厂商 JDBC driver JAR | 必需 | 例如 PostgreSQL、MySQL、达梦、Oracle、H2、SQLite 等驱动 JAR |
-| JDBC URL | 必需 | JDBC URL 通常已经包含主机、端口、数据库名和参数 |
-| 用户名/密码 | 视数据库而定 | 文件型数据库或部分认证方式可能不需要 |
-| 驱动类 | 通常可选 | 多数现代 JDBC 驱动可以自动注册;自动识别失败时再填写 |
+| 项目 | 是否必需 | 说明 |
+| -------------------------- | -----------: | ----------------------------------------------------------- |
+| DBX JDBC 插件 | 必需 | 在 DBX 设置中一键安装,用来让 DBX 调用 JDBC |
+| Java Runtime | 必需 | 本机需要能运行 `java`;建议 Java 17 或更高版本 |
+| 数据库厂商 JDBC driver JAR | 必需 | 例如 PostgreSQL、MySQL、达梦、Oracle、H2、SQLite 等驱动 JAR |
+| JDBC URL | 必需 | JDBC URL 通常已经包含主机、端口、数据库名和参数 |
+| 用户名/密码 | 视数据库而定 | 文件型数据库或部分认证方式可能不需要 |
+| 驱动类 | 通常可选 | 多数现代 JDBC 驱动可以自动注册;自动识别失败时再填写 |
## 第一步:安装 Java
@@ -50,6 +48,7 @@ java -version
```
如果 `java -version` 仍不可用,可以按 Homebrew 输出提示配置 `PATH` 或 `JAVA_HOME`。
+
</Tab>
<Tab value="Windows">
安装 Temurin、Oracle JDK 或 Microsoft Build of OpenJDK。安装后重新打开 DBX,并确认命令行中可以运行:
@@ -57,6 +56,7 @@ java -version
```powershell
java -version
```
+
</Tab>
<Tab value="Linux">
Debian / Ubuntu:
@@ -70,6 +70,7 @@ java -version
```bash
sudo dnf install java-17-openjdk
```
+
</Tab>
</Tabs>
@@ -95,23 +96,21 @@ DBX 不会自动下载数据库厂商驱动。你需要从数据库官网或 Mav
常见驱动示例:
-| 数据库 | 常见 Maven Artifact | 驱动类 | JDBC URL 示例 |
-|---|---|---|---|
-| PostgreSQL | `org.postgresql:postgresql` | `org.postgresql.Driver` | `jdbc:postgresql://localhost:5432/postgres` |
-| MySQL | `com.mysql:mysql-connector-j` | `com.mysql.cj.jdbc.Driver` | `jdbc:mysql://localhost:3306/test` |
-| MariaDB | `org.mariadb.jdbc:mariadb-java-client` | `org.mariadb.jdbc.Driver` | `jdbc:mariadb://localhost:3306/test` |
-| 达梦 DM | `com.dameng:DmJdbcDriver8` | `dm.jdbc.driver.DmDriver` | `jdbc:dm://localhost:5236` |
-| SQL Server | `com.microsoft.sqlserver:mssql-jdbc` | `com.microsoft.sqlserver.jdbc.SQLServerDriver` | `jdbc:sqlserver://localhost:1433;databaseName=master` |
-| Oracle | `com.oracle.database.jdbc:ojdbc11` | `oracle.jdbc.OracleDriver` | `jdbc:oracle:thin:@//localhost:1521/ORCLPDB1` |
-| H2 | `com.h2database:h2` | `org.h2.Driver` | `jdbc:h2:/tmp/dbx-h2-test` |
-| SQLite | `org.xerial:sqlite-jdbc` | `org.sqlite.JDBC` | `jdbc:sqlite:/Users/me/test.db` |
-| ClickHouse | `com.clickhouse:clickhouse-jdbc` | `com.clickhouse.jdbc.ClickHouseDriver` | `jdbc:clickhouse://localhost:8123/default` |
-| DB2 | `com.ibm.db2:jcc` | `com.ibm.db2.jcc.DB2Driver` | `jdbc:db2://localhost:50000/SAMPLE` |
-| Snowflake | `net.snowflake:snowflake-jdbc` | `net.snowflake.client.jdbc.SnowflakeDriver` | `jdbc:snowflake://account.region.snowflakecomputing.com/?db=DEMO` |
-
-<Callout type="warn">
-不同数据库和驱动版本的 URL 参数可能不同。以厂商官方文档为准。如果驱动依赖多个 JAR,请把需要的 JAR 路径都导入或填写进去。
-</Callout>
+| 数据库 | 常见 Maven Artifact | 驱动类 | JDBC URL 示例 |
+| ---------- | -------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------- |
+| PostgreSQL | `org.postgresql:postgresql` | `org.postgresql.Driver` | `jdbc:postgresql://localhost:5432/postgres` |
+| MySQL | `com.mysql:mysql-connector-j` | `com.mysql.cj.jdbc.Driver` | `jdbc:mysql://localhost:3306/test` |
+| MariaDB | `org.mariadb.jdbc:mariadb-java-client` | `org.mariadb.jdbc.Driver` | `jdbc:mariadb://localhost:3306/test` |
+| 达梦 DM | `com.dameng:DmJdbcDriver8` | `dm.jdbc.driver.DmDriver` | `jdbc:dm://localhost:5236` |
+| SQL Server | `com.microsoft.sqlserver:mssql-jdbc` | `com.microsoft.sqlserver.jdbc.SQLServerDriver` | `jdbc:sqlserver://localhost:1433;databaseName=master` |
+| Oracle | `com.oracle.database.jdbc:ojdbc11` | `oracle.jdbc.OracleDriver` | `jdbc:oracle:thin:@//localhost:1521/ORCLPDB1` |
+| H2 | `com.h2database:h2` | `org.h2.Driver` | `jdbc:h2:/tmp/dbx-h2-test` |
+| SQLite | `org.xerial:sqlite-jdbc` | `org.sqlite.JDBC` | `jdbc:sqlite:/Users/me/test.db` |
+| ClickHouse | `com.clickhouse:clickhouse-jdbc` | `com.clickhouse.jdbc.ClickHouseDriver` | `jdbc:clickhouse://localhost:8123/default` |
+| DB2 | `com.ibm.db2:jcc` | `com.ibm.db2.jcc.DB2Driver` | `jdbc:db2://localhost:50000/SAMPLE` |
+| Snowflake | `net.snowflake:snowflake-jdbc` | `net.snowflake.client.jdbc.SnowflakeDriver` | `jdbc:snowflake://account.region.snowflakecomputing.com/?db=DEMO` |
+
+<Callout type="warn">不同数据库和驱动版本的 URL 参数可能不同。以厂商官方文档为准。如果驱动依赖多个 JAR,请把需要的 JAR 路径都导入或填写进去。</Callout>
## 第四步:导入 JDBC 驱动 JAR
@@ -129,14 +128,14 @@ DBX 不会自动下载数据库厂商驱动。你需要从数据库官网或 Mav
创建连接时选择 **JDBC** 类型。
-| 字段 | 怎么填 |
-|---|---|
-| 名称 | 连接显示名,例如 `H2 Test`、`DM Dev`、`Oracle Dev` |
-| JDBC URL | 完整 JDBC URL,例如 `jdbc:postgresql://localhost:5432/postgres` |
-| 用户名 | 数据库用户名;不需要认证时可以留空 |
-| 密码 | 数据库密码;不需要认证时可以留空 |
-| 驱动类(可选) | 自动识别失败时填写,例如 `org.postgresql.Driver` |
-| 驱动 JAR | 从已导入驱动下拉框选择,或填写本机 JAR 路径 |
+| 字段 | 怎么填 |
+| -------------- | --------------------------------------------------------------- |
+| 名称 | 连接显示名,例如 `H2 Test`、`DM Dev`、`Oracle Dev` |
+| JDBC URL | 完整 JDBC URL,例如 `jdbc:postgresql://localhost:5432/postgres` |
+| 用户名 | 数据库用户名;不需要认证时可以留空 |
+| 密码 | 数据库密码;不需要认证时可以留空 |
+| 驱动类(可选) | 自动识别失败时填写,例如 `org.postgresql.Driver` |
+| 驱动 JAR | 从已导入驱动下拉框选择,或填写本机 JAR 路径 |
JDBC URL 通常已经包含主机、端口和数据库名,因此 JDBC 表单不会再单独显示主机和端口。
@@ -153,13 +152,13 @@ DBX 已经内置 DM ODBC 连接类型。如果你更想使用达梦官方 JDBC
5. 新建连接,选择 **JDBC**
6. 填写:
-| 字段 | 值 |
-|---|---|
-| JDBC URL | `jdbc:dm://127.0.0.1:5236` |
-| 用户名 | `SYSDBA` |
-| 密码 | 你的达梦密码 |
-| 驱动类(可选) | `dm.jdbc.driver.DmDriver` |
-| 驱动 JAR | 选择已导入的达梦 JDBC JAR |
+| 字段 | 值 |
+| -------------- | -------------------------- |
+| JDBC URL | `jdbc:dm://127.0.0.1:5236` |
+| 用户名 | `SYSDBA` |
+| 密码 | 你的达梦密码 |
+| 驱动类(可选) | `dm.jdbc.driver.DmDriver` |
+| 驱动 JAR | 选择已导入的达梦 JDBC JAR |
达梦这里建议直接填写驱动类 `dm.jdbc.driver.DmDriver`,这样不依赖驱动 JAR 的自动发现配置。
@@ -173,13 +172,13 @@ H2 很适合验证 JDBC 流程。
4. 新建连接,选择 **JDBC**
5. 填写:
-| 字段 | 值 |
-|---|---|
-| JDBC URL | `jdbc:h2:/tmp/dbx-h2-demo` |
-| 用户名 | `sa` |
-| 密码 | 留空 |
-| 驱动类(可选) | `org.h2.Driver` |
-| 驱动 JAR | 选择已导入的 H2 JAR |
+| 字段 | 值 |
+| -------------- | -------------------------- |
+| JDBC URL | `jdbc:h2:/tmp/dbx-h2-demo` |
+| 用户名 | `sa` |
+| 密码 | 留空 |
+| 驱动类(可选) | `org.h2.Driver` |
+| 驱动 JAR | 选择已导入的 H2 JAR |
保存后可以执行:
@@ -201,13 +200,13 @@ SELECT * FROM users;
3. 新建 JDBC 连接
4. 填写:
-| 字段 | 值 |
-|---|---|
-| JDBC URL | `jdbc:postgresql://localhost:5432/postgres` |
-| 用户名 | `postgres` |
-| 密码 | 你的 PostgreSQL 密码 |
-| 驱动类(可选) | `org.postgresql.Driver` |
-| 驱动 JAR | 选择已导入的 PostgreSQL JAR |
+| 字段 | 值 |
+| -------------- | ------------------------------------------- |
+| JDBC URL | `jdbc:postgresql://localhost:5432/postgres` |
+| 用户名 | `postgres` |
+| 密码 | 你的 PostgreSQL 密码 |
+| 驱动类(可选) | `org.postgresql.Driver` |
+| 驱动 JAR | 选择已导入的 PostgreSQL JAR |
如果数据库要求 SSL,可以在 JDBC URL 后添加参数:
@@ -296,6 +295,4 @@ DBX 会启动插件可执行文件,并通过 stdin/stdout 发送 JSON Lines
第一版协议支持 `testConnection`、`connect`、`executeQuery`、`listDatabases`、`listSchemas`、`listTables` 和 `getColumns`。
-<Callout type="info">
-JDBC 连接配置会保存 `jdbc_driver_class` 和 `jdbc_driver_paths`。如果一个驱动需要多个 JAR,请把所有路径都绑定到连接上,这样元数据和查询调用会使用同一套 classpath。
-</Callout>
+<Callout type="info">JDBC 连接配置会保存 `jdbc_driver_class` 和 `jdbc_driver_paths`。如果一个驱动需要多个 JAR,请把所有路径都绑定到连接上,这样元数据和查询调用会使用同一套 classpath。</Callout>
diff --git a/docs/content/docs/plugins.mdx b/docs/content/docs/plugins.mdx
index fad322b257..27d3048a69 100644
--- a/docs/content/docs/plugins.mdx
+++ b/docs/content/docs/plugins.mdx
@@ -5,9 +5,7 @@ description: Install the DBX JDBC plugin, import vendor JDBC driver JARs, and cr
DBX uses native Rust database drivers by default. JDBC is optional: install the JDBC plugin when you need to connect to a database that DBX does not support natively, or when you specifically need a vendor JDBC driver.
-<Callout type="info">
-The JDBC plugin is not bundled with the main DBX app, and it does not include vendor JDBC drivers. Install the DBX JDBC plugin first, then import the database vendor's JDBC driver JAR.
-</Callout>
+<Callout type="info">The JDBC plugin is not bundled with the main DBX app, and it does not include vendor JDBC drivers. Install the DBX JDBC plugin first, then import the database vendor's JDBC driver JAR.</Callout>
## When to Use JDBC
@@ -22,14 +20,14 @@ Use JDBC when:
## Requirements
-| Item | Required | Notes |
-|---|---:|---|
-| DBX JDBC plugin | Yes | Installed from DBX settings; lets DBX call JDBC |
-| Java Runtime | Yes | The local machine must be able to run `java`; Java 17 or newer is recommended |
-| Vendor JDBC driver JAR | Yes | For example PostgreSQL, MySQL, Dameng DM, Oracle, H2, SQLite, or another vendor driver |
-| JDBC URL | Yes | The URL usually contains host, port, database name, and parameters |
-| Username/password | Depends | File databases or some auth modes may not need them |
-| Driver class | Usually optional | Most modern JDBC drivers auto-register; enter it only when auto-discovery fails |
+| Item | Required | Notes |
+| ---------------------- | ---------------: | -------------------------------------------------------------------------------------- |
+| DBX JDBC plugin | Yes | Installed from DBX settings; lets DBX call JDBC |
+| Java Runtime | Yes | The local machine must be able to run `java`; Java 17 or newer is recommended |
+| Vendor JDBC driver JAR | Yes | For example PostgreSQL, MySQL, Dameng DM, Oracle, H2, SQLite, or another vendor driver |
+| JDBC URL | Yes | The URL usually contains host, port, database name, and parameters |
+| Username/password | Depends | File databases or some auth modes may not need them |
+| Driver class | Usually optional | Most modern JDBC drivers auto-register; enter it only when auto-discovery fails |
## Step 1: Install Java
@@ -50,6 +48,7 @@ If the command is missing, install Java first. DBX checks `JAVA_HOME` first, the
```
If `java -version` still does not work, follow the Homebrew output to configure `PATH` or `JAVA_HOME`.
+
</Tab>
<Tab value="Windows">
Install Temurin, Oracle JDK, or Microsoft Build of OpenJDK. Restart DBX after installation and verify:
@@ -57,6 +56,7 @@ If the command is missing, install Java first. DBX checks `JAVA_HOME` first, the
```powershell
java -version
```
+
</Tab>
<Tab value="Linux">
Debian / Ubuntu:
@@ -70,6 +70,7 @@ If the command is missing, install Java first. DBX checks `JAVA_HOME` first, the
```bash
sudo dnf install java-17-openjdk
```
+
</Tab>
</Tabs>
@@ -95,23 +96,21 @@ DBX does not download vendor JDBC drivers automatically. Download the `.jar` fil
Common examples:
-| Database | Common Maven Artifact | Driver Class | JDBC URL Example |
-|---|---|---|---|
-| PostgreSQL | `org.postgresql:postgresql` | `org.postgresql.Driver` | `jdbc:postgresql://localhost:5432/postgres` |
-| MySQL | `com.mysql:mysql-connector-j` | `com.mysql.cj.jdbc.Driver` | `jdbc:mysql://localhost:3306/test` |
-| MariaDB | `org.mariadb.jdbc:mariadb-java-client` | `org.mariadb.jdbc.Driver` | `jdbc:mariadb://localhost:3306/test` |
-| Dameng DM | `com.dameng:DmJdbcDriver8` | `dm.jdbc.driver.DmDriver` | `jdbc:dm://localhost:5236` |
-| SQL Server | `com.microsoft.sqlserver:mssql-jdbc` | `com.microsoft.sqlserver.jdbc.SQLServerDriver` | `jdbc:sqlserver://localhost:1433;databaseName=master` |
-| Oracle | `com.oracle.database.jdbc:ojdbc11` | `oracle.jdbc.OracleDriver` | `jdbc:oracle:thin:@//localhost:1521/ORCLPDB1` |
-| H2 | `com.h2database:h2` | `org.h2.Driver` | `jdbc:h2:/tmp/dbx-h2-test` |
-| SQLite | `org.xerial:sqlite-jdbc` | `org.sqlite.JDBC` | `jdbc:sqlite:/Users/me/test.db` |
-| ClickHouse | `com.clickhouse:clickhouse-jdbc` | `com.clickhouse.jdbc.ClickHouseDriver` | `jdbc:clickhouse://localhost:8123/default` |
-| DB2 | `com.ibm.db2:jcc` | `com.ibm.db2.jcc.DB2Driver` | `jdbc:db2://localhost:50000/SAMPLE` |
-| Snowflake | `net.snowflake:snowflake-jdbc` | `net.snowflake.client.jdbc.SnowflakeDriver` | `jdbc:snowflake://account.region.snowflakecomputing.com/?db=DEMO` |
-
-<Callout type="warn">
-JDBC URL parameters vary by database and driver version. Follow the vendor documentation. If a driver depends on multiple JARs, import or list all required JAR paths.
-</Callout>
+| Database | Common Maven Artifact | Driver Class | JDBC URL Example |
+| ---------- | -------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------- |
+| PostgreSQL | `org.postgresql:postgresql` | `org.postgresql.Driver` | `jdbc:postgresql://localhost:5432/postgres` |
+| MySQL | `com.mysql:mysql-connector-j` | `com.mysql.cj.jdbc.Driver` | `jdbc:mysql://localhost:3306/test` |
+| MariaDB | `org.mariadb.jdbc:mariadb-java-client` | `org.mariadb.jdbc.Driver` | `jdbc:mariadb://localhost:3306/test` |
+| Dameng DM | `com.dameng:DmJdbcDriver8` | `dm.jdbc.driver.DmDriver` | `jdbc:dm://localhost:5236` |
+| SQL Server | `com.microsoft.sqlserver:mssql-jdbc` | `com.microsoft.sqlserver.jdbc.SQLServerDriver` | `jdbc:sqlserver://localhost:1433;databaseName=master` |
+| Oracle | `com.oracle.database.jdbc:ojdbc11` | `oracle.jdbc.OracleDriver` | `jdbc:oracle:thin:@//localhost:1521/ORCLPDB1` |
+| H2 | `com.h2database:h2` | `org.h2.Driver` | `jdbc:h2:/tmp/dbx-h2-test` |
+| SQLite | `org.xerial:sqlite-jdbc` | `org.sqlite.JDBC` | `jdbc:sqlite:/Users/me/test.db` |
+| ClickHouse | `com.clickhouse:clickhouse-jdbc` | `com.clickhouse.jdbc.ClickHouseDriver` | `jdbc:clickhouse://localhost:8123/default` |
+| DB2 | `com.ibm.db2:jcc` | `com.ibm.db2.jcc.DB2Driver` | `jdbc:db2://localhost:50000/SAMPLE` |
+| Snowflake | `net.snowflake:snowflake-jdbc` | `net.snowflake.client.jdbc.SnowflakeDriver` | `jdbc:snowflake://account.region.snowflakecomputing.com/?db=DEMO` |
+
+<Callout type="warn">JDBC URL parameters vary by database and driver version. Follow the vendor documentation. If a driver depends on multiple JARs, import or list all required JAR paths.</Callout>
## Step 4: Import JDBC Driver JARs
@@ -129,14 +128,14 @@ Importing a driver only copies local files. It does not change your system Java
Create a new connection and choose **JDBC**.
-| Field | What to enter |
-|---|---|
-| Name | Display name, such as `H2 Test`, `DM Dev`, or `Oracle Dev` |
-| JDBC URL | Full JDBC URL, such as `jdbc:postgresql://localhost:5432/postgres` |
-| Username | Database username; leave empty if not needed |
-| Password | Database password; leave empty if not needed |
+| Field | What to enter |
+| ----------------------- | ---------------------------------------------------------------------- |
+| Name | Display name, such as `H2 Test`, `DM Dev`, or `Oracle Dev` |
+| JDBC URL | Full JDBC URL, such as `jdbc:postgresql://localhost:5432/postgres` |
+| Username | Database username; leave empty if not needed |
+| Password | Database password; leave empty if not needed |
| Driver Class (optional) | Enter it only if auto-discovery fails, such as `org.postgresql.Driver` |
-| Driver JARs | Choose an imported driver from the dropdown, or enter local JAR paths |
+| Driver JARs | Choose an imported driver from the dropdown, or enter local JAR paths |
JDBC URLs usually already include host, port, and database name, so the JDBC form does not show separate host and port fields.
@@ -153,13 +152,13 @@ DBX already has a built-in DM ODBC connection type. If you prefer the official D
5. Create a new connection and choose **JDBC**
6. Fill in:
-| Field | Value |
-|---|---|
-| JDBC URL | `jdbc:dm://127.0.0.1:5236` |
-| Username | `SYSDBA` |
-| Password | Your DM password |
-| Driver Class (optional) | `dm.jdbc.driver.DmDriver` |
-| Driver JARs | Choose the imported DM JDBC JAR |
+| Field | Value |
+| ----------------------- | ------------------------------- |
+| JDBC URL | `jdbc:dm://127.0.0.1:5236` |
+| Username | `SYSDBA` |
+| Password | Your DM password |
+| Driver Class (optional) | `dm.jdbc.driver.DmDriver` |
+| Driver JARs | Choose the imported DM JDBC JAR |
For DM, entering `dm.jdbc.driver.DmDriver` is recommended so the connection does not depend on automatic driver discovery metadata.
@@ -173,13 +172,13 @@ H2 is a good way to verify the JDBC workflow.
4. Create a new connection and choose **JDBC**
5. Fill in:
-| Field | Value |
-|---|---|
-| JDBC URL | `jdbc:h2:/tmp/dbx-h2-demo` |
-| Username | `sa` |
-| Password | Leave empty |
-| Driver Class (optional) | `org.h2.Driver` |
-| Driver JARs | Choose the imported H2 JAR |
+| Field | Value |
+| ----------------------- | -------------------------- |
+| JDBC URL | `jdbc:h2:/tmp/dbx-h2-demo` |
+| Username | `sa` |
+| Password | Leave empty |
+| Driver Class (optional) | `org.h2.Driver` |
+| Driver JARs | Choose the imported H2 JAR |
After saving, try:
@@ -201,13 +200,13 @@ SELECT * FROM users;
3. Create a new JDBC connection
4. Fill in:
-| Field | Value |
-|---|---|
-| JDBC URL | `jdbc:postgresql://localhost:5432/postgres` |
-| Username | `postgres` |
-| Password | Your PostgreSQL password |
-| Driver Class (optional) | `org.postgresql.Driver` |
-| Driver JARs | Choose the imported PostgreSQL JAR |
+| Field | Value |
+| ----------------------- | ------------------------------------------- |
+| JDBC URL | `jdbc:postgresql://localhost:5432/postgres` |
+| Username | `postgres` |
+| Password | Your PostgreSQL password |
+| Driver Class (optional) | `org.postgresql.Driver` |
+| Driver JARs | Choose the imported PostgreSQL JAR |
If SSL is required, add parameters to the JDBC URL:
@@ -296,6 +295,4 @@ The current DBX app supports plugin protocol version `1`. DBX rejects a plugin w
The initial protocol supports `testConnection`, `connect`, `executeQuery`, `listDatabases`, `listSchemas`, `listTables`, and `getColumns`.
-<Callout type="info">
-JDBC connection configs store `jdbc_driver_class` and `jdbc_driver_paths`. If a driver needs several JARs, keep all paths attached to the connection so metadata and query calls use the same classpath.
-</Callout>
+<Callout type="info">JDBC connection configs store `jdbc_driver_class` and `jdbc_driver_paths`. If a driver needs several JARs, keep all paths attached to the connection so metadata and query calls use the same classpath.</Callout>
diff --git a/docs/content/docs/query-editor.cn.mdx b/docs/content/docs/query-editor.cn.mdx
index 7d106ca5de..05592718d8 100644
--- a/docs/content/docs/query-editor.cn.mdx
+++ b/docs/content/docs/query-editor.cn.mdx
@@ -12,34 +12,36 @@ description: 使用 DBX 的 SQL 编辑器编写、补全、格式化、执行和
### 打开连接
从侧边栏选择一个数据库连接。DBX 会根据当前连接加载对应的数据库类型和元数据。
+
</Step>
<Step>
### 编写 SQL
在编辑器中输入 SQL。补全会结合 SQL 关键字、表、视图、字段和部分关系信息给出建议。
+
</Step>
<Step>
### 执行查询
使用快捷键执行全部 SQL 或选中的 SQL 片段。结果会显示在编辑器下方的数据表格中。
+
</Step>
<Step>
### 复用历史
通过查询历史找回之前执行过的语句,适合重复排查和调试。
+
</Step>
</Steps>
## 执行 SQL
-| 操作 | macOS | Windows / Linux |
-|---|---|---|
-| 执行全部 SQL | `Cmd+Enter` | `Ctrl+Enter` |
+| 操作 | macOS | Windows / Linux |
+| ------------ | ---------------------- | ----------------------- |
+| 执行全部 SQL | `Cmd+Enter` | `Ctrl+Enter` |
| 执行选中 SQL | 选中文本后 `Cmd+Enter` | 选中文本后 `Ctrl+Enter` |
-<Callout type="info">
-如果编辑器中有选中文本,DBX 只执行选中的 SQL;没有选中文本时,执行当前编辑器中的全部内容。
-</Callout>
+<Callout type="info">如果编辑器中有选中文本,DBX 只执行选中的 SQL;没有选中文本时,执行当前编辑器中的全部内容。</Callout>
执行完成后,结果区域会展示返回行、耗时、影响行数或错误信息。多语句执行时,建议先选中要执行的片段,减少误操作。
@@ -47,15 +49,13 @@ DBX 也会跟踪查询会话,离开结果集时可以关闭会话;当数据
## 执行范围
-| 范围 | 如何确定 | 适合场景 |
-|---|---|---|
-| 选中 SQL | 执行前先高亮文本 | 多语句草稿中最安全 |
+| 范围 | 如何确定 | 适合场景 |
+| -------- | ---------------------- | ---------------------------- |
+| 选中 SQL | 执行前先高亮文本 | 多语句草稿中最安全 |
| 当前语句 | 使用编辑器光标相关流程 | 不手动选择文本时运行单条语句 |
-| 全部内容 | 没有选中文本时执行 | 单用途查询标签页或短脚本 |
+| 全部内容 | 没有选中文本时执行 | 单用途查询标签页或短脚本 |
-<Callout type="warn">
-DBX 可以执行批量 SQL 和脚本,但在查询编辑器里仍建议一次运行一条已审查语句。大型 `.sql` 文件请使用带进度跟踪的 [SQL 文件执行](/cn/docs/sql-file)。
-</Callout>
+<Callout type="warn">DBX 可以执行批量 SQL 和脚本,但在查询编辑器里仍建议一次运行一条已审查语句。大型 `.sql` 文件请使用带进度跟踪的 [SQL 文件执行](/cn/docs/sql-file)。</Callout>
## 自动补全
@@ -67,9 +67,7 @@ DBX 可以执行批量 SQL 和脚本,但在查询编辑器里仍建议一次
- **JOIN 建议**:基于外键或已知关系提示可关联表和关联条件
- **SQL Server 语法**:SQL Server 连接下支持 `CROSS APPLY`、`OUTER APPLY` 等补全
-<Callout type="info">
-补全的准确性依赖当前连接的元数据。如果刚创建表或修改字段,可以刷新连接元数据后再试。
-</Callout>
+<Callout type="info">补全的准确性依赖当前连接的元数据。如果刚创建表或修改字段,可以刷新连接元数据后再试。</Callout>
## 格式化 SQL
@@ -87,9 +85,7 @@ DBX 会记录已经执行过的 SQL,方便复用:
- 适合找回临时排查 SQL、报表查询和修复语句
- 历史记录会保留足够上下文,用于区分手写查询和 AI 辅助操作
-<Callout type="warn">
-查询历史可能包含业务字段、表名或筛选条件。共享电脑或演示环境中,建议注意历史记录里的敏感信息。
-</Callout>
+<Callout type="warn">查询历史可能包含业务字段、表名或筛选条件。共享电脑或演示环境中,建议注意历史记录里的敏感信息。</Callout>
## 与数据表格配合
diff --git a/docs/content/docs/query-editor.mdx b/docs/content/docs/query-editor.mdx
index bdee567b6e..b27e9c8c60 100644
--- a/docs/content/docs/query-editor.mdx
+++ b/docs/content/docs/query-editor.mdx
@@ -12,34 +12,36 @@ The query editor is where daily SQL work happens: writing queries, using complet
### Open a Connection
Select a database connection from the sidebar. DBX loads the database type and metadata for the active connection.
+
</Step>
<Step>
### Write SQL
Type SQL in the editor. Completion suggestions use SQL keywords, tables, views, columns, and available relationship metadata.
+
</Step>
<Step>
### Execute the Query
Use the shortcut to execute all SQL or only the selected fragment. Results appear in the data grid below the editor.
+
</Step>
<Step>
### Reuse History
Open query history to bring back previously executed SQL for repeated debugging or analysis.
+
</Step>
</Steps>
## Execute SQL
-| Action | macOS | Windows / Linux |
-|---|---|---|
-| Execute all SQL | `Cmd+Enter` | `Ctrl+Enter` |
+| Action | macOS | Windows / Linux |
+| -------------------- | ----------------------------- | ------------------------------ |
+| Execute all SQL | `Cmd+Enter` | `Ctrl+Enter` |
| Execute selected SQL | Select text, then `Cmd+Enter` | Select text, then `Ctrl+Enter` |
-<Callout type="info">
-When text is selected, DBX executes only the selected SQL. When nothing is selected, it executes the full editor content.
-</Callout>
+<Callout type="info">When text is selected, DBX executes only the selected SQL. When nothing is selected, it executes the full editor content.</Callout>
After execution, the result area shows returned rows, duration, affected row count, or the error message. For multi-statement scripts, select the exact fragment you want to run to reduce mistakes.
@@ -47,15 +49,13 @@ DBX also tracks query sessions so long-running result sets can be closed when yo
## Execution Scope
-| Scope | How It Is Chosen | Use Case |
-|---|---|---|
-| Selected SQL | Highlight text before running | Safest option for multi-statement scratch pads |
+| Scope | How It Is Chosen | Use Case |
+| ----------------- | ------------------------------------------- | ------------------------------------------------- |
+| Selected SQL | Highlight text before running | Safest option for multi-statement scratch pads |
| Current statement | Use editor cursor workflows where available | Run one statement without selecting text manually |
-| Full editor | Run with no selection | Single-purpose query tabs and short scripts |
+| Full editor | Run with no selection | Single-purpose query tabs and short scripts |
-<Callout type="warn">
-DBX can execute batches and scripts, but the query editor is still safest when you run one reviewed statement at a time. Use [SQL File Execution](/en/docs/sql-file) for large `.sql` files that need progress tracking.
-</Callout>
+<Callout type="warn">DBX can execute batches and scripts, but the query editor is still safest when you run one reviewed statement at a time. Use [SQL File Execution](/en/docs/sql-file) for large `.sql` files that need progress tracking.</Callout>
## Autocomplete
@@ -67,9 +67,7 @@ Completion suggestions come from the active database context:
- **JOIN suggestions**: related tables and join conditions from foreign keys or known relationships
- **SQL Server syntax**: `CROSS APPLY`, `OUTER APPLY`, and related completions for SQL Server connections
-<Callout type="info">
-Completion accuracy depends on connection metadata. If you just created a table or changed columns, refresh the connection metadata and try again.
-</Callout>
+<Callout type="info">Completion accuracy depends on connection metadata. If you just created a table or changed columns, refresh the connection metadata and try again.</Callout>
## Format SQL
@@ -87,9 +85,7 @@ DBX records executed SQL so you can reuse it later:
- Useful for investigation queries, reports, and repair statements
- History entries preserve enough context to identify manual queries and AI-assisted work
-<Callout type="warn">
-Query history may include business fields, table names, or filter values. Be mindful of sensitive information on shared machines or demo environments.
-</Callout>
+<Callout type="warn">Query history may include business fields, table names, or filter values. Be mindful of sensitive information on shared machines or demo environments.</Callout>
## Working With the Data Grid
diff --git a/docs/content/docs/redis.cn.mdx b/docs/content/docs/redis.cn.mdx
index 2929da17e2..ccc77a0e70 100644
--- a/docs/content/docs/redis.cn.mdx
+++ b/docs/content/docs/redis.cn.mdx
@@ -14,22 +14,20 @@ Redis 键浏览器以表格形式展示键,便于扫描和过滤:
- 使用搜索栏按模式过滤键(如 `user:*`、`cache:*`)
- 内联显示键类型、TTL 和大小
-<Callout type="info">
-对于包含数百万键的 Redis 实例,建议在搜索栏中使用具体的键模式,而不是加载整个键空间。可在设置中调整扫描页大小,以控制每批获取的键数量。
-</Callout>
+<Callout type="info">对于包含数百万键的 Redis 实例,建议在搜索栏中使用具体的键模式,而不是加载整个键空间。可在设置中调整扫描页大小,以控制每批获取的键数量。</Callout>
## 值查看器与编辑器
每种 Redis 数据类型都有专用的查看器和编辑器:
-| 类型 | 查看器 | 编辑方式 |
-|---|---|---|
-| String | 纯文本或 JSON 查看器 | 内联文本编辑 |
-| Hash | 可调整列宽的字段/值表格 | 编辑单个字段 |
-| List | 带索引的有序列表 | 添加、删除、重排元素 |
-| Set | 带基数的成员列表 | 添加和删除成员 |
-| Sorted Set | 带分数的成员列表 | 编辑成员和分数 |
-| Stream | 带 ID 的条目列表 | 查看流条目 |
+| 类型 | 查看器 | 编辑方式 |
+| ---------- | ----------------------- | -------------------- |
+| String | 纯文本或 JSON 查看器 | 内联文本编辑 |
+| Hash | 可调整列宽的字段/值表格 | 编辑单个字段 |
+| List | 带索引的有序列表 | 添加、删除、重排元素 |
+| Set | 带基数的成员列表 | 添加和删除成员 |
+| Sorted Set | 带分数的成员列表 | 编辑成员和分数 |
+| Stream | 带 ID 的条目列表 | 查看流条目 |
## JSON 值查看器
@@ -43,9 +41,7 @@ Redis 键浏览器以表格形式展示键,便于扫描和过滤:
- 按值查找 Hash 字段
- 对于大型键空间,结果会逐步流式返回
-<Callout type="warn">
-值搜索会扫描匹配当前模式的所有键。在大型数据库上这可能会消耗大量资源。在开始值搜索之前,请先缩小键模式范围。
-</Callout>
+<Callout type="warn">值搜索会扫描匹配当前模式的所有键。在大型数据库上这可能会消耗大量资源。在开始值搜索之前,请先缩小键模式范围。</Callout>
## 批量操作
diff --git a/docs/content/docs/redis.mdx b/docs/content/docs/redis.mdx
index 5d14b758d1..ffd0ab7c67 100644
--- a/docs/content/docs/redis.mdx
+++ b/docs/content/docs/redis.mdx
@@ -14,22 +14,20 @@ The Redis key browser displays keys in a table format for easier scanning and fi
- Use the search bar to filter keys by pattern (e.g., `user:*`, `cache:*`)
- Key type, TTL, and size are shown inline
-<Callout type="info">
-For Redis instances with millions of keys, use specific key patterns in the search bar instead of loading the entire keyspace. Set the scan page size in Settings to control how many keys are fetched per batch.
-</Callout>
+<Callout type="info">For Redis instances with millions of keys, use specific key patterns in the search bar instead of loading the entire keyspace. Set the scan page size in Settings to control how many keys are fetched per batch.</Callout>
## Value Viewer and Editor
Each Redis data type has a dedicated viewer and editor:
-| Type | Viewer | Editing |
-|---|---|---|
-| String | Plain text or JSON viewer | Inline text edit |
-| Hash | Field/value table with resizable columns | Edit individual fields |
-| List | Ordered list with index | Add, remove, reorder elements |
-| Set | Member list with cardinality | Add and remove members |
-| Sorted Set | Member list with scores | Edit members and scores |
-| Stream | Entry list with IDs | View stream entries |
+| Type | Viewer | Editing |
+| ---------- | ---------------------------------------- | ----------------------------- |
+| String | Plain text or JSON viewer | Inline text edit |
+| Hash | Field/value table with resizable columns | Edit individual fields |
+| List | Ordered list with index | Add, remove, reorder elements |
+| Set | Member list with cardinality | Add and remove members |
+| Sorted Set | Member list with scores | Edit members and scores |
+| Stream | Entry list with IDs | View stream entries |
## JSON Value Viewer
@@ -43,9 +41,7 @@ Search Redis values by content, not just keys:
- Find Hash fields by value
- Results are streamed progressively for large keyspaces
-<Callout type="warn">
-Value search scans all keys that match the current pattern. On large databases this can be resource-intensive. Narrow the key pattern before starting a value search.
-</Callout>
+<Callout type="warn">Value search scans all keys that match the current pattern. On large databases this can be resource-intensive. Narrow the key pattern before starting a value search.</Callout>
## Bulk Operations
diff --git a/docs/content/docs/schema-browser.cn.mdx b/docs/content/docs/schema-browser.cn.mdx
index 2615c2ea56..5c126802d3 100644
--- a/docs/content/docs/schema-browser.cn.mdx
+++ b/docs/content/docs/schema-browser.cn.mdx
@@ -21,13 +21,13 @@ description: 使用侧边栏浏览连接、数据库、Schema、表、字段和
## 不同数据库的树结构
-| 连接类型 | 浏览模型 |
-|---|---|
+| 连接类型 | 浏览模型 |
+| ------------ | ------------------------------------------------------------------------------- |
| 关系型数据库 | 连接、数据库、Schema、表/视图、字段、索引、外键、触发器,以及可获取元数据的例程 |
-| Redis | Redis 数据库和键,并为 String、Hash、List、Set、Sorted Set、Stream 提供值编辑 |
-| MongoDB | 数据库、集合和分页文档浏览 |
-| 对象浏览器 | 在数据库支持时查看视图、存储过程和函数源码 |
-| 保存的 SQL | 侧边栏中的 SQL 文件夹和可复用 SQL 文件 |
+| Redis | Redis 数据库和键,并为 String、Hash、List、Set、Sorted Set、Stream 提供值编辑 |
+| MongoDB | 数据库、集合和分页文档浏览 |
+| 对象浏览器 | 在数据库支持时查看视图、存储过程和函数源码 |
+| 保存的 SQL | 侧边栏中的 SQL 文件夹和可复用 SQL 文件 |
## 搜索
@@ -38,9 +38,7 @@ description: 使用侧边栏浏览连接、数据库、Schema、表、字段和
- 字段名
- 部分数据库对象路径
-<Callout type="info">
-当连接中有大量表时,搜索会优先面向可见对象和缓存的元数据工作。刚刷新或首次展开的对象,可能需要等待元数据加载完成后才能完整匹配。
-</Callout>
+<Callout type="info">当连接中有大量表时,搜索会优先面向可见对象和缓存的元数据工作。刚刷新或首次展开的对象,可能需要等待元数据加载完成后才能完整匹配。</Callout>
## 置顶
@@ -55,17 +53,15 @@ description: 使用侧边栏浏览连接、数据库、Schema、表、字段和
不同节点会显示不同的上下文操作:
-| 节点 | 常用操作 |
-|---|---|
-| 连接 | 刷新元数据、复制连接、断开连接、编辑连接 |
-| 数据库 | 创建数据库、删除数据库、导出数据库 |
-| Schema | 创建 Schema、删除 Schema |
-| 表 | 打开数据、查看结构、导入数据、复制表名、删除表 |
-| 字段 | 复制字段名、查看字段信息 |
+| 节点 | 常用操作 |
+| ------ | ---------------------------------------------- |
+| 连接 | 刷新元数据、复制连接、断开连接、编辑连接 |
+| 数据库 | 创建数据库、删除数据库、导出数据库 |
+| Schema | 创建 Schema、删除 Schema |
+| 表 | 打开数据、查看结构、导入数据、复制表名、删除表 |
+| 字段 | 复制字段名、查看字段信息 |
-<Callout type="warn">
-删除数据库、删除 Schema、删除表等操作可能不可恢复。执行前请确认当前连接环境,必要时先备份。
-</Callout>
+<Callout type="warn">删除数据库、删除 Schema、删除表等操作可能不可恢复。执行前请确认当前连接环境,必要时先备份。</Callout>
## 字段注释
@@ -75,12 +71,12 @@ description: 使用侧边栏浏览连接、数据库、Schema、表、字段和
可以给连接设置颜色,用于区分环境。例如:
-| 环境 | 建议颜色 |
-|---|---|
+| 环境 | 建议颜色 |
+| ---- | ---------- |
| 本地 | 灰色或绿色 |
| 测试 | 蓝色或紫色 |
-| 预发 | 黄色 |
-| 生产 | 红色 |
+| 预发 | 黄色 |
+| 生产 | 红色 |
颜色会出现在侧边栏连接名称和标签页中,帮助减少误操作。
@@ -97,10 +93,10 @@ Redis 键空间较大时,建议配合搜索和分页使用,避免一次性
## 功能边界
-| 功能 | 支持类型 |
-|---|---|
-| Schema 感知树 | PostgreSQL、SQL Server、Oracle、Redshift、DM、GaussDB、KingBase、HighGo、Vastbase、JDBC、H2、Snowflake、Trino、DB2、TDengine |
-| ER 图 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM、GaussDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、DB2 |
-| 数据库搜索 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DuckDB、ClickHouse、DM、GaussDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、TDengine |
+| 功能 | 支持类型 |
+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Schema 感知树 | PostgreSQL、SQL Server、Oracle、Redshift、DM、GaussDB、KingBase、HighGo、Vastbase、JDBC、H2、Snowflake、Trino、DB2、TDengine |
+| ER 图 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DM、GaussDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、DB2 |
+| 数据库搜索 | MySQL、PostgreSQL、SQLite、SQL Server、Oracle、Redshift、DuckDB、ClickHouse、DM、GaussDB、KingBase、HighGo、Vastbase、GoldenDB、Access、H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、TDengine |
如果某个节点菜单里没有对应操作,通常说明当前数据库类型没有暴露所需元数据,或 DBX 没有足够把握生成安全 SQL。
diff --git a/docs/content/docs/schema-browser.mdx b/docs/content/docs/schema-browser.mdx
index b50d513025..4b85d741ce 100644
--- a/docs/content/docs/schema-browser.mdx
+++ b/docs/content/docs/schema-browser.mdx
@@ -21,13 +21,13 @@ Expand or collapse nodes to drill down. Click a table to open its data. Column e
## Database-Specific Trees
-| Connection Type | Browser Model |
-|---|---|
+| Connection Type | Browser Model |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Relational databases | Connection, database, schema, tables/views, columns, indexes, foreign keys, triggers, and routines where metadata is available |
-| Redis | Redis databases and keys, with value editors for String, Hash, List, Set, Sorted Set, and Stream |
-| MongoDB | Databases, collections, and paginated document browsing |
-| Object browser | Views, procedures, and functions when the database exposes source metadata |
-| Saved SQL | Folders and reusable SQL files in the sidebar library |
+| Redis | Redis databases and keys, with value editors for String, Hash, List, Set, Sorted Set, and Stream |
+| MongoDB | Databases, collections, and paginated document browsing |
+| Object browser | Views, procedures, and functions when the database exposes source metadata |
+| Saved SQL | Folders and reusable SQL files in the sidebar library |
## Search
@@ -38,9 +38,7 @@ Sidebar search helps locate objects when a connection contains many tables:
- Column names
- Parts of database object paths
-<Callout type="info">
-For large schemas, search works best with visible objects and cached metadata. Objects that were just refreshed or not yet expanded may need metadata loading before they are fully matched.
-</Callout>
+<Callout type="info">For large schemas, search works best with visible objects and cached metadata. Objects that were just refreshed or not yet expanded may need metadata loading before they are fully matched.</Callout>
## Pinning
@@ -55,17 +53,15 @@ Pin frequently used connections, databases, or tables to reduce repeated navigat
Different node types expose different actions:
-| Node | Common Actions |
-|---|---|
+| Node | Common Actions |
+| ---------- | ------------------------------------------------------------------- |
| Connection | Refresh metadata, duplicate connection, disconnect, edit connection |
-| Database | Create database, drop database, export database |
-| Schema | Create schema, drop schema |
-| Table | Open data, open structure, import data, copy table name, drop table |
-| Column | Copy column name, inspect column details |
+| Database | Create database, drop database, export database |
+| Schema | Create schema, drop schema |
+| Table | Open data, open structure, import data, copy table name, drop table |
+| Column | Copy column name, inspect column details |
-<Callout type="warn">
-Dropping databases, schemas, or tables may be irreversible. Confirm the active connection and back up data when needed.
-</Callout>
+<Callout type="warn">Dropping databases, schemas, or tables may be irreversible. Confirm the active connection and back up data when needed.</Callout>
## Column Comments
@@ -76,11 +72,11 @@ When the database supports column comments, DBX displays them next to columns. T
Connection colors help separate environments:
| Environment | Suggested Color |
-|---|---|
-| Local | Gray or green |
-| Test | Blue or purple |
-| Staging | Yellow |
-| Production | Red |
+| ----------- | --------------- |
+| Local | Gray or green |
+| Test | Blue or purple |
+| Staging | Yellow |
+| Production | Red |
Colors appear beside connection names in the sidebar and in tabs, reducing the chance of operating on the wrong environment.
@@ -97,10 +93,10 @@ For large Redis keyspaces, use search and pagination together instead of expandi
## Feature Boundaries
-| Feature | Supported Types |
-|---|---|
-| Schema-aware tree | PostgreSQL, SQL Server, Oracle, Redshift, DM, GaussDB, KingBase, HighGo, Vastbase, JDBC, H2, Snowflake, Trino, DB2, TDengine |
-| ER diagram | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, GaussDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, DB2 |
-| Database search | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DuckDB, ClickHouse, DM, GaussDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, Snowflake, Trino, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, TDengine |
+| Feature | Supported Types |
+| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Schema-aware tree | PostgreSQL, SQL Server, Oracle, Redshift, DM, GaussDB, KingBase, HighGo, Vastbase, JDBC, H2, Snowflake, Trino, DB2, TDengine |
+| ER diagram | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DM, GaussDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, DB2 |
+| Database search | MySQL, PostgreSQL, SQLite, SQL Server, Oracle, Redshift, DuckDB, ClickHouse, DM, GaussDB, KingBase, HighGo, Vastbase, GoldenDB, Access, H2, Snowflake, Trino, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, TDengine |
If an action is missing from a node menu, the active database type may not expose the required metadata or safe SQL generation path.
diff --git a/docs/content/docs/schema-diff.cn.mdx b/docs/content/docs/schema-diff.cn.mdx
index dea0f981b3..e1d5a92b01 100644
--- a/docs/content/docs/schema-diff.cn.mdx
+++ b/docs/content/docs/schema-diff.cn.mdx
@@ -5,9 +5,7 @@ description: 对比两个数据库的结构差异,生成可审查的同步 SQL
Schema 对比用于检查两个数据库环境之间的结构差异,例如开发库和生产库、测试库和预发库,或迁移前后的数据库。
-<Callout type="warn">
-Schema 同步可能包含删除表、删除字段、修改字段类型等破坏性操作。生成 SQL 后请逐条审查,生产环境建议先备份。
-</Callout>
+<Callout type="warn">Schema 同步可能包含删除表、删除字段、修改字段类型等破坏性操作。生成 SQL 后请逐条审查,生产环境建议先备份。</Callout>
## 适合的场景
@@ -23,41 +21,44 @@ Schema 同步可能包含删除表、删除字段、修改字段类型等破坏
### 选择源库
源库通常是你认为“结构较新”或“结构正确”的数据库。
+
</Step>
<Step>
### 选择目标库
目标库是需要被检查或同步的数据库。它可以和源库位于不同服务器,也可以是不同数据库引擎。
+
</Step>
<Step>
### 执行对比
DBX 会读取两边的表、字段和索引元数据,并计算差异。当前对比只处理表,不包含视图。
+
</Step>
<Step>
### 审查差异
重点检查缺失表、额外表、字段类型变化、是否允许 NULL、默认值变化、索引增删和可能的数据风险。
+
</Step>
<Step>
### 生成同步 SQL
根据差异生成 `CREATE TABLE`、`ALTER TABLE`、`DROP TABLE` 等语句。确认后再决定是否执行。
+
</Step>
</Steps>
## 差异类型
-| 类型 | 含义 |
-|---|---|
-| 仅源库存在 | 目标库缺少该对象,通常需要创建 |
+| 类型 | 含义 |
+| ------------ | -------------------------------------------- |
+| 仅源库存在 | 目标库缺少该对象,通常需要创建 |
| 仅目标库存在 | 目标库多出该对象,删除前需要确认是否仍被使用 |
-| 字段差异 | 字段类型、是否允许 NULL 或默认值不同 |
-| 索引差异 | 按索引名称检查新增或删除的索引 |
+| 字段差异 | 字段类型、是否允许 NULL 或默认值不同 |
+| 索引差异 | 按索引名称检查新增或删除的索引 |
-<Callout type="info">
-当前 Schema 对比不完整覆盖外键、触发器、视图定义、字段注释,也不会检测同名索引的列或唯一性变化。重要迁移仍建议人工审查生成的 SQL。
-</Callout>
+<Callout type="info">当前 Schema 对比不完整覆盖外键、触发器、视图定义、字段注释,也不会检测同名索引的列或唯一性变化。重要迁移仍建议人工审查生成的 SQL。</Callout>
## 数据库覆盖范围
diff --git a/docs/content/docs/schema-diff.mdx b/docs/content/docs/schema-diff.mdx
index dabca38a43..9abd673783 100644
--- a/docs/content/docs/schema-diff.mdx
+++ b/docs/content/docs/schema-diff.mdx
@@ -5,9 +5,7 @@ description: Compare two database schemas and generate reviewable sync SQL.
Schema Diff helps compare structure between database environments, such as development and production, staging and QA, or databases before and after a migration.
-<Callout type="warn">
-Schema sync may include destructive operations such as dropping tables, dropping columns, or changing column types. Review generated SQL line by line, and back up production databases first.
-</Callout>
+<Callout type="warn">Schema sync may include destructive operations such as dropping tables, dropping columns, or changing column types. Review generated SQL line by line, and back up production databases first.</Callout>
## Use Cases
@@ -23,41 +21,44 @@ Schema sync may include destructive operations such as dropping tables, dropping
### Select the Source
The source is usually the database whose structure is newer or considered correct.
+
</Step>
<Step>
### Select the Target
The target is the database to inspect or sync. It can be on another server or even another database engine.
+
</Step>
<Step>
### Run the Comparison
DBX reads table, column, and index metadata from both sides. The current comparison handles tables, not views.
+
</Step>
<Step>
### Review Differences
Check missing tables, extra tables, column type changes, nullable changes, default value changes, added or removed indexes, and data risk.
+
</Step>
<Step>
### Generate Sync SQL
DBX generates statements such as `CREATE TABLE`, `ALTER TABLE`, and `DROP TABLE`. Review them before execution.
+
</Step>
</Steps>
## Difference Types
-| Type | Meaning |
-|---|---|
-| Source only | The object is missing from the target and may need to be created |
-| Target only | The object exists only in the target; confirm usage before dropping it |
-| Column difference | Type, nullable flag, or default value differs |
-| Index difference | Added or removed indexes, matched by index name |
+| Type | Meaning |
+| ----------------- | ---------------------------------------------------------------------- |
+| Source only | The object is missing from the target and may need to be created |
+| Target only | The object exists only in the target; confirm usage before dropping it |
+| Column difference | Type, nullable flag, or default value differs |
+| Index difference | Added or removed indexes, matched by index name |
-<Callout type="info">
-Schema Diff currently does not fully compare foreign keys, triggers, view definitions, column comments, or changed columns/uniqueness inside an index with the same name. Important migrations still need manual SQL review.
-</Callout>
+<Callout type="info">Schema Diff currently does not fully compare foreign keys, triggers, view definitions, column comments, or changed columns/uniqueness inside an index with the same name. Important migrations still need manual SQL review.</Callout>
## Database Coverage
diff --git a/docs/content/docs/sql-file.cn.mdx b/docs/content/docs/sql-file.cn.mdx
index a2a2b224cc..0a93d920ce 100644
--- a/docs/content/docs/sql-file.cn.mdx
+++ b/docs/content/docs/sql-file.cn.mdx
@@ -5,9 +5,7 @@ description: 选择连接后执行 .sql 文件,查看进度,并在需要时
SQL 文件执行用于导入或运行本地 `.sql` 脚本。它适合执行初始化脚本、数据补丁、数据库导出文件和迁移脚本。
-<Callout type="warn">
-执行 SQL 文件可能修改大量数据或结构。运行前请确认目标连接、目标数据库和脚本来源,生产环境建议先备份。
-</Callout>
+<Callout type="warn">执行 SQL 文件可能修改大量数据或结构。运行前请确认目标连接、目标数据库和脚本来源,生产环境建议先备份。</Callout>
## 使用流程
@@ -16,26 +14,31 @@ SQL 文件执行用于导入或运行本地 `.sql` 脚本。它适合执行初
### 打开 SQL 文件执行
在 DBX 中打开 SQL 文件执行面板。
+
</Step>
<Step>
### 选择文件
选择本地 `.sql` 文件。大文件可能需要更长解析和执行时间。
+
</Step>
<Step>
### 选择目标连接
选择要执行脚本的数据库连接和数据库。
+
</Step>
<Step>
### 开始执行
点击执行后,DBX 会按语句执行并显示进度。
+
</Step>
<Step>
### 检查结果
执行结束后查看成功数量、失败语句和错误信息。
+
</Step>
</Steps>
@@ -61,9 +64,7 @@ SQL 文件执行面向 SQL 类数据库。Redis、MongoDB 和 Elasticsearch 不
执行过程中可以取消任务。取消只会阻止后续语句继续执行,已经提交到数据库的语句不会自动回滚。
-<Callout type="info">
-如果脚本需要整体原子性,建议脚本本身包含事务控制,并确认目标数据库支持相关事务语义。
-</Callout>
+<Callout type="info">如果脚本需要整体原子性,建议脚本本身包含事务控制,并确认目标数据库支持相关事务语义。</Callout>
## 执行前检查
diff --git a/docs/content/docs/sql-file.mdx b/docs/content/docs/sql-file.mdx
index 4a2a39e789..9a8cf413d8 100644
--- a/docs/content/docs/sql-file.mdx
+++ b/docs/content/docs/sql-file.mdx
@@ -5,9 +5,7 @@ description: Execute .sql files against a selected connection, monitor progress,
SQL File Execution runs local `.sql` scripts in DBX. Use it for initialization scripts, data patches, database dumps, and migration scripts.
-<Callout type="warn">
-SQL files may modify large amounts of data or schema. Confirm the target connection, target database, and script source before running. Back up production databases first.
-</Callout>
+<Callout type="warn">SQL files may modify large amounts of data or schema. Confirm the target connection, target database, and script source before running. Back up production databases first.</Callout>
## Workflow
@@ -16,26 +14,31 @@ SQL files may modify large amounts of data or schema. Confirm the target connect
### Open SQL File Execution
Open the SQL file execution panel in DBX.
+
</Step>
<Step>
### Choose a File
Select a local `.sql` file. Large files may take longer to parse and execute.
+
</Step>
<Step>
### Select Target Connection
Choose the connection and database where the script should run.
+
</Step>
<Step>
### Start Execution
DBX executes the script statement by statement and shows progress.
+
</Step>
<Step>
### Check Results
After execution, review successful statements, failed statements, and error messages.
+
</Step>
</Steps>
@@ -61,9 +64,7 @@ By default, execution stops when a statement fails. You can enable continue-on-e
You can cancel while execution is running. Cancelling stops later statements from running, but statements already submitted to the database are not rolled back automatically.
-<Callout type="info">
-If a script must be atomic, include transaction control in the script itself and confirm the target database supports the required transaction behavior.
-</Callout>
+<Callout type="info">If a script must be atomic, include transaction control in the script itself and confirm the target database supports the required transaction behavior.</Callout>
## Before Running
diff --git a/docs/content/docs/sql-snippets.cn.mdx b/docs/content/docs/sql-snippets.cn.mdx
index 3dbae73d67..4aa33b1be6 100644
--- a/docs/content/docs/sql-snippets.cn.mdx
+++ b/docs/content/docs/sql-snippets.cn.mdx
@@ -15,20 +15,9 @@ SQL 代码片段允许你定义可复用的 SQL 模板,输入触发键时自
## 创建代码片段
<Steps>
- <Step>
- ### 打开代码片段设置
- 前往**设置 → SQL 代码片段**。
- </Step>
- <Step>
- ### 添加新片段
- 点击**添加片段**并填写:
- - **触发键**:在编辑器中输入的简短关键字(如 `selall`、`joinex`)
- - **模板**:替换触发键的 SQL 文本
- </Step>
- <Step>
- ### 使用代码片段
- 在 SQL 编辑器中输入触发键,然后按 `Tab` 或从自动补全列表中选择。模板会在光标处展开。
- </Step>
+ <Step>### 打开代码片段设置 前往**设置 → SQL 代码片段**。</Step>
+ <Step>### 添加新片段 点击**添加片段**并填写: - **触发键**:在编辑器中输入的简短关键字(如 `selall`、`joinex`) - **模板**:替换触发键的 SQL 文本</Step>
+ <Step>### 使用代码片段 在 SQL 编辑器中输入触发键,然后按 `Tab` 或从自动补全列表中选择。模板会在光标处展开。</Step>
</Steps>
## 示例片段
@@ -36,6 +25,7 @@ SQL 代码片段允许你定义可复用的 SQL 模板,输入触发键时自
以下是一些实用的片段模板:
**带常用子句的 SELECT:**
+
```sql
SELECT ${1:columns}
FROM ${2:table}
@@ -44,11 +34,13 @@ ORDER BY ${4:column}
```
**LEFT JOIN 模式:**
+
```sql
LEFT JOIN ${1:table} ON ${2:left_alias}.${3:column} = ${4:right_alias}.${5:column}
```
**带 GROUP BY 的 COUNT:**
+
```sql
SELECT ${1:column}, COUNT(*) AS cnt
FROM ${2:table}
@@ -58,6 +50,7 @@ ORDER BY cnt DESC
```
**CREATE TABLE 模板:**
+
```sql
CREATE TABLE ${1:table_name} (
${2:id} INTEGER PRIMARY KEY,
diff --git a/docs/content/docs/sql-snippets.mdx b/docs/content/docs/sql-snippets.mdx
index d52d5402fe..23ca7fdd6a 100644
--- a/docs/content/docs/sql-snippets.mdx
+++ b/docs/content/docs/sql-snippets.mdx
@@ -15,20 +15,9 @@ SQL Snippets let you define reusable SQL templates that expand automatically whe
## Creating A Snippet
<Steps>
- <Step>
- ### Open Snippet Settings
- Go to **Settings → SQL Snippets**.
- </Step>
- <Step>
- ### Add a New Snippet
- Click **Add Snippet** and fill in:
- - **Trigger**: a short key you type in the editor (e.g., `selall`, `joinex`)
- - **Template**: the SQL text that replaces the trigger
- </Step>
- <Step>
- ### Use the Snippet
- In the SQL editor, type the trigger key and press `Tab` or select it from the autocomplete list. The template expands in place.
- </Step>
+ <Step>### Open Snippet Settings Go to **Settings → SQL Snippets**.</Step>
+ <Step>### Add a New Snippet Click **Add Snippet** and fill in: - **Trigger**: a short key you type in the editor (e.g., `selall`, `joinex`) - **Template**: the SQL text that replaces the trigger</Step>
+ <Step>### Use the Snippet In the SQL editor, type the trigger key and press `Tab` or select it from the autocomplete list. The template expands in place.</Step>
</Steps>
## Example Snippets
@@ -36,6 +25,7 @@ SQL Snippets let you define reusable SQL templates that expand automatically whe
Here are some useful snippet templates to get started:
**SELECT with common clauses:**
+
```sql
SELECT ${1:columns}
FROM ${2:table}
@@ -44,11 +34,13 @@ ORDER BY ${4:column}
```
**LEFT JOIN pattern:**
+
```sql
LEFT JOIN ${1:table} ON ${2:left_alias}.${3:column} = ${4:right_alias}.${5:column}
```
**COUNT with GROUP BY:**
+
```sql
SELECT ${1:column}, COUNT(*) AS cnt
FROM ${2:table}
@@ -58,6 +50,7 @@ ORDER BY cnt DESC
```
**CREATE TABLE template:**
+
```sql
CREATE TABLE ${1:table_name} (
${2:id} INTEGER PRIMARY KEY,
diff --git a/docs/content/docs/ssh-tunnel.cn.mdx b/docs/content/docs/ssh-tunnel.cn.mdx
index 1379775e78..44eb8fe2bf 100644
--- a/docs/content/docs/ssh-tunnel.cn.mdx
+++ b/docs/content/docs/ssh-tunnel.cn.mdx
@@ -3,9 +3,7 @@ title: SSH 隧道
description: 通过 SSH 隧道安全连接防火墙后的数据库,支持密码和密钥认证。
---
-<Callout type="info">
-内置 SSH 隧道,无需在终端手动建立。支持密码和密钥认证,可选暴露给局域网供团队共享。
-</Callout>
+<Callout type="info">内置 SSH 隧道,无需在终端手动建立。支持密码和密钥认证,可选暴露给局域网供团队共享。</Callout>
当数据库服务器不允许直接远程访问时(例如在防火墙或私有网络后面),你可以通过 SSH 隧道安全地连接。
@@ -13,12 +11,12 @@ description: 通过 SSH 隧道安全连接防火墙后的数据库,支持密
在创建或编辑数据库连接时,启用"SSH 隧道"选项:
-| 字段 | 说明 |
-|---|---|
-| SSH 主机 | SSH 服务器的地址 |
-| SSH 端口 | SSH 端口(默认 22) |
-| SSH 用户名 | 登录 SSH 服务器的用户名 |
-| 连接超时 | DBX 等待 SSH 连接建立的最长时间,默认 5 秒 |
+| 字段 | 说明 |
+| ---------- | ------------------------------------------ |
+| SSH 主机 | SSH 服务器的地址 |
+| SSH 端口 | SSH 端口(默认 22) |
+| SSH 用户名 | 登录 SSH 服务器的用户名 |
+| 连接超时 | DBX 等待 SSH 连接建立的最长时间,默认 5 秒 |
## 认证方式
@@ -30,6 +28,7 @@ description: 通过 SSH 隧道安全连接防火墙后的数据库,支持密
- **密钥密码** — 如果私钥设置了密码保护,在此输入
密钥认证比密码认证更安全,推荐优先使用。
+
</Tab>
<Tab value="密码认证">
输入 SSH 用户的登录密码即可。适用于允许密码登录的服务器。
@@ -38,9 +37,7 @@ description: 通过 SSH 隧道安全连接防火墙后的数据库,支持密
## 允许局域网访问
-<Callout type="warn">
-启用"允许局域网访问"后,同一网络中的其他设备也可以通过你的机器访问该 SSH 隧道。仅在可信网络中启用此选项。
-</Callout>
+<Callout type="warn">启用"允许局域网访问"后,同一网络中的其他设备也可以通过你的机器访问该 SSH 隧道。仅在可信网络中启用此选项。</Callout>
默认情况下,SSH 隧道仅监听 `localhost`。启用局域网访问后,隧道绑定到 `0.0.0.0`,适用于团队协作或多设备共享数据库连接的场景。
diff --git a/docs/content/docs/ssh-tunnel.mdx b/docs/content/docs/ssh-tunnel.mdx
index db313c0bd0..f27d85a6be 100644
--- a/docs/content/docs/ssh-tunnel.mdx
+++ b/docs/content/docs/ssh-tunnel.mdx
@@ -3,9 +3,7 @@ title: SSH Tunnel
description: Connect securely to databases behind firewalls via SSH tunnel. Password and key authentication.
---
-<Callout type="info">
-Built-in SSH tunnel — no manual terminal setup. Supports password and private key authentication, with optional LAN exposure for team sharing.
-</Callout>
+<Callout type="info">Built-in SSH tunnel — no manual terminal setup. Supports password and private key authentication, with optional LAN exposure for team sharing.</Callout>
DBX can connect to databases through an SSH tunnel, allowing secure access to servers behind firewalls or on private networks.
@@ -13,11 +11,11 @@ DBX can connect to databases through an SSH tunnel, allowing secure access to se
When creating or editing a connection, enable the SSH tunnel option:
-| Field | Description |
-|---|---|
-| SSH Host | Hostname or IP of the SSH server |
-| SSH Port | Port for SSH (default: 22) |
-| SSH User | Username for SSH authentication |
+| Field | Description |
+| --------------- | ----------------------------------------------------------------------------- |
+| SSH Host | Hostname or IP of the SSH server |
+| SSH Port | Port for SSH (default: 22) |
+| SSH User | Username for SSH authentication |
| Connect Timeout | Maximum time DBX waits while opening the SSH connection; default is 5 seconds |
## Authentication Methods
@@ -30,6 +28,7 @@ When creating or editing a connection, enable the SSH tunnel option:
- **Key Passphrase** — Enter the passphrase if your key is password-protected
Key authentication is more secure than password authentication.
+
</Tab>
<Tab value="Password">
Enter your SSH password directly. Works on servers that allow password authentication.
@@ -38,9 +37,7 @@ When creating or editing a connection, enable the SSH tunnel option:
## Expose Tunnel to LAN
-<Callout type="warn">
-Enabling LAN exposure means any device on the same network can access the tunneled database port. Only enable this on trusted networks.
-</Callout>
+<Callout type="warn">Enabling LAN exposure means any device on the same network can access the tunneled database port. Only enable this on trusted networks.</Callout>
By default, the SSH tunnel listens on `localhost` only. Enable LAN exposure to bind to `0.0.0.0`, making the tunnel accessible to other devices on your network — useful for team collaboration or multi-device access.
diff --git a/docs/content/docs/table-import.cn.mdx b/docs/content/docs/table-import.cn.mdx
index 5fe6a9dee3..bf98f71f86 100644
--- a/docs/content/docs/table-import.cn.mdx
+++ b/docs/content/docs/table-import.cn.mdx
@@ -7,11 +7,11 @@ description: 将 CSV、TSV、JSON 或 Excel 文件导入数据库表,并检查
## 支持的文件
-| 格式 | 说明 |
-|---|---|
-| CSV | 逗号分隔文本,适合通用数据交换 |
-| TSV | 制表符分隔文本,适合字段中包含逗号的场景 |
-| JSON | JSON 数组,适合从接口或脚本导出的数据 |
+| 格式 | 说明 |
+| ----- | ----------------------------------------------------- |
+| CSV | 逗号分隔文本,适合通用数据交换 |
+| TSV | 制表符分隔文本,适合字段中包含逗号的场景 |
+| JSON | JSON 数组,适合从接口或脚本导出的数据 |
| Excel | `.xlsx`、`.xlsm` 或 `.xls` 文件;DBX 读取第一个工作表 |
DBX 会在导入前预览前 50 行。CSV/TSV 中的空单元格会按 `NULL` 处理。JSON 可以是单个对象、对象数组或数组行;对象行和数组行混用会被拒绝。
@@ -23,39 +23,42 @@ DBX 会在导入前预览前 50 行。CSV/TSV 中的空单元格会按 `NULL`
### 选择目标表
在侧边栏中右键目标表,选择 **导入数据**。
+
</Step>
<Step>
### 选择文件
选择要导入的 CSV、TSV、JSON 或 Excel 文件。
+
</Step>
<Step>
### 检查列映射
DBX 会按列名尝试匹配文件字段和数据库字段。请检查主键、必填字段、日期字段和数值字段。
+
</Step>
<Step>
### 选择导入模式
选择追加或清空后导入。清空模式会先删除目标表已有数据。
+
</Step>
<Step>
### 执行并检查结果
导入完成后检查成功行数、失败原因和目标表数据。
+
</Step>
</Steps>
## 导入模式
-| 模式 | 行为 | 适合场景 |
-|---|---|---|
-| 追加 | 保留原有数据,继续插入新行 | 补充数据、追加样例数据 |
+| 模式 | 行为 | 适合场景 |
+| ---------- | ---------------------------- | ------------------------ |
+| 追加 | 保留原有数据,继续插入新行 | 补充数据、追加样例数据 |
| 清空后导入 | 先清空目标表,再导入文件内容 | 重建测试表、替换临时数据 |
-<Callout type="warn">
-清空后导入会删除目标表中的现有数据。生产环境使用前请确认备份和影响范围。
-</Callout>
+<Callout type="warn">清空后导入会删除目标表中的现有数据。生产环境使用前请确认备份和影响范围。</Callout>
导入会分批执行。默认批大小为 500 行,进度视图会显示已导入行数、总行数、错误和取消状态。
@@ -82,9 +85,9 @@ DBX 会在导入前预览前 50 行。CSV/TSV 中的空单元格会按 `NULL`
## 常见问题
-| 现象 | 可能原因 |
-|---|---|
-| 部分列没有导入 | 文件列名和表字段名不匹配,或列被取消映射 |
-| 导入失败 | 非空字段为空、类型不匹配、主键冲突或唯一约束冲突 |
-| 中文乱码 | 文件编码和解析方式不一致 |
-| 日期错误 | 文件中的日期格式无法被目标数据库识别 |
+| 现象 | 可能原因 |
+| -------------- | ------------------------------------------------ |
+| 部分列没有导入 | 文件列名和表字段名不匹配,或列被取消映射 |
+| 导入失败 | 非空字段为空、类型不匹配、主键冲突或唯一约束冲突 |
+| 中文乱码 | 文件编码和解析方式不一致 |
+| 日期错误 | 文件中的日期格式无法被目标数据库识别 |
diff --git a/docs/content/docs/table-import.mdx b/docs/content/docs/table-import.mdx
index e39075961a..da770bcc80 100644
--- a/docs/content/docs/table-import.mdx
+++ b/docs/content/docs/table-import.mdx
@@ -7,12 +7,12 @@ Table Import writes a local file into a selected database table. Use it for one-
## Supported Files
-| Format | Details |
-|---|---|
-| CSV | Comma-separated text for general data exchange |
-| TSV | Tab-separated text, useful when values contain commas |
-| JSON | JSON arrays exported from APIs or scripts |
-| Excel | `.xlsx`, `.xlsm`, or `.xls` files; DBX reads the first sheet |
+| Format | Details |
+| ------ | ------------------------------------------------------------ |
+| CSV | Comma-separated text for general data exchange |
+| TSV | Tab-separated text, useful when values contain commas |
+| JSON | JSON arrays exported from APIs or scripts |
+| Excel | `.xlsx`, `.xlsm`, or `.xls` files; DBX reads the first sheet |
DBX previews the first 50 rows before import. Empty CSV/TSV cells are treated as `NULL`. JSON imports can be a single object, an array of objects, or an array of arrays; mixed object and array rows are rejected.
@@ -23,39 +23,42 @@ DBX previews the first 50 rows before import. Empty CSV/TSV cells are treated as
### Select the Target Table
Right-click the target table in the sidebar and choose **Import Data**.
+
</Step>
<Step>
### Choose a File
Select a CSV, TSV, JSON, or Excel file.
+
</Step>
<Step>
### Review Column Mapping
DBX tries to match file columns to table columns by name. Check primary keys, required fields, dates, and numeric values.
+
</Step>
<Step>
### Choose Import Mode
Select append or truncate-then-import. Truncate mode removes existing target data first.
+
</Step>
<Step>
### Run and Inspect
After import, check inserted rows, failures, and the resulting table data.
+
</Step>
</Steps>
## Import Modes
-| Mode | Behavior | Best For |
-|---|---|---|
-| Append | Keep existing data and insert new rows | Backfills and sample data |
+| Mode | Behavior | Best For |
+| -------------------- | ------------------------------------------------- | -------------------------------------------------- |
+| Append | Keep existing data and insert new rows | Backfills and sample data |
| Truncate then import | Remove existing rows first, then insert file data | Rebuilding test tables or replacing temporary data |
-<Callout type="warn">
-Truncate-then-import deletes existing rows from the target table. Confirm backups and impact before using it on production data.
-</Callout>
+<Callout type="warn">Truncate-then-import deletes existing rows from the target table. Confirm backups and impact before using it on production data.</Callout>
Imports run in batches. The default batch size is 500 rows, and the progress view reports imported rows, total rows, errors, and cancellation state.
@@ -82,9 +85,9 @@ Table import is available for MySQL, PostgreSQL, SQLite, DuckDB, ClickHouse, SQL
## Troubleshooting
-| Symptom | Possible Cause |
-|---|---|
-| Some columns are skipped | File column names do not match table columns, or the mapping was disabled |
-| Import fails | Required value missing, type mismatch, primary key conflict, or unique constraint conflict |
-| Text is garbled | File encoding does not match parser settings |
-| Dates are wrong | Date format is not recognized by the target database |
+| Symptom | Possible Cause |
+| ------------------------ | ------------------------------------------------------------------------------------------ |
+| Some columns are skipped | File column names do not match table columns, or the mapping was disabled |
+| Import fails | Required value missing, type mismatch, primary key conflict, or unique constraint conflict |
+| Text is garbled | File encoding does not match parser settings |
+| Dates are wrong | Date format is not recognized by the target database |
diff --git a/docs/content/docs/table-structure.cn.mdx b/docs/content/docs/table-structure.cn.mdx
index f9241ff034..3e0a1782cb 100644
--- a/docs/content/docs/table-structure.cn.mdx
+++ b/docs/content/docs/table-structure.cn.mdx
@@ -5,19 +5,17 @@ description: 可视化编辑表字段和索引,并在保存前预览 DDL。
表结构编辑器用于修改单张表的字段、索引和约束。它适合小范围结构调整,也适合在不手写 DDL 的情况下生成可审查的变更 SQL。
-<Callout type="info">
-表结构编辑器目前面向 MySQL、PostgreSQL、SQLite、SQL Server 和 ClickHouse 开启。其他数据库仍可能在结构浏览器中展示 DDL,但当 DBX 无法可靠生成安全变更时,不会显示可视化编辑器。
-</Callout>
+<Callout type="info">表结构编辑器目前面向 MySQL、PostgreSQL、SQLite、SQL Server 和 ClickHouse 开启。其他数据库仍可能在结构浏览器中展示 DDL,但当 DBX 无法可靠生成安全变更时,不会显示可视化编辑器。</Callout>
## 可以编辑什么
-| 对象 | 支持操作 |
-|---|---|
-| 字段 | 新增、删除、重命名和修改字段;修改类型、长度、默认值、可空性和注释 |
-| 主键 | 添加、修改或移除主键字段 |
-| 索引 | 新增、删除和重建索引;配置索引类型、包含列、WHERE 过滤和注释 |
-| 注释 | MySQL/PostgreSQL 支持字段和索引注释写入 |
-| 列顺序 | 可视化调整列顺序;DBX 会生成对应的 ALTER 语句 |
+| 对象 | 支持操作 |
+| ------ | ------------------------------------------------------------------ |
+| 字段 | 新增、删除、重命名和修改字段;修改类型、长度、默认值、可空性和注释 |
+| 主键 | 添加、修改或移除主键字段 |
+| 索引 | 新增、删除和重建索引;配置索引类型、包含列、WHERE 过滤和注释 |
+| 注释 | MySQL/PostgreSQL 支持字段和索引注释写入 |
+| 列顺序 | 可视化调整列顺序;DBX 会生成对应的 ALTER 语句 |
## 编辑器界面
@@ -37,37 +35,39 @@ description: 可视化编辑表字段和索引,并在保存前预览 DDL。
### 打开表结构
在侧边栏右键表,选择查看或编辑结构。
+
</Step>
<Step>
### 修改字段或索引
在可视化界面中添加、修改或删除字段和索引。修改会先暂存在本地。
+
</Step>
<Step>
### 查看 SQL 预览
保存前检查 DBX 生成的 `ALTER TABLE`、`CREATE INDEX`、`DROP INDEX` 等语句。
+
</Step>
<Step>
### 确认执行
确认 SQL 没有问题后再应用到数据库。
+
</Step>
</Steps>
-<Callout type="warn">
-删除字段、修改字段类型、修改 NULL 约束都可能影响现有数据。生产环境执行前建议先备份,并确认应用代码是否依赖旧结构。
-</Callout>
+<Callout type="warn">删除字段、修改字段类型、修改 NULL 约束都可能影响现有数据。生产环境执行前建议先备份,并确认应用代码是否依赖旧结构。</Callout>
## 数据库差异
-| 数据库 | 说明 |
-|---|---|
-| MySQL / MariaDB | 支持新增、删除、修改字段,以及新增/删除索引 |
-| PostgreSQL | 支持字段重命名、类型、默认值、NULL 约束和注释变更,以及新增/删除索引 |
-| SQLite | 支持新增字段、删除字段和重命名字段;更复杂的字段修改会提示无法安全处理 |
-| SQL Server | 支持常见单表结构操作 |
-| 其他引擎 | 当 DBX 不显示可视化编辑器时,使用生成 DDL、Schema 对比或手写 SQL |
+| 数据库 | 说明 |
+| --------------- | ---------------------------------------------------------------------- |
+| MySQL / MariaDB | 支持新增、删除、修改字段,以及新增/删除索引 |
+| PostgreSQL | 支持字段重命名、类型、默认值、NULL 约束和注释变更,以及新增/删除索引 |
+| SQLite | 支持新增字段、删除字段和重命名字段;更复杂的字段修改会提示无法安全处理 |
+| SQL Server | 支持常见单表结构操作 |
+| 其他引擎 | 当 DBX 不显示可视化编辑器时,使用生成 DDL、Schema 对比或手写 SQL |
## 使用建议
diff --git a/docs/content/docs/table-structure.mdx b/docs/content/docs/table-structure.mdx
index a93bc800d5..304f886f4f 100644
--- a/docs/content/docs/table-structure.mdx
+++ b/docs/content/docs/table-structure.mdx
@@ -5,19 +5,17 @@ description: Edit table columns and indexes visually, then preview DDL before ap
The table structure editor modifies columns, indexes, and constraints for a single table. Use it for focused structure changes or to generate reviewable DDL without writing it by hand.
-<Callout type="info">
-The structure editor is enabled for MySQL, PostgreSQL, SQLite, SQL Server, and ClickHouse. Other databases may still expose DDL through the schema browser, but DBX does not show the visual editor when it cannot generate safe changes.
-</Callout>
+<Callout type="info">The structure editor is enabled for MySQL, PostgreSQL, SQLite, SQL Server, and ClickHouse. Other databases may still expose DDL through the schema browser, but DBX does not show the visual editor when it cannot generate safe changes.</Callout>
## What You Can Edit
-| Object | Supported Actions |
-|---|---|
-| Columns | Add, delete, rename, and modify columns; change type, length, default, nullable, and comments |
-| Primary Key | Add, modify, or remove primary key columns |
-| Indexes | Add, delete, and rebuild indexes; configure index type, included columns, WHERE filter, and comments |
-| Comments | MySQL/PostgreSQL can write column and index comments |
-| Column Order | Reorder columns visually; DBX generates the appropriate ALTER statements |
+| Object | Supported Actions |
+| ------------ | ---------------------------------------------------------------------------------------------------- |
+| Columns | Add, delete, rename, and modify columns; change type, length, default, nullable, and comments |
+| Primary Key | Add, modify, or remove primary key columns |
+| Indexes | Add, delete, and rebuild indexes; configure index type, included columns, WHERE filter, and comments |
+| Comments | MySQL/PostgreSQL can write column and index comments |
+| Column Order | Reorder columns visually; DBX generates the appropriate ALTER statements |
## Editor Interface
@@ -37,37 +35,39 @@ Database engines differ in DDL capabilities. DBX generates SQL for the active co
### Open Table Structure
Right-click a table in the sidebar and open its structure view.
+
</Step>
<Step>
### Edit Columns or Indexes
Add, modify, or remove columns and indexes in the visual editor. Changes are staged locally first.
+
</Step>
<Step>
### Review SQL Preview
Before saving, review generated statements such as `ALTER TABLE`, `CREATE INDEX`, and `DROP INDEX`.
+
</Step>
<Step>
### Apply Changes
Execute the SQL only after confirming it matches your intent.
+
</Step>
</Steps>
-<Callout type="warn">
-Dropping columns, changing column types, and changing nullable constraints can affect existing data. Back up production databases first and confirm application code does not depend on the old structure.
-</Callout>
+<Callout type="warn">Dropping columns, changing column types, and changing nullable constraints can affect existing data. Back up production databases first and confirm application code does not depend on the old structure.</Callout>
## Engine Differences
-| Engine | Notes |
-|---|---|
-| MySQL / MariaDB | Add, delete, and modify columns; add and delete indexes |
-| PostgreSQL | Rename columns, change type/default/nullability/comments, and add/delete indexes |
-| SQLite | Add, delete, and rename columns; more complex existing-column edits are blocked with a warning |
-| SQL Server | Focused editor support for common table structure operations |
-| Other engines | Use generated DDL, Schema Diff, or manual SQL when DBX does not expose the visual editor |
+| Engine | Notes |
+| --------------- | ---------------------------------------------------------------------------------------------- |
+| MySQL / MariaDB | Add, delete, and modify columns; add and delete indexes |
+| PostgreSQL | Rename columns, change type/default/nullability/comments, and add/delete indexes |
+| SQLite | Add, delete, and rename columns; more complex existing-column edits are blocked with a warning |
+| SQL Server | Focused editor support for common table structure operations |
+| Other engines | Use generated DDL, Schema Diff, or manual SQL when DBX does not expose the visual editor |
## Recommendations
diff --git a/docs/content/docs/what-is-dbx.cn.mdx b/docs/content/docs/what-is-dbx.cn.mdx
index 169a3c75a6..ed45754ba0 100644
--- a/docs/content/docs/what-is-dbx.cn.mdx
+++ b/docs/content/docs/what-is-dbx.cn.mdx
@@ -28,16 +28,16 @@ DBX 是一个开源数据库工作台。它把日常数据库工作里的高频
## 主要能力
-| 能力 | 说明 |
-|---|---|
+| 能力 | 说明 |
+| ------------ | ----------------------------------------------------------------------------------------------- |
| 多数据库连接 | 支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle 等数据库 |
-| SQL 编辑器 | 基于 CodeMirror 6,支持语法高亮、元数据补全、格式化、选中执行和查询历史 |
-| 数据表格 | 虚拟滚动、行内编辑、WHERE/ORDER BY 控制、SQL 预览和多格式导出 |
-| 结构工具 | 结构浏览、表结构编辑、Schema 对比、ER 图、字段血缘、数据库导出和 SQL 文件执行 |
-| 数据流转 | 表数据导入、数据传输、SQL 文件执行,以及支持进度和取消的 SQL 导出 |
-| 专项浏览器 | Redis 键值浏览和 MongoDB 文档浏览 |
-| AI 与自动化 | 根据连接元数据生成 SQL、解释查询、优化语句、辅助修复错误,并通过 MCP 暴露连接给编程助手 |
-| 自托管访问 | Docker 版本可部署在服务器上,通过浏览器访问 DBX |
+| SQL 编辑器 | 基于 CodeMirror 6,支持语法高亮、元数据补全、格式化、选中执行和查询历史 |
+| 数据表格 | 虚拟滚动、行内编辑、WHERE/ORDER BY 控制、SQL 预览和多格式导出 |
+| 结构工具 | 结构浏览、表结构编辑、Schema 对比、ER 图、字段血缘、数据库导出和 SQL 文件执行 |
+| 数据流转 | 表数据导入、数据传输、SQL 文件执行,以及支持进度和取消的 SQL 导出 |
+| 专项浏览器 | Redis 键值浏览和 MongoDB 文档浏览 |
+| AI 与自动化 | 根据连接元数据生成 SQL、解释查询、优化语句、辅助修复错误,并通过 MCP 暴露连接给编程助手 |
+| 自托管访问 | Docker 版本可部署在服务器上,通过浏览器访问 DBX |
## 设计取向
diff --git a/docs/content/docs/what-is-dbx.mdx b/docs/content/docs/what-is-dbx.mdx
index b12e427728..5fc6d1df28 100644
--- a/docs/content/docs/what-is-dbx.mdx
+++ b/docs/content/docs/what-is-dbx.mdx
@@ -28,16 +28,16 @@ DBX is available as both a desktop app and a Docker deployment. Use the desktop
## Core Capabilities
-| Capability | Details |
-|---|---|
-| Database connections | MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, and more |
-| SQL editor | CodeMirror 6, syntax highlighting, metadata completion, formatting, selected execution, and query history |
-| Data grid | Virtual scrolling, inline editing, WHERE/ORDER BY controls, SQL preview, and export tools |
-| Schema tools | Schema browser, table structure editing, schema diff, ER diagrams, field lineage, database export, and SQL file execution |
-| Data movement | Table import, data transfer, SQL file execution, and SQL export with progress and cancellation where supported |
-| Specialized browsers | Redis key/value browsing and MongoDB document browsing |
-| AI and automation | Generate SQL, explain queries, suggest optimizations, help fix errors, and expose DBX connections to coding agents through MCP |
-| Self-hosted access | Run DBX with Docker and access it from a browser |
+| Capability | Details |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
+| Database connections | MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, and more |
+| SQL editor | CodeMirror 6, syntax highlighting, metadata completion, formatting, selected execution, and query history |
+| Data grid | Virtual scrolling, inline editing, WHERE/ORDER BY controls, SQL preview, and export tools |
+| Schema tools | Schema browser, table structure editing, schema diff, ER diagrams, field lineage, database export, and SQL file execution |
+| Data movement | Table import, data transfer, SQL file execution, and SQL export with progress and cancellation where supported |
+| Specialized browsers | Redis key/value browsing and MongoDB document browsing |
+| AI and automation | Generate SQL, explain queries, suggest optimizations, help fix errors, and expose DBX connections to coding agents through MCP |
+| Self-hosted access | Run DBX with Docker and access it from a browser |
## Product Principles
diff --git a/docs/lib/agentRegistry.ts b/docs/lib/agentRegistry.ts
index 2b9126033a..0d11e26f27 100644
--- a/docs/lib/agentRegistry.ts
+++ b/docs/lib/agentRegistry.ts
@@ -34,8 +34,7 @@ export interface AgentRegistry {
}
const AGENT_REGISTRY_R2_URL = "https://dl.dbxio.com/agents/agent-registry.json";
-const AGENT_REGISTRY_GITHUB_URL =
- "https://github.com/t8y2/dbx-agents/releases/latest/download/agent-registry.json";
+const AGENT_REGISTRY_GITHUB_URL = "https://github.com/t8y2/dbx-agents/releases/latest/download/agent-registry.json";
export async function fetchAgentRegistry(): Promise<AgentRegistry | null> {
const urls = [AGENT_REGISTRY_R2_URL, AGENT_REGISTRY_GITHUB_URL];
diff --git a/docs/lib/appVersion.ts b/docs/lib/appVersion.ts
index 17721b9379..ed5667e562 100644
--- a/docs/lib/appVersion.ts
+++ b/docs/lib/appVersion.ts
@@ -1,4 +1,4 @@
-import appPackage from '../../package.json';
+import appPackage from "../../package.json";
export function getAppVersion() {
return appPackage.version;
diff --git a/docs/lib/changelog.ts b/docs/lib/changelog.ts
index d5889c7d22..2b4e739cda 100644
--- a/docs/lib/changelog.ts
+++ b/docs/lib/changelog.ts
@@ -1,4 +1,4 @@
-import { requestJson } from '@/lib/httpJson';
+import { requestJson } from "@/lib/httpJson";
export type ChangelogItem = {
title: string;
@@ -32,32 +32,29 @@ type GitHubRelease = {
prerelease: boolean;
};
-const DEFAULT_BASE_URL = 'https://dl.dbxio.com/changelog';
-const GITHUB_RELEASES_URL = 'https://api.github.com/repos/t8y2/dbx/releases?per_page=30';
+const DEFAULT_BASE_URL = "https://dl.dbxio.com/changelog";
+const GITHUB_RELEASES_URL = "https://api.github.com/repos/t8y2/dbx/releases?per_page=30";
const SECTION_MAP: Record<string, string> = {
- 新功能: 'added',
- Added: 'added',
- 改进: 'improved',
- Improved: 'improved',
- 修复: 'fixed',
- Fixed: 'fixed',
- 变更: 'changed',
- Changed: 'changed',
- 移除: 'removed',
- Removed: 'removed',
+ 新功能: "added",
+ Added: "added",
+ 改进: "improved",
+ Improved: "improved",
+ 修复: "fixed",
+ Fixed: "fixed",
+ 变更: "changed",
+ Changed: "changed",
+ 移除: "removed",
+ Removed: "removed",
};
-export function changelogUrl(lang: 'en' | 'cn') {
- const baseUrl =
- (typeof process !== 'undefined' &&
- (process.env.NEXT_PUBLIC_CHANGELOG_BASE_URL || process.env.CHANGELOG_BASE_URL)) ||
- DEFAULT_BASE_URL;
+export function changelogUrl(lang: "en" | "cn") {
+ const baseUrl = (typeof process !== "undefined" && (process.env.NEXT_PUBLIC_CHANGELOG_BASE_URL || process.env.CHANGELOG_BASE_URL)) || DEFAULT_BASE_URL;
return `${baseUrl}/releases-${lang}.json`;
}
-export async function fetchChangelog(lang: 'en' | 'cn'): Promise<ChangelogData> {
+export async function fetchChangelog(lang: "en" | "cn"): Promise<ChangelogData> {
const url = changelogUrl(lang);
try {
@@ -68,7 +65,7 @@ export async function fetchChangelog(lang: 'en' | 'cn'): Promise<ChangelogData>
}
function stripDownloadSection(body: string) {
- const markers = ['### 下载安装', '### Download', '### 系统要求', '### System Requirements'];
+ const markers = ["### 下载安装", "### Download", "### 系统要求", "### System Requirements"];
let idx = body.length;
for (const marker of markers) {
@@ -85,11 +82,11 @@ function parseReleaseBody(body: string) {
const sections: ChangelogSection[] = [];
let current: ChangelogSection | null = null;
- for (const line of stripDownloadSection(body).split('\n')) {
+ for (const line of stripDownloadSection(body).split("\n")) {
const headerMatch = line.match(/^###\s+(.+)/);
if (headerMatch) {
const title = headerMatch[1].trim();
- current = { type: SECTION_MAP[title] || 'other', title, items: [] };
+ current = { type: SECTION_MAP[title] || "other", title, items: [] };
sections.push(current);
continue;
}
@@ -104,7 +101,7 @@ function parseReleaseBody(body: string) {
const plainMatch = line.match(/^-\s+(.+)/);
if (plainMatch) {
- current.items.push({ title: plainMatch[1].trim(), desc: '' });
+ current.items.push({ title: plainMatch[1].trim(), desc: "" });
}
}
@@ -114,7 +111,7 @@ function parseReleaseBody(body: string) {
export async function fetchGitHubChangelog(): Promise<ChangelogData> {
try {
const releases = await requestJson<GitHubRelease[]>(GITHUB_RELEASES_URL, {
- headers: { Accept: 'application/vnd.github+json' },
+ headers: { Accept: "application/vnd.github+json" },
});
return {
@@ -124,11 +121,11 @@ export async function fetchGitHubChangelog(): Promise<ChangelogData> {
.map((release) => ({
tag: release.tag_name,
name: release.name || release.tag_name,
- date: (release.published_at || '').slice(0, 10),
- sections: parseReleaseBody(release.body || ''),
+ date: (release.published_at || "").slice(0, 10),
+ sections: parseReleaseBody(release.body || ""),
})),
};
} catch {
- return { updatedAt: '', releases: [] };
+ return { updatedAt: "", releases: [] };
}
}
diff --git a/docs/lib/cjkSearchTokenizer.ts b/docs/lib/cjkSearchTokenizer.ts
index f80421fe40..ec2b185ae6 100644
--- a/docs/lib/cjkSearchTokenizer.ts
+++ b/docs/lib/cjkSearchTokenizer.ts
@@ -31,10 +31,10 @@ function tokenizeCjkText(input: string) {
export function createCjkSearchTokenizer() {
return {
- language: 'cjk',
+ language: "cjk",
normalizationCache: new Map<string, string>(),
tokenize(raw: string) {
- if (typeof raw !== 'string') return [raw];
+ if (typeof raw !== "string") return [raw];
return tokenizeCjkText(raw);
},
};
diff --git a/docs/lib/downloadLinks.ts b/docs/lib/downloadLinks.ts
index 41f47e99f5..2dacdbc897 100644
--- a/docs/lib/downloadLinks.ts
+++ b/docs/lib/downloadLinks.ts
@@ -1,4 +1,4 @@
-export type InstallLang = 'en' | 'cn';
+export type InstallLang = "en" | "cn";
export type InstallOption = {
id: string;
@@ -12,33 +12,33 @@ type DownloadArtifact = {
suffix: string;
};
-const DOWNLOAD_BASE_URL = 'https://dl.dbxio.com/releases/latest';
+const DOWNLOAD_BASE_URL = "https://dl.dbxio.com/releases/latest";
const downloadArtifacts: DownloadArtifact[] = [
{
- id: 'macos-arm',
- labels: { en: 'For macOS (Apple Silicon)', cn: '适用于 macOS (Apple Silicon)' },
- suffix: 'aarch64.dmg',
+ id: "macos-arm",
+ labels: { en: "For macOS (Apple Silicon)", cn: "适用于 macOS (Apple Silicon)" },
+ suffix: "aarch64.dmg",
},
{
- id: 'macos-intel',
- labels: { en: 'For macOS (Intel)', cn: '适用于 macOS (Intel)' },
- suffix: 'x64.dmg',
+ id: "macos-intel",
+ labels: { en: "For macOS (Intel)", cn: "适用于 macOS (Intel)" },
+ suffix: "x64.dmg",
},
{
- id: 'windows',
- labels: { en: 'For Windows', cn: '适用于 Windows' },
- suffix: 'x64-setup.exe',
+ id: "windows",
+ labels: { en: "For Windows", cn: "适用于 Windows" },
+ suffix: "x64-setup.exe",
},
{
- id: 'linux',
- labels: { en: 'For Linux x64', cn: '适用于 Linux x64' },
- suffix: 'amd64.AppImage',
+ id: "linux",
+ labels: { en: "For Linux x64", cn: "适用于 Linux x64" },
+ suffix: "amd64.AppImage",
},
{
- id: 'linux-arm',
- labels: { en: 'For Linux ARM64', cn: '适用于 Linux ARM64' },
- suffix: 'aarch64.AppImage',
+ id: "linux-arm",
+ labels: { en: "For Linux ARM64", cn: "适用于 Linux ARM64" },
+ suffix: "aarch64.AppImage",
},
];
diff --git a/docs/lib/httpJson.ts b/docs/lib/httpJson.ts
index 49d14d0ba7..3fff325d5e 100644
--- a/docs/lib/httpJson.ts
+++ b/docs/lib/httpJson.ts
@@ -1,9 +1,9 @@
function requestJsonWithXhr<T>(url: string): Promise<T> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.responseType = 'json';
- xhr.setRequestHeader('Accept', 'application/json');
+ xhr.open("GET", url, true);
+ xhr.responseType = "json";
+ xhr.setRequestHeader("Accept", "application/json");
xhr.onload = () => {
if (xhr.status < 200 || xhr.status >= 300) {
reject(new Error(`Request failed with status ${xhr.status}`));
@@ -12,13 +12,13 @@ function requestJsonWithXhr<T>(url: string): Promise<T> {
resolve((xhr.response ?? JSON.parse(xhr.responseText)) as T);
};
- xhr.onerror = () => reject(new Error('Request failed'));
+ xhr.onerror = () => reject(new Error("Request failed"));
xhr.send();
});
}
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
- if (typeof fetch === 'function') {
+ if (typeof fetch === "function") {
const res = await fetch(url, init);
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}`);
@@ -26,9 +26,9 @@ export async function requestJson<T>(url: string, init?: RequestInit): Promise<T
return res.json() as Promise<T>;
}
- if (typeof XMLHttpRequest === 'function') {
+ if (typeof XMLHttpRequest === "function") {
return requestJsonWithXhr<T>(url);
}
- throw new Error('No browser request API is available');
+ throw new Error("No browser request API is available");
}
diff --git a/docs/lib/i18n.ts b/docs/lib/i18n.ts
index a7908108e8..66151c0ca3 100644
--- a/docs/lib/i18n.ts
+++ b/docs/lib/i18n.ts
@@ -1,24 +1,24 @@
-import { defineI18n } from 'fumadocs-core/i18n';
-import { defineI18nUI } from 'fumadocs-ui/i18n';
+import { defineI18n } from "fumadocs-core/i18n";
+import { defineI18nUI } from "fumadocs-ui/i18n";
export const i18n = defineI18n({
- defaultLanguage: 'en',
- languages: ['en', 'cn'],
+ defaultLanguage: "en",
+ languages: ["en", "cn"],
});
export const i18nUI = defineI18nUI(i18n, {
- en: { displayName: 'English' },
+ en: { displayName: "English" },
cn: {
- displayName: '简体中文',
- search: '搜索',
- searchNoResult: '没有找到结果',
- toc: '本页目录',
- tocNoHeadings: '没有目录',
- lastUpdate: '最后更新',
- chooseLanguage: '选择语言',
- nextPage: '下一页',
- previousPage: '上一页',
- chooseTheme: '选择主题',
- editOnGithub: '在 GitHub 上编辑',
+ displayName: "简体中文",
+ search: "搜索",
+ searchNoResult: "没有找到结果",
+ toc: "本页目录",
+ tocNoHeadings: "没有目录",
+ lastUpdate: "最后更新",
+ chooseLanguage: "选择语言",
+ nextPage: "下一页",
+ previousPage: "上一页",
+ chooseTheme: "选择主题",
+ editOnGithub: "在 GitHub 上编辑",
},
});
diff --git a/docs/lib/landingLatest.ts b/docs/lib/landingLatest.ts
index 35cfb14e5b..c1313ee650 100644
--- a/docs/lib/landingLatest.ts
+++ b/docs/lib/landingLatest.ts
@@ -1,5 +1,5 @@
-import type { ChangelogRelease } from '@/lib/changelog';
-import type { LatestReleaseInfo } from '@/lib/latestRelease';
+import type { ChangelogRelease } from "@/lib/changelog";
+import type { LatestReleaseInfo } from "@/lib/latestRelease";
type LandingLatestUpdates = {
version: string;
@@ -11,31 +11,21 @@ type LandingLatestUpdates = {
const text = {
en: {
- title: 'Latest updates',
- desc: 'Mirrored from the latest GitHub release notes.',
- link: 'Read the changelog',
- fallbackItems: [
- 'Desktop and Docker release assets',
- 'Database workflow improvements',
- 'Bug fixes and reliability updates',
- 'Documentation and packaging updates',
- ],
+ title: "Latest updates",
+ desc: "Mirrored from the latest GitHub release notes.",
+ link: "Read the changelog",
+ fallbackItems: ["Desktop and Docker release assets", "Database workflow improvements", "Bug fixes and reliability updates", "Documentation and packaging updates"],
},
cn: {
- title: '最近更新',
- desc: '同步 GitHub 最新 Release Notes。',
- link: '查看更新日志',
- fallbackItems: [
- '桌面版与 Docker 发布资产',
- '数据库工作流改进',
- '问题修复与稳定性更新',
- '文档与打包流程更新',
- ],
+ title: "最近更新",
+ desc: "同步 GitHub 最新 Release Notes。",
+ link: "查看更新日志",
+ fallbackItems: ["桌面版与 Docker 发布资产", "数据库工作流改进", "问题修复与稳定性更新", "文档与打包流程更新"],
},
};
-function releaseItems(release: ChangelogRelease, lang: 'en' | 'cn') {
- const separator = lang === 'cn' ? ',' : ': ';
+function releaseItems(release: ChangelogRelease, lang: "en" | "cn") {
+ const separator = lang === "cn" ? "," : ": ";
return release.sections
.flatMap((section) => section.items)
@@ -43,15 +33,10 @@ function releaseItems(release: ChangelogRelease, lang: 'en' | 'cn') {
.slice(0, 4);
}
-export function buildLandingLatestUpdates(
- lang: 'en' | 'cn',
- release: ChangelogRelease | undefined,
- appVersion: string,
- latestRelease?: LatestReleaseInfo | null,
-): LandingLatestUpdates {
+export function buildLandingLatestUpdates(lang: "en" | "cn", release: ChangelogRelease | undefined, appVersion: string, latestRelease?: LatestReleaseInfo | null): LandingLatestUpdates {
const t = text[lang];
const items = release ? releaseItems(release, lang) : [];
- const version = latestRelease?.version ? `v${latestRelease.version}` : release?.tag ?? `v${appVersion}`;
+ const version = latestRelease?.version ? `v${latestRelease.version}` : (release?.tag ?? `v${appVersion}`);
return {
version,
diff --git a/docs/lib/latestRelease.ts b/docs/lib/latestRelease.ts
index 157ca7bc99..eba09dc0d8 100644
--- a/docs/lib/latestRelease.ts
+++ b/docs/lib/latestRelease.ts
@@ -1,5 +1,5 @@
-import { requestJson } from '@/lib/httpJson';
-import { browserCacheBuster, createUncachedUrl, releaseMetadataRequestInit } from '@/lib/releaseMetadataRequest';
+import { requestJson } from "@/lib/httpJson";
+import { browserCacheBuster, createUncachedUrl, releaseMetadataRequestInit } from "@/lib/releaseMetadataRequest";
export type LatestReleaseInfo = {
version: string;
@@ -13,19 +13,16 @@ type GitHubLatestRelease = {
published_at: string | null;
};
-const LATEST_RELEASE_URL = 'https://dl.dbxio.com/releases/latest/latest.json';
-const GITHUB_LATEST_RELEASE_URL = 'https://api.github.com/repos/t8y2/dbx/releases/latest';
+const LATEST_RELEASE_URL = "https://dl.dbxio.com/releases/latest/latest.json";
+const GITHUB_LATEST_RELEASE_URL = "https://api.github.com/repos/t8y2/dbx/releases/latest";
function normalizeVersion(version: string) {
- return version.replace(/^v/, '');
+ return version.replace(/^v/, "");
}
export async function fetchLatestReleaseInfo(): Promise<LatestReleaseInfo | null> {
try {
- const release = await requestJson<LatestReleaseInfo>(
- createUncachedUrl(LATEST_RELEASE_URL, browserCacheBuster()),
- releaseMetadataRequestInit(),
- );
+ const release = await requestJson<LatestReleaseInfo>(createUncachedUrl(LATEST_RELEASE_URL, browserCacheBuster()), releaseMetadataRequestInit());
return release.version ? { ...release, version: normalizeVersion(release.version) } : null;
} catch {
return fetchGitHubLatestReleaseInfo();
@@ -34,10 +31,7 @@ export async function fetchLatestReleaseInfo(): Promise<LatestReleaseInfo | null
export async function fetchGitHubLatestReleaseInfo(): Promise<LatestReleaseInfo | null> {
try {
- const release = await requestJson<GitHubLatestRelease>(
- createUncachedUrl(GITHUB_LATEST_RELEASE_URL, browserCacheBuster()),
- releaseMetadataRequestInit({ headers: { Accept: 'application/vnd.github+json' } }),
- );
+ const release = await requestJson<GitHubLatestRelease>(createUncachedUrl(GITHUB_LATEST_RELEASE_URL, browserCacheBuster()), releaseMetadataRequestInit({ headers: { Accept: "application/vnd.github+json" } }));
return {
version: normalizeVersion(release.tag_name),
diff --git a/docs/lib/metadata.ts b/docs/lib/metadata.ts
index 940bc78d34..9477b67632 100644
--- a/docs/lib/metadata.ts
+++ b/docs/lib/metadata.ts
@@ -1,23 +1,22 @@
-import type { Metadata } from 'next';
+import type { Metadata } from "next";
-export const SITE_URL = 'https://dbxio.com';
-export const SITE_NAME = 'DBX';
-export const DEFAULT_DESCRIPTION =
- '25+ databases in 15 MB. Desktop & Docker self-hosting, with built-in AI assistant.';
-export const DEFAULT_OG_IMAGE = '/logo.png';
+export const SITE_URL = "https://dbxio.com";
+export const SITE_NAME = "DBX";
+export const DEFAULT_DESCRIPTION = "25+ databases in 15 MB. Desktop & Docker self-hosting, with built-in AI assistant.";
+export const DEFAULT_OG_IMAGE = "/logo.png";
const LOCALE_MAP: Record<string, string> = {
- en: 'en_US',
- cn: 'zh_CN',
+ en: "en_US",
+ cn: "zh_CN",
};
const HTML_LANG_MAP: Record<string, string> = {
- en: 'en',
- cn: 'zh-CN',
+ en: "en",
+ cn: "zh-CN",
};
export function getHtmlLang(lang: string): string {
- return HTML_LANG_MAP[lang] ?? 'en';
+ return HTML_LANG_MAP[lang] ?? "en";
}
function swapLang(path: string, to: string): string {
@@ -29,21 +28,14 @@ interface BuildMetadataParams {
description: string;
path: string;
lang: string;
- ogType?: 'website' | 'article';
+ ogType?: "website" | "article";
images?: string[];
lastModified?: Date;
}
-export function buildMetadata({
- title,
- description,
- path,
- lang,
- ogType = 'website',
- images,
-}: BuildMetadataParams): Metadata {
+export function buildMetadata({ title, description, path, lang, ogType = "website", images }: BuildMetadataParams): Metadata {
const canonical = `${SITE_URL}${path}`;
- const locale = LOCALE_MAP[lang] ?? 'en_US';
+ const locale = LOCALE_MAP[lang] ?? "en_US";
return {
title,
@@ -51,9 +43,9 @@ export function buildMetadata({
alternates: {
canonical,
languages: {
- en: `${SITE_URL}${swapLang(path, 'en')}`,
- zh: `${SITE_URL}${swapLang(path, 'cn')}`,
- 'x-default': `${SITE_URL}${swapLang(path, 'en')}`,
+ en: `${SITE_URL}${swapLang(path, "en")}`,
+ zh: `${SITE_URL}${swapLang(path, "cn")}`,
+ "x-default": `${SITE_URL}${swapLang(path, "en")}`,
},
},
openGraph: {
@@ -66,7 +58,7 @@ export function buildMetadata({
images: images?.map((url) => ({ url })) ?? [{ url: DEFAULT_OG_IMAGE }],
},
twitter: {
- card: 'summary_large_image',
+ card: "summary_large_image",
title,
description,
images: images ?? [DEFAULT_OG_IMAGE],
diff --git a/docs/lib/releaseMetadataRequest.test.ts b/docs/lib/releaseMetadataRequest.test.ts
index 74c512b956..8af7f5113e 100644
--- a/docs/lib/releaseMetadataRequest.test.ts
+++ b/docs/lib/releaseMetadataRequest.test.ts
@@ -1,21 +1,21 @@
-import assert from 'node:assert/strict';
-import { test } from 'vitest';
-import { createUncachedUrl, releaseMetadataRequestInit } from './releaseMetadataRequest';
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { createUncachedUrl, releaseMetadataRequestInit } from "./releaseMetadataRequest";
-test('createUncachedUrl appends cache buster without removing existing query params', () => {
- assert.equal(createUncachedUrl('https://dl.dbxio.com/releases/latest/latest.json?lang=cn', 123), 'https://dl.dbxio.com/releases/latest/latest.json?lang=cn&_ts=123');
+test("createUncachedUrl appends cache buster without removing existing query params", () => {
+ assert.equal(createUncachedUrl("https://dl.dbxio.com/releases/latest/latest.json?lang=cn", 123), "https://dl.dbxio.com/releases/latest/latest.json?lang=cn&_ts=123");
});
-test('createUncachedUrl leaves server-side build URLs stable without a cache buster', () => {
- assert.equal(createUncachedUrl('https://dl.dbxio.com/releases/latest/latest.json'), 'https://dl.dbxio.com/releases/latest/latest.json');
+test("createUncachedUrl leaves server-side build URLs stable without a cache buster", () => {
+ assert.equal(createUncachedUrl("https://dl.dbxio.com/releases/latest/latest.json"), "https://dl.dbxio.com/releases/latest/latest.json");
});
-test('releaseMetadataRequestInit disables fetch cache and preserves custom headers', () => {
- assert.deepEqual(releaseMetadataRequestInit({ headers: { Authorization: 'token example' } }), {
- cache: 'no-store',
+test("releaseMetadataRequestInit disables fetch cache and preserves custom headers", () => {
+ assert.deepEqual(releaseMetadataRequestInit({ headers: { Authorization: "token example" } }), {
+ cache: "no-store",
headers: {
- Accept: 'application/json',
- Authorization: 'token example',
+ Accept: "application/json",
+ Authorization: "token example",
},
});
});
diff --git a/docs/lib/releaseMetadataRequest.ts b/docs/lib/releaseMetadataRequest.ts
index dffa19be4d..ecc2741f37 100644
--- a/docs/lib/releaseMetadataRequest.ts
+++ b/docs/lib/releaseMetadataRequest.ts
@@ -2,20 +2,20 @@ export function createUncachedUrl(url: string, cacheBuster?: string | number) {
if (cacheBuster === undefined) return url;
const nextUrl = new URL(url);
- nextUrl.searchParams.set('_ts', String(cacheBuster));
+ nextUrl.searchParams.set("_ts", String(cacheBuster));
return nextUrl.toString();
}
export function browserCacheBuster() {
- return typeof window === 'undefined' ? undefined : Date.now();
+ return typeof window === "undefined" ? undefined : Date.now();
}
export function releaseMetadataRequestInit(init: RequestInit = {}): RequestInit {
return {
...init,
- cache: 'no-store',
+ cache: "no-store",
headers: {
- Accept: 'application/json',
+ Accept: "application/json",
...init.headers,
},
};
diff --git a/docs/lib/source.ts b/docs/lib/source.ts
index 7dddf33dcb..c0f7e2775d 100644
--- a/docs/lib/source.ts
+++ b/docs/lib/source.ts
@@ -1,49 +1,49 @@
-import { loader } from 'fumadocs-core/source';
-import { icons } from 'lucide-react';
-import { createElement } from 'react';
-import { i18n } from '@/lib/i18n';
-import { docs } from '@/.source/server';
+import { loader } from "fumadocs-core/source";
+import { icons } from "lucide-react";
+import { createElement } from "react";
+import { i18n } from "@/lib/i18n";
+import { docs } from "@/.source/server";
const pageIcons: Record<string, keyof typeof icons> = {
- 'what-is-dbx': 'BookOpen',
- changelog: 'History',
- 'getting-started': 'Rocket',
- databases: 'Database',
- 'query-editor': 'SquareTerminal',
- 'data-grid': 'Table2',
- 'schema-browser': 'Network',
- redis: 'KeyRound',
- mongodb: 'Braces',
- 'object-browser': 'Package',
- 'schema-diff': 'GitCompareArrows',
- 'data-transfer': 'ArrowRightLeft',
- 'table-structure': 'TableProperties',
- 'field-lineage': 'GitBranch',
- 'table-import': 'Upload',
- 'sql-file': 'FileCode2',
- 'database-export': 'Download',
- 'sql-snippets': 'ScrollText',
- 'ai-assistant': 'Bot',
- cli: 'Terminal',
- mcp: 'Cable',
- plugins: 'Plug',
- 'driver-management': 'Package',
- 'keyboard-shortcuts': 'Keyboard',
- 'connection-import': 'Import',
- 'config-export': 'FileUp',
- 'ssh-tunnel': 'ShieldCheck',
+ "what-is-dbx": "BookOpen",
+ changelog: "History",
+ "getting-started": "Rocket",
+ databases: "Database",
+ "query-editor": "SquareTerminal",
+ "data-grid": "Table2",
+ "schema-browser": "Network",
+ redis: "KeyRound",
+ mongodb: "Braces",
+ "object-browser": "Package",
+ "schema-diff": "GitCompareArrows",
+ "data-transfer": "ArrowRightLeft",
+ "table-structure": "TableProperties",
+ "field-lineage": "GitBranch",
+ "table-import": "Upload",
+ "sql-file": "FileCode2",
+ "database-export": "Download",
+ "sql-snippets": "ScrollText",
+ "ai-assistant": "Bot",
+ cli: "Terminal",
+ mcp: "Cable",
+ plugins: "Plug",
+ "driver-management": "Package",
+ "keyboard-shortcuts": "Keyboard",
+ "connection-import": "Import",
+ "config-export": "FileUp",
+ "ssh-tunnel": "ShieldCheck",
};
export const source = loader({
- baseUrl: '/docs',
+ baseUrl: "/docs",
source: docs.toFumadocsSource(),
i18n,
plugins: [
{
- name: 'dbx-sidebar-icons',
+ name: "dbx-sidebar-icons",
transformPageTree: {
file(node) {
- const slug = node.url.split('/').filter(Boolean).at(-1);
+ const slug = node.url.split("/").filter(Boolean).at(-1);
const iconName = slug ? pageIcons[slug] : undefined;
const Icon = iconName ? icons[iconName] : undefined;
@@ -52,8 +52,8 @@ export const source = loader({
return {
...node,
icon: createElement(Icon, {
- 'aria-hidden': true,
- className: 'size-4',
+ "aria-hidden": true,
+ className: "size-4",
strokeWidth: 2,
}),
};
diff --git a/docs/next.config.mjs b/docs/next.config.mjs
index adbeea417f..ec56b3871c 100644
--- a/docs/next.config.mjs
+++ b/docs/next.config.mjs
@@ -1,10 +1,10 @@
-import { createMDX } from 'fumadocs-mdx/next';
+import { createMDX } from "fumadocs-mdx/next";
const withMDX = createMDX();
/** @type {import('next').NextConfig} */
const config = {
- output: 'export',
+ output: "export",
images: { unoptimized: true },
};
diff --git a/docs/performance/dom-density-audit.md b/docs/performance/dom-density-audit.md
index 497506517e..3be12c5906 100644
--- a/docs/performance/dom-density-audit.md
+++ b/docs/performance/dom-density-audit.md
@@ -16,23 +16,23 @@ Candidate: `perf/dom-density-audit`
## Memory Results
-| Scenario | Before RSS MiB | After RSS MiB | RSS Delta MiB | Before JS Heap MiB | After JS Heap MiB | JS Heap Delta MiB |
-| --- | ---: | ---: | ---: | ---: | ---: | ---: |
-| Grid 1000 x 20 | 1226.3 | 1214.2 | -12.1 | 19.6 | 16.6 | -3.0 |
-| Grid 1000 x 200 | 1462.5 | 1399.7 | -62.8 | 96.7 | 67.5 | -29.2 |
-| Redis list value 3000 | 1396.6 | 1185.4 | -211.2 | 82.7 | 11.3 | -71.4 |
-| Redis hash value 3000 | 1402.3 | 1183.8 | -218.5 | 83.7 | 11.5 | -72.2 |
-| Redis stream 1000 x 5 | 1444.3 | 1182.1 | -262.2 | 92.5 | 13.3 | -79.2 |
+| Scenario | Before RSS MiB | After RSS MiB | RSS Delta MiB | Before JS Heap MiB | After JS Heap MiB | JS Heap Delta MiB |
+| --------------------- | -------------: | ------------: | ------------: | -----------------: | ----------------: | ----------------: |
+| Grid 1000 x 20 | 1226.3 | 1214.2 | -12.1 | 19.6 | 16.6 | -3.0 |
+| Grid 1000 x 200 | 1462.5 | 1399.7 | -62.8 | 96.7 | 67.5 | -29.2 |
+| Redis list value 3000 | 1396.6 | 1185.4 | -211.2 | 82.7 | 11.3 | -71.4 |
+| Redis hash value 3000 | 1402.3 | 1183.8 | -218.5 | 83.7 | 11.5 | -72.2 |
+| Redis stream 1000 x 5 | 1444.3 | 1182.1 | -262.2 | 92.5 | 13.3 | -79.2 |
## DOM Results
-| Scenario | Before DOM Elements | After DOM Elements | Element Delta | Before DOM Nodes | After DOM Nodes | Node Delta | Listener Delta |
-| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
-| Grid 1000 x 20 | 6937 | 1837 | -5100 | 12644 | 8564 | -4080 | -1020 |
-| Grid 1000 x 200 | 65257 | 14257 | -51000 | 106784 | 65984 | -40800 | -10200 |
-| Redis list value 3000 | 57293 | 1096 | -56197 | 82472 | 2760 | -79712 | -11839 |
-| Redis hash value 3000 | 57295 | 1098 | -56197 | 82478 | 2766 | -79712 | -11839 |
-| Redis stream 1000 x 5 | 62281 | 1180 | -61101 | 96450 | 2928 | -93522 | -14759 |
+| Scenario | Before DOM Elements | After DOM Elements | Element Delta | Before DOM Nodes | After DOM Nodes | Node Delta | Listener Delta |
+| --------------------- | ------------------: | -----------------: | ------------: | ---------------: | --------------: | ---------: | -------------: |
+| Grid 1000 x 20 | 6937 | 1837 | -5100 | 12644 | 8564 | -4080 | -1020 |
+| Grid 1000 x 200 | 65257 | 14257 | -51000 | 106784 | 65984 | -40800 | -10200 |
+| Redis list value 3000 | 57293 | 1096 | -56197 | 82472 | 2760 | -79712 | -11839 |
+| Redis hash value 3000 | 57295 | 1098 | -56197 | 82478 | 2766 | -79712 | -11839 |
+| Redis stream 1000 x 5 | 62281 | 1180 | -61101 | 96450 | 2928 | -93522 | -14759 |
## Notes
diff --git a/docs/postcss.config.mjs b/docs/postcss.config.mjs
index 4c12660ece..2df6729480 100644
--- a/docs/postcss.config.mjs
+++ b/docs/postcss.config.mjs
@@ -1,6 +1,6 @@
/** @type {import('postcss-load-config').Config} */
export default {
plugins: {
- '@tailwindcss/postcss': {},
+ "@tailwindcss/postcss": {},
},
};
diff --git a/docs/scripts/generate-sitemap.mjs b/docs/scripts/generate-sitemap.mjs
index c239282ea0..c9ebbd310a 100644
--- a/docs/scripts/generate-sitemap.mjs
+++ b/docs/scripts/generate-sitemap.mjs
@@ -1,11 +1,11 @@
-import { readdirSync, writeFileSync } from 'fs';
-import { resolve, relative } from 'path';
+import { readdirSync, writeFileSync } from "fs";
+import { resolve, relative } from "path";
-const OUT_DIR = resolve(import.meta.dirname, '../out');
-const SITE_URL = 'https://dbxio.com';
-const TODAY = new Date().toISOString().split('T')[0];
+const OUT_DIR = resolve(import.meta.dirname, "../out");
+const SITE_URL = "https://dbxio.com";
+const TODAY = new Date().toISOString().split("T")[0];
-const EXCLUDE = new Set(['index.html', '404.html', '_not-found.html']);
+const EXCLUDE = new Set(["index.html", "404.html", "_not-found.html"]);
function* walkDir(dir) {
const entries = readdirSync(dir, { withFileTypes: true });
@@ -13,7 +13,7 @@ function* walkDir(dir) {
const fullPath = resolve(dir, entry.name);
if (entry.isDirectory()) {
yield* walkDir(fullPath);
- } else if (entry.isFile() && entry.name.endsWith('.html')) {
+ } else if (entry.isFile() && entry.name.endsWith(".html")) {
yield fullPath;
}
}
@@ -21,11 +21,11 @@ function* walkDir(dir) {
function pathToUrl(filePath) {
const rel = relative(OUT_DIR, filePath);
- return '/' + rel.replace(/\.html$/, '').replace(/\\/g, '/');
+ return "/" + rel.replace(/\.html$/, "").replace(/\\/g, "/");
}
const htmlFiles = [...walkDir(OUT_DIR)].filter((f) => {
- const basename = f.split('/').pop() ?? '';
+ const basename = f.split("/").pop() ?? "";
return !EXCLUDE.has(basename);
});
@@ -38,7 +38,7 @@ for (const file of htmlFiles) {
pagesByPath.set(url, { en: null, cn: null });
continue;
}
- const relativePath = match[2] || '/';
+ const relativePath = match[2] || "/";
if (!pagesByPath.has(relativePath)) {
pagesByPath.set(relativePath, { en: null, cn: null });
}
@@ -57,14 +57,14 @@ for (const [, langs] of pagesByPath) {
const altLinks = [];
if (langs.en) {
- altLinks.push({ lang: 'en', href: `${SITE_URL}${langs.en}` });
+ altLinks.push({ lang: "en", href: `${SITE_URL}${langs.en}` });
}
if (langs.cn) {
- altLinks.push({ lang: 'zh', href: `${SITE_URL}${langs.cn}` });
+ altLinks.push({ lang: "zh", href: `${SITE_URL}${langs.cn}` });
}
if (altLinks.length > 1) {
- altLinks.push({ lang: 'x-default', href: `${SITE_URL}${langs.en}` });
+ altLinks.push({ lang: "x-default", href: `${SITE_URL}${langs.en}` });
}
urls.push({ loc: `${SITE_URL}${primary}`, lastmod: TODAY, altLinks });
@@ -79,12 +79,12 @@ ${urls
` <url>
<loc>${entry.loc}</loc>
<lastmod>${entry.lastmod}</lastmod>
-${entry.altLinks.map((alt) => ` <xhtml:link rel="alternate" hreflang="${alt.lang}" href="${alt.href}" />`).join('\n')}
- </url>`
+${entry.altLinks.map((alt) => ` <xhtml:link rel="alternate" hreflang="${alt.lang}" href="${alt.href}" />`).join("\n")}
+ </url>`,
)
- .join('\n')}
+ .join("\n")}
</urlset>
`;
-writeFileSync(resolve(OUT_DIR, 'sitemap.xml'), sitemapXml);
+writeFileSync(resolve(OUT_DIR, "sitemap.xml"), sitemapXml);
console.log(`sitemap.xml generated with ${urls.length} URLs`);
diff --git a/docs/source.config.ts b/docs/source.config.ts
index 7784ccba87..71c0f61467 100644
--- a/docs/source.config.ts
+++ b/docs/source.config.ts
@@ -1,7 +1,7 @@
-import { defineDocs, defineConfig } from 'fumadocs-mdx/config';
+import { defineDocs, defineConfig } from "fumadocs-mdx/config";
export const docs = defineDocs({
- dir: 'content/docs',
+ dir: "content/docs",
});
export default defineConfig({
diff --git a/docs/tsconfig.json b/docs/tsconfig.json
index f94008bbc9..219e459050 100644
--- a/docs/tsconfig.json
+++ b/docs/tsconfig.json
@@ -1,11 +1,7 @@
{
"compilerOptions": {
"target": "ESNext",
- "lib": [
- "dom",
- "dom.iterable",
- "esnext"
- ],
+ "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -23,23 +19,10 @@
}
],
"paths": {
- "@/*": [
- "./*"
- ],
- "@/content/*": [
- "./.source/*"
- ]
+ "@/*": ["./*"],
+ "@/content/*": ["./.source/*"]
}
},
- "include": [
- "next-env.d.ts",
- "**/*.ts",
- "**/*.tsx",
- ".source/**/*.ts",
- ".next/types/**/*.ts",
- ".next/dev/types/**/*.ts"
- ],
- "exclude": [
- "node_modules"
- ]
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".source/**/*.ts", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
+ "exclude": ["node_modules"]
}
diff --git a/packages/app-tests/agentDriverUpdateBadge.test.ts b/packages/app-tests/agentDriverUpdateBadge.test.ts
index 15a643eb0c..6255ead222 100644
--- a/packages/app-tests/agentDriverUpdateBadge.test.ts
+++ b/packages/app-tests/agentDriverUpdateBadge.test.ts
@@ -1,10 +1,7 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- countAvailableAgentDriverUpdates,
- countAvailableDriverUpdates,
-} from "../../apps/desktop/src/lib/agentDriverUpdateBadge.ts";
+import { countAvailableAgentDriverUpdates, countAvailableDriverUpdates } from "../../apps/desktop/src/lib/agentDriverUpdateBadge.ts";
test("returns zero when there are no available agent driver updates", () => {
assert.equal(countAvailableAgentDriverUpdates([]), 0);
@@ -12,19 +9,9 @@ test("returns zero when there are no available agent driver updates", () => {
});
test("counts available agent driver updates", () => {
- assert.equal(
- countAvailableAgentDriverUpdates([
- { update_available: true },
- { update_available: false },
- { update_available: true },
- ]),
- 2,
- );
+ assert.equal(countAvailableAgentDriverUpdates([{ update_available: true }, { update_available: false }, { update_available: true }]), 2);
});
test("counts JDBC plugin update alongside agent driver updates", () => {
- assert.equal(
- countAvailableDriverUpdates([{ update_available: true }, { update_available: false }], { update_available: true }),
- 2,
- );
+ assert.equal(countAvailableDriverUpdates([{ update_available: true }, { update_available: false }], { update_available: true }), 2);
});
diff --git a/packages/app-tests/aiAgentPlan.test.ts b/packages/app-tests/aiAgentPlan.test.ts
index 1566a3bd78..23bc999b17 100644
--- a/packages/app-tests/aiAgentPlan.test.ts
+++ b/packages/app-tests/aiAgentPlan.test.ts
@@ -172,18 +172,7 @@ test("agent plan ignores comment-only SQL blocks and executes the first real SQL
const plan = buildAiAgentPlan(
planInput({
instruction: "查一下当前数据库里有哪些表",
- assistantContent: [
- "当前数据库中的表:",
- "```sql",
- "-- 当前数据库中的表(仅从已加载的 Schema 上下文得知):",
- "-- public.ihli_data",
- "```",
- "若需查看该表数据,可执行:",
- "```sql",
- "SELECT * FROM ihli_data",
- "LIMIT 10;",
- "```",
- ].join("\n"),
+ assistantContent: ["当前数据库中的表:", "```sql", "-- 当前数据库中的表(仅从已加载的 Schema 上下文得知):", "-- public.ihli_data", "```", "若需查看该表数据,可执行:", "```sql", "SELECT * FROM ihli_data", "LIMIT 10;", "```"].join("\n"),
}),
);
diff --git a/packages/app-tests/aiAgentStepPresentation.test.ts b/packages/app-tests/aiAgentStepPresentation.test.ts
index 63a51e087b..e9fb862699 100644
--- a/packages/app-tests/aiAgentStepPresentation.test.ts
+++ b/packages/app-tests/aiAgentStepPresentation.test.ts
@@ -70,12 +70,7 @@ test("presents blocked and confirmation plans with warning tones", () => {
buildAiAgentStepItems(blocked).map((item) => [item.labelKey, item.tone, item.titleKey, item.titleParams]),
[
["ai.agentSteps.generated", "success", undefined, undefined],
- [
- "ai.agentSteps.blocked",
- "danger",
- "ai.agentStepTitles.riskCheck",
- { action: "block", category: "dangerous", environment: "non_production", reasons: "-" },
- ],
+ ["ai.agentSteps.blocked", "danger", "ai.agentStepTitles.riskCheck", { action: "block", category: "dangerous", environment: "non_production", reasons: "-" }],
["ai.agentSteps.skipped", "muted", "ai.agentStepTitles.blocked", undefined],
],
);
@@ -83,12 +78,7 @@ test("presents blocked and confirmation plans with warning tones", () => {
buildAiAgentStepItems(confirm).map((item) => [item.labelKey, item.tone, item.titleKey, item.titleParams]),
[
["ai.agentSteps.generated", "success", undefined, undefined],
- [
- "ai.agentSteps.needsConfirm",
- "warning",
- "ai.agentStepTitles.riskCheck",
- { action: "confirm", category: "low_risk_write", environment: "production", reasons: "-" },
- ],
+ ["ai.agentSteps.needsConfirm", "warning", "ai.agentStepTitles.riskCheck", { action: "confirm", category: "low_risk_write", environment: "production", reasons: "-" }],
["ai.agentSteps.skipped", "muted", "ai.agentStepTitles.requiresConfirmation", undefined],
],
);
diff --git a/packages/app-tests/aiPromptEval.test.ts b/packages/app-tests/aiPromptEval.test.ts
index 2ea07c1639..4c0180b49e 100644
--- a/packages/app-tests/aiPromptEval.test.ts
+++ b/packages/app-tests/aiPromptEval.test.ts
@@ -86,12 +86,7 @@ const cases: PromptEvalCase[] = [
name: "agent generate keeps the first SQL block executable and read-oriented",
action: "generate",
mode: "agent",
- mustInclude: [
- /Agent 模式/,
- /可直接执行的只读 SQL/,
- /第一个 ```sql 代码块只能包含最终推荐执行的 SQL/,
- /不要把解释性 SQL、备选 SQL、危险 SQL 放在第一个代码块/,
- ],
+ mustInclude: [/Agent 模式/, /可直接执行的只读 SQL/, /第一个 ```sql 代码块只能包含最终推荐执行的 SQL/, /不要把解释性 SQL、备选 SQL、危险 SQL 放在第一个代码块/],
},
{
name: "ask generate never implies auto execution",
@@ -111,12 +106,7 @@ const cases: PromptEvalCase[] = [
action: "generate",
mode: "agent",
context: { schemaScope: "focused_table" },
- mustInclude: [
- /focused table only; not a complete database table list/,
- /不要直接断言不存在/,
- /只读元数据查询/,
- /有哪些表/,
- ],
+ mustInclude: [/focused table only; not a complete database table list/, /不要直接断言不存在/, /只读元数据查询/, /有哪些表/],
mustNotInclude: [/Schema context is complete\./],
},
{
diff --git a/packages/app-tests/aiPromptKeyboard.test.ts b/packages/app-tests/aiPromptKeyboard.test.ts
index 7a9fb44600..f966470641 100644
--- a/packages/app-tests/aiPromptKeyboard.test.ts
+++ b/packages/app-tests/aiPromptKeyboard.test.ts
@@ -1,9 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- isAiPromptImeCompositionEvent,
- shouldSubmitAiPromptOnKeydown,
-} from "../../apps/desktop/src/lib/aiPromptKeyboard.ts";
+import { isAiPromptImeCompositionEvent, shouldSubmitAiPromptOnKeydown } from "../../apps/desktop/src/lib/aiPromptKeyboard.ts";
test("submits AI prompt on plain Enter", () => {
assert.equal(shouldSubmitAiPromptOnKeydown({ key: "Enter" }), true);
diff --git a/packages/app-tests/aiSqlExecutionPolicy.test.ts b/packages/app-tests/aiSqlExecutionPolicy.test.ts
index 7780ba7657..57e8c0b3bf 100644
--- a/packages/app-tests/aiSqlExecutionPolicy.test.ts
+++ b/packages/app-tests/aiSqlExecutionPolicy.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- classifyAiSqlExecution,
- classifyConnectionEnvironment,
- shouldAttemptAiAutoExecute,
-} from "../../apps/desktop/src/lib/aiSqlExecutionPolicy.ts";
+import { classifyAiSqlExecution, classifyConnectionEnvironment, shouldAttemptAiAutoExecute } from "../../apps/desktop/src/lib/aiSqlExecutionPolicy.ts";
import type { ConnectionConfig } from "../../apps/desktop/src/types/database.ts";
function conn(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
@@ -28,10 +24,7 @@ test("classifyConnectionEnvironment treats local and dev targets as non-producti
test("classifyConnectionEnvironment treats production signals and unknown targets as production-like", () => {
assert.equal(classifyConnectionEnvironment(conn({ name: "prod-db", host: "10.0.0.9" })), "production");
- assert.equal(
- classifyConnectionEnvironment(conn({ name: "analytics", host: "10.0.0.9", database: "warehouse" })),
- "unknown",
- );
+ assert.equal(classifyConnectionEnvironment(conn({ name: "analytics", host: "10.0.0.9", database: "warehouse" })), "unknown");
});
test("read SQL auto-executes on production and non-production", () => {
@@ -41,10 +34,7 @@ test("read SQL auto-executes on production and non-production", () => {
test("single insert auto-executes only on non-production targets", () => {
assert.equal(classifyAiSqlExecution("INSERT INTO users(name) VALUES ('a')", conn()).action, "auto_execute");
- assert.equal(
- classifyAiSqlExecution("INSERT INTO users(name) VALUES ('a')", conn({ name: "prod-db" })).action,
- "confirm",
- );
+ assert.equal(classifyAiSqlExecution("INSERT INTO users(name) VALUES ('a')", conn({ name: "prod-db" })).action, "confirm");
});
test("scoped single update auto-executes only on non-production targets", () => {
@@ -62,10 +52,7 @@ test("broad or destructive writes do not auto-execute", () => {
test("comments and multi-statement writes do not bypass policy", () => {
assert.equal(classifyAiSqlExecution("-- SELECT\nDROP TABLE users", conn()).action, "block");
- assert.equal(
- classifyAiSqlExecution("INSERT INTO users(name) VALUES ('a'); UPDATE users SET name='b' WHERE id=1", conn()).action,
- "confirm",
- );
+ assert.equal(classifyAiSqlExecution("INSERT INTO users(name) VALUES ('a'); UPDATE users SET name='b' WHERE id=1", conn()).action, "confirm");
});
test("AI auto-execution trusts generated SQL in agent generate mode unless the user opts out", () => {
diff --git a/packages/app-tests/aiTableMentions.test.ts b/packages/app-tests/aiTableMentions.test.ts
index 7bc67b4d61..9f4623134e 100644
--- a/packages/app-tests/aiTableMentions.test.ts
+++ b/packages/app-tests/aiTableMentions.test.ts
@@ -17,9 +17,7 @@ test("parses quoted AI table mentions with spaces and dots", () => {
});
test("deduplicates AI table mentions case-insensitively", () => {
- assert.deepEqual(parseAiTableMentions("check @public.Users then @PUBLIC.users"), [
- { raw: "@public.Users", schema: "public", table: "Users" },
- ]);
+ assert.deepEqual(parseAiTableMentions("check @public.Users then @PUBLIC.users"), [{ raw: "@public.Users", schema: "public", table: "Users" }]);
});
test("formats AI table mentions with quotes only when needed", () => {
diff --git a/packages/app-tests/appTheme.test.ts b/packages/app-tests/appTheme.test.ts
index b73eba4c49..b485c4756b 100644
--- a/packages/app-tests/appTheme.test.ts
+++ b/packages/app-tests/appTheme.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- getTauriThemeForMode,
- normalizeAppThemeMode,
- resolveAppThemeAppearance,
-} from "../../apps/desktop/src/lib/appTheme.ts";
+import { getTauriThemeForMode, normalizeAppThemeMode, resolveAppThemeAppearance } from "../../apps/desktop/src/lib/appTheme.ts";
test("normalizes stored app theme modes", () => {
assert.equal(normalizeAppThemeMode("dark"), "dark");
diff --git a/packages/app-tests/binaryCellDownload.test.ts b/packages/app-tests/binaryCellDownload.test.ts
index 13d9bd0c30..0c19b0455b 100644
--- a/packages/app-tests/binaryCellDownload.test.ts
+++ b/packages/app-tests/binaryCellDownload.test.ts
@@ -1,15 +1,7 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- binaryCellDisplayText,
- binaryCellDownloadFileName,
- binaryCellDownloadPayload,
- canDownloadBinaryCellValue,
- isBinaryCellColumnType,
- parseBinaryCellBytes,
- parseBinaryCellHexValue,
-} from "../../apps/desktop/src/lib/binaryCellDownload.ts";
+import { binaryCellDisplayText, binaryCellDownloadFileName, binaryCellDownloadPayload, canDownloadBinaryCellValue, isBinaryCellColumnType, parseBinaryCellBytes, parseBinaryCellHexValue } from "../../apps/desktop/src/lib/binaryCellDownload.ts";
test("parseBinaryCellHexValue accepts 0x and \\x prefixed hex values", () => {
assert.deepEqual(Array.from(parseBinaryCellHexValue("0X48656c6c6f") ?? []), [72, 101, 108, 108, 111]);
@@ -26,9 +18,7 @@ test("parseBinaryCellBytes accepts common driver binary shapes", () => {
assert.deepEqual(Array.from(parseBinaryCellBytes("89504e47", "BLOB") ?? []), [137, 80, 78, 71]);
assert.deepEqual(Array.from(parseBinaryCellBytes("\\x89\\x50\\x4e\\x47") ?? []), [137, 80, 78, 71]);
assert.deepEqual(Array.from(parseBinaryCellBytes([0, 1, 171, 255]) ?? []), [0, 1, 171, 255]);
- assert.deepEqual(Array.from(parseBinaryCellBytes({ type: "Buffer", data: [222, 173, 190, 239] }) ?? []), [
- 222, 173, 190, 239,
- ]);
+ assert.deepEqual(Array.from(parseBinaryCellBytes({ type: "Buffer", data: [222, 173, 190, 239] }) ?? []), [222, 173, 190, 239]);
});
test("binary cell download detects common blob column types", () => {
@@ -69,8 +59,5 @@ test("binaryCellDownloadPayload decodes GBK text bytes", () => {
});
test("binaryCellDownloadFileName sanitizes column names", () => {
- assert.equal(
- binaryCellDownloadFileName({ column: "avatar/blob", rowNumber: 7, mode: "gbk", extension: "txt" }),
- "avatar-blob-row-7-gbk.txt",
- );
+ assert.equal(binaryCellDownloadFileName({ column: "avatar/blob", rowNumber: 7, mode: "gbk", extension: "txt" }), "avatar-blob-row-7-gbk.txt");
});
diff --git a/packages/app-tests/cellImageUrl.test.ts b/packages/app-tests/cellImageUrl.test.ts
index 09a5d3d68b..b89e3f6796 100644
--- a/packages/app-tests/cellImageUrl.test.ts
+++ b/packages/app-tests/cellImageUrl.test.ts
@@ -4,10 +4,7 @@ import { cellImagePreviewUrl } from "../../apps/desktop/src/lib/cellImageUrl.ts"
test("detects obvious remote image URLs", () => {
assert.equal(cellImagePreviewUrl("https://cdn.example.com/avatar/user.png"), "https://cdn.example.com/avatar/user.png");
- assert.equal(
- cellImagePreviewUrl(" https://cdn.example.com/photo.JPG?width=320#preview "),
- "https://cdn.example.com/photo.JPG?width=320#preview",
- );
+ assert.equal(cellImagePreviewUrl(" https://cdn.example.com/photo.JPG?width=320#preview "), "https://cdn.example.com/photo.JPG?width=320#preview");
assert.equal(cellImagePreviewUrl("https://cdn.example.com/image.webp"), "https://cdn.example.com/image.webp");
});
diff --git a/packages/app-tests/cellValue.test.ts b/packages/app-tests/cellValue.test.ts
index 0925ffb7da..51b6330517 100644
--- a/packages/app-tests/cellValue.test.ts
+++ b/packages/app-tests/cellValue.test.ts
@@ -49,4 +49,4 @@ test("displayCellValue handles empty JSON-like strings without alteration", () =
assert.equal(displayCellValue("[]"), "[]");
assert.equal(displayCellValue('{"key":"value"}'), '{"key":"value"}');
assert.equal(displayCellValue("[1,2,3]"), "[1,2,3]");
-});
\ No newline at end of file
+});
diff --git a/packages/app-tests/columnFormatter.test.ts b/packages/app-tests/columnFormatter.test.ts
index 364faef52a..0875a31de0 100644
--- a/packages/app-tests/columnFormatter.test.ts
+++ b/packages/app-tests/columnFormatter.test.ts
@@ -1,26 +1,11 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- applyColumnFormatter,
- buildColumnFormatterKey,
- resolveColumnFormatter,
- normalizeColumnFormatter,
- type ColumnFormatterConfig,
-} from "../../apps/desktop/src/lib/columnFormatter.ts";
+import { applyColumnFormatter, buildColumnFormatterKey, resolveColumnFormatter, normalizeColumnFormatter, type ColumnFormatterConfig } from "../../apps/desktop/src/lib/columnFormatter.ts";
test("formats unix timestamps in seconds, milliseconds, and auto mode", () => {
- assert.equal(
- applyColumnFormatter(1715758200, { kind: "datetime", unit: "seconds" }),
- new Date(1715758200 * 1000).toLocaleString(),
- );
- assert.equal(
- applyColumnFormatter(1715758200000, { kind: "datetime", unit: "milliseconds" }),
- new Date(1715758200000).toLocaleString(),
- );
- assert.equal(
- applyColumnFormatter("1715758200", { kind: "datetime", unit: "auto" }),
- new Date(1715758200 * 1000).toLocaleString(),
- );
+ assert.equal(applyColumnFormatter(1715758200, { kind: "datetime", unit: "seconds" }), new Date(1715758200 * 1000).toLocaleString());
+ assert.equal(applyColumnFormatter(1715758200000, { kind: "datetime", unit: "milliseconds" }), new Date(1715758200000).toLocaleString());
+ assert.equal(applyColumnFormatter("1715758200", { kind: "datetime", unit: "auto" }), new Date(1715758200 * 1000).toLocaleString());
});
test("does not treat compact date strings as unix timestamps", () => {
@@ -88,12 +73,6 @@ test("applies safe custom formatter templates", () => {
});
test("resolves saved custom formatter references", () => {
- assert.deepEqual(
- resolveColumnFormatter(
- { kind: "custom-ref", formatterId: "fmt_1" },
- { fmt_1: { id: "fmt_1", name: "User label", template: "user:${value}" } },
- ),
- { kind: "custom-template", template: "user:${value}" },
- );
+ assert.deepEqual(resolveColumnFormatter({ kind: "custom-ref", formatterId: "fmt_1" }, { fmt_1: { id: "fmt_1", name: "User label", template: "user:${value}" } }), { kind: "custom-template", template: "user:${value}" });
assert.equal(resolveColumnFormatter({ kind: "custom-ref", formatterId: "missing" }, {}), undefined);
});
diff --git a/packages/app-tests/configCrypto.test.ts b/packages/app-tests/configCrypto.test.ts
index 8dfce0858b..99317c7283 100644
--- a/packages/app-tests/configCrypto.test.ts
+++ b/packages/app-tests/configCrypto.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- CONFIG_CRYPTO_UNAVAILABLE,
- encryptConfig,
- decryptConfig,
- isEncryptedConfig,
-} from "../../apps/desktop/src/lib/configCrypto.ts";
+import { CONFIG_CRYPTO_UNAVAILABLE, encryptConfig, decryptConfig, isEncryptedConfig } from "../../apps/desktop/src/lib/configCrypto.ts";
test("encrypts and decrypts config round-trip", async () => {
const original = JSON.stringify([{ id: "1", name: "test", password: "secret123" }]);
@@ -46,7 +41,10 @@ test("reports crypto unavailable when Web Crypto is missing", async () => {
});
try {
- await assert.rejects(() => encryptConfig("{}", "passphrase"), (err: Error) => err.message === CONFIG_CRYPTO_UNAVAILABLE);
+ await assert.rejects(
+ () => encryptConfig("{}", "passphrase"),
+ (err: Error) => err.message === CONFIG_CRYPTO_UNAVAILABLE,
+ );
} finally {
Object.defineProperty(globalThis, "crypto", {
configurable: true,
diff --git a/packages/app-tests/connectionAttemptTimeout.test.ts b/packages/app-tests/connectionAttemptTimeout.test.ts
index 703c2491a8..11cf355f81 100644
--- a/packages/app-tests/connectionAttemptTimeout.test.ts
+++ b/packages/app-tests/connectionAttemptTimeout.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS,
- MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS,
- connectionAttemptTimeoutMessage,
- connectionAttemptTimeoutMs,
-} from "../../apps/desktop/src/lib/connectionAttemptTimeout.ts";
+import { CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS, MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS, connectionAttemptTimeoutMessage, connectionAttemptTimeoutMs } from "../../apps/desktop/src/lib/connectionAttemptTimeout.ts";
test("uses connection timeout with a small UI buffer", () => {
assert.equal(connectionAttemptTimeoutMs({ connect_timeout_secs: 8 }), 8_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
@@ -27,10 +22,7 @@ test("honors slower SSH tunnel connection timeouts", () => {
});
test("allows MongoDB legacy agent fallback after native driver timeout", () => {
- assert.equal(
- connectionAttemptTimeoutMs({ db_type: "mongodb", connect_timeout_secs: 5 }),
- 5_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS + MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS,
- );
+ assert.equal(connectionAttemptTimeoutMs({ db_type: "mongodb", connect_timeout_secs: 5 }), 5_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS + MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS);
});
test("formats connection attempt timeout messages", () => {
diff --git a/packages/app-tests/connectionDeepLink.test.ts b/packages/app-tests/connectionDeepLink.test.ts
index 27bf02ead1..4814e58c37 100644
--- a/packages/app-tests/connectionDeepLink.test.ts
+++ b/packages/app-tests/connectionDeepLink.test.ts
@@ -3,9 +3,7 @@ import { test } from "vitest";
import { parseConnectionDeepLink } from "../../apps/desktop/src/lib/connectionDeepLink.ts";
test("parses dbx connection deep link query fields", () => {
- const draft = parseConnectionDeepLink(
- "dbx://connection/new?type=postgres&host=db.internal&port=15432&user=app&database=orders&name=Orders",
- );
+ const draft = parseConnectionDeepLink("dbx://connection/new?type=postgres&host=db.internal&port=15432&user=app&database=orders&name=Orders");
assert.deepEqual(draft, {
name: "Orders",
@@ -23,9 +21,7 @@ test("parses dbx connection deep link query fields", () => {
});
test("parses encoded database URL with password", () => {
- const draft = parseConnectionDeepLink(
- "dbx://connection/new?url=postgres%3A%2F%2Fapp%3Asecret%40db.internal%3A5432%2Forders%3Fsslmode%3Drequire",
- );
+ const draft = parseConnectionDeepLink("dbx://connection/new?url=postgres%3A%2F%2Fapp%3Asecret%40db.internal%3A5432%2Forders%3Fsslmode%3Drequire");
assert.equal(draft?.dbType, "postgres");
assert.equal(draft?.driverProfile, "postgres");
@@ -38,9 +34,7 @@ test("parses encoded database URL with password", () => {
});
test("allows password query field to override database URL password", () => {
- const draft = parseConnectionDeepLink(
- "dbx://connection/new?url=postgres%3A%2F%2Fapp%3Asecret%40db.internal%3A5432%2Forders&password=override",
- );
+ const draft = parseConnectionDeepLink("dbx://connection/new?url=postgres%3A%2F%2Fapp%3Asecret%40db.internal%3A5432%2Forders&password=override");
assert.equal(draft?.password, "override");
});
diff --git a/packages/app-tests/connectionPresentation.test.ts b/packages/app-tests/connectionPresentation.test.ts
index 9a5375fe94..0bcf7c5ece 100644
--- a/packages/app-tests/connectionPresentation.test.ts
+++ b/packages/app-tests/connectionPresentation.test.ts
@@ -1,15 +1,7 @@
import { test } from "vitest";
import assert from "node:assert/strict";
import type { ConnectionConfig } from "../../apps/desktop/src/types/database.ts";
-import {
- connectionDriverLabel,
- connectionEndpointLabel,
- connectionIconType,
- connectionOptionSubtitle,
- connectionRedactedEndpointLabel,
- connectionRedactedNameLabel,
- connectionRedactedOptionSubtitle,
-} from "../../apps/desktop/src/lib/connectionPresentation.ts";
+import { connectionDriverLabel, connectionEndpointLabel, connectionIconType, connectionOptionSubtitle, connectionRedactedEndpointLabel, connectionRedactedNameLabel, connectionRedactedOptionSubtitle } from "../../apps/desktop/src/lib/connectionPresentation.ts";
const baseConnection: ConnectionConfig = {
id: "conn-1",
diff --git a/packages/app-tests/connectionStoreGroupedConnect.test.ts b/packages/app-tests/connectionStoreGroupedConnect.test.ts
index bc0dd876b9..a854a0bcde 100644
--- a/packages/app-tests/connectionStoreGroupedConnect.test.ts
+++ b/packages/app-tests/connectionStoreGroupedConnect.test.ts
@@ -89,7 +89,10 @@ test("connecting a grouped connection updates it in place instead of adding a ro
assert.equal(store.treeNodes.length, 1);
assert.equal(store.treeNodes[0].type, "connection-group");
- assert.deepEqual(store.treeNodes[0].children?.map((node) => node.id), ["conn-1"]);
+ assert.deepEqual(
+ store.treeNodes[0].children?.map((node) => node.id),
+ ["conn-1"],
+ );
assert.equal(countConnectionNodes(store.treeNodes, "conn-1"), 1);
} finally {
globalThis.fetch = originalFetch;
diff --git a/packages/app-tests/connectionStorePinnedCleanup.test.ts b/packages/app-tests/connectionStorePinnedCleanup.test.ts
index 9390fd1f37..0f75ef918c 100644
--- a/packages/app-tests/connectionStorePinnedCleanup.test.ts
+++ b/packages/app-tests/connectionStorePinnedCleanup.test.ts
@@ -83,4 +83,3 @@ test("removeConnection prunes pinned ids and persists the pruned set", async ()
storage.restore();
}
});
-
diff --git a/packages/app-tests/connectionUrl.test.ts b/packages/app-tests/connectionUrl.test.ts
index f81ba44f78..acd5494329 100644
--- a/packages/app-tests/connectionUrl.test.ts
+++ b/packages/app-tests/connectionUrl.test.ts
@@ -51,18 +51,14 @@ test("parses mysql TLS URL params into the SSL switch state", () => {
});
test("parses TiDB Cloud MySQL URLs as TLS connections", () => {
- const parsed = parseConnectionUrl(
- "mysql://root:[email protected]:4000/test",
- );
+ const parsed = parseConnectionUrl("mysql://root:[email protected]:4000/test");
assert.equal(parsed.dbType, "mysql");
assert.equal(parsed.ssl, true);
});
test("parses MySQL JDBC user and password URL params as credentials", () => {
- const parsed = parseConnectionUrl(
- "jdbc:mysql://127.0.0.1:1234/example?user=admin&password=pwd&useUnicode=true&characterEncoding=UTF8&useSSL=false",
- );
+ const parsed = parseConnectionUrl("jdbc:mysql://127.0.0.1:1234/example?user=admin&password=pwd&useUnicode=true&characterEncoding=UTF8&useSSL=false");
assert.equal(parsed.dbType, "mysql");
assert.equal(parsed.host, "127.0.0.1");
@@ -159,9 +155,7 @@ test("parses Apache IoTDB JDBC URLs", () => {
});
test("parses GBase 8s JDBC URLs", () => {
- const parsed = parseConnectionUrl(
- "jdbc:gbasedbt-sqli://gbasedbt:[email protected]:20013/testdb:GBASEDBTSERVER=gbase01;CLIENT_LOCALE=zh_cn.utf8",
- );
+ const parsed = parseConnectionUrl("jdbc:gbasedbt-sqli://gbasedbt:[email protected]:20013/testdb:GBASEDBTSERVER=gbase01;CLIENT_LOCALE=zh_cn.utf8");
assert.equal(parsed.dbType, "gbase");
assert.equal(parsed.driverProfile, "gbase8s");
@@ -187,9 +181,7 @@ test("parses UCanAccess JDBC URLs as Access database files", () => {
});
test("parses SQL Server JDBC URLs with semicolon properties", () => {
- const parsed = parseConnectionUrl(
- "jdbc:sqlserver://sql.example.com:1434;databaseName=erp;user=sa;password=s%40cret;encrypt=true",
- );
+ const parsed = parseConnectionUrl("jdbc:sqlserver://sql.example.com:1434;databaseName=erp;user=sa;password=s%40cret;encrypt=true");
assert.equal(parsed.dbType, "sqlserver");
assert.equal(parsed.driverProfile, "sqlserver");
@@ -224,8 +216,7 @@ test("parses Oracle JDBC SID URLs", () => {
});
test("parses Oracle JDBC descriptors and keeps the original connection string", () => {
- const source =
- "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracle.example.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))";
+ const source = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracle.example.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))";
const parsed = parseConnectionUrl(source);
assert.equal(parsed.dbType, "oracle");
@@ -260,10 +251,7 @@ test("normalizes MongoDB URL credentials when reserved characters can be parsed
});
test("normalizes invalid percent escapes in MongoDB URL credentials", () => {
- assert.equal(
- normalizeMongoConnectionString("mongodb://reader:pa%[email protected]/admin"),
- "mongodb://reader:pa%[email protected]/admin",
- );
+ assert.equal(normalizeMongoConnectionString("mongodb://reader:pa%[email protected]/admin"), "mongodb://reader:pa%[email protected]/admin");
});
test("uses selected HTTP-compatible profile for HTTP URLs", () => {
@@ -277,10 +265,7 @@ test("uses selected HTTP-compatible profile for HTTP URLs", () => {
});
test("parses HTTPS ClickHouse URLs with selected profile", () => {
- const parsed = parseConnectionUrl(
- "https://default:[email protected]:8443/default?secure=true",
- "clickhouse",
- );
+ const parsed = parseConnectionUrl("https://default:[email protected]:8443/default?secure=true", "clickhouse");
assert.equal(parsed.dbType, "clickhouse");
assert.equal(parsed.driverProfile, "clickhouse");
@@ -294,8 +279,7 @@ test("parses HTTPS ClickHouse URLs with selected profile", () => {
});
test("parses MongoDB multi-host replica set URL", () => {
- const source =
- "mongodb://test:[email protected]:27017,1.1.1.2:27017,1.1.1.3:27017/admin?authMechanism=SCRAM-SHA-256&authSource=admin&replicaSet=testRS0";
+ const source = "mongodb://test:[email protected]:27017,1.1.1.2:27017,1.1.1.3:27017/admin?authMechanism=SCRAM-SHA-256&authSource=admin&replicaSet=testRS0";
const parsed = parseConnectionUrl(source);
assert.equal(parsed.dbType, "mongodb");
@@ -312,8 +296,7 @@ test("parses MongoDB multi-host replica set URL", () => {
});
test("parses MongoDB single-host URL with replicaSet and auth params", () => {
- const source =
- "mongodb://test:[email protected]:27017/?authMechanism=SCRAM-SHA-256&authSource=admin&replicaSet=testRS0";
+ const source = "mongodb://test:[email protected]:27017/?authMechanism=SCRAM-SHA-256&authSource=admin&replicaSet=testRS0";
const parsed = parseConnectionUrl(source);
assert.equal(parsed.dbType, "mongodb");
diff --git a/packages/app-tests/connectionVisibleDatabases.test.ts b/packages/app-tests/connectionVisibleDatabases.test.ts
index 0bbf5fcb7a..5a67afb164 100644
--- a/packages/app-tests/connectionVisibleDatabases.test.ts
+++ b/packages/app-tests/connectionVisibleDatabases.test.ts
@@ -1,11 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- buildDraftVisibleDatabasesConnectionId,
- connectionCanChooseVisibleDatabases,
- visibleDatabaseSelectionIsStale,
- initialVisibleDatabaseSelection,
-} from "../../apps/desktop/src/lib/connectionVisibleDatabases.ts";
+import { buildDraftVisibleDatabasesConnectionId, connectionCanChooseVisibleDatabases, visibleDatabaseSelectionIsStale, initialVisibleDatabaseSelection } from "../../apps/desktop/src/lib/connectionVisibleDatabases.ts";
import type { ConnectionConfig } from "../../apps/desktop/src/types/database.ts";
function config(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
@@ -55,9 +50,7 @@ test("visible databases can be chosen for catalog-like connections only", () =>
});
test("initial selection uses configured visible databases when available", () => {
- assert.deepEqual(initialVisibleDatabaseSelection(["app", "analytics", "billing"], ["billing", "missing"]), [
- "billing",
- ]);
+ assert.deepEqual(initialVisibleDatabaseSelection(["app", "analytics", "billing"], ["billing", "missing"]), ["billing"]);
});
test("initial selection uses default visible database names when no filter is configured", () => {
diff --git a/packages/app-tests/createDatabaseSql.test.ts b/packages/app-tests/createDatabaseSql.test.ts
index 22ab44749c..b49d5fa2a0 100644
--- a/packages/app-tests/createDatabaseSql.test.ts
+++ b/packages/app-tests/createDatabaseSql.test.ts
@@ -1,10 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- duckDbAttachedDatabaseNameFromPath,
- uniqueDuckDbAttachedDatabaseName,
- supportsCreateDatabaseCharset,
-} from "../../apps/desktop/src/lib/createDatabaseSql.ts";
+import { duckDbAttachedDatabaseNameFromPath, uniqueDuckDbAttachedDatabaseName, supportsCreateDatabaseCharset } from "../../apps/desktop/src/lib/createDatabaseSql.ts";
test("recognizes MySQL-compatible driver profiles", () => {
assert.equal(supportsCreateDatabaseCharset("mysql", "oceanbase"), true);
diff --git a/packages/app-tests/dataGridCellCoercion.test.ts b/packages/app-tests/dataGridCellCoercion.test.ts
index aee1fcd418..26a78cddfb 100644
--- a/packages/app-tests/dataGridCellCoercion.test.ts
+++ b/packages/app-tests/dataGridCellCoercion.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- coerceDataGridCellValue,
- dataGridCellDisplayText,
- dataGridCellEditorText,
-} from "../../apps/desktop/src/lib/dataGridCellCoercion.ts";
+import { coerceDataGridCellValue, dataGridCellDisplayText, dataGridCellEditorText } from "../../apps/desktop/src/lib/dataGridCellCoercion.ts";
test("formats Postgres array cells with native brace syntax", () => {
const columnInfo = { data_type: "_text" };
diff --git a/packages/app-tests/dataGridColumnFilter.test.ts b/packages/app-tests/dataGridColumnFilter.test.ts
index 6e3694ea33..d997ada305 100644
--- a/packages/app-tests/dataGridColumnFilter.test.ts
+++ b/packages/app-tests/dataGridColumnFilter.test.ts
@@ -1,9 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- appendColumnValueFilterCondition,
- buildColumnValueFilterCondition,
-} from "../../apps/desktop/src/lib/dataGridColumnFilter.ts";
+import { appendColumnValueFilterCondition, buildColumnValueFilterCondition } from "../../apps/desktop/src/lib/dataGridColumnFilter.ts";
function installFilterFetchMock() {
globalThis.fetch = (async (input, init) => {
@@ -12,16 +9,9 @@ function installFilterFetchMock() {
}
const body = JSON.parse(String(init?.body ?? "{}"));
const options = body.options;
- const quote =
- options.databaseType === "mysql"
- ? (name: string) => `\`${name}\``
- : options.databaseType === "sqlserver"
- ? (name: string) => `[${name}]`
- : (name: string) => `"${name}"`;
+ const quote = options.databaseType === "mysql" ? (name: string) => `\`${name}\`` : options.databaseType === "sqlserver" ? (name: string) => `[${name}]` : (name: string) => `"${name}"`;
const text = String(options.rawValue ?? "").trim();
- const result = /^null$/i.test(text)
- ? `${quote(options.columnName)} IS NULL`
- : `${quote(options.columnName)} = ${/^\d+$/.test(text) ? text : `'${text}'`}`;
+ const result = /^null$/i.test(text) ? `${quote(options.columnName)} IS NULL` : `${quote(options.columnName)} = ${/^\d+$/.test(text) ? text : `'${text}'`}`;
return new Response(JSON.stringify(result), { status: 200, headers: { "Content-Type": "application/json" } });
}) as typeof fetch;
}
diff --git a/packages/app-tests/dataGridColumnType.test.ts b/packages/app-tests/dataGridColumnType.test.ts
index be1feb80c8..f63453d791 100644
--- a/packages/app-tests/dataGridColumnType.test.ts
+++ b/packages/app-tests/dataGridColumnType.test.ts
@@ -51,8 +51,5 @@ test("treats blank/whitespace types as absent and falls through", () => {
});
assert.equal(type, "text");
- assert.equal(
- resolveHeaderColumnType({ tableColumnType: "", resultColumnTypes: [""], actualColIdx: 0 }),
- undefined,
- );
+ assert.equal(resolveHeaderColumnType({ tableColumnType: "", resultColumnTypes: [""], actualColIdx: 0 }), undefined);
});
diff --git a/packages/app-tests/dataGridColumnVisibility.test.ts b/packages/app-tests/dataGridColumnVisibility.test.ts
index d8fb45560e..fd8ac344d1 100644
--- a/packages/app-tests/dataGridColumnVisibility.test.ts
+++ b/packages/app-tests/dataGridColumnVisibility.test.ts
@@ -1,14 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- allNullColumnIndexes,
- filterColumnVisibilityOptions,
- hiddenColumnIndexesWithAllNullColumns,
- invertedHiddenColumnIndexes,
- nextHiddenColumnIndexes,
- removeAutoHiddenColumnIndexes,
- visibleColumnIndexesForFilter,
-} from "../../apps/desktop/src/lib/dataGridColumnVisibility.ts";
+import { allNullColumnIndexes, filterColumnVisibilityOptions, hiddenColumnIndexesWithAllNullColumns, invertedHiddenColumnIndexes, nextHiddenColumnIndexes, removeAutoHiddenColumnIndexes, visibleColumnIndexesForFilter } from "../../apps/desktop/src/lib/dataGridColumnVisibility.ts";
test("filters column visibility options by trimmed case-insensitive text", () => {
const options = filterColumnVisibilityOptions(["id", "created_at", "CustomerName"], " NAME ");
diff --git a/packages/app-tests/dataGridDetail.test.ts b/packages/app-tests/dataGridDetail.test.ts
index d4bf407f5a..3b5b635ea2 100644
--- a/packages/app-tests/dataGridDetail.test.ts
+++ b/packages/app-tests/dataGridDetail.test.ts
@@ -1,17 +1,7 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- buildDataGridCellDetail,
- buildDataGridColumnDetail,
- dataGridColumnDetailJson,
- dataGridColumnDetailTsv,
- buildDataGridRowDetail,
- dataGridRowDetailJson,
- dataGridRowDetailTsv,
- filterDataGridDetailFields,
- type DataGridCellDetail,
-} from "../../apps/desktop/src/lib/dataGridDetail.ts";
+import { buildDataGridCellDetail, buildDataGridColumnDetail, dataGridColumnDetailJson, dataGridColumnDetailTsv, buildDataGridRowDetail, dataGridRowDetailJson, dataGridRowDetailTsv, filterDataGridDetailFields, type DataGridCellDetail } from "../../apps/desktop/src/lib/dataGridDetail.ts";
import type { CellValue } from "../../apps/desktop/src/lib/cellValue.ts";
test("buildDataGridCellDetail returns null for an invalid column", () => {
@@ -215,10 +205,7 @@ test("dataGridColumnDetailJson and dataGridColumnDetailTsv format copy payloads"
});
assert.ok(detail);
- assert.equal(
- dataGridColumnDetailJson(detail),
- '[\n {\n "row": 1,\n "value": "Ada"\n },\n {\n "row": 2,\n "value": null\n }\n]',
- );
+ assert.equal(dataGridColumnDetailJson(detail), '[\n {\n "row": 1,\n "value": "Ada"\n },\n {\n "row": 2,\n "value": null\n }\n]');
assert.equal(dataGridColumnDetailTsv(detail), "Ada\nNULL");
});
diff --git a/packages/app-tests/dataGridEditor.test.ts b/packages/app-tests/dataGridEditor.test.ts
index fc0bc66364..408b39d5f3 100644
--- a/packages/app-tests/dataGridEditor.test.ts
+++ b/packages/app-tests/dataGridEditor.test.ts
@@ -27,8 +27,7 @@ function installBrowserTestGlobals() {
JSON.stringify({
statements: mockPreparedSaveStatements(options),
rollbackStatements: [],
- executionSchema:
- options.databaseType === "oracle" || options.databaseType === "neo4j" ? undefined : options.tableMeta.schema,
+ executionSchema: options.databaseType === "oracle" || options.databaseType === "neo4j" ? undefined : options.tableMeta.schema,
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
@@ -36,9 +35,7 @@ function installBrowserTestGlobals() {
}
function mockPreparedSaveStatements(options: DataGridSaveStatementOptions): string[] {
- const table = options.tableMeta.schema
- ? `${quotePgIdentifier(options.tableMeta.schema)}.${quotePgIdentifier(options.tableMeta.tableName)}`
- : quotePgIdentifier(options.tableMeta.tableName);
+ const table = options.tableMeta.schema ? `${quotePgIdentifier(options.tableMeta.schema)}.${quotePgIdentifier(options.tableMeta.tableName)}` : quotePgIdentifier(options.tableMeta.tableName);
const statements: string[] = [];
for (const rowIndex of options.deletedRows) {
const row = options.rows[rowIndex];
@@ -48,12 +45,7 @@ function mockPreparedSaveStatements(options: DataGridSaveStatementOptions): stri
for (const [rowIndex, changes] of options.dirtyRows) {
const row = options.rows[rowIndex];
if (!row) continue;
- const sets = changes
- .map(
- ([columnIndex, value]) =>
- `${quotePgIdentifier(options.columns[columnIndex])} = ${formatGridSqlLiteral(value, options.databaseType)}`,
- )
- .join(", ");
+ const sets = changes.map(([columnIndex, value]) => `${quotePgIdentifier(options.columns[columnIndex])} = ${formatGridSqlLiteral(value, options.databaseType)}`).join(", ");
statements.push(`UPDATE ${table} SET ${sets} WHERE ${primaryKeyWhere(options, row)};`);
}
for (const row of options.newRows) {
@@ -387,9 +379,7 @@ test("saving inserted rows reloads current table data", async () => {
await editor.saveChanges();
assert.deepEqual(executedSql, [`INSERT INTO "public"."people" ("id", "name") VALUES (2, 'Linus');`]);
- assert.deepEqual(emitted, [
- ["reload", "SELECT id, name FROM people", "linus", "name ILIKE '%l%'", "id DESC", 50, 50],
- ]);
+ assert.deepEqual(emitted, [["reload", "SELECT id, name FROM people", "linus", "name ILIKE '%l%'", "id DESC", 50, 50]]);
});
test("saving edited rows without deletes does not reload table data", async () => {
@@ -500,9 +490,7 @@ test("saving manually typed JSON from a MySQL grid normalizes smart quotes", asy
editor.applyCellValue(0, 1, "{“2:3”:“3:4”,“3:2”:“4:3”,“21:9”:“16:9”}");
await editor.saveChanges();
- assert.deepEqual(executedSql, [
- `UPDATE "settings" SET "payload" = '{"2:3":"3:4","3:2":"4:3","21:9":"16:9"}' WHERE "id" = 1;`,
- ]);
+ assert.deepEqual(executedSql, [`UPDATE "settings" SET "payload" = '{"2:3":"3:4","3:2":"4:3","21:9":"16:9"}' WHERE "id" = 1;`]);
});
test("saving manually typed JSON arrays from a Postgres array column uses array values", async () => {
diff --git a/packages/app-tests/dataGridSearchSplit.test.ts b/packages/app-tests/dataGridSearchSplit.test.ts
index 8f913425f1..b2ca60d834 100644
--- a/packages/app-tests/dataGridSearchSplit.test.ts
+++ b/packages/app-tests/dataGridSearchSplit.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- clampSearchSplitWidth,
- DEFAULT_SEARCH_SPLIT_RATIO,
- MIN_SEARCH_SPLIT_PANE_WIDTH,
-} from "../../apps/desktop/src/lib/dataGridSearchSplit.ts";
+import { clampSearchSplitWidth, DEFAULT_SEARCH_SPLIT_RATIO, MIN_SEARCH_SPLIT_PANE_WIDTH } from "../../apps/desktop/src/lib/dataGridSearchSplit.ts";
test("defaults the search split to an even width", () => {
assert.equal(clampSearchSplitWidth({ containerWidth: 800 }), 400);
diff --git a/packages/app-tests/dataGridTemporalEditor.test.ts b/packages/app-tests/dataGridTemporalEditor.test.ts
index 4269ab1d76..e856447eb1 100644
--- a/packages/app-tests/dataGridTemporalEditor.test.ts
+++ b/packages/app-tests/dataGridTemporalEditor.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- formatTemporalInputValue,
- parseTemporalInputValue,
- temporalCellEditorKind,
-} from "../../apps/desktop/src/lib/dataGridTemporalEditor.ts";
+import { formatTemporalInputValue, parseTemporalInputValue, temporalCellEditorKind } from "../../apps/desktop/src/lib/dataGridTemporalEditor.ts";
test("detects explicit date time column types for grid editing", () => {
assert.equal(temporalCellEditorKind("date"), "date");
diff --git a/packages/app-tests/databaseCapabilities.test.ts b/packages/app-tests/databaseCapabilities.test.ts
index fbd10304e2..cb848467b6 100644
--- a/packages/app-tests/databaseCapabilities.test.ts
+++ b/packages/app-tests/databaseCapabilities.test.ts
@@ -61,17 +61,7 @@ test("treats Access as a local single-database agent driver", () => {
});
test("exposes the extended JDBC agent ecosystem through driver management", () => {
- for (const dbType of [
- "databricks",
- "saphana",
- "teradata",
- "vertica",
- "firebird",
- "exasol",
- "opengauss",
- "oceanbase-oracle",
- "gbase",
- ] as const) {
+ for (const dbType of ["databricks", "saphana", "teradata", "vertica", "firebird", "exasol", "opengauss", "oceanbase-oracle", "gbase"] as const) {
assert.equal(supportsDriverManagement(dbType), true, `${dbType} should be agent-managed`);
assert.equal(supportsDatabaseSearch(dbType), true, `${dbType} should support database search`);
}
@@ -266,12 +256,5 @@ test("object browser entry follows database tree shape", () => {
test("sidebar object capability registry describes object groups by database type", () => {
assert.deepEqual(sidebarObjectKindsForDatabase("databend"), ["TABLE", "VIEW"]);
assert.deepEqual(sidebarObjectKindsForDatabase("postgres"), ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE"]);
- assert.deepEqual(sidebarObjectKindsForDatabase("oracle"), [
- "TABLE",
- "VIEW",
- "PROCEDURE",
- "FUNCTION",
- "PACKAGE",
- "PACKAGE_BODY",
- ]);
+ assert.deepEqual(sidebarObjectKindsForDatabase("oracle"), ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"]);
});
diff --git a/packages/app-tests/databaseSearch.test.ts b/packages/app-tests/databaseSearch.test.ts
index 61d4f070b4..276850ca69 100644
--- a/packages/app-tests/databaseSearch.test.ts
+++ b/packages/app-tests/databaseSearch.test.ts
@@ -22,12 +22,7 @@ test("classifies searchable database search columns", () => {
});
test("finds matched columns from returned rows", () => {
- const matches = findMatchedSearchColumns(
- ["id", "email", "note"],
- [42, "[email protected]", "inactive"],
- [col("id", "integer", true), col("email", "varchar"), col("note", "text")],
- "alice",
- );
+ const matches = findMatchedSearchColumns(["id", "email", "note"], [42, "[email protected]", "inactive"], [col("id", "integer", true), col("email", "varchar"), col("note", "text")], "alice");
assert.deepEqual(matches, ["email"]);
});
diff --git a/packages/app-tests/databaseTree.test.ts b/packages/app-tests/databaseTree.test.ts
index 9d56644476..bf9c5b6888 100644
--- a/packages/app-tests/databaseTree.test.ts
+++ b/packages/app-tests/databaseTree.test.ts
@@ -1,20 +1,9 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- buildDatabaseTreeNodes,
- buildDuckDbConnectionTreeNodes,
- sortSidebarNames,
- shouldIncludeDefaultDatabaseNode,
-} from "../../apps/desktop/src/lib/databaseTree.ts";
+import { buildDatabaseTreeNodes, buildDuckDbConnectionTreeNodes, sortSidebarNames, shouldIncludeDefaultDatabaseNode } from "../../apps/desktop/src/lib/databaseTree.ts";
test("数据库节点按自然名称排序", () => {
- const nodes = buildDatabaseTreeNodes("conn-1", [
- { name: "db10" },
- { name: "db2" },
- { name: "campaign_data" },
- { name: "cms" },
- { name: "mk_campaign" },
- ]);
+ const nodes = buildDatabaseTreeNodes("conn-1", [{ name: "db10" }, { name: "db2" }, { name: "campaign_data" }, { name: "cms" }, { name: "mk_campaign" }]);
assert.deepEqual(
nodes.map((node) => node.database),
@@ -54,11 +43,7 @@ test("MySQL-compatible catalogless services can opt into the default database no
});
test("DuckDB shows primary catalog schemas directly under the connection", () => {
- const nodes = buildDuckDbConnectionTreeNodes(
- "conn-1",
- [{ name: "main" }, { name: "attached_reports" }, { name: "analytics_20" }, { name: "analytics_3" }],
- ["prod_sales", "main", "mysql"],
- );
+ const nodes = buildDuckDbConnectionTreeNodes("conn-1", [{ name: "main" }, { name: "attached_reports" }, { name: "analytics_20" }, { name: "analytics_3" }], ["prod_sales", "main", "mysql"]);
assert.deepEqual(
nodes.map((node) => [node.type, node.label, node.database, node.schema]),
diff --git a/packages/app-tests/databaseUserAdmin.test.ts b/packages/app-tests/databaseUserAdmin.test.ts
index 3a71b4b13d..2dabc81a2f 100644
--- a/packages/app-tests/databaseUserAdmin.test.ts
+++ b/packages/app-tests/databaseUserAdmin.test.ts
@@ -76,14 +76,8 @@ test("builds MySQL grant and revoke SQL with normalized privileges", () => {
assert.deepEqual(normalizeMySqlPrivileges(input.privileges), ["SELECT", "SHOW VIEW"]);
assert.equal(mysqlPrivilegeTargetSql("analytics", "daily`rollup"), "`analytics`.`daily``rollup`");
- assert.equal(
- mysqlGrantPrivilegesSql(input),
- "GRANT SELECT, SHOW VIEW ON `analytics`.`daily``rollup` TO 'reporter'@'localhost' WITH GRANT OPTION;",
- );
- assert.equal(
- mysqlRevokePrivilegesSql(input),
- "REVOKE SELECT, SHOW VIEW ON `analytics`.`daily``rollup` FROM 'reporter'@'localhost';",
- );
+ assert.equal(mysqlGrantPrivilegesSql(input), "GRANT SELECT, SHOW VIEW ON `analytics`.`daily``rollup` TO 'reporter'@'localhost' WITH GRANT OPTION;");
+ assert.equal(mysqlRevokePrivilegesSql(input), "REVOKE SELECT, SHOW VIEW ON `analytics`.`daily``rollup` FROM 'reporter'@'localhost';");
assert.equal(mysqlPrivilegeTargetSql("", ""), "*.*");
});
@@ -104,20 +98,14 @@ test("parses MySQL user result variants", () => {
],
);
- assert.deepEqual(
- usersFromMySqlGranteeResult(result(["GRANTEE"], [["'app'@'%'"], ["'o''brien'@'localhost'"], ["CURRENT_USER"]])),
- [
- { user: "app", host: "%" },
- { user: "o'brien", host: "localhost" },
- ],
- );
+ assert.deepEqual(usersFromMySqlGranteeResult(result(["GRANTEE"], [["'app'@'%'"], ["'o''brien'@'localhost'"], ["CURRENT_USER"]])), [
+ { user: "app", host: "%" },
+ { user: "o'brien", host: "localhost" },
+ ]);
});
test("extracts grants from show grants result", () => {
- assert.deepEqual(
- grantsFromQueryResult(result(["Grants for app@%"], [["GRANT SELECT ON `app`.* TO 'app'@'%'"], [null]])),
- ["GRANT SELECT ON `app`.* TO 'app'@'%'"],
- );
+ assert.deepEqual(grantsFromQueryResult(result(["Grants for app@%"], [["GRANT SELECT ON `app`.* TO 'app'@'%'"], [null]])), ["GRANT SELECT ON `app`.* TO 'app'@'%'"]);
});
test("builds PostgreSQL role lifecycle SQL", () => {
@@ -125,14 +113,8 @@ test("builds PostgreSQL role lifecycle SQL", () => {
assert.equal(quotePostgresIdentifier('report"reader'), '"report""reader"');
assert.equal(postgresRoleLabel(role), 'report"reader');
- assert.equal(
- postgresCreateRoleSql({ ...role, password: "it'works", canLogin: true }),
- "CREATE ROLE \"report\"\"reader\" LOGIN PASSWORD 'it''works';",
- );
- assert.equal(
- postgresCreateRoleSql({ ...role, password: "secret", canLogin: false }),
- 'CREATE ROLE "report""reader" NOLOGIN PASSWORD \'secret\';',
- );
+ assert.equal(postgresCreateRoleSql({ ...role, password: "it'works", canLogin: true }), "CREATE ROLE \"report\"\"reader\" LOGIN PASSWORD 'it''works';");
+ assert.equal(postgresCreateRoleSql({ ...role, password: "secret", canLogin: false }), 'CREATE ROLE "report""reader" NOLOGIN PASSWORD \'secret\';');
assert.equal(postgresAlterRolePasswordSql(role, "next"), 'ALTER ROLE "report""reader" PASSWORD \'next\';');
assert.equal(postgresAlterRoleLoginSql(role, false), 'ALTER ROLE "report""reader" NOLOGIN;');
assert.equal(postgresAlterRoleLoginSql(role, true), 'ALTER ROLE "report""reader" LOGIN;');
@@ -144,14 +126,8 @@ test("builds PostgreSQL privilege and membership SQL", () => {
assert.equal(postgresPrivilegeTargetSql({ scope: "database", database: "analytics" }), 'DATABASE "analytics"');
assert.equal(postgresPrivilegeTargetSql({ scope: "schema", database: "mart" }), 'SCHEMA "mart"');
- assert.equal(
- postgresPrivilegeTargetSql({ scope: "table", database: "mart", table: 'daily"rollup' }),
- 'TABLE "mart"."daily""rollup"',
- );
- assert.equal(
- postgresPrivilegeTargetSql({ scope: "table", database: "mart", table: "*" }),
- 'ALL TABLES IN SCHEMA "mart"',
- );
+ assert.equal(postgresPrivilegeTargetSql({ scope: "table", database: "mart", table: 'daily"rollup' }), 'TABLE "mart"."daily""rollup"');
+ assert.equal(postgresPrivilegeTargetSql({ scope: "table", database: "mart", table: "*" }), 'ALL TABLES IN SCHEMA "mart"');
assert.equal(
postgresGrantPrivilegesSql({
user,
@@ -162,10 +138,7 @@ test("builds PostgreSQL privilege and membership SQL", () => {
}),
'GRANT CONNECT, CREATE ON DATABASE "analytics" TO "reporter" WITH GRANT OPTION;',
);
- assert.equal(
- postgresRevokePrivilegesSql({ user, scope: "schema", database: "mart", privileges: ["usage"] }),
- 'REVOKE USAGE ON SCHEMA "mart" FROM "reporter";',
- );
+ assert.equal(postgresRevokePrivilegesSql({ user, scope: "schema", database: "mart", privileges: ["usage"] }), 'REVOKE USAGE ON SCHEMA "mart" FROM "reporter";');
assert.equal(
postgresGrantPrivilegesSql({
user,
@@ -177,10 +150,7 @@ test("builds PostgreSQL privilege and membership SQL", () => {
}),
'GRANT "readonly" TO "reporter" WITH ADMIN OPTION;',
);
- assert.equal(
- postgresRevokePrivilegesSql({ user, scope: "role", database: "", privileges: [], role: "readonly" }),
- 'REVOKE "readonly" FROM "reporter";',
- );
+ assert.equal(postgresRevokePrivilegesSql({ user, scope: "role", database: "", privileges: [], role: "readonly" }), 'REVOKE "readonly" FROM "reporter";');
});
test("parses PostgreSQL role rows", () => {
diff --git a/packages/app-tests/defaultDatabase.test.ts b/packages/app-tests/defaultDatabase.test.ts
index c108dac84e..6e7f7b225c 100644
--- a/packages/app-tests/defaultDatabase.test.ts
+++ b/packages/app-tests/defaultDatabase.test.ts
@@ -1,13 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- TREE_SCHEMA_DEFAULT_DATABASE_SELECT_VALUE,
- decodeSelectableDatabaseValue,
- encodeSelectableDatabaseValue,
- formatDatabaseLabel,
- isDefaultDatabase,
- resolveDefaultDatabase,
-} from "../../apps/desktop/src/lib/defaultDatabase.ts";
+import { TREE_SCHEMA_DEFAULT_DATABASE_SELECT_VALUE, decodeSelectableDatabaseValue, encodeSelectableDatabaseValue, formatDatabaseLabel, isDefaultDatabase, resolveDefaultDatabase } from "../../apps/desktop/src/lib/defaultDatabase.ts";
test("优先使用连接上已保存的默认数据库", () => {
assert.equal(resolveDefaultDatabase({ database: "analytics" }, ["app", "analytics"]), "analytics");
@@ -39,10 +32,7 @@ test("命名数据库保持原始值不变", () => {
});
test("数据库标签复用默认库显示语义", () => {
- assert.equal(
- formatDatabaseLabel({ db_type: "saphana" }, "", { defaultDatabase: "Default", noDatabase: "No database selected" }),
- "Default",
- );
+ assert.equal(formatDatabaseLabel({ db_type: "saphana" }, "", { defaultDatabase: "Default", noDatabase: "No database selected" }), "Default");
assert.equal(
formatDatabaseLabel({ db_type: "postgres" }, "analytics", {
defaultDatabase: "Default",
@@ -50,8 +40,5 @@ test("数据库标签复用默认库显示语义", () => {
}),
"analytics",
);
- assert.equal(
- formatDatabaseLabel({ db_type: "redis" }, "3", { defaultDatabase: "Default", noDatabase: "No database selected" }),
- "db3",
- );
+ assert.equal(formatDatabaseLabel({ db_type: "redis" }, "3", { defaultDatabase: "Default", noDatabase: "No database selected" }), "db3");
});
diff --git a/packages/app-tests/diagramSvgExport.test.ts b/packages/app-tests/diagramSvgExport.test.ts
index 81e1276bed..88960022a8 100644
--- a/packages/app-tests/diagramSvgExport.test.ts
+++ b/packages/app-tests/diagramSvgExport.test.ts
@@ -1,11 +1,7 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
import { buildEngineeringDiagram } from "../../apps/desktop/src/lib/engineeringDiagram.ts";
-import {
- buildEngineeringDiagramSvg,
- buildTableDiagramSvg,
- diagramSvgFileName,
-} from "../../apps/desktop/src/lib/diagramSvgExport.ts";
+import { buildEngineeringDiagramSvg, buildTableDiagramSvg, diagramSvgFileName } from "../../apps/desktop/src/lib/diagramSvgExport.ts";
import { buildDiagramRelationships, type DiagramTable } from "../../apps/desktop/src/lib/erDiagram.ts";
const tables: DiagramTable[] = [
@@ -23,9 +19,7 @@ const tables: DiagramTable[] = [
{ name: "id", data_type: "bigint", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
{ name: "user_id", data_type: "bigint", is_nullable: false, column_default: null, is_primary_key: false, extra: null },
],
- foreignKeys: [
- { name: "orders_user_id_fk", column: "user_id", ref_table: "users", ref_column: "id" },
- ],
+ foreignKeys: [{ name: "orders_user_id_fk", column: "user_id", ref_table: "users", ref_column: "id" }],
},
];
@@ -76,12 +70,6 @@ test("exports the engineering ER diagram with Chen-style shapes and cardinalitie
});
test("builds safe SVG file names from the active diagram context", () => {
- assert.equal(
- diagramSvgFileName("prod/main", "billing db", "engineering"),
- "dbx-prod-main-billing-db-engineering-er.svg",
- );
- assert.equal(
- diagramSvgFileName("", "", "table"),
- "dbx-diagram-table-structure.svg",
- );
+ assert.equal(diagramSvgFileName("prod/main", "billing db", "engineering"), "dbx-prod-main-billing-db-engineering-er.svg");
+ assert.equal(diagramSvgFileName("", "", "table"), "dbx-diagram-table-structure.svg");
});
diff --git a/packages/app-tests/diagramZoom.test.ts b/packages/app-tests/diagramZoom.test.ts
index 472754bf43..416b998657 100644
--- a/packages/app-tests/diagramZoom.test.ts
+++ b/packages/app-tests/diagramZoom.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- clampDiagramZoom,
- zoomFromGestureScale,
- zoomFromWheelDelta,
-} from "../../apps/desktop/src/lib/diagramZoom.ts";
+import { clampDiagramZoom, zoomFromGestureScale, zoomFromWheelDelta } from "../../apps/desktop/src/lib/diagramZoom.ts";
test("clamps diagram zoom to supported bounds", () => {
assert.equal(clampDiagramZoom(0.2), 0.6);
diff --git a/packages/app-tests/driverInstallProgressUi.test.ts b/packages/app-tests/driverInstallProgressUi.test.ts
index a0a8d6d392..ae49a0a368 100644
--- a/packages/app-tests/driverInstallProgressUi.test.ts
+++ b/packages/app-tests/driverInstallProgressUi.test.ts
@@ -1,13 +1,7 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- addDriverInstallQueue,
- driverInstallProgressPercent,
- isDriverInstallProgressTarget,
- removeDriverInstallQueue,
- takeNextDriverInstallQueue,
-} from "../../apps/desktop/src/lib/driverInstallProgressUi.ts";
+import { addDriverInstallQueue, driverInstallProgressPercent, isDriverInstallProgressTarget, removeDriverInstallQueue, takeNextDriverInstallQueue } from "../../apps/desktop/src/lib/driverInstallProgressUi.ts";
test("formats driver install progress as a bounded whole percent", () => {
assert.equal(driverInstallProgressPercent({ step: "driver", downloaded: 3_900_000, total: 10_500_000 }), 37);
@@ -22,14 +16,8 @@ test("returns null when install progress has no measurable total", () => {
});
test("targets only the row currently installing or upgrading", () => {
- assert.equal(
- isDriverInstallProgressTarget("mysql", { installing: "mysql", upgradingAll: false, progress: null }),
- true,
- );
- assert.equal(
- isDriverInstallProgressTarget("postgres", { installing: "mysql", upgradingAll: false, progress: null }),
- false,
- );
+ assert.equal(isDriverInstallProgressTarget("mysql", { installing: "mysql", upgradingAll: false, progress: null }), true);
+ assert.equal(isDriverInstallProgressTarget("postgres", { installing: "mysql", upgradingAll: false, progress: null }), false);
assert.equal(
isDriverInstallProgressTarget("postgres", {
installing: null,
diff --git a/packages/app-tests/driverRuntimePresentation.test.ts b/packages/app-tests/driverRuntimePresentation.test.ts
index 53a4d20798..bc63f1d74c 100644
--- a/packages/app-tests/driverRuntimePresentation.test.ts
+++ b/packages/app-tests/driverRuntimePresentation.test.ts
@@ -1,14 +1,7 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- formatRuntimeBytes,
- formatRuntimeCpu,
- formatRuntimeUptime,
- runtimeHealthClass,
- runtimeStatusDotClass,
- runtimeStatusClass,
-} from "../../apps/desktop/src/lib/driverRuntimePresentation.ts";
+import { formatRuntimeBytes, formatRuntimeCpu, formatRuntimeUptime, runtimeHealthClass, runtimeStatusDotClass, runtimeStatusClass } from "../../apps/desktop/src/lib/driverRuntimePresentation.ts";
test("formats runtime byte counts compactly", () => {
assert.equal(formatRuntimeBytes(null), "-");
diff --git a/packages/app-tests/editorZoom.test.ts b/packages/app-tests/editorZoom.test.ts
index 516dfc1553..c1871c9920 100644
--- a/packages/app-tests/editorZoom.test.ts
+++ b/packages/app-tests/editorZoom.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- clampEditorFontSize,
- createEditorZoomCommitScheduler,
- fontSizeFromGestureScale,
- fontSizeFromWheelDelta,
-} from "../../apps/desktop/src/lib/editorZoom.ts";
+import { clampEditorFontSize, createEditorZoomCommitScheduler, fontSizeFromGestureScale, fontSizeFromWheelDelta } from "../../apps/desktop/src/lib/editorZoom.ts";
test("clamps editor font size to supported bounds", () => {
assert.equal(clampEditorFontSize(8), 10);
diff --git a/packages/app-tests/elasticsearchCompletion.test.ts b/packages/app-tests/elasticsearchCompletion.test.ts
index 4327921489..75f7ed8b74 100644
--- a/packages/app-tests/elasticsearchCompletion.test.ts
+++ b/packages/app-tests/elasticsearchCompletion.test.ts
@@ -1,19 +1,13 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildElasticsearchCompletionItems,
- getElasticsearchCompletionContext,
- shouldAutoOpenElasticsearchCompletion,
-} from "../../apps/desktop/src/lib/elasticsearchCompletion.ts";
+import { buildElasticsearchCompletionItems, getElasticsearchCompletionContext, shouldAutoOpenElasticsearchCompletion } from "../../apps/desktop/src/lib/elasticsearchCompletion.ts";
import { buildSqlCompletionItems } from "../../apps/desktop/src/lib/sqlCompletion.ts";
const indices = ["orders", "order_items", "users"];
function applyCompletion(text: string, cursor: number, label: string): string {
const context = getElasticsearchCompletionContext(text, cursor);
- const item = buildElasticsearchCompletionItems(text, cursor, { indices }).find(
- (candidate) => candidate.label === label,
- );
+ const item = buildElasticsearchCompletionItems(text, cursor, { indices }).find((candidate) => candidate.label === label);
assert.ok(item, `Expected completion item ${label}`);
return `${text.slice(0, context.from)}${item.apply ?? item.label}${text.slice(cursor)}`;
}
@@ -60,16 +54,10 @@ test("index completion preserves endpoint suffix after cursor", () => {
});
test("suggests Elasticsearch JSON DSL keys and snippets", () => {
- const keyItems = buildElasticsearchCompletionItems(
- 'GET /orders/_search\n{\n "qu',
- 'GET /orders/_search\n{\n "qu'.length,
- );
+ const keyItems = buildElasticsearchCompletionItems('GET /orders/_search\n{\n "qu', 'GET /orders/_search\n{\n "qu'.length);
assert.ok(keyItems.find((item) => item.label === '"query"'));
- const snippetItems = buildElasticsearchCompletionItems(
- 'GET /orders/_search\n{\n "match_',
- 'GET /orders/_search\n{\n "match_'.length,
- );
+ const snippetItems = buildElasticsearchCompletionItems('GET /orders/_search\n{\n "match_', 'GET /orders/_search\n{\n "match_'.length);
const matchAll = snippetItems.find((item) => item.label === "match_all");
assert.ok(matchAll);
assert.doesNotThrow(() => JSON.parse(`{${matchAll?.apply}}`));
@@ -79,13 +67,7 @@ test("Elasticsearch completion auto trigger ignores structural JSON punctuation"
assert.equal(shouldAutoOpenElasticsearchCompletion("GET /", "GET /".length), true);
assert.equal(shouldAutoOpenElasticsearchCompletion("GET /_", "GET /_".length), true);
assert.equal(shouldAutoOpenElasticsearchCompletion("GET /orders/_search\n{", "GET /orders/_search\n{".length), false);
- assert.equal(
- shouldAutoOpenElasticsearchCompletion(
- 'GET /orders/_search\n{"query": {},',
- 'GET /orders/_search\n{"query": {},'.length,
- ),
- false,
- );
+ assert.equal(shouldAutoOpenElasticsearchCompletion('GET /orders/_search\n{"query": {},', 'GET /orders/_search\n{"query": {},'.length), false);
});
test("SQL completion does not include Elasticsearch endpoints", () => {
diff --git a/packages/app-tests/engineeringDiagram.test.ts b/packages/app-tests/engineeringDiagram.test.ts
index 365fd18793..4913596a6f 100644
--- a/packages/app-tests/engineeringDiagram.test.ts
+++ b/packages/app-tests/engineeringDiagram.test.ts
@@ -11,9 +11,7 @@ const tables: DiagramTable[] = [
{ name: "user_id", data_type: "bigint", is_nullable: false, column_default: null, is_primary_key: false, extra: null },
{ name: "status", data_type: "varchar", is_nullable: false, column_default: null, is_primary_key: false, extra: null },
],
- foreignKeys: [
- { name: "orders_user_id_fk", column: "user_id", ref_table: "users", ref_column: "id" },
- ],
+ foreignKeys: [{ name: "orders_user_id_fk", column: "user_id", ref_table: "users", ref_column: "id" }],
},
{
name: "users",
@@ -42,7 +40,10 @@ test("builds engineering ER nodes from tables, columns, and relationships", () =
users: { x: 40, y: 200 },
});
- assert.deepEqual(diagram.entities.map((entity) => entity.name), ["orders", "users"]);
+ assert.deepEqual(
+ diagram.entities.map((entity) => entity.name),
+ ["orders", "users"],
+ );
assert.equal(diagram.attributes.filter((attr) => attr.tableName === "orders").length, 3);
assert.equal(diagram.relationships[0]?.sourceCardinality, "N");
assert.equal(diagram.relationships[0]?.targetCardinality, "1");
@@ -59,35 +60,31 @@ test("sizes the engineering canvas around attributes and relationship diamonds",
});
test("keeps dense attribute clouds from overlapping", () => {
- const denseTables: DiagramTable[] = [{
- name: "roles",
- columns: Array.from({ length: 36 }, (_, index) => ({
- name: `column_${index + 1}`,
- data_type: "varchar",
- is_nullable: true,
- column_default: null,
- is_primary_key: index === 0,
- extra: null,
- })),
- foreignKeys: [],
- }];
+ const denseTables: DiagramTable[] = [
+ {
+ name: "roles",
+ columns: Array.from({ length: 36 }, (_, index) => ({
+ name: `column_${index + 1}`,
+ data_type: "varchar",
+ is_nullable: true,
+ column_default: null,
+ is_primary_key: index === 0,
+ extra: null,
+ })),
+ foreignKeys: [],
+ },
+ ];
const diagram = buildEngineeringDiagram(denseTables, [], {
roles: { x: 40, y: 40 },
});
- const rects = [
- ...diagram.entities,
- ...diagram.attributes,
- ];
+ const rects = [...diagram.entities, ...diagram.attributes];
for (let i = 0; i < rects.length; i++) {
for (let j = i + 1; j < rects.length; j++) {
const left = rects[i];
const right = rects[j];
- const overlaps = left.x < right.x + right.width &&
- left.x + left.width > right.x &&
- left.y < right.y + right.height &&
- left.y + left.height > right.y;
+ const overlaps = left.x < right.x + right.width && left.x + left.width > right.x && left.y < right.y + right.height && left.y + left.height > right.y;
assert.equal(overlaps, false, `${left.id} overlaps ${right.id}`);
}
}
diff --git a/packages/app-tests/erDiagram.test.ts b/packages/app-tests/erDiagram.test.ts
index 3aa80e38aa..cc49bd3d6e 100644
--- a/packages/app-tests/erDiagram.test.ts
+++ b/packages/app-tests/erDiagram.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildDiagramRelationships,
- filterDiagramTables,
- layoutDiagramTables,
-} from "../../apps/desktop/src/lib/erDiagram.ts";
+import { buildDiagramRelationships, filterDiagramTables, layoutDiagramTables } from "../../apps/desktop/src/lib/erDiagram.ts";
test("builds relationships only between tables in the diagram", () => {
const relationships = buildDiagramRelationships([
@@ -49,9 +45,18 @@ test("filters diagram tables by table, column, and foreign key names", () => {
},
];
- assert.deepEqual(filterDiagramTables(tables, "payload").map((table) => table.name), ["audit_log"]);
- assert.deepEqual(filterDiagramTables(tables, "orders_user").map((table) => table.name), ["orders"]);
- assert.deepEqual(filterDiagramTables(tables, "").map((table) => table.name), ["orders", "audit_log"]);
+ assert.deepEqual(
+ filterDiagramTables(tables, "payload").map((table) => table.name),
+ ["audit_log"],
+ );
+ assert.deepEqual(
+ filterDiagramTables(tables, "orders_user").map((table) => table.name),
+ ["orders"],
+ );
+ assert.deepEqual(
+ filterDiagramTables(tables, "").map((table) => table.name),
+ ["orders", "audit_log"],
+ );
});
test("lays out diagram tables in stable rows", () => {
diff --git a/packages/app-tests/gridSelection.test.ts b/packages/app-tests/gridSelection.test.ts
index 9203c85a3c..78d1370999 100644
--- a/packages/app-tests/gridSelection.test.ts
+++ b/packages/app-tests/gridSelection.test.ts
@@ -85,10 +85,7 @@ test("formats selected cells as TSV, CSV, JSON, and SQL values", () => {
};
assert.equal(formatSelectionAsTsv(selection), 'Ada\tmath\nBob\tquote "here"\nO\'Hara\tNULL');
- assert.equal(
- formatSelectionAsCsv(selection),
- '"name","note"\n"Ada","math"\n"Bob","quote ""here"""\n"O\'Hara","NULL"',
- );
+ assert.equal(formatSelectionAsCsv(selection), '"name","note"\n"Ada","math"\n"Bob","quote ""here"""\n"O\'Hara","NULL"');
assert.equal(
formatSelectionAsJson(selection),
JSON.stringify(
diff --git a/packages/app-tests/h2Connection.test.ts b/packages/app-tests/h2Connection.test.ts
index 5141856610..098ca27596 100644
--- a/packages/app-tests/h2Connection.test.ts
+++ b/packages/app-tests/h2Connection.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- h2ConnectionModeForConfig,
- h2FileJdbcUrl,
- h2FilePathFromJdbcUrl,
- h2JdbcFileBasePath,
-} from "../../apps/desktop/src/lib/h2Connection.ts";
+import { h2ConnectionModeForConfig, h2FileJdbcUrl, h2FilePathFromJdbcUrl, h2JdbcFileBasePath } from "../../apps/desktop/src/lib/h2Connection.ts";
test("H2 file JDBC URL strips database file suffixes", () => {
assert.equal(h2JdbcFileBasePath("/data/app.mv.db"), "/data/app");
@@ -20,8 +15,5 @@ test("H2 file path is parsed from JDBC URL with options", () => {
test("H2 connection mode preserves TCP connections unless file mode is explicit", () => {
assert.equal(h2ConnectionModeForConfig({ db_type: "h2", port: 9092, connection_string: undefined }), "tcp");
assert.equal(h2ConnectionModeForConfig({ db_type: "h2", port: 0, connection_string: undefined }), "file");
- assert.equal(
- h2ConnectionModeForConfig({ db_type: "h2", port: 9092, connection_string: "jdbc:h2:file:/data/app" }),
- "file",
- );
+ assert.equal(h2ConnectionModeForConfig({ db_type: "h2", port: 9092, connection_string: "jdbc:h2:file:/data/app" }), "file");
});
diff --git a/packages/app-tests/historyActions.test.ts b/packages/app-tests/historyActions.test.ts
index 3de7e4bf24..182b468647 100644
--- a/packages/app-tests/historyActions.test.ts
+++ b/packages/app-tests/historyActions.test.ts
@@ -3,12 +3,27 @@ import { test } from "vitest";
import { shouldDeleteHistoryEntry, shouldClearHistory } from "../../apps/desktop/src/lib/historyActions.ts";
test("requires confirmation before deleting history entries", () => {
- assert.equal(shouldDeleteHistoryEntry(() => false), false);
- assert.equal(shouldDeleteHistoryEntry(() => true), true);
+ assert.equal(
+ shouldDeleteHistoryEntry(() => false),
+ false,
+ );
+ assert.equal(
+ shouldDeleteHistoryEntry(() => true),
+ true,
+ );
});
test("requires existing entries and confirmation before clearing history", () => {
- assert.equal(shouldClearHistory(0, () => true), false);
- assert.equal(shouldClearHistory(2, () => false), false);
- assert.equal(shouldClearHistory(2, () => true), true);
+ assert.equal(
+ shouldClearHistory(0, () => true),
+ false,
+ );
+ assert.equal(
+ shouldClearHistory(2, () => false),
+ false,
+ );
+ assert.equal(
+ shouldClearHistory(2, () => true),
+ true,
+ );
});
diff --git a/packages/app-tests/historyAiAnalysis.test.ts b/packages/app-tests/historyAiAnalysis.test.ts
index c901755c5c..77654288bb 100644
--- a/packages/app-tests/historyAiAnalysis.test.ts
+++ b/packages/app-tests/historyAiAnalysis.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildHistoryAiAnalysisPrompt,
- canRollbackHistoryEntry,
- type HistoryAiAnalysisEntry,
-} from "../../apps/desktop/src/lib/historyAiAnalysis.ts";
+import { buildHistoryAiAnalysisPrompt, canRollbackHistoryEntry, type HistoryAiAnalysisEntry } from "../../apps/desktop/src/lib/historyAiAnalysis.ts";
const baseEntry: HistoryAiAnalysisEntry = {
id: "h1",
diff --git a/packages/app-tests/historyVirtualList.test.ts b/packages/app-tests/historyVirtualList.test.ts
index ce62ab4e69..d2c200ffdb 100644
--- a/packages/app-tests/historyVirtualList.test.ts
+++ b/packages/app-tests/historyVirtualList.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- HISTORY_ROW_HEIGHT,
- HISTORY_SCROLL_BUFFER,
- shouldVirtualizeHistory,
-} from "../../apps/desktop/src/lib/historyVirtualList.ts";
+import { HISTORY_ROW_HEIGHT, HISTORY_SCROLL_BUFFER, shouldVirtualizeHistory } from "../../apps/desktop/src/lib/historyVirtualList.ts";
test("history list virtualizes every non-empty result set", () => {
assert.equal(shouldVirtualizeHistory(0), false);
diff --git a/packages/app-tests/i18nLocale.test.ts b/packages/app-tests/i18nLocale.test.ts
index 46532b86f3..1fd6836c67 100644
--- a/packages/app-tests/i18nLocale.test.ts
+++ b/packages/app-tests/i18nLocale.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- detectLocaleFromLanguages,
- localeFromLanguageTag,
- normalizeLocale,
-} from "../../apps/desktop/src/i18n/index.ts";
+import { detectLocaleFromLanguages, localeFromLanguageTag, normalizeLocale } from "../../apps/desktop/src/i18n/index.ts";
test("normalizes exact supported locales", () => {
assert.equal(normalizeLocale("en"), "en");
diff --git a/packages/app-tests/imagePreviewViewer.test.ts b/packages/app-tests/imagePreviewViewer.test.ts
index a570d680d4..e2ac92ddba 100644
--- a/packages/app-tests/imagePreviewViewer.test.ts
+++ b/packages/app-tests/imagePreviewViewer.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- imagePreviewFitScale,
- clampImagePreviewScale,
- imagePreviewTransform,
- nextImagePreviewScale,
-} from "../../apps/desktop/src/lib/imagePreviewViewer.ts";
+import { imagePreviewFitScale, clampImagePreviewScale, imagePreviewTransform, nextImagePreviewScale } from "../../apps/desktop/src/lib/imagePreviewViewer.ts";
test("clamps image preview zoom to usable bounds", () => {
assert.equal(clampImagePreviewScale(0.1), 0.2);
@@ -20,10 +15,7 @@ test("zooms in fixed steps from wheel direction", () => {
});
test("builds a stable CSS transform for image previews", () => {
- assert.equal(
- imagePreviewTransform({ scale: 1.5, offsetX: 12, offsetY: -8 }),
- "translate(12px, -8px) scale(1.5)",
- );
+ assert.equal(imagePreviewTransform({ scale: 1.5, offsetX: 12, offsetY: -8 }), "translate(12px, -8px) scale(1.5)");
});
test("calculates fit scale from image and viewport dimensions", () => {
diff --git a/packages/app-tests/jdbcDialect.test.ts b/packages/app-tests/jdbcDialect.test.ts
index b617492938..ab02d1da0a 100644
--- a/packages/app-tests/jdbcDialect.test.ts
+++ b/packages/app-tests/jdbcDialect.test.ts
@@ -1,31 +1,15 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- connectionObjectTreeNodeSchema,
- connectionObjectTreeQuerySchema,
- connectionUsesSchemaExecutionContext,
- connectionUsesDatabaseObjectTreeMode,
- effectiveDatabaseTypeForConnection,
- inferJdbcDialect,
-} from "../../apps/desktop/src/lib/jdbcDialect.ts";
+import { connectionObjectTreeNodeSchema, connectionObjectTreeQuerySchema, connectionUsesSchemaExecutionContext, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, inferJdbcDialect } from "../../apps/desktop/src/lib/jdbcDialect.ts";
import { supportsTableStructureEditing } from "../../apps/desktop/src/lib/databaseFeatureSupport.ts";
import { qualifiedTableName } from "../../apps/desktop/src/lib/tableSelectSql.ts";
test("infers JDBC dialect from URL, driver class, and driver jar path", () => {
- assert.equal(
- inferJdbcDialect({ db_type: "jdbc", connection_string: "jdbc:mysql://db.example.com:9030/demo" }),
- "mysql",
- );
- assert.equal(
- inferJdbcDialect({ db_type: "jdbc", jdbc_driver_class: "org.apache.kyuubi.jdbc.KyuubiHiveDriver" }),
- "mysql",
- );
+ assert.equal(inferJdbcDialect({ db_type: "jdbc", connection_string: "jdbc:mysql://db.example.com:9030/demo" }), "mysql");
+ assert.equal(inferJdbcDialect({ db_type: "jdbc", jdbc_driver_class: "org.apache.kyuubi.jdbc.KyuubiHiveDriver" }), "mysql");
assert.equal(inferJdbcDialect({ db_type: "jdbc", jdbc_driver_class: "org.apache.hive.jdbc.HiveDriver" }), "hive");
assert.equal(inferJdbcDialect({ db_type: "jdbc", jdbc_driver_paths: ["/drivers/starrocks-jdbc.jar"] }), "starrocks");
- assert.equal(
- inferJdbcDialect({ db_type: "jdbc", connection_string: "jdbc:databend://db.example.com:8000/default" }),
- "databend",
- );
+ assert.equal(inferJdbcDialect({ db_type: "jdbc", connection_string: "jdbc:databend://db.example.com:8000/default" }), "databend");
});
test("effective database type keeps non-JDBC types and enables compatible JDBC structure editing", () => {
diff --git a/packages/app-tests/keyboardShortcuts.test.ts b/packages/app-tests/keyboardShortcuts.test.ts
index 126d6552d9..60f85aa089 100644
--- a/packages/app-tests/keyboardShortcuts.test.ts
+++ b/packages/app-tests/keyboardShortcuts.test.ts
@@ -60,10 +60,7 @@ test("matches Cmd+T for opening a new query", () => {
test("matches custom shortcut settings for opening a new query", () => {
assert.equal(isNewQueryShortcut({ key: "t", metaKey: true }, { newQuery: "Shift+Mod+N" } as any), false);
- assert.equal(
- isNewQueryShortcut({ key: "n", ctrlKey: true, shiftKey: true } as any, { newQuery: "Shift+Mod+N" } as any),
- true,
- );
+ assert.equal(isNewQueryShortcut({ key: "n", ctrlKey: true, shiftKey: true } as any, { newQuery: "Shift+Mod+N" } as any), true);
});
test("matches Mod+Comma for opening settings", () => {
@@ -75,9 +72,12 @@ test("matches Mod+Comma for opening settings", () => {
test("matches custom shortcut settings for opening settings", () => {
assert.equal(isOpenSettingsShortcut({ key: ",", metaKey: true }, { openSettings: "Shift+Mod+P" } as any), false);
assert.equal(
- isOpenSettingsShortcut({ key: "p", ctrlKey: true, shiftKey: true } as any, {
- openSettings: "Shift+Mod+P",
- } as any),
+ isOpenSettingsShortcut(
+ { key: "p", ctrlKey: true, shiftKey: true } as any,
+ {
+ openSettings: "Shift+Mod+P",
+ } as any,
+ ),
true,
);
});
@@ -118,10 +118,7 @@ test("matches configurable shortcut for toggling transpose view", () => {
test("matches custom shortcut settings for refreshing data", () => {
assert.equal(isRefreshDataShortcut({ key: "F5" }, { refreshData: "Shift+Mod+R" } as any), false);
- assert.equal(
- isRefreshDataShortcut({ key: "r", metaKey: true, shiftKey: true } as any, { refreshData: "Shift+Mod+R" } as any),
- true,
- );
+ assert.equal(isRefreshDataShortcut({ key: "r", metaKey: true, shiftKey: true } as any, { refreshData: "Shift+Mod+R" } as any), true);
});
test("detects browser reload shortcuts for desktop suppression", () => {
@@ -194,8 +191,7 @@ test("ignores Alt+S for saving", () => {
test("detects object source editor targets for contextual save", () => {
const target = {
- closest: (selector: string) =>
- selector === "[data-object-source-editor], [data-object-source-preview]" ? {} : null,
+ closest: (selector: string) => (selector === "[data-object-source-editor], [data-object-source-preview]" ? {} : null),
};
assert.equal(isObjectSourceSaveShortcutTarget(target), true);
diff --git a/packages/app-tests/mongoConnectionOptions.test.ts b/packages/app-tests/mongoConnectionOptions.test.ts
index ec428d1e9e..c2994c446b 100644
--- a/packages/app-tests/mongoConnectionOptions.test.ts
+++ b/packages/app-tests/mongoConnectionOptions.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- mongoUrlParam,
- setMongoUrlParam,
- mongodbAuthFailureHint,
-} from "../../apps/desktop/src/lib/mongoConnectionOptions.ts";
+import { mongoUrlParam, setMongoUrlParam, mongodbAuthFailureHint } from "../../apps/desktop/src/lib/mongoConnectionOptions.ts";
test("reads MongoDB authSource from URL params", () => {
assert.equal(mongoUrlParam("?replicaSet=rs0&authSource=admin", "authSource"), "admin");
@@ -19,8 +15,7 @@ test("removes empty MongoDB authSource from URL params", () => {
});
test("adds a MongoDB authSource hint for legacy authentication failures", () => {
- const message =
- "Agent RPC error: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='rwuser', source='gray_lite_twin_fat'}";
+ const message = "Agent RPC error: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='rwuser', source='gray_lite_twin_fat'}";
assert.equal(
mongodbAuthFailureHint(message),
@@ -35,8 +30,7 @@ test("adds a MongoDB URL encoding hint for reserved password characters", () =>
});
test("adds a MongoDB listDatabases permission hint", () => {
- const message =
- "Command failed with error 13 (Unauthorized): not authorized on admin to execute command { listDatabases: 1 }";
+ const message = "Command failed with error 13 (Unauthorized): not authorized on admin to execute command { listDatabases: 1 }";
assert.match(mongodbAuthFailureHint(message), /does not have permission to run listDatabases/);
});
diff --git a/packages/app-tests/mongoShellCommand.test.ts b/packages/app-tests/mongoShellCommand.test.ts
index d92201a061..5d8644544c 100644
--- a/packages/app-tests/mongoShellCommand.test.ts
+++ b/packages/app-tests/mongoShellCommand.test.ts
@@ -24,18 +24,13 @@ test("parseMongoFindCommand parses db collection find with an empty JSON filter"
});
test("parseMongoFindCommand parses getCollection find with chained sort skip and limit", () => {
- assert.deepEqual(
- parseMongoFindCommand(
- 'db.getCollection("audit.logs").find({"level":"warn"}).sort({"createdAt":-1}).skip(20).limit(10)',
- ),
- {
- collection: "audit.logs",
- filter: '{"level":"warn"}',
- skip: 20,
- limit: 10,
- sort: '{"createdAt":-1}',
- },
- );
+ assert.deepEqual(parseMongoFindCommand('db.getCollection("audit.logs").find({"level":"warn"}).sort({"createdAt":-1}).skip(20).limit(10)'), {
+ collection: "audit.logs",
+ filter: '{"level":"warn"}',
+ skip: 20,
+ limit: 10,
+ sort: '{"createdAt":-1}',
+ });
});
test("parseMongoFindCommand accepts Compass-style unquoted keys and ObjectId", () => {
@@ -65,16 +60,13 @@ test("parseMongoWriteCommand accepts unquoted insert and update commands", () =>
collection: "products",
docsJson: '{"name": "demo", "price": 1}',
});
- assert.deepEqual(
- parseMongoWriteCommand("db.products.updateOne({_id: ObjectId('507f1f77bcf86cd799439011')}, {$set: {stock: 3}})"),
- {
- kind: "update",
- collection: "products",
- filter: '{"_id": {"$oid":"507f1f77bcf86cd799439011"}}',
- update: '{"$set": {"stock": 3}}',
- many: false,
- },
- );
+ assert.deepEqual(parseMongoWriteCommand("db.products.updateOne({_id: ObjectId('507f1f77bcf86cd799439011')}, {$set: {stock: 3}})"), {
+ kind: "update",
+ collection: "products",
+ filter: '{"_id": {"$oid":"507f1f77bcf86cd799439011"}}',
+ update: '{"$set": {"stock": 3}}',
+ many: false,
+ });
});
test("parseMongoCountDocumentsCommand parses db collection countDocuments", () => {
@@ -85,13 +77,10 @@ test("parseMongoCountDocumentsCommand parses db collection countDocuments", () =
});
test("parseMongoAggregateCommand parses db collection aggregate", () => {
- assert.deepEqual(
- parseMongoAggregateCommand('db.products.aggregate([{"$match":{"active":true}},{"$count":"total"}])'),
- {
- collection: "products",
- pipeline: '[{"$match":{"active":true}},{"$count":"total"}]',
- },
- );
+ assert.deepEqual(parseMongoAggregateCommand('db.products.aggregate([{"$match":{"active":true}},{"$count":"total"}])'), {
+ collection: "products",
+ pipeline: '[{"$match":{"active":true}},{"$count":"total"}]',
+ });
});
test("parseMongoAggregateCommand accepts an empty pipeline", () => {
@@ -110,9 +99,7 @@ test("parseMongoAggregateCommand rejects non-array pipelines and extra arguments
test("parseMongoAggregateCommand normalises ObjectId arguments with either quote style", () => {
const oid = "507f1f77bcf86cd799439011";
for (const quote of ['"', "'"]) {
- const command = parseMongoAggregateCommand(
- `db.orders.aggregate([{"$match":{"_id":ObjectId(${quote}${oid}${quote})}}])`,
- );
+ const command = parseMongoAggregateCommand(`db.orders.aggregate([{"$match":{"_id":ObjectId(${quote}${oid}${quote})}}])`);
assert.ok(command, `quote=${quote} should parse`);
assert.equal(command.collection, "orders");
assert.deepEqual(JSON.parse(command.pipeline), [{ $match: { _id: { $oid: oid } } }]);
@@ -138,10 +125,7 @@ test("evaluateMongoAggregateSafety blocks write stages unless MCP write flags al
const merge = parseMongoAggregateCommand('db.products.aggregate([{"$merge":{"into":"products_copy"}}])');
assert.ok(merge);
assert.equal(mongoAggregateWriteStage(merge.pipeline), "$merge");
- assert.match(
- evaluateMongoAggregateSafety(merge, { allowWrites: true }).reason || "",
- /DBX_MCP_ALLOW_DANGEROUS_SQL=1/,
- );
+ assert.match(evaluateMongoAggregateSafety(merge, { allowWrites: true }).reason || "", /DBX_MCP_ALLOW_DANGEROUS_SQL=1/);
assert.equal(evaluateMongoAggregateSafety(merge, { allowWrites: true, allowDangerous: true }).allowed, true);
});
diff --git a/packages/app-tests/objectBrowserRows.test.ts b/packages/app-tests/objectBrowserRows.test.ts
index 55d003dc2b..f9a754ae4d 100644
--- a/packages/app-tests/objectBrowserRows.test.ts
+++ b/packages/app-tests/objectBrowserRows.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildObjectBrowserRows,
- filterObjectBrowserRows,
- formatObjectBrowserTimestamp,
- sortObjectBrowserRows,
-} from "../../apps/desktop/src/lib/objectBrowserRows.ts";
+import { buildObjectBrowserRows, filterObjectBrowserRows, formatObjectBrowserTimestamp, sortObjectBrowserRows } from "../../apps/desktop/src/lib/objectBrowserRows.ts";
test("builds unique row ids for overloaded routines with the same visible name", () => {
const rows = buildObjectBrowserRows({
diff --git a/packages/app-tests/openTabsPersistence.test.ts b/packages/app-tests/openTabsPersistence.test.ts
index 1a8f722a2e..1bf7c6cbd6 100644
--- a/packages/app-tests/openTabsPersistence.test.ts
+++ b/packages/app-tests/openTabsPersistence.test.ts
@@ -143,10 +143,7 @@ test("ignores legacy table data result cache handles on restore", () => {
});
test("restores unsaved query tabs and active tab after restart", () => {
- const raw = JSON.stringify([
- queryTab({ id: "tab-1", sql: "select 1" }),
- queryTab({ id: "tab-2", title: "Query 2", sql: "select 2" }),
- ]);
+ const raw = JSON.stringify([queryTab({ id: "tab-1", sql: "select 1" }), queryTab({ id: "tab-2", title: "Query 2", sql: "select 2" })]);
const restored = restoreOpenTabsState(raw, "tab-2");
diff --git a/packages/app-tests/pinnedItems.test.ts b/packages/app-tests/pinnedItems.test.ts
index 05a216e3f8..199199342d 100644
--- a/packages/app-tests/pinnedItems.test.ts
+++ b/packages/app-tests/pinnedItems.test.ts
@@ -4,18 +4,18 @@ import { applyPinnedTreeNodeState, orderPinnedFirst } from "../../apps/desktop/s
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
test("orders pinned items before unpinned items without changing relative order", () => {
- const items = [
- { id: "a" },
- { id: "b", pinned: true },
- { id: "c" },
- { id: "d", pinned: true },
- { id: "e" },
- ];
+ const items = [{ id: "a" }, { id: "b", pinned: true }, { id: "c" }, { id: "d", pinned: true }, { id: "e" }];
const ordered = orderPinnedFirst(items, (item) => !!item.pinned);
- assert.deepEqual(ordered.map((item) => item.id), ["b", "d", "a", "c", "e"]);
- assert.deepEqual(items.map((item) => item.id), ["a", "b", "c", "d", "e"]);
+ assert.deepEqual(
+ ordered.map((item) => item.id),
+ ["b", "d", "a", "c", "e"],
+ );
+ assert.deepEqual(
+ items.map((item) => item.id),
+ ["a", "b", "c", "d", "e"],
+ );
});
test("applies pinned state recursively to grouped tree nodes", () => {
diff --git a/packages/app-tests/pinnedTreeNodeIds.test.ts b/packages/app-tests/pinnedTreeNodeIds.test.ts
index 4515c03354..4cc147d2c8 100644
--- a/packages/app-tests/pinnedTreeNodeIds.test.ts
+++ b/packages/app-tests/pinnedTreeNodeIds.test.ts
@@ -9,4 +9,3 @@ test("prunePinnedTreeNodeIdsForConnection removes pinned ids for a deleted conne
assert.deepEqual([...next], ["conn-10:db:main", "other"]);
});
-
diff --git a/packages/app-tests/queryStore.test.ts b/packages/app-tests/queryStore.test.ts
index f68cee19a8..4f13b8998d 100644
--- a/packages/app-tests/queryStore.test.ts
+++ b/packages/app-tests/queryStore.test.ts
@@ -747,13 +747,10 @@ test("grid refreshes can preserve the previous result while loading", async () =
});
}
if (url === "/api/query/execute-multi") {
- return new Response(
- JSON.stringify([{ columns: ["id", "name"], rows: [[2, "Grace"]], affected_rows: 0, execution_time_ms: 1 }]),
- {
- status: 200,
- headers: { "Content-Type": "application/json" },
- },
- );
+ return new Response(JSON.stringify([{ columns: ["id", "name"], rows: [[2, "Grace"]], affected_rows: 0, execution_time_ms: 1 }]), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
}
if (url === "/api/query/analyze-editability") {
return new Response(JSON.stringify({ editable: false, reason: "complex-source" }), {
@@ -801,13 +798,10 @@ test("data tab execution preserves pagination offset metadata", async () => {
}
if (url === "/api/query/execute-multi") {
executeBody = JSON.parse(String(init?.body ?? "{}"));
- return new Response(
- JSON.stringify([{ columns: ["id"], rows: [[101]], affected_rows: 0, execution_time_ms: 1 }]),
- {
- status: 200,
- headers: { "Content-Type": "application/json" },
- },
- );
+ return new Response(JSON.stringify([{ columns: ["id"], rows: [[101]], affected_rows: 0, execution_time_ms: 1 }]), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
}
return new Response("unexpected request", { status: 500 });
}) as typeof fetch;
@@ -921,9 +915,7 @@ test("query result export fetches every paginated page", async () => {
const body = JSON.parse(String(init?.body ?? "{}"));
executedSqls.push(body.sql);
timeoutSecs.push(body.timeoutSecs);
- const rows = String(body.sql).includes("offset:0")
- ? Array.from({ length: 10_000 }, (_, index) => [index + 1])
- : [[10_001], [10_002]];
+ const rows = String(body.sql).includes("offset:0") ? Array.from({ length: 10_000 }, (_, index) => [index + 1]) : [[10_001], [10_002]];
return new Response(JSON.stringify([{ columns: ["id"], rows, affected_rows: 0, execution_time_ms: 1 }]), {
status: 200,
headers: { "Content-Type": "application/json" },
@@ -999,17 +991,17 @@ test("table data export fetches every filtered page", async () => {
const body = JSON.parse(String(init?.body ?? "{}"));
buildRequests.push(body.options);
const { limit, offset } = body.options;
- return new Response(
- JSON.stringify(`SELECT * FROM "public"."users" WHERE (status = 'active') ORDER BY "id" DESC LIMIT ${limit} OFFSET ${offset ?? 0};`),
- { status: 200, headers: { "Content-Type": "application/json" } },
- );
+ return new Response(JSON.stringify(`SELECT * FROM "public"."users" WHERE (status = 'active') ORDER BY "id" DESC LIMIT ${limit} OFFSET ${offset ?? 0};`), { status: 200, headers: { "Content-Type": "application/json" } });
}
if (url === "/api/query/execute-multi") {
const body = JSON.parse(String(init?.body ?? "{}"));
executedSqls.push(body.sql);
const rows = String(body.sql).includes("OFFSET 0")
? Array.from({ length: 10_000 }, (_, index) => [index + 1, "active"])
- : [[10_001, "active"], [10_002, "active"]];
+ : [
+ [10_001, "active"],
+ [10_002, "active"],
+ ];
return new Response(JSON.stringify([{ columns: ["id", "status"], rows, affected_rows: 0, execution_time_ms: 1 }]), {
status: 200,
headers: { "Content-Type": "application/json" },
@@ -1052,10 +1044,7 @@ test("table data export fetches every filtered page", async () => {
},
],
);
- assert.deepEqual(executedSqls, [
- 'SELECT * FROM "public"."users" WHERE (status = \'active\') ORDER BY "id" DESC LIMIT 10000 OFFSET 0;',
- 'SELECT * FROM "public"."users" WHERE (status = \'active\') ORDER BY "id" DESC LIMIT 10000 OFFSET 10000;',
- ]);
+ assert.deepEqual(executedSqls, ['SELECT * FROM "public"."users" WHERE (status = \'active\') ORDER BY "id" DESC LIMIT 10000 OFFSET 0;', 'SELECT * FROM "public"."users" WHERE (status = \'active\') ORDER BY "id" DESC LIMIT 10000 OFFSET 10000;']);
assert.equal(exported?.rows.length, 10_002);
assert.deepEqual(exported?.rows.at(-1), [10_002, "active"]);
} finally {
@@ -1380,7 +1369,10 @@ test("multi statement execution shows the first result set by default", async ()
assert.deepEqual(tab?.result?.rows, [[1]]);
assert.equal(isReactive(tab?.result?.rows), false);
assert.equal(isReactive(tab?.result?.rows[0]), false);
- assert.equal(tab?.results?.every((result) => !isReactive(result.rows)), true);
+ assert.equal(
+ tab?.results?.every((result) => !isReactive(result.rows)),
+ true,
+ );
} finally {
globalThis.fetch = originalFetch;
restoreStorage();
diff --git a/packages/app-tests/redisCommandSession.test.ts b/packages/app-tests/redisCommandSession.test.ts
index 9bcd19ab01..225cf2f0a2 100644
--- a/packages/app-tests/redisCommandSession.test.ts
+++ b/packages/app-tests/redisCommandSession.test.ts
@@ -1,10 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- isRedisClearScreenCommand,
- nextRedisCommandDb,
- redisKeyTextToRaw,
-} from "../../apps/desktop/src/lib/redisCommandSession.ts";
+import { isRedisClearScreenCommand, nextRedisCommandDb, redisKeyTextToRaw } from "../../apps/desktop/src/lib/redisCommandSession.ts";
test("keeps Redis command session database after SELECT succeeds", () => {
assert.equal(nextRedisCommandDb(3, "SELECT 0", "OK"), 0);
diff --git a/packages/app-tests/redisKeyTree.test.ts b/packages/app-tests/redisKeyTree.test.ts
index 857beecc7a..b298d6652b 100644
--- a/packages/app-tests/redisKeyTree.test.ts
+++ b/packages/app-tests/redisKeyTree.test.ts
@@ -1,13 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import {
- buildRedisKeyTree,
- collectRedisGroupKeyRaws,
- collectExpandedGroupIds,
- flattenVisibleRedisKeyTree,
- mergeKeysIntoRedisKeyTree,
- type RedisKeyTreeNode,
-} from "../../apps/desktop/src/lib/redisKeyTree.ts";
+import { buildRedisKeyTree, collectRedisGroupKeyRaws, collectExpandedGroupIds, flattenVisibleRedisKeyTree, mergeKeysIntoRedisKeyTree, type RedisKeyTreeNode } from "../../apps/desktop/src/lib/redisKeyTree.ts";
import type { RedisKeyInfo } from "../../apps/desktop/src/lib/api.ts";
function makeKey(key_display: string, key_raw: string, key_type = "string", ttl = -1): RedisKeyInfo {
@@ -19,10 +12,7 @@ function leafLabels(nodes: RedisKeyTreeNode[]): string[] {
}
test("buildRedisKeyTree groups colon-delimited keys by segment", () => {
- const tree = buildRedisKeyTree(
- [makeKey("a:b:c", "k1"), makeKey("a:b:d", "k2"), makeKey("a:e", "k3"), makeKey("x", "k4")],
- 0,
- );
+ const tree = buildRedisKeyTree([makeKey("a:b:c", "k1"), makeKey("a:b:d", "k2"), makeKey("a:e", "k3"), makeKey("x", "k4")], 0);
assert.equal(tree.length, 2);
assert.equal(tree[0]?.kind, "group");
@@ -79,15 +69,7 @@ test("collectExpandedGroupIds and flattenVisibleRedisKeyTree expand all search p
});
test("collectRedisGroupKeyRaws returns every leaf key under a group", () => {
- const tree = buildRedisKeyTree(
- [
- makeKey("user:profile:name", "k1"),
- makeKey("user:profile:email", "k2"),
- makeKey("user:settings", "k3"),
- makeKey("session:1", "k4"),
- ],
- 0,
- );
+ const tree = buildRedisKeyTree([makeKey("user:profile:name", "k1"), makeKey("user:profile:email", "k2"), makeKey("user:settings", "k3"), makeKey("session:1", "k4")], 0);
const userGroup = tree.find((node) => node.kind === "group" && node.label === "user");
assert.ok(userGroup);
@@ -171,8 +153,7 @@ test("mergeKeysIntoRedisKeyTree into empty tree falls back to full build", () =>
const merged = mergeKeysIntoRedisKeyTree([], [makeKey("a:b:c", "k1"), makeKey("x", "k2")], 0);
const full = buildRedisKeyTree([makeKey("a:b:c", "k1"), makeKey("x", "k2")], 0);
- const toStr = (nodes: RedisKeyTreeNode[]): string =>
- JSON.stringify(nodes.map((node) => node.label));
+ const toStr = (nodes: RedisKeyTreeNode[]): string => JSON.stringify(nodes.map((node) => node.label));
assert.equal(toStr(merged), toStr(full));
});
diff --git a/packages/app-tests/redisValuePresentation.test.ts b/packages/app-tests/redisValuePresentation.test.ts
index 8594e608b7..231214905d 100644
--- a/packages/app-tests/redisValuePresentation.test.ts
+++ b/packages/app-tests/redisValuePresentation.test.ts
@@ -1,15 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- canEditRedisMemberDetail,
- clampRedisMemberDetailSheetWidth,
- formatRedisCommandResult,
- formatRedisMemberDetail,
- formatRedisStringValue,
- getRedisMemberSelectionKey,
- highlightRedisJsonDetail,
- parseRedisJsonDetail,
-} from "../../apps/desktop/src/lib/redisValuePresentation.ts";
+import { canEditRedisMemberDetail, clampRedisMemberDetailSheetWidth, formatRedisCommandResult, formatRedisMemberDetail, formatRedisStringValue, getRedisMemberSelectionKey, highlightRedisJsonDetail, parseRedisJsonDetail } from "../../apps/desktop/src/lib/redisValuePresentation.ts";
test("formats JSON object strings for Redis member details", () => {
const detail = formatRedisMemberDetail('{"id":1,"name":"Ada","tags":["dbx","redis"]}');
diff --git a/packages/app-tests/routineExecutionSql.test.ts b/packages/app-tests/routineExecutionSql.test.ts
index ee35b8aff9..927885d111 100644
--- a/packages/app-tests/routineExecutionSql.test.ts
+++ b/packages/app-tests/routineExecutionSql.test.ts
@@ -1,28 +1,13 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildProcedureExecutionSql,
- buildProcedureExecutionSqlFromValues,
-} from "../../apps/desktop/src/lib/routineExecutionSql.ts";
+import { buildProcedureExecutionSql, buildProcedureExecutionSqlFromValues } from "../../apps/desktop/src/lib/routineExecutionSql.ts";
import { routineParametersFromResult, routineParametersQuery } from "../../apps/desktop/src/lib/routineParameters.ts";
test("builds procedure execution templates for common dialect families", () => {
- assert.equal(
- buildProcedureExecutionSql({ databaseType: "postgres", schema: "public", routineName: "refresh_stats" }),
- 'CALL "public"."refresh_stats"();',
- );
- assert.equal(
- buildProcedureExecutionSql({ databaseType: "mysql", schema: "app", routineName: "refresh_stats" }),
- "CALL `refresh_stats`();",
- );
- assert.equal(
- buildProcedureExecutionSql({ databaseType: "sqlserver", schema: "dbo", routineName: "refresh_stats" }),
- "EXEC [dbo].[refresh_stats];",
- );
- assert.equal(
- buildProcedureExecutionSql({ databaseType: "dameng", schema: "SYSDBA", routineName: "refresh_stats" }),
- 'BEGIN\n "SYSDBA"."refresh_stats"();\nEND;',
- );
+ assert.equal(buildProcedureExecutionSql({ databaseType: "postgres", schema: "public", routineName: "refresh_stats" }), 'CALL "public"."refresh_stats"();');
+ assert.equal(buildProcedureExecutionSql({ databaseType: "mysql", schema: "app", routineName: "refresh_stats" }), "CALL `refresh_stats`();");
+ assert.equal(buildProcedureExecutionSql({ databaseType: "sqlserver", schema: "dbo", routineName: "refresh_stats" }), "EXEC [dbo].[refresh_stats];");
+ assert.equal(buildProcedureExecutionSql({ databaseType: "dameng", schema: "SYSDBA", routineName: "refresh_stats" }), 'BEGIN\n "SYSDBA"."refresh_stats"();\nEND;');
});
test("builds procedure execution templates from parameter values", () => {
@@ -138,24 +123,9 @@ test("maps routine parameter query results into form metadata", () => {
});
test("builds parameter metadata queries for supported dialects", () => {
- assert.match(
- routineParametersQuery({ database: "app", databaseType: "postgres", schema: "public", routineName: "demo" }) ?? "",
- /pg_proc/,
- );
- assert.match(
- routineParametersQuery({ database: "app", databaseType: "sqlserver", schema: "dbo", routineName: "demo" }) ?? "",
- /sys\.parameters/,
- );
- assert.match(
- routineParametersQuery({ database: "app", databaseType: "mysql", routineName: "demo" }) ?? "",
- /SPECIFIC_SCHEMA = 'app'/,
- );
- assert.match(
- routineParametersQuery({ database: "app", databaseType: "postgres", routineName: "demo" }) ?? "",
- /n\.nspname = 'public'/,
- );
- assert.equal(
- routineParametersQuery({ database: "app", databaseType: "sqlite", schema: "main", routineName: "demo" }),
- null,
- );
+ assert.match(routineParametersQuery({ database: "app", databaseType: "postgres", schema: "public", routineName: "demo" }) ?? "", /pg_proc/);
+ assert.match(routineParametersQuery({ database: "app", databaseType: "sqlserver", schema: "dbo", routineName: "demo" }) ?? "", /sys\.parameters/);
+ assert.match(routineParametersQuery({ database: "app", databaseType: "mysql", routineName: "demo" }) ?? "", /SPECIFIC_SCHEMA = 'app'/);
+ assert.match(routineParametersQuery({ database: "app", databaseType: "postgres", routineName: "demo" }) ?? "", /n\.nspname = 'public'/);
+ assert.equal(routineParametersQuery({ database: "app", databaseType: "sqlite", schema: "main", routineName: "demo" }), null);
});
diff --git a/packages/app-tests/schemaTreeCache.test.ts b/packages/app-tests/schemaTreeCache.test.ts
index 70f520d874..8ff85a0d5e 100644
--- a/packages/app-tests/schemaTreeCache.test.ts
+++ b/packages/app-tests/schemaTreeCache.test.ts
@@ -1,10 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- SCHEMA_TREE_CACHE_TTL_MS,
- decodeSchemaTreeCache,
- encodeSchemaTreeCache,
-} from "../../apps/desktop/src/lib/schemaTreeCache.ts";
+import { SCHEMA_TREE_CACHE_TTL_MS, decodeSchemaTreeCache, encodeSchemaTreeCache } from "../../apps/desktop/src/lib/schemaTreeCache.ts";
const children = [{ id: "conn:db", label: "db", type: "database" }];
const now = Date.parse("2026-05-17T10:00:00.000Z");
diff --git a/packages/app-tests/settingsStore.test.ts b/packages/app-tests/settingsStore.test.ts
index d75de82113..eb8df0b288 100644
--- a/packages/app-tests/settingsStore.test.ts
+++ b/packages/app-tests/settingsStore.test.ts
@@ -2,13 +2,7 @@ import { test } from "vitest";
import assert from "node:assert/strict";
import { createPinia, setActivePinia } from "pinia";
import { DEFAULT_SQL_FORMATTER_SETTINGS } from "../../apps/desktop/src/lib/sqlFormatterConfig.ts";
-import {
- AI_PROVIDER_PRESETS,
- DEFAULT_EDITOR_SETTINGS,
- normalizeAiConfig,
- normalizeEditorSettings,
- useSettingsStore,
-} from "../../apps/desktop/src/stores/settingsStore.ts";
+import { AI_PROVIDER_PRESETS, DEFAULT_EDITOR_SETTINGS, normalizeAiConfig, normalizeEditorSettings, useSettingsStore } from "../../apps/desktop/src/stores/settingsStore.ts";
const OLD_FONT_SIZE_KEY = "dbx-query-editor-font-size";
@@ -167,10 +161,7 @@ test("normalizes table structure editor density", () => {
assert.equal(DEFAULT_EDITOR_SETTINGS.structureEditorDensity, "compact");
assert.equal(normalizeEditorSettings({}).structureEditorDensity, "compact");
assert.equal(normalizeEditorSettings({ structureEditorDensity: "standard" }).structureEditorDensity, "standard");
- assert.equal(
- normalizeEditorSettings({ structureEditorDensity: "comfortable" }).structureEditorDensity,
- "comfortable",
- );
+ assert.equal(normalizeEditorSettings({ structureEditorDensity: "comfortable" }).structureEditorDensity, "comfortable");
assert.equal(normalizeEditorSettings({ structureEditorDensity: "invalid" as any }).structureEditorDensity, "compact");
});
@@ -194,10 +185,7 @@ test("keeps saved active tab sidebar selection", () => {
});
test("keeps saved sidebar horizontal scroll preference", () => {
- assert.equal(
- normalizeEditorSettings({ sidebarAllowHorizontalScroll: true } as any).sidebarAllowHorizontalScroll,
- true,
- );
+ assert.equal(normalizeEditorSettings({ sidebarAllowHorizontalScroll: true } as any).sidebarAllowHorizontalScroll, true);
});
test("keeps saved sidebar activation", () => {
@@ -207,11 +195,7 @@ test("keeps saved sidebar activation", () => {
test("normalizes saved sidebar hidden table prefixes", () => {
assert.deepEqual(DEFAULT_EDITOR_SETTINGS.sidebarHiddenTablePrefixes, []);
- assert.deepEqual(
- normalizeEditorSettings({ sidebarHiddenTablePrefixes: [" app_", "app_", "", "ods."] } as any)
- .sidebarHiddenTablePrefixes,
- ["app_", "ods."],
- );
+ assert.deepEqual(normalizeEditorSettings({ sidebarHiddenTablePrefixes: [" app_", "app_", "", "ods."] } as any).sidebarHiddenTablePrefixes, ["app_", "ods."]);
});
test("defaults column formatters to an empty record", () => {
diff --git a/packages/app-tests/sidebarActiveTabTarget.test.ts b/packages/app-tests/sidebarActiveTabTarget.test.ts
index 9efdd76eb2..96affee88c 100644
--- a/packages/app-tests/sidebarActiveTabTarget.test.ts
+++ b/packages/app-tests/sidebarActiveTabTarget.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- activeTabSidebarTarget,
- findSidebarNodeForActiveTab,
- scrollTopForSidebarNode,
- shouldScrollActiveSidebarSelection,
-} from "../../apps/desktop/src/lib/sidebarActiveTabTarget.ts";
+import { activeTabSidebarTarget, findSidebarNodeForActiveTab, scrollTopForSidebarNode, shouldScrollActiveSidebarSelection } from "../../apps/desktop/src/lib/sidebarActiveTabTarget.ts";
import type { FlatTreeNode } from "../../apps/desktop/src/composables/useFlatTree.ts";
import type { QueryTab, TreeNode } from "../../apps/desktop/src/types/database.ts";
diff --git a/packages/app-tests/sidebarLayout.test.ts b/packages/app-tests/sidebarLayout.test.ts
index 1b71525c51..2f37ca3b99 100644
--- a/packages/app-tests/sidebarLayout.test.ts
+++ b/packages/app-tests/sidebarLayout.test.ts
@@ -1,18 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import {
- reconcileLayout,
- buildTreeNodesFromLayout,
- createGroup,
- deleteGroup,
- renameGroup,
- moveConnectionToGroup,
- reorderEntry,
- toggleGroupCollapsed,
- appendConnectionToLayout,
- removeConnectionFromSidebarLayout,
- emptyLayout,
-} from "../../apps/desktop/src/lib/sidebarLayout.ts";
+import { reconcileLayout, buildTreeNodesFromLayout, createGroup, deleteGroup, renameGroup, moveConnectionToGroup, reorderEntry, toggleGroupCollapsed, appendConnectionToLayout, removeConnectionFromSidebarLayout, emptyLayout } from "../../apps/desktop/src/lib/sidebarLayout.ts";
import type { ConnectionConfig, SidebarLayout } from "../../apps/desktop/src/types/database.ts";
function conn(id: string, name?: string): ConnectionConfig {
@@ -199,7 +187,10 @@ test("reorderEntry moves connection before another", () => {
],
};
const result = reorderEntry(layout, "c", "a", "before");
- assert.deepEqual(result.order.map((e) => e.id), ["c", "a", "b"]);
+ assert.deepEqual(
+ result.order.map((e) => e.id),
+ ["c", "a", "b"],
+ );
});
test("reorderEntry moves connection after another", () => {
@@ -212,7 +203,10 @@ test("reorderEntry moves connection after another", () => {
],
};
const result = reorderEntry(layout, "a", "b", "after");
- assert.deepEqual(result.order.map((e) => e.id), ["b", "a", "c"]);
+ assert.deepEqual(
+ result.order.map((e) => e.id),
+ ["b", "a", "c"],
+ );
});
test("reorderEntry moves connection inside a group", () => {
diff --git a/packages/app-tests/sidebarRenameFocus.test.ts b/packages/app-tests/sidebarRenameFocus.test.ts
index 745419ecf6..655eb31992 100644
--- a/packages/app-tests/sidebarRenameFocus.test.ts
+++ b/packages/app-tests/sidebarRenameFocus.test.ts
@@ -1,9 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import {
- focusSidebarRenameInput,
- shouldPreventRenameCloseAutoFocus,
-} from "../../apps/desktop/src/lib/sidebarRenameFocus.ts";
+import { focusSidebarRenameInput, shouldPreventRenameCloseAutoFocus } from "../../apps/desktop/src/lib/sidebarRenameFocus.ts";
test("focusSidebarRenameInput waits for menu focus restoration before focusing", () => {
const calls: string[] = [];
diff --git a/packages/app-tests/sidebarSearchTree.test.ts b/packages/app-tests/sidebarSearchTree.test.ts
index 8a064bc475..2b909fe189 100644
--- a/packages/app-tests/sidebarSearchTree.test.ts
+++ b/packages/app-tests/sidebarSearchTree.test.ts
@@ -1,9 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- filterSidebarSearchRootsByConnectionState,
- filterSidebarTree,
-} from "../../apps/desktop/src/lib/sidebarSearchTree.ts";
+import { filterSidebarSearchRootsByConnectionState, filterSidebarTree } from "../../apps/desktop/src/lib/sidebarSearchTree.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
test("preserves loaded table children when the table itself matches search", () => {
diff --git a/packages/app-tests/sidebarTableNameDisplay.test.ts b/packages/app-tests/sidebarTableNameDisplay.test.ts
index 9402d81ae6..8475f29eee 100644
--- a/packages/app-tests/sidebarTableNameDisplay.test.ts
+++ b/packages/app-tests/sidebarTableNameDisplay.test.ts
@@ -1,9 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import {
- normalizeSidebarHiddenTablePrefixes,
- sidebarDisplayTableName,
-} from "../../apps/desktop/src/lib/sidebarTableNameDisplay.ts";
+import { normalizeSidebarHiddenTablePrefixes, sidebarDisplayTableName } from "../../apps/desktop/src/lib/sidebarTableNameDisplay.ts";
test("normalizes sidebar hidden table prefixes", () => {
assert.deepEqual(normalizeSidebarHiddenTablePrefixes([" app_", "app_", "", "ods."]), ["app_", "ods."]);
diff --git a/packages/app-tests/sidebarTreeItemLayout.test.ts b/packages/app-tests/sidebarTreeItemLayout.test.ts
index a34855cb83..bb7fd024c7 100644
--- a/packages/app-tests/sidebarTreeItemLayout.test.ts
+++ b/packages/app-tests/sidebarTreeItemLayout.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- canTreeNodeExpand,
- canTreeNodeShowExpander,
- treeItemPaddingLeft,
- usesFullWidthTreeLabel,
-} from "../../apps/desktop/src/lib/sidebarTreeItemLayout.ts";
+import { canTreeNodeExpand, canTreeNodeShowExpander, treeItemPaddingLeft, usesFullWidthTreeLabel } from "../../apps/desktop/src/lib/sidebarTreeItemLayout.ts";
test("treeItemPaddingLeft converts tree depth to sidebar indentation", () => {
assert.equal(treeItemPaddingLeft(0), "8px");
diff --git a/packages/app-tests/sidebarTreeSelection.test.ts b/packages/app-tests/sidebarTreeSelection.test.ts
index dfca11194c..2e4b57840c 100644
--- a/packages/app-tests/sidebarTreeSelection.test.ts
+++ b/packages/app-tests/sidebarTreeSelection.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- selectedTreeNodesInVisibleOrder,
- treeSelectionRangeIdsByIndex,
- treeSelectionRangeIds,
-} from "../../apps/desktop/src/lib/sidebarTreeSelection.ts";
+import { selectedTreeNodesInVisibleOrder, treeSelectionRangeIdsByIndex, treeSelectionRangeIds } from "../../apps/desktop/src/lib/sidebarTreeSelection.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
const nodes: TreeNode[] = [
diff --git a/packages/app-tests/sqlAnalysis.test.ts b/packages/app-tests/sqlAnalysis.test.ts
index a012d10bf9..dff010ff3d 100644
--- a/packages/app-tests/sqlAnalysis.test.ts
+++ b/packages/app-tests/sqlAnalysis.test.ts
@@ -1,13 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- allEditableColumnsWriteable,
- allPrimaryKeysPresent,
- analyzeEditableQuery,
- analyzeEditableQueryEditability,
- isBinaryType,
- queryEditabilityMessageKey,
-} from "../../apps/desktop/src/lib/sqlAnalysis.ts";
+import { allEditableColumnsWriteable, allPrimaryKeysPresent, analyzeEditableQuery, analyzeEditableQueryEditability, isBinaryType, queryEditabilityMessageKey } from "../../apps/desktop/src/lib/sqlAnalysis.ts";
test("recognizes a simple single-table SELECT as editable", () => {
const result = analyzeEditableQueryEditability("select id, name from public.users where active = true order by id");
@@ -87,9 +80,7 @@ test("reports computed result columns as unsafe to edit", () => {
});
test("keeps single-table expression columns while mapping writable source columns", () => {
- const result = analyzeEditableQueryEditability(
- "select iso3, year, country_name, ihli / gdp_pc as score from ihli_data",
- );
+ const result = analyzeEditableQueryEditability("select iso3, year, country_name, ihli / gdp_pc as score from ihli_data");
assert.equal(result.editable, true);
assert.deepEqual(result.analysis.columns, [
@@ -98,10 +89,7 @@ test("keeps single-table expression columns while mapping writable source column
{ sourceName: "country_name", sourceNameQuoted: false, resultName: "country_name", expression: "country_name" },
{ sourceName: undefined, sourceNameQuoted: false, resultName: "score", expression: "ihli / gdp_pc" },
]);
- assert.equal(
- allPrimaryKeysPresent(["iso3", "year"], ["iso3", "year", "country_name", "score"], result.analysis),
- true,
- );
+ assert.equal(allPrimaryKeysPresent(["iso3", "year"], ["iso3", "year", "country_name", "score"], result.analysis), true);
assert.equal(allEditableColumnsWriteable(result.analysis, ["iso3", "year", "country_name", "score"]), true);
});
@@ -111,10 +99,7 @@ test("accepts aliased primary key source columns for row identity", () => {
assert.ok(analysis);
assert.equal(allPrimaryKeysPresent(["id"], ["user_id", "name"], analysis), true);
assert.equal(allEditableColumnsWriteable(analysis, ["user_id", "name"]), true);
- assert.equal(
- allPrimaryKeysPresent(["id"], ["id", "name"], analyzeEditableQuery("select id, name from users")!),
- true,
- );
+ assert.equal(allPrimaryKeysPresent(["id"], ["id", "name"], analyzeEditableQuery("select id, name from users")!), true);
});
test("recognizes binary type declarations with lengths", () => {
diff --git a/packages/app-tests/sqlCompletion.test.ts b/packages/app-tests/sqlCompletion.test.ts
index bd8e74cfd2..a6c4af88da 100644
--- a/packages/app-tests/sqlCompletion.test.ts
+++ b/packages/app-tests/sqlCompletion.test.ts
@@ -78,15 +78,11 @@ test("suggests SQL keywords for generic keyword input", () => {
});
test("suggests PostgreSQL-specific data types and functions", () => {
- const typeItems = buildSqlCompletionItems(
- "create table events (payload js",
- "create table events (payload js".length,
- {
- tables: [],
- columnsByTable: new Map(),
- databaseType: "postgres",
- },
- );
+ const typeItems = buildSqlCompletionItems("create table events (payload js", "create table events (payload js".length, {
+ tables: [],
+ columnsByTable: new Map(),
+ databaseType: "postgres",
+ });
const serialItems = buildSqlCompletionItems("create table events (id ser", "create table events (id ser".length, {
tables: [],
columnsByTable: new Map(),
@@ -756,18 +752,14 @@ test("extracts CTE explicit column list", () => {
});
test("extracts multiple CTEs", () => {
- const ctes = extractCteDefinitions(
- "WITH first AS (SELECT id FROM users), second AS (SELECT id FROM orders) SELECT * FROM first JOIN second",
- );
+ const ctes = extractCteDefinitions("WITH first AS (SELECT id FROM users), second AS (SELECT id FROM orders) SELECT * FROM first JOIN second");
assert.equal(ctes.length, 2);
assert.equal(ctes[0]?.name, "first");
assert.equal(ctes[1]?.name, "second");
});
test("handles WITH RECURSIVE", () => {
- const ctes = extractCteDefinitions(
- "WITH RECURSIVE tree AS (SELECT id, parent_id FROM categories UNION ALL SELECT c.id, c.parent_id FROM categories c JOIN tree t ON c.parent_id = t.id) SELECT * FROM tree",
- );
+ const ctes = extractCteDefinitions("WITH RECURSIVE tree AS (SELECT id, parent_id FROM categories UNION ALL SELECT c.id, c.parent_id FROM categories c JOIN tree t ON c.parent_id = t.id) SELECT * FROM tree");
assert.equal(ctes.length, 1);
assert.equal(ctes[0]?.name, "tree");
});
@@ -811,14 +803,10 @@ test("suggests columns for INSERT INTO target table", () => {
// --- Column data type in detail ---
test("shows column data type in detail", () => {
- const items = buildSqlCompletionItems(
- "select id from public.users u where u.",
- "select id from public.users u where u.".length,
- {
- tables,
- columnsByTable,
- },
- );
+ const items = buildSqlCompletionItems("select id from public.users u where u.", "select id from public.users u where u.".length, {
+ tables,
+ columnsByTable,
+ });
const emailColumn = items.find((item) => item.label === "email");
assert.ok(emailColumn);
assert.ok(emailColumn.detail!.includes("[varchar]"));
@@ -1101,12 +1089,7 @@ test("getSqlCompletionContext returns nonAggregatedSelectColumns", () => {
// --- Better FK join inference ---
test("prefers explicit foreign-key join condition with table aliases", () => {
- const foreignKeysByTable = new Map<string, SqlCompletionForeignKey[]>([
- [
- "public.orders",
- [{ name: "orders_customer_id_fkey", column: "customer_id", ref_table: "customers", ref_column: "id" }],
- ],
- ]);
+ const foreignKeysByTable = new Map<string, SqlCompletionForeignKey[]>([["public.orders", [{ name: "orders_customer_id_fkey", column: "customer_id", ref_table: "customers", ref_column: "id" }]]]);
const sql = "select * from public.orders o join public.customers c on ";
const items = buildSqlCompletionItems(sql, sql.length, {
tables: [
@@ -1127,12 +1110,7 @@ test("prefers explicit foreign-key join condition with table aliases", () => {
});
test("suggests explicit foreign-key join when the joined table owns the key", () => {
- const foreignKeysByTable = new Map<string, SqlCompletionForeignKey[]>([
- [
- "public.orders",
- [{ name: "orders_customer_id_fkey", column: "customer_id", ref_table: "customers", ref_column: "id" }],
- ],
- ]);
+ const foreignKeysByTable = new Map<string, SqlCompletionForeignKey[]>([["public.orders", [{ name: "orders_customer_id_fkey", column: "customer_id", ref_table: "customers", ref_column: "id" }]]]);
const sql = "select * from public.customers c join public.orders o on ";
const items = buildSqlCompletionItems(sql, sql.length, {
tables: [
@@ -1334,9 +1312,7 @@ test("suggests join condition for parent_id self-reference", () => {
tables: [{ name: "categories", schema: "public", type: "table" }],
columnsByTable: colsWithParent,
});
- const parentJoin = items.find(
- (item) => item.label === "c1.parent_id = c2.id" || item.label === "c2.parent_id = c1.id",
- );
+ const parentJoin = items.find((item) => item.label === "c1.parent_id = c2.id" || item.label === "c2.parent_id = c1.id");
assert.ok(parentJoin, "should suggest parent_id = id for self-reference");
});
diff --git a/packages/app-tests/sqlCompletionPerformance.test.ts b/packages/app-tests/sqlCompletionPerformance.test.ts
index bbb84d9f44..2a30cc52e8 100644
--- a/packages/app-tests/sqlCompletionPerformance.test.ts
+++ b/packages/app-tests/sqlCompletionPerformance.test.ts
@@ -110,9 +110,7 @@ test("completion metadata refresh is deduplicated and local lookups rank the cur
const schema = url.searchParams.get("schema") ?? "";
const filter = (url.searchParams.get("filter") ?? "").toLowerCase();
const limit = Number(url.searchParams.get("limit") || "0") || undefined;
- const tables = (tablesBySchema.get(schema) ?? [])
- .filter((table) => !filter || table.name.toLowerCase().includes(filter))
- .slice(0, limit);
+ const tables = (tablesBySchema.get(schema) ?? []).filter((table) => !filter || table.name.toLowerCase().includes(filter)).slice(0, limit);
return Response.json(tables);
}
return Response.json(null);
@@ -123,10 +121,7 @@ test("completion metadata refresh is deduplicated and local lookups rank the cur
const store = useConnectionStore();
store.addEphemeralConnection(postgresConnection());
- await Promise.all([
- store.refreshCompletionTables("conn-large", "app", "customer", 20, "schema_010"),
- store.refreshCompletionTables("conn-large", "app", "customer", 20, "schema_010"),
- ]);
+ await Promise.all([store.refreshCompletionTables("conn-large", "app", "customer", 20, "schema_010"), store.refreshCompletionTables("conn-large", "app", "customer", 20, "schema_010")]);
assert.equal(tableCalls, 1);
assert.equal(schemaCalls, 0);
diff --git a/packages/app-tests/sqlFormatter.test.ts b/packages/app-tests/sqlFormatter.test.ts
index 9ab95ce142..a8dca78530 100644
--- a/packages/app-tests/sqlFormatter.test.ts
+++ b/packages/app-tests/sqlFormatter.test.ts
@@ -12,15 +12,9 @@ test("rejects very large SQL before importing formatter", async () => {
throw new Error("formatter should not load");
});
- const {
- formatSqlText: isolatedFormatSqlText,
- MAX_SQL_FORMAT_CHARS: isolatedMaxSqlFormatChars,
- } = await import("../../apps/desktop/src/lib/sqlFormatter.ts");
-
- await assert.rejects(
- () => isolatedFormatSqlText("x".repeat(isolatedMaxSqlFormatChars + 1), "generic"),
- /too large/i,
- );
+ const { formatSqlText: isolatedFormatSqlText, MAX_SQL_FORMAT_CHARS: isolatedMaxSqlFormatChars } = await import("../../apps/desktop/src/lib/sqlFormatter.ts");
+
+ await assert.rejects(() => isolatedFormatSqlText("x".repeat(isolatedMaxSqlFormatChars + 1), "generic"), /too large/i);
});
test("formats SQL with uppercase keywords and readable line breaks by default", async () => {
@@ -56,8 +50,5 @@ test("leaves blank SQL unchanged", async () => {
});
test("rejects very large SQL before loading formatter work", async () => {
- await assert.rejects(
- () => formatSqlText("x".repeat(MAX_SQL_FORMAT_CHARS + 1), "generic"),
- /too large/i,
- );
+ await assert.rejects(() => formatSqlText("x".repeat(MAX_SQL_FORMAT_CHARS + 1), "generic"), /too large/i);
});
diff --git a/packages/app-tests/sqlFormatterConfig.test.ts b/packages/app-tests/sqlFormatterConfig.test.ts
index b01da62fa5..a033e13e73 100644
--- a/packages/app-tests/sqlFormatterConfig.test.ts
+++ b/packages/app-tests/sqlFormatterConfig.test.ts
@@ -1,13 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- DEFAULT_SQL_FORMATTER_SETTINGS,
- parseSqlFormatterConfig,
- serializeSqlFormatterConfig,
- normalizeSqlFormatterSettings,
- syncSqlFormatterConfigDraft,
- sqlFormatterOptions,
-} from "../../apps/desktop/src/lib/sqlFormatterConfig.ts";
+import { DEFAULT_SQL_FORMATTER_SETTINGS, parseSqlFormatterConfig, serializeSqlFormatterConfig, normalizeSqlFormatterSettings, syncSqlFormatterConfigDraft, sqlFormatterOptions } from "../../apps/desktop/src/lib/sqlFormatterConfig.ts";
test("normalizes empty formatter settings to defaults", () => {
assert.deepEqual(normalizeSqlFormatterSettings({}), DEFAULT_SQL_FORMATTER_SETTINGS);
@@ -119,28 +112,19 @@ test("rejects malformed formatter config files", () => {
assert.deepEqual(parseSqlFormatterConfig("{bad json").ok, false);
assert.deepEqual(parseSqlFormatterConfig(JSON.stringify({ version: 2, formatter: "sql-formatter", options: {} })).ok, false);
assert.deepEqual(parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "prettier", options: {} })).ok, false);
- assert.deepEqual(
- parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { unknown: true } })).ok,
- false,
- );
+ assert.deepEqual(parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { unknown: true } })).ok, false);
});
test("rejects invalid known formatter option values when parsing config files", () => {
- const invalidKeywordCase = parseSqlFormatterConfig(
- JSON.stringify({ version: 1, formatter: "sql-formatter", options: { keywordCase: "camel" } }),
- );
+ const invalidKeywordCase = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { keywordCase: "camel" } }));
assert.equal(invalidKeywordCase.ok, false);
if (!invalidKeywordCase.ok) assert.match(invalidKeywordCase.message, /keywordCase/);
- const invalidBoolean = parseSqlFormatterConfig(
- JSON.stringify({ version: 1, formatter: "sql-formatter", options: { useTabs: "yes" } }),
- );
+ const invalidBoolean = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { useTabs: "yes" } }));
assert.equal(invalidBoolean.ok, false);
if (!invalidBoolean.ok) assert.match(invalidBoolean.message, /useTabs/);
- const invalidNumericChoice = parseSqlFormatterConfig(
- JSON.stringify({ version: 1, formatter: "sql-formatter", options: { tabWidth: 3 } }),
- );
+ const invalidNumericChoice = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { tabWidth: 3 } }));
assert.equal(invalidNumericChoice.ok, false);
if (!invalidNumericChoice.ok) assert.match(invalidNumericChoice.message, /tabWidth/);
});
diff --git a/packages/app-tests/sqlFormatterConfigEditor.test.ts b/packages/app-tests/sqlFormatterConfigEditor.test.ts
index 85af0cfcfc..42f47d62aa 100644
--- a/packages/app-tests/sqlFormatterConfigEditor.test.ts
+++ b/packages/app-tests/sqlFormatterConfigEditor.test.ts
@@ -27,19 +27,7 @@ test("builds common SQL formatter config editor key bindings", () => {
assert.deepEqual(
bindings.map((binding) => binding.key),
- [
- "Tab",
- "Shift-Tab",
- "Mod-d",
- "Shift-Mod-k",
- "Alt-ArrowUp",
- "Alt-ArrowDown",
- "Shift-Alt-ArrowUp",
- "Shift-Alt-ArrowDown",
- "Ctrl-h",
- "Shift-Alt-f",
- "Mod-s",
- ],
+ ["Tab", "Shift-Tab", "Mod-d", "Shift-Mod-k", "Alt-ArrowUp", "Alt-ArrowDown", "Shift-Alt-ArrowUp", "Shift-Alt-ArrowDown", "Ctrl-h", "Shift-Alt-f", "Mod-s"],
);
});
@@ -61,9 +49,7 @@ test("sets search, format, and apply binding details", () => {
test("keeps duplicate line before later Mod-d search bindings", () => {
const bindings = [...createBindings(), { key: "Mod-d", run: otherCommand }];
- const duplicateLineIndex = bindings.findIndex(
- (binding) => binding.key === "Mod-d" && binding.run === commands.copyLineDown,
- );
+ const duplicateLineIndex = bindings.findIndex((binding) => binding.key === "Mod-d" && binding.run === commands.copyLineDown);
const searchKeymapIndex = bindings.findIndex((binding) => binding.key === "Mod-d" && binding.run === otherCommand);
assert.notEqual(duplicateLineIndex, -1);
diff --git a/packages/app-tests/sqlMetadataRefresh.test.ts b/packages/app-tests/sqlMetadataRefresh.test.ts
index ba9f5557ca..d8ee41a541 100644
--- a/packages/app-tests/sqlMetadataRefresh.test.ts
+++ b/packages/app-tests/sqlMetadataRefresh.test.ts
@@ -18,10 +18,7 @@ test("object DDL refreshes the selected database tree", () => {
assert.equal(sqlMetadataRefreshScope("CREATE MATERIALIZED VIEW daily_users AS SELECT 1;"), "database");
assert.equal(sqlMetadataRefreshScope("ALTER TABLE users ADD COLUMN name text;"), "database");
assert.equal(sqlMetadataRefreshScope("DROP VIEW active_users;"), "database");
- assert.equal(
- sqlMetadataRefreshScope("CREATE OR REPLACE FUNCTION f() RETURNS int AS $$ SELECT 1 $$ LANGUAGE SQL;"),
- "database",
- );
+ assert.equal(sqlMetadataRefreshScope("CREATE OR REPLACE FUNCTION f() RETURNS int AS $$ SELECT 1 $$ LANGUAGE SQL;"), "database");
});
test("qualified object DDL refreshes the matching schema node", () => {
@@ -52,10 +49,7 @@ test("unqualified object DDL can use the active schema as the refresh target", (
});
test("multiple object DDL schemas fall back to refreshing the database tree", () => {
- assert.deepEqual(
- sqlMetadataRefreshTarget("CREATE TABLE public.users (id int); CREATE TABLE audit.events (id int);"),
- { scope: "database" },
- );
+ assert.deepEqual(sqlMetadataRefreshTarget("CREATE TABLE public.users (id int); CREATE TABLE audit.events (id int);"), { scope: "database" });
});
test("data-only SQL does not refresh metadata trees", () => {
diff --git a/packages/app-tests/sqlSemanticDiagnostics.test.ts b/packages/app-tests/sqlSemanticDiagnostics.test.ts
index 62a58ee499..cad425cc1d 100644
--- a/packages/app-tests/sqlSemanticDiagnostics.test.ts
+++ b/packages/app-tests/sqlSemanticDiagnostics.test.ts
@@ -1,11 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildSqlParserErrorDiagnostic,
- buildSqlSemanticDiagnostics,
- areSqlSemanticDiagnosticsEqual,
- shouldRunSqlSemanticDiagnostics,
-} from "../../apps/desktop/src/lib/sqlSemanticDiagnostics.ts";
+import { buildSqlParserErrorDiagnostic, buildSqlSemanticDiagnostics, areSqlSemanticDiagnosticsEqual, shouldRunSqlSemanticDiagnostics } from "../../apps/desktop/src/lib/sqlSemanticDiagnostics.ts";
import type { SqlReferenceAnalysis } from "../../apps/desktop/src/types/database.ts";
const span = (startColumn: number, endColumn: number) => ({
@@ -56,10 +51,7 @@ test("does not flag unqualified columns when multiple tables make ownership ambi
});
test("builds a syntax diagnostic from parser errors with line and column", () => {
- const diagnostic = buildSqlParserErrorDiagnostic(
- "Expected: end of statement, found: FOM at Line: 1, Column: 10",
- "SELECT * FOM",
- );
+ const diagnostic = buildSqlParserErrorDiagnostic("Expected: end of statement, found: FOM at Line: 1, Column: 10", "SELECT * FOM");
assert.equal(diagnostic?.message, "Expected: end of statement, found: FOM at Line: 1, Column: 10");
assert.deepEqual(diagnostic?.span, span(10, 12));
@@ -81,10 +73,7 @@ test("compares diagnostics by severity message and span", () => {
),
true,
);
- assert.equal(
- areSqlSemanticDiagnosticsEqual(diagnostics, [{ ...diagnostics[0], message: "Unknown column u.name" }]),
- false,
- );
+ assert.equal(areSqlSemanticDiagnosticsEqual(diagnostics, [{ ...diagnostics[0], message: "Unknown column u.name" }]), false);
});
test("defers diagnostics while the cursor is in table completion context", () => {
@@ -95,22 +84,13 @@ test("defers diagnostics while the cursor is in table completion context", () =>
});
test("skips diagnostics for MongoDB connections", () => {
- assert.equal(
- shouldRunSqlSemanticDiagnostics("db.my_collection.find({})", 0, { databaseType: "mongodb" }),
- false,
- );
+ assert.equal(shouldRunSqlSemanticDiagnostics("db.my_collection.find({})", 0, { databaseType: "mongodb" }), false);
});
test("skips diagnostics for Elasticsearch connections", () => {
- assert.equal(
- shouldRunSqlSemanticDiagnostics("db.my_collection.find({})", 0, { databaseType: "elasticsearch" }),
- false,
- );
+ assert.equal(shouldRunSqlSemanticDiagnostics("db.my_collection.find({})", 0, { databaseType: "elasticsearch" }), false);
});
test("still runs diagnostics for SQL connections", () => {
- assert.equal(
- shouldRunSqlSemanticDiagnostics("SELECT * FROM users WHERE id = 1", 42, { databaseType: "mysql" }),
- true,
- );
+ assert.equal(shouldRunSqlSemanticDiagnostics("SELECT * FROM users WHERE id = 1", 42, { databaseType: "mysql" }), true);
});
diff --git a/packages/app-tests/sqlServerTree.test.ts b/packages/app-tests/sqlServerTree.test.ts
index a9fb96c94c..b7de41a01c 100644
--- a/packages/app-tests/sqlServerTree.test.ts
+++ b/packages/app-tests/sqlServerTree.test.ts
@@ -11,12 +11,7 @@ function obj(name: string, objectType = "TABLE"): ObjectInfo {
}
test("SQL Server database tree groups dbo objects and keeps non-default schemas", () => {
- const nodes = buildSqlServerDatabaseTreeNodes(
- "conn",
- "app",
- ["dbo", "zeta", "sales"],
- [obj("customers"), obj("customer_view", "VIEW"), obj("get_total", "FUNCTION")],
- );
+ const nodes = buildSqlServerDatabaseTreeNodes("conn", "app", ["dbo", "zeta", "sales"], [obj("customers"), obj("customer_view", "VIEW"), obj("get_total", "FUNCTION")]);
const topLevel = nodes.map((n) => ({ id: n.id, label: n.label, type: n.type }));
assert.deepEqual(topLevel, [
@@ -53,12 +48,7 @@ test("SQL Server database tree shows only schemas when dbo has no objects", () =
});
test("SQL Server database tree groups procedures alongside tables", () => {
- const nodes = buildSqlServerDatabaseTreeNodes(
- "conn",
- "app",
- ["dbo"],
- [obj("orders"), obj("sp_refresh", "PROCEDURE")],
- );
+ const nodes = buildSqlServerDatabaseTreeNodes("conn", "app", ["dbo"], [obj("orders"), obj("sp_refresh", "PROCEDURE")]);
assert.deepEqual(
nodes.map((n) => ({ label: n.label, type: n.type })),
diff --git a/packages/app-tests/syncChangelog.test.ts b/packages/app-tests/syncChangelog.test.ts
index cc856c1c47..90e5b24ffe 100644
--- a/packages/app-tests/syncChangelog.test.ts
+++ b/packages/app-tests/syncChangelog.test.ts
@@ -27,9 +27,7 @@ test("translateToEnglish reuses cached release translations when source hash is
);
const cachedRelease = {
...cnJson.releases[1],
- sections: [
- { type: "fixed", title: "Fixed", items: [{ title: "Connection fix", desc: "Avoid duplicate connects" }] },
- ],
+ sections: [{ type: "fixed", title: "Fixed", items: [{ title: "Connection fix", desc: "Avoid duplicate connects" }] }],
};
const cachedEnJson = {
updatedAt: "2026-05-17T01:00:00.000Z",
diff --git a/packages/app-tests/tabCloseActions.test.ts b/packages/app-tests/tabCloseActions.test.ts
index b84dc2c829..5b41f79268 100644
--- a/packages/app-tests/tabCloseActions.test.ts
+++ b/packages/app-tests/tabCloseActions.test.ts
@@ -7,9 +7,15 @@ test("close other tabs keeps the target tab and makes it active", () => {
const result = closeOtherTabsState(tabs, "a", "b");
- assert.deepEqual(result.tabs.map((tab) => tab.id), ["b"]);
+ assert.deepEqual(
+ result.tabs.map((tab) => tab.id),
+ ["b"],
+ );
assert.equal(result.activeTabId, "b");
- assert.deepEqual(tabs.map((tab) => tab.id), ["a", "b", "c"]);
+ assert.deepEqual(
+ tabs.map((tab) => tab.id),
+ ["a", "b", "c"],
+ );
});
test("close other tabs is a no-op when the target tab is missing", () => {
@@ -17,7 +23,10 @@ test("close other tabs is a no-op when the target tab is missing", () => {
const result = closeOtherTabsState(tabs, "a", "missing");
- assert.deepEqual(result.tabs.map((tab) => tab.id), ["a", "b"]);
+ assert.deepEqual(
+ result.tabs.map((tab) => tab.id),
+ ["a", "b"],
+ );
assert.equal(result.activeTabId, "a");
});
diff --git a/packages/app-tests/tabPresentation.test.ts b/packages/app-tests/tabPresentation.test.ts
index cd9577f5e7..65b3a752bb 100644
--- a/packages/app-tests/tabPresentation.test.ts
+++ b/packages/app-tests/tabPresentation.test.ts
@@ -1,11 +1,7 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
import { createPinia, setActivePinia } from "pinia";
-import {
- executionSummaryItems,
- tabDisplayTitle,
- tabularResultItems,
-} from "../../apps/desktop/src/lib/tabPresentation.ts";
+import { executionSummaryItems, tabDisplayTitle, tabularResultItems } from "../../apps/desktop/src/lib/tabPresentation.ts";
import { useConnectionStore } from "../../apps/desktop/src/stores/connectionStore.ts";
import type { ConnectionConfig, QueryResult, QueryTab } from "../../apps/desktop/src/types/database.ts";
diff --git a/packages/app-tests/tabResultCache.test.ts b/packages/app-tests/tabResultCache.test.ts
index 8251269f30..cffb80079c 100644
--- a/packages/app-tests/tabResultCache.test.ts
+++ b/packages/app-tests/tabResultCache.test.ts
@@ -1,10 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- buildTabResultSnapshot,
- decodeTabResultSnapshot,
- encodeTabResultSnapshot,
-} from "../../apps/desktop/src/lib/tabResultCache.ts";
+import { buildTabResultSnapshot, decodeTabResultSnapshot, encodeTabResultSnapshot } from "../../apps/desktop/src/lib/tabResultCache.ts";
import type { QueryTab } from "../../apps/desktop/src/types/database.ts";
function queryTab(overrides: Partial<QueryTab> = {}): QueryTab {
diff --git a/packages/app-tests/tableDataExport.test.ts b/packages/app-tests/tableDataExport.test.ts
index ccb9a70021..99e06f8cbd 100644
--- a/packages/app-tests/tableDataExport.test.ts
+++ b/packages/app-tests/tableDataExport.test.ts
@@ -16,16 +16,12 @@ function result(rows: QueryResult["rows"]): QueryResult {
test("fetchTableDataForExport pages past the 10000 row export boundary", async () => {
const sqls: string[] = [];
- const pages = [
- result(Array.from({ length: TABLE_DATA_EXPORT_PAGE_SIZE }, (_, index) => [index + 1])),
- result([[10_001], [10_002]]),
- ];
+ const pages = [result(Array.from({ length: TABLE_DATA_EXPORT_PAGE_SIZE }, (_, index) => [index + 1])), result([[10_001], [10_002]])];
const exported = await fetchTableDataForExport({
databaseType: "mysql",
tableName: "users",
- buildPageSql: ({ limit, offset }) =>
- offset ? `SELECT * FROM \`users\` LIMIT ${limit} OFFSET ${offset};` : `SELECT * FROM \`users\` LIMIT ${limit};`,
+ buildPageSql: ({ limit, offset }) => (offset ? `SELECT * FROM \`users\` LIMIT ${limit} OFFSET ${offset};` : `SELECT * FROM \`users\` LIMIT ${limit};`),
executePage: async (sql) => {
sqls.push(sql);
return pages.shift() ?? result([]);
@@ -34,9 +30,6 @@ test("fetchTableDataForExport pages past the 10000 row export boundary", async (
assert.equal(exported.rows.length, TABLE_DATA_EXPORT_PAGE_SIZE + 2);
assert.deepEqual(exported.rows.at(-1), [10_002]);
- assert.deepEqual(sqls, [
- "SELECT * FROM `users` LIMIT 10000;",
- "SELECT * FROM `users` LIMIT 10000 OFFSET 10000;",
- ]);
+ assert.deepEqual(sqls, ["SELECT * FROM `users` LIMIT 10000;", "SELECT * FROM `users` LIMIT 10000 OFFSET 10000;"]);
assert.equal(exported.truncated, false);
});
diff --git a/packages/app-tests/tableEditing.test.ts b/packages/app-tests/tableEditing.test.ts
index c7aa2f724b..0aa12a40a5 100644
--- a/packages/app-tests/tableEditing.test.ts
+++ b/packages/app-tests/tableEditing.test.ts
@@ -39,10 +39,7 @@ test("does not synthesize ROWID for non-Oracle keyless tables", () => {
});
test("uses tbname and timestamp as TDengine editable keys", () => {
- assert.deepEqual(editablePrimaryKeys("tdengine", [column("ts", true), column("current")]), [
- DBX_TDENGINE_TBNAME_COLUMN,
- "ts",
- ]);
+ assert.deepEqual(editablePrimaryKeys("tdengine", [column("ts", true), column("current")]), [DBX_TDENGINE_TBNAME_COLUMN, "ts"]);
});
test("allows updateable SQL table data editing even without declared primary keys", () => {
@@ -116,12 +113,7 @@ test("keeps TDengine existing row identity and tag columns read-only", () => {
assert.equal(isTdengineExistingRowReadonlyColumn("tdengine", "ts", [column("ts", true)]), true);
assert.equal(isTdengineExistingRowReadonlyColumn("tdengine", "location", [column("location")]), false);
assert.equal(isTdengineExistingRowReadonlyColumn("mysql", "ts", [column("ts", true)]), false);
- assert.equal(
- isTdengineExistingRowReadonlyColumn("tdengine", "location", [
- { ...column("location"), extra: "TAG", comment: "TAG" },
- ]),
- true,
- );
+ assert.equal(isTdengineExistingRowReadonlyColumn("tdengine", "location", [{ ...column("location"), extra: "TAG", comment: "TAG" }]), true);
});
test("detects the synthetic Oracle ROWID key case", () => {
diff --git a/packages/app-tests/tableImport.test.ts b/packages/app-tests/tableImport.test.ts
index 229b321847..917f541e71 100644
--- a/packages/app-tests/tableImport.test.ts
+++ b/packages/app-tests/tableImport.test.ts
@@ -1,9 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- autoMapImportColumns,
- normalizeImportColumnName,
-} from "../../apps/desktop/src/lib/tableImport.ts";
+import { autoMapImportColumns, normalizeImportColumnName } from "../../apps/desktop/src/lib/tableImport.ts";
test("normalizes import column names for matching", () => {
assert.equal(normalizeImportColumnName(" User ID "), "user id");
@@ -12,10 +9,7 @@ test("normalizes import column names for matching", () => {
});
test("auto maps source columns to matching target columns and skips unknown columns", () => {
- const mapping = autoMapImportColumns(
- ["id", "Name", "created-at", "ignored"],
- ["user_id", "name", "created_at"],
- );
+ const mapping = autoMapImportColumns(["id", "Name", "created-at", "ignored"], ["user_id", "name", "created_at"]);
assert.deepEqual(mapping, {
id: "",
diff --git a/packages/app-tests/tableSelectSql.test.ts b/packages/app-tests/tableSelectSql.test.ts
index aa057792ba..13565c45d2 100644
--- a/packages/app-tests/tableSelectSql.test.ts
+++ b/packages/app-tests/tableSelectSql.test.ts
@@ -5,10 +5,7 @@ import { qualifiedTableName, quoteTableIdentifier } from "../../apps/desktop/src
test("JDBC table identifiers avoid double quotes for Kyuubi-compatible names", () => {
assert.equal(quoteTableIdentifier("jdbc", "cbsdw_dwd"), "cbsdw_dwd");
assert.equal(quoteTableIdentifier("jdbc", "dwd_test_df"), "dwd_test_df");
- assert.equal(
- qualifiedTableName({ databaseType: "jdbc", schema: "cbsdw_dwd", tableName: "dwd_test_df" }),
- "dwd_test_df",
- );
+ assert.equal(qualifiedTableName({ databaseType: "jdbc", schema: "cbsdw_dwd", tableName: "dwd_test_df" }), "dwd_test_df");
});
test("JDBC table identifiers use backticks only when quoting is needed", () => {
@@ -18,12 +15,6 @@ test("JDBC table identifiers use backticks only when quoting is needed", () => {
test("IoTDB table identifiers use tree paths without SQL quotes", () => {
assert.equal(quoteTableIdentifier("iotdb", "root.test.device2"), "root.test.device2");
- assert.equal(
- qualifiedTableName({ databaseType: "iotdb", schema: "root.test", tableName: "device2" }),
- "root.test.device2",
- );
- assert.equal(
- qualifiedTableName({ databaseType: "iotdb", schema: "root.test", tableName: "root.test.device2" }),
- "root.test.device2",
- );
+ assert.equal(qualifiedTableName({ databaseType: "iotdb", schema: "root.test", tableName: "device2" }), "root.test.device2");
+ assert.equal(qualifiedTableName({ databaseType: "iotdb", schema: "root.test", tableName: "root.test.device2" }), "root.test.device2");
});
diff --git a/packages/app-tests/tableStructureCapabilities.test.ts b/packages/app-tests/tableStructureCapabilities.test.ts
index a4a493c680..fa70c2af70 100644
--- a/packages/app-tests/tableStructureCapabilities.test.ts
+++ b/packages/app-tests/tableStructureCapabilities.test.ts
@@ -1,9 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- canEditTableStructure,
- getTableStructureCapabilities,
-} from "../../apps/desktop/src/lib/tableStructureCapabilities.ts";
+import { canEditTableStructure, getTableStructureCapabilities } from "../../apps/desktop/src/lib/tableStructureCapabilities.ts";
test("sqlite-family and duckdb do not support table comments", () => {
for (const dbType of ["sqlite", "rqlite", "duckdb"] as const) {
diff --git a/packages/app-tests/tableStructureEditorState.test.ts b/packages/app-tests/tableStructureEditorState.test.ts
index 64e1bc7a02..98b64d5cf0 100644
--- a/packages/app-tests/tableStructureEditorState.test.ts
+++ b/packages/app-tests/tableStructureEditorState.test.ts
@@ -1,15 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- buildStructureTargetLabel,
- combineDataTypeForDatabase,
- createColumnDrafts,
- createIndexDrafts,
- getDataTypeOptions,
- normalizeDataTypeParams,
- parseExtraToColumnExtra,
- toColumnNames,
-} from "../../apps/desktop/src/lib/tableStructureEditorState.ts";
+import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, getDataTypeOptions, normalizeDataTypeParams, parseExtraToColumnExtra, toColumnNames } from "../../apps/desktop/src/lib/tableStructureEditorState.ts";
import type { ColumnInfo, IndexInfo } from "../../apps/desktop/src/types/database.ts";
const columns: ColumnInfo[] = [
@@ -163,14 +154,8 @@ test("creates editable index drafts and splits pasted column lists", () => {
});
test("structure editor target label omits duplicate database and schema", () => {
- assert.equal(
- buildStructureTargetLabel("online-clickhouse", "testdb", "testdb", "users"),
- "online-clickhouse / testdb / users",
- );
- assert.equal(
- buildStructureTargetLabel("online-postgres", "app", "public", "users"),
- "online-postgres / app / public / users",
- );
+ assert.equal(buildStructureTargetLabel("online-clickhouse", "testdb", "testdb", "users"), "online-clickhouse / testdb / users");
+ assert.equal(buildStructureTargetLabel("online-postgres", "app", "public", "users"), "online-postgres / app / public / users");
});
test("normalizes temporal precision when combining data types", () => {
diff --git a/packages/app-tests/tableTree.test.ts b/packages/app-tests/tableTree.test.ts
index 2a164f63ab..c07ff694ec 100644
--- a/packages/app-tests/tableTree.test.ts
+++ b/packages/app-tests/tableTree.test.ts
@@ -1,12 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import {
- buildGroupedObjectTreeNodes,
- buildObjectGroupPlaceholderNodes,
- buildSimpleObjectTreeNodes,
- buildTableTreeNodes,
- mergeTableInfosIntoObjects,
-} from "../../apps/desktop/src/lib/tableTree.ts";
+import { buildGroupedObjectTreeNodes, buildObjectGroupPlaceholderNodes, buildSimpleObjectTreeNodes, buildTableTreeNodes, mergeTableInfosIntoObjects } from "../../apps/desktop/src/lib/tableTree.ts";
import type { ObjectInfo, TableInfo, TreeNode } from "../../apps/desktop/src/types/database.ts";
function table(name: string, parent?: string): TableInfo {
diff --git a/packages/app-tests/transferProgressState.test.ts b/packages/app-tests/transferProgressState.test.ts
index f816031d4c..5fbf93ccd6 100644
--- a/packages/app-tests/transferProgressState.test.ts
+++ b/packages/app-tests/transferProgressState.test.ts
@@ -3,30 +3,18 @@ import { test } from "vitest";
import { nextTransferTerminalState } from "../../apps/desktop/src/lib/transferProgressState.ts";
test("does not mark transfer as failed when only a table progress event reports error", () => {
- const state = nextTransferTerminalState(
- { done: false, cancelled: false, error: false },
- { status: "error" },
- );
+ const state = nextTransferTerminalState({ done: false, cancelled: false, error: false }, { status: "error" });
assert.deepEqual(state, { done: false, cancelled: false, error: false });
});
test("keeps terminal flags for done and cancelled progress events", () => {
- assert.deepEqual(
- nextTransferTerminalState({ done: false, cancelled: false, error: false }, { status: "done" }),
- { done: true, cancelled: false, error: false },
- );
- assert.deepEqual(
- nextTransferTerminalState({ done: false, cancelled: false, error: false }, { status: "cancelled" }),
- { done: false, cancelled: true, error: false },
- );
+ assert.deepEqual(nextTransferTerminalState({ done: false, cancelled: false, error: false }, { status: "done" }), { done: true, cancelled: false, error: false });
+ assert.deepEqual(nextTransferTerminalState({ done: false, cancelled: false, error: false }, { status: "cancelled" }), { done: false, cancelled: true, error: false });
});
test("still marks transfer as done after earlier table errors", () => {
- const afterError = nextTransferTerminalState(
- { done: false, cancelled: false, error: false },
- { status: "error" },
- );
+ const afterError = nextTransferTerminalState({ done: false, cancelled: false, error: false }, { status: "error" });
assert.deepEqual(nextTransferTerminalState(afterError, { status: "done" }), {
done: true,
diff --git a/packages/app-tests/treeNodeClick.test.ts b/packages/app-tests/treeNodeClick.test.ts
index 456db121dd..0a4d1092d1 100644
--- a/packages/app-tests/treeNodeClick.test.ts
+++ b/packages/app-tests/treeNodeClick.test.ts
@@ -1,12 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import {
- copyNameForTreeNode,
- objectSourceKindForTreeNode,
- sidebarSelectionCopyAction,
- treeNodeRowAction,
- treeNodeRowDoubleClickAction,
-} from "../../apps/desktop/src/lib/treeNodeClick.ts";
+import { copyNameForTreeNode, objectSourceKindForTreeNode, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "../../apps/desktop/src/lib/treeNodeClick.ts";
test("table and view rows open data without toggling structure groups", () => {
assert.equal(treeNodeRowAction("table", true), "open-data");
diff --git a/packages/app-tests/treeNodeContext.test.ts b/packages/app-tests/treeNodeContext.test.ts
index 9538f5675b..974b5d008d 100644
--- a/packages/app-tests/treeNodeContext.test.ts
+++ b/packages/app-tests/treeNodeContext.test.ts
@@ -1,10 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- hasTreeNodeDatabaseContext,
- normalizeCataloglessDatabaseNodes,
- treeNodeSchemaCachePrefix,
-} from "../../apps/desktop/src/lib/treeNodeContext.ts";
+import { hasTreeNodeDatabaseContext, normalizeCataloglessDatabaseNodes, treeNodeSchemaCachePrefix } from "../../apps/desktop/src/lib/treeNodeContext.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
test("treats empty database string as a valid catalogless context", () => {
diff --git a/packages/app-tests/useFlatTree.test.ts b/packages/app-tests/useFlatTree.test.ts
index 678463a913..d80ba46cf0 100644
--- a/packages/app-tests/useFlatTree.test.ts
+++ b/packages/app-tests/useFlatTree.test.ts
@@ -1,14 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- SIDEBAR_TREE_ROW_HEIGHT,
- SIDEBAR_TREE_PRERENDER_COUNT,
- SIDEBAR_TREE_SCROLL_BUFFER,
- flattenTree,
- scrollTopForExpandedTreeNode,
- shouldAutoScrollExpandedTreeNode,
- shouldVirtualizeFlatTree,
-} from "../../apps/desktop/src/composables/useFlatTree.ts";
+import { SIDEBAR_TREE_ROW_HEIGHT, SIDEBAR_TREE_PRERENDER_COUNT, SIDEBAR_TREE_SCROLL_BUFFER, flattenTree, scrollTopForExpandedTreeNode, shouldAutoScrollExpandedTreeNode, shouldVirtualizeFlatTree } from "../../apps/desktop/src/composables/useFlatTree.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
test("flattenTree preserves depth and node type for virtualized sidebar rows", () => {
diff --git a/packages/app-tests/visibleDatabases.test.ts b/packages/app-tests/visibleDatabases.test.ts
index a5895de3b5..8f07d9ebdd 100644
--- a/packages/app-tests/visibleDatabases.test.ts
+++ b/packages/app-tests/visibleDatabases.test.ts
@@ -1,13 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import {
- filterDatabaseNamesForConnection,
- filterVisibleDatabaseNames,
- isSystemDatabaseName,
- canSaveVisibleDatabaseSelection,
- normalizeVisibleDatabaseSelection,
- visibleDatabaseFilterIsEnabled,
-} from "../../apps/desktop/src/lib/visibleDatabases.ts";
+import { filterDatabaseNamesForConnection, filterVisibleDatabaseNames, isSystemDatabaseName, canSaveVisibleDatabaseSelection, normalizeVisibleDatabaseSelection, visibleDatabaseFilterIsEnabled } from "../../apps/desktop/src/lib/visibleDatabases.ts";
test("undefined visible database filter keeps every database", () => {
assert.deepEqual(filterVisibleDatabaseNames(["app", "analytics"], undefined), ["app", "analytics"]);
@@ -30,19 +23,13 @@ test("empty visible database selection cannot be saved", () => {
});
test("normalizes selected database names against fresh database names", () => {
- assert.deepEqual(normalizeVisibleDatabaseSelection(["billing", "missing", "app", "app"], ["app", "billing"]), [
- "billing",
- "app",
- ]);
+ assert.deepEqual(normalizeVisibleDatabaseSelection(["billing", "missing", "app", "app"], ["app", "billing"]), ["billing", "app"]);
});
test("mysql system databases are hidden by default but can be explicitly selected", () => {
const databases = ["app", "information_schema", "mysql", "performance_schema", "sys"];
assert.deepEqual(filterDatabaseNamesForConnection(databases, { db_type: "mysql" }), ["app"]);
- assert.deepEqual(
- filterDatabaseNamesForConnection(databases, { db_type: "mysql", visible_databases: ["app", "sys"] }),
- ["app", "sys"],
- );
+ assert.deepEqual(filterDatabaseNamesForConnection(databases, { db_type: "mysql", visible_databases: ["app", "sys"] }), ["app", "sys"]);
assert.equal(isSystemDatabaseName("mysql", "performance_schema"), true);
assert.equal(isSystemDatabaseName("postgres", "information_schema"), false);
});
@@ -50,10 +37,7 @@ test("mysql system databases are hidden by default but can be explicitly selecte
test("gbase8s does not inherit base gbase system database filtering", () => {
const databases = ["app", "information_schema", "mysql", "performance_schema", "sys"];
assert.deepEqual(filterDatabaseNamesForConnection(databases, { db_type: "gbase" }), ["app"]);
- assert.deepEqual(
- filterDatabaseNamesForConnection(databases, { db_type: "gbase", driver_profile: "gbase8s" }),
- databases,
- );
+ assert.deepEqual(filterDatabaseNamesForConnection(databases, { db_type: "gbase", driver_profile: "gbase8s" }), databases);
});
test("system database detection is registered per database type", () => {
@@ -70,7 +54,5 @@ test("system database registry covers common database families", () => {
assert.deepEqual(filterDatabaseNamesForConnection(["_SYS_BIC", "SALES"], { db_type: "saphana" }), ["SALES"]);
assert.deepEqual(filterDatabaseNamesForConnection(["system_schema", "app"], { db_type: "cassandra" }), ["app"]);
assert.deepEqual(filterDatabaseNamesForConnection(["system", "neo4j"], { db_type: "neo4j" }), ["neo4j"]);
- assert.deepEqual(filterDatabaseNamesForConnection(["SNOWFLAKE", "ANALYTICS"], { db_type: "snowflake" }), [
- "ANALYTICS",
- ]);
+ assert.deepEqual(filterDatabaseNamesForConnection(["SNOWFLAKE", "ANALYTICS"], { db_type: "snowflake" }), ["ANALYTICS"]);
});
diff --git a/packages/cli/README.md b/packages/cli/README.md
index c795eb5724..9eadf14e09 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -29,17 +29,17 @@ dbx open local users
## Commands
-| Command | Description |
-|---|---|
-| `dbx doctor` | Show local DBX config and desktop bridge diagnostics |
-| `dbx capabilities` | Show direct-query and desktop-bridge database support |
-| `dbx connections list` | List DBX connections without printing secrets |
-| `dbx schema list <connection>` | List tables and views |
-| `dbx schema describe <connection> <table>` | Show table columns |
-| `dbx query <connection> <sql>` | Execute one SQL statement |
-| `dbx query <connection> --file ./query.sql` | Execute SQL from a file |
-| `dbx context <connection>` | Print compact schema context for prompts |
-| `dbx open <connection> <table>` | Open a table in DBX Desktop |
+| Command | Description |
+| ------------------------------------------- | ----------------------------------------------------- |
+| `dbx doctor` | Show local DBX config and desktop bridge diagnostics |
+| `dbx capabilities` | Show direct-query and desktop-bridge database support |
+| `dbx connections list` | List DBX connections without printing secrets |
+| `dbx schema list <connection>` | List tables and views |
+| `dbx schema describe <connection> <table>` | Show table columns |
+| `dbx query <connection> <sql>` | Execute one SQL statement |
+| `dbx query <connection> --file ./query.sql` | Execute SQL from a file |
+| `dbx context <connection>` | Print compact schema context for prompts |
+| `dbx open <connection> <table>` | Open a table in DBX Desktop |
## Output
@@ -102,16 +102,16 @@ npm install -g @dbx-app/cli
CLI JSON errors use stable codes:
-| Code | Meaning |
-|---|---|
-| `UNKNOWN_OPTION` | An unsupported flag was provided |
-| `INVALID_OPTION` | A flag is missing a value or has an invalid value |
-| `INVALID_ARGUMENT` | Positional arguments are missing or conflicting |
+| Code | Meaning |
+| ------------------------ | --------------------------------------------------- |
+| `UNKNOWN_OPTION` | An unsupported flag was provided |
+| `INVALID_OPTION` | A flag is missing a value or has an invalid value |
+| `INVALID_ARGUMENT` | Positional arguments are missing or conflicting |
| `CONNECTION_STORE_ERROR` | DBX connection storage exists but could not be read |
-| `CONNECTION_NOT_FOUND` | No DBX connection matched the requested name |
-| `SQL_BLOCKED` | SQL safety rules blocked execution |
-| `DBX_NOT_RUNNING` | DBX Desktop bridge is unavailable |
-| `ERROR` | Unexpected runtime failure |
+| `CONNECTION_NOT_FOUND` | No DBX connection matched the requested name |
+| `SQL_BLOCKED` | SQL safety rules blocked execution |
+| `DBX_NOT_RUNNING` | DBX Desktop bridge is unavailable |
+| `ERROR` | Unexpected runtime failure |
## Codex
diff --git a/packages/cli/package.json b/packages/cli/package.json
index c84d1f2371..45e651e221 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -2,9 +2,23 @@
"name": "@dbx-app/cli",
"version": "0.4.7",
"description": "Command line interface for DBX database connections, schema, and safe queries",
- "type": "module",
- "engines": {
- "node": ">=22.13.0"
+ "keywords": [
+ "ai-agent",
+ "automation",
+ "cli",
+ "codex",
+ "database",
+ "dbx",
+ "mysql",
+ "postgresql",
+ "terminal"
+ ],
+ "homepage": "https://github.com/t8y2/dbx/tree/main/packages/cli",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/cli"
},
"bin": {
"dbx": "dist/cli.js"
@@ -12,30 +26,13 @@
"files": [
"dist"
],
+ "type": "module",
"scripts": {
"start": "tsx src/cli.ts",
"test": "pnpm --filter @dbx-app/node-core build && vitest run --config vitest.config.ts",
"build": "pnpm --filter @dbx-app/node-core build && tsc",
"prepublishOnly": "tsc"
},
- "keywords": [
- "cli",
- "database",
- "dbx",
- "codex",
- "terminal",
- "automation",
- "postgresql",
- "mysql",
- "ai-agent"
- ],
- "license": "Apache-2.0",
- "repository": {
- "type": "git",
- "url": "https://github.com/t8y2/dbx",
- "directory": "packages/cli"
- },
- "homepage": "https://github.com/t8y2/dbx/tree/main/packages/cli",
"dependencies": {
"@dbx-app/node-core": "workspace:^"
},
@@ -43,5 +40,8 @@
"@types/node": "^22.15.21",
"tsx": "^4.19.4",
"typescript": "^5.8.3"
+ },
+ "engines": {
+ "node": ">=22.13.0"
}
}
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index e7bd7c4266..ae85200076 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -1,19 +1,6 @@
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
-import {
- buildSchemaContext,
- createBackend,
- DIRECT_QUERY_TYPES,
- BRIDGE_REQUIRED_TYPES,
- evaluateSqlSafety,
- formatSchemaContext,
- getDbxDiagnostics,
- isMainModule,
- postBridge,
- type Backend,
- type DbxDiagnostics,
- type SqlSafetyOptions,
-} from "@dbx-app/node-core";
+import { buildSchemaContext, createBackend, DIRECT_QUERY_TYPES, BRIDGE_REQUIRED_TYPES, evaluateSqlSafety, formatSchemaContext, getDbxDiagnostics, isMainModule, postBridge, type Backend, type DbxDiagnostics, type SqlSafetyOptions } from "@dbx-app/node-core";
import { connectionSummary, csvTable, errorPayload, formatCell, formatErrorMessage, mdTable } from "./cli-format.js";
export interface CliResult {
@@ -80,20 +67,23 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
if (flags.format === "json") return okJson(diagnostics);
if (flags.format === "csv") {
return ok(
- csvTable(["check", "value"], [
- { check: "appDataDir", value: diagnostics.appDataDir },
- { check: "dbPath", value: diagnostics.dbPath },
- { check: "dbPathExists", value: diagnostics.dbPathExists },
- { check: "connectionsTableExists", value: diagnostics.connectionsTableExists },
- { check: "connectionRowCount", value: diagnostics.connectionRowCount },
- { check: "loadConnectionsOk", value: diagnostics.loadConnectionsOk },
- { check: "loadedConnectionCount", value: diagnostics.loadedConnectionCount },
- { check: "loadConnectionsError", value: diagnostics.loadConnectionsError ?? "" },
- { check: "loadConnectionsHint", value: diagnostics.loadConnectionsHint ?? "" },
- { check: "bridgePortFile", value: diagnostics.bridgePortFile },
- { check: "bridgePortFileExists", value: diagnostics.bridgePortFileExists },
- { check: "bridgeUrl", value: diagnostics.bridgeUrl ?? "" },
- ]),
+ csvTable(
+ ["check", "value"],
+ [
+ { check: "appDataDir", value: diagnostics.appDataDir },
+ { check: "dbPath", value: diagnostics.dbPath },
+ { check: "dbPathExists", value: diagnostics.dbPathExists },
+ { check: "connectionsTableExists", value: diagnostics.connectionsTableExists },
+ { check: "connectionRowCount", value: diagnostics.connectionRowCount },
+ { check: "loadConnectionsOk", value: diagnostics.loadConnectionsOk },
+ { check: "loadedConnectionCount", value: diagnostics.loadedConnectionCount },
+ { check: "loadConnectionsError", value: diagnostics.loadConnectionsError ?? "" },
+ { check: "loadConnectionsHint", value: diagnostics.loadConnectionsHint ?? "" },
+ { check: "bridgePortFile", value: diagnostics.bridgePortFile },
+ { check: "bridgePortFileExists", value: diagnostics.bridgePortFileExists },
+ { check: "bridgeUrl", value: diagnostics.bridgeUrl ?? "" },
+ ],
+ ),
);
}
return ok(formatDoctor(diagnostics));
@@ -107,17 +97,17 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
};
if (flags.format === "json") return okJson(payload);
if (flags.format === "csv") {
- return ok(
- csvTable(
- ["mode", "type"],
- [
- ...payload.directQueryTypes.map((type) => ({ mode: "direct", type })),
- ...payload.bridgeRequiredTypes.map((type) => ({ mode: "bridge", type })),
- ],
- ),
- );
+ return ok(csvTable(["mode", "type"], [...payload.directQueryTypes.map((type) => ({ mode: "direct", type })), ...payload.bridgeRequiredTypes.map((type) => ({ mode: "bridge", type }))]));
}
- return ok(`${mdTable(["Mode", "Types"], [["Direct", payload.directQueryTypes.join(", ")], ["Requires DBX Desktop", payload.bridgeRequiredTypes.join(", ")]])}\n`);
+ return ok(
+ `${mdTable(
+ ["Mode", "Types"],
+ [
+ ["Direct", payload.directQueryTypes.join(", ")],
+ ["Requires DBX Desktop", payload.bridgeRequiredTypes.join(", ")],
+ ],
+ )}\n`,
+ );
}
if (args[0] === "connections" && args[1] === "list") {
@@ -140,7 +130,12 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
const tables = await backend.listTables(config, flags.schema);
if (flags.format === "json") return okJson({ connection: connectionName, schema: flags.schema, tables });
if (flags.format === "csv") return ok(csvTable(["name", "type"], tables));
- return ok(`${mdTable(["Table", "Type"], tables.map((t) => [t.name, t.type]))}\n`);
+ return ok(
+ `${mdTable(
+ ["Table", "Type"],
+ tables.map((t) => [t.name, t.type]),
+ )}\n`,
+ );
}
if (args[0] === "schema" && args[1] === "describe") {
@@ -156,13 +151,7 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
return ok(
`${mdTable(
["Column", "Type", "Nullable", "Default", "Comment"],
- columns.map((c) => [
- c.is_primary_key ? `${c.name} (PK)` : c.name,
- c.data_type,
- c.is_nullable ? "YES" : "NO",
- c.column_default ?? "",
- c.comment ?? "",
- ]),
+ columns.map((c) => [c.is_primary_key ? `${c.name} (PK)` : c.name, c.data_type, c.is_nullable ? "YES" : "NO", c.column_default ?? "", c.comment ?? ""]),
)}\n`,
);
}
@@ -237,12 +226,7 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
return fail("USAGE", usage(), flags.json);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
- const code =
- error instanceof CliError
- ? error.code
- : typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
- ? error.code
- : "ERROR";
+ const code = error instanceof CliError ? error.code : typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "ERROR";
const wantsJson = argv.includes("--json");
return fail(code, message, wantsJson);
} finally {
@@ -271,8 +255,7 @@ function parseFlags(argv: string[]): ParsedFlags {
if (arg === "--json") {
flags.json = true;
flags.format = "json";
- }
- else if (arg === "--format") flags.format = parseFormat(readOptionValue(argv, ++i, "--format"));
+ } else if (arg === "--format") flags.format = parseFormat(readOptionValue(argv, ++i, "--format"));
else if (arg === "--help" || arg === "-h") flags.help = true;
else if (arg === "--version" || arg === "-V") flags.version = true;
else if (arg === "--schema") flags.schema = readOptionValue(argv, ++i, "--schema");
@@ -396,12 +379,7 @@ function formatDoctor(diagnostics: DbxDiagnostics): string {
["App data directory", diagnostics.appDataDir],
["DBX database", diagnostics.dbPathExists ? `found (${diagnostics.dbPath})` : `missing (${diagnostics.dbPath})`],
["Connections table", diagnostics.connectionsTableExists ? `${diagnostics.connectionRowCount} row(s)` : "missing"],
- [
- "Connection loading",
- diagnostics.loadConnectionsOk
- ? `ok (${diagnostics.loadedConnectionCount} loaded)`
- : `failed (${diagnostics.loadConnectionsError ?? "unknown error"})`,
- ],
+ ["Connection loading", diagnostics.loadConnectionsOk ? `ok (${diagnostics.loadedConnectionCount} loaded)` : `failed (${diagnostics.loadConnectionsError ?? "unknown error"})`],
...(diagnostics.loadConnectionsHint ? [["Connection fix", diagnostics.loadConnectionsHint]] : []),
["Desktop bridge", diagnostics.bridgePortFileExists ? `available (${diagnostics.bridgeUrl ?? diagnostics.bridgePortFile})` : "not running"],
["Direct query types", diagnostics.directQueryTypes.join(", ")],
diff --git a/packages/cli/tests/bin.test.ts b/packages/cli/tests/bin.test.ts
index 159630a459..ce3f05fcbf 100644
--- a/packages/cli/tests/bin.test.ts
+++ b/packages/cli/tests/bin.test.ts
@@ -30,8 +30,8 @@ test("prints capabilities when invoked through an npm-style symlink", async () =
assert.equal(result.status, 0);
assert.equal(result.stderr, "");
const payload = JSON.parse(result.stdout) as { directQueryTypes: string[]; bridgeRequiredTypes: string[] };
- assert.ok(payload.directQueryTypes.includes("postgres"));
- assert.ok(payload.directQueryTypes.includes("rqlite"));
+ assert.ok(payload.directQueryTypes.includes("postgres"));
+ assert.ok(payload.directQueryTypes.includes("rqlite"));
assert.ok(payload.bridgeRequiredTypes.includes("oracle"));
} finally {
await rm(bin.dir, { recursive: true, force: true });
diff --git a/packages/cli/tests/cli-format.test.ts b/packages/cli/tests/cli-format.test.ts
index 3b8d389c73..32d5ba610b 100644
--- a/packages/cli/tests/cli-format.test.ts
+++ b/packages/cli/tests/cli-format.test.ts
@@ -39,7 +39,7 @@ test("formats markdown tables", () => {
test("formats database cell values with shared formatter", () => {
assert.equal(formatCell(null), "NULL");
- assert.equal(formatCell({ ok: true }), "{\"ok\":true}");
+ assert.equal(formatCell({ ok: true }), '{"ok":true}');
});
test("builds stable error payloads", () => {
diff --git a/packages/mcp-server/README.md b/packages/mcp-server/README.md
index 9d592097cf..dc83bfe776 100644
--- a/packages/mcp-server/README.md
+++ b/packages/mcp-server/README.md
@@ -79,16 +79,16 @@ See the [DBX CLI README](../cli/README.md) for command details.
## Tools
-| Tool | Description |
-|---|---|
-| `dbx_list_connections` | List all database connections configured in DBX |
-| `dbx_add_connection` | Add a new database connection |
-| `dbx_remove_connection` | Remove a database connection |
-| `dbx_list_tables` | List tables and views for a connection |
-| `dbx_describe_table` | Get column definitions for a table |
+| Tool | Description |
+| ------------------------ | ---------------------------------------------------- |
+| `dbx_list_connections` | List all database connections configured in DBX |
+| `dbx_add_connection` | Add a new database connection |
+| `dbx_remove_connection` | Remove a database connection |
+| `dbx_list_tables` | List tables and views for a connection |
+| `dbx_describe_table` | Get column definitions for a table |
| `dbx_get_schema_context` | Get compact table and column context for writing SQL |
-| `dbx_execute_query` | Execute a SQL query (max 100 rows) |
-| `dbx_open_table` | Open a table in DBX desktop app UI |
+| `dbx_execute_query` | Execute a SQL query (max 100 rows) |
+| `dbx_open_table` | Open a table in DBX desktop app UI |
## SQL Safety
@@ -202,16 +202,16 @@ dbx query local "select 1" --json
### 工具列表
-| 工具 | 说明 |
-|---|---|
-| `dbx_list_connections` | 列出 DBX 中所有已配置的数据库连接 |
-| `dbx_add_connection` | 添加新的数据库连接 |
-| `dbx_remove_connection` | 删除数据库连接 |
-| `dbx_list_tables` | 列出指定连接的表和视图 |
-| `dbx_describe_table` | 获取表的列定义 |
+| 工具 | 说明 |
+| ------------------------ | ------------------------------------- |
+| `dbx_list_connections` | 列出 DBX 中所有已配置的数据库连接 |
+| `dbx_add_connection` | 添加新的数据库连接 |
+| `dbx_remove_connection` | 删除数据库连接 |
+| `dbx_list_tables` | 列出指定连接的表和视图 |
+| `dbx_describe_table` | 获取表的列定义 |
| `dbx_get_schema_context` | 获取适合 AI 写 SQL 的紧凑表结构上下文 |
-| `dbx_execute_query` | 执行 SQL 查询(最多返回 100 行) |
-| `dbx_open_table` | 在 DBX 桌面端打开指定表 |
+| `dbx_execute_query` | 执行 SQL 查询(最多返回 100 行) |
+| `dbx_open_table` | 在 DBX 桌面端打开指定表 |
### SQL 安全
diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json
index afdc40108c..c76ee5e5ee 100644
--- a/packages/mcp-server/package.json
+++ b/packages/mcp-server/package.json
@@ -1,42 +1,38 @@
{
"name": "@dbx-app/mcp-server",
"version": "0.4.7",
- "mcpName": "io.github.t8y2/dbx",
"description": "MCP server for DBX — query databases from Claude Code, Cursor, and other AI agents",
- "type": "module",
- "engines": {
- "node": ">=22.13.0"
+ "keywords": [
+ "ai-agent",
+ "claude",
+ "database",
+ "dbx",
+ "mcp",
+ "mysql",
+ "postgresql"
+ ],
+ "homepage": "https://github.com/t8y2/dbx/tree/main/packages/mcp-server",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/t8y2/dbx",
+ "directory": "packages/mcp-server"
},
"bin": {
- "mcp-server": "dist/index.js",
- "dbx-mcp-server": "dist/index.js"
+ "dbx-mcp-server": "dist/index.js",
+ "mcp-server": "dist/index.js"
},
"files": [
"dist",
"server.json"
],
+ "type": "module",
"scripts": {
"start": "tsx src/index.ts",
"test": "pnpm --filter @dbx-app/mcp-server build && vitest run --config vitest.config.ts",
"build": "pnpm --filter @dbx-app/node-core build && tsc",
"prepublishOnly": "tsc"
},
- "keywords": [
- "mcp",
- "database",
- "dbx",
- "claude",
- "postgresql",
- "mysql",
- "ai-agent"
- ],
- "license": "Apache-2.0",
- "repository": {
- "type": "git",
- "url": "https://github.com/t8y2/dbx",
- "directory": "packages/mcp-server"
- },
- "homepage": "https://github.com/t8y2/dbx/tree/main/packages/mcp-server",
"dependencies": {
"@dbx-app/node-core": "workspace:^",
"@modelcontextprotocol/sdk": "^1.12.1",
@@ -46,5 +42,9 @@
"@types/node": "^22.15.21",
"tsx": "^4.19.4",
"typescript": "^5.8.3"
- }
+ },
+ "engines": {
+ "node": ">=22.13.0"
+ },
+ "mcpName": "io.github.t8y2/dbx"
}
diff --git a/packages/mcp-server/src/index.ts b/packages/mcp-server/src/index.ts
index 68dd7977fd..81898cbd91 100644
--- a/packages/mcp-server/src/index.ts
+++ b/packages/mcp-server/src/index.ts
@@ -95,13 +95,7 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
const columns = await backend.describeTable(withDatabase(config, database), table, schema);
if (columns.length === 0) return text("No columns found.");
- const rows = columns.map((c) => [
- c.is_primary_key ? `${c.name} (PK)` : c.name,
- c.data_type,
- c.is_nullable ? "YES" : "NO",
- c.column_default ?? "",
- c.comment ?? "",
- ]);
+ const rows = columns.map((c) => [c.is_primary_key ? `${c.name} (PK)` : c.name, c.data_type, c.is_nullable ? "YES" : "NO", c.column_default ?? "", c.comment ?? ""]);
return text(mdTable(["Column", "Type", "Nullable", "Default", "Comment"], rows));
},
);
@@ -130,11 +124,7 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
results.push(await backend.executeQuery(withDatabase(config, database), statement));
}
if (results.length === 1) return formatQueryToolResult(results[0]);
- return text(
- results
- .map((result, index) => formatQueryToolResult(result, `Statement ${index + 1}`).content[0].text)
- .join("\n\n"),
- );
+ return text(results.map((result, index) => formatQueryToolResult(result, `Statement ${index + 1}`).content[0].text).join("\n\n"));
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
return toolError("QUERY_ERROR", msg);
@@ -172,10 +162,7 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
name: z.string().describe("Connection name"),
db_type: z.string().describe(DBX_CONNECTION_TYPE_DESCRIPTION),
host: z.string().describe("Database host"),
- port: z
- .number()
- .optional()
- .describe("Database port (TDengine defaults to 6041, IoTDB defaults to 6667, XuguDB defaults to 5138)"),
+ port: z.number().optional().describe("Database port (TDengine defaults to 6041, IoTDB defaults to 6667, XuguDB defaults to 5138)"),
username: z.string().default("").describe("Username"),
password: z.string().default("").describe("Password"),
database: z.string().optional().describe("Default database name"),
@@ -191,8 +178,7 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
iotdb: 6667,
xugu: 5138,
};
- const resolvedPort =
- port ?? DEFAULT_PORTS[db_type] ?? (FILE_CAPABLE_CONNECTION_TYPES.has(db_type) ? 0 : undefined);
+ const resolvedPort = port ?? DEFAULT_PORTS[db_type] ?? (FILE_CAPABLE_CONNECTION_TYPES.has(db_type) ? 0 : undefined);
if (resolvedPort === undefined) return text("Port is required for this database type.");
const config = await backend.addConnection({
name,
diff --git a/packages/mcp-server/tests/bin.test.ts b/packages/mcp-server/tests/bin.test.ts
index 1d27c0609b..b3a455795b 100644
--- a/packages/mcp-server/tests/bin.test.ts
+++ b/packages/mcp-server/tests/bin.test.ts
@@ -62,10 +62,7 @@ function encodeMessage(payload: unknown): string {
return `${JSON.stringify(payload)}\n`;
}
-function readJsonRpcResponse(
- child: ChildProcessWithoutNullStreams,
- timeoutMs: number,
-): Promise<InitializeResponse> {
+function readJsonRpcResponse(child: ChildProcessWithoutNullStreams, timeoutMs: number): Promise<InitializeResponse> {
return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
@@ -97,9 +94,7 @@ function readJsonRpcResponse(
const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
cleanup();
- reject(
- new Error(`MCP server exited before initialize response. code=${code} signal=${signal} stderr: ${stderr}`),
- );
+ reject(new Error(`MCP server exited before initialize response. code=${code} signal=${signal} stderr: ${stderr}`));
};
const onError = (error: Error) => {
diff --git a/packages/mcp-server/tests/server.test.ts b/packages/mcp-server/tests/server.test.ts
index 4c68e5d430..dbf7f9251e 100644
--- a/packages/mcp-server/tests/server.test.ts
+++ b/packages/mcp-server/tests/server.test.ts
@@ -25,9 +25,7 @@ const backend: Backend = {
addConnection: async () => connection,
removeConnection: async () => true,
listTables: async () => [{ name: "users", type: "BASE TABLE" }],
- describeTable: async () => [
- { name: "id", data_type: "integer", is_nullable: false, column_default: null, is_primary_key: true, comment: null },
- ],
+ describeTable: async () => [{ name: "id", data_type: "integer", is_nullable: false, column_default: null, is_primary_key: true, comment: null }],
executeQuery: async () => ({ columns: ["total"], rows: [{ total: 1 }], row_count: 1 }),
};
diff --git a/packages/node-core/README.md b/packages/node-core/README.md
index c360352ca1..69f055aa4a 100644
--- a/packages/node-core/README.md
+++ b/packages/node-core/README.md
@@ -21,13 +21,7 @@ Other DBX connection types can be routed through DBX Desktop bridge integrations
## Public Modules
```ts
-import {
- createBackend,
- loadConnections,
- getDbxDiagnostics,
- evaluateSqlSafety,
- buildSchemaContext,
-} from "@dbx-app/node-core";
+import { createBackend, loadConnections, getDbxDiagnostics, evaluateSqlSafety, buildSchemaContext } from "@dbx-app/node-core";
```
The package is intended as a shared implementation layer for official DBX Node packages. Applications should prefer `@dbx-app/cli` for terminal workflows and `@dbx-app/mcp-server` for MCP clients.
diff --git a/packages/node-core/package.json b/packages/node-core/package.json
index dac6557da3..e4a9898b8f 100644
--- a/packages/node-core/package.json
+++ b/packages/node-core/package.json
@@ -2,13 +2,11 @@
"name": "@dbx-app/node-core",
"version": "0.4.7",
"description": "Shared Node.js database and DBX connection utilities for DBX CLI and MCP server",
- "type": "module",
- "engines": {
- "node": ">=22.13.0"
- },
+ "license": "Apache-2.0",
"files": [
"dist"
],
+ "type": "module",
"exports": {
".": "./dist/index.js",
"./backend": "./dist/backend.js",
@@ -27,7 +25,6 @@
"build": "tsc",
"prepublishOnly": "tsc"
},
- "license": "Apache-2.0",
"dependencies": {
"better-sqlite3": "^12.9.0",
"keytar": "^7.9.0",
@@ -40,5 +37,8 @@
"@types/pg": "^8.15.4",
"tsx": "^4.19.4",
"typescript": "^5.8.3"
+ },
+ "engines": {
+ "node": ">=22.13.0"
}
}
diff --git a/packages/node-core/src/backend.ts b/packages/node-core/src/backend.ts
index d8a4f66856..22f172d2b6 100644
--- a/packages/node-core/src/backend.ts
+++ b/packages/node-core/src/backend.ts
@@ -1,15 +1,5 @@
-import {
- addConnection as desktopAddConnection,
- findConnection as desktopFindConnection,
- loadConnections as desktopLoadConnections,
- removeConnection as desktopRemoveConnection,
-} from "./connections.js";
-import {
- closeDatabaseResources as desktopCloseDatabaseResources,
- describeTable as desktopDescribeTable,
- executeQuery as desktopExecuteQuery,
- listTables as desktopListTables,
-} from "./database.js";
+import { addConnection as desktopAddConnection, findConnection as desktopFindConnection, loadConnections as desktopLoadConnections, removeConnection as desktopRemoveConnection } from "./connections.js";
+import { closeDatabaseResources as desktopCloseDatabaseResources, describeTable as desktopDescribeTable, executeQuery as desktopExecuteQuery, listTables as desktopListTables } from "./database.js";
import type { ConnectionConfig } from "./connections.js";
import type { ColumnInfo, QueryOptions, QueryResult, TableInfo } from "./database.js";
diff --git a/packages/node-core/src/bridge.ts b/packages/node-core/src/bridge.ts
index 2ce3ccdaba..475f4818d1 100644
--- a/packages/node-core/src/bridge.ts
+++ b/packages/node-core/src/bridge.ts
@@ -6,10 +6,7 @@ export async function getBridgeUrl(): Promise<string> {
return `http://127.0.0.1:${port}`;
}
-export async function postBridge(
- path: string,
- body: Record<string, unknown>,
-): Promise<{ ok: true; text: string } | { ok: false; text: string }> {
+export async function postBridge(path: string, body: Record<string, unknown>): Promise<{ ok: true; text: string } | { ok: false; text: string }> {
try {
const bridgeUrl = await getBridgeUrl();
const res = await fetch(`${bridgeUrl}${path}`, {
diff --git a/packages/node-core/src/connections.ts b/packages/node-core/src/connections.ts
index 45d3b1fe5f..15629d0db0 100644
--- a/packages/node-core/src/connections.ts
+++ b/packages/node-core/src/connections.ts
@@ -103,9 +103,7 @@ function openDb(readonly = false, path = defaultDbPath()): Database.Database {
}
function getSecret(db: Database.Database, connectionId: string, key: string): string {
- const row = db
- .prepare("SELECT secret FROM connection_secrets WHERE connection_id = ? AND key = ?")
- .get(connectionId, key) as { secret: string } | undefined;
+ const row = db.prepare("SELECT secret FROM connection_secrets WHERE connection_id = ? AND key = ?").get(connectionId, key) as { secret: string } | undefined;
return row?.secret ?? "";
}
@@ -183,18 +181,10 @@ function hydrateTransportLayerSecrets(db: Database.Database, config: ConnectionC
config.transport_layers = normalizeTransportLayers(config as LegacyConnectionConfig);
config.transport_layers.forEach((layer, index) => {
if (layer.type === "ssh") {
- layer.password ||=
- getSecret(db, connectionId, transportLayerSshPasswordKey(index, layer)) ||
- (layer.id === "legacy" ? getSecret(db, connectionId, "ssh_password") : getSecret(db, connectionId, `ssh_tunnels.${layer.id || index}.password`));
- layer.key_passphrase ||=
- getSecret(db, connectionId, transportLayerSshKeyPassphraseKey(index, layer)) ||
- (layer.id === "legacy"
- ? getSecret(db, connectionId, "ssh_key_passphrase")
- : getSecret(db, connectionId, `ssh_tunnels.${layer.id || index}.key_passphrase`));
+ layer.password ||= getSecret(db, connectionId, transportLayerSshPasswordKey(index, layer)) || (layer.id === "legacy" ? getSecret(db, connectionId, "ssh_password") : getSecret(db, connectionId, `ssh_tunnels.${layer.id || index}.password`));
+ layer.key_passphrase ||= getSecret(db, connectionId, transportLayerSshKeyPassphraseKey(index, layer)) || (layer.id === "legacy" ? getSecret(db, connectionId, "ssh_key_passphrase") : getSecret(db, connectionId, `ssh_tunnels.${layer.id || index}.key_passphrase`));
} else {
- layer.password ||=
- getSecret(db, connectionId, transportLayerProxyPasswordKey(index, layer)) ||
- (layer.id === "legacy-proxy" ? getSecret(db, connectionId, "proxy_password") : "");
+ layer.password ||= getSecret(db, connectionId, transportLayerProxyPasswordKey(index, layer)) || (layer.id === "legacy-proxy" ? getSecret(db, connectionId, "proxy_password") : "");
}
});
}
@@ -271,9 +261,7 @@ export async function inspectConnectionStore(options: ConnectionStoreOptions = {
}
function tableExists(db: Database.Database, name: string): boolean {
- const row = db
- .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?")
- .get(name) as { "1": number } | undefined;
+ const row = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) as { "1": number } | undefined;
return !!row;
}
@@ -320,42 +308,22 @@ export async function addConnection(config: Omit<ConnectionConfig, "id">): Promi
const insert = db.transaction(() => {
db.prepare("INSERT INTO connections (id, config_json) VALUES (?, ?)").run(id, configJson);
if (normalized.password) {
- db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
- id,
- "password",
- normalized.password,
- );
+ db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, "password", normalized.password);
}
normalizeTransportLayers(normalized as LegacyConnectionConfig).forEach((layer, index) => {
if (layer.type === "ssh") {
if (layer.password) {
- db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
- id,
- transportLayerSshPasswordKey(index, layer),
- layer.password,
- );
+ db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, transportLayerSshPasswordKey(index, layer), layer.password);
}
if (layer.key_passphrase) {
- db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
- id,
- transportLayerSshKeyPassphraseKey(index, layer),
- layer.key_passphrase,
- );
+ db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, transportLayerSshKeyPassphraseKey(index, layer), layer.key_passphrase);
}
} else if (layer.password) {
- db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
- id,
- transportLayerProxyPasswordKey(index, layer),
- layer.password,
- );
+ db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, transportLayerProxyPasswordKey(index, layer), layer.password);
}
});
if (normalized.redis_sentinel_password) {
- db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(
- id,
- "redis_sentinel_password",
- normalized.redis_sentinel_password,
- );
+ db.prepare("INSERT INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)").run(id, "redis_sentinel_password", normalized.redis_sentinel_password);
}
});
insert();
diff --git a/packages/node-core/src/database.ts b/packages/node-core/src/database.ts
index e606f5b690..2d6b2491a9 100644
--- a/packages/node-core/src/database.ts
+++ b/packages/node-core/src/database.ts
@@ -366,7 +366,9 @@ function resolveTimeoutMs(options?: QueryOptions): number {
function convertBridgeQueryResult(result: BridgeQueryResult, options?: QueryOptions): QueryResult {
const rows = result.rows.slice(0, resolveMaxRows(options)).map((row) => {
const obj: Record<string, unknown> = {};
- result.columns.forEach((col, i) => { obj[col] = row[i]; });
+ result.columns.forEach((col, i) => {
+ obj[col] = row[i];
+ });
return obj;
});
return { columns: result.columns, rows, row_count: rows.length };
@@ -397,21 +399,29 @@ async function queryWithRetry(config: ConnectionConfig, fn: () => Promise<QueryR
}
async function pgQuery(config: ConnectionConfig, sql: string, params?: unknown[], options?: QueryOptions): Promise<QueryResult> {
- return queryWithRetry(config, async () => {
- const pool = await getPgPool(config);
- const result = await pool.query(sql, params);
- const rows = (result.rows || []).slice(0, resolveMaxRows(options));
- return { columns: result.fields?.map((f) => f.name) ?? [], rows, row_count: rows.length };
- }, options);
+ return queryWithRetry(
+ config,
+ async () => {
+ const pool = await getPgPool(config);
+ const result = await pool.query(sql, params);
+ const rows = (result.rows || []).slice(0, resolveMaxRows(options));
+ return { columns: result.fields?.map((f) => f.name) ?? [], rows, row_count: rows.length };
+ },
+ options,
+ );
}
async function mysqlQuery(config: ConnectionConfig, sql: string, params?: unknown[], options?: QueryOptions): Promise<QueryResult> {
- return queryWithRetry(config, async () => {
- const pool = await getMysqlPool(config);
- const [results, fields] = await pool.query(sql, params);
- const rows = (Array.isArray(results) ? results : []).slice(0, resolveMaxRows(options)) as Record<string, unknown>[];
- return { columns: (fields as Array<{ name: string }>)?.map((f) => f.name) ?? [], rows, row_count: rows.length };
- }, options);
+ return queryWithRetry(
+ config,
+ async () => {
+ const pool = await getMysqlPool(config);
+ const [results, fields] = await pool.query(sql, params);
+ const rows = (Array.isArray(results) ? results : []).slice(0, resolveMaxRows(options)) as Record<string, unknown>[];
+ return { columns: (fields as Array<{ name: string }>)?.map((f) => f.name) ?? [], rows, row_count: rows.length };
+ },
+ options,
+ );
}
async function query(config: ConnectionConfig, sql: string, params?: unknown[], options?: QueryOptions): Promise<QueryResult> {
@@ -507,18 +517,12 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
if (aggregate) {
const safety = evaluateMongoAggregateSafety(aggregate, sqlSafetyFromEnv());
if (!safety.allowed) throw new Error(safety.reason);
- const result = await withTimeout(
- mongoAggregateDocuments(config, aggregate.collection, aggregate.pipeline, resolveMaxRows(options)),
- resolveTimeoutMs(options),
- );
+ const result = await withTimeout(mongoAggregateDocuments(config, aggregate.collection, aggregate.pipeline, resolveMaxRows(options)), resolveTimeoutMs(options));
return mongoDocumentsToQueryResult(result.documents.slice(0, resolveMaxRows(options)), result.total);
}
const getIndexes = parseMongoGetIndexesCommand(sql);
if (getIndexes) {
- const result = await withTimeout(
- mongoAggregateDocuments(config, getIndexes.collection, '[{"$indexStats":{}}]', resolveMaxRows(options)),
- resolveTimeoutMs(options),
- );
+ const result = await withTimeout(mongoAggregateDocuments(config, getIndexes.collection, '[{"$indexStats":{}}]', resolveMaxRows(options)), resolveTimeoutMs(options));
return mongoDocumentsToQueryResult(result.documents.slice(0, resolveMaxRows(options)), result.total);
}
const write = parseMongoWriteCommand(sql);
@@ -528,18 +532,19 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
const affected = await withTimeout(executeMongoWrite(config, write), resolveTimeoutMs(options));
return { columns: [], rows: [], row_count: affected };
}
- throw new Error(
- "Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.getIndexes(), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})",
- );
+ throw new Error("Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.getIndexes(), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})");
}
if (isDirectQueryType(config.db_type)) {
return query(config, sql, undefined, options);
}
- const result = await withTimeout(bridgeDataRequest<BridgeQueryResult>("/data/execute-query", {
- connection_name: config.name,
- database: config.database || "",
- sql,
- }), resolveTimeoutMs(options));
+ const result = await withTimeout(
+ bridgeDataRequest<BridgeQueryResult>("/data/execute-query", {
+ connection_name: config.name,
+ database: config.database || "",
+ sql,
+ }),
+ resolveTimeoutMs(options),
+ );
return convertBridgeQueryResult(result, options);
}
@@ -553,10 +558,7 @@ export async function listTables(config: ConnectionConfig, schema?: string): Pro
return collections.map((name) => ({ name, type: "COLLECTION" }));
}
if (config.db_type === "sqlite" || config.db_type === "rqlite") {
- const result = await query(
- config,
- `SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name`,
- );
+ const result = await query(config, `SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name`);
return result.rows.map((r) => ({ name: String(r.name || ""), type: String(r.type || "table") }));
}
if (!isDirectQueryType(config.db_type)) {
@@ -571,11 +573,7 @@ export async function listTables(config: ConnectionConfig, schema?: string): Pro
if (isMysqlType(config.db_type)) {
result = await query(config, `SELECT TABLE_NAME AS name, TABLE_TYPE AS type FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME`);
} else {
- result = await query(
- config,
- `SELECT table_name AS name, table_type AS type FROM information_schema.tables WHERE table_schema = $1 ORDER BY table_name`,
- [schema || "public"],
- );
+ result = await query(config, `SELECT table_name AS name, table_type AS type FROM information_schema.tables WHERE table_schema = $1 ORDER BY table_name`, [schema || "public"]);
}
return result.rows.map((r) => ({ name: String(r.name || r.NAME), type: String(r.type || r.TYPE || "TABLE") }));
}
@@ -636,14 +634,7 @@ export async function describeTable(config: ConnectionConfig, table: string, sch
}));
}
-async function mongoFindDocuments(
- config: ConnectionConfig,
- collection: string,
- skip: number,
- limit: number,
- filter: string,
- sort?: string,
-): Promise<MongoDocumentResult> {
+async function mongoFindDocuments(config: ConnectionConfig, collection: string, skip: number, limit: number, filter: string, sort?: string): Promise<MongoDocumentResult> {
return bridgeDataRequest<MongoDocumentResult>("/data/mongo/find-documents", {
connection_name: config.name,
database: config.database || "",
@@ -686,12 +677,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
return result.affected_rows;
}
-async function mongoAggregateDocuments(
- config: ConnectionConfig,
- collection: string,
- pipelineJson: string,
- maxRows: number,
-): Promise<MongoDocumentResult> {
+async function mongoAggregateDocuments(config: ConnectionConfig, collection: string, pipelineJson: string, maxRows: number): Promise<MongoDocumentResult> {
return bridgeDataRequest<MongoDocumentResult>("/data/mongo/aggregate-documents", {
connection_name: config.name,
database: config.database || "",
@@ -770,10 +756,7 @@ interface MongoGetIndexesCommand {
collection: string;
}
-export type MongoWriteCommand =
- | { kind: "insert"; collection: string; docsJson: string }
- | { kind: "update"; collection: string; filter: string; update: string; many: boolean }
- | { kind: "delete"; collection: string; filter: string; many: boolean };
+export type MongoWriteCommand = { kind: "insert"; collection: string; docsJson: string } | { kind: "update"; collection: string; filter: string; update: string; many: boolean } | { kind: "delete"; collection: string; filter: string; many: boolean };
export function parseMongoFindCommand(input: string): MongoFindCommand | null {
const source = input.trim().replace(/;$/, "").trim();
@@ -891,10 +874,7 @@ export function parseMongoWriteCommand(input: string): MongoWriteCommand | null
return null;
}
-export function evaluateMongoWriteSafety(
- command: MongoWriteCommand,
- options: { allowWrites?: boolean; allowDangerous?: boolean },
-): { allowed: boolean; reason?: string } {
+export function evaluateMongoWriteSafety(command: MongoWriteCommand, options: { allowWrites?: boolean; allowDangerous?: boolean }): { allowed: boolean; reason?: string } {
if (!options.allowWrites) {
return {
allowed: false,
@@ -910,10 +890,7 @@ export function evaluateMongoWriteSafety(
return { allowed: true };
}
-export function evaluateMongoAggregateSafety(
- command: MongoAggregateCommand,
- options: { allowWrites?: boolean; allowDangerous?: boolean },
-): { allowed: boolean; reason?: string } {
+export function evaluateMongoAggregateSafety(command: MongoAggregateCommand, options: { allowWrites?: boolean; allowDangerous?: boolean }): { allowed: boolean; reason?: string } {
const writeStage = mongoAggregateWriteStage(command.pipeline);
if (!writeStage) return { allowed: true };
if (!options.allowWrites) {
@@ -963,9 +940,7 @@ function readChainedIntegerArgument(chain: string, method: string, fallback: num
}
function normalizeJsonArgument(arg: string): string | null {
- const value = quoteUnquotedObjectKeys(
- convertSingleQuotedStrings((arg.trim() || "{}").replace(/ObjectId\s*\(\s*["']([^"']+)["']\s*\)/g, '{"$oid":"$1"}')),
- );
+ const value = quoteUnquotedObjectKeys(convertSingleQuotedStrings((arg.trim() || "{}").replace(/ObjectId\s*\(\s*["']([^"']+)["']\s*\)/g, '{"$oid":"$1"}')));
try {
JSON.parse(value);
return value;
diff --git a/packages/node-core/src/diagnostics.ts b/packages/node-core/src/diagnostics.ts
index 94a44113a9..85d519982e 100644
--- a/packages/node-core/src/diagnostics.ts
+++ b/packages/node-core/src/diagnostics.ts
@@ -2,18 +2,7 @@ import { access, readFile } from "node:fs/promises";
import { bridgePortFilePath, dbPath, appDataDir } from "./paths.js";
import { inspectConnectionStore } from "./connections.js";
-export const DIRECT_QUERY_TYPES = [
- "postgres",
- "redshift",
- "mysql",
- "doris",
- "starrocks",
- "sqlite",
- "rqlite",
- "gaussdb",
- "kwdb",
- "opengauss",
-] as const;
+export const DIRECT_QUERY_TYPES = ["postgres", "redshift", "mysql", "doris", "starrocks", "sqlite", "rqlite", "gaussdb", "kwdb", "opengauss"] as const;
export type DirectQueryType = (typeof DIRECT_QUERY_TYPES)[number];
@@ -105,9 +94,7 @@ export async function getDbxDiagnostics(): Promise<DbxDiagnostics> {
loadConnectionsOk: connectionStore.loadConnectionsOk,
loadedConnectionCount: connectionStore.loadedConnectionCount,
loadConnectionsError: connectionStore.loadConnectionsError,
- loadConnectionsHint: connectionStore.loadConnectionsError
- ? connectionStoreHint(connectionStore.loadConnectionsError)
- : undefined,
+ loadConnectionsHint: connectionStore.loadConnectionsError ? connectionStoreHint(connectionStore.loadConnectionsError) : undefined,
bridgePortFile: portFile,
bridgePortFileExists,
bridgeUrl,
diff --git a/packages/node-core/src/schema-context.ts b/packages/node-core/src/schema-context.ts
index 0edaa3d3f5..b9f847ff45 100644
--- a/packages/node-core/src/schema-context.ts
+++ b/packages/node-core/src/schema-context.ts
@@ -28,17 +28,11 @@ export interface SchemaContext {
const DEFAULT_MAX_TABLES = 8;
-export async function buildSchemaContext(
- backend: SchemaContextBackend,
- config: ConnectionConfig,
- options: SchemaContextOptions = {},
-): Promise<SchemaContext> {
+export async function buildSchemaContext(backend: SchemaContextBackend, config: ConnectionConfig, options: SchemaContextOptions = {}): Promise<SchemaContext> {
const maxTables = Math.max(1, Math.min(options.maxTables ?? DEFAULT_MAX_TABLES, 20));
const availableTables = await backend.listTables(config, options.schema);
const requested = new Set((options.tables ?? []).map((table) => table.toLowerCase()));
- const selected = requested.size
- ? availableTables.filter((table) => requested.has(table.name.toLowerCase()))
- : availableTables.slice(0, maxTables);
+ const selected = requested.size ? availableTables.filter((table) => requested.has(table.name.toLowerCase())) : availableTables.slice(0, maxTables);
const limited = selected.slice(0, maxTables);
const tables = await Promise.all(
@@ -59,19 +53,10 @@ export async function buildSchemaContext(
}
export function formatSchemaContext(context: SchemaContext): string {
- const header = [
- `Connection: ${context.connection}`,
- context.database ? `Database: ${context.database}` : "",
- context.schema ? `Schema: ${context.schema}` : "",
- ].filter(Boolean);
+ const header = [`Connection: ${context.connection}`, context.database ? `Database: ${context.database}` : "", context.schema ? `Schema: ${context.schema}` : ""].filter(Boolean);
const sections = context.tables.map((table) => {
const lines = table.columns.map((column) => {
- const parts = [
- column.name,
- column.data_type,
- column.is_nullable ? "NULL" : "NOT NULL",
- column.is_primary_key ? "PK" : "",
- ].filter(Boolean);
+ const parts = [column.name, column.data_type, column.is_nullable ? "NULL" : "NOT NULL", column.is_primary_key ? "PK" : ""].filter(Boolean);
return `- ${parts.join(" ")}${column.comment ? ` -- ${column.comment}` : ""}`;
});
return [`## ${table.name}`, `Type: ${table.type}`, ...lines].join("\n");
@@ -79,4 +64,3 @@ export function formatSchemaContext(context: SchemaContext): string {
const suffix = context.truncated ? "\n\nNote: table list was truncated; request specific table names for more context." : "";
return `${header.join("\n")}\n\n${sections.join("\n\n")}${suffix}`;
}
-
diff --git a/packages/node-core/src/web-backend.ts b/packages/node-core/src/web-backend.ts
index 2d27cc9b96..e2c2c0a3bf 100644
--- a/packages/node-core/src/web-backend.ts
+++ b/packages/node-core/src/web-backend.ts
@@ -1,17 +1,6 @@
import type { ConnectionConfig } from "./connections.js";
import type { TableInfo, ColumnInfo, QueryOptions, QueryResult } from "./database.js";
-import {
- evaluateMongoAggregateSafety,
- evaluateMongoWriteSafety,
- inferMongoColumns,
- mongoDocumentsToQueryResult,
- parseMongoAggregateCommand,
- parseMongoCountDocumentsCommand,
- parseMongoFindCommand,
- parseMongoGetIndexesCommand,
- parseMongoWriteCommand,
- type MongoWriteCommand,
-} from "./database.js";
+import { evaluateMongoAggregateSafety, evaluateMongoWriteSafety, inferMongoColumns, mongoDocumentsToQueryResult, parseMongoAggregateCommand, parseMongoCountDocumentsCommand, parseMongoFindCommand, parseMongoGetIndexesCommand, parseMongoWriteCommand, type MongoWriteCommand } from "./database.js";
import { sqlSafetyFromEnv } from "./sql-safety.js";
const baseUrl = process.env.DBX_WEB_URL!.replace(/\/+$/, "");
@@ -211,9 +200,7 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
const affected = await executeMongoWrite(config, write);
return { columns: [], rows: [], row_count: affected };
}
- throw new Error(
- "Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.getIndexes(), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})",
- );
+ throw new Error("Use MongoDB shell-style commands, for example: db.projects.find({}).limit(100), db.projects.countDocuments({}), db.projects.getIndexes(), db.projects.insertOne({...}), db.projects.updateOne({...}, {$set: {...}}), or db.projects.deleteOne({...})");
}
const res = await apiFetch("/api/query/execute", {
method: "POST",
diff --git a/packages/node-core/tests/format.test.ts b/packages/node-core/tests/format.test.ts
index ec3e3bd39e..bfa21a49fa 100644
--- a/packages/node-core/tests/format.test.ts
+++ b/packages/node-core/tests/format.test.ts
@@ -9,6 +9,6 @@ test("formats markdown tables", () => {
test("formats database cell values", () => {
assert.equal(formatCell(null), "NULL");
assert.equal(formatCell(undefined), "NULL");
- assert.equal(formatCell({ ok: true }), "{\"ok\":true}");
+ assert.equal(formatCell({ ok: true }), '{"ok":true}');
assert.equal(formatCell("hello"), "hello");
});
diff --git a/packages/node-core/tests/mongo-query.test.ts b/packages/node-core/tests/mongo-query.test.ts
index 2b5fb737f5..4a9cd59a87 100644
--- a/packages/node-core/tests/mongo-query.test.ts
+++ b/packages/node-core/tests/mongo-query.test.ts
@@ -1,16 +1,6 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import {
- executeQuery,
- inferMongoColumns,
- mongoAggregateWriteStage,
- mongoDocumentsToQueryResult,
- parseMongoAggregateCommand,
- parseMongoCountDocumentsCommand,
- parseMongoFindCommand,
- parseMongoGetIndexesCommand,
- parseMongoWriteCommand,
-} from "../src/database.js";
+import { executeQuery, inferMongoColumns, mongoAggregateWriteStage, mongoDocumentsToQueryResult, parseMongoAggregateCommand, parseMongoCountDocumentsCommand, parseMongoFindCommand, parseMongoGetIndexesCommand, parseMongoWriteCommand } from "../src/database.js";
test("parseMongoFindCommand accepts shell-style find commands", () => {
assert.deepEqual(parseMongoFindCommand('db.getCollection("operation_logs").find({"level":"info"}).sort({"ts":-1}).skip(5).limit(10)'), {
@@ -88,10 +78,7 @@ test("mongodb executeQuery blocks aggregate write stages until dangerous SQL is
ssl: false,
} as const;
- await assert.rejects(
- executeQuery(config, 'db.projects.aggregate([{"$merge":{"into":"projects_dump"}}])'),
- /DBX_MCP_ALLOW_DANGEROUS_SQL=1/,
- );
+ await assert.rejects(executeQuery(config, 'db.projects.aggregate([{"$merge":{"into":"projects_dump"}}])'), /DBX_MCP_ALLOW_DANGEROUS_SQL=1/);
if (oldAllowWrites === undefined) delete process.env.DBX_MCP_ALLOW_WRITES;
else process.env.DBX_MCP_ALLOW_WRITES = oldAllowWrites;
@@ -146,33 +133,48 @@ test("mongodb executeQuery blocks writes when writes are explicitly disabled", a
});
test("mongoDocumentsToQueryResult turns documents into rows", () => {
- assert.deepEqual(mongoDocumentsToQueryResult([{ _id: "1", nested: { ok: true } }, { _id: "2", name: "demo" }], 2), {
- columns: ["_id", "nested", "name"],
- rows: [
- { _id: "1", nested: '{"ok":true}', name: undefined },
- { _id: "2", nested: undefined, name: "demo" },
- ],
- row_count: 2,
- });
+ assert.deepEqual(
+ mongoDocumentsToQueryResult(
+ [
+ { _id: "1", nested: { ok: true } },
+ { _id: "2", name: "demo" },
+ ],
+ 2,
+ ),
+ {
+ columns: ["_id", "nested", "name"],
+ rows: [
+ { _id: "1", nested: '{"ok":true}', name: undefined },
+ { _id: "2", nested: undefined, name: "demo" },
+ ],
+ row_count: 2,
+ },
+ );
});
test("inferMongoColumns marks _id as primary and reports observed types", () => {
- assert.deepEqual(inferMongoColumns([{ _id: "1", active: true }, { _id: "2", active: null }]), [
- {
- name: "_id",
- data_type: "string",
- is_nullable: false,
- column_default: null,
- is_primary_key: true,
- comment: null,
- },
- {
- name: "active",
- data_type: "boolean | null",
- is_nullable: true,
- column_default: null,
- is_primary_key: false,
- comment: null,
- },
- ]);
+ assert.deepEqual(
+ inferMongoColumns([
+ { _id: "1", active: true },
+ { _id: "2", active: null },
+ ]),
+ [
+ {
+ name: "_id",
+ data_type: "string",
+ is_nullable: false,
+ column_default: null,
+ is_primary_key: true,
+ comment: null,
+ },
+ {
+ name: "active",
+ data_type: "boolean | null",
+ is_nullable: true,
+ column_default: null,
+ is_primary_key: false,
+ comment: null,
+ },
+ ],
+ );
});
diff --git a/packages/node-core/tests/rqlite-direct.test.ts b/packages/node-core/tests/rqlite-direct.test.ts
index 306e05f4f8..5832738d12 100644
--- a/packages/node-core/tests/rqlite-direct.test.ts
+++ b/packages/node-core/tests/rqlite-direct.test.ts
@@ -47,7 +47,17 @@ test("executes rqlite query through the HTTP API", async () => {
assert.equal(req.url, "/db/query");
assert.equal(req.headers.authorization, "Basic ZGJ4OnNlY3JldA==");
assert.deepEqual(JSON.parse(body), ["select id, name from users"]);
- json(res, { results: [{ columns: ["id", "name"], values: [[1, "Ada"], [2, "Linus"]] }] });
+ json(res, {
+ results: [
+ {
+ columns: ["id", "name"],
+ values: [
+ [1, "Ada"],
+ [2, "Linus"],
+ ],
+ },
+ ],
+ });
});
try {
@@ -62,7 +72,17 @@ test("lists rqlite tables and describes columns", async () => {
const server = await withRqliteServer((_req, res, body) => {
const sql = JSON.parse(body)[0] as string;
if (sql.includes("sqlite_master")) {
- json(res, { results: [{ columns: ["name", "type"], values: [["users", "table"], ["active_users", "view"]] }] });
+ json(res, {
+ results: [
+ {
+ columns: ["name", "type"],
+ values: [
+ ["users", "table"],
+ ["active_users", "view"],
+ ],
+ },
+ ],
+ });
return;
}
if (sql.includes("PRAGMA table_info")) {
diff --git a/packages/node-core/tests/schema-context.test.ts b/packages/node-core/tests/schema-context.test.ts
index 072185c520..ff96db02d4 100644
--- a/packages/node-core/tests/schema-context.test.ts
+++ b/packages/node-core/tests/schema-context.test.ts
@@ -85,4 +85,3 @@ test("formats schema context as compact markdown", async () => {
assert.match(markdown, /id integer NOT NULL PK/);
assert.match(markdown, /email text NOT NULL -- Login email/);
});
-
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index b46192451a..46732dcc67 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -2,9 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "enables the default permissions",
- "windows": [
- "main"
- ],
+ "windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-show",
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 5c1c3ef14d..13275febbe 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -60,13 +60,7 @@
"template": "windows/nsis/installer.nsi"
}
},
- "icon": [
- "icons/32x32.png",
- "icons/128x128.png",
- "icons/icon.icns",
- "icons/icon.ico"
- ]
+ "icon": ["icons/32x32.png", "icons/128x128.png", "icons/[email protected]", "icons/icon.icns", "icons/icon.ico"]
},
"plugins": {
"deep-link": {
@@ -76,10 +70,7 @@
},
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDkxNEYyMzE3QkJCNkM3REYKUldUZng3YTdGeU5Qa1NnTUZCRVhJVkxsOWZKQWFPVCtacUgySlNlcjRDU2RmZElCQnphd25pYUMK",
- "endpoints": [
- "https://dl.dbxio.com/releases/latest/latest.json",
- "https://github.com/t8y2/dbx/releases/latest/download/latest.json"
- ]
+ "endpoints": ["https://dl.dbxio.com/releases/latest/latest.json", "https://github.com/t8y2/dbx/releases/latest/download/latest.json"]
}
}
}
diff --git a/vitest.config.ts b/vitest.config.ts
index df4e5f19a5..2c17f5186d 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -8,11 +8,6 @@ export default defineConfig({
},
},
test: {
- include: [
- "packages/app-tests/*.test.ts",
- "packages/node-core/tests/*.test.ts",
- "apps/desktop/src/**/*.spec.ts",
- "docs/lib/*.test.ts",
- ],
+ include: ["packages/app-tests/*.test.ts", "packages/node-core/tests/*.test.ts", "apps/desktop/src/**/*.spec.ts", "docs/lib/*.test.ts"],
},
});