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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(docs): database documentation viewer and DBML export
Fernando Possebonf30d59b989d9
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vueindex bb9fba16d7..c0ab86a8bf 100644--- a/apps/desktop/src/components/connection/ConnectionDialog.vue+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue@@ -298,6 +298,7 @@ const defaultForm = (): ConnectionForm => ({informix_server: "",external_config: undefined,init_script: undefined,+ docs_notes_path: undefined,read_only: false,show_system_schemas: false,is_production: false,@@ -2273,6 +2274,7 @@ watch(external_config: config.external_config,attached_databases: config.attached_databases || [],init_script: config.init_script,+ docs_notes_path: config.docs_notes_path,read_only: config.read_only || false,show_system_schemas: config.show_system_schemas || false,is_production: config.is_production || false,@@ -7337,6 +7339,17 @@ function openExternalUrl(url: string) {<span class="text-xs text-muted-foreground">{{ t("connection.showSystemSchemasHint") }}</span></label></div>+ <!-- Documentation notes are a relational-only feature, so this+ follows the same isSchemaAware gate as the row above. -->+ <div v-if="isSchemaAware(form.db_type)" class="grid grid-cols-4 items-start gap-4">+ <Label :class="connectionLabelTopClass">{{ t("connection.docsNotesPath") }}</Label>+ <div class="col-span-3 space-y-1">+ <Input v-model="form.docs_notes_path" :placeholder="t('connection.docsNotesPathPlaceholder')" spellcheck="false" />+ <p class="text-xs text-muted-foreground">+ {{ t("connection.docsNotesPathHint") }}+ </p>+ </div>+ </div><div class="grid grid-cols-4 items-start gap-4 rounded-[6px] border border-red-500/25 bg-red-500/[0.035] px-3 py-2.5"><Label :class="[connectionLabelSmallClass, 'pt-0.5 text-red-700 dark:text-red-300']"><span class="inline-flex items-center justify-end gap-1"><ShieldAlert class="h-3.5 w-3.5" />PROD</span>diff --git a/apps/desktop/src/components/docs/DatabaseDocsDialog.vue b/apps/desktop/src/components/docs/DatabaseDocsDialog.vuenew file mode 100644index 0000000000..1ae2616975--- /dev/null+++ b/apps/desktop/src/components/docs/DatabaseDocsDialog.vue@@ -0,0 +1,196 @@+<script setup lang="ts">+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Network } from "@lucide/vue";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import DocsApp from "@/docs/DocsApp.vue";+import { emptyAnnotations, removeGroup, setColumnNote, setProjectNote, setTableGroup, setTableNote, upsertGroup } from "@/docs/annotationEdits";+import type { AnnotationFile, DocsEdit, SchemaSnapshot } from "@/docs/types";+import type { Translate } from "@/docs/docsWarnings";+import * as api from "@/lib/backend/api";+import { useConnectionStore } from "@/stores/connectionStore";+import { createAutosave } from "./docsAutosave";++const props = defineProps<{+ prefillConnectionId?: string;+ prefillDatabase?: string;+ prefillSchema?: string;+}>();++const open = defineModel<boolean>("open", { default: false });++// This component lives OUTSIDE src/docs/, so it may and must use useI18n():+// it is what supplies the `translate` prop that the viewer components need,+// since they are banned from importing vue-i18n themselves.+const { t } = useI18n();++// `Translate` is one narrow signature; vue-i18n's `t` is heavily overloaded and+// does not assign to it directly, so bridge it explicitly.+const translate: Translate = (key, params) => (params === undefined ? t(key) : t(key, params));++const connectionStore = useConnectionStore();++/** The snapshot as collected, kept so every edit can re-derive the merged view. */+const rawSnapshot = ref<SchemaSnapshot | null>(null);+const snapshot = ref<SchemaSnapshot | null>(null);+const annotations = ref<AnnotationFile>(emptyAnnotations());+const loading = ref(false);+const loadError = ref<string | null>(null);++/**+ * Guards against a slow re-derivation landing after a newer one. Each load or+ * edit takes the next number and only writes if it is still the latest, so a+ * fast second edit is never overwritten by the first edit's stale response.+ */+let generation = 0;++const autosave = createAutosave(async (file) => {+ const connectionId = props.prefillConnectionId;+ if (connectionId === undefined || connectionId === "") {+ return;+ }+ await api.saveDocsAnnotations(connectionId, file);+}, 500);++const status = autosave.status;++const statusLabel = computed(() => {+ switch (status.value.state) {+ case "saving":+ return t("docs.saving");+ case "saved":+ return t("docs.saved");+ case "failed":+ return t("docs.saveFailed", { error: status.value.message });+ default:+ return "";+ }+});++const canOpenDiagram = computed(() => (props.prefillConnectionId ?? "") !== "" && (props.prefillDatabase ?? "") !== "");++async function load(): Promise<void> {+ const connectionId = props.prefillConnectionId;+ const database = props.prefillDatabase;+ if (connectionId === undefined || connectionId === "" || database === undefined || database === "") {+ return;+ }+ const mine = ++generation;+ loading.value = true;+ loadError.value = null;+ try {+ // An absent schema means "everything the collector finds" rather than a+ // filter naming nothing.+ const schemas = props.prefillSchema ? [props.prefillSchema] : [];+ const collected = await api.collectDocsSnapshot(connectionId, database, schemas, [], database);+ const file = (await api.loadDocsAnnotations(connectionId)) ?? emptyAnnotations();+ const merged = await api.applyDocsAnnotations(connectionId, collected, file);+ if (mine !== generation) {+ return;+ }+ rawSnapshot.value = collected;+ annotations.value = file;+ snapshot.value = merged;+ } catch (error) {+ if (mine === generation) {+ loadError.value = error instanceof Error ? error.message : String(error);+ }+ } finally {+ if (mine === generation) {+ loading.value = false;+ }+ }+}++function nextAnnotations(file: AnnotationFile, edit: DocsEdit): AnnotationFile {+ switch (edit.kind) {+ case "projectNote":+ return setProjectNote(file, edit.note);+ case "tableNote":+ return setTableNote(file, edit.tableKey, edit.note);+ case "columnNote":+ return setColumnNote(file, edit.tableKey, edit.column, edit.note);+ case "tableGroup":+ return setTableGroup(file, edit.tableKey, edit.groupId);+ case "upsertGroup":+ return upsertGroup(file, edit.group);+ case "removeGroup":+ return removeGroup(file, edit.groupId);+ }+}++async function onEdit(edit: DocsEdit): Promise<void> {+ const connectionId = props.prefillConnectionId;+ const collected = rawSnapshot.value;+ if (connectionId === undefined || connectionId === "" || collected === null) {+ return;+ }+ const file = nextAnnotations(annotations.value, edit);+ annotations.value = file;+ // Schedule before re-deriving: the write must not wait on a display refresh.+ autosave.schedule(file);++ const mine = ++generation;+ try {+ const merged = await api.applyDocsAnnotations(connectionId, collected, file);+ if (mine === generation) {+ snapshot.value = merged;+ }+ } catch (error) {+ if (mine === generation) {+ loadError.value = error instanceof Error ? error.message : String(error);+ }+ }+}++function openDiagram(): void {+ const connectionId = props.prefillConnectionId;+ const database = props.prefillDatabase;+ if (connectionId === undefined || database === undefined) {+ return;+ }+ connectionStore.diagramSource = { connectionId, database, schema: props.prefillSchema };+}++watch(+ open,+ (isOpen, wasOpen) => {+ if (isOpen) {+ void load();+ return;+ }+ if (wasOpen) {+ // A note typed a moment before closing is still sitting behind the+ // debounce; flushing here is what keeps it.+ void autosave.flush();+ }+ },+ { immediate: true },+);+</script>++<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">+ <DialogHeader class="px-4 py-3 border-b">+ <DialogTitle class="flex items-center gap-2">+ <span>{{ t("docs.title") }}</span>+ <span v-if="statusLabel" class="text-xs font-normal" :class="status.state === 'failed' ? 'text-destructive' : 'text-muted-foreground'">+ {{ statusLabel }}+ </span>+ <Button v-if="canOpenDiagram" variant="outline" size="sm" class="ml-auto" @click="openDiagram()">+ <Network class="w-4 h-4" />+ {{ t("docs.openDiagram") }}+ </Button>+ </DialogTitle>+ </DialogHeader>++ <div class="min-h-0 flex-1 overflow-hidden">+ <p v-if="loadError" class="p-4 text-sm text-destructive">{{ loadError }}</p>+ <p v-else-if="loading || snapshot === null" class="p-4 text-sm text-muted-foreground">{{ t("common.loading") }}</p>+ <DocsApp v-else :snapshot="snapshot" :annotations="annotations" :readonly="false" :translate="translate" @edit="onEdit" />+ </div>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/docs/__tests__/docsAutosave.spec.ts b/apps/desktop/src/components/docs/__tests__/docsAutosave.spec.tsnew file mode 100644index 0000000000..cd5c189f5f--- /dev/null+++ b/apps/desktop/src/components/docs/__tests__/docsAutosave.spec.ts@@ -0,0 +1,76 @@+import { describe, expect, it, vi } from "vitest";+import { createAutosave } from "../docsAutosave";++const file = { formatVersion: 1 } as const;++describe("createAutosave", () => {+ it("coalesces rapid edits into one save", async () => {+ vi.useFakeTimers();+ const save = vi.fn().mockResolvedValue(undefined);+ const autosave = createAutosave(save, 500);++ autosave.schedule(file);+ autosave.schedule(file);+ autosave.schedule(file);+ expect(save).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(500);+ expect(save).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it("surfaces a failure instead of swallowing it", async () => {+ // A silently swallowed write failure is the worst outcome this feature+ // can produce: the user keeps typing and believes their notes are saved.+ vi.useFakeTimers();+ const save = vi.fn().mockRejectedValue(new Error("disk full"));+ const autosave = createAutosave(save, 500);++ autosave.schedule(file);+ await vi.advanceTimersByTimeAsync(500);++ expect(autosave.status.value.state).toBe("failed");+ expect(autosave.status.value.message).toContain("disk full");+ vi.useRealTimers();+ });++ it("reports saved after a successful write", async () => {+ vi.useFakeTimers();+ const autosave = createAutosave(vi.fn().mockResolvedValue(undefined), 500);+ autosave.schedule(file);+ await vi.advanceTimersByTimeAsync(500);+ expect(autosave.status.value.state).toBe("saved");+ vi.useRealTimers();+ });++ it("never runs two saves concurrently", async () => {+ // flush() clears the timer, but a debounced write may already be awaiting+ // save. Starting a second one issues two concurrent writes of the same+ // file — a wasted round trip, a stale-write race, and the exact+ // concurrency that corrupts the notes file.+ let concurrent = 0;+ let maxConcurrent = 0;+ const save = vi.fn().mockImplementation(async () => {+ concurrent += 1;+ maxConcurrent = Math.max(maxConcurrent, concurrent);+ await new Promise((resolve) => setTimeout(resolve, 10));+ concurrent -= 1;+ });++ const autosave = createAutosave(save, 0);+ autosave.schedule(file);+ await Promise.all([autosave.flush(), autosave.flush(), autosave.flush()]);++ expect(maxConcurrent).toBe(1);+ });++ it("flush writes immediately without waiting for the timer", async () => {+ // The dialog calls this on close, so a note typed a moment earlier is+ // not lost to a pending debounce.+ const save = vi.fn().mockResolvedValue(undefined);+ const autosave = createAutosave(save, 500);+ autosave.schedule(file);+ await autosave.flush();+ expect(save).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/components/docs/docsAutosave.ts b/apps/desktop/src/components/docs/docsAutosave.tsnew file mode 100644index 0000000000..bba185aca2--- /dev/null+++ b/apps/desktop/src/components/docs/docsAutosave.ts@@ -0,0 +1,83 @@+import { ref, type Ref } from "vue";+import type { AnnotationFile } from "@/docs/types";++export type SaveStatus = { state: "idle" } | { state: "saving" } | { state: "saved" } | { state: "failed"; message: string };++export interface Autosave {+ schedule: (file: AnnotationFile) => void;+ flush: () => Promise<void>;+ status: Ref<SaveStatus>;+}++/**+ * Debounced autosave.+ *+ * A failed write MUST become visible: the user keeps typing and believes+ * their notes are saved otherwise. The pending file is retained on failure so+ * the next edit retries rather than discarding what they wrote.+ */+export function createAutosave(save: (file: AnnotationFile) => Promise<void>, delayMs: number): Autosave {+ const status = ref<SaveStatus>({ state: "idle" });+ let timer: ReturnType<typeof setTimeout> | undefined;+ let pending: AnnotationFile | undefined;+ // The write currently in flight, if any. `flush()` clearing the timer is not+ // enough: a debounced write may already be awaiting `save`, and starting a+ // second one issues two concurrent saves of the same file. Beyond wasting a+ // round trip, the later one can land stale, and it is the exact concurrency+ // that corrupted the notes file before the Rust side used a unique temp path.+ let inFlight: Promise<void> | undefined;++ async function write(): Promise<void> {+ if (inFlight !== undefined) {+ // Wait for the current write, then run again if an edit arrived while it+ // was going — never two at once.+ await inFlight;+ if (pending === undefined) {+ return;+ }+ }+ if (pending === undefined) {+ return;+ }+ const file = pending;+ status.value = { state: "saving" };+ const attempt = (async () => {+ try {+ await save(file);+ // Only clear if no newer edit arrived while this was in flight.+ if (pending === file) {+ pending = undefined;+ }+ status.value = { state: "saved" };+ } catch (error) {+ status.value = { state: "failed", message: error instanceof Error ? error.message : String(error) };+ }+ })();+ inFlight = attempt;+ try {+ await attempt;+ } finally {+ if (inFlight === attempt) {+ inFlight = undefined;+ }+ }+ }++ return {+ status,+ schedule(file) {+ pending = file;+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ timer = setTimeout(() => void write(), delayMs);+ },+ async flush() {+ if (timer !== undefined) {+ clearTimeout(timer);+ timer = undefined;+ }+ await write();+ },+ };+}diff --git a/apps/desktop/src/components/layout/AppDialogs.vue b/apps/desktop/src/components/layout/AppDialogs.vueindex a42616efad..87215ba232 100644--- a/apps/desktop/src/components/layout/AppDialogs.vue+++ b/apps/desktop/src/components/layout/AppDialogs.vue@@ -11,6 +11,7 @@ const SchemaDiffDialog = defineAsyncComponent(() => import("@/components/diff/Scconst DataCompareDialog = defineAsyncComponent(() => import("@/components/diff/DataCompareDialog.vue"));const SqlFileExecutionDialog = defineAsyncComponent(() => import("@/components/sql-file/SqlFileExecutionDialog.vue"));const SchemaDiagramDialog = defineAsyncComponent(() => import("@/components/diagram/SchemaDiagramDialog.vue"));+const DatabaseDocsDialog = defineAsyncComponent(() => import("@/components/docs/DatabaseDocsDialog.vue"));const TableImportDialog = defineAsyncComponent(() => import("@/components/import/TableImportDialog.vue"));const FieldLineageDialog = defineAsyncComponent(() => import("@/components/lineage/FieldLineageDialog.vue"));const ConfigPassphraseDialog = defineAsyncComponent(() => import("@/components/config/ConfigPassphraseDialog.vue"));@@ -204,6 +205,7 @@ watch(:focus-table-name="dialogs.diagramFocusTableName.value"@open-target="emit('openDiagramTarget', $event)"/>+ <DatabaseDocsDialog v-if="dialogs.showDocsDialog.value" v-model:open="dialogs.showDocsDialog.value" :prefill-connection-id="dialogs.docsPrefillConnectionId.value" :prefill-database="dialogs.docsPrefillDatabase.value" :prefill-schema="dialogs.docsPrefillSchema.value" /><TableImportDialogv-if="dialogs.showTableImportDialog.value"v-model:open="dialogs.showTableImportDialog.value"diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 92e6f99301..50ec827beb 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -6,6 +6,7 @@ import {ArrowDown,ArrowRightLeft,ArrowUp,+ BookOpen,Braces,CheckSquare,Clipboard,@@ -1461,6 +1462,16 @@ function openDiagram(row: ObjectBrowserRow) {};}+function openDocs(row: ObjectBrowserRow) {+ // The docs viewer documents the whole schema rather than one object, so the+ // row only supplies which schema to collect.+ connectionStore.docsSource = {+ connectionId: props.connection.id,+ database: props.database,+ schema: row.schema || selectedSchema.value,+ };+}+function openTableImport(row: ObjectBrowserRow) {if (row.type !== "TABLE") return;connectionStore.tableImportSource = {@@ -2651,7 +2662,12 @@ function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {...(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 }] : []),+ ...(canOpenDiagram.value+ ? [+ { label: t("diagram.open"), action: () => openDiagram(item), icon: Network },+ { label: t("docs.title"), action: () => openDocs(item), icon: BookOpen },+ ]+ : []),...(canOpenTableImport.value ? [{ label: t("contextMenu.importData"), action: () => openTableImport(item), icon: Download }] : []),{ label: t("dataCompare.title"), action: () => openDataCompare(item), icon: ArrowRightLeft },{ label: "", separator: true },@@ -2701,7 +2717,12 @@ function getViewMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {},...(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 }] : []),+ ...(canOpenDiagram.value+ ? [+ { label: t("diagram.open"), action: () => openDiagram(item), icon: Network },+ { label: t("docs.title"), action: () => openDocs(item), icon: BookOpen },+ ]+ : []),{ label: "", separator: true },exportDataSubmenu(item),{ label: t("contextMenu.exportDatabase"), action: () => openDatabaseExport(item), icon: Upload },diff --git a/apps/desktop/src/composables/useDialogSources.ts b/apps/desktop/src/composables/useDialogSources.tsindex b185b71d24..994eb09366 100644--- a/apps/desktop/src/composables/useDialogSources.ts+++ b/apps/desktop/src/composables/useDialogSources.ts@@ -9,6 +9,7 @@ const showSchemaDiffDialog = ref(false);const showDataCompareDialog = ref(false);const showSqlFileDialog = ref(false);const showDiagramDialog = ref(false);+const showDocsDialog = ref(false);const showTableImportDialog = ref(false);const showTableDataGenerateDialog = ref(false);const showFieldLineageDialog = ref(false);@@ -43,6 +44,9 @@ const diagramPrefillConnectionId = ref("");const diagramPrefillDatabase = ref("");const diagramPrefillSchema = ref("");const diagramFocusTableName = ref("");+const docsPrefillConnectionId = ref("");+const docsPrefillDatabase = ref("");+const docsPrefillSchema = ref("");const tableImportPrefillConnectionId = ref("");const tableImportPrefillDatabase = ref("");const tableImportPrefillSchema = ref("");@@ -173,6 +177,21 @@ export function useDialogSources() {},);+ watch(+ () => connectionStore.docsSource,+ (v) => {+ if (v) {+ docsPrefillConnectionId.value = v.connectionId;+ docsPrefillDatabase.value = v.database;+ docsPrefillSchema.value = v.schema ?? "";+ showDocsDialog.value = true;+ // Clearing the source is what makes the dialog re-openable: setting+ // the same value twice would not re-trigger this watcher.+ connectionStore.docsSource = null;+ }+ },+ );+watch(() => connectionStore.tableImportSource,(v) => {@@ -321,6 +340,7 @@ export function useDialogSources() {showDataCompareDialog,showSqlFileDialog,showDiagramDialog,+ showDocsDialog,showTableImportDialog,showTableDataGenerateDialog,showFieldLineageDialog,@@ -354,6 +374,9 @@ export function useDialogSources() {diagramPrefillDatabase,diagramPrefillSchema,diagramFocusTableName,+ docsPrefillConnectionId,+ docsPrefillDatabase,+ docsPrefillSchema,tableImportPrefillConnectionId,tableImportPrefillDatabase,tableImportPrefillSchema,diff --git a/apps/desktop/src/docs/DocsApp.vue b/apps/desktop/src/docs/DocsApp.vuenew file mode 100644index 0000000000..52b5f4ef29--- /dev/null+++ b/apps/desktop/src/docs/DocsApp.vue@@ -0,0 +1,153 @@+<script setup lang="ts">+import { computed, ref } from "vue";+import DocsSearch from "./components/DocsSearch.vue";+import DocsSidebar from "./components/DocsSidebar.vue";+import EnumPage from "./components/EnumPage.vue";+import GroupEditor from "./components/GroupEditor.vue";+import NoteEditor from "./components/NoteEditor.vue";+import TablePage from "./components/TablePage.vue";+import WarningBanner from "./components/WarningBanner.vue";+import WikiIndex from "./components/WikiIndex.vue";+import "./docs.css";+import type { Translate } from "./docsWarnings";+import { qualifiedTableKey } from "./docsKeys";+import { groupBySchema, groupByTableGroup } from "./docsIndex";+import type { AnnotationFile, DocsEdit, GroupAnnotation, SchemaSnapshot } from "./types";++const props = defineProps<{+ snapshot: SchemaSnapshot;+ /**+ * The local notes layer. `snapshot` already carries notes merged for display,+ * so this is here for what the merge erases: `groups` holds the editable+ * `GroupAnnotation` records, while `snapshot.groups` holds resolved+ * `TableGroup`s that GroupEditor and GroupPicker cannot write back to.+ */+ annotations: AnnotationFile;+ readonly?: boolean;+ translate: Translate;+}>();++const emit = defineEmits<{+ edit: [edit: DocsEdit];+}>();++/** `readonly` is the one optional prop; absent means editing is allowed. */+const isReadonly = computed(() => props.readonly ?? false);++const annotationGroups = computed<GroupAnnotation[]>(() => props.annotations.groups ?? []);++// Grouping is computed once here and handed to both the sidebar and the index,+// so the two can never disagree about what the sections are.+const mode = ref<"schema" | "group">(props.snapshot.groups.length > 0 ? "group" : "schema");+const activeKey = ref<string | null>(null);+const activeEnumName = ref<string | null>(null);++const sections = computed(() => (mode.value === "schema" ? groupBySchema(props.snapshot) : groupByTableGroup(props.snapshot)));++const activeTable = computed(() => props.snapshot.tables.find((table) => qualifiedTableKey(table) === activeKey.value) ?? null);++/**+ * Matched on the bare name because that is the only thing a column's+ * `data_type` can be compared against — `columnsUsingEnum` resolves enums the+ * same way, so both agree when one name appears in two schemas.+ */+const activeEnum = computed(() => (activeEnumName.value === null ? null : (props.snapshot.enums.find((value) => value.name === activeEnumName.value) ?? null)));++const view = computed<"index" | "table" | "enum">(() => {+ if (activeEnum.value !== null) {+ return "enum";+ }+ return activeTable.value === null ? "index" : "table";+});++const activeGroup = computed(() => {+ const groupId = activeTable.value?.groupId;+ if (!groupId) {+ return null;+ }+ return props.snapshot.groups.find((group) => group.id === groupId) ?? null;+});++function open(key: string): void {+ // A key naming no table leaves the reader where they are rather than+ // dropping them on a blank page.+ if (props.snapshot.tables.some((table) => qualifiedTableKey(table) === key)) {+ activeEnumName.value = null;+ activeKey.value = key;+ }+}++function openEnum(name: string): void {+ if (props.snapshot.enums.some((value) => value.name === name)) {+ activeKey.value = null;+ activeEnumName.value = name;+ }+}++function home(): void {+ activeKey.value = null;+ activeEnumName.value = null;+}++/**+ * GroupPicker asks for a new group without naming it, so the id and hue are+ * minted here. The hue rotates rather than repeating so two fresh groups are+ * visually distinct before anyone opens GroupEditor to choose a colour.+ */+function createGroupFor(tableKey: string): void {+ const group: GroupAnnotation = {+ id: crypto.randomUUID(),+ // Reuses the picker's own "New group" string rather than adding a locale+ // key for a placeholder the user renames immediately in GroupEditor.+ name: props.translate("docs.newGroup"),+ hue: (annotationGroups.value.length * 47) % 360,+ };+ emit("edit", { kind: "upsertGroup", group });+ emit("edit", { kind: "tableGroup", tableKey, groupId: group.id });+}+</script>++<template>+ <div class="flex h-full min-h-0 bg-background text-foreground">+ <DocsSidebar :sections="sections" :mode="mode" :active-key="activeKey" @update:mode="mode = $event" @select="open" @home="home()" />++ <main class="flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto p-4">+ <header class="flex flex-wrap items-start justify-between gap-3">+ <div class="flex flex-col gap-1">+ <h1 class="text-base font-semibold">{{ snapshot.project.name }}</h1>+ <p class="text-xs text-muted-foreground">+ {{ snapshot.project.databaseType }}<template v-if="snapshot.project.database"> · {{ snapshot.project.database }}</template> · {{ snapshot.tables.length }} tables · generated {{ snapshot.project.generatedAt }}+ </p>+ </div>+ <DocsSearch :snapshot="snapshot" @select="open" @select-enum="openEnum" />+ </header>++ <WarningBanner :warnings="snapshot.warnings" :translate="translate" />++ <div v-if="view === 'index'" class="flex flex-col gap-4">+ <NoteEditor :model-value="snapshot.project.note ?? ''" :readonly="isReadonly" :translate="translate" @update:model-value="emit('edit', { kind: 'projectNote', note: $event })" />+ <WikiIndex :sections="sections" @select="open" />++ <section v-if="!isReadonly && annotationGroups.length > 0" class="flex flex-col gap-2">+ <h2 class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Groups</h2>+ <GroupEditor v-for="group in annotationGroups" :key="group.id" :group="group" :translate="translate" @update:group="emit('edit', { kind: 'upsertGroup', group: $event })" @delete="emit('edit', { kind: 'removeGroup', groupId: $event })" />+ </section>+ </div>++ <TablePage+ v-else-if="view === 'table' && activeTable"+ :table="activeTable"+ :relationships="snapshot.relationships"+ :group="activeGroup"+ :annotation-groups="annotationGroups"+ :readonly="isReadonly"+ :translate="translate"+ @select="open"+ @edit="emit('edit', $event)"+ @create-group="createGroupFor"+ />++ <EnumPage v-else-if="activeEnum" :enum-type="activeEnum" :snapshot="snapshot" :translate="translate" @select="open" />+ </main>+ </div>+</template>diff --git a/apps/desktop/src/docs/__tests__/annotationEdits.spec.ts b/apps/desktop/src/docs/__tests__/annotationEdits.spec.tsnew file mode 100644index 0000000000..c56199e004--- /dev/null+++ b/apps/desktop/src/docs/__tests__/annotationEdits.spec.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import { emptyAnnotations, removeGroup, setColumnNote, setProjectNote, setTableGroup, setTableNote, upsertGroup } from "../annotationEdits";++const base = emptyAnnotations();++describe("annotationEdits", () => {+ it("starts from a valid empty file", () => {+ expect(emptyAnnotations()).toEqual({ formatVersion: 1 });+ });++ it("never mutates its input", () => {+ // Every function returns a new file. Mutating in place would make Vue's+ // reactivity miss the change and make undo impossible to add later.+ const before = JSON.stringify(base);+ setTableNote(base, "public.orders", "hello");+ expect(JSON.stringify(base)).toBe(before);+ });++ it("sets and clears a table note", () => {+ const withNote = setTableNote(base, "public.orders", "One row per checkout.");+ expect(withNote.tables?.["public.orders"].note).toBe("One row per checkout.");++ const cleared = setTableNote(withNote, "public.orders", " ");+ expect(cleared.tables?.["public.orders"]).toBeUndefined();+ });++ it("keeps a table entry when it still carries a group after the note clears", () => {+ // Dropping the whole entry here would silently unassign the group.+ const grouped = setTableGroup(setTableNote(base, "public.orders", "n"), "public.orders", "g1");+ const cleared = setTableNote(grouped, "public.orders", "");+ expect(cleared.tables?.["public.orders"].group).toBe("g1");+ expect(cleared.tables?.["public.orders"].note).toBeUndefined();+ });++ it("sets and clears a column note", () => {+ const withNote = setColumnNote(base, "public.orders", "status", "Lifecycle state.");+ expect(withNote.tables?.["public.orders"].columns?.status.note).toBe("Lifecycle state.");++ const cleared = setColumnNote(withNote, "public.orders", "status", "");+ expect(cleared.tables?.["public.orders"]).toBeUndefined();+ });++ it("upserts a group by id", () => {+ const created = upsertGroup(base, { id: "g1", name: "Core", hue: 28 });+ expect(created.groups).toEqual([{ id: "g1", name: "Core", hue: 28 }]);++ const renamed = upsertGroup(created, { id: "g1", name: "Core Accounts", hue: 200 });+ expect(renamed.groups).toHaveLength(1);+ expect(renamed.groups?.[0]).toEqual({ id: "g1", name: "Core Accounts", hue: 200 });+ });++ it("removing a group also clears every table that referenced it", () => {+ // A dangling groupId renders as no group at all, so the file would look+ // correct while carrying a reference to something that does not exist.+ const withGroup = setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1");+ const removed = removeGroup(withGroup, "g1");++ expect(removed.groups ?? []).toEqual([]);+ expect(removed.tables?.["public.orders"]).toBeUndefined();+ });++ it("removing a group keeps a table that still has a note", () => {+ const seeded = setTableNote(setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1"), "public.orders", "keep me");+ const removed = removeGroup(seeded, "g1");+ expect(removed.tables?.["public.orders"].note).toBe("keep me");+ expect(removed.tables?.["public.orders"].group).toBeUndefined();+ });++ it("sets and clears the project note", () => {+ const withNote = setProjectNote(base, "# Sales\n\nThe billing schema.");+ expect(withNote.project?.note).toBe("# Sales\n\nThe billing schema.");+ expect(setProjectNote(withNote, "").project).toBeUndefined();+ });+});diff --git a/apps/desktop/src/docs/__tests__/annotationTypes.spec.ts b/apps/desktop/src/docs/__tests__/annotationTypes.spec.tsnew file mode 100644index 0000000000..4a920b6f9c--- /dev/null+++ b/apps/desktop/src/docs/__tests__/annotationTypes.spec.ts@@ -0,0 +1,36 @@+import { readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { ANNOTATION_FILE_KEYS, COLUMN_ANNOTATION_KEYS, GROUP_ANNOTATION_KEYS, PROJECT_ANNOTATION_KEYS, TABLE_ANNOTATION_KEYS } from "../types";++// The Rust structs carry deny_unknown_fields, so any property TypeScript adds+// that Rust does not declare turns every save into a deserialization error at+// runtime. vue-tsc cannot see across the language boundary, so this reads the+// Rust source and compares the field sets directly.+const rustSource = readFileSync(path.resolve(__dirname, "../../../../../crates/dbx-core/src/docs/annotations.rs"), "utf8");++function rustFields(structName: string): string[] {+ const start = rustSource.indexOf(`pub struct ${structName} {`);+ expect(start, `struct ${structName} not found in annotations.rs`).toBeGreaterThan(-1);+ const body = rustSource.slice(start, rustSource.indexOf("\n}", start));+ return [...body.matchAll(/^\s{4}pub ([a-z_]+):/gm)].map((match) => toCamel(match[1])).sort();+}++function toCamel(value: string): string {+ return value.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());+}++describe("annotation types match the Rust structs", () => {+ it.each([+ ["AnnotationFile", ANNOTATION_FILE_KEYS],+ ["ProjectAnnotation", PROJECT_ANNOTATION_KEYS],+ ["GroupAnnotation", GROUP_ANNOTATION_KEYS],+ ["TableAnnotation", TABLE_ANNOTATION_KEYS],+ ["ColumnAnnotation", COLUMN_ANNOTATION_KEYS],+ ])("%s", (structName, witness) => {+ // Rust source on one side, the TS interface's own keys on the other —+ // so this fails whichever side drifts. Comparing Rust against a hardcoded+ // list would only ever catch the Rust side.+ expect(rustFields(structName as string)).toEqual(Object.keys(witness).sort());+ });+});diff --git a/apps/desktop/src/docs/__tests__/componentContract.spec.ts b/apps/desktop/src/docs/__tests__/componentContract.spec.tsnew file mode 100644index 0000000000..b9077eb4c8--- /dev/null+++ b/apps/desktop/src/docs/__tests__/componentContract.spec.ts@@ -0,0 +1,157 @@+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { parse } from "vue/compiler-sfc";++const docsRoot = path.resolve(__dirname, "..");++function vueFiles(): string[] {+ const found: string[] = [];+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory() && entry.name !== "__tests__" && entry.name !== "fixtures") {+ walk(full);+ } else if (entry.isFile() && entry.name.endsWith(".vue")) {+ found.push(full);+ }+ }+ };+ walk(docsRoot);+ return found;+}++function scriptOf(file: string): string {+ const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });+ return `${descriptor.script?.content ?? ""}\n${descriptor.scriptSetup?.content ?? ""}`;+}++const EXPECTED = ["ColumnTable.vue", "DocsApp.vue", "DocsSearch.vue", "DocsSidebar.vue", "EnumPage.vue", "GroupEditor.vue", "GroupPicker.vue", "NoteEditor.vue", "RelationshipList.vue", "TablePage.vue", "WarningBanner.vue", "WikiIndex.vue"];++describe("docs viewer component contract", () => {+ it("finds every expected component", () => {+ expect(+ vueFiles()+ .map((file) => path.basename(file))+ .sort(),+ ).toEqual(EXPECTED);+ });++ // Every test below loops over vueFiles(). On an empty set those loops run zero+ // assertions and pass while proving nothing, so each one asserts the set is+ // populated first. Without this, deleting every component turns the whole+ // contract green.+ it("makes no backend calls", () => {+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ // vue-i18n belongs here for the same reason as the backend imports: these+ // components are bundled into a standalone HTML file with no Vue app+ // around them, and useI18n() throws without a provided instance. Strings+ // arrive as a `translate` prop from the host instead.+ const forbidden = ["@/lib/backend", "@tauri-apps", "invoke(", "useConnectionStore", "useQueryStore", "useSettingsStore", "fetch(", "axios", "vue-i18n", "useI18n("];+ for (const file of files) {+ const script = scriptOf(file);+ for (const needle of forbidden) {+ expect(script.includes(needle), `${path.basename(file)} must not reference ${needle}`).toBe(false);+ }+ }+ });++ it("keeps colour decisions out of templates", () => {+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ for (const file of files) {+ const source = readFileSync(file, "utf8");+ expect(source.includes("oklch("), `${path.basename(file)} must not compute colour`).toBe(false);+ expect(/#[0-9a-fA-F]{6}\b/.test(source), `${path.basename(file)} must not hardcode a hex colour`).toBe(false);+ }+ });++ it("only ever feeds renderNote output to v-html", () => {+ // The single most dangerous thing a template here can do. Task 7 escapes+ // author HTML, but `v-html="table.note"` bypasses it entirely and hands a+ // COMMENT ON value straight to the DOM. Every v-html binding must name+ // renderNote, and no component may build HTML any other way.+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ for (const file of files) {+ const source = readFileSync(file, "utf8");+ // Either quote style. A double-quote-only pattern finds zero matches in+ // `v-html='table.note'` and passes it, which is the exact binding this+ // test exists to catch.+ for (const match of source.matchAll(/v-html\s*=\s*(["'])(.*?)\1/g)) {+ expect(match[2], `${path.basename(file)}: v-html must render renderNote output`).toContain("renderNote");+ }+ expect(source.includes("innerHTML"), `${path.basename(file)} must not touch innerHTML`).toBe(false);+ }+ });++ it("the viewer emits edits rather than persisting them", () => {+ // src/docs/ must stay free of I/O so Part 3c can bundle it. Editing works+ // by emitting upward; the dialog outside this directory does the saving.+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ for (const file of files) {+ const source = readFileSync(file, "utf8");+ for (const needle of ["saveDocsAnnotations", "loadDocsAnnotations", "applyDocsAnnotations"]) {+ expect(source.includes(needle), `${path.basename(file)} must not call ${needle}`).toBe(false);+ }+ }+ });++ it("editing components accept a readonly mode", () => {+ // Part 3c renders these same components with editing off inside an+ // exported HTML file. A component that cannot be made read-only would+ // have to be forked for the export.+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ const editors = files.filter((file) => path.basename(file) === "NoteEditor.vue");+ expect(editors.length).toBe(1);+ expect(readFileSync(editors[0], "utf8")).toContain("readonly");+ });++ it('uses <script setup lang="ts">', () => {+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ for (const file of files) {+ const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });+ expect(descriptor.scriptSetup, `${path.basename(file)} must use <script setup>`).toBeTruthy();+ expect(descriptor.scriptSetup?.lang, `${path.basename(file)} must be TypeScript`).toBe("ts");+ }+ });++ it("defines the group colour tokens for WebViews without oklch", () => {+ // DBX supports legacy WebViews with no oklch (globals.css carries an+ // `@supports not (color: oklch(...))` block). The repo's convention is+ // progressive enhancement: a legacy-safe base value first, then the same+ // token redefined inside `@supports (color: oklch(1 0 0))`. Without the+ // base, every table group renders colourless on those WebViews.+ //+ // Assert each selector's base block separately. An ordering check like+ // `indexOf(hsl) < indexOf(@supports)` quantifies over ANY occurrence, so+ // deleting the light block leaves the dark block's hsl satisfying it — the+ // test passes while light-theme legacy WebViews render every group+ // colourless.+ //+ // `.docs-ground-light` is here for the same reason as the other two, not as+ // a third theme: GroupEditor previews a hue on a light ground whatever the+ // app's theme, so that ground needs its own legacy-safe base. Without this+ // entry the whole block could be deleted with the suite still green, and+ // the preview would quietly show dark-theme colours on white in dark mode.+ const css = readFileSync(path.join(docsRoot, "docs.css"), "utf8");+ const enhanced = css.indexOf("@supports (color: oklch(1 0 0))");+ expect(enhanced).toBeGreaterThan(-1);+ const legacyBase = css.slice(0, enhanced);++ for (const selector of [".docs-group", ".dark .docs-group", ".docs-ground-light .docs-group"]) {+ // `^` with the m flag anchors to a line start, so `.docs-group` cannot+ // match inside `.dark .docs-group`, and neither matches the indented+ // copies inside the @supports block.+ const pattern = new RegExp(`^${selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*\\{([^}]*)\\}`, "m");+ const block = pattern.exec(legacyBase)?.[1];+ expect(block, `${selector} needs a legacy-safe base block before @supports`).toBeTruthy();+ expect(block, `${selector} must define --group-c without oklch`).toContain("--group-c: hsl(");+ expect(block, `${selector} must define --group-tint without oklch`).toContain("--group-tint: hsl(");+ }+ });+});diff --git a/apps/desktop/src/docs/__tests__/docsIndex.spec.ts b/apps/desktop/src/docs/__tests__/docsIndex.spec.tsnew file mode 100644index 0000000000..1195758bd9--- /dev/null+++ b/apps/desktop/src/docs/__tests__/docsIndex.spec.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from "vitest";+import { columnsUsingEnum, groupBySchema, groupByTableGroup } from "../docsIndex";+import type { DocTable, SchemaSnapshot, TableGroup } from "../types";++function table(schema: string | null, name: string, groupId: string | null = null): DocTable {+ return {+ schema,+ name,+ kind: "TABLE",+ columns: [],+ indexes: [],+ foreignKeys: [],+ groupId,+ note: null,+ noteSource: "NONE",+ shadowedNote: null,+ columnNotes: {},+ estimatedRows: null,+ viewDefinition: null,+ };+}++function snapshot(tables: DocTable[], groups: TableGroup[] = []): SchemaSnapshot {+ return {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables,+ relationships: [],+ groups,+ enums: [],+ warnings: [],+ };+}++describe("groupBySchema", () => {+ it("groups tables under their schema, sorted by schema then name", () => {+ const sections = groupBySchema(snapshot([table("public", "orders"), table("analytics", "daily_sales"), table("public", "customers")]));++ expect(sections.map((section) => section.key)).toEqual(["analytics", "public"]);+ expect(sections[1].tables.map((t) => t.name)).toEqual(["customers", "orders"]);+ });++ it("puts schema-less tables in a single bare section", () => {+ const sections = groupBySchema(snapshot([table(null, "orders")]));+ expect(sections).toHaveLength(1);+ expect(sections[0].tables[0].name).toBe("orders");+ });+});++describe("groupByTableGroup", () => {+ const groups: TableGroup[] = [+ { id: "order-mgmt", name: "Order Management", hue: 28, note: "Checkout." },+ { id: "product-mgmt", name: "Product Management", hue: 148, note: null },+ ];++ it("groups tables by their group, preserving the snapshot's group order", () => {+ const sections = groupByTableGroup(snapshot([table("product", "products", "product-mgmt"), table("core", "orders", "order-mgmt")], groups));++ expect(sections.map((section) => section.key)).toEqual(["order-mgmt", "product-mgmt"]);+ expect(sections[0].label).toBe("Order Management");+ expect(sections[0].hue).toBe(28);+ expect(sections[0].note).toBe("Checkout.");+ });++ it("collects ungrouped tables into a trailing (no group) section", () => {+ const sections = groupByTableGroup(snapshot([table("core", "orders", "order-mgmt"), table("core", "users", null)], groups));++ const last = sections[sections.length - 1];+ expect(last.key).toBe("");+ expect(last.hue).toBeNull();+ expect(last.tables.map((t) => t.name)).toEqual(["users"]);+ });++ it("omits a group that has no members", () => {+ // render_group in the serializer skips empty groups; the viewer must not+ // show an empty header where the DBML shows nothing.+ const sections = groupByTableGroup(snapshot([table("core", "orders", "order-mgmt")], groups));+ expect(sections.map((section) => section.key)).not.toContain("product-mgmt");+ });++ it("treats a table whose groupId names no group as ungrouped", () => {+ const sections = groupByTableGroup(snapshot([table("core", "orders", "ghost")], groups));+ expect(sections).toHaveLength(1);+ expect(sections[0].key).toBe("");+ });+});++describe("columnsUsingEnum", () => {+ // The file's existing helper is `table(schema, name, groupId)` and builds a+ // table with NO columns, so these tests need columns attached. Add this+ // helper beside it rather than changing the existing signature — the other+ // tests in this file call it positionally.+ function withColumns(base: DocTable, columns: Array<{ name: string; type: string }>): DocTable {+ return {+ ...base,+ columns: columns.map((column) => ({+ name: column.name,+ data_type: column.type,+ is_nullable: false,+ column_default: null,+ is_primary_key: false,+ extra: "",+ comment: null,+ numeric_precision: null,+ numeric_scale: null,+ character_maximum_length: null,+ })),+ };+ }++ function snapshotOf(tables: DocTable[], enums: SchemaSnapshot["enums"]): SchemaSnapshot {+ return {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables,+ relationships: [],+ groups: [],+ enums,+ warnings: [],+ };+ }++ it("finds every column using an enum, across tables", () => {+ const snapshot = snapshotOf(+ [withColumns(table("public", "orders"), [{ name: "status", type: "order_status" }]), withColumns(table("public", "returns"), [{ name: "state", type: "order_status" }]), withColumns(table("public", "users"), [{ name: "id", type: "integer" }])],+ [{ schema: "public", name: "order_status", values: ["new"], note: null, synthesized: false }],+ );++ expect(columnsUsingEnum(snapshot, "order_status")).toEqual([+ { tableKey: "public.orders", table: "orders", column: "status" },+ { tableKey: "public.returns", table: "returns", column: "state" },+ ]);+ });++ it("returns nothing for an enum no column references", () => {+ // Must not fall back to "every column". The `statement` column is the one+ // that matters: it is the only type here that *contains* `state`, so a+ // substring match would claim it while an unrelated type like `integer`+ // would not. Drop it and this test passes against `includes()` too, which+ // makes it stop guarding anything.+ const snapshot = snapshotOf(+ [+ withColumns(table("public", "users"), [+ { name: "id", type: "integer" },+ { name: "body", type: "statement" },+ ]),+ ],+ [{ schema: "public", name: "state", values: ["a"], note: null, synthesized: false }],+ );+ expect(columnsUsingEnum(snapshot, "state")).toEqual([]);+ });+});diff --git a/apps/desktop/src/docs/__tests__/docsSearch.spec.ts b/apps/desktop/src/docs/__tests__/docsSearch.spec.tsnew file mode 100644index 0000000000..f3becd32d8--- /dev/null+++ b/apps/desktop/src/docs/__tests__/docsSearch.spec.ts@@ -0,0 +1,149 @@+import { describe, expect, it } from "vitest";+import { searchDocs, type SearchHit } from "../docsSearch";+import type { DocTable, SchemaSnapshot } from "../types";++function column(name: string) {+ return {+ name,+ data_type: "text",+ is_nullable: true,+ column_default: null,+ is_primary_key: false,+ extra: null,+ };+}++function table(schema: string, name: string, columns: string[] = []): DocTable {+ return {+ schema,+ name,+ kind: "TABLE",+ columns: columns.map(column),+ indexes: [],+ foreignKeys: [],+ groupId: null,+ note: null,+ noteSource: "NONE",+ shadowedNote: null,+ columnNotes: {},+ estimatedRows: null,+ viewDefinition: null,+ };+}++const snapshot: SchemaSnapshot = {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables: [+ table("public", "orders", ["status", "total"]),+ // `orders_count` contains "orders", so a query for "orders" matches BOTH+ // a table and a column — which is what makes the ranking test able to fail.+ table("public", "customers", ["status", "orders_count"]),+ // Mixed case, so a mutant that lowercases only the needle and not the+ // candidate would fail the case-insensitivity test.+ table("public", "Invoices", ["Amount"]),+ ],+ relationships: [],+ groups: [{ id: "g1", name: "Order Management", hue: 28, note: null }],+ enums: [{ schema: "public", name: "order_status", values: ["pending"], note: null, synthesized: false }],+ warnings: [],+};++// Columns outnumber every other kind by two orders of magnitude in a real+// database — the fixture answers "e" with 133 columns against 1 group and 12+// enums. This snapshot reproduces that shape: one term matching more of each+// kind than its cap allows.+const flooded: SchemaSnapshot = {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables: [+ table(+ "public",+ "notes",+ Array.from({ length: 30 }, (_, index) => `note_${index}`),+ ),+ ],+ relationships: [],+ groups: Array.from({ length: 12 }, (_, index) => ({ id: `g${index}`, name: `note group ${index}`, hue: 28, note: null })),+ enums: Array.from({ length: 12 }, (_, index) => ({ schema: "public", name: `note_enum_${index}`, values: ["pending"], note: null, synthesized: false })),+ warnings: [],+};++describe("searchDocs", () => {+ it("returns nothing for an empty query", () => {+ expect(searchDocs(snapshot, "")).toEqual([]);+ expect(searchDocs(snapshot, " ")).toEqual([]);+ });++ it("matches table names case-insensitively", () => {+ const hits = searchDocs(snapshot, "ORD");+ expect(hits.some((hit) => hit.kind === "table" && hit.label === "orders")).toBe(true);+ });++ it("matches columns and reports which table they belong to", () => {+ const hits = searchDocs(snapshot, "total");+ const hit = hits.find((candidate) => candidate.kind === "column");+ expect(hit).toBeDefined();+ expect(hit!.label).toBe("total");+ expect(hit!.context).toContain("orders");+ });++ it("returns one hit per table for a column name shared by several tables", () => {+ const hits = searchDocs(snapshot, "status").filter((hit) => hit.kind === "column");+ expect(hits).toHaveLength(2);+ expect(hits.map((hit) => hit.context).sort()).toEqual(["public.customers", "public.orders"]);+ });++ it("matches groups and enums", () => {+ expect(searchDocs(snapshot, "Order Man").some((hit) => hit.kind === "group")).toBe(true);+ expect(searchDocs(snapshot, "order_status").some((hit) => hit.kind === "enum")).toBe(true);+ });++ it("ranks table matches above column matches for the same term", () => {+ // "orders" now matches the `orders` table AND the `orders_count` column+ // on `customers`. Reversing the concatenation order must fail this.+ const hits = searchDocs(snapshot, "orders");+ const firstTable = hits.findIndex((hit) => hit.kind === "table");+ const firstColumn = hits.findIndex((hit) => hit.kind === "column");+ expect(firstTable).toBeGreaterThanOrEqual(0);+ expect(firstColumn).toBeGreaterThanOrEqual(0);+ expect(firstTable).toBeLessThan(firstColumn);+ });++ it("carries a tableKey so a hit can navigate", () => {+ const hit = searchDocs(snapshot, "total").find((candidate) => candidate.kind === "column");+ expect(hit!.tableKey).toBe("public.orders");+ });++ it("still returns group and enum hits when columns flood the results", () => {+ // A single cap applied after concatenation deletes the tail of the list,+ // and groups and enums are the tail — making them unreachable through+ // search no matter what the user types.+ const hits = searchDocs(flooded, "note");+ expect(+ hits.some((hit) => hit.kind === "group"),+ "groups must survive a column flood",+ ).toBe(true);+ expect(+ hits.some((hit) => hit.kind === "enum"),+ "enums must survive a column flood",+ ).toBe(true);+ });++ it("caps each kind independently", () => {+ const hits = searchDocs(flooded, "note");+ const count = (kind: SearchHit["kind"]) => hits.filter((hit) => hit.kind === kind).length;+ expect(count("table")).toBe(1);+ expect(count("column")).toBe(20);+ expect(count("group")).toBe(10);+ expect(count("enum")).toBe(10);+ });++ it("matches a mixed-case identifier from a lowercase query", () => {+ // The candidate, not just the needle, must be lowercased — otherwise+ // search silently becomes case-sensitive for databases with quoted or+ // uppercase identifiers.+ expect(searchDocs(snapshot, "invoice").some((hit) => hit.label === "Invoices")).toBe(true);+ expect(searchDocs(snapshot, "amount").some((hit) => hit.label === "Amount")).toBe(true);+ });+});diff --git a/apps/desktop/src/docs/__tests__/docsWarnings.spec.ts b/apps/desktop/src/docs/__tests__/docsWarnings.spec.tsnew file mode 100644index 0000000000..2194b33ff8--- /dev/null+++ b/apps/desktop/src/docs/__tests__/docsWarnings.spec.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { describeWarning, type Translate } from "../docsWarnings";+import type { SnapshotWarning } from "../types";++// A fake translator that echoes the key and params back rather than English+// prose. This is what actually matters now: that describeWarning calls+// translate with the right key and the right params, not what the English+// copy says — the copy itself lives in the i18n namespace and is covered by+// the parity test.+const translate: Translate = (key, params) => `${key}|${JSON.stringify(params ?? {})}`;++describe("describeWarning", () => {+ it("explains a skipped table as a warning naming the table and reason", () => {+ const notice = describeWarning({ kind: "tableSkipped", table: "public.secret", reason: "permission denied" }, translate);+ expect(notice.severity).toBe("warning");+ expect(notice.title).toBe("docs.warnings.tableSkipped.title|{}");+ expect(notice.detail).toBe('docs.warnings.tableSkipped.detail|{"table":"public.secret","reason":"permission denied"}');+ });++ it("explains missing foreign-key metadata as an engine limitation, not a fault", () => {+ const notice = describeWarning({ kind: "noForeignKeyMetadata", engine: "ClickHouse" }, translate);+ expect(notice.severity).toBe("info");+ expect(notice.title).toBe("docs.warnings.noForeignKeyMetadata.title|{}");+ expect(notice.detail).toBe('docs.warnings.noForeignKeyMetadata.detail|{"engine":"ClickHouse"}');+ });++ it("explains unsupported comments", () => {+ const notice = describeWarning({ kind: "commentsUnsupported", engine: "SQLite" }, translate);+ expect(notice.severity).toBe("info");+ expect(notice.title).toBe("docs.warnings.commentsUnsupported.title|{}");+ expect(notice.detail).toBe('docs.warnings.commentsUnsupported.detail|{"engine":"SQLite"}');+ });++ it("reports orphaned notes with the count", () => {+ const notice = describeWarning({ kind: "orphanedNotes", count: 3 }, translate);+ expect(notice.severity).toBe("warning");+ expect(notice.title).toBe("docs.warnings.orphanedNotes.title|{}");+ expect(notice.detail).toBe('docs.warnings.orphanedNotes.detail|{"count":3}');+ });++ it("explains a DBML omission naming the item", () => {+ const notice = describeWarning(+ {+ kind: "dbmlOmitted",+ table: "public.orders",+ item: "idx_orders_open",+ reason: "partial index filter has no DBML equivalent",+ },+ translate,+ );+ expect(notice.severity).toBe("info");+ expect(notice.title).toBe("docs.warnings.dbmlOmitted.title|{}");+ expect(notice.detail).toBe('docs.warnings.dbmlOmitted.detail|{"item":"idx_orders_open","table":"public.orders","reason":"partial index filter has no DBML equivalent"}');+ });++ it("never returns an empty title or detail for any known kind", () => {+ const samples: SnapshotWarning[] = [+ { kind: "tableSkipped", table: "t", reason: "r" },+ { kind: "noForeignKeyMetadata", engine: "e" },+ { kind: "commentsUnsupported", engine: "e" },+ { kind: "orphanedNotes", count: 1 },+ { kind: "dbmlOmitted", table: "t", item: "i", reason: "r" },+ ];+ for (const sample of samples) {+ const notice = describeWarning(sample, translate);+ expect(notice.title.length, `empty title for ${sample.kind}`).toBeGreaterThan(0);+ expect(notice.detail.length, `empty detail for ${sample.kind}`).toBeGreaterThan(0);+ }+ });+});diff --git a/apps/desktop/src/docs/__tests__/fixtureConformance.spec.ts b/apps/desktop/src/docs/__tests__/fixtureConformance.spec.tsnew file mode 100644index 0000000000..c18da5a947--- /dev/null+++ b/apps/desktop/src/docs/__tests__/fixtureConformance.spec.ts@@ -0,0 +1,158 @@+import { readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import type { SchemaSnapshot } from "../types";++const fixturePath = path.resolve(__dirname, "../fixtures/keycloak.snapshot.json");++function loadFixture(): SchemaSnapshot {+ return JSON.parse(readFileSync(fixturePath, "utf8")) as SchemaSnapshot;+}++describe("fixture conformance", () => {+ // This fixture is generated by the REAL Rust serializer. Its job is to fail+ // when the Rust model changes shape, so the hand-maintained types.ts cannot+ // drift silently.++ it("has the shape types.ts declares", () => {+ const snapshot = loadFixture();+ expect(snapshot.formatVersion).toBe(1);+ expect(Array.isArray(snapshot.tables)).toBe(true);+ expect(snapshot.tables.length).toBeGreaterThan(0);+ expect(typeof snapshot.project.databaseType).toBe("string");+ expect(Array.isArray(snapshot.project.schemas)).toBe(true);+ });++ it("uses camelCase for snapshot-owned fields", () => {+ const raw = JSON.parse(readFileSync(fixturePath, "utf8")) as Record<string, unknown>;+ expect(raw).toHaveProperty("formatVersion");+ expect(raw).not.toHaveProperty("format_version");++ const table = (raw.tables as Record<string, unknown>[])[0];+ expect(table).toHaveProperty("noteSource");+ expect(table).toHaveProperty("columnNotes");+ expect(table).toHaveProperty("foreignKeys");+ expect(table).not.toHaveProperty("note_source");+ });++ it("keeps snake_case on columns, which come from crate::types", () => {+ const snapshot = loadFixture();+ const withColumns = snapshot.tables.find((table) => table.columns.length > 0);+ expect(withColumns, "fixture must contain at least one table with columns").toBeDefined();+ const column = withColumns!.columns[0] as unknown as Record<string, unknown>;+ expect(column).toHaveProperty("data_type");+ expect(column).toHaveProperty("is_nullable");+ expect(column).not.toHaveProperty("dataType");+ });++ it("carries an annotated note, a group and an orphan warning", () => {+ const snapshot = loadFixture();++ const annotated = snapshot.tables.find((table) => table.noteSource === "LOCAL");+ expect(annotated, "fixture must include a LOCAL-sourced note").toBeDefined();+ expect(annotated!.note).toBeTruthy();++ expect(snapshot.groups.length).toBeGreaterThan(0);+ expect(typeof snapshot.groups[0].hue).toBe("number");++ const orphan = snapshot.warnings.find((warning) => warning.kind === "orphanedNotes");+ expect(orphan, "fixture must include an orphanedNotes warning").toBeDefined();+ });++ it("every warning discriminant is one types.ts knows", () => {+ const known = new Set(["tableSkipped", "noForeignKeyMetadata", "commentsUnsupported", "orphanedNotes", "dbmlOmitted"]);+ for (const warning of loadFixture().warnings) {+ expect(known.has(warning.kind), `unknown warning kind: ${warning.kind}`).toBe(true);+ }+ });++ // Every struct below is pinned in BOTH directions — no missing key, no+ // unexpected key — because each direction catches a different drift. A+ // missing key is a removal or a rename's old name; an unexpected key is the+ // rename's new name. Pinning only "required keys present" lets a rename of+ // Relationship::to slip through the whole suite AND vue-tsc while+ // RelationshipList reads `field.table` on undefined and every table page+ // renders blank.+ //+ // `Object.hasOwn`, never truthiness: most of these keys are legitimately+ // null, and "present and null" must stay distinguishable from "absent",+ // which is what skip_serializing_if produces.+ function pinShape(label: string, instances: unknown[], required: string[], optional: string[] = []): void {+ // An empty instance list runs zero assertions and passes while proving+ // nothing, so every struct has to actually appear in the fixture.+ expect(instances.length, `fixture must contain at least one ${label}`).toBeGreaterThan(0);+ const allowed = new Set([...required, ...optional]);+ for (const [position, instance] of instances.entries()) {+ const record = instance as Record<string, unknown>;+ for (const key of required) {+ expect(Object.hasOwn(record, key), `${label}[${position}] must always carry ${key}`).toBe(true);+ }+ for (const key of Object.keys(record)) {+ expect(allowed.has(key), `${label}[${position}] carries unexpected key ${key}`).toBe(true);+ }+ }+ }++ it("the snapshot root has exactly the keys types.ts declares", () => {+ pinShape("SchemaSnapshot", [loadFixture()], ["formatVersion", "project", "tables", "relationships", "groups", "enums", "warnings"]);+ });++ it("ProjectMeta has exactly the keys types.ts declares", () => {+ pinShape("ProjectMeta", [loadFixture().project], ["name", "databaseType", "database", "schemas", "generatedAt", "note"]);+ });++ it("DocTable has exactly the keys types.ts declares", () => {+ pinShape("DocTable", loadFixture().tables, ["schema", "name", "kind", "columns", "indexes", "foreignKeys", "groupId", "note", "noteSource", "shadowedNote", "columnNotes", "estimatedRows", "viewDefinition"]);+ });++ it("ColumnInfo has exactly the keys types.ts declares", () => {+ // The required ten are required because Rust has no skip_serializing_if on+ // them. The optional three DO carry one, so the key is absent rather than+ // null when there is no value.+ const columns = loadFixture().tables.flatMap((table) => table.columns);+ pinShape("ColumnInfo", columns, ["name", "data_type", "is_nullable", "column_default", "is_primary_key", "extra", "comment", "numeric_precision", "numeric_scale", "character_maximum_length"], ["enum_values", "character_set", "collation"]);+ });++ it("IndexInfo has exactly the keys types.ts declares", () => {+ const indexes = loadFixture().tables.flatMap((table) => table.indexes);+ pinShape("IndexInfo", indexes, ["name", "columns", "is_unique", "is_primary", "filter", "index_type", "included_columns", "comment"]);+ });++ it("ForeignKeyInfo has exactly the keys types.ts declares", () => {+ const foreignKeys = loadFixture().tables.flatMap((table) => table.foreignKeys);+ pinShape("ForeignKeyInfo", foreignKeys, ["name", "column", "ref_table", "ref_column"], ["ref_schema", "on_update", "on_delete"]);+ });++ it("ColumnNote has exactly the keys types.ts declares", () => {+ const notes = loadFixture().tables.flatMap((table) => Object.values(table.columnNotes));+ pinShape("ColumnNote", notes, ["note", "source", "shadowed"]);+ });++ it("Relationship and FieldRef have exactly the keys types.ts declares", () => {+ const relationships = loadFixture().relationships;+ pinShape("Relationship", relationships, ["id", "name", "from", "to", "cardinality", "onUpdate", "onDelete"]);+ pinShape(+ "FieldRef",+ relationships.flatMap((relationship) => [relationship.from, relationship.to]),+ ["schema", "table", "column"],+ );+ });++ it("TableGroup has exactly the keys types.ts declares", () => {+ pinShape("TableGroup", loadFixture().groups, ["id", "name", "hue", "note"]);+ });++ it("records that the fixture source declares no enum types, leaving DocEnum unpinned", () => {+ // Keycloak's schema has no PostgreSQL enum types, so this fixture cannot+ // exercise DocEnum. That is a real gap: a Rust-side rename of a DocEnum+ // field would pass every test in this file and break the viewer's enum+ // rendering silently.+ //+ // Asserting the gap rather than deleting the test keeps it visible and+ // makes it self-correcting — the day the fixture source gains an enum this+ // fails, and the pin below should replace it:+ //+ // pinShape("DocEnum", loadFixture().enums, ["schema", "name", "values", "note", "synthesized"]);+ expect(loadFixture().enums, "fixture gained enums — restore the DocEnum pinShape here").toEqual([]);+ });+});diff --git a/apps/desktop/src/docs/__tests__/groupColor.spec.ts b/apps/desktop/src/docs/__tests__/groupColor.spec.tsnew file mode 100644index 0000000000..d15e17774f--- /dev/null+++ b/apps/desktop/src/docs/__tests__/groupColor.spec.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";+import { groupStyle } from "../groupColor";++describe("groupStyle", () => {+ it("exposes the hue as a CSS custom property", () => {+ expect(groupStyle(28)).toEqual({ "--h": "28" });+ });++ it("returns no custom property for an ungrouped section", () => {+ expect(groupStyle(null)).toEqual({});+ });++ it("wraps hues into 0-359 rather than emitting an out-of-range value", () => {+ expect(groupStyle(360)).toEqual({ "--h": "0" });+ expect(groupStyle(388)).toEqual({ "--h": "28" });+ expect(groupStyle(-1)).toEqual({ "--h": "359" });+ });++ it("never emits a colour value", () => {+ // Lightness and chroma belong to the theme. If this function ever returns+ // a hex or oklch string, the dark-mode contrast guarantee is gone.+ const style = groupStyle(200);+ const serialized = JSON.stringify(style);+ expect(serialized).not.toContain("#");+ expect(serialized).not.toContain("oklch");+ expect(serialized).not.toContain("rgb");+ });++ it("coerces a non-integer hue to an integer", () => {+ expect(groupStyle(28.7)).toEqual({ "--h": "28" });+ });+});diff --git a/apps/desktop/src/docs/__tests__/renderNote.spec.ts b/apps/desktop/src/docs/__tests__/renderNote.spec.tsnew file mode 100644index 0000000000..40df6e5897--- /dev/null+++ b/apps/desktop/src/docs/__tests__/renderNote.spec.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from "vitest";+import { renderNote } from "../renderNote";++describe("renderNote", () => {+ it("renders ordinary markdown", () => {+ expect(renderNote("One row per **checkout**.")).toContain("<strong>checkout</strong>");+ });++ it("renders inline code and fenced blocks", () => {+ expect(renderNote("see `order_status`")).toContain("<code>order_status</code>");+ expect(renderNote("```sql\nSELECT 1;\n```")).toContain("<pre>");+ });++ it("returns an empty string for null or blank input", () => {+ expect(renderNote(null)).toBe("");+ expect(renderNote(" ")).toBe("");+ });++ it("escapes a script tag rather than rendering it", () => {+ const html = renderNote("<script>alert(1)</script>");+ expect(html).not.toContain("<script>");+ expect(html).toContain("<script>");+ });++ it("escapes an img onerror payload", () => {+ // NB: asserting !contains("onerror=") would FAIL against a correct+ // implementation — the escaped text legitimately still contains that+ // substring. What matters is that no <img> ELEMENT is produced.+ const html = renderNote('<img src=x onerror="alert(1)">');+ expect(html.toLowerCase()).not.toContain("<img");+ expect(html).toContain("<img");+ });++ it("escapes raw HTML even when it looks harmless", () => {+ // Blanket rule: no author-supplied HTML is rendered, ever. A rule with+ // exceptions is a rule someone will find a way around.+ const html = renderNote("<b>bold</b>");+ expect(html).not.toContain("<b>bold</b>");+ expect(html).toContain("<b>");+ });++ it("does not preserve HTML entities twice", () => {+ // Guards the pre-escaping approach, which turns "a & b" into+ // "a &amp; b" and renders the entity visibly to the reader.+ expect(renderNote("a & b")).toContain("a & b");+ expect(renderNote("a & b")).not.toContain("&amp;");+ });++ it.each([+ ["javascript:alert(1)", "javascript"],+ ["JaVaScRiPt:alert(1)", "javascript"],+ ["javascript:alert(1)", "avascript"],+ ["vbscript:alert(1)", "vbscript"],+ ["data:text/html;base64,PHNjcmlwdD4=", "data:"],+ ])("drops the unsafe link scheme %s", (href, forbidden) => {+ const html = renderNote(`[click](${href})`).toLowerCase();+ expect(html).not.toContain(forbidden);+ expect(html).toContain("click"); // the text survives; only the href is dropped+ });++ it("drops an unsafe image scheme", () => {+ const html = renderNote(")").toLowerCase();+ expect(html).not.toContain("javascript");+ expect(html).not.toContain("<img");+ });++ it.each(["//evil.example.com", "//evil.example.com/a.png", "/\\evil.example.com", "/\\evil.example.com/a.png", "\\\\evil.example.com"])("drops the protocol-relative URL %s", (href) => {+ // The URL spec treats /\ like //, so both separators must be rejected.+ expect(renderNote(`[x](${href})`)).not.toContain("evil.example.com");+ expect(renderNote(``)).not.toContain("evil.example.com");+ });++ it("escapes single quotes so the escaper does not rely on double-quoted attributes", () => {+ // Not exploitable while every attribute here is double-quoted, but that is+ // a formatting convention enforced nowhere. Escaping ' keeps escapeHtml+ // correct on its own rather than correct-given-a-distant-invariant.+ const html = renderNote(`[x](https://example.com "it's here")`);+ expect(html).toContain("'");+ expect(html).not.toContain("it's here");+ });++ it("still allows an ordinary root-relative path", () => {+ // The // guard must not break the single-slash relative case it sits in+ // front of.+ expect(renderNote("[x](/docs/page.html)")).toContain('href="/docs/page.html"');+ });++ it.each(["https://example.com", "http://example.com", "mailto:[email protected]", "#anchor", "./rel.html"])("keeps the safe link target %s", (href) => {+ expect(renderNote(`[ok](${href})`)).toContain(`href="${href}"`);+ });++ it("parses markdown inside link text instead of emitting it raw", () => {+ // marked hands the renderer the RAW source text. Emitting it directly+ // both breaks formatting and injects unescaped HTML.+ expect(renderNote("[**keep**](https://example.com)")).toContain("<strong>keep</strong>");+ const dropped = renderNote('[<img src=x onerror="alert(1)">](javascript:alert(1))');+ expect(dropped.toLowerCase()).not.toContain("<img");+ expect(dropped).toContain("<img");+ });+});diff --git a/apps/desktop/src/docs/__tests__/types.spec.ts b/apps/desktop/src/docs/__tests__/types.spec.tsnew file mode 100644index 0000000000..3698d02dd1--- /dev/null+++ b/apps/desktop/src/docs/__tests__/types.spec.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from "vitest";+import type { ColumnInfo, IndexInfo, SchemaSnapshot, SnapshotWarning } from "../types";++describe("snapshot types", () => {+ it("accepts a minimal snapshot shaped like the Rust output", () => {+ const snapshot: SchemaSnapshot = {+ formatVersion: 1,+ project: {+ name: "Ecommerce",+ databaseType: "postgres",+ database: "shop",+ schemas: ["public"],+ generatedAt: "2026-08-03T00:00:00Z",+ note: null,+ },+ tables: [+ {+ schema: "public",+ name: "orders",+ kind: "TABLE",+ columns: [],+ indexes: [],+ foreignKeys: [],+ groupId: null,+ note: "Checkout rows.",+ noteSource: "DATABASE",+ shadowedNote: null,+ columnNotes: {},+ estimatedRows: null,+ viewDefinition: null,+ },+ ],+ relationships: [],+ groups: [],+ enums: [],+ warnings: [],+ };++ expect(snapshot.tables[0].noteSource).toBe("DATABASE");+ expect(snapshot.tables[0].kind).toBe("TABLE");+ });++ it("discriminates warnings on a camelCase kind", () => {+ // Rust: #[serde(rename_all = "camelCase", tag = "kind")] — so the+ // discriminant is camelCase even though sibling enums are SCREAMING_SNAKE.+ const warning: SnapshotWarning = {+ kind: "tableSkipped",+ table: "public.secret",+ reason: "permission denied",+ };+ expect(warning.kind).toBe("tableSkipped");++ const orphans: SnapshotWarning = { kind: "orphanedNotes", count: 3 };+ if (orphans.kind === "orphanedNotes") {+ expect(orphans.count).toBe(3);+ } else {+ throw new Error("discriminated union must narrow on kind");+ }+ });++ it("requires the always-serialized column and index fields", () => {+ // These keys have no skip_serializing_if in Rust, so they are always+ // present in the JSON. Typing them optional would let `undefined` reach+ // code that checks `=== null`.+ const column: ColumnInfo = {+ name: "status",+ data_type: "text",+ is_nullable: false,+ column_default: null,+ is_primary_key: false,+ extra: null,+ comment: null,+ numeric_precision: null,+ numeric_scale: null,+ character_maximum_length: null,+ };+ expect(column.comment).toBeNull();++ const index: IndexInfo = {+ name: "idx",+ columns: ["status"],+ is_unique: false,+ is_primary: false,+ filter: null,+ index_type: null,+ included_columns: null,+ comment: null,+ };+ expect(index.filter).toBeNull();++ // The skip_serializing_if fields may simply be absent.+ const minimal: ColumnInfo = { ...column, enum_values: undefined };+ expect(minimal.character_set).toBeUndefined();+ });+});diff --git a/apps/desktop/src/docs/annotationEdits.ts b/apps/desktop/src/docs/annotationEdits.tsnew file mode 100644index 0000000000..a23e720abb--- /dev/null+++ b/apps/desktop/src/docs/annotationEdits.ts@@ -0,0 +1,100 @@+import type { AnnotationFile, GroupAnnotation, TableAnnotation } from "./types";++/**+ * Every function here returns a NEW file rather than mutating.+ *+ * Empty or whitespace-only prose removes the entry instead of storing "" —+ * the notes file is meant to be committed and reviewed, so it must not+ * accumulate keys holding nothing.+ */+export function emptyAnnotations(): AnnotationFile {+ return { formatVersion: 1 };+}++function blank(value: string): boolean {+ return value.trim() === "";+}++/** Drop a table entry once it carries neither a note nor a group. */+function pruneTable(tables: Record<string, TableAnnotation>, key: string): Record<string, TableAnnotation> {+ const entry = tables[key];+ const empty = entry !== undefined && entry.note === undefined && entry.group === undefined && Object.keys(entry.columns ?? {}).length === 0;+ if (!empty) {+ return tables;+ }+ const { [key]: _dropped, ...rest } = tables;+ return rest;+}++function withTable(file: AnnotationFile, key: string, change: (entry: TableAnnotation) => TableAnnotation): AnnotationFile {+ const tables = { ...file.tables };+ tables[key] = change(tables[key] ?? {});+ const pruned = pruneTable(tables, key);+ return { ...file, tables: Object.keys(pruned).length > 0 ? pruned : undefined };+}++export function setTableNote(file: AnnotationFile, tableKey: string, note: string): AnnotationFile {+ return withTable(file, tableKey, (entry) => {+ const { note: _old, ...rest } = entry;+ return blank(note) ? rest : { ...rest, note };+ });+}++export function setColumnNote(file: AnnotationFile, tableKey: string, column: string, note: string): AnnotationFile {+ return withTable(file, tableKey, (entry) => {+ const columns = { ...entry.columns };+ if (blank(note)) {+ delete columns[column];+ } else {+ columns[column] = { note };+ }+ const { columns: _old, ...rest } = entry;+ return Object.keys(columns).length > 0 ? { ...rest, columns } : rest;+ });+}++export function setTableGroup(file: AnnotationFile, tableKey: string, groupId: string | null): AnnotationFile {+ return withTable(file, tableKey, (entry) => {+ const { group: _old, ...rest } = entry;+ return groupId === null ? rest : { ...rest, group: groupId };+ });+}++export function upsertGroup(file: AnnotationFile, group: GroupAnnotation): AnnotationFile {+ const groups = [...(file.groups ?? [])];+ const index = groups.findIndex((candidate) => candidate.id === group.id);+ if (index >= 0) {+ groups[index] = group;+ } else {+ groups.push(group);+ }+ return { ...file, groups };+}++/**+ * Remove a group and every reference to it.+ *+ * `docsIndex` already drops a dangling groupId when rendering, so the viewer+ * degrades correctly either way — but the committed file should not carry a+ * reference to a group that no longer exists.+ */+export function removeGroup(file: AnnotationFile, groupId: string): AnnotationFile {+ const groups = (file.groups ?? []).filter((group) => group.id !== groupId);+ let next: AnnotationFile = { ...file, groups };+ for (const [key, entry] of Object.entries(file.tables ?? {})) {+ if (entry.group === groupId) {+ next = setTableGroup(next, key, null);+ }+ }+ return next;+}++export function setProjectNote(file: AnnotationFile, note: string): AnnotationFile {+ const project = { ...file.project };+ if (blank(note)) {+ delete project.note;+ } else {+ project.note = note;+ }+ return { ...file, project: Object.keys(project).length > 0 ? project : undefined };+}diff --git a/apps/desktop/src/docs/components/ColumnTable.vue b/apps/desktop/src/docs/components/ColumnTable.vuenew file mode 100644index 0000000000..86b05ca6f5--- /dev/null+++ b/apps/desktop/src/docs/components/ColumnTable.vue@@ -0,0 +1,101 @@+<script setup lang="ts">+import type { Translate } from "../docsWarnings";+import type { ColumnInfo, ColumnNote, DocsEdit } from "../types";+import NoteEditor from "./NoteEditor.vue";++const props = defineProps<{+ columns: ColumnInfo[];+ /** Keyed by the column's real name, exactly as the snapshot emits it. */+ columnNotes: Record<string, ColumnNote>;+ /** Qualified key of the table these columns belong to, for emitted edits. */+ tableKey: string;+ readonly: boolean;+ translate: Translate;+}>();++const emit = defineEmits<{+ edit: [edit: DocsEdit];+}>();++/** Rebuild the declared type from the parts the snapshot reports separately. */+function typeLabel(column: ColumnInfo): string {+ if (column.character_maximum_length !== null) {+ return `${column.data_type}(${column.character_maximum_length})`;+ }+ if (column.numeric_precision !== null) {+ const scale = column.numeric_scale === null ? "" : `,${column.numeric_scale}`;+ return `${column.data_type}(${column.numeric_precision}${scale})`;+ }+ return column.data_type;+}++function settings(column: ColumnInfo): string[] {+ const parts: string[] = [];+ if (column.is_primary_key) {+ parts.push("pk");+ }+ if (!column.is_nullable) {+ parts.push("not null");+ }+ if (column.column_default !== null) {+ parts.push(`default: ${column.column_default}`);+ }+ if (column.extra !== null && column.extra !== "") {+ parts.push(column.extra);+ }+ if (column.enum_values !== undefined && column.enum_values.length > 0) {+ parts.push(`enum: ${column.enum_values.join(", ")}`);+ }+ return parts;+}++function noteOf(column: ColumnInfo): ColumnNote | null {+ return props.columnNotes[column.name] ?? null;+}++/**+ * The database's own comment, when a local note replaced it. Bound with+ * `:title` so Vue escapes it — this is author text like any other note.+ */+function shadowedTitle(column: ColumnInfo): string | undefined {+ const shadowed = noteOf(column)?.shadowed;+ return shadowed ? `Database comment: ${shadowed}` : undefined;+}+</script>++<template>+ <div class="overflow-hidden rounded-md border border-border">+ <table class="w-full text-xs">+ <thead>+ <tr class="bg-muted/30">+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Column</th>+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Type</th>+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Settings</th>+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Note</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="column in columns" :key="column.name" class="border-t border-border align-top">+ <td class="px-2 py-1.5 font-mono font-medium text-foreground">{{ column.name }}</td>+ <td class="px-2 py-1.5 font-mono text-muted-foreground">{{ typeLabel(column) }}</td>+ <td class="px-2 py-1.5">+ <div class="flex flex-wrap gap-1">+ <span v-for="setting in settings(column)" :key="setting" class="rounded bg-muted/50 px-1.5 py-0.5 text-[10px] text-muted-foreground">+ {{ setting }}+ </span>+ </div>+ </td>+ <td class="px-2 py-1.5 text-muted-foreground">+ <div class="flex items-start gap-1">+ <span v-if="noteOf(column)?.source === 'LOCAL'" class="mt-0.5 shrink-0 text-[10px] font-medium" :title="shadowedTitle(column)">⬤ LOCAL</span>+ <!-- Merged note, for the same reason as TablePage: NoteEditor+ renders and edits one value, and the local layer alone would+ hide notes that came from the database. -->+ <NoteEditor class="min-w-0 flex-1" :model-value="noteOf(column)?.note ?? ''" :readonly="readonly" :translate="translate" @update:model-value="emit('edit', { kind: 'columnNote', tableKey, column: column.name, note: $event })" />+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/DocsSearch.vue b/apps/desktop/src/docs/components/DocsSearch.vuenew file mode 100644index 0000000000..9cc5277998--- /dev/null+++ b/apps/desktop/src/docs/components/DocsSearch.vue@@ -0,0 +1,94 @@+<script setup lang="ts">+import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";+import { searchDocs, type SearchHit } from "../docsSearch";+import type { SchemaSnapshot } from "../types";++const props = defineProps<{+ snapshot: SchemaSnapshot;+}>();++const emit = defineEmits<{+ select: [tableKey: string];+ selectEnum: [enumName: string];+}>();++const open = ref(false);+const query = ref("");+const input = ref<HTMLInputElement | null>(null);++// searchDocs caps its own results, per kind. Slicing again here would just+// re-create the bug where columns crowd out every other kind.+const hits = computed(() => searchDocs(props.snapshot, query.value));++async function show(): Promise<void> {+ open.value = true;+ query.value = "";+ await nextTick();+ input.value?.focus();+}++function onKeydown(event: KeyboardEvent): void {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {+ event.preventDefault();+ if (open.value) {+ open.value = false;+ } else {+ void show();+ }+ return;+ }+ if (event.key === "Escape" && open.value) {+ open.value = false;+ }+}++/** Enums navigate by name, everything else by table key; groups have neither. */+function isNavigable(hit: SearchHit): boolean {+ return hit.kind === "enum" || hit.tableKey !== null;+}++function choose(hit: SearchHit): void {+ // Enums navigate by name — they have no table key, and EnumPage resolves them+ // by bare name for the same reason columnsUsingEnum does.+ if (hit.kind === "enum") {+ emit("selectEnum", hit.label);+ open.value = false;+ return;+ }+ // Groups still have no page of their own, so they stay unclickable rather+ // than navigating somewhere arbitrary.+ if (hit.tableKey === null) {+ return;+ }+ emit("select", hit.tableKey);+ open.value = false;+}++onMounted(() => window.addEventListener("keydown", onKeydown));+onBeforeUnmount(() => window.removeEventListener("keydown", onKeydown));+</script>++<template>+ <div>+ <button type="button" class="flex items-center gap-2 rounded border border-border bg-background px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40" @click="show()">+ <span>Search</span>+ <span class="rounded bg-muted/50 px-1 py-0.5 text-[10px]">⌘K</span>+ </button>++ <div v-if="open" class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-24" @click.self="open = false">+ <div class="w-full max-w-lg overflow-hidden rounded-md border border-border bg-background shadow-lg">+ <input ref="input" v-model="query" type="text" placeholder="Search tables, columns, groups, enums…" class="w-full border-b border-border bg-transparent px-3 py-2 text-sm text-foreground outline-none" />+ <ul class="max-h-80 overflow-y-auto">+ <li v-if="query.trim() !== '' && hits.length === 0" class="px-3 py-4 text-center text-xs text-muted-foreground">Nothing matches “{{ query }}”.</li>+ <li v-for="(hit, position) in hits" :key="`${hit.kind}-${hit.context}-${hit.label}-${position}`">+ <button type="button" class="flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-xs transition-colors" :class="isNavigable(hit) ? 'hover:bg-muted/40' : 'cursor-default text-muted-foreground'" :disabled="!isNavigable(hit)" @click="choose(hit)">+ <span class="w-14 shrink-0 text-[10px] uppercase text-muted-foreground">{{ hit.kind }}</span>+ <span class="font-mono text-foreground">{{ hit.label }}</span>+ <span class="truncate text-[11px] text-muted-foreground">{{ hit.context }}</span>+ </button>+ </li>+ </ul>+ </div>+ </div>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/DocsSidebar.vue b/apps/desktop/src/docs/components/DocsSidebar.vuenew file mode 100644index 0000000000..d3bbc7dea3--- /dev/null+++ b/apps/desktop/src/docs/components/DocsSidebar.vue@@ -0,0 +1,51 @@+<script setup lang="ts">+import type { IndexSection } from "../docsIndex";+import { qualifiedTableKey } from "../docsKeys";+import { groupStyle } from "../groupColor";++defineProps<{+ sections: IndexSection[];+ mode: "schema" | "group";+ /** Qualified name of the table currently open, or null on the index. */+ activeKey: string | null;+}>();++const emit = defineEmits<{+ "update:mode": ["schema" | "group"];+ select: [tableKey: string];+ home: [];+}>();+</script>++<template>+ <nav class="flex w-64 shrink-0 flex-col gap-3 overflow-y-auto border-r border-border bg-background p-3">+ <button type="button" class="rounded px-2 py-1 text-left text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/40" @click="emit('home')">Overview</button>++ <div class="flex flex-col gap-1">+ <span class="px-2 text-[10px] uppercase tracking-wide text-muted-foreground">Group by</span>+ <div class="flex rounded border border-border p-0.5">+ <button type="button" class="flex-1 rounded px-2 py-1 text-xs transition-colors" :class="mode === 'schema' ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/40'" @click="emit('update:mode', 'schema')">Schemas</button>+ <button type="button" class="flex-1 rounded px-2 py-1 text-xs transition-colors" :class="mode === 'group' ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/40'" @click="emit('update:mode', 'group')">Table Groups</button>+ </div>+ </div>++ <div v-for="section in sections" :key="section.key" class="flex flex-col gap-0.5">+ <div class="flex items-center gap-1.5 px-2 py-1" :class="{ 'docs-group': section.hue !== null }" :style="groupStyle(section.hue)">+ <span v-if="section.hue !== null" class="h-2 w-2 shrink-0 rounded-full" style="background-color: var(--group-c)"></span>+ <span class="truncate text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ {{ section.label || "(no schema)" }}+ </span>+ </div>+ <button+ v-for="table in section.tables"+ :key="qualifiedTableKey(table)"+ type="button"+ class="truncate rounded px-2 py-1 text-left font-mono text-xs transition-colors"+ :class="activeKey === qualifiedTableKey(table) ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/40'"+ @click="emit('select', qualifiedTableKey(table))"+ >+ {{ table.name }}+ </button>+ </div>+ </nav>+</template>diff --git a/apps/desktop/src/docs/components/EnumPage.vue b/apps/desktop/src/docs/components/EnumPage.vuenew file mode 100644index 0000000000..d4a227bd6b--- /dev/null+++ b/apps/desktop/src/docs/components/EnumPage.vue@@ -0,0 +1,55 @@+<script setup lang="ts">+import { computed } from "vue";+import { columnsUsingEnum } from "../docsIndex";+import type { Translate } from "../docsWarnings";+import type { DocEnum, SchemaSnapshot } from "../types";+import NoteEditor from "./NoteEditor.vue";++const props = defineProps<{+ enumType: DocEnum;+ /** Every table in the snapshot; usedBy filters them down to enum columns. */+ snapshot: SchemaSnapshot;+ translate: Translate;+}>();++const emit = defineEmits<{+ select: [tableKey: string];+}>();++const qualifiedName = computed(() => (props.enumType.schema ? `${props.enumType.schema}.${props.enumType.name}` : props.enumType.name));++// No annotation storage exists for enum notes yet (AnnotationFile has no+// `enums` key), so this is always read-only — there is nowhere to save an+// edit to.+const usedBy = computed(() => columnsUsingEnum(props.snapshot, props.enumType.name));+</script>++<template>+ <article class="flex flex-col gap-5">+ <header class="flex flex-col gap-2">+ <div class="flex flex-wrap items-center gap-2">+ <h2 class="font-mono text-lg font-semibold text-foreground">{{ qualifiedName }}</h2>+ <span v-if="enumType.synthesized" class="rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground">synthesized</span>+ </div>++ <NoteEditor :model-value="enumType.note ?? ''" readonly :translate="translate" />+ </header>++ <section>+ <h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{{ translate("docs.enumValues") }}</h3>+ <ul class="flex flex-wrap gap-1">+ <li v-for="value in enumType.values" :key="value" class="rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground">{{ value }}</li>+ </ul>+ </section>++ <section>+ <h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{{ translate("docs.usedBy") }}</h3>+ <p v-if="usedBy.length === 0" class="text-xs text-muted-foreground">No column uses this enum.</p>+ <ul v-else class="flex flex-col gap-1">+ <li v-for="hit in usedBy" :key="`${hit.tableKey}.${hit.column}`" class="text-xs">+ <button type="button" class="w-full rounded border border-border bg-background px-2 py-1.5 text-left font-mono transition-colors hover:bg-muted/40" @click="emit('select', hit.tableKey)">{{ hit.tableKey }}.{{ hit.column }}</button>+ </li>+ </ul>+ </section>+ </article>+</template>diff --git a/apps/desktop/src/docs/components/GroupEditor.vue b/apps/desktop/src/docs/components/GroupEditor.vuenew file mode 100644index 0000000000..6448c56d43--- /dev/null+++ b/apps/desktop/src/docs/components/GroupEditor.vue@@ -0,0 +1,96 @@+<script setup lang="ts">+import type { Translate } from "../docsWarnings";+import { groupStyle } from "../groupColor";+import type { GroupAnnotation } from "../types";++const props = defineProps<{+ group: GroupAnnotation;+ translate: Translate;+}>();++const emit = defineEmits<{+ "update:group": [group: GroupAnnotation];+ delete: [groupId: string];+}>();++/**+ * Twelve evenly spaced hues.+ *+ * Presets are hues, not colours: docs.css fixes lightness and chroma per+ * theme, so any point on the wheel is legible on both grounds and an even+ * split cannot produce a bad preset.+ */+const PRESET_HUES = Array.from({ length: 12 }, (_, step) => step * 30);++function rename(event: Event): void {+ emit("update:group", { ...props.group, name: (event.target as HTMLInputElement).value });+}++function recolour(hue: number): void {+ emit("update:group", { ...props.group, hue });+}++function slide(event: Event): void {+ recolour(Number((event.target as HTMLInputElement).value));+}++/**+ * No per-hue i18n key exists and adding one means eight locale files, so the+ * tooltip pairs the "Colour" label with the raw hue.+ */+function swatchTitle(hue: number): string {+ return `${props.translate("docs.groupColour")} ${hue}°`;+}+</script>++<template>+ <div class="flex flex-col gap-3">+ <label class="flex flex-col gap-1">+ <span class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ translate("docs.groupName") }}</span>+ <input type="text" :value="group.name" :placeholder="translate('docs.groupName')" class="rounded border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus:border-ring" @input="rename($event)" />+ </label>++ <div class="flex flex-col gap-2">+ <span class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ translate("docs.groupColour") }}</span>++ <!-- `docs-group` and the hue go on the SAME element: the class brings in+ the theme's lightness and chroma, groupStyle only supplies --h. A+ hex fill here could not stay legible on both grounds. -->+ <div class="flex items-center gap-1.5">+ <button+ v-for="hue in PRESET_HUES"+ :key="hue"+ type="button"+ class="docs-group h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105"+ :class="group.hue === hue ? 'ring-2 ring-ring ring-offset-2' : 'border-border'"+ style="background-color: var(--group-c)"+ :style="groupStyle(hue)"+ :title="swatchTitle(hue)"+ @click="recolour(hue)"+ ></button>+ </div>++ <input type="range" min="0" max="359" :value="group.hue" class="w-full" :title="swatchTitle(group.hue)" @input="slide($event)" />++ <!-- Both grounds at once: the reader picks one hue and it has to work in+ either theme, so neither can be left to imagination. `docs-ground-light`+ and `dark` pin each half to a theme regardless of the app's own. -->+ <div class="grid grid-cols-2 gap-2">+ <div class="docs-ground-light flex items-center gap-2 overflow-hidden rounded border border-border bg-white p-2">+ <span class="docs-group h-4 w-4 shrink-0 rounded-full" style="background-color: var(--group-c)" :style="groupStyle(group.hue)"></span>+ <span class="docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium" style="background-color: var(--group-tint); color: var(--group-c)" :style="groupStyle(group.hue)">{{ group.name }}</span>+ </div>+ <div class="dark flex items-center gap-2 overflow-hidden rounded border border-border bg-neutral-900 p-2">+ <span class="docs-group h-4 w-4 shrink-0 rounded-full" style="background-color: var(--group-c)" :style="groupStyle(group.hue)"></span>+ <span class="docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium" style="background-color: var(--group-tint); color: var(--group-c)" :style="groupStyle(group.hue)">{{ group.name }}</span>+ </div>+ </div>+ </div>++ <div class="flex justify-end">+ <button type="button" class="rounded border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40" @click="emit('delete', group.id)">+ {{ translate("docs.deleteGroup") }}+ </button>+ </div>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/GroupPicker.vue b/apps/desktop/src/docs/components/GroupPicker.vuenew file mode 100644index 0000000000..88f9a33eba--- /dev/null+++ b/apps/desktop/src/docs/components/GroupPicker.vue@@ -0,0 +1,50 @@+<script setup lang="ts">+import { computed } from "vue";+import type { Translate } from "../docsWarnings";+import { groupStyle } from "../groupColor";+import type { GroupAnnotation } from "../types";++const props = defineProps<{+ groups: GroupAnnotation[];+ /** Id of the selected group, or null when the table belongs to none. */+ modelValue: string | null;+ translate: Translate;+}>();++const emit = defineEmits<{+ "update:modelValue": [groupId: string | null];+ create: [];+}>();++/**+ * Value of the "New group…" option. Group ids come from a hand-editable notes+ * file, so this is treated as the sentinel only when no real group claims it —+ * otherwise picking that group would silently open a create flow instead.+ */+const CREATE = "__dbx_new_group__";++const selected = computed(() => props.groups.find((group) => group.id === props.modelValue) ?? null);++function choose(event: Event): void {+ const select = event.target as HTMLSelectElement;+ if (select.value === CREATE && !props.groups.some((group) => group.id === CREATE)) {+ // "New group…" is an action, not a selection: park the select back on the+ // current group so it does not display a group that does not exist.+ select.value = props.modelValue ?? "";+ emit("create");+ return;+ }+ emit("update:modelValue", select.value === "" ? null : select.value);+}+</script>++<template>+ <div class="flex items-center gap-1.5">+ <span v-if="selected" class="docs-group h-3 w-3 shrink-0 rounded-full" style="background-color: var(--group-c)" :style="groupStyle(selected.hue)"></span>+ <select :value="modelValue ?? ''" class="rounded border border-border bg-background px-2 py-1 text-xs text-foreground outline-none focus:border-ring" @change="choose($event)">+ <option value="">{{ translate("docs.noGroup") }}</option>+ <option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }}</option>+ <option :value="CREATE">{{ translate("docs.newGroup") }}</option>+ </select>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/NoteEditor.vue b/apps/desktop/src/docs/components/NoteEditor.vuenew file mode 100644index 0000000000..ee10d37ee3--- /dev/null+++ b/apps/desktop/src/docs/components/NoteEditor.vue@@ -0,0 +1,66 @@+<script setup lang="ts">+import { nextTick, ref } from "vue";+import type { Translate } from "../docsWarnings";+import { renderNote } from "../renderNote";++const props = defineProps<{+ /** Raw markdown. Displayed through renderNote, edited as its source. */+ modelValue: string;+ /**+ * Part 3c renders this same component inside the standalone HTML export,+ * where nothing can be saved. Read-only means the note never turns into a+ * textarea — not a disabled one, none at all.+ */+ readonly: boolean;+ translate: Translate;+}>();++const emit = defineEmits<{+ "update:modelValue": [note: string];+}>();++const editing = ref(false);+const draft = ref("");+const input = ref<HTMLTextAreaElement | null>(null);++async function begin(): Promise<void> {+ if (props.readonly) {+ return;+ }+ draft.value = props.modelValue;+ editing.value = true;+ await nextTick();+ input.value?.focus();+}++function commit(): void {+ editing.value = false;+ // The parent owns the value. Emitting an unchanged note would dirty the+ // annotation file for a click that edited nothing.+ if (draft.value !== props.modelValue) {+ emit("update:modelValue", draft.value);+ }+}++/** Escape abandons the draft; the stored note stays the source of truth. */+function cancel(): void {+ draft.value = props.modelValue;+ editing.value = false;+}+</script>++<template>+ <div class="text-sm text-muted-foreground">+ <textarea v-if="editing" ref="input" v-model="draft" rows="4" class="w-full resize-y rounded border border-border bg-background p-2 font-mono text-xs text-foreground outline-none focus:border-ring" @blur="commit()" @keydown.escape="cancel()"></textarea>++ <!-- renderNote is the sanitiser: a note can be a database COMMENT ON value+ the reader never wrote, so its markdown is rendered here and its HTML+ is escaped there. Binding the raw note would hand that comment to the+ DOM verbatim. -->+ <div v-else-if="modelValue.trim() !== ''" class="leading-relaxed" :class="readonly ? '' : 'cursor-text rounded transition-colors hover:bg-muted/30'" :title="readonly ? undefined : translate('docs.editNote')" @click="begin()" v-html="renderNote(modelValue)"></div>++ <button v-else-if="!readonly" type="button" class="rounded border border-dashed border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40" @click="begin()">+ {{ translate("docs.addNote") }}+ </button>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/RelationshipList.vue b/apps/desktop/src/docs/components/RelationshipList.vuenew file mode 100644index 0000000000..ed5b59428b--- /dev/null+++ b/apps/desktop/src/docs/components/RelationshipList.vue@@ -0,0 +1,86 @@+<script setup lang="ts">+import { computed } from "vue";+import { qualifiedTableKey } from "../docsKeys";+import type { FieldRef, Relationship } from "../types";++const props = defineProps<{+ /** Every relationship in the snapshot; filtered here on the current table. */+ relationships: Relationship[];+ schema: string | null;+ table: string;+}>();++const emit = defineEmits<{+ select: [tableKey: string];+}>();++function isCurrent(field: FieldRef): boolean {+ return field.table === props.table && (field.schema ?? null) === props.schema;+}++// FieldRef names its table property `table`, not `name`, so it is remapped+// rather than passed to qualifiedTableKey directly.+function keyOf(field: FieldRef): string {+ return qualifiedTableKey({ schema: field.schema, name: field.table });+}++function label(field: FieldRef): string {+ return `${keyOf(field)}.${field.column}`;+}++function notation(relationship: Relationship): string {+ return relationship.cardinality === "ONE_TO_ONE" ? "1 – 1" : "* – 1";+}++function actions(relationship: Relationship): string[] {+ const parts: string[] = [];+ if (relationship.onUpdate) {+ parts.push(`on update ${relationship.onUpdate}`);+ }+ if (relationship.onDelete) {+ parts.push(`on delete ${relationship.onDelete}`);+ }+ return parts;+}++const outgoing = computed(() => props.relationships.filter((relationship) => isCurrent(relationship.from)));+const incoming = computed(() => props.relationships.filter((relationship) => isCurrent(relationship.to)));+</script>++<template>+ <div class="grid gap-4 sm:grid-cols-2">+ <section>+ <h4 class="mb-1.5 text-xs font-medium text-muted-foreground">References ({{ outgoing.length }})</h4>+ <p v-if="outgoing.length === 0" class="text-xs text-muted-foreground">This table references no other table.</p>+ <ul v-else class="flex flex-col gap-1">+ <li v-for="relationship in outgoing" :key="relationship.id" class="text-xs">+ <button type="button" class="w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40" @click="emit('select', keyOf(relationship.to))">+ <span class="font-mono">{{ relationship.from.column }}</span>+ <span class="mx-1.5 text-muted-foreground">{{ notation(relationship) }}</span>+ <span class="font-mono">{{ label(relationship.to) }}</span>+ <span v-if="actions(relationship).length > 0" class="ml-1.5 text-[10px] text-muted-foreground">+ {{ actions(relationship).join(", ") }}+ </span>+ </button>+ </li>+ </ul>+ </section>++ <section>+ <h4 class="mb-1.5 text-xs font-medium text-muted-foreground">Referenced by ({{ incoming.length }})</h4>+ <p v-if="incoming.length === 0" class="text-xs text-muted-foreground">No table references this one.</p>+ <ul v-else class="flex flex-col gap-1">+ <li v-for="relationship in incoming" :key="relationship.id" class="text-xs">+ <button type="button" class="w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40" @click="emit('select', keyOf(relationship.from))">+ <span class="font-mono">{{ label(relationship.from) }}</span>+ <span class="mx-1.5 text-muted-foreground">{{ notation(relationship) }}</span>+ <span class="font-mono">{{ relationship.to.column }}</span>+ <span v-if="actions(relationship).length > 0" class="ml-1.5 text-[10px] text-muted-foreground">+ {{ actions(relationship).join(", ") }}+ </span>+ </button>+ </li>+ </ul>+ </section>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/TablePage.vue b/apps/desktop/src/docs/components/TablePage.vuenew file mode 100644index 0000000000..6e03cda732--- /dev/null+++ b/apps/desktop/src/docs/components/TablePage.vue@@ -0,0 +1,112 @@+<script setup lang="ts">+import { computed } from "vue";+import type { Translate } from "../docsWarnings";+import { qualifiedTableKey } from "../docsKeys";+import { groupStyle } from "../groupColor";+import type { DocsEdit, DocTable, GroupAnnotation, Relationship, TableGroup } from "../types";+import ColumnTable from "./ColumnTable.vue";+import GroupPicker from "./GroupPicker.vue";+import NoteEditor from "./NoteEditor.vue";+import RelationshipList from "./RelationshipList.vue";++const props = defineProps<{+ table: DocTable;+ /** Every relationship in the snapshot; RelationshipList filters them. */+ relationships: Relationship[];+ /** The table's group, or null when it belongs to none. */+ group: TableGroup | null;+ /** The editable group records, which `group` above cannot be written back to. */+ annotationGroups: GroupAnnotation[];+ readonly: boolean;+ translate: Translate;+}>();++const emit = defineEmits<{+ select: [tableKey: string];+ edit: [edit: DocsEdit];+ createGroup: [tableKey: string];+}>();++const qualified = computed(() => qualifiedTableKey(props.table));++const kindLabel = computed(() => props.table.kind.toLowerCase().replace(/_/g, " "));++/**+ * The database comment a local note replaced. Bound with `:title` so Vue+ * escapes it — it is author text, exactly like the note itself.+ */+const shadowedTitle = computed(() => (props.table.shadowedNote ? `Database comment: ${props.table.shadowedNote}` : undefined));+</script>++<template>+ <article class="flex flex-col gap-5">+ <header class="flex flex-col gap-2">+ <div class="flex flex-wrap items-center gap-2">+ <h2 class="font-mono text-lg font-semibold text-foreground">{{ qualified }}</h2>+ <span class="rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground">{{ kindLabel }}</span>+ <span v-if="group" class="docs-group rounded px-1.5 py-0.5 text-[10px] font-medium" style="background-color: var(--group-tint); color: var(--group-c)" :style="groupStyle(group.hue)">+ {{ group.name }}+ </span>+ <span v-if="table.estimatedRows !== null" class="text-[10px] text-muted-foreground"> ~{{ table.estimatedRows }} rows </span>+ </div>++ <!-- NoteEditor is fed the MERGED note, not the local one. It renders and+ edits a single value, so seeding it from the annotation file would+ show nothing for a note that came from a database comment. Writing+ one shadows that comment, which is what noteSource and shadowedNote+ below exist to disclose. -->+ <div class="flex items-start gap-2">+ <span v-if="table.noteSource === 'LOCAL'" class="mt-0.5 shrink-0 text-[10px] font-medium text-muted-foreground" :title="shadowedTitle">⬤ LOCAL</span>+ <NoteEditor class="min-w-0 flex-1" :model-value="table.note ?? ''" :readonly="readonly" :translate="translate" @update:model-value="emit('edit', { kind: 'tableNote', tableKey: qualified, note: $event })" />+ </div>++ <GroupPicker v-if="!readonly" :groups="annotationGroups" :model-value="table.groupId" :translate="translate" @update:model-value="emit('edit', { kind: 'tableGroup', tableKey: qualified, groupId: $event })" @create="emit('createGroup', qualified)" />+ </header>++ <section>+ <h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Columns</h3>+ <ColumnTable :columns="table.columns" :column-notes="table.columnNotes" :table-key="qualified" :readonly="readonly" :translate="translate" @edit="emit('edit', $event)" />+ </section>++ <section v-if="table.indexes.length > 0">+ <h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Indexes</h3>+ <div class="overflow-hidden rounded-md border border-border">+ <table class="w-full text-xs">+ <thead>+ <tr class="bg-muted/30">+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Name</th>+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Columns</th>+ <th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Settings</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="index in table.indexes" :key="index.name" class="border-t border-border align-top">+ <td class="px-2 py-1.5 font-mono">{{ index.name }}</td>+ <td class="px-2 py-1.5 font-mono text-muted-foreground">+ {{ index.columns.join(", ") }}<template v-if="index.included_columns && index.included_columns.length > 0"> (include {{ index.included_columns.join(", ") }}) </template>+ </td>+ <td class="px-2 py-1.5">+ <div class="flex flex-wrap gap-1 text-[10px] text-muted-foreground">+ <span v-if="index.is_primary" class="rounded bg-muted/50 px-1.5 py-0.5">pk</span>+ <span v-if="index.is_unique" class="rounded bg-muted/50 px-1.5 py-0.5">unique</span>+ <span v-if="index.index_type" class="rounded bg-muted/50 px-1.5 py-0.5">{{ index.index_type }}</span>+ <span v-if="index.filter" class="rounded bg-muted/50 px-1.5 py-0.5">where {{ index.filter }}</span>+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </section>++ <section>+ <h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Relationships</h3>+ <RelationshipList :relationships="relationships" :schema="table.schema" :table="table.name" @select="emit('select', $event)" />+ </section>++ <section v-if="table.viewDefinition">+ <h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Definition</h3>+ <pre class="overflow-x-auto rounded-md border border-border bg-muted/20 p-2 font-mono text-xs">{{ table.viewDefinition }}</pre>+ </section>+ </article>+</template>diff --git a/apps/desktop/src/docs/components/WarningBanner.vue b/apps/desktop/src/docs/components/WarningBanner.vuenew file mode 100644index 0000000000..ff506eb2ba--- /dev/null+++ b/apps/desktop/src/docs/components/WarningBanner.vue@@ -0,0 +1,27 @@+<script setup lang="ts">+import { computed } from "vue";+import { describeWarning, type Translate } from "../docsWarnings";+import type { SnapshotWarning } from "../types";++const props = defineProps<{+ warnings: SnapshotWarning[];+ translate: Translate;+}>();++// Keyed by index: two warnings of the same kind can carry identical text.+const notices = computed(() => props.warnings.map((warning, index) => ({ key: `${warning.kind}-${index}`, ...describeWarning(warning, props.translate) })));+</script>++<template>+ <div v-if="notices.length > 0" class="flex flex-col gap-2">+ <div+ v-for="notice in notices"+ :key="notice.key"+ class="rounded-md border px-3 py-2 text-xs"+ :class="notice.severity === 'warning' ? 'border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200' : 'border-border bg-muted/30 text-muted-foreground'"+ >+ <div class="font-medium">{{ notice.title }}</div>+ <div class="mt-0.5 leading-relaxed">{{ notice.detail }}</div>+ </div>+ </div>+</template>diff --git a/apps/desktop/src/docs/components/WikiIndex.vue b/apps/desktop/src/docs/components/WikiIndex.vuenew file mode 100644index 0000000000..9a9942d62e--- /dev/null+++ b/apps/desktop/src/docs/components/WikiIndex.vue@@ -0,0 +1,44 @@+<script setup lang="ts">+import type { IndexSection } from "../docsIndex";+import { qualifiedTableKey } from "../docsKeys";+import { groupStyle } from "../groupColor";+import { renderNote } from "../renderNote";++defineProps<{+ sections: IndexSection[];+}>();++const emit = defineEmits<{+ select: [tableKey: string];+}>();+</script>++<template>+ <div class="flex flex-col gap-6">+ <section v-for="section in sections" :key="section.key" class="flex flex-col gap-2">+ <div class="flex flex-col gap-1 border-l-2 pl-3" :class="{ 'docs-group': section.hue !== null }" style="border-color: var(--group-c, var(--border))" :style="groupStyle(section.hue)">+ <div class="flex items-baseline gap-2">+ <h2 class="text-sm font-semibold text-foreground">{{ section.label || "(no schema)" }}</h2>+ <span class="text-xs text-muted-foreground">{{ section.tables.length }} tables</span>+ </div>+ <div v-if="section.note" class="text-xs text-muted-foreground" v-html="renderNote(section.note)"></div>+ </div>++ <ul class="grid gap-1 sm:grid-cols-2 lg:grid-cols-3">+ <!-- The note renders author markdown, so it can contain an <a>. Inside+ the <button> that would be invalid nesting and the link would not+ be keyboard reachable, so the note is a sibling of the button and+ the <li> carries the card. -->+ <li v-for="table in section.tables" :key="qualifiedTableKey(table)" class="flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 transition-colors hover:bg-muted/40">+ <button type="button" class="flex w-full items-baseline gap-1.5 text-left" @click="emit('select', qualifiedTableKey(table))">+ <span class="font-mono text-xs font-medium text-foreground">{{ table.name }}</span>+ <span v-if="table.kind !== 'TABLE'" class="text-[10px] uppercase text-muted-foreground">+ {{ table.kind.toLowerCase().replace(/_/g, " ") }}+ </span>+ </button>+ <div v-if="table.note" class="line-clamp-2 text-[11px] text-muted-foreground" v-html="renderNote(table.note)"></div>+ </li>+ </ul>+ </section>+ </div>+</template>diff --git a/apps/desktop/src/docs/docs.css b/apps/desktop/src/docs/docs.cssnew file mode 100644index 0000000000..4df72de03b--- /dev/null+++ b/apps/desktop/src/docs/docs.css@@ -0,0 +1,42 @@+/* Group colour. A group stores one number (the hue); lightness and chroma are+ * fixed here per theme, so no hue can produce an illegible swatch.+ *+ * Base values use hsl() because DBX supports WebViews without oklch — the same+ * bare `--h` number works in both functions. The oklch values below are the+ * enhancement, matching how globals.css defines its own tokens. */+.docs-group {+ --group-c: hsl(var(--h, 220), 55%, 38%);+ --group-tint: hsl(var(--h, 220), 55%, 94%);+}++.dark .docs-group {+ --group-c: hsl(var(--h, 220), 50%, 72%);+ --group-tint: hsl(var(--h, 220), 30%, 18%);+}++/* GroupEditor previews a hue on a light and a dark ground side by side. The+ * dark half just carries `.dark`, which works in either theme; the light half+ * needs this, because in dark mode `.dark .docs-group` would otherwise paint+ * dark-theme values onto a white ground and the preview would lie. Same+ * specificity as the rule above and declared after it, so it wins. */+.docs-ground-light .docs-group {+ --group-c: hsl(var(--h, 220), 55%, 38%);+ --group-tint: hsl(var(--h, 220), 55%, 94%);+}++@supports (color: oklch(1 0 0)) {+ .docs-group {+ --group-c: oklch(0.55 0.15 var(--h, 220));+ --group-tint: oklch(0.96 0.03 var(--h, 220));+ }++ .dark .docs-group {+ --group-c: oklch(0.76 0.13 var(--h, 220));+ --group-tint: oklch(0.28 0.05 var(--h, 220));+ }++ .docs-ground-light .docs-group {+ --group-c: oklch(0.55 0.15 var(--h, 220));+ --group-tint: oklch(0.96 0.03 var(--h, 220));+ }+}diff --git a/apps/desktop/src/docs/docsIndex.ts b/apps/desktop/src/docs/docsIndex.tsnew file mode 100644index 0000000000..66579856fe--- /dev/null+++ b/apps/desktop/src/docs/docsIndex.ts@@ -0,0 +1,88 @@+import { qualifiedTableKey } from "./docsKeys";+import type { DocTable, SchemaSnapshot } from "./types";++export interface IndexSection {+ /** Schema name, group id, or "" for the ungrouped bucket. */+ key: string;+ label: string;+ /** Group hue, or null for schema sections and the ungrouped bucket. */+ hue: number | null;+ note: string | null;+ tables: DocTable[];+}++function byName(a: DocTable, b: DocTable): number {+ return a.name.localeCompare(b.name);+}++export function groupBySchema(snapshot: SchemaSnapshot): IndexSection[] {+ const sections = new Map<string, DocTable[]>();+ for (const table of snapshot.tables) {+ const key = table.schema ?? "";+ const bucket = sections.get(key);+ if (bucket) {+ bucket.push(table);+ } else {+ sections.set(key, [table]);+ }+ }++ return [...sections.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([key, tables]) => ({+ key,+ label: key,+ hue: null,+ note: null,+ tables: [...tables].sort(byName),+ }));+}++export function groupByTableGroup(snapshot: SchemaSnapshot): IndexSection[] {+ const known = new Map(snapshot.groups.map((group) => [group.id, group]));+ const sections: IndexSection[] = [];++ // Snapshot order is the notes file's order — the user's own arrangement.+ for (const group of snapshot.groups) {+ const tables = snapshot.tables.filter((table) => table.groupId === group.id).sort(byName);+ // An empty group renders nothing, matching render_group in the serializer.+ if (tables.length === 0) {+ continue;+ }+ sections.push({+ key: group.id,+ label: group.name,+ hue: group.hue,+ note: group.note,+ tables,+ });+ }++ // A groupId naming no known group is treated as ungrouped rather than+ // creating a phantom section.+ const ungrouped = snapshot.tables.filter((table) => table.groupId === null || !known.has(table.groupId)).sort(byName);++ if (ungrouped.length > 0) {+ sections.push({ key: "", label: "(no group)", hue: null, note: null, tables: ungrouped });+ }++ return sections;+}++/**+ * Every column whose declared type is this enum.+ *+ * Exact match on `data_type`, never a substring: an enum named `state` would+ * otherwise claim every column of type `statement`.+ */+export function columnsUsingEnum(snapshot: SchemaSnapshot, enumName: string): Array<{ tableKey: string; table: string; column: string }> {+ const hits: Array<{ tableKey: string; table: string; column: string }> = [];+ for (const table of snapshot.tables) {+ for (const column of table.columns) {+ if (column.data_type === enumName) {+ hits.push({ tableKey: qualifiedTableKey(table), table: table.name, column: column.name });+ }+ }+ }+ return hits;+}diff --git a/apps/desktop/src/docs/docsKeys.ts b/apps/desktop/src/docs/docsKeys.tsnew file mode 100644index 0000000000..366834407c--- /dev/null+++ b/apps/desktop/src/docs/docsKeys.ts@@ -0,0 +1,17 @@+import type { DocTable } from "./types";++/**+ * The key that identifies a table across the viewer — `schema.name`, or the+ * bare name on schema-less engines like SQLite and MySQL.+ *+ * This rule was copied into four places before it lived here. It is the key+ * that annotations are stored under, so two call sites disagreeing would+ * attach a note to the wrong table.+ *+ * Typed as `Pick<DocTable, "schema" | "name">` rather than the full `DocTable`+ * so callers that only have a schema/name pair on hand — a relationship's+ * `FieldRef`, remapped — can use it too without an unsafe cast.+ */+export function qualifiedTableKey(table: Pick<DocTable, "schema" | "name">): string {+ return table.schema ? `${table.schema}.${table.name}` : table.name;+}diff --git a/apps/desktop/src/docs/docsSearch.ts b/apps/desktop/src/docs/docsSearch.tsnew file mode 100644index 0000000000..d232d2d0da--- /dev/null+++ b/apps/desktop/src/docs/docsSearch.ts@@ -0,0 +1,66 @@+import { qualifiedTableKey } from "./docsKeys";+import type { SchemaSnapshot } from "./types";++export interface SearchHit {+ kind: "table" | "column" | "group" | "enum";+ label: string;+ /** Where the hit lives — a qualified table name, or a count for groups. */+ context: string;+ /** Qualified table name for navigation, or null for groups and enums. */+ tableKey: string | null;+}++/** Per-kind result caps. A single overall cap lets columns — by far the most+ * numerous kind — crowd groups and enums out of the list entirely. */+const LIMITS = { table: 20, column: 20, group: 10, enum: 10 } as const;++/**+ * Case-insensitive substring search over the whole snapshot.+ *+ * Tables rank first: someone typing a table's name almost always wants the+ * table, not a column that happens to share the word.+ *+ * Results are capped per kind — see LIMITS. This is the only place results are+ * limited; callers render everything they are handed.+ */+export function searchDocs(snapshot: SchemaSnapshot, query: string): SearchHit[] {+ const needle = query.trim().toLowerCase();+ if (needle.length === 0) {+ return [];+ }++ const tables: SearchHit[] = [];+ const columns: SearchHit[] = [];++ for (const table of snapshot.tables) {+ const key = qualifiedTableKey(table);+ if (table.name.toLowerCase().includes(needle)) {+ tables.push({ kind: "table", label: table.name, context: key, tableKey: key });+ }+ for (const column of table.columns) {+ if (column.name.toLowerCase().includes(needle)) {+ columns.push({ kind: "column", label: column.name, context: key, tableKey: key });+ }+ }+ }++ const groups: SearchHit[] = snapshot.groups+ .filter((group) => group.name.toLowerCase().includes(needle))+ .map((group) => ({+ kind: "group",+ label: group.name,+ context: `${snapshot.tables.filter((table) => table.groupId === group.id).length} tables`,+ tableKey: null,+ }));++ const enums: SearchHit[] = snapshot.enums+ .filter((value) => value.name.toLowerCase().includes(needle))+ .map((value) => ({+ kind: "enum",+ label: value.name,+ context: `${value.values.length} values`,+ tableKey: null,+ }));++ return [...tables.slice(0, LIMITS.table), ...columns.slice(0, LIMITS.column), ...groups.slice(0, LIMITS.group), ...enums.slice(0, LIMITS.enum)];+}diff --git a/apps/desktop/src/docs/docsWarnings.ts b/apps/desktop/src/docs/docsWarnings.tsnew file mode 100644index 0000000000..4113c039c4--- /dev/null+++ b/apps/desktop/src/docs/docsWarnings.ts@@ -0,0 +1,60 @@+import type { SnapshotWarning } from "./types";++export interface WarningNotice {+ severity: "info" | "warning";+ title: string;+ detail: string;+}++/**+ * A `useI18n().t`-shaped function, passed in rather than imported directly.+ *+ * `useI18n()` throws without a provided Vue instance — exactly the standalone+ * HTML export case (Part 3c), which bootstraps no Vue app around this module.+ * Taking the translator as a parameter keeps this file a pure module the+ * export can call with an English identity function, and is why `src/docs/`+ * must never import vue-i18n directly.+ */+export type Translate = (key: string, params?: Record<string, string | number>) => string;++/**+ * Turn a snapshot warning into something a reader can act on.+ *+ * This is where "degrade visibly, never silently" becomes literal: if a table+ * could not be read, or an engine cannot report relationships, the reader has+ * to learn that from the page rather than infer it from an absence.+ */+export function describeWarning(warning: SnapshotWarning, translate: Translate): WarningNotice {+ switch (warning.kind) {+ case "tableSkipped":+ return {+ severity: "warning",+ title: translate("docs.warnings.tableSkipped.title"),+ detail: translate("docs.warnings.tableSkipped.detail", { table: warning.table, reason: warning.reason }),+ };+ case "noForeignKeyMetadata":+ return {+ severity: "info",+ title: translate("docs.warnings.noForeignKeyMetadata.title"),+ detail: translate("docs.warnings.noForeignKeyMetadata.detail", { engine: warning.engine }),+ };+ case "commentsUnsupported":+ return {+ severity: "info",+ title: translate("docs.warnings.commentsUnsupported.title"),+ detail: translate("docs.warnings.commentsUnsupported.detail", { engine: warning.engine }),+ };+ case "orphanedNotes":+ return {+ severity: "warning",+ title: translate("docs.warnings.orphanedNotes.title"),+ detail: translate("docs.warnings.orphanedNotes.detail", { count: warning.count }),+ };+ case "dbmlOmitted":+ return {+ severity: "info",+ title: translate("docs.warnings.dbmlOmitted.title"),+ detail: translate("docs.warnings.dbmlOmitted.detail", { item: warning.item, table: warning.table, reason: warning.reason }),+ };+ }+}diff --git a/apps/desktop/src/docs/fixtures/keycloak.snapshot.json b/apps/desktop/src/docs/fixtures/keycloak.snapshot.jsonnew file mode 100644index 0000000000..c9655d2dbe--- /dev/null+++ b/apps/desktop/src/docs/fixtures/keycloak.snapshot.json@@ -0,0 +1,2586 @@+{+ "formatVersion": 1,+ "project": {+ "name": "Keycloak",+ "databaseType": "postgres",+ "database": "keycloak",+ "schemas": [+ "public"+ ],+ "generatedAt": "2026-08-03T14:40:30.253915+00:00",+ "note": "# Keycloak\n\nFixture generated for the docs viewer conformance test."+ },+ "tables": [+ {+ "schema": "public",+ "name": "client",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "full_scope_allowed",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "client_id",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "not_before",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "public_client",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "secret",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "base_url",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "bearer_only",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "management_url",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "surrogate_auth_required",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "realm_id",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "protocol",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "node_rereg_timeout",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "frontchannel_logout",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "consent_required",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "service_accounts_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "client_authenticator_type",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "root_url",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "description",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "registration_token",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "standard_flow_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "true",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "implicit_flow_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "direct_access_grants_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "always_display_in_console",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ }+ ],+ "indexes": [+ {+ "name": "constraint_7",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_client_id",+ "columns": [+ "client_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "uk_b71cjlbenv945rb6gcon438at",+ "columns": [+ "realm_id",+ "client_id"+ ],+ "is_unique": true,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [],+ "groupId": "client-registry",+ "note": "Every registered OIDC/SAML client. Owned by the platform team.",+ "noteSource": "LOCAL",+ "shadowedNote": null,+ "columnNotes": {+ "client_id": {+ "note": "The public client identifier callers send at the token endpoint.",+ "source": "LOCAL",+ "shadowed": null+ }+ },+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "client_attributes",+ "kind": "TABLE",+ "columns": [+ {+ "name": "client_id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "value",+ "data_type": "text",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ }+ ],+ "indexes": [+ {+ "name": "constraint_3c",+ "columns": [+ "client_id",+ "name"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_client_att_by_name_value",+ "columns": [+ "name",+ "substr(value, 1, 255)"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk3c47c64beacca966",+ "column": "client_id",+ "ref_schema": "public",+ "ref_table": "client",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "client_scope",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "realm_id",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "description",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "protocol",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ }+ ],+ "indexes": [+ {+ "name": "idx_realm_clscope",+ "columns": [+ "realm_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "pk_cli_template",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "uk_cli_scope",+ "columns": [+ "realm_id",+ "name"+ ],+ "is_unique": true,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "client_scope_attributes",+ "kind": "TABLE",+ "columns": [+ {+ "name": "scope_id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "value",+ "data_type": "character varying(2048)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 2048+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ }+ ],+ "indexes": [+ {+ "name": "idx_clscope_attrs",+ "columns": [+ "scope_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "pk_cl_tmpl_attr",+ "columns": [+ "scope_id",+ "name"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk_cl_scope_attr_scope",+ "column": "scope_id",+ "ref_schema": "public",+ "ref_table": "client_scope",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "composite_role",+ "kind": "TABLE",+ "columns": [+ {+ "name": "composite",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "child_role",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ }+ ],+ "indexes": [+ {+ "name": "constraint_composite_role",+ "columns": [+ "composite",+ "child_role"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_composite",+ "columns": [+ "composite"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_composite_child",+ "columns": [+ "child_role"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk_a63wvekftu8jo1pnj81e7mce2",+ "column": "composite",+ "ref_schema": "public",+ "ref_table": "keycloak_role",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ },+ {+ "name": "fk_gr7thllb9lu8q4vqa4524jjy8",+ "column": "child_role",+ "ref_schema": "public",+ "ref_table": "keycloak_role",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "credential",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "salt",+ "data_type": "bytea",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "type",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "user_id",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "created_date",+ "data_type": "bigint",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "user_label",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "secret_data",+ "data_type": "text",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "credential_data",+ "data_type": "text",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "priority",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "version",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ }+ ],+ "indexes": [+ {+ "name": "constraint_f",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_user_credential",+ "columns": [+ "user_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk_pfyr0glasqyl0dei3kl69r6v0",+ "column": "user_id",+ "ref_schema": "public",+ "ref_table": "user_entity",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "federated_identity",+ "kind": "TABLE",+ "columns": [+ {+ "name": "identity_provider",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "realm_id",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "federated_user_id",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "federated_username",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "token",+ "data_type": "text",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "user_id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ }+ ],+ "indexes": [+ {+ "name": "constraint_40",+ "columns": [+ "identity_provider",+ "user_id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_fedidentity_feduser",+ "columns": [+ "federated_user_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_fedidentity_user",+ "columns": [+ "user_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk404288b92ef007a6",+ "column": "user_id",+ "ref_schema": "public",+ "ref_table": "user_entity",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "keycloak_role",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "client_realm_constraint",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "client_role",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "description",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "realm_id",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "client",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "realm",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ }+ ],+ "indexes": [+ {+ "name": "UK_J3RWUVD56ONTGSUHOGM184WW2-2",+ "columns": [+ "name",+ "client_realm_constraint"+ ],+ "is_unique": true,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "constraint_a",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_keycloak_role_client",+ "columns": [+ "client"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_keycloak_role_realm",+ "columns": [+ "realm"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk_6vyqfe4cn4wlq8r6kt5vdsj5c",+ "column": "realm",+ "ref_schema": "public",+ "ref_table": "realm",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "protocol_mapper",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "protocol",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "protocol_mapper_name",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "client_id",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "client_scope_id",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ }+ ],+ "indexes": [+ {+ "name": "constraint_pcm",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_clscope_protmap",+ "columns": [+ "client_scope_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_protocol_mapper_client",+ "columns": [+ "client_id"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk_cli_scope_mapper",+ "column": "client_scope_id",+ "ref_schema": "public",+ "ref_table": "client_scope",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ },+ {+ "name": "fk_pcm_realm",+ "column": "client_id",+ "ref_schema": "public",+ "ref_table": "client",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "protocol_mapper_config",+ "kind": "TABLE",+ "columns": [+ {+ "name": "protocol_mapper_id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "value",+ "data_type": "text",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ }+ ],+ "indexes": [+ {+ "name": "constraint_pmconfig",+ "columns": [+ "protocol_mapper_id",+ "name"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [+ {+ "name": "fk_pmconfig",+ "column": "protocol_mapper_id",+ "ref_schema": "public",+ "ref_table": "protocol_mapper",+ "ref_column": "id",+ "on_update": "NO ACTION",+ "on_delete": "NO ACTION"+ }+ ],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "realm",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "access_code_lifespan",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "user_action_lifespan",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "access_token_lifespan",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "account_theme",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "admin_theme",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "email_theme",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "events_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "events_expiration",+ "data_type": "bigint",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "login_theme",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "name",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "not_before",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "password_policy",+ "data_type": "character varying(2550)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 2550+ },+ {+ "name": "registration_allowed",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "remember_me",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "reset_password_allowed",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "social",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "ssl_required",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "sso_idle_timeout",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "sso_max_lifespan",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "update_profile_on_soc_login",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "verify_email",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "master_admin_client",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "login_lifespan",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "internationalization_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "default_locale",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "reg_email_as_username",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "admin_events_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "admin_events_details_enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "edit_username_allowed",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "otp_policy_counter",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "otp_policy_window",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "1",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "otp_policy_period",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "30",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "otp_policy_digits",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "6",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "otp_policy_alg",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": "'HmacSHA1'::character varying",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "otp_policy_type",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": "'totp'::character varying",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "browser_flow",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "registration_flow",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "direct_grant_flow",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "reset_credentials_flow",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "client_auth_flow",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "offline_session_idle_timeout",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "revoke_refresh_token",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "access_token_life_implicit",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "login_with_email_allowed",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "true",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "duplicate_emails_allowed",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "docker_auth_flow",+ "data_type": "character varying(36)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "refresh_token_max_reuse",+ "data_type": "integer",+ "is_nullable": true,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "allow_user_managed_access",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "sso_max_lifespan_remember_me",+ "data_type": "integer",+ "is_nullable": false,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "sso_idle_timeout_remember_me",+ "data_type": "integer",+ "is_nullable": false,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "default_role",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ }+ ],+ "indexes": [+ {+ "name": "constraint_4a",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_realm_master_adm_cli",+ "columns": [+ "master_admin_client"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "uk_orvsdmla56612eaefiq6wl5oi",+ "columns": [+ "name"+ ],+ "is_unique": true,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ },+ {+ "schema": "public",+ "name": "user_entity",+ "kind": "TABLE",+ "columns": [+ {+ "name": "id",+ "data_type": "character varying(36)",+ "is_nullable": false,+ "column_default": null,+ "is_primary_key": true,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 36+ },+ {+ "name": "email",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "email_constraint",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "email_verified",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "enabled",+ "data_type": "boolean",+ "is_nullable": false,+ "column_default": "false",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "federation_link",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "first_name",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "last_name",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "realm_id",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "username",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "created_timestamp",+ "data_type": "bigint",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ },+ {+ "name": "service_account_client_link",+ "data_type": "character varying(255)",+ "is_nullable": true,+ "column_default": null,+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": 255+ },+ {+ "name": "not_before",+ "data_type": "integer",+ "is_nullable": false,+ "column_default": "0",+ "is_primary_key": false,+ "extra": null,+ "comment": null,+ "numeric_precision": null,+ "numeric_scale": null,+ "character_maximum_length": null+ }+ ],+ "indexes": [+ {+ "name": "constraint_fb",+ "columns": [+ "id"+ ],+ "is_unique": true,+ "is_primary": true,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_user_email",+ "columns": [+ "email"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "idx_user_service_account",+ "columns": [+ "realm_id",+ "service_account_client_link"+ ],+ "is_unique": false,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "uk_dykn684sl8up1crfei6eckhd7",+ "columns": [+ "realm_id",+ "email_constraint"+ ],+ "is_unique": true,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ },+ {+ "name": "uk_ru8tt6t700s9v50bu18ws5ha6",+ "columns": [+ "realm_id",+ "username"+ ],+ "is_unique": true,+ "is_primary": false,+ "filter": null,+ "index_type": "btree",+ "included_columns": null,+ "comment": null+ }+ ],+ "foreignKeys": [],+ "groupId": null,+ "note": null,+ "noteSource": "NONE",+ "shadowedNote": null,+ "columnNotes": {},+ "estimatedRows": null,+ "viewDefinition": null+ }+ ],+ "relationships": [+ {+ "id": "public.client_attributes:fk3c47c64beacca966:client_id:client:id",+ "name": "fk3c47c64beacca966",+ "from": {+ "schema": "public",+ "table": "client_attributes",+ "column": "client_id"+ },+ "to": {+ "schema": "public",+ "table": "client",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.client_scope_attributes:fk_cl_scope_attr_scope:scope_id:client_scope:id",+ "name": "fk_cl_scope_attr_scope",+ "from": {+ "schema": "public",+ "table": "client_scope_attributes",+ "column": "scope_id"+ },+ "to": {+ "schema": "public",+ "table": "client_scope",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.composite_role:fk_a63wvekftu8jo1pnj81e7mce2:composite:keycloak_role:id",+ "name": "fk_a63wvekftu8jo1pnj81e7mce2",+ "from": {+ "schema": "public",+ "table": "composite_role",+ "column": "composite"+ },+ "to": {+ "schema": "public",+ "table": "keycloak_role",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.composite_role:fk_gr7thllb9lu8q4vqa4524jjy8:child_role:keycloak_role:id",+ "name": "fk_gr7thllb9lu8q4vqa4524jjy8",+ "from": {+ "schema": "public",+ "table": "composite_role",+ "column": "child_role"+ },+ "to": {+ "schema": "public",+ "table": "keycloak_role",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.credential:fk_pfyr0glasqyl0dei3kl69r6v0:user_id:user_entity:id",+ "name": "fk_pfyr0glasqyl0dei3kl69r6v0",+ "from": {+ "schema": "public",+ "table": "credential",+ "column": "user_id"+ },+ "to": {+ "schema": "public",+ "table": "user_entity",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.federated_identity:fk404288b92ef007a6:user_id:user_entity:id",+ "name": "fk404288b92ef007a6",+ "from": {+ "schema": "public",+ "table": "federated_identity",+ "column": "user_id"+ },+ "to": {+ "schema": "public",+ "table": "user_entity",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.keycloak_role:fk_6vyqfe4cn4wlq8r6kt5vdsj5c:realm:realm:id",+ "name": "fk_6vyqfe4cn4wlq8r6kt5vdsj5c",+ "from": {+ "schema": "public",+ "table": "keycloak_role",+ "column": "realm"+ },+ "to": {+ "schema": "public",+ "table": "realm",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.protocol_mapper:fk_cli_scope_mapper:client_scope_id:client_scope:id",+ "name": "fk_cli_scope_mapper",+ "from": {+ "schema": "public",+ "table": "protocol_mapper",+ "column": "client_scope_id"+ },+ "to": {+ "schema": "public",+ "table": "client_scope",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.protocol_mapper:fk_pcm_realm:client_id:client:id",+ "name": "fk_pcm_realm",+ "from": {+ "schema": "public",+ "table": "protocol_mapper",+ "column": "client_id"+ },+ "to": {+ "schema": "public",+ "table": "client",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ },+ {+ "id": "public.protocol_mapper_config:fk_pmconfig:protocol_mapper_id:protocol_mapper:id",+ "name": "fk_pmconfig",+ "from": {+ "schema": "public",+ "table": "protocol_mapper_config",+ "column": "protocol_mapper_id"+ },+ "to": {+ "schema": "public",+ "table": "protocol_mapper",+ "column": "id"+ },+ "cardinality": "MANY_TO_ONE",+ "onUpdate": "NO ACTION",+ "onDelete": "NO ACTION"+ }+ ],+ "groups": [+ {+ "id": "client-registry",+ "name": "Client Registry",+ "hue": 210,+ "note": "Tables describing registered clients and their protocol mappers."+ }+ ],+ "enums": [],+ "warnings": [+ {+ "kind": "orphanedNotes",+ "count": 1+ }+ ]+}\ No newline at end of filediff --git a/apps/desktop/src/docs/groupColor.ts b/apps/desktop/src/docs/groupColor.tsnew file mode 100644index 0000000000..4ca9c63e1a--- /dev/null+++ b/apps/desktop/src/docs/groupColor.ts@@ -0,0 +1,15 @@+/**+ * Inline style exposing a table group's hue to CSS.+ *+ * A group stores ONE number. Lightness and chroma are fixed per theme in the+ * stylesheet — `--group-c: oklch(0.55 0.15 var(--h))` in light,+ * `oklch(0.76 0.13 var(--h))` in dark — so every hue is legible on both+ * grounds by construction. Computing a colour here would throw that away.+ */+export function groupStyle(hue: number | null): Record<string, string> {+ if (hue === null) {+ return {};+ }+ const wrapped = ((Math.trunc(hue) % 360) + 360) % 360;+ return { "--h": String(wrapped) };+}diff --git a/apps/desktop/src/docs/renderNote.ts b/apps/desktop/src/docs/renderNote.tsnew file mode 100644index 0000000000..6557c01574--- /dev/null+++ b/apps/desktop/src/docs/renderNote.ts@@ -0,0 +1,78 @@+import { Marked } from "marked";++/** Escape the five characters that can break out of text or an attribute value. */+function escapeHtml(value: unknown): string {+ return (+ String(value ?? "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ // Single quotes too, so the escaper is self-sufficient. Every attribute+ // here is double-quoted today, which makes this redundant — but that is a+ // formatting convention enforced nowhere, and the day someone writes+ // title='...' it becomes the difference between escaping and a breakout.+ .replace(/'/g, "'")+ );+}++/**+ * URL allowlist. Blocklists lose: `javascript:` alone misses `JaVaScRiPt:`,+ * the entity-encoded `javascript:`, `vbscript:` and `data:text/html`.+ * Permitting only what we understand is both shorter and complete.+ */+const SAFE_SCHEME = /^(https?:|mailto:)/i;++function safeUrl(raw: unknown): string | null {+ const url = String(raw ?? "").trim();+ if (url === "") {+ return null;+ }+ // Protocol-relative. Harmless over https, but the Part 3b standalone export+ // is opened via file://, where //host/path is a UNC path — on Windows that+ // opens an SMB connection and leaks an NTLM hash, and images need no click.+ // Both separators must be rejected: the URL spec treats /\ exactly like //.+ if (/^[/\\]{2}/.test(url)) {+ return null;+ }+ if (url.startsWith("#") || url.startsWith("/") || url.startsWith("./") || url.startsWith("../")) {+ return url;+ }+ return SAFE_SCHEME.test(url) ? url : null;+}++const renderer = new Marked({+ renderer: {+ // Raw HTML in the source is shown as text, never rendered.+ html({ text }) {+ return escapeHtml(text);+ },+ link({ href, title, tokens }) {+ // `tokens`, not `text` — `text` is the raw markdown source, so returning+ // it would emit author HTML unescaped and swallow inline formatting.+ const inner = this.parser.parseInline(tokens);+ const safe = safeUrl(href);+ if (safe === null) {+ return inner;+ }+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";+ return `<a href="${escapeHtml(safe)}"${titleAttr}>${inner}</a>`;+ },+ image({ href, title, text }) {+ const safe = safeUrl(href);+ if (safe === null) {+ return escapeHtml(text);+ }+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";+ return `<img src="${escapeHtml(safe)}" alt="${escapeHtml(text)}"${titleAttr}>`;+ },+ },+});++/** Render a note's markdown to HTML with all author-supplied HTML escaped. */+export function renderNote(markdown: string | null): string {+ if (markdown === null || markdown.trim() === "") {+ return "";+ }+ return renderer.parse(markdown) as string;+}diff --git a/apps/desktop/src/docs/types.ts b/apps/desktop/src/docs/types.tsnew file mode 100644index 0000000000..b1b7573564--- /dev/null+++ b/apps/desktop/src/docs/types.ts@@ -0,0 +1,210 @@+// Mirrors crates/dbx-core/src/docs/snapshot.rs. There is no Rust->TS codegen+// in this repo, so this file is maintained by hand — see+// __tests__/fixtureConformance.spec.ts, which validates it against a snapshot+// generated by the real Rust code and fails if the two drift apart.++export type TableKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW";+export type NoteSource = "DATABASE" | "LOCAL" | "NONE";+export type Cardinality = "ONE_TO_ONE" | "MANY_TO_ONE";++export interface ColumnInfo {+ name: string;+ data_type: string;+ is_nullable: boolean;+ column_default: string | null;+ is_primary_key: boolean;+ extra: string | null;+ // No skip_serializing_if in Rust — these keys are ALWAYS present, so they+ // are required and may be null. Marking them optional would let `undefined`+ // reach code that checks `=== null`.+ comment: string | null;+ numeric_precision: number | null;+ numeric_scale: number | null;+ character_maximum_length: number | null;+ // These three DO carry skip_serializing_if, so the key is absent rather+ // than null when there is no value.+ enum_values?: string[];+ character_set?: string;+ collation?: string;+}++export interface IndexInfo {+ name: string;+ columns: string[];+ is_unique: boolean;+ is_primary: boolean;+ // No skip_serializing_if on any of these in Rust — required, may be null.+ filter: string | null;+ index_type: string | null;+ included_columns: string[] | null;+ comment: string | null;+}++export interface ForeignKeyInfo {+ name: string;+ column: string;+ ref_schema?: string | null;+ ref_table: string;+ ref_column: string;+ on_update?: string | null;+ on_delete?: string | null;+}++export interface ProjectMeta {+ name: string;+ databaseType: string;+ database: string | null;+ schemas: string[];+ generatedAt: string;+ note: string | null;+}++export interface ColumnNote {+ note: string;+ source: NoteSource;+ shadowed: string | null;+}++export interface DocTable {+ schema: string | null;+ name: string;+ kind: TableKind;+ columns: ColumnInfo[];+ indexes: IndexInfo[];+ foreignKeys: ForeignKeyInfo[];+ groupId: string | null;+ note: string | null;+ noteSource: NoteSource;+ shadowedNote: string | null;+ columnNotes: Record<string, ColumnNote>;+ estimatedRows: number | null;+ viewDefinition: string | null;+}++export interface TableGroup {+ id: string;+ name: string;+ /** 0-359. Lightness and chroma are theme-controlled in CSS. */+ hue: number;+ note: string | null;+}++export interface FieldRef {+ schema: string | null;+ table: string;+ column: string;+}++export interface Relationship {+ id: string;+ name: string | null;+ from: FieldRef;+ to: FieldRef;+ cardinality: Cardinality;+ onUpdate: string | null;+ onDelete: string | null;+}++export interface DocEnum {+ schema: string | null;+ name: string;+ values: string[];+ note: string | null;+ synthesized: boolean;+}++/**+ * Internally tagged on a camelCase `kind`. Note this differs from+ * TableKind/NoteSource/Cardinality, which are SCREAMING_SNAKE — the Rust enum+ * carries both `tag = "kind"` and `rename_all = "camelCase"`.+ */+export type SnapshotWarning =+ | { kind: "tableSkipped"; table: string; reason: string }+ | { kind: "noForeignKeyMetadata"; engine: string }+ | { kind: "commentsUnsupported"; engine: string }+ | { kind: "orphanedNotes"; count: number }+ | { kind: "dbmlOmitted"; table: string; item: string; reason: string };++export interface SchemaSnapshot {+ formatVersion: number;+ project: ProjectMeta;+ tables: DocTable[];+ relationships: Relationship[];+ groups: TableGroup[];+ enums: DocEnum[];+ warnings: SnapshotWarning[];+}++/** Mirrors `dbx_core::docs::annotations::ColumnAnnotation`. */+export interface ColumnAnnotation {+ note: string;+}++/** Mirrors `TableAnnotation`. Absent keys are omitted, never sent as null. */+export interface TableAnnotation {+ group?: string;+ note?: string;+ columns?: Record<string, ColumnAnnotation>;+}++/** Mirrors `GroupAnnotation`. `hue` is 0–359; lightness and chroma are the theme's. */+export interface GroupAnnotation {+ id: string;+ name: string;+ hue: number;+ note?: string;+}++/** Mirrors `ProjectAnnotation`. */+export interface ProjectAnnotation {+ name?: string;+ note?: string;+}++/**+ * The on-disk notes file. Rust declares `deny_unknown_fields`, so adding a+ * property here without adding it in Rust makes every save fail.+ */+export interface AnnotationFile {+ formatVersion: number;+ project?: ProjectAnnotation;+ groups?: GroupAnnotation[];+ tables?: Record<string, TableAnnotation>;+}++/**+ * What the viewer asks its host to do. The viewer never persists anything —+ * that is what keeps `src/docs/` free of backend calls and bundleable into a+ * standalone HTML file.+ */+export type DocsEdit =+ | { kind: "projectNote"; note: string }+ | { kind: "tableNote"; tableKey: string; note: string }+ | { kind: "columnNote"; tableKey: string; column: string; note: string }+ | { kind: "tableGroup"; tableKey: string; groupId: string | null }+ | { kind: "upsertGroup"; group: GroupAnnotation }+ | { kind: "removeGroup"; groupId: string };++/**+ * Runtime witnesses for the interfaces above.+ *+ * TypeScript types are erased at runtime, so a test cannot enumerate an+ * interface's keys. `Record<keyof T, true>` gives a value that IS enumerable+ * and that `vue-tsc` checks against the interface: add a field and this object+ * is missing a key; remove one and it carries an excess property. Either way+ * the build fails here rather than at a user's save.+ *+ * These live in this file, not in the spec, because `tsconfig.json` excludes+ * `src/**\/__tests__/**` from `vue-tsc` — witnesses in a spec file would be+ * checked by nothing.+ */+export const COLUMN_ANNOTATION_KEYS: Record<keyof ColumnAnnotation, true> = { note: true };+export const TABLE_ANNOTATION_KEYS: Record<keyof TableAnnotation, true> = { group: true, note: true, columns: true };+export const GROUP_ANNOTATION_KEYS: Record<keyof GroupAnnotation, true> = { id: true, name: true, hue: true, note: true };+export const PROJECT_ANNOTATION_KEYS: Record<keyof ProjectAnnotation, true> = { name: true, note: true };+export const ANNOTATION_FILE_KEYS: Record<keyof AnnotationFile, true> = {+ formatVersion: true,+ project: true,+ groups: true,+ tables: true,+};diff --git a/apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts b/apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.tsnew file mode 100644index 0000000000..76a5db3a64--- /dev/null+++ b/apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import en from "../locales/docs/en";+import es from "../locales/docs/es";+import it_ from "../locales/docs/it";+import ja from "../locales/docs/ja";+import ko from "../locales/docs/ko";+import ptBR from "../locales/docs/pt-BR";+import zhCN from "../locales/docs/zh-CN";+import zhTW from "../locales/docs/zh-TW";++// These import the per-locale DOCS modules, NOT ../locales/<name>.+//+// Every non-English locale file is `export default withEnglishFallback({...})`,+// which deep-merges `en` UNDER the locale at module level. Importing those+// default exports yields the ALREADY-MERGED object, so every locale appears to+// have every key and this test would pass while translations were missing —+// the fallback would silently defeat the test written to catch it.+const locales: Array<[string, Record<string, unknown>]> = [+ ["es", es],+ ["it", it_],+ ["ja", ja],+ ["ko", ko],+ ["pt-BR", ptBR],+ ["zh-CN", zhCN],+ ["zh-TW", zhTW],+];++function leafKeys(value: unknown, prefix = ""): string[] {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return [prefix];+ }+ return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) => leafKeys(child, prefix ? `${prefix}.${key}` : key));+}++describe("docs i18n namespace parity", () => {+ const expected = leafKeys(en as Record<string, unknown>).sort();++ it("english declares the docs namespace", () => {+ expect(expected.length, "locales/docs/en.ts must declare keys").toBeGreaterThan(0);+ });++ it.each(locales)("%s declares exactly the same docs keys as en", (_name, locale) => {+ expect(leafKeys(locale).sort()).toEqual(expected);+ });+});diff --git a/apps/desktop/src/i18n/locales/docs/en.ts b/apps/desktop/src/i18n/locales/docs/en.tsnew file mode 100644index 0000000000..f0f72d6342--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/en.ts@@ -0,0 +1,48 @@+export default {+ title: "Documentation",+ groupBySchema: "Schemas",+ groupByTableGroup: "Table Groups",+ noGroup: "(no group)",+ noSchema: "(no schema)",+ search: "Search tables, columns, groups…",+ columns: "Columns",+ indexes: "Indexes",+ references: "References",+ referencedBy: "Referenced by",+ localNote: "LOCAL",+ shadowedComment: "Database comment: {comment}",+ addNote: "Add a note",+ editNote: "Edit note",+ newGroup: "New group…",+ groupName: "Group name",+ groupColour: "Colour",+ deleteGroup: "Delete group",+ enumValues: "Values",+ usedBy: "Used by",+ openDiagram: "Open schema diagram",+ saving: "Saving…",+ saved: "Saved",+ saveFailed: "Could not save notes: {error}",+ warnings: {+ tableSkipped: {+ title: "A table could not be documented",+ detail: "{table} was skipped: {reason}. It is missing from this documentation.",+ },+ noForeignKeyMetadata: {+ title: "No relationships available",+ detail: "{engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.",+ },+ commentsUnsupported: {+ title: "Database comments unavailable",+ detail: "{engine} does not support table or column comments, so every description here comes from this project's own notes.",+ },+ orphanedNotes: {+ title: "Some notes no longer match anything",+ detail: "{count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.",+ },+ dbmlOmitted: {+ title: "Not representable in DBML",+ detail: "{item} on {table} is documented here but omitted from the exported DBML: {reason}.",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/es.ts b/apps/desktop/src/i18n/locales/docs/es.tsnew file mode 100644index 0000000000..eed9b3f0de--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/es.ts@@ -0,0 +1,48 @@+export default {+ title: "Documentación",+ groupBySchema: "Esquemas",+ groupByTableGroup: "Grupos de tablas",+ noGroup: "(sin grupo)",+ noSchema: "(sin esquema)",+ search: "Buscar tablas, columnas, grupos…",+ columns: "Columnas",+ indexes: "Índices",+ references: "Referencias",+ referencedBy: "Referenciado por",+ localNote: "LOCAL",+ shadowedComment: "Comentario de la base de datos: {comment}",+ addNote: "Agregar una nota",+ editNote: "Editar nota",+ newGroup: "Nuevo grupo…",+ groupName: "Nombre del grupo",+ groupColour: "Color",+ deleteGroup: "Eliminar grupo",+ enumValues: "Valores",+ usedBy: "Usado por",+ openDiagram: "Abrir diagrama del esquema",+ saving: "Guardando…",+ saved: "Guardado",+ saveFailed: "No se pudieron guardar las notas: {error}",+ warnings: {+ tableSkipped: {+ title: "No se pudo documentar una tabla",+ detail: "{table} fue omitida: {reason}. Falta en esta documentación.",+ },+ noForeignKeyMetadata: {+ title: "No hay relaciones disponibles",+ detail: "{engine} no reporta metadatos de claves foráneas, por lo que no se pudieron derivar relaciones. El diagrama está completo para este motor.",+ },+ commentsUnsupported: {+ title: "Comentarios de base de datos no disponibles",+ detail: "{engine} no admite comentarios en tablas o columnas, por lo que toda descripción aquí proviene de las notas de este proyecto.",+ },+ orphanedNotes: {+ title: "Algunas notas ya no coinciden con nada",+ detail: "{count} nota(s) hacen referencia a una tabla o columna que ya no existe. No se eliminó nada — vuelva a asignarlas o elimínelas en el archivo de notas.",+ },+ dbmlOmitted: {+ title: "No representable en DBML",+ detail: "{item} en {table} está documentado aquí pero se omitió del DBML exportado: {reason}.",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/it.ts b/apps/desktop/src/i18n/locales/docs/it.tsnew file mode 100644index 0000000000..c78a5e9fef--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/it.ts@@ -0,0 +1,48 @@+export default {+ title: "Documentazione",+ groupBySchema: "Schemi",+ groupByTableGroup: "Gruppi di tabelle",+ noGroup: "(nessun gruppo)",+ noSchema: "(nessuno schema)",+ search: "Cerca tabelle, colonne, gruppi…",+ columns: "Colonne",+ indexes: "Indici",+ references: "Riferimenti",+ referencedBy: "Referenziato da",+ localNote: "LOCALE",+ shadowedComment: "Commento del database: {comment}",+ addNote: "Aggiungi una nota",+ editNote: "Modifica nota",+ newGroup: "Nuovo gruppo…",+ groupName: "Nome del gruppo",+ groupColour: "Colore",+ deleteGroup: "Elimina gruppo",+ enumValues: "Valori",+ usedBy: "Usato da",+ openDiagram: "Apri diagramma dello schema",+ saving: "Salvataggio…",+ saved: "Salvato",+ saveFailed: "Impossibile salvare le note: {error}",+ warnings: {+ tableSkipped: {+ title: "Impossibile documentare una tabella",+ detail: "{table} è stata saltata: {reason}. Manca da questa documentazione.",+ },+ noForeignKeyMetadata: {+ title: "Nessuna relazione disponibile",+ detail: "{engine} non riporta i metadati delle chiavi esterne, quindi non è stato possibile derivare alcuna relazione. Il diagramma è completo per questo motore.",+ },+ commentsUnsupported: {+ title: "Commenti del database non disponibili",+ detail: "{engine} non supporta i commenti su tabelle o colonne, quindi ogni descrizione qui proviene dalle note di questo progetto.",+ },+ orphanedNotes: {+ title: "Alcune note non corrispondono più a nulla",+ detail: "{count} nota/e fanno riferimento a una tabella o colonna che non esiste più. Nulla è stato eliminato — rimappa o rimuovi queste note nel file delle note.",+ },+ dbmlOmitted: {+ title: "Non rappresentabile in DBML",+ detail: "{item} su {table} è documentato qui ma omesso dal DBML esportato: {reason}.",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/ja.ts b/apps/desktop/src/i18n/locales/docs/ja.tsnew file mode 100644index 0000000000..b8267a63ae--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/ja.ts@@ -0,0 +1,48 @@+export default {+ title: "ドキュメント",+ groupBySchema: "スキーマ",+ groupByTableGroup: "テーブルグループ",+ noGroup: "(グループなし)",+ noSchema: "(スキーマなし)",+ search: "テーブル、カラム、グループを検索…",+ columns: "カラム",+ indexes: "インデックス",+ references: "参照",+ referencedBy: "参照元",+ localNote: "ローカル",+ shadowedComment: "データベースのコメント: {comment}",+ addNote: "メモを追加",+ editNote: "メモを編集",+ newGroup: "新しいグループ…",+ groupName: "グループ名",+ groupColour: "色",+ deleteGroup: "グループを削除",+ enumValues: "値",+ usedBy: "使用元",+ openDiagram: "スキーマ図を開く",+ saving: "保存中…",+ saved: "保存済み",+ saveFailed: "メモを保存できませんでした: {error}",+ warnings: {+ tableSkipped: {+ title: "ドキュメント化できないテーブルがあります",+ detail: "{table} はスキップされました: {reason}。このドキュメントには含まれていません。",+ },+ noForeignKeyMetadata: {+ title: "リレーションシップを表示できません",+ detail: "{engine} は外部キーのメタデータを報告しないため、リレーションシップを導出できませんでした。この図はこのエンジンについては完全です。",+ },+ commentsUnsupported: {+ title: "データベースのコメントは利用できません",+ detail: "{engine} はテーブルやカラムのコメントをサポートしていないため、ここでの説明はすべてこのプロジェクトのメモから提供されています。",+ },+ orphanedNotes: {+ title: "対象がなくなったメモがあります",+ detail: "{count} 件のメモが、既に存在しないテーブルまたはカラムを参照しています。何も削除されていません。メモファイルで再割り当てまたは削除してください。",+ },+ dbmlOmitted: {+ title: "DBMLでは表現できません",+ detail: "{table} の {item} はここに記載されていますが、エクスポートされたDBMLからは除外されています: {reason}。",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/ko.ts b/apps/desktop/src/i18n/locales/docs/ko.tsnew file mode 100644index 0000000000..da6652376c--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/ko.ts@@ -0,0 +1,48 @@+export default {+ title: "문서",+ groupBySchema: "스키마",+ groupByTableGroup: "테이블 그룹",+ noGroup: "(그룹 없음)",+ noSchema: "(스키마 없음)",+ search: "테이블, 컬럼, 그룹 검색…",+ columns: "컬럼",+ indexes: "인덱스",+ references: "참조",+ referencedBy: "참조된 위치",+ localNote: "로컬",+ shadowedComment: "데이터베이스 코멘트: {comment}",+ addNote: "메모 추가",+ editNote: "메모 편집",+ newGroup: "새 그룹…",+ groupName: "그룹 이름",+ groupColour: "색상",+ deleteGroup: "그룹 삭제",+ enumValues: "값",+ usedBy: "사용처",+ openDiagram: "스키마 다이어그램 열기",+ saving: "저장 중…",+ saved: "저장됨",+ saveFailed: "메모를 저장할 수 없습니다: {error}",+ warnings: {+ tableSkipped: {+ title: "문서화할 수 없는 테이블이 있습니다",+ detail: "{table} 을(를) 건너뛰었습니다: {reason}. 이 문서에서 누락되었습니다.",+ },+ noForeignKeyMetadata: {+ title: "표시할 관계가 없습니다",+ detail: "{engine} 은(는) 외래 키 메타데이터를 보고하지 않으므로 관계를 도출할 수 없습니다. 이 엔진에 대해서는 다이어그램이 완전합니다.",+ },+ commentsUnsupported: {+ title: "데이터베이스 코멘트를 사용할 수 없습니다",+ detail: "{engine} 은(는) 테이블 또는 컬럼 코멘트를 지원하지 않으므로 여기의 모든 설명은 이 프로젝트의 메모에서만 제공됩니다.",+ },+ orphanedNotes: {+ title: "더 이상 일치하는 대상이 없는 메모가 있습니다",+ detail: "{count} 개의 메모가 더 이상 존재하지 않는 테이블 또는 컬럼을 참조하고 있습니다. 삭제된 항목은 없습니다 — 메모 파일에서 다시 매핑하거나 제거하세요.",+ },+ dbmlOmitted: {+ title: "DBML로 표현할 수 없습니다",+ detail: "{table} 의 {item} 은(는) 여기에 문서화되어 있지만 내보낸 DBML에서는 제외되었습니다: {reason}.",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/pt-BR.ts b/apps/desktop/src/i18n/locales/docs/pt-BR.tsnew file mode 100644index 0000000000..276d907081--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/pt-BR.ts@@ -0,0 +1,48 @@+export default {+ title: "Documentação",+ groupBySchema: "Schemas",+ groupByTableGroup: "Grupos de tabelas",+ noGroup: "(sem grupo)",+ noSchema: "(sem schema)",+ search: "Buscar tabelas, colunas, grupos…",+ columns: "Colunas",+ indexes: "Índices",+ references: "Referências",+ referencedBy: "Referenciado por",+ localNote: "LOCAL",+ shadowedComment: "Comentário do banco de dados: {comment}",+ addNote: "Adicionar uma nota",+ editNote: "Editar nota",+ newGroup: "Novo grupo…",+ groupName: "Nome do grupo",+ groupColour: "Cor",+ deleteGroup: "Excluir grupo",+ enumValues: "Valores",+ usedBy: "Usado por",+ openDiagram: "Abrir diagrama do schema",+ saving: "Salvando…",+ saved: "Salvo",+ saveFailed: "Não foi possível salvar as notas: {error}",+ warnings: {+ tableSkipped: {+ title: "Uma tabela não pôde ser documentada",+ detail: "{table} foi ignorada: {reason}. Ela está faltando nesta documentação.",+ },+ noForeignKeyMetadata: {+ title: "Nenhum relacionamento disponível",+ detail: "{engine} não reporta metadados de foreign key, então nenhum relacionamento pôde ser derivado. O diagrama está completo para este engine.",+ },+ commentsUnsupported: {+ title: "Comentários do banco de dados indisponíveis",+ detail: "{engine} não suporta comentários em tabelas ou colunas, então toda descrição aqui vem apenas das notas deste projeto.",+ },+ orphanedNotes: {+ title: "Algumas notas não correspondem mais a nada",+ detail: "{count} nota(s) referenciam uma tabela ou coluna que não existe mais. Nada foi excluído — remapeie ou remova essas notas no arquivo de notas.",+ },+ dbmlOmitted: {+ title: "Não representável em DBML",+ detail: "{item} em {table} está documentado aqui mas foi omitido do DBML exportado: {reason}.",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/zh-CN.ts b/apps/desktop/src/i18n/locales/docs/zh-CN.tsnew file mode 100644index 0000000000..c968bc8acc--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/zh-CN.ts@@ -0,0 +1,48 @@+export default {+ title: "文档",+ groupBySchema: "Schema",+ groupByTableGroup: "表分组",+ noGroup: "(无分组)",+ noSchema: "(无 Schema)",+ search: "搜索表、列、分组…",+ columns: "列",+ indexes: "索引",+ references: "引用",+ referencedBy: "被引用",+ localNote: "本地",+ shadowedComment: "数据库注释: {comment}",+ addNote: "添加备注",+ editNote: "编辑备注",+ newGroup: "新建分组…",+ groupName: "分组名称",+ groupColour: "颜色",+ deleteGroup: "删除分组",+ enumValues: "值",+ usedBy: "被使用于",+ openDiagram: "打开 Schema 图",+ saving: "保存中…",+ saved: "已保存",+ saveFailed: "无法保存备注: {error}",+ warnings: {+ tableSkipped: {+ title: "有一张表无法生成文档",+ detail: "{table} 被跳过: {reason}。此文档中缺少该表。",+ },+ noForeignKeyMetadata: {+ title: "没有可用的关系",+ detail: "{engine} 不报告外键元数据,因此无法推导出任何关系。此图对该数据库引擎而言已经完整。",+ },+ commentsUnsupported: {+ title: "数据库注释不可用",+ detail: "{engine} 不支持表或列注释,因此这里的所有描述均仅来自本项目的备注。",+ },+ orphanedNotes: {+ title: "部分备注已不再对应任何内容",+ detail: "{count} 条备注引用的表或列已不存在。没有任何内容被删除 — 请在备注文件中重新映射或移除它们。",+ },+ dbmlOmitted: {+ title: "无法在 DBML 中表示",+ detail: "{table} 上的 {item} 已在此处记录,但已从导出的 DBML 中省略: {reason}。",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/docs/zh-TW.ts b/apps/desktop/src/i18n/locales/docs/zh-TW.tsnew file mode 100644index 0000000000..48a53fd047--- /dev/null+++ b/apps/desktop/src/i18n/locales/docs/zh-TW.ts@@ -0,0 +1,48 @@+export default {+ title: "文件",+ groupBySchema: "Schema",+ groupByTableGroup: "資料表分組",+ noGroup: "(無分組)",+ noSchema: "(無 Schema)",+ search: "搜尋資料表、欄位、分組…",+ columns: "欄位",+ indexes: "索引",+ references: "參照",+ referencedBy: "被參照",+ localNote: "本機",+ shadowedComment: "資料庫註解: {comment}",+ addNote: "新增備註",+ editNote: "編輯備註",+ newGroup: "新增分組…",+ groupName: "分組名稱",+ groupColour: "顏色",+ deleteGroup: "刪除分組",+ enumValues: "值",+ usedBy: "被使用於",+ openDiagram: "開啟 Schema 圖",+ saving: "儲存中…",+ saved: "已儲存",+ saveFailed: "無法儲存備註: {error}",+ warnings: {+ tableSkipped: {+ title: "有一張資料表無法產生文件",+ detail: "{table} 被略過: {reason}。此文件中缺少該資料表。",+ },+ noForeignKeyMetadata: {+ title: "沒有可用的關聯",+ detail: "{engine} 未回報外鍵中繼資料,因此無法推導出任何關聯。此圖對該資料庫引擎而言已經完整。",+ },+ commentsUnsupported: {+ title: "資料庫註解無法使用",+ detail: "{engine} 不支援資料表或欄位註解,因此這裡的所有說明均僅來自本專案的備註。",+ },+ orphanedNotes: {+ title: "部分備註已不再對應任何內容",+ detail: "{count} 筆備註參照的資料表或欄位已不存在。沒有任何內容被刪除 — 請在備註檔案中重新對應或移除它們。",+ },+ dbmlOmitted: {+ title: "無法在 DBML 中表示",+ detail: "{table} 上的 {item} 已在此處記錄,但已從匯出的 DBML 中省略: {reason}。",+ },+ },+};diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex dde8a373f8..000e963cdd 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1,7 +1,10 @@+import docs from "./docs/en";+export default {app: {name: "DBX",},+ docs,auth: {rateLimited: "Please try again in {seconds}s",setupTitle: "Set up access password",@@ -770,6 +773,9 @@ export default {readOnlyHint: "Block all write operations (INSERT, UPDATE, DELETE, etc.)",showSystemSchemas: "Show System Schemas",showSystemSchemasHint: "Show built-in and metadata schemas in the sidebar and schema pickers for this connection.",+ docsNotesPath: "Notes file",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "Where documentation notes are stored. Leave empty to keep them in the app data directory, or point this at a file in your repository to review schema documentation in pull requests.",readOnlyBadge: "Read-only",proxy: "Proxy",proxyEnable: "Connect database through proxy",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 3c2dc5735c..3372df01aa 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1,9 +1,11 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/es";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "Vuelva a intentarlo en {seconds} s",setupTitle: "Configurar contraseña de acceso",@@ -750,6 +752,9 @@ export default withEnglishFallback({jdbcMissingRuntimeDependencyHint: "El controlador JDBC actual carece de dependencias de ejecución. Utilice las coordenadas Maven en 'Administración de controladores' para instalar, o importe el controlador y todos los JAR de dependencia de una vez.",showSystemSchemas: "Mostrar Schema del sistema",showSystemSchemasHint: "Mostrar el Schema integrado/de metadatos para la conexión actual en la barra lateral y el selector de Schema.",+ docsNotesPath: "Archivo de notas",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "Dónde se guardan las notas de documentación. Déjalo vacío para mantenerlas en el directorio de datos de la aplicación, o apunta a un archivo de tu repositorio para revisar la documentación del schema en los pull requests.",sshHostKeyVerifyTitle: "Confirmar clave de host SSH desconocida",sshHostKeyVerifyMessage: "No se puede confirmar la autenticidad del host '{host}:{port}'. Para evitar ataques de intermediario, verifique la huella digital de la clave del host con el administrador del servidor antes de continuar.",sshHostKeyVerifyKeyType: "Tipo de clave",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex ea5ec212f1..12187f806f 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1,8 +1,10 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/it";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "Riprova tra {seconds} s",setupTitle: "Imposta la password di accesso",@@ -748,6 +750,9 @@ export default withEnglishFallback({jdbcMissingRuntimeDependencyHint: "Il driver JDBC corrente manca di dipendenze runtime. Installare utilizzando le coordinate Maven in 'Gestione driver', o importare il driver e tutti i JAR delle dipendenze in una volta.",showSystemSchemas: "Mostra Schema di sistema",showSystemSchemasHint: "Mostra lo Schema built-in/di metadati nella barra laterale e nel selettore Schema per la connessione corrente.",+ docsNotesPath: "File delle note",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "Dove vengono salvate le note della documentazione. Lascia vuoto per tenerle nella directory dati dell'applicazione, oppure indica un file nel tuo repository per revisionare la documentazione dello schema nelle pull request.",sshHostKeyVerifyTitle: "Conferma chiave host SSH sconosciuta",sshHostKeyVerifyMessage: "Impossibile confermare l'autenticità dell'host '{host}:{port}'. Per prevenire attacchi man-in-the-middle, verifica l'impronta della chiave host con l'amministratore del server prima di procedere.",sshHostKeyVerifyKeyType: "Tipo di chiave",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex ac45c67183..ae61cd09f0 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1,9 +1,11 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/ja";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "{seconds} 秒後に再試行してください",setupTitle: "アクセスパスワードを設定",@@ -748,6 +750,9 @@ export default withEnglishFallback({jdbcMissingRuntimeDependencyHint: "現在のJDBCドライバーには実行依存関係が不足しています。「ドライバ管理」でMaven座標を使用してインストールするか、ドライバーとすべての依存JARを一度にインポートしてください。",showSystemSchemas: "システムスキーマを表示",showSystemSchemasHint: "現在の接続で、サイドバーとスキーマセレクターに組み込み/メタデータスキーマを表示します。",+ docsNotesPath: "ノートファイル",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "ドキュメントのノートの保存先です。空のままにするとアプリのデータディレクトリに保存されます。リポジトリ内のファイルを指定すると、スキーマのドキュメントをプルリクエストでレビューできます。",sshHostKeyVerifyTitle: "不明なSSHホストキーの確認",sshHostKeyVerifyMessage: "ホスト '{host}:{port}' の正当性を確認できません。中間者攻撃を防ぐため、続行する前にサーバー管理者にホストキーのフィンガープリントを確認してください。",sshHostKeyVerifyKeyType: "キータイプ",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 556d965669..b9ca6feb38 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1,9 +1,11 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/ko";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "{seconds}초 후에 다시 시도해 주세요",setupTitle: "접속 비밀번호 설정",@@ -687,6 +689,9 @@ export default withEnglishFallback({readOnlyHint: "모든 쓰기 작업 차단 (INSERT, UPDATE, DELETE 등)",showSystemSchemas: "시스템 스키마 표시",showSystemSchemasHint: "이 연결의 사이드바와 스키마 선택기에 내장 및 메타데이터 스키마를 표시합니다.",+ docsNotesPath: "노트 파일",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "문서 노트를 저장할 위치입니다. 비워 두면 앱 데이터 디렉터리에 저장되며, 저장소 내 파일을 지정하면 스키마 문서를 풀 리퀘스트에서 검토할 수 있습니다.",readOnlyBadge: "읽기 전용",proxy: "프록시",proxyEnable: "프록시를 통해 데이터베이스 연결",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex ddd3120f0b..a303d356e5 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1,9 +1,11 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/pt-BR";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "Tente novamente em {seconds}s",setupTitle: "Configurar senha de acesso",@@ -749,6 +751,9 @@ export default withEnglishFallback({jdbcMissingRuntimeDependencyHint: "O driver JDBC atual está sem dependências de execução. Por favor, instale-o usando as coordenadas Maven no 'Gerenciamento de Drivers' ou importe o driver e todos os JARs de dependência de uma só vez.",showSystemSchemas: "Mostrar Schema do sistema",showSystemSchemasHint: "Exibir Schemas de sistema/metadados integrados na barra lateral e no seletor de Schema para a conexão atual.",+ docsNotesPath: "Arquivo de notas",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "Onde as notas da documentação são gravadas. Deixe vazio para mantê-las no diretório de dados do aplicativo, ou aponte para um arquivo do seu repositório para revisar a documentação do schema em pull requests.",sshHostKeyVerifyTitle: "Confirmar chave de host SSH desconhecida",sshHostKeyVerifyMessage: "Não foi possível confirmar a autenticidade do host '{host}:{port}'. Para evitar ataques man-in-the-middle, verifique a impressão digital da chave do host com o administrador do servidor antes de continuar.",sshHostKeyVerifyKeyType: "Tipo de chave",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 58c67e3488..c4a1bb0ec9 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1,9 +1,11 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/zh-CN";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "请 {seconds} 秒后再试",setupTitle: "设置访问密码",@@ -774,6 +776,9 @@ export default withEnglishFallback({readOnlyHint: "阻止所有写操作(INSERT、UPDATE、DELETE 等)",showSystemSchemas: "显示系统 Schema",showSystemSchemasHint: "为当前连接在侧边栏和 Schema 选择器中显示内置/元数据 Schema。",+ docsNotesPath: "笔记文件",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "文档笔记的存储位置。留空则保存在应用数据目录中;指向仓库中的文件后,即可在 Pull Request 中审阅 Schema 文档。",readOnlyBadge: "只读",proxy: "代理",proxyEnable: "通过代理连接数据库",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex c62aec579b..086d6c15c7 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1,9 +1,11 @@import { withEnglishFallback } from "./fallback";+import docs from "./docs/zh-TW";export default withEnglishFallback({app: {name: "DBX",},+ docs,auth: {rateLimited: "請 {seconds} 秒後再試",setupTitle: "設定存取密碼",@@ -748,6 +750,9 @@ export default withEnglishFallback({jdbcMissingRuntimeDependencyHint: "目前 JDBC 驅動缺少執行依賴。請在「驅動管理」中使用 Maven 座標安裝,或一次匯入驅動及全部依賴 JAR。",showSystemSchemas: "顯示系統 Schema",showSystemSchemasHint: "為目前連線在側邊欄和 Schema 選擇器中顯示內建/中繼資料 Schema。",+ docsNotesPath: "筆記檔案",+ docsNotesPathPlaceholder: "docs/dbx-docs.json",+ docsNotesPathHint: "文件筆記的儲存位置。留空則儲存在應用程式資料目錄中;指向存放庫中的檔案後,即可在 Pull Request 中審閱 Schema 文件。",sshHostKeyVerifyTitle: "確認未知的 SSH 主機金鑰",sshHostKeyVerifyMessage: "無法確認主機 '{host}:{port}' 的真實性。為防止中間人攻擊,請在繼續前與伺服器管理員核對主機金鑰指紋。",sshHostKeyVerifyKeyType: "金鑰類型",diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex 3dfa128ab0..152502cfaa 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -179,6 +179,12 @@ export const prepareSchemaDiff = forward("prepareSchemaDiff");export const generateSchemaSyncSql = forward("generateSchemaSyncSql");export const listDialectDataTypes = forward("listDialectDataTypes");+// Docs+export const collectDocsSnapshot = forward("collectDocsSnapshot");+export const loadDocsAnnotations = forward("loadDocsAnnotations");+export const applyDocsAnnotations = forward("applyDocsAnnotations");+export const saveDocsAnnotations = forward("saveDocsAnnotations");+// Queryexport const executeQuery = forward("executeQuery");export const executeMulti = forward("executeMulti");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex bead2fe855..dac91dc842 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -202,6 +202,7 @@ import type {} from "@/types/nacos";import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";import { normalizeConnectionTestResult } from "@/lib/connection/connectionDatabaseInfo";+import type { AnnotationFile, SchemaSnapshot } from "@/docs/types";// ---------------------------------------------------------------------------// Helpers@@ -839,6 +840,26 @@ export async function listDialectDataTypes(dialectName: string): Promise<string[return get(`/api/dialect/data-types?${qs({ dialect_name: dialectName })}`);}+// ---------------------------------------------------------------------------+// Docs+// ---------------------------------------------------------------------------++export async function collectDocsSnapshot(connectionId: string, database: string, schemas: string[], tables: string[], projectName?: string): Promise<SchemaSnapshot> {+ return post("/api/docs/snapshot", { connectionId, database, schemas, tables, projectName });+}++export async function loadDocsAnnotations(connectionId: string): Promise<AnnotationFile | null> {+ return post("/api/docs/annotations/load", { connectionId });+}++export async function applyDocsAnnotations(connectionId: string, snapshot: SchemaSnapshot, annotations: AnnotationFile): Promise<SchemaSnapshot> {+ return post("/api/docs/annotations/apply", { connectionId, snapshot, annotations });+}++export async function saveDocsAnnotations(connectionId: string, annotations: AnnotationFile): Promise<void> {+ return post("/api/docs/annotations/save", { connectionId, annotations });+}+// ---------------------------------------------------------------------------// Query// ---------------------------------------------------------------------------diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex fe7bff357e..f757116e85 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -59,6 +59,7 @@ import type {ExternalSqlFileVersion,} from "@/types/database";import { isTauriCommandUnavailable, normalizeConnectionTestResult } from "@/lib/connection/connectionDatabaseInfo";+import type { AnnotationFile, SchemaSnapshot } from "@/docs/types";import type { CollectionInfo } from "@/types/database";import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";import type { AiChatSelectionState, AiConfig, AiConfigItem, AiEffortCapability, AiEffortLevel, AiTestConnectionResult } from "@/types/ai";@@ -1662,6 +1663,24 @@ export async function listAvailableExtensions(connectionId: string, database: streturn invoke("list_available_extensions", { connectionId, database });}+// --- Docs ---++export async function collectDocsSnapshot(connectionId: string, database: string, schemas: string[], tables: string[], projectName?: string): Promise<SchemaSnapshot> {+ return invoke("docs_collect_snapshot", { connectionId, database, schemas, tables, projectName });+}++export async function loadDocsAnnotations(connectionId: string): Promise<AnnotationFile | null> {+ return invoke("docs_load_annotations", { connectionId });+}++export async function applyDocsAnnotations(connectionId: string, snapshot: SchemaSnapshot, annotations: AnnotationFile): Promise<SchemaSnapshot> {+ return invoke("docs_apply_annotations", { connectionId, snapshot, annotations });+}++export async function saveDocsAnnotations(connectionId: string, annotations: AnnotationFile): Promise<void> {+ return invoke("docs_save_annotations", { connectionId, annotations });+}+export async function saveConnections(configs: ConnectionConfig[]): Promise<void> {return invoke("save_connections", { configs });}diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.tsindex 1a1ce391a9..32d4e62f6a 100644--- a/apps/desktop/src/stores/connectionStore.ts+++ b/apps/desktop/src/stores/connectionStore.ts@@ -389,6 +389,12 @@ export const useConnectionStore = defineStore("connection", () => {schema?: string;tableName?: string;} | null>(null);+ const docsSource = ref<{+ connectionId: string;+ database: string;+ schema?: string;+ tableName?: string;+ } | null>(null);const tableImportSource = ref<{connectionId: string;database: string;@@ -1052,6 +1058,10 @@ export const useConnectionStore = defineStore("connection", () => {agent_java_options: Array.isArray(config.agent_java_options) ? config.agent_java_options : [],attached_databases: Array.isArray(config.attached_databases) ? config.attached_databases.filter((database) => database.name?.trim() && database.path?.trim()) : [],init_script: config.init_script?.trim() ? config.init_script : undefined,+ // A cleared field must become absent, not "". `resolve_notes_path` treats+ // blank as unset anyway, but an empty string would still be written to+ // the config file as though a path had been chosen.+ docs_notes_path: config.docs_notes_path?.trim() ? config.docs_notes_path.trim() : undefined,transport_layers: Array.isArray(config.transport_layers) ? config.transport_layers : [],show_system_schemas: config.show_system_schemas === true,connect_timeout_secs: config.connect_timeout_secs || 10,@@ -7059,6 +7069,7 @@ export const useConnectionStore = defineStore("connection", () => {dataCompareSource,sqlFileSource,diagramSource,+ docsSource,tableImportSource,tableDataGenerateSource,fieldLineageSource,diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 53484f2b9a..cbeb9f82dc 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -144,6 +144,12 @@ export interface ConnectionConfig {attached_databases?: AttachedDatabaseConfig[];init_script?: string;color?: string;+ /**+ * Where this connection's documentation notes are stored. Absent means the+ * per-connection default inside the app data directory; an explicit path+ * lets the notes file live in a repository and be reviewed in pull requests.+ */+ docs_notes_path?: string;transport_layers?: TransportLayerConfig[];connect_timeout_secs?: number;query_timeout_secs?: number;diff --git a/crates/dbx-cli/src/main.rs b/crates/dbx-cli/src/main.rsindex eed169680d..a8477f5489 100644--- a/crates/dbx-cli/src/main.rs+++ b/crates/dbx-cli/src/main.rs@@ -7,6 +7,7 @@ use dbx_core::{types::{ColumnInfo, QueryResult, TableInfo},};use dbx_mcp::{+ backend::DocsSnapshotOptions,mongo::{self, MongoSafetyError},DbxBackend, LocalBackend, WebBackend,};@@ -91,6 +92,8 @@ struct Flags {max_rows: Option<usize>,timeout_ms: Option<u64>,file: Option<PathBuf>,+ out: Option<PathBuf>,+ notes: Option<PathBuf>,allow_writes: bool,allow_dangerous: bool,help: bool,@@ -109,6 +112,22 @@ impl CliError {}}+/// `--notes` names a file explicitly, so a missing one is a typo rather than+/// "no notes yet".+///+/// `load_annotations` deliberately returns `Ok(None)` for a missing file,+/// because the implicit per-connection notes path may legitimately not exist+/// yet. That is the right behaviour there and the wrong behaviour here: without+/// this check, `--notes ./typo.json` produces DBML with every note silently+/// absent and no diagnostic at all, which reads exactly like a database that+/// has no documentation.+fn require_notes_file(path: &std::path::Path) -> Result<(), CliError> {+ if path.exists() {+ return Ok(());+ }+ Err(CliError::new("NOTES_NOT_FOUND", format!("Notes file {} does not exist.", path.display())))+}+#[derive(Serialize)]#[serde(rename_all = "camelCase")]struct Diagnostics {@@ -223,6 +242,9 @@ async fn run_with_backend(backend: &dyn DbxBackend, flags: Flags) -> Result<Striif args.first().is_some_and(|arg| arg == "context") {return run_context(backend, &flags).await;}+ if args.first().is_some_and(|arg| arg == "dbml") {+ return run_dbml(backend, &flags).await;+ }if args.first().is_some_and(|arg| arg == "open") {ensure_arg_count(args, 3, "dbx open")?;let connection = required(args.get(1), "Connection name is required.")?;@@ -436,6 +458,46 @@ async fn run_context(backend: &dyn DbxBackend, flags: &Flags) -> Result<String,Ok(output)}+async fn run_dbml(backend: &dyn DbxBackend, flags: &Flags) -> Result<String, CliError> {+ let args = &flags.args;+ let connection_name = required(args.get(1), "Connection name is required.")?;+ let connection = find_connection(backend, connection_name).await?;+ let database = selected_database(&connection, flags.database.as_deref());++ let options = DocsSnapshotOptions {+ schemas: flags.schema.clone().into_iter().collect(),+ tables: flags.tables.clone(),+ project_name: Some(connection.name.clone()),+ };++ let mut snapshot = backend.collect_docs_snapshot(&connection, &database, options).await.map_err(command_error)?;++ if let Some(path) = flags.notes.as_ref() {+ require_notes_file(path)?;+ if let Some(annotations) = dbx_core::docs::annotations::load_annotations(path)+ .map_err(|error| CliError::new("NOTES_INVALID", error))?+ {+ dbx_core::docs::annotations::apply_annotations(&mut snapshot, &annotations, connection.db_type);+ }+ }++ let output = dbx_core::docs::to_dbml(&snapshot);++ for warning in &output.warnings {+ eprintln!("warning: {warning}");+ }++ match flags.out.as_ref() {+ Some(path) => {+ std::fs::write(path, &output.text).map_err(|error| {+ CliError::new("WRITE_FAILED", format!("Failed to write {}: {error}", path.display()))+ })?;+ Ok(format!("Wrote {} bytes to {}", output.text.len(), path.display()))+ }+ None => Ok(output.text),+ }+}+async fn find_connection(backend: &dyn DbxBackend, name: &str) -> Result<ConnectionConfig, CliError> {backend.load_connections()@@ -461,6 +523,8 @@ fn parse_flags(argv: &[String]) -> Result<Flags, CliError> {max_rows: None,timeout_ms: None,file: None,+ out: None,+ notes: None,allow_writes: false,allow_dangerous: false,help: false,@@ -505,6 +569,8 @@ fn parse_flags(argv: &[String]) -> Result<Flags, CliError> {flags.timeout_ms = Some(duration_ms(&option_value(argv, &mut index, "--timeout")?, "--timeout")?)}"--file" => flags.file = Some(PathBuf::from(option_value(argv, &mut index, "--file")?)),+ "--out" => flags.out = Some(PathBuf::from(option_value(argv, &mut index, "--out")?)),+ "--notes" => flags.notes = Some(PathBuf::from(option_value(argv, &mut index, "--notes")?)),"--allow-writes" => flags.allow_writes = true,"--allow-dangerous-sql" => flags.allow_dangerous = true,value if value.starts_with('-') => {@@ -833,12 +899,31 @@ fn csv_cell(value: &str) -> String {}fn usage() -> &'static str {- "Usage:\n dbx doctor [--json]\n dbx capabilities [--json]\n dbx connections list [--json]\n dbx schema list <connection> [--schema name] [--json]\n dbx schema describe <connection> <table> [--schema name] [--json]\n dbx query <connection> <sql> [--file path] [--limit n] [--timeout 10s] [--allow-writes] [--allow-dangerous-sql] [--json]\n dbx context <connection> [--schema name] [--tables a,b] [--max-tables n] [--json]\n dbx open <connection> <table> [--schema name] [--database name] [--json]"+ "Usage:\n dbx doctor [--json]\n dbx capabilities [--json]\n dbx connections list [--json]\n dbx schema list <connection> [--schema name] [--json]\n dbx schema describe <connection> <table> [--schema name] [--json]\n dbx query <connection> <sql> [--file path] [--limit n] [--timeout 10s] [--allow-writes] [--allow-dangerous-sql] [--json]\n dbx context <connection> [--schema name] [--tables a,b] [--max-tables n] [--json]\n dbx dbml <connection> [--out path] [--notes path] [--schema name] [--database name] [--tables a,b]\n dbx open <connection> <table> [--schema name] [--database name] [--json]"}#[cfg(test)]mod tests {use super::*;++ #[test]+ fn require_notes_file_accepts_an_existing_file() {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("notes.json");+ std::fs::write(&path, "{}").expect("write");+ assert!(require_notes_file(&path).is_ok());+ }++ #[test]+ fn require_notes_file_rejects_a_mistyped_path() {+ // The regression: without this, `--notes ./typo.json` emitted DBML with+ // every note missing and printed nothing, indistinguishable from a+ // database that genuinely has no documentation.+ let dir = tempfile::tempdir().expect("tempdir");+ let error = require_notes_file(&dir.path().join("typo.json")).expect_err("missing file must error");+ assert_eq!(error.code, "NOTES_NOT_FOUND");+ assert!(error.message.contains("typo.json"), "message names the path: {}", error.message);+ }use async_trait::async_trait;use dbx_core::{agent_events::ToolResult,@@ -1057,4 +1142,40 @@ mod tests {.unwrap();run_with_backend(&backend, cleanup).await.expect("final cleanup");}++ #[test]+ fn parses_the_out_flag() {+ let flags = parse_flags(&args(&["dbml", "local", "--out", "schema.dbml"])).expect("parse");+ assert_eq!(flags.args, args(&["dbml", "local"]));+ assert_eq!(flags.out.as_deref(), Some(std::path::Path::new("schema.dbml")));+ }++ #[test]+ fn out_requires_a_value() {+ let error = parse_flags(&args(&["dbml", "local", "--out"])).expect_err("should fail");+ assert_eq!(error.code, "INVALID_OPTION");+ }++ #[test]+ fn parses_the_notes_flag() {+ let flags = parse_flags(&args(&["dbml", "local", "--notes", "docs/dbx-docs.json"])).expect("parse");+ assert_eq!(flags.args, args(&["dbml", "local"]));+ assert_eq!(flags.notes.as_deref(), Some(std::path::Path::new("docs/dbx-docs.json")));+ }++ #[test]+ fn notes_requires_a_value() {+ let error = parse_flags(&args(&["dbml", "local", "--notes"])).expect_err("should fail");+ assert_eq!(error.code, "INVALID_OPTION");+ }++ #[test]+ fn notes_appears_in_the_usage_text() {+ assert!(usage().contains("--notes"), "got: {}", usage());+ }++ #[test]+ fn dbml_appears_in_the_usage_text() {+ assert!(usage().contains("dbx dbml <connection>"), "got: {}", usage());+ }}diff --git a/crates/dbx-core/examples/table_import_live_bench.rs b/crates/dbx-core/examples/table_import_live_bench.rsindex df01227f1a..8bcecc4fd8 100644--- a/crates/dbx-core/examples/table_import_live_bench.rs+++ b/crates/dbx-core/examples/table_import_live_bench.rs@@ -151,6 +151,7 @@ fn env_required(name: &str) -> Result<String, String> {fn connection_config(id: &str, database: BenchDatabase) -> Result<ConnectionConfig, String> {let database_name = env_required("DBX_BENCH_DATABASE")?;Ok(ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: id.to_string(),note: String::new(),diff --git a/crates/dbx-core/src/agent_connection.rs b/crates/dbx-core/src/agent_connection.rsindex de94bde594..d88215bace 100644--- a/crates/dbx-core/src/agent_connection.rs+++ b/crates/dbx-core/src/agent_connection.rs@@ -634,6 +634,7 @@ mod tests {fn config(db_type: DatabaseType, database: Option<&str>) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "conn".to_string(),name: "Connection".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/agent_tools.rs b/crates/dbx-core/src/agent_tools.rsindex eee9f58aa4..97b53875e4 100644--- a/crates/dbx-core/src/agent_tools.rs+++ b/crates/dbx-core/src/agent_tools.rs@@ -1151,6 +1151,7 @@ for line in sys.stdin:#[cfg(unix)]fn agent_test_connection(id: &str, name: &str, db_type: DatabaseType, database: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: name.to_string(),note: String::new(),diff --git a/crates/dbx-core/src/cloud_sync.rs b/crates/dbx-core/src/cloud_sync.rsindex acdfad3d21..6ac9ae6afe 100644--- a/crates/dbx-core/src/cloud_sync.rs+++ b/crates/dbx-core/src/cloud_sync.rs@@ -1471,6 +1471,7 @@ mod tests {fn postgres_connection(id: &str, password: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: "Postgres".to_string(),note: String::new(),@@ -1528,6 +1529,7 @@ mod tests {fn nacos_connection(id: &str, password: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: "Nacos".to_string(),note: String::new(),@@ -1622,6 +1624,7 @@ mod tests {#[test]fn scrubs_connection_secret_fields() {let mut config = ConnectionConfig {+ docs_notes_path: None,id: "id".to_string(),name: "name".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rsindex 8ce48acb9e..acb338f39a 100644--- a/crates/dbx-core/src/connection.rs+++ b/crates/dbx-core/src/connection.rs@@ -4987,6 +4987,7 @@ mod tests {fn mysql_config(database: Option<&str>) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "conn".to_string(),name: "MySQL".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/connection_secrets.rs b/crates/dbx-core/src/connection_secrets.rsindex eca355c1f2..4ebd5d7701 100644--- a/crates/dbx-core/src/connection_secrets.rs+++ b/crates/dbx-core/src/connection_secrets.rs@@ -824,6 +824,7 @@ mod tests {fn connection(id: &str, password: &str, _ssh_password: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: format!("{id} connection"),note: String::new(),diff --git a/crates/dbx-core/src/db/redis_driver.rs b/crates/dbx-core/src/db/redis_driver.rsindex e268b32205..3ead27c421 100644--- a/crates/dbx-core/src/db/redis_driver.rs+++ b/crates/dbx-core/src/db/redis_driver.rs@@ -5333,6 +5333,7 @@ mod tests {fn redis_test_connection_config() -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "redis".to_string(),name: "Redis".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/docs/annotations.rs b/crates/dbx-core/src/docs/annotations.rsnew file mode 100644index 0000000000..ec28dc143e--- /dev/null+++ b/crates/dbx-core/src/docs/annotations.rs@@ -0,0 +1,873 @@+use std::collections::BTreeMap;+use std::io::Write;+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use crate::docs::keys::{column_key, fold_identifier, table_key};+use crate::docs::{ColumnNote, NoteSource, SchemaSnapshot, SnapshotWarning, TableGroup};+use crate::models::connection::DatabaseType;++/// The on-disk notes file. This IS the store — not a cache of anything.+/// It is meant to be committed to a repository and reviewed in pull+/// requests, so it must stay small, readable, and stable in key order.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct AnnotationFile {+ pub format_version: u32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub project: Option<ProjectAnnotation>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub groups: Vec<GroupAnnotation>,+ /// Keyed by `schema.table` (or bare `table` on schema-less engines).+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub tables: BTreeMap<String, TableAnnotation>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct ProjectAnnotation {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// Markdown. Becomes the documentation landing page.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct GroupAnnotation {+ /// Stable slug, referenced by `TableAnnotation::group`.+ pub id: String,+ pub name: String,+ /// 0..=359. Lightness and chroma are theme-controlled, so any hue is+ /// legible on both light and dark grounds by construction.+ pub hue: u16,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct TableAnnotation {+ /// References `GroupAnnotation::id`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub group: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+ /// Keyed by bare column name.+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub columns: BTreeMap<String, ColumnAnnotation>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct ColumnAnnotation {+ pub note: String,+}++/// The only format version this build understands.+pub const ANNOTATION_FORMAT_VERSION: u32 = 1;++/// Load the notes file.+///+/// An ABSENT file returns `Ok(None)` — that is the normal first-run and+/// first-CI-run state. A MALFORMED file is a hard error: someone's prose is+/// in there, and rendering apparently-complete documentation while silently+/// discarding it is worse than failing.+pub fn load_annotations(path: &Path) -> Result<Option<AnnotationFile>, String> {+ let contents = match std::fs::read_to_string(path) {+ Ok(contents) => contents,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(format!("Failed to read notes file {}: {error}", path.display())),+ };++ // Read the version BEFORE full deserialization. `deny_unknown_fields`+ // would otherwise reject a future-format file with a confusing+ // "unknown field" error, never reaching the version check — defeating+ // the entire purpose of having a version field.+ let probe: serde_json::Value = serde_json::from_str(&contents)+ .map_err(|error| format!("Failed to parse notes file {}: {error}", path.display()))?;++ match probe.get("formatVersion").and_then(serde_json::Value::as_u64) {+ Some(version) if version == u64::from(ANNOTATION_FORMAT_VERSION) => {}+ Some(version) => {+ return Err(format!(+ "Notes file {} has formatVersion {version}, but this build understands {}.",+ path.display(),+ ANNOTATION_FORMAT_VERSION+ ))+ }+ None => return Err(format!("Notes file {} is missing formatVersion.", path.display())),+ }++ let parsed: AnnotationFile = serde_json::from_value(probe)+ .map_err(|error| format!("Failed to parse notes file {}: {error}", path.display()))?;++ Ok(Some(parsed))+}++/// A unique sibling temp path for an atomic save.+///+/// MUST be unique per call: a temp name derived from the target alone is+/// shared by every concurrent writer, so two saves interleave their bytes into+/// one file and the last rename publishes the mixture. MUST also be a sibling+/// — rename is only atomic within a filesystem.+///+/// The base name is truncated so the whole component stays within the 255-byte+/// limit most filesystems enforce on a single path component. The wrapper+/// costs 14 bytes, so a long-but-valid target name would otherwise make every+/// save fail with ENAMETOOLONG — a regression against the previous 4-byte+/// `.tmp` suffix. Truncating the base is safe because uniqueness comes from+/// the uuid, not from the name.+fn temp_save_path(path: &Path) -> PathBuf {+ /// Most filesystems cap one path component at 255 bytes.+ const MAX_COMPONENT: usize = 255;+ /// `.` + `.` + 8 hex + `.tmp`+ const WRAPPER: usize = 14;++ let name = path.file_name().map(|value| value.to_string_lossy().into_owned()).unwrap_or_default();+ let budget = MAX_COMPONENT - WRAPPER;++ // Truncate on a char boundary — slicing a String by bytes can split a+ // multi-byte character and panic.+ let mut used = 0usize;+ let trimmed: String = name+ .chars()+ .take_while(|character| {+ used += character.len_utf8();+ used <= budget+ })+ .collect();++ let unique = uuid::Uuid::new_v4().simple().to_string();+ path.with_file_name(format!(".{trimmed}.{}.tmp", &unique[..8]))+}++/// Write the notes file atomically.+///+/// A partial write destroys prose a human typed, and `load_annotations`+/// errors loudly on malformed JSON — so a torn write becomes "your notes file+/// is corrupt" the next time the viewer opens. Write a sibling temp file,+/// flush it to disk, then rename: rename within a directory is atomic on+/// every platform DBX targets.+pub fn save_annotations(path: &Path, annotations: &AnnotationFile) -> Result<(), String> {+ let json =+ serde_json::to_string_pretty(annotations).map_err(|error| format!("Failed to serialize notes: {error}"))?;++ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).map_err(|error| format!("Failed to create {}: {error}", parent.display()))?;+ }++ let temp = temp_save_path(path);+ {+ let mut file =+ std::fs::File::create(&temp).map_err(|error| format!("Failed to create {}: {error}", temp.display()))?;+ file.write_all(json.as_bytes()).map_err(|error| {+ let _ = std::fs::remove_file(&temp);+ format!("Failed to write {}: {error}", temp.display())+ })?;+ file.sync_all().map_err(|error| {+ let _ = std::fs::remove_file(&temp);+ format!("Failed to flush {}: {error}", temp.display())+ })?;+ }++ std::fs::rename(&temp, path).map_err(|error| {+ let _ = std::fs::remove_file(&temp);+ format!("Failed to replace {}: {error}", path.display())+ })+}++/// Where a connection's notes file lives.+///+/// An explicit `docs_notes_path` wins — that is the entire point of the field.+/// Pointing it at a file inside a repository is what lets schema documentation+/// be reviewed in pull requests. Otherwise the file lives under the app data+/// directory keyed by connection id, so the feature works with no setup.+///+/// Takes the two fields it needs rather than a whole `ConnectionConfig`:+/// that struct has no `Default` and ~60 fields, so passing it would force+/// every test to build a literal full of values the function never reads.+/// `data_dir` is a parameter because `dbx-core` cannot reach the caller's+/// data directory on its own.+pub fn resolve_notes_path(connection_id: &str, docs_notes_path: Option<&str>, data_dir: &Path) -> PathBuf {+ if let Some(path) = docs_notes_path.map(str::trim).filter(|value| !value.is_empty()) {+ return PathBuf::from(path);+ }+ data_dir.join("docs-notes").join(format!("{connection_id}.json"))+}++/// Merge a notes file into a collected snapshot.+///+/// Precedence is `local ?? database_comment`. When a local note shadows a+/// database comment the comment is kept in `shadowed_note`, so a later+/// `COMMENT ON` improvement stays visible rather than being silently hidden.+pub fn apply_annotations(snapshot: &mut SchemaSnapshot, annotations: &AnnotationFile, db_type: DatabaseType) {+ if let Some(project) = annotations.project.as_ref() {+ if let Some(name) = project.name.as_deref().filter(|value| !value.trim().is_empty()) {+ snapshot.project.name = name.to_string();+ }+ if project.note.is_some() {+ snapshot.project.note = project.note.clone();+ }+ }++ let known_groups: std::collections::HashSet<&str> =+ annotations.groups.iter().map(|group| group.id.as_str()).collect();++ let mut seen_group_ids = std::collections::HashSet::new();+ snapshot.groups = annotations+ .groups+ .iter()+ // A duplicate id would emit two TableGroup blocks with the same+ // name, which is invalid DBML. First occurrence wins.+ .filter(|group| seen_group_ids.insert(group.id.as_str()))+ .map(|group| TableGroup {+ id: group.id.clone(),+ name: group.name.clone(),+ hue: group.hue,+ note: group.note.clone(),+ })+ .collect();++ for table in &mut snapshot.tables {+ let key = table_key(db_type, table.schema.as_deref(), &table.name);+ let Some(annotation) = annotations.tables.get(&key) else { continue };++ if let Some(note) = annotation.note.as_deref().filter(|value| !value.trim().is_empty()) {+ // Preserve whatever the database said before overwriting it.+ if matches!(table.note_source, NoteSource::Database) {+ table.shadowed_note = table.note.clone();+ }+ table.note = Some(note.to_string());+ table.note_source = NoteSource::Local;+ }++ // A group reference that names no defined group is dropped rather+ // than assigned — a dangling id would render an empty group header.+ table.group_id = annotation.group.as_deref().filter(|id| known_groups.contains(id)).map(ToOwned::to_owned);++ for column in &table.columns {+ let column_fold = fold_identifier(db_type, &column.name);+ let annotated = annotation.columns.iter().find(|(name, _)| fold_identifier(db_type, name) == column_fold);++ let Some((_, column_annotation)) = annotated else { continue };+ if column_annotation.note.trim().is_empty() {+ continue;+ }++ table.column_notes.insert(+ column.name.clone(),+ ColumnNote {+ note: column_annotation.note.clone(),+ source: NoteSource::Local,+ shadowed: column.comment.clone().filter(|value| !value.trim().is_empty()),+ },+ );+ }+ }++ let orphans = detect_orphans(snapshot, annotations, db_type);+ if !orphans.is_empty() {+ snapshot.warnings.push(SnapshotWarning::OrphanedNotes { count: orphans.len() });+ }+}++/// Annotation keys whose target no longer exists in the collected schema.+///+/// Returns fully-qualified keys, sorted, so the caller can list them for a+/// human to re-map. This function NEVER mutates the notes file — user prose+/// is only ever removed by an explicit human action.+///+/// Suggestions for where a renamed target went are deliberately absent:+/// producing them requires the OLD schema to diff against, and the notes+/// file stores prose only. That becomes possible once snapshot history+/// exists (see the spec's deferred versioning seam).+pub fn detect_orphans(snapshot: &SchemaSnapshot, annotations: &AnnotationFile, db_type: DatabaseType) -> Vec<String> {+ use std::collections::HashSet;++ let live_tables: HashSet<String> =+ snapshot.tables.iter().map(|table| table_key(db_type, table.schema.as_deref(), &table.name)).collect();++ let live_columns: HashSet<String> = snapshot+ .tables+ .iter()+ .flat_map(|table| {+ table+ .columns+ .iter()+ .map(move |column| column_key(db_type, table.schema.as_deref(), &table.name, &column.name))+ })+ .collect();++ let mut orphans = Vec::new();++ for (key, annotation) in &annotations.tables {+ let folded_table = fold_key(db_type, key);+ if !live_tables.contains(&folded_table) {+ orphans.push(folded_table);+ continue;+ }+ for column in annotation.columns.keys() {+ let folded_column = format!("{folded_table}.{}", fold_identifier(db_type, column));+ if !live_columns.contains(&folded_column) {+ orphans.push(folded_column);+ }+ }+ }++ orphans.sort();+ orphans+}++/// Fold an already-dotted key (e.g. `Core.Orders`) segment by segment.+fn fold_key(db_type: DatabaseType, key: &str) -> String {+ key.split('.').map(|segment| fold_identifier(db_type, segment)).collect::<Vec<_>>().join(".")+}++#[cfg(test)]+mod tests {+ use super::*;++ const SAMPLE: &str = r##"{+ "formatVersion": 1,+ "project": { "name": "Ecommerce", "note": "# Overview" },+ "groups": [+ { "id": "order-management", "name": "Order Management", "hue": 28, "note": "Checkout to handoff." }+ ],+ "tables": {+ "core.orders": {+ "group": "order-management",+ "note": "One row per checkout.",+ "columns": { "status": { "note": "State machine." } }+ }+ }+}"##;++ #[test]+ fn parses_a_complete_notes_file() {+ let parsed: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ assert_eq!(parsed.format_version, 1);+ assert_eq!(parsed.project.as_ref().unwrap().name.as_deref(), Some("Ecommerce"));+ assert_eq!(parsed.groups.len(), 1);+ assert_eq!(parsed.groups[0].hue, 28);+ assert_eq!(parsed.tables.len(), 1);++ let orders = parsed.tables.get("core.orders").expect("orders");+ assert_eq!(orders.group.as_deref(), Some("order-management"));+ assert_eq!(orders.note.as_deref(), Some("One row per checkout."));+ assert_eq!(orders.columns.get("status").unwrap().note, "State machine.");+ }++ #[test]+ fn a_minimal_file_needs_only_the_format_version() {+ let parsed: AnnotationFile = serde_json::from_str(r#"{"formatVersion": 1}"#).expect("parse");+ assert!(parsed.tables.is_empty());+ assert!(parsed.groups.is_empty());+ assert!(parsed.project.is_none());+ }++ #[test]+ fn round_trips_through_json() {+ let parsed: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ let written = serde_json::to_string(&parsed).expect("serialize");+ let reparsed: AnnotationFile = serde_json::from_str(&written).expect("reparse");++ // Every field in SAMPLE must survive a write/read cycle. Asserting+ // only a count here would pass against a model that silently drops+ // fields on write via a wrong skip_serializing_if predicate.+ assert_eq!(reparsed.format_version, 1);++ let project = reparsed.project.as_ref().expect("project survived");+ assert_eq!(project.name.as_deref(), Some("Ecommerce"));+ assert_eq!(project.note.as_deref(), Some("# Overview"));++ assert_eq!(reparsed.groups.len(), 1);+ let group = &reparsed.groups[0];+ assert_eq!(group.id, "order-management");+ assert_eq!(group.name, "Order Management");+ assert_eq!(group.hue, 28);+ assert_eq!(group.note.as_deref(), Some("Checkout to handoff."));++ assert_eq!(reparsed.tables.len(), 1);+ let orders = reparsed.tables.get("core.orders").expect("orders survived");+ assert_eq!(orders.group.as_deref(), Some("order-management"));+ assert_eq!(orders.note.as_deref(), Some("One row per checkout."));+ assert_eq!(orders.columns.len(), 1);+ assert_eq!(orders.columns.get("status").expect("column survived").note, "State machine.");+ }++ #[test]+ fn rejects_a_file_with_an_unknown_top_level_field() {+ // Typos in a hand-edited file must not be silently ignored — a+ // misspelled "tabels" key would otherwise discard every note in it.+ let result: Result<AnnotationFile, _> = serde_json::from_str(r#"{"formatVersion": 1, "tabels": {}}"#);+ assert!(result.is_err(), "unknown fields must be rejected");+ }++ fn temp_notes(contents: &str) -> std::path::PathBuf {+ let path = std::env::temp_dir().join(format!("dbx-notes-test-{}.json", uuid::Uuid::new_v4()));+ std::fs::write(&path, contents).expect("write temp notes file");+ path+ }++ fn temp_case_dir(label: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("dbx-notes-{label}-{}", uuid::Uuid::new_v4().simple()));+ std::fs::create_dir_all(&dir).expect("create temp dir");+ dir+ }++ #[test]+ fn save_then_load_round_trips() {+ let dir = temp_case_dir("round-trip");+ let path = dir.join("notes.json");+ let file = AnnotationFile {+ format_version: 1,+ project: Some(ProjectAnnotation { name: Some("P".into()), note: Some("hello".into()) }),+ groups: vec![GroupAnnotation { id: "g".into(), name: "G".into(), hue: 200, note: None }],+ tables: BTreeMap::from([(+ "public.t".to_string(),+ TableAnnotation { group: Some("g".into()), note: Some("n".into()), columns: BTreeMap::new() },+ )]),+ };++ save_annotations(&path, &file).expect("save");+ let loaded = load_annotations(&path).expect("load").expect("present");++ assert_eq!(loaded.format_version, 1);+ assert_eq!(loaded.groups[0].hue, 200);+ assert_eq!(loaded.tables["public.t"].note.as_deref(), Some("n"));+ assert_eq!(loaded.project.and_then(|p| p.note).as_deref(), Some("hello"));+ }++ #[test]+ fn save_creates_missing_parent_directories() {+ let dir = temp_case_dir("nested");+ let path = dir.join("nested").join("deeper").join("notes.json");+ let file = AnnotationFile { format_version: 1, project: None, groups: Vec::new(), tables: BTreeMap::new() };+ save_annotations(&path, &file).expect("save into a new directory");+ assert!(path.exists());+ }++ #[test]+ fn save_leaves_no_temp_file_behind() {+ // A stray notes.json.tmp would be picked up by nothing, but it means+ // the rename did not happen and the write was not atomic.+ let dir = temp_case_dir("no-temp-left");+ let path = dir.join("notes.json");+ let file = AnnotationFile { format_version: 1, project: None, groups: Vec::new(), tables: BTreeMap::new() };+ save_annotations(&path, &file).expect("save");++ let leftovers: Vec<_> = std::fs::read_dir(&dir)+ .expect("read_dir")+ .filter_map(Result::ok)+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .filter(|name| name.ends_with(".tmp"))+ .collect();+ assert!(leftovers.is_empty(), "temp files left behind: {leftovers:?}");+ }++ #[cfg(unix)]+ #[test]+ fn a_save_replaces_the_file_by_rename_rather_than_writing_in_place() {+ // The whole point of temp-and-rename. A reader either sees the old+ // file or the new one, never a half-written mix — load_annotations+ // errors loudly on malformed JSON, so a torn write reads as "your+ // notes file is corrupt".+ //+ // Writing in place keeps the inode; renaming over the target changes+ // it. That is the difference, and it is observable without having to+ // make a write fail halfway.+ use std::os::unix::fs::MetadataExt;++ let dir = temp_case_dir("atomic-replace");+ let path = dir.join("notes.json");+ let first = AnnotationFile {+ format_version: 1,+ project: None,+ groups: Vec::new(),+ tables: BTreeMap::from([(+ "public.a".to_string(),+ TableAnnotation { group: None, note: Some("first".into()), columns: BTreeMap::new() },+ )]),+ };+ save_annotations(&path, &first).expect("first save");+ let before = std::fs::metadata(&path).expect("metadata").ino();++ let second = AnnotationFile {+ format_version: 1,+ project: None,+ groups: Vec::new(),+ tables: BTreeMap::from([(+ "public.b".to_string(),+ TableAnnotation { group: None, note: Some("second".into()), columns: BTreeMap::new() },+ )]),+ };+ save_annotations(&path, &second).expect("second save");+ let after = std::fs::metadata(&path).expect("metadata").ino();++ assert_ne!(before, after, "an atomic save replaces the file by rename, never writes in place");+ let loaded = load_annotations(&path).expect("load").expect("present");+ assert_eq!(loaded.tables["public.b"].note.as_deref(), Some("second"));+ }++ #[test]+ fn an_explicit_notes_path_wins_over_the_default() {+ let resolved = resolve_notes_path("conn-1", Some("/tmp/team/schema-notes.json"), std::path::Path::new("/data"));+ assert_eq!(resolved, std::path::PathBuf::from("/tmp/team/schema-notes.json"));+ }++ #[test]+ fn the_default_notes_path_is_keyed_by_connection_id() {+ let resolved = resolve_notes_path("conn-1", None, std::path::Path::new("/data"));+ assert_eq!(resolved, std::path::PathBuf::from("/data/docs-notes/conn-1.json"));+ }++ #[test]+ fn a_blank_notes_path_falls_back_to_the_default() {+ // An empty string in the config is a cleared field, not a path to a+ // file named "". Treating it as explicit would resolve to garbage.+ let resolved = resolve_notes_path("conn-1", Some(" "), std::path::Path::new("/data"));+ assert_eq!(resolved, std::path::PathBuf::from("/data/docs-notes/conn-1.json"));+ }++ #[test]+ fn each_save_uses_a_distinct_temp_path() {+ // A temp name derived from the target alone is shared by every+ // concurrent writer, so two saves interleave into one file and the+ // last rename publishes the mixture.+ let target = std::path::Path::new("/data/docs-notes/conn-1.json");+ let first = temp_save_path(target);+ let second = temp_save_path(target);+ assert_ne!(first, second);+ }++ #[test]+ fn the_temp_path_is_a_sibling_of_the_target() {+ // rename is only atomic within one filesystem. A temp file in /tmp+ // could be on a different mount, making the rename a copy.+ let target = std::path::Path::new("/data/docs-notes/conn-1.json");+ assert_eq!(temp_save_path(target).parent(), target.parent());+ }++ #[test]+ fn a_failed_write_leaves_no_temp_file_in_the_target_directory() {+ // docs_notes_path is meant to point into a user's repository, so+ // debris from a failed save shows up in their git status.+ let dir = temp_case_dir("failed-write-debris");+ let path = dir.join("notes.json");+ // A directory at the target makes the rename fail after the temp file+ // has been written.+ std::fs::create_dir(&path).expect("block the target path");+ let file = AnnotationFile { format_version: 1, project: None, groups: Vec::new(), tables: BTreeMap::new() };++ let result = save_annotations(&path, &file);+ assert!(result.is_err(), "save must fail when the target is a directory");++ let leftovers: Vec<_> = std::fs::read_dir(&dir)+ .expect("read_dir")+ .filter_map(Result::ok)+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .filter(|name| name.ends_with(".tmp"))+ .collect();+ assert!(leftovers.is_empty(), "temp files left behind: {leftovers:?}");+ }++ #[test]+ fn a_long_target_name_still_yields_a_usable_temp_component() {+ // The wrapper costs 14 bytes. Without a budget, a 245-byte name makes+ // a 259-byte component and every save fails with ENAMETOOLONG — a+ // regression against the old 4-byte `.tmp` suffix.+ let name = format!("{}.json", "a".repeat(240));+ let target = std::path::Path::new("/data").join(&name);+ let temp = temp_save_path(&target);+ let component = temp.file_name().expect("file name").to_string_lossy().len();+ assert!(component <= 255, "temp component is {component} bytes: {temp:?}");+ }++ #[test]+ fn a_long_multibyte_target_name_is_truncated_on_a_char_boundary() {+ // Slicing a String by bytes can split a multi-byte character and+ // panic. This name is 3 bytes per character.+ let name = format!("{}.json", "é".repeat(200));+ let target = std::path::Path::new("/data").join(&name);+ let temp = temp_save_path(&target); // must not panic+ let component = temp.file_name().expect("file name").to_string_lossy().len();+ assert!(component <= 255, "temp component is {component} bytes");+ }++ #[test]+ fn a_long_target_name_still_saves_and_loads() {+ // End to end: the budget is only useful if the save actually works.+ let dir = temp_case_dir("long-name");+ let path = dir.join(format!("{}.json", "a".repeat(200)));+ let file = AnnotationFile { format_version: 1, project: None, groups: Vec::new(), tables: BTreeMap::new() };+ save_annotations(&path, &file).expect("save with a long name");+ assert!(load_annotations(&path).expect("load").is_some());+ }++ #[test]+ fn an_absent_file_is_not_an_error() {+ let missing = std::path::Path::new("/nonexistent/dbx-notes-does-not-exist.json");+ assert!(matches!(load_annotations(missing), Ok(None)));+ }++ #[test]+ fn a_valid_file_loads() {+ let path = temp_notes(SAMPLE);+ let loaded = load_annotations(&path);+ let _ = std::fs::remove_file(&path);+ let loaded = loaded.expect("load").expect("some");+ assert_eq!(loaded.tables.len(), 1);+ }++ #[test]+ fn a_malformed_file_is_a_hard_error_naming_the_path() {+ let path = temp_notes("{ this is not json");+ let error = load_annotations(&path);+ let _ = std::fs::remove_file(&path);+ let error = error.expect_err("must fail");+ assert!(error.contains(&path.display().to_string()), "error must name the file: {error}");+ }++ #[test]+ fn an_unsupported_format_version_is_rejected() {+ let path = temp_notes(r#"{"formatVersion": 99}"#);+ let error = load_annotations(&path);+ let _ = std::fs::remove_file(&path);+ let error = error.expect_err("must fail");+ assert!(error.contains("99"), "error must name the version: {error}");+ }++ #[test]+ fn a_future_format_version_reports_the_version_not_an_unknown_field() {+ // deny_unknown_fields must NOT pre-empt the version check — a v1+ // build reading a v2 file has to say so, or the version field is+ // useless exactly when it is needed.+ let path = temp_notes(r#"{"formatVersion": 2, "someNewField": {"a": 1}}"#);+ let error = load_annotations(&path);+ let _ = std::fs::remove_file(&path);+ let error = error.expect_err("must fail");++ assert!(error.contains("formatVersion 2"), "should name the version, got: {error}");+ assert!(!error.contains("unknown field"), "should not surface a raw serde error, got: {error}");+ }++ use crate::docs::{DocTable, NoteSource, ProjectMeta, SchemaSnapshot, TableKind};+ use crate::models::connection::DatabaseType;++ fn snapshot_with(tables: Vec<DocTable>) -> SchemaSnapshot {+ SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: "conn".to_string(),+ database_type: "postgres".to_string(),+ database: None,+ schemas: vec!["core".to_string()],+ generated_at: String::new(),+ note: None,+ },+ tables,+ relationships: vec![],+ groups: vec![],+ enums: vec![],+ warnings: vec![],+ }+ }++ fn table_named(schema: &str, name: &str, comment: Option<&str>) -> DocTable {+ DocTable {+ schema: Some(schema.to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ group_id: None,+ note: comment.map(ToOwned::to_owned),+ note_source: if comment.is_some() { NoteSource::Database } else { NoteSource::None },+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn a_local_note_shadows_the_database_comment_and_preserves_it() {+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", Some("Old DB comment."))]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let table = &snapshot.tables[0];+ assert_eq!(table.note.as_deref(), Some("One row per checkout."));+ assert_eq!(table.note_source, NoteSource::Local);+ assert_eq!(table.shadowed_note.as_deref(), Some("Old DB comment."));+ }++ #[test]+ fn a_database_comment_survives_when_there_is_no_local_note() {+ let mut snapshot = snapshot_with(vec![table_named("core", "users", Some("From the database."))]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let table = &snapshot.tables[0];+ assert_eq!(table.note.as_deref(), Some("From the database."));+ assert_eq!(table.note_source, NoteSource::Database);+ assert_eq!(table.shadowed_note, None);+ }++ #[test]+ fn keys_match_case_insensitively_on_postgres() {+ // The notes file says "core.orders"; the live schema reports "Core"/"Orders".+ let mut snapshot = snapshot_with(vec![table_named("Core", "Orders", None)]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.tables[0].note.as_deref(), Some("One row per checkout."));+ }++ #[test]+ fn column_notes_are_applied_and_marked_local() {+ let mut table = table_named("core", "orders", None);+ table.columns.push(crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ ..Default::default()+ });+ let mut snapshot = snapshot_with(vec![table]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let note = snapshot.tables[0].column_notes.get("status").expect("column note");+ assert_eq!(note.note, "State machine.");+ assert_eq!(note.source, NoteSource::Local);+ }++ #[test]+ fn the_project_note_and_name_are_applied() {+ let mut snapshot = snapshot_with(vec![]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.project.name, "Ecommerce");+ assert_eq!(snapshot.project.note.as_deref(), Some("# Overview"));+ }++ #[test]+ fn groups_are_copied_and_membership_is_assigned() {+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.groups.len(), 1);+ assert_eq!(snapshot.groups[0].id, "order-management");+ assert_eq!(snapshot.groups[0].hue, 28);+ assert_eq!(snapshot.tables[0].group_id.as_deref(), Some("order-management"));+ }++ #[test]+ fn a_table_referencing_an_undefined_group_is_left_ungrouped() {+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);+ let mut annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ annotations.groups.clear();++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.tables[0].group_id, None, "a dangling group reference must not be assigned");+ }++ #[test]+ fn duplicate_group_ids_collapse_to_one_entry() {+ // Two TableGroup blocks sharing an id is invalid DBML.+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);+ let mut annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ let mut dup = annotations.groups[0].clone();+ dup.name = "Duplicate".to_string();+ annotations.groups.push(dup);++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.groups.len(), 1, "duplicate ids must collapse");+ assert_eq!(snapshot.groups[0].name, "Order Management", "first occurrence wins");+ }++ use crate::docs::SnapshotWarning;++ #[test]+ fn a_note_for_a_missing_table_is_reported_as_orphaned() {+ // The notes file describes core.orders; the schema no longer has it.+ let mut snapshot = snapshot_with(vec![table_named("core", "customers", None)]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ let orphans = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);+ assert_eq!(orphans, vec!["core.orders".to_string()]);++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);+ let orphan_warnings: Vec<&SnapshotWarning> = snapshot+ .warnings+ .iter()+ .filter(|warning| matches!(warning, SnapshotWarning::OrphanedNotes { .. }))+ .collect();+ assert_eq!(orphan_warnings.len(), 1);+ match orphan_warnings[0] {+ SnapshotWarning::OrphanedNotes { count } => assert_eq!(*count, 1),+ other => panic!("unexpected: {other:?}"),+ }+ }++ #[test]+ fn a_note_for_a_missing_column_is_reported_as_orphaned() {+ // The table exists but no longer has the annotated column.+ let mut table = table_named("core", "orders", None);+ table.columns.push(crate::types::ColumnInfo {+ name: "id".to_string(),+ data_type: "integer".to_string(),+ ..Default::default()+ });+ let snapshot = snapshot_with(vec![table]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ let orphans = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);+ assert_eq!(orphans, vec!["core.orders.status".to_string()]);+ }++ #[test]+ fn nothing_is_orphaned_when_everything_matches() {+ let mut table = table_named("core", "orders", None);+ table.columns.push(crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ ..Default::default()+ });+ let mut snapshot = snapshot_with(vec![table]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ assert!(detect_orphans(&snapshot, &annotations, DatabaseType::Postgres).is_empty());++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);+ assert!(+ !snapshot.warnings.iter().any(|w| matches!(w, SnapshotWarning::OrphanedNotes { .. })),+ "no orphan warning when everything matches"+ );+ }++ #[test]+ fn orphan_detection_never_removes_anything_from_the_file() {+ let snapshot = snapshot_with(vec![]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ let before = annotations.tables.len();++ let _ = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(annotations.tables.len(), before, "detection must not mutate the file");+ }+}diff --git a/crates/dbx-core/src/docs/collector.rs b/crates/dbx-core/src/docs/collector.rsnew file mode 100644index 0000000000..ea7aae7f9c--- /dev/null+++ b/crates/dbx-core/src/docs/collector.rs@@ -0,0 +1,549 @@+use std::collections::{BTreeMap, HashSet};+use std::sync::atomic::{AtomicBool, Ordering};++use futures::stream::{self, StreamExt};++use crate::connection::AppState;+use crate::docs::dbml::{enum_type_name, is_inline_enum_spelling};+use crate::docs::{+ build_relationships, DocEnum, DocTable, NoteSource, ProjectMeta, Relationship, SchemaSnapshot, SnapshotWarning,+ TableKind,+};+use crate::models::connection::ConnectionConfig;+use crate::schema;+use crate::table_structure_sql::{database_type_label, supports_comments, supports_foreign_keys};+use crate::types::ColumnInfo;++/// Concurrent per-table metadata fetches. Bounded so documenting a large+/// schema cannot starve the connection pool the UI is also using.+const MAX_CONCURRENT_TABLES: usize = 8;++#[derive(Debug, Clone)]+pub struct CollectOptions {+ pub database: String,+ pub schemas: Vec<String>,+ /// Empty means every table. Entries may be bare (`orders`) or+ /// qualified (`analytics.daily_sales`).+ pub tables: Vec<String>,+ pub project_name: String,+}++impl CollectOptions {+ pub fn includes_table(&self, schema: &str, table: &str) -> bool {+ if self.tables.is_empty() {+ return true;+ }+ let qualified = format!("{schema}.{table}");+ self.tables.iter().any(|wanted| wanted == table || wanted == &qualified)+ }+}++#[derive(Debug, Clone)]+pub struct CollectProgress {+ pub completed: usize,+ pub total: usize,+ pub current: String,+}++fn table_kind_from(table_type: &str) -> TableKind {+ let normalized = table_type.trim().to_ascii_uppercase().replace('_', " ");+ match normalized.as_str() {+ "VIEW" => TableKind::View,+ "MATERIALIZED VIEW" => TableKind::MaterializedView,+ _ => TableKind::Table,+ }+}++/// MySQL reports `ENUM('a','b')` inline rather than as a named type, so DBML+/// needs a synthesized `{table}_{column}` name for it. PostgreSQL, by+/// contrast, reports a named enum type's own identifier in `data_type` — its+/// native name is used instead, so the user's real type identity survives+/// and a type shared by several columns is recognized as the same enum+/// (see `build_enums`, which deduplicates by name).+fn synthesize_enum(schema: Option<&str>, table: &str, column: &ColumnInfo) -> Option<DocEnum> {+ let values = column.enum_values.as_ref().filter(|values| !values.is_empty())?;+ Some(DocEnum {+ schema: schema.map(ToOwned::to_owned),+ name: enum_type_name(column, table),+ values: values.clone(),+ note: None,+ synthesized: is_inline_enum_spelling(&column.data_type),+ })+}++/// Collect every enum referenced by `tables`, deduplicated by (schema,+/// name). A named type (e.g. a PostgreSQL enum) is typically shared by+/// several columns — without deduplication each column would emit its own+/// copy of the same block, which is invalid DBML.+fn build_enums(tables: &[DocTable]) -> Vec<DocEnum> {+ let mut enums = Vec::new();+ let mut seen: HashSet<(Option<String>, String)> = HashSet::new();+ for table in tables {+ for column in &table.columns {+ let Some(value) = synthesize_enum(table.schema.as_deref(), &table.name, column) else { continue };+ if seen.insert((value.schema.clone(), value.name.clone())) {+ enums.push(value);+ }+ }+ }+ enums+}++fn cancelled(cancel: &AtomicBool) -> bool {+ cancel.load(Ordering::Relaxed)+}++/// Whether any table or column in the collected snapshot carries a+/// non-empty comment. Used to corroborate `supports_comments` — a DDL-only+/// capability flag — against what introspection actually returned.+fn any_comment_collected(tables: &[DocTable]) -> bool {+ tables.iter().any(|table| {+ table.note.as_deref().is_some_and(|note| !note.trim().is_empty())+ || table+ .columns+ .iter()+ .any(|column| column.comment.as_deref().is_some_and(|comment| !comment.trim().is_empty()))+ })+}++/// True when the `CommentsUnsupported` warning belongs in the snapshot: the+/// engine's DDL capability flag says it can't do comments, and collection+/// found none to contradict it.+fn should_warn_comments_unsupported(supports_comments: bool, tables: &[DocTable]) -> bool {+ !supports_comments && !any_comment_collected(tables)+}++/// True when the `NoForeignKeyMetadata` warning belongs in the snapshot: the+/// engine's DDL capability flag says it can't do foreign keys, and+/// collection found no relationships to contradict it.+fn should_warn_no_foreign_key_metadata(supports_foreign_keys: bool, relationships: &[Relationship]) -> bool {+ !supports_foreign_keys && relationships.is_empty()+}++/// Collect a documentation snapshot.+///+/// A per-table failure is recorded as a `TableSkipped` warning and does not+/// abort the run — a permissions gap on one table must not kill a+/// 400-table documentation build.+pub async fn collect_snapshot(+ state: &AppState,+ connection: &ConnectionConfig,+ options: &CollectOptions,+ progress: &(dyn Fn(CollectProgress) + Send + Sync),+ cancel: &AtomicBool,+) -> Result<SchemaSnapshot, String> {+ let mut warnings: Vec<SnapshotWarning> = Vec::new();+ let engine = database_type_label(connection.db_type);+ let connection_id = connection.id.as_str();++ let schemas = if options.schemas.is_empty() {+ match schema::list_schemas_core(state, connection_id, &options.database).await {+ Ok(schemas) => schemas,+ Err(error) => {+ // Distinguish "enumeration failed" from "no schemas exist" —+ // the latter is a legitimately empty document, the former is+ // a cryptic one if it silently proceeds against schema "".+ warnings.push(SnapshotWarning::TableSkipped {+ table: "*".to_string(),+ reason: format!("schema enumeration failed: {error}"),+ });+ Vec::new()+ }+ }+ } else {+ options.schemas.clone()+ };+ let effective_schemas = if schemas.is_empty() { vec![String::new()] } else { schemas };++ // Enumerate every table first so progress has a real total.+ let mut targets: Vec<(String, crate::types::TableInfo)> = Vec::new();+ for schema_name in &effective_schemas {+ match schema::list_tables_core(+ state,+ connection_id,+ &options.database,+ schema_name,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ {+ Ok(tables) => {+ for info in tables {+ if options.includes_table(schema_name, &info.name) {+ targets.push((schema_name.clone(), info));+ }+ }+ }+ Err(error) => {+ warnings.push(SnapshotWarning::TableSkipped { table: format!("{schema_name}.*"), reason: error })+ }+ }+ }++ let total = targets.len();++ let collected: Vec<Result<(DocTable, Vec<SnapshotWarning>), SnapshotWarning>> =+ stream::iter(targets.into_iter().enumerate())+ .map(|(index, (schema_name, info))| {+ let database = options.database.clone();+ async move {+ if cancelled(cancel) {+ return Err(SnapshotWarning::TableSkipped {+ table: info.name.clone(),+ reason: "cancelled".to_string(),+ });+ }++ progress(CollectProgress {+ completed: index,+ total,+ current: format!("{schema_name}.{}", info.name),+ });++ let columns = schema::get_columns_core(state, connection_id, &database, &schema_name, &info.name)+ .await+ .map_err(|error| SnapshotWarning::TableSkipped {+ table: format!("{schema_name}.{}", info.name),+ reason: error,+ })?;++ let mut table_warnings = Vec::new();++ // Indexes feed `relations.rs`'s uniqueness check, so a+ // failure here must not look identical to "this table+ // genuinely has no indexes" — that would silently+ // downgrade a OneToOne relationship to ManyToOne.+ let indexes = match schema::list_indexes_core(+ state,+ connection_id,+ &database,+ &schema_name,+ &info.name,+ )+ .await+ {+ Ok(indexes) => indexes,+ Err(error) => {+ table_warnings.push(SnapshotWarning::TableSkipped {+ table: format!("{schema_name}.{}", info.name),+ reason: format!("indexes unavailable: {error}"),+ });+ Vec::new()+ }+ };++ // Foreign keys also degrade to empty rather than failing the+ // table, but a real query failure must not look identical to+ // "this table genuinely has no foreign keys" — it is reported+ // as its own warning instead of being silently discarded.+ let foreign_keys =+ match schema::list_foreign_keys_core(state, connection_id, &database, &schema_name, &info.name)+ .await+ {+ Ok(keys) => keys,+ Err(error) => {+ table_warnings.push(SnapshotWarning::TableSkipped {+ table: format!("{schema_name}.{}", info.name),+ reason: format!("foreign keys unavailable: {error}"),+ });+ Vec::new()+ }+ };++ Ok((+ DocTable {+ schema: (!schema_name.is_empty()).then(|| schema_name.clone()),+ name: info.name.clone(),+ kind: table_kind_from(&info.table_type),+ columns,+ indexes,+ foreign_keys,+ group_id: None,+ note: info.comment.clone().filter(|value| !value.trim().is_empty()),+ note_source: if info.comment.as_deref().is_some_and(|v| !v.trim().is_empty()) {+ NoteSource::Database+ } else {+ NoteSource::None+ },+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ },+ table_warnings,+ ))+ }+ })+ .buffer_unordered(MAX_CONCURRENT_TABLES)+ .collect()+ .await;++ let mut tables = Vec::new();+ for outcome in collected {+ match outcome {+ Ok((table, table_warnings)) => {+ tables.push(table);+ warnings.extend(table_warnings);+ }+ Err(warning) => warnings.push(warning),+ }+ }++ tables.sort_by_key(|table| table.qualified_name());++ let enums = build_enums(&tables);++ let relationships = build_relationships(&tables);++ // The capability flags gate DDL generation (COMMENT ON, foreign key+ // clauses), not introspection — IRIS is the proven divergence: it+ // reports comments on introspection despite the editor being unable to+ // ALTER them, so `supports_comments` alone would be a false positive. A+ // warning fires only when the flag says an engine can't AND collection+ // corroborates that nothing of the kind actually came back.+ if should_warn_comments_unsupported(supports_comments(connection.db_type), &tables) {+ warnings.push(SnapshotWarning::CommentsUnsupported { engine: engine.clone() });+ }+ if should_warn_no_foreign_key_metadata(supports_foreign_keys(connection.db_type), &relationships) {+ warnings.push(SnapshotWarning::NoForeignKeyMetadata { engine: engine.clone() });+ }++ progress(CollectProgress { completed: total, total, current: String::new() });++ Ok(SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: options.project_name.clone(),+ database_type: engine,+ database: (!options.database.is_empty()).then(|| options.database.clone()),+ schemas: effective_schemas.into_iter().filter(|s| !s.is_empty()).collect(),+ generated_at: chrono::Utc::now().to_rfc3339(),+ note: None,+ },+ tables,+ relationships,+ groups: Vec::new(),+ enums,+ warnings,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn table_kind_maps_from_the_engine_reported_type() {+ assert_eq!(table_kind_from("TABLE"), TableKind::Table);+ assert_eq!(table_kind_from("BASE TABLE"), TableKind::Table);+ assert_eq!(table_kind_from("VIEW"), TableKind::View);+ assert_eq!(table_kind_from("MATERIALIZED VIEW"), TableKind::MaterializedView);+ assert_eq!(table_kind_from("materialized_view"), TableKind::MaterializedView);+ assert_eq!(table_kind_from("something else"), TableKind::Table);+ }++ #[test]+ fn table_filter_is_empty_means_include_everything() {+ let options = CollectOptions {+ database: "shop".to_string(),+ schemas: vec!["public".to_string()],+ tables: vec![],+ project_name: "Ecommerce".to_string(),+ };+ assert!(options.includes_table("public", "orders"));+ assert!(options.includes_table("public", "anything"));+ }++ #[test]+ fn table_filter_matches_bare_and_qualified_names() {+ let options = CollectOptions {+ database: "shop".to_string(),+ schemas: vec!["public".to_string()],+ tables: vec!["orders".to_string(), "analytics.daily_sales".to_string()],+ project_name: "Ecommerce".to_string(),+ };+ assert!(options.includes_table("public", "orders"));+ assert!(options.includes_table("analytics", "daily_sales"));+ assert!(!options.includes_table("public", "users"));+ assert!(!options.includes_table("public", "daily_sales"));+ }++ #[test]+ fn synthesises_a_named_enum_from_an_inline_mysql_enum_column() {+ let mut column = crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "enum('pending','shipped')".to_string(),+ ..Default::default()+ };+ column.enum_values = Some(vec!["pending".to_string(), "shipped".to_string()]);++ let synthesized = synthesize_enum(Some("public"), "orders", &column).expect("enum");++ assert_eq!(synthesized.name, "orders_status");+ assert_eq!(synthesized.values, vec!["pending", "shipped"]);+ assert!(synthesized.synthesized);+ }++ #[test]+ fn a_postgres_named_enum_column_keeps_its_own_type_name() {+ // PostgreSQL reports the enum's own type name in `data_type`, not an+ // inline `ENUM(...)` spelling. The user's real type identity must+ // survive into the document instead of being replaced by a+ // synthesized `{table}_{column}` name.+ let mut column = crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "ConversationStatus".to_string(),+ ..Default::default()+ };+ column.enum_values = Some(vec!["open".to_string(), "closed".to_string()]);++ let synthesized = synthesize_enum(Some("public"), "conversations", &column).expect("enum");++ assert_eq!(synthesized.name, "ConversationStatus");+ assert!(!synthesized.synthesized);+ }++ #[test]+ fn a_column_without_enum_values_synthesises_nothing() {+ let column = crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ ..Default::default()+ };+ assert!(synthesize_enum(Some("public"), "orders", &column).is_none());+ }++ fn enum_column(name: &str, data_type: &str, values: &[&str]) -> crate::types::ColumnInfo {+ crate::types::ColumnInfo {+ name: name.to_string(),+ data_type: data_type.to_string(),+ enum_values: Some(values.iter().map(|v| v.to_string()).collect()),+ ..Default::default()+ }+ }++ fn table_with_columns(schema: &str, name: &str, columns: Vec<crate::types::ColumnInfo>) -> DocTable {+ DocTable {+ schema: Some(schema.to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns,+ indexes: vec![],+ foreign_keys: vec![],+ group_id: None,+ note: None,+ note_source: NoteSource::None,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn a_named_enum_type_shared_by_two_columns_is_emitted_once() {+ let conversations = table_with_columns(+ "public",+ "conversations",+ vec![enum_column("status", "ConversationStatus", &["open", "closed"])],+ );+ let archived_conversations = table_with_columns(+ "public",+ "archived_conversations",+ vec![enum_column("status", "ConversationStatus", &["open", "closed"])],+ );++ let enums = build_enums(&[conversations, archived_conversations]);++ assert_eq!(enums.len(), 1, "two columns of the same named type must dedupe to one block: {enums:?}");+ assert_eq!(enums[0].name, "ConversationStatus");+ assert!(!enums[0].synthesized);+ }++ #[test]+ fn postgres_reports_foreign_key_ddl_capability_true() {+ assert!(supports_foreign_keys(crate::models::connection::DatabaseType::Postgres));+ }++ fn column_with_comment(comment: &str) -> crate::types::ColumnInfo {+ crate::types::ColumnInfo {+ name: "notes".to_string(),+ data_type: "text".to_string(),+ comment: Some(comment.to_string()),+ ..Default::default()+ }+ }++ fn sample_relationship() -> Relationship {+ Relationship {+ id: "orders.customer_id->customers.id".to_string(),+ name: None,+ from: crate::docs::FieldRef {+ schema: Some("public".to_string()),+ table: "orders".to_string(),+ column: "customer_id".to_string(),+ },+ to: crate::docs::FieldRef {+ schema: Some("public".to_string()),+ table: "customers".to_string(),+ column: "id".to_string(),+ },+ cardinality: crate::docs::Cardinality::ManyToOne,+ on_update: None,+ on_delete: None,+ }+ }++ #[test]+ fn comments_unsupported_warning_fires_when_flag_is_false_and_nothing_was_collected() {+ let tables = vec![table_with_columns("public", "orders", vec![])];+ assert!(should_warn_comments_unsupported(false, &tables));+ }++ #[test]+ fn comments_unsupported_warning_is_absent_when_a_table_comment_was_collected() {+ // Regression: IRIS reports `comment: false` on the DDL capability+ // flag (it supports %DESCRIPTION at CREATE time but DBX cannot ALTER+ // it), yet IRIS still returns real comments on introspection. The+ // warning must not contradict data actually present in the snapshot.+ let mut table = table_with_columns("public", "orders", vec![]);+ table.note = Some("Checkout rows.".to_string());+ assert!(!should_warn_comments_unsupported(false, &[table]));+ }++ #[test]+ fn comments_unsupported_warning_is_absent_when_a_column_comment_was_collected() {+ let tables = vec![table_with_columns("public", "orders", vec![column_with_comment("Internal notes.")])];+ assert!(!should_warn_comments_unsupported(false, &tables));+ }++ #[test]+ fn comments_unsupported_warning_does_not_fire_when_the_capability_flag_is_true() {+ let tables = vec![table_with_columns("public", "orders", vec![])];+ assert!(!should_warn_comments_unsupported(true, &tables));+ }++ #[test]+ fn no_foreign_key_warning_fires_when_flag_is_false_and_no_relationships_were_collected() {+ assert!(should_warn_no_foreign_key_metadata(false, &[]));+ }++ #[test]+ fn no_foreign_key_warning_is_absent_when_relationships_were_collected() {+ // Regression: ClickHouse/Doris genuinely report zero FK metadata, so+ // this must still fire for them — but an engine that DOES report+ // relationships must not be flagged just because its DDL capability+ // flag is false.+ let relationships = vec![sample_relationship()];+ assert!(!should_warn_no_foreign_key_metadata(false, &relationships));+ }++ #[test]+ fn no_foreign_key_warning_does_not_fire_when_the_capability_flag_is_true() {+ assert!(!should_warn_no_foreign_key_metadata(true, &[]));+ }+}diff --git a/crates/dbx-core/src/docs/color.rs b/crates/dbx-core/src/docs/color.rsnew file mode 100644index 0000000000..249c15a152--- /dev/null+++ b/crates/dbx-core/src/docs/color.rs@@ -0,0 +1,85 @@+/// Lightness and chroma of the light-theme `--group-c` token. Only hue+/// varies per group, which is what guarantees legible contrast.+const GROUP_LIGHTNESS: f64 = 0.55;+const GROUP_CHROMA: f64 = 0.15;++fn linear_to_srgb(channel: f64) -> f64 {+ if channel <= 0.003_130_8 {+ 12.92 * channel+ } else {+ 1.055 * channel.powf(1.0 / 2.4) - 0.055+ }+}++fn to_byte(channel: f64) -> u8 {+ (linear_to_srgb(channel).clamp(0.0, 1.0) * 255.0).round() as u8+}++/// Convert a group hue to the sRGB hex DBML expects.+///+/// OKLCH -> OKLab -> LMS -> linear sRGB -> gamma-encoded sRGB.+/// Coefficients are Björn Ottosson's published OKLab matrices.+pub fn hue_to_hex(hue: u16) -> String {+ let radians = f64::from(hue % 360) * std::f64::consts::PI / 180.0;+ let a = GROUP_CHROMA * radians.cos();+ let b = GROUP_CHROMA * radians.sin();++ let l_ = GROUP_LIGHTNESS + 0.396_337_777_4 * a + 0.215_803_757_3 * b;+ let m_ = GROUP_LIGHTNESS - 0.105_561_345_8 * a - 0.063_854_172_8 * b;+ let s_ = GROUP_LIGHTNESS - 0.089_484_177_5 * a - 1.291_485_548_0 * b;++ let l = l_ * l_ * l_;+ let m = m_ * m_ * m_;+ let s = s_ * s_ * s_;++ let red = 4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s;+ let green = -1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s;+ let blue = -0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701_0 * s;++ format!("#{:02x}{:02x}{:02x}", to_byte(red), to_byte(green), to_byte(blue))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn produces_a_six_digit_lowercase_hex_string() {+ let hex = hue_to_hex(28);+ assert_eq!(hex.len(), 7, "got {hex}");+ assert!(hex.starts_with('#'), "got {hex}");+ assert!(hex[1..].chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()), "got {hex}");+ }++ #[test]+ fn hue_28_is_a_warm_orange_red() {+ // Sanity check against the group palette: red channel dominates.+ let hex = hue_to_hex(28);+ let r = u8::from_str_radix(&hex[1..3], 16).unwrap();+ let g = u8::from_str_radix(&hex[3..5], 16).unwrap();+ let b = u8::from_str_radix(&hex[5..7], 16).unwrap();+ assert!(r > g && g > b, "expected r > g > b, got {hex}");+ }++ #[test]+ fn hue_148_is_green_dominant() {+ let hex = hue_to_hex(148);+ let r = u8::from_str_radix(&hex[1..3], 16).unwrap();+ let g = u8::from_str_radix(&hex[3..5], 16).unwrap();+ assert!(g > r, "expected green to dominate, got {hex}");+ }++ #[test]+ fn every_hue_is_in_range_and_never_panics() {+ for hue in 0..=359u16 {+ let hex = hue_to_hex(hue);+ assert_eq!(hex.len(), 7, "hue {hue} produced {hex}");+ }+ }++ #[test]+ fn hue_wraps_past_360() {+ assert_eq!(hue_to_hex(0), hue_to_hex(360));+ assert_eq!(hue_to_hex(28), hue_to_hex(388));+ }+}diff --git a/crates/dbx-core/src/docs/dbml.rs b/crates/dbx-core/src/docs/dbml.rsnew file mode 100644index 0000000000..2bd43e4bcc--- /dev/null+++ b/crates/dbx-core/src/docs/dbml.rs@@ -0,0 +1,893 @@+use crate::docs::hue_to_hex;+use crate::docs::{+ Cardinality, DocEnum, DocTable, FieldRef, Relationship, SchemaSnapshot, SnapshotWarning, TableGroup,+};+use crate::types::{ColumnInfo, IndexInfo};++/// DBML accepts bare identifiers matching `[A-Za-z_][A-Za-z0-9_]*`;+/// everything else needs double quotes.+pub(crate) fn quote_identifier(value: &str) -> String {+ let plain = !value.is_empty()+ && value.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')+ && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');++ if plain {+ value.to_string()+ } else {+ format!("\"{}\"", value.replace('"', "\\\""))+ }+}++/// `schema.name` when qualifying, bare `name` otherwise. Both parts quoted+/// independently so an irregular schema or table name is handled correctly.+pub(crate) fn qualified(schema: Option<&str>, name: &str, qualify: bool) -> String {+ match schema.filter(|s| !s.is_empty()) {+ Some(schema) if qualify => format!("{}.{}", quote_identifier(schema), quote_identifier(name)),+ _ => quote_identifier(name),+ }+}++/// Notes always use triple quotes so an apostrophe in prose can never break+/// the file.+///+/// Two things need escaping. A literal `'''` inside the prose, obviously —+/// and also a SINGLE trailing quote, which is subtler: the note `he said '`+/// would otherwise render as `'''he said ''''`, four quotes in a row, and a+/// parser scanning for the closing `'''` would close early and strand the+/// fourth. DBML honours `\'` inside triple quotes.+pub(crate) fn render_note(value: &str) -> String {+ let escaped = value.replace("'''", "\\'''");+ let escaped = match escaped.strip_suffix('\'') {+ Some(head) => format!("{head}\\'"),+ None => escaped,+ };+ format!("'''{escaped}'''")+}++fn looks_like_expression(value: &str) -> bool {+ let trimmed = value.trim();+ if trimmed.starts_with('\'') && trimmed.ends_with('\'') && trimmed.len() >= 2 {+ return false;+ }+ if trimmed.parse::<f64>().is_ok() {+ return false;+ }+ if matches!(trimmed.to_ascii_lowercase().as_str(), "true" | "false" | "null") {+ return false;+ }+ true+}++/// `default: …` for a column, or None when it has no default.+/// Expressions go in backticks, literals stay as written.+pub(crate) fn render_default(column: &ColumnInfo) -> Option<String> {+ let value = column.column_default.as_deref()?.trim();+ if value.is_empty() {+ return None;+ }++ if looks_like_expression(value) {+ Some(format!("default: `{value}`"))+ } else {+ Some(format!("default: {value}"))+ }+}++/// True when `data_type` is MySQL's inline `ENUM(...)` spelling rather than+/// a genuine named type. PostgreSQL reports a named enum type's own+/// identifier in `data_type` instead (e.g. `"ConversationStatus"`) — only+/// the inline MySQL spelling needs a synthesized name.+pub(crate) fn is_inline_enum_spelling(data_type: &str) -> bool {+ let trimmed = data_type.trim();+ trimmed.get(..5).is_some_and(|prefix| prefix.eq_ignore_ascii_case("enum(")) && trimmed.ends_with(')')+}++/// PostgreSQL's `format_type` double-quotes an identifier that needs it+/// (e.g. `"ConversationStatus"`); strip that quoting so the bare name can be+/// used as a DBML identifier directly — `quote_identifier` re-quotes it if+/// DBML itself requires that.+pub(crate) fn unquote_pg_identifier(value: &str) -> String {+ let trimmed = value.trim();+ match trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {+ true => trimmed[1..trimmed.len() - 1].replace("\"\"", "\""),+ false => trimmed.to_string(),+ }+}++/// The enum name a column's `enum_values` refers to: the synthesized+/// `{table}_{column}` name for MySQL's inline `ENUM(...)` columns, or the+/// native type name for a genuine named enum type (e.g. PostgreSQL).+///+/// This is the single source of truth for that name — `synthesize_enum`+/// (collector) and `render_type` (below) both go through it, so a column's+/// type reference and its `Enum` block name can never drift apart again.+pub(crate) fn enum_type_name(column: &ColumnInfo, table_name: &str) -> String {+ if is_inline_enum_spelling(&column.data_type) {+ format!("{table_name}_{}", column.name)+ } else {+ unquote_pg_identifier(&column.data_type)+ }+}++/// DBML does not validate type names, so native types pass through intact.+/// Precision is reconstructed only when the engine reported a bare type.+pub(crate) fn render_type(column: &ColumnInfo, table_schema: Option<&str>, table_name: &str, qualify: bool) -> String {+ // A column carrying enum values is emitted as a named enum elsewhere in+ // the document. This must produce the SAME string `render_enum` produces+ // for that block — including schema qualification — or the reference+ // dangles and the Enum block becomes an orphan.+ if column.enum_values.as_ref().is_some_and(|values| !values.is_empty()) {+ return qualified(table_schema, &enum_type_name(column, table_name), qualify);+ }++ let base = column.data_type.trim();+ if base.contains('(') {+ return base.to_string();+ }++ if let Some(length) = column.character_maximum_length.filter(|value| *value > 0) {+ return format!("{base}({length})");+ }++ if let Some(precision) = column.numeric_precision.filter(|value| *value > 0) {+ return match column.numeric_scale {+ Some(scale) if scale > 0 => format!("{base}({precision},{scale})"),+ _ => format!("{base}({precision})"),+ };+ }++ base.to_string()+}++fn column_settings(column: &ColumnInfo, table: &DocTable) -> Vec<String> {+ let mut settings = Vec::new();++ if column.is_primary_key {+ settings.push("pk".to_string());+ }++ let extra = column.extra.as_deref().unwrap_or("").to_ascii_lowercase();+ if extra.contains("auto_increment") || extra.contains("identity") {+ settings.push("increment".to_string());+ }++ if !column.is_nullable && !column.is_primary_key {+ settings.push("not null".to_string());+ }++ if let Some(default) = render_default(column) {+ settings.push(default);+ }++ if let Some(note) = table.column_notes.get(&column.name) {+ settings.push(format!("note: {}", render_note(¬e.note)));+ } else if let Some(comment) = column.comment.as_deref().filter(|value| !value.trim().is_empty()) {+ settings.push(format!("note: {}", render_note(comment)));+ }++ settings+}++fn render_index(index: &IndexInfo) -> String {+ let columns = index.columns.iter().map(|c| quote_identifier(c)).collect::<Vec<_>>().join(", ");++ let mut settings = vec![format!("name: '{}'", index.name.replace('\'', "\\'"))];+ if index.is_unique {+ settings.push("unique".to_string());+ }++ format!(" ({columns}) [{}]\n", settings.join(", "))+}++/// Render one `Table` block.+///+/// The primary-key index is skipped because columns already carry `pk`.+/// Indexes DBML cannot express are skipped and recorded in `warnings`+/// rather than dropped silently.+pub(crate) fn render_table(table: &DocTable, qualify: bool, warnings: &mut Vec<SnapshotWarning>) -> String {+ let name = qualified(table.schema.as_deref(), &table.name, qualify);++ let mut out = format!("Table {name} {{\n");++ for column in &table.columns {+ let settings = column_settings(column, table);+ let rendered_settings = if settings.is_empty() { String::new() } else { format!(" [{}]", settings.join(", ")) };+ out.push_str(&format!(+ " {} {}{}\n",+ quote_identifier(&column.name),+ render_type(column, table.schema.as_deref(), &table.name, qualify),+ rendered_settings+ ));+ }++ let emittable: Vec<&IndexInfo> = table+ .indexes+ .iter()+ .filter(|index| {+ if index.is_primary {+ return false;+ }+ if index.filter.as_deref().is_some_and(|f| !f.trim().is_empty()) {+ warnings.push(SnapshotWarning::DbmlOmitted {+ table: table.qualified_name(),+ item: index.name.clone(),+ reason: "partial index filter has no DBML equivalent".to_string(),+ });+ return false;+ }+ if index.included_columns.as_ref().is_some_and(|columns| !columns.is_empty()) {+ warnings.push(SnapshotWarning::DbmlOmitted {+ table: table.qualified_name(),+ item: index.name.clone(),+ reason: "included columns have no DBML equivalent".to_string(),+ });+ return false;+ }+ !index.columns.is_empty()+ })+ .collect();++ if !emittable.is_empty() {+ out.push_str("\n Indexes {\n");+ for index in emittable {+ out.push_str(&render_index(index));+ }+ out.push_str(" }\n");+ }++ if let Some(note) = table.note.as_deref().filter(|value| !value.trim().is_empty()) {+ out.push_str(&format!("\n Note: {}\n", render_note(note)));+ }++ out.push_str("}\n");+ out+}++fn qualified_field(field: &FieldRef, qualify: bool) -> String {+ let table = qualified(field.schema.as_deref(), &field.table, qualify);+ format!("{table}.{}", quote_identifier(&field.column))+}++/// One `Ref` line. `>` is many-to-one, `-` is one-to-one.+pub(crate) fn render_ref(relationship: &Relationship, qualify: bool) -> String {+ let operator = match relationship.cardinality {+ Cardinality::ManyToOne => ">",+ Cardinality::OneToOne => "-",+ };++ let mut actions = Vec::new();+ if let Some(update) = relationship.on_update.as_deref().filter(|v| !v.trim().is_empty()) {+ actions.push(format!("update: {}", update.to_lowercase()));+ }+ if let Some(delete) = relationship.on_delete.as_deref().filter(|v| !v.trim().is_empty()) {+ actions.push(format!("delete: {}", delete.to_lowercase()));+ }+ let settings = if actions.is_empty() { String::new() } else { format!(" [{}]", actions.join(", ")) };++ let label = match relationship.name.as_deref().filter(|v| !v.trim().is_empty()) {+ Some(name) => format!("Ref {}", quote_identifier(name)),+ None => "Ref".to_string(),+ };++ format!(+ "{label}: {} {operator} {}{settings}\n",+ qualified_field(&relationship.from, qualify),+ qualified_field(&relationship.to, qualify)+ )+}++pub(crate) fn render_enum(value: &DocEnum, qualify: bool) -> String {+ let name = qualified(value.schema.as_deref(), &value.name, qualify);++ let mut out = format!("Enum {name} {{\n");+ for variant in &value.values {+ out.push_str(&format!(" {}\n", quote_identifier(variant)));+ }+ if let Some(note) = value.note.as_deref().filter(|v| !v.trim().is_empty()) {+ out.push_str(&format!("\n Note: {}\n", render_note(note)));+ }+ out.push_str("}\n");+ out+}++/// A `TableGroup` block. Returns an empty string when the group has no+/// members, since DBML rejects an empty group body.+pub(crate) fn render_group(group: &TableGroup, members: &[&DocTable], qualify: bool) -> String {+ if members.is_empty() {+ return String::new();+ }++ let mut out = format!("TableGroup {} [color: {}] {{\n", quote_identifier(&group.name), hue_to_hex(group.hue));++ for member in members {+ let name = qualified(member.schema.as_deref(), &member.name, qualify);+ out.push_str(&format!(" {name}\n"));+ }++ if let Some(note) = group.note.as_deref().filter(|v| !v.trim().is_empty()) {+ out.push_str(&format!("\n Note: {}\n", render_note(note)));+ }++ out.push_str("}\n");+ out+}++/// DBML text plus every construct that could not be represented in it.+#[derive(Debug, Clone)]+pub struct DbmlOutput {+ pub text: String,+ pub warnings: Vec<SnapshotWarning>,+}++fn render_project(snapshot: &SchemaSnapshot) -> String {+ let mut out = format!("Project {} {{\n", quote_identifier(&snapshot.project.name));+ out.push_str(&format!(" database_type: '{}'\n", snapshot.project.database_type.replace('\'', "\\'")));+ if let Some(note) = snapshot.project.note.as_deref().filter(|v| !v.trim().is_empty()) {+ out.push_str(&format!(" Note: {}\n", render_note(note)));+ }+ out.push_str("}\n");+ out+}++/// Serialize a snapshot to DBML.+///+/// DBML is an interchange format, not a backup: check constraints, partial+/// indexes, included columns, collations and generated columns have no+/// representation. Each omission is reported in `warnings` so the HTML+/// documentation — which *is* the complete record — can mark it.+pub fn to_dbml(snapshot: &SchemaSnapshot) -> DbmlOutput {+ let qualify = snapshot.project.schemas.len() > 1;+ // Start from the collector's warnings so omissions discovered at collection+ // time (skipped tables, unsupported comments) survive into the output+ // alongside those discovered while rendering.+ let mut warnings = snapshot.warnings.clone();+ let mut sections: Vec<String> = vec![render_project(snapshot)];++ for value in &snapshot.enums {+ sections.push(render_enum(value, qualify));+ }++ for group in &snapshot.groups {+ let members: Vec<&DocTable> =+ snapshot.tables.iter().filter(|table| table.group_id.as_deref() == Some(group.id.as_str())).collect();+ let rendered = render_group(group, &members, qualify);+ if !rendered.is_empty() {+ sections.push(rendered);+ }+ }++ for table in &snapshot.tables {+ sections.push(render_table(table, qualify, &mut warnings));+ }++ if !snapshot.relationships.is_empty() {+ let refs: String = snapshot.relationships.iter().map(|rel| render_ref(rel, qualify)).collect();+ sections.push(refs);+ }++ DbmlOutput { text: sections.join("\n"), warnings }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::types::ColumnInfo;++ fn col(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo { name: name.to_string(), data_type: data_type.to_string(), ..ColumnInfo::default() }+ }++ #[test]+ fn plain_identifiers_are_not_quoted() {+ assert_eq!(quote_identifier("orders"), "orders");+ assert_eq!(quote_identifier("order_items"), "order_items");+ assert_eq!(quote_identifier("_private"), "_private");+ assert_eq!(quote_identifier("t2"), "t2");+ }++ #[test]+ fn irregular_identifiers_are_quoted() {+ assert_eq!(quote_identifier("order items"), "\"order items\"");+ assert_eq!(quote_identifier("2fast"), "\"2fast\"");+ assert_eq!(quote_identifier("user-profile"), "\"user-profile\"");+ assert_eq!(quote_identifier(""), "\"\"");+ }++ #[test]+ fn embedded_double_quotes_are_escaped() {+ assert_eq!(quote_identifier("we\"ird"), "\"we\\\"ird\"");+ }++ #[test]+ fn notes_always_use_triple_quotes_so_apostrophes_are_safe() {+ assert_eq!(render_note("Bob's orders"), "'''Bob's orders'''");+ }++ #[test]+ fn notes_escape_a_literal_triple_quote() {+ assert_eq!(render_note("a ''' b"), "'''a \\''' b'''");+ }++ #[test]+ fn multiline_notes_are_preserved() {+ assert_eq!(render_note("line one\nline two"), "'''line one\nline two'''");+ }++ #[test]+ fn a_note_ending_in_a_single_quote_does_not_break_the_delimiter() {+ // Without escaping this yields four quotes in a row and a parser+ // closes the string early.+ assert_eq!(render_note("Deprecated in '24'"), "'''Deprecated in '24\\''''");+ }++ #[test]+ fn expression_defaults_use_backticks_and_literals_use_quotes() {+ let mut expression = col("created_at", "timestamptz");+ expression.column_default = Some("now()".to_string());+ assert_eq!(render_default(&expression).as_deref(), Some("default: `now()`"));++ let mut sequence = col("id", "integer");+ sequence.column_default = Some("nextval('orders_id_seq'::regclass)".to_string());+ assert_eq!(render_default(&sequence).as_deref(), Some("default: `nextval('orders_id_seq'::regclass)`"));++ let mut literal = col("status", "text");+ literal.column_default = Some("'pending'".to_string());+ assert_eq!(render_default(&literal).as_deref(), Some("default: 'pending'"));++ let mut number = col("qty", "integer");+ number.column_default = Some("0".to_string());+ assert_eq!(render_default(&number).as_deref(), Some("default: 0"));++ let mut boolean = col("active", "boolean");+ boolean.column_default = Some("true".to_string());+ assert_eq!(render_default(&boolean).as_deref(), Some("default: true"));++ assert_eq!(render_default(&col("plain", "text")), None);+ }++ #[test]+ fn types_pass_through_verbatim_when_already_parameterised() {+ assert_eq!(render_type(&col("total", "numeric(10,2)"), None, "orders", false), "numeric(10,2)");+ assert_eq!(render_type(&col("meta", "jsonb"), None, "orders", false), "jsonb");+ assert_eq!(+ render_type(&col("at", "timestamp with time zone"), None, "orders", false),+ "timestamp with time zone"+ );+ }++ #[test]+ fn bare_types_are_reconstructed_from_precision_metadata() {+ let mut varchar = col("email", "character varying");+ varchar.character_maximum_length = Some(255);+ assert_eq!(render_type(&varchar, None, "orders", false), "character varying(255)");++ let mut decimal = col("total", "numeric");+ decimal.numeric_precision = Some(10);+ decimal.numeric_scale = Some(2);+ assert_eq!(render_type(&decimal, None, "orders", false), "numeric(10,2)");++ let mut integer = col("count", "numeric");+ integer.numeric_precision = Some(8);+ integer.numeric_scale = Some(0);+ assert_eq!(render_type(&integer, None, "orders", false), "numeric(8)");+ }++ #[test]+ fn an_inline_enum_column_references_the_synthesized_enum_name() {+ let mut status = col("status", "enum('pending','shipped')");+ status.enum_values = Some(vec!["pending".to_string(), "shipped".to_string()]);+ assert_eq!(render_type(&status, None, "orders", false), "orders_status");+ }++ #[test]+ fn a_named_enum_type_column_references_its_own_native_name_not_a_synthesized_one() {+ // PostgreSQL reports the enum's own type name in `data_type` rather+ // than an inline `ENUM(...)` spelling — that native name must be+ // used verbatim, not the `{table}_{column}` scheme MySQL needs.+ let mut status = col("status", "ConversationStatus");+ status.enum_values = Some(vec!["open".to_string(), "closed".to_string()]);+ assert_eq!(render_type(&status, None, "conversations", false), "ConversationStatus");+ }++ #[test]+ fn a_quoted_native_enum_type_name_is_unquoted_for_the_reference() {+ // `format_type` double-quotes an identifier that needs it (mixed+ // case, here). The DBML reference must be the bare name so+ // `quote_identifier` can decide on its own quoting.+ let mut status = col("status", "\"ConversationStatus\"");+ status.enum_values = Some(vec!["open".to_string()]);+ assert_eq!(render_type(&status, None, "conversations", false), "ConversationStatus");+ }++ #[test]+ fn a_multi_schema_enum_reference_is_qualified_like_its_enum_block() {+ let mut status = col("status", "enum('pending','shipped')");+ status.enum_values = Some(vec!["pending".to_string(), "shipped".to_string()]);++ // qualify=true is what to_dbml sets for a multi-schema snapshot. The+ // column's type must match render_enum's block name exactly, or the+ // reference dangles.+ let reference = render_type(&status, Some("public"), "orders", true);++ let block = DocEnum {+ schema: Some("public".to_string()),+ name: "orders_status".to_string(),+ values: vec!["pending".to_string()],+ note: None,+ synthesized: true,+ };+ let rendered_block = render_enum(&block, true);++ // Anchored, not `contains`: a bare unqualified reference is a substring+ // of the qualified block name, so `contains` would pass against the very+ // bug this test exists to catch.+ assert!(+ rendered_block.starts_with(&format!("Enum {reference} {{\n")),+ "column reference `{reference}` must be exactly the Enum block name in:\n{rendered_block}"+ );+ }++ use crate::docs::{ColumnNote, DocTable, NoteSource, SnapshotWarning, TableKind};+ use crate::types::IndexInfo;+ use std::collections::BTreeMap;++ fn doc_table(name: &str, columns: Vec<ColumnInfo>, indexes: Vec<IndexInfo>) -> DocTable {+ DocTable {+ schema: Some("public".to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns,+ indexes,+ foreign_keys: vec![],+ group_id: None,+ note: None,+ note_source: NoteSource::None,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn renders_a_table_with_columns_and_settings() {+ let mut id = col("id", "integer");+ id.is_primary_key = true;+ id.extra = Some("auto_increment".to_string());++ let mut user_id = col("user_id", "integer");+ user_id.is_nullable = false;++ // ColumnInfo::default() gives is_nullable=false (i.e. NOT NULL), so a+ // genuinely nullable column has to say so explicitly.+ let mut nullable = col("shipped_at", "timestamptz");+ nullable.is_nullable = true;++ let mut table = doc_table("orders", vec![id, user_id, nullable], vec![]);+ table.note = Some("Checkout rows.".to_string());+ table.column_notes.insert(+ "user_id".to_string(),+ ColumnNote { note: "Owning customer".to_string(), source: NoteSource::Local, shadowed: None },+ );++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);++ assert!(out.starts_with("Table orders {\n"), "got:\n{out}");+ assert!(out.contains("id integer [pk, increment]"), "got:\n{out}");+ assert!(out.contains("user_id integer [not null, note: '''Owning customer''']"), "got:\n{out}");+ assert!(out.contains("shipped_at timestamptz\n"), "got:\n{out}");+ assert!(out.contains("Note: '''Checkout rows.'''"), "got:\n{out}");+ assert!(out.ends_with("}\n"), "got:\n{out}");+ }++ #[test]+ fn qualifies_the_table_name_when_requested() {+ let table = doc_table("orders", vec![col("id", "integer")], vec![]);+ let mut warnings = Vec::new();+ assert!(render_table(&table, true, &mut warnings).starts_with("Table public.orders {"));+ }++ #[test]+ fn renders_an_indexes_block() {+ let index = IndexInfo {+ name: "idx_orders_user_placed".to_string(),+ columns: vec!["user_id".to_string(), "placed_at".to_string()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let table = doc_table("orders", vec![col("user_id", "integer")], vec![index]);++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);++ assert!(out.contains("Indexes {"), "got:\n{out}");+ assert!(out.contains("(user_id, placed_at) [name: 'idx_orders_user_placed']"), "got:\n{out}");+ assert!(warnings.is_empty());+ }++ #[test]+ fn a_unique_index_carries_the_unique_setting() {+ let index = IndexInfo {+ name: "uq_orders_ref".to_string(),+ columns: vec!["reference".to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let table = doc_table("orders", vec![col("reference", "text")], vec![index]);+ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);+ assert!(out.contains("(reference) [name: 'uq_orders_ref', unique]"), "got:\n{out}");+ }++ #[test]+ fn the_primary_key_index_is_skipped_because_columns_already_carry_pk() {+ let index = IndexInfo {+ name: "orders_pkey".to_string(),+ columns: vec!["id".to_string()],+ is_unique: true,+ is_primary: true,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let mut id = col("id", "integer");+ id.is_primary_key = true;+ let table = doc_table("orders", vec![id], vec![index]);++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);+ assert!(!out.contains("orders_pkey"), "got:\n{out}");+ }++ #[test]+ fn a_filtered_index_is_omitted_and_warned_about() {+ let index = IndexInfo {+ name: "idx_orders_open".to_string(),+ columns: vec!["status".to_string()],+ is_unique: false,+ is_primary: false,+ filter: Some("status <> 'cancelled'".to_string()),+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let table = doc_table("orders", vec![col("status", "text")], vec![index]);++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);++ assert!(!out.contains("idx_orders_open"), "filtered index must not be emitted, got:\n{out}");+ assert_eq!(warnings.len(), 1);+ match &warnings[0] {+ SnapshotWarning::DbmlOmitted { table, item, reason } => {+ assert_eq!(table, "public.orders");+ assert_eq!(item, "idx_orders_open");+ assert!(reason.contains("filter"), "got {reason}");+ }+ other => panic!("unexpected warning: {other:?}"),+ }+ }++ use crate::docs::{Cardinality, DocEnum, FieldRef, Relationship, TableGroup};++ fn relationship(cardinality: Cardinality) -> Relationship {+ Relationship {+ id: "r1".to_string(),+ name: Some("fk_orders_user".to_string()),+ from: FieldRef {+ schema: Some("public".to_string()),+ table: "orders".to_string(),+ column: "user_id".to_string(),+ },+ to: FieldRef { schema: Some("public".to_string()), table: "users".to_string(), column: "id".to_string() },+ cardinality,+ on_update: None,+ on_delete: Some("CASCADE".to_string()),+ }+ }++ #[test]+ fn many_to_one_uses_the_gt_operator() {+ let out = render_ref(&relationship(Cardinality::ManyToOne), false);+ assert_eq!(out, "Ref fk_orders_user: orders.user_id > users.id [delete: cascade]\n");+ }++ #[test]+ fn one_to_one_uses_the_dash_operator() {+ let out = render_ref(&relationship(Cardinality::OneToOne), false);+ assert!(out.contains("orders.user_id - users.id"), "got {out}");+ }++ #[test]+ fn refs_qualify_both_sides_together() {+ let out = render_ref(&relationship(Cardinality::ManyToOne), true);+ assert!(out.contains("public.orders.user_id > public.users.id"), "got {out}");+ }++ #[test]+ fn referential_actions_are_lowercased_and_both_emitted() {+ let mut rel = relationship(Cardinality::ManyToOne);+ rel.on_update = Some("NO ACTION".to_string());+ rel.on_delete = Some("RESTRICT".to_string());+ let out = render_ref(&rel, false);+ assert!(out.contains("[update: no action, delete: restrict]"), "got {out}");+ }++ #[test]+ fn an_unnamed_ref_omits_the_name() {+ let mut rel = relationship(Cardinality::ManyToOne);+ rel.name = None;+ assert!(render_ref(&rel, false).starts_with("Ref: orders.user_id"), "got {}", render_ref(&rel, false));+ }++ #[test]+ fn renders_an_enum_block() {+ let value = DocEnum {+ schema: Some("public".to_string()),+ name: "order_status".to_string(),+ values: vec!["pending".to_string(), "shipped".to_string()],+ note: None,+ synthesized: false,+ };+ let out = render_enum(&value, false);+ assert_eq!(out, "Enum order_status {\n pending\n shipped\n}\n");+ }++ #[test]+ fn renders_a_table_group_with_colour_and_note() {+ let group = TableGroup {+ id: "order-management".to_string(),+ name: "Order Management".to_string(),+ hue: 28,+ note: Some("Checkout to carrier handoff.".to_string()),+ };+ let orders = doc_table("orders", vec![], vec![]);+ let items = doc_table("order_items", vec![], vec![]);++ let out = render_group(&group, &[&orders, &items], false);++ assert!(out.starts_with("TableGroup \"Order Management\" [color: #"), "got:\n{out}");+ assert!(out.contains("\n orders\n"), "got:\n{out}");+ assert!(out.contains("\n order_items\n"), "got:\n{out}");+ assert!(out.contains("Note: '''Checkout to carrier handoff.'''"), "got:\n{out}");+ }++ #[test]+ fn an_empty_group_renders_nothing() {+ let group = TableGroup { id: "empty".to_string(), name: "Empty".to_string(), hue: 0, note: None };+ assert_eq!(render_group(&group, &[], false), "");+ }++ use crate::docs::{ProjectMeta, SchemaSnapshot};++ fn snapshot(tables: Vec<DocTable>, schemas: Vec<&str>) -> SchemaSnapshot {+ SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: "Ecommerce".to_string(),+ database_type: "PostgreSQL".to_string(),+ database: Some("shop".to_string()),+ schemas: schemas.into_iter().map(str::to_string).collect(),+ generated_at: "2026-08-02T12:00:00Z".to_string(),+ note: Some("Storefront database.".to_string()),+ },+ tables,+ relationships: vec![],+ groups: vec![],+ enums: vec![],+ warnings: vec![],+ }+ }++ #[test]+ fn emits_a_project_block_first() {+ let out = to_dbml(&snapshot(vec![], vec!["public"]));+ assert!(out.text.starts_with("Project Ecommerce {\n"), "got:\n{}", out.text);+ assert!(out.text.contains("database_type: 'PostgreSQL'"), "got:\n{}", out.text);+ assert!(out.text.contains("Note: '''Storefront database.'''"), "got:\n{}", out.text);+ }++ #[test]+ fn a_single_schema_snapshot_uses_bare_table_names() {+ let out = to_dbml(&snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]));+ assert!(out.text.contains("Table orders {"), "got:\n{}", out.text);+ assert!(!out.text.contains("Table public.orders"), "got:\n{}", out.text);+ }++ #[test]+ fn a_multi_schema_snapshot_qualifies_every_table() {+ let mut analytics = doc_table("daily_sales", vec![col("id", "integer")], vec![]);+ analytics.schema = Some("analytics".to_string());++ let out = to_dbml(&snapshot(+ vec![doc_table("orders", vec![col("id", "integer")], vec![]), analytics],+ vec!["public", "analytics"],+ ));++ assert!(out.text.contains("Table public.orders {"), "got:\n{}", out.text);+ assert!(out.text.contains("Table analytics.daily_sales {"), "got:\n{}", out.text);+ }++ #[test]+ fn sections_appear_in_order_project_enums_groups_tables_refs() {+ let mut snap = snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]);+ snap.enums.push(DocEnum {+ schema: Some("public".to_string()),+ name: "order_status".to_string(),+ values: vec!["pending".to_string()],+ note: None,+ synthesized: false,+ });+ snap.groups.push(TableGroup {+ id: "order-management".to_string(),+ name: "Order Management".to_string(),+ hue: 28,+ note: None,+ });+ snap.tables[0].group_id = Some("order-management".to_string());+ snap.relationships.push(relationship(Cardinality::ManyToOne));++ let text = to_dbml(&snap).text;+ let project = text.find("Project ").expect("project");+ let enum_at = text.find("Enum ").expect("enum");+ let group = text.find("TableGroup ").expect("group");+ let table = text.find("Table orders").expect("table");+ let reference = text.find("Ref ").expect("ref");++ assert!(project < enum_at, "project before enums:\n{text}");+ assert!(enum_at < group, "enums before groups:\n{text}");+ assert!(group < table, "groups before tables:\n{text}");+ assert!(table < reference, "tables before refs:\n{text}");+ }++ #[test]+ fn warnings_from_table_rendering_reach_the_output() {+ let index = IndexInfo {+ name: "idx_partial".to_string(),+ columns: vec!["status".to_string()],+ is_unique: false,+ is_primary: false,+ filter: Some("status <> 'x'".to_string()),+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let out =+ to_dbml(&snapshot(vec![doc_table("orders", vec![col("status", "text")], vec![index])], vec!["public"]));+ assert_eq!(out.warnings.len(), 1);+ }++ #[test]+ fn a_group_referencing_a_missing_table_is_skipped() {+ let mut snap = snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]);+ snap.groups.push(TableGroup { id: "ghost".to_string(), name: "Ghost".to_string(), hue: 200, note: None });+ assert!(!to_dbml(&snap).text.contains("Ghost"), "got:\n{}", to_dbml(&snap).text);+ }++ #[test]+ fn collector_warnings_survive_into_the_output() {+ let mut snap = snapshot(vec![], vec!["public"]);+ snap.warnings.push(SnapshotWarning::TableSkipped {+ table: "public.secret".to_string(),+ reason: "permission denied".to_string(),+ });++ let out = to_dbml(&snap);++ assert_eq!(out.warnings.len(), 1, "collector warnings must not be dropped");+ match &out.warnings[0] {+ SnapshotWarning::TableSkipped { table, .. } => assert_eq!(table, "public.secret"),+ other => panic!("unexpected warning: {other:?}"),+ }+ }+}diff --git a/crates/dbx-core/src/docs/keys.rs b/crates/dbx-core/src/docs/keys.rsnew file mode 100644index 0000000000..cd5327c406--- /dev/null+++ b/crates/dbx-core/src/docs/keys.rs@@ -0,0 +1,98 @@+use crate::models::connection::DatabaseType;++/// Fold an identifier to its canonical case for note matching.+///+/// PostgreSQL folds unquoted identifiers to lower case, Oracle to upper.+/// MySQL depends on the server's `lower_case_table_names`; we fold to lower+/// unconditionally rather than pay a `SHOW VARIABLES` round-trip per+/// collection — on the rare case-sensitive configuration the only risk is+/// matching a note to a table differing solely by case, never attaching a+/// note to an unrelated table.+///+/// ClickHouse and MongoDB are genuinely case-sensitive: two identifiers+/// differing only by case are DIFFERENT objects there, so folding them+/// would let one note attach to the wrong one. They are left untouched.+///+/// The lower-case default is correct for the remaining SQL engines+/// (SQLite, SQL Server, DuckDB, rqlite, Doris, StarRocks), all of which+/// compare identifiers case-insensitively.+pub fn fold_identifier(db_type: DatabaseType, value: &str) -> String {+ match db_type {+ DatabaseType::Oracle => value.to_uppercase(),+ DatabaseType::ClickHouse | DatabaseType::MongoDb => value.to_string(),+ _ => value.to_lowercase(),+ }+}++/// `schema.table`, or bare `table` when there is no schema.+pub fn table_key(db_type: DatabaseType, schema: Option<&str>, table: &str) -> String {+ match schema.filter(|value| !value.is_empty()) {+ Some(schema) => {+ format!("{}.{}", fold_identifier(db_type, schema), fold_identifier(db_type, table))+ }+ None => fold_identifier(db_type, table),+ }+}++/// `schema.table.column`, or `table.column` when there is no schema.+pub fn column_key(db_type: DatabaseType, schema: Option<&str>, table: &str, column: &str) -> String {+ format!("{}.{}", table_key(db_type, schema, table), fold_identifier(db_type, column))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::models::connection::DatabaseType;++ #[test]+ fn postgres_folds_to_lowercase() {+ assert_eq!(fold_identifier(DatabaseType::Postgres, "Orders"), "orders");+ assert_eq!(fold_identifier(DatabaseType::Postgres, "ORDERS"), "orders");+ }++ #[test]+ fn mysql_folds_to_lowercase() {+ assert_eq!(fold_identifier(DatabaseType::Mysql, "Orders"), "orders");+ }++ #[test]+ fn table_keys_are_qualified_when_a_schema_is_present() {+ assert_eq!(table_key(DatabaseType::Postgres, Some("Core"), "Orders"), "core.orders");+ assert_eq!(table_key(DatabaseType::Postgres, None, "Orders"), "orders");+ assert_eq!(table_key(DatabaseType::Postgres, Some(""), "Orders"), "orders");+ }++ #[test]+ fn column_keys_extend_the_table_key() {+ assert_eq!(column_key(DatabaseType::Postgres, Some("core"), "orders", "Status"), "core.orders.status");+ }++ #[test]+ fn folding_is_idempotent() {+ // Folding an already-folded value must be a no-op, or a key would+ // depend on how many times it had been normalised.+ for engine in [DatabaseType::Postgres, DatabaseType::Oracle, DatabaseType::ClickHouse] {+ let once = fold_identifier(engine, "MixedCase");+ assert_eq!(fold_identifier(engine, &once), once, "engine {engine:?}");+ }++ let key_once = table_key(DatabaseType::Postgres, Some("Core"), "Orders");+ assert_eq!(key_once, "core.orders");+ // Re-folding each segment of an existing key must not change it.+ let refolded = key_once+ .split('.')+ .map(|segment| fold_identifier(DatabaseType::Postgres, segment))+ .collect::<Vec<_>>()+ .join(".");+ assert_eq!(refolded, key_once);+ }++ #[test]+ fn case_sensitive_engines_are_not_folded() {+ // ClickHouse and MongoDB treat `Orders` and `orders` as DIFFERENT+ // objects. Folding them would let one note attach to the wrong one.+ assert_eq!(fold_identifier(DatabaseType::ClickHouse, "Orders"), "Orders");+ assert_eq!(fold_identifier(DatabaseType::MongoDb, "Orders"), "Orders");+ assert_eq!(table_key(DatabaseType::ClickHouse, Some("Analytics"), "Orders"), "Analytics.Orders");+ }+}diff --git a/crates/dbx-core/src/docs/mod.rs b/crates/dbx-core/src/docs/mod.rsnew file mode 100644index 0000000000..dabea07811--- /dev/null+++ b/crates/dbx-core/src/docs/mod.rs@@ -0,0 +1,14 @@+pub mod annotations;+pub mod collector;+pub mod color;+pub mod dbml;+pub mod keys;+pub mod relations;+pub mod snapshot;++pub use collector::{collect_snapshot, CollectOptions, CollectProgress};+pub use color::hue_to_hex;+pub use dbml::{to_dbml, DbmlOutput};+pub use keys::{column_key, fold_identifier, table_key};+pub use relations::build_relationships;+pub use snapshot::*;diff --git a/crates/dbx-core/src/docs/relations.rs b/crates/dbx-core/src/docs/relations.rsnew file mode 100644index 0000000000..be555bfa67--- /dev/null+++ b/crates/dbx-core/src/docs/relations.rs@@ -0,0 +1,392 @@+use std::collections::HashSet;++use crate::docs::{Cardinality, DocTable, FieldRef, Relationship};+use crate::types::ForeignKeyInfo;++/// True when `column` alone is guaranteed unique on `table` — either it is a+/// single-column primary key, or a single-column unique index covers it.+///+/// A composite unique index over (a, b) does NOT make `a` unique, which is+/// why the column count is checked.+fn column_is_unique(table: &DocTable, column: &str) -> bool {+ let primary_columns: Vec<&str> =+ table.columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();++ if primary_columns.len() == 1 && primary_columns[0] == column {+ return true;+ }++ table+ .indexes+ .iter()+ .any(|index| (index.is_unique || index.is_primary) && index.columns.len() == 1 && index.columns[0] == column)+}++fn cardinality_for(table: &DocTable, foreign_key: &ForeignKeyInfo) -> Cardinality {+ if column_is_unique(table, &foreign_key.column) {+ Cardinality::OneToOne+ } else {+ Cardinality::ManyToOne+ }+}++fn relationship_id(source: &DocTable, foreign_key: &ForeignKeyInfo) -> String {+ [+ source.qualified_name().as_str(),+ if foreign_key.name.is_empty() { "foreign_key" } else { foreign_key.name.as_str() },+ foreign_key.column.as_str(),+ foreign_key.ref_table.as_str(),+ foreign_key.ref_column.as_str(),+ ]+ .join(":")+}++/// Resolve a foreign key's target against the tables actually present.+///+/// Resolution order mirrors SQL's own: an explicit `ref_schema` wins; an+/// unqualified reference resolves inside the source table's own schema;+/// only then do we consider a bare-name match elsewhere — and an ambiguous+/// one is dropped rather than guessed at, because a wrong edge is worse+/// than a missing one.+fn find_target<'a>(tables: &'a [DocTable], source: &DocTable, foreign_key: &ForeignKeyInfo) -> Option<&'a DocTable> {+ // An explicit ref_schema is authoritative: the database told us exactly+ // which schema the key points at. If that schema was not collected, the+ // edge must be DROPPED, not resolved elsewhere. Falling through would bind+ // it to a same-named table in a different schema — `sales.orders` pointing+ // at `archive.customers` would render as pointing at `sales.customers`,+ // which is a confidently wrong diagram rather than an incomplete one.+ if let Some(ref_schema) = foreign_key.ref_schema.as_deref().filter(|s| !s.is_empty()) {+ return tables.iter().find(|t| t.name == foreign_key.ref_table && t.schema.as_deref() == Some(ref_schema));+ }++ if let Some(found) = tables.iter().find(|t| t.name == foreign_key.ref_table && t.schema == source.schema) {+ return Some(found);+ }++ let mut matches = tables.iter().filter(|t| t.name == foreign_key.ref_table);+ let first = matches.next()?;+ if matches.next().is_some() {+ return None;+ }+ Some(first)+}++/// Build the relationship set for a snapshot.+///+/// Foreign keys pointing at tables outside the collected set are dropped —+/// the target may live in a schema the user did not select, and a dangling+/// edge renders as a relationship to nothing.+pub fn build_relationships(tables: &[DocTable]) -> Vec<Relationship> {+ let mut seen: HashSet<String> = HashSet::new();+ let mut relationships = Vec::new();++ for source in tables {+ for foreign_key in &source.foreign_keys {+ let Some(target) = find_target(tables, source, foreign_key) else { continue };++ if !source.columns.iter().any(|c| c.name == foreign_key.column) {+ continue;+ }++ let id = relationship_id(source, foreign_key);+ if !seen.insert(id.clone()) {+ continue;+ }++ relationships.push(Relationship {+ id,+ name: (!foreign_key.name.is_empty()).then(|| foreign_key.name.clone()),+ from: FieldRef {+ schema: source.schema.clone(),+ table: source.name.clone(),+ column: foreign_key.column.clone(),+ },+ to: FieldRef {+ schema: target.schema.clone(),+ table: target.name.clone(),+ column: foreign_key.ref_column.clone(),+ },+ cardinality: cardinality_for(source, foreign_key),+ on_update: foreign_key.on_update.clone(),+ on_delete: foreign_key.on_delete.clone(),+ });+ }+ }++ relationships+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docs::{NoteSource, TableKind};+ use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};+ use std::collections::BTreeMap;++ fn column(name: &str, primary: bool) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: "integer".to_string(),+ is_nullable: false,+ is_primary_key: primary,+ ..ColumnInfo::default()+ }+ }++ fn fk(name: &str, column: &str, ref_table: &str, ref_column: &str) -> ForeignKeyInfo {+ ForeignKeyInfo {+ name: name.to_string(),+ column: column.to_string(),+ ref_schema: Some("public".to_string()),+ ref_table: ref_table.to_string(),+ ref_column: ref_column.to_string(),+ on_update: None,+ on_delete: Some("CASCADE".to_string()),+ }+ }++ fn table_in(schema: &str, name: &str, fks: Vec<ForeignKeyInfo>) -> DocTable {+ DocTable {+ schema: Some(schema.to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns: vec![column("id", true), column("customer_id", false)],+ indexes: Vec::new(),+ foreign_keys: fks,+ group_id: None,+ note: None,+ note_source: NoteSource::None,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn an_unresolvable_explicit_ref_schema_does_not_fall_back_to_another_schema() {+ // sales.orders -> archive.customers, but only the `sales` schema was+ // collected. `archive.customers` is absent, and `sales.customers`+ // exists with the same bare name. Falling through to the source-schema+ // tier would bind the edge to sales.customers — a different table than+ // the foreign key names — and render a plausible but wrong diagram.+ let mut fk = fk("orders_customer_fk", "customer_id", "customers", "id");+ fk.ref_schema = Some("archive".to_string());++ let tables = vec![table_in("sales", "orders", vec![fk]), table_in("sales", "customers", Vec::new())];++ let relationships = build_relationships(&tables);+ assert!(+ relationships.is_empty(),+ "expected the edge to be dropped, got {:?}",+ relationships.iter().map(|r| (&r.from.table, &r.to.table)).collect::<Vec<_>>()+ );+ }++ fn unique_index(name: &str, columns: &[&str]) -> IndexInfo {+ IndexInfo {+ name: name.to_string(),+ columns: columns.iter().map(|c| c.to_string()).collect(),+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ }+ }++ fn table(name: &str, columns: Vec<ColumnInfo>, indexes: Vec<IndexInfo>, fks: Vec<ForeignKeyInfo>) -> DocTable {+ DocTable {+ schema: Some("public".to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns,+ indexes,+ foreign_keys: fks,+ group_id: None,+ note: None,+ note_source: NoteSource::None,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn plain_foreign_key_is_many_to_one() {+ let tables = vec![+ table(+ "orders",+ vec![column("id", true), column("user_id", false)],+ vec![],+ vec![fk("fk_orders_user", "user_id", "users", "id")],+ ),+ table("users", vec![column("id", true)], vec![], vec![]),+ ];++ let rels = build_relationships(&tables);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].cardinality, Cardinality::ManyToOne);+ assert_eq!(rels[0].from.table, "orders");+ assert_eq!(rels[0].from.column, "user_id");+ assert_eq!(rels[0].to.table, "users");+ assert_eq!(rels[0].to.column, "id");+ assert_eq!(rels[0].on_delete.as_deref(), Some("CASCADE"));+ }++ #[test]+ fn foreign_key_on_a_unique_column_is_one_to_one() {+ let tables = vec![+ table(+ "shipments",+ vec![column("id", true), column("order_id", false)],+ vec![unique_index("uq_shipments_order", &["order_id"])],+ vec![fk("fk_shipments_order", "order_id", "orders", "id")],+ ),+ table("orders", vec![column("id", true)], vec![], vec![]),+ ];++ let rels = build_relationships(&tables);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].cardinality, Cardinality::OneToOne);+ }++ #[test]+ fn foreign_key_on_a_primary_key_column_is_one_to_one() {+ let tables = vec![+ table(+ "user_profiles",+ vec![column("user_id", true)],+ vec![],+ vec![fk("fk_profile_user", "user_id", "users", "id")],+ ),+ table("users", vec![column("id", true)], vec![], vec![]),+ ];++ assert_eq!(build_relationships(&tables)[0].cardinality, Cardinality::OneToOne);+ }++ #[test]+ fn multi_column_unique_index_does_not_make_a_single_column_unique() {+ // uq(a, b) does NOT make `a` alone unique, so the FK stays many-to-one.+ let tables = vec![+ table(+ "order_items",+ vec![column("order_id", false), column("product_id", false)],+ vec![unique_index("uq_items", &["order_id", "product_id"])],+ vec![fk("fk_items_order", "order_id", "orders", "id")],+ ),+ table("orders", vec![column("id", true)], vec![], vec![]),+ ];++ assert_eq!(build_relationships(&tables)[0].cardinality, Cardinality::ManyToOne);+ }++ #[test]+ fn self_referencing_foreign_key_is_supported() {+ let tables = vec![table(+ "categories",+ vec![column("id", true), column("parent_id", false)],+ vec![],+ vec![fk("fk_cat_parent", "parent_id", "categories", "id")],+ )];++ let rels = build_relationships(&tables);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].from.table, "categories");+ assert_eq!(rels[0].to.table, "categories");+ }++ #[test]+ fn foreign_key_to_an_absent_table_is_dropped() {+ // The target may live outside the selected schema. A dangling edge+ // would render as a relationship to nothing.+ let tables = vec![table(+ "orders",+ vec![column("user_id", false)],+ vec![],+ vec![fk("fk_orders_user", "user_id", "users", "id")],+ )];++ assert!(build_relationships(&tables).is_empty());+ }++ #[test]+ fn relationship_ids_are_stable_and_unique() {+ let tables = vec![+ table(+ "orders",+ vec![column("user_id", false), column("merchant_id", false)],+ vec![],+ vec![fk("fk_a", "user_id", "users", "id"), fk("fk_b", "merchant_id", "users", "id")],+ ),+ table("users", vec![column("id", true)], vec![], vec![]),+ ];++ let rels = build_relationships(&tables);+ assert_eq!(rels.len(), 2);+ assert_ne!(rels[0].id, rels[1].id);+ assert_eq!(build_relationships(&tables)[0].id, rels[0].id);+ }++ #[test]+ fn an_unqualified_foreign_key_resolves_within_the_source_schema() {+ let mut orders = table(+ "orders",+ vec![column("id", true), column("user_id", false)],+ vec![],+ vec![ForeignKeyInfo {+ name: "fk_orders_user".to_string(),+ column: "user_id".to_string(),+ ref_schema: None,+ ref_table: "users".to_string(),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: None,+ }],+ );+ orders.schema = Some("tenant_a".to_string());++ let mut users_a = table("users", vec![column("id", true)], vec![], vec![]);+ users_a.schema = Some("tenant_a".to_string());+ let mut users_b = table("users", vec![column("id", true)], vec![], vec![]);+ users_b.schema = Some("tenant_b".to_string());++ // tenant_b listed FIRST so a naive first-match would pick the wrong one.+ let rels = build_relationships(&[users_b, orders, users_a]);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].to.schema.as_deref(), Some("tenant_a"));+ }++ #[test]+ fn an_ambiguous_bare_name_reference_is_dropped_rather_than_guessed() {+ let mut orders = table(+ "orders",+ vec![column("id", true), column("user_id", false)],+ vec![],+ vec![ForeignKeyInfo {+ name: "fk_orders_user".to_string(),+ column: "user_id".to_string(),+ ref_schema: None,+ ref_table: "users".to_string(),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: None,+ }],+ );+ orders.schema = Some("app".to_string());++ let mut users_a = table("users", vec![column("id", true)], vec![], vec![]);+ users_a.schema = Some("tenant_a".to_string());+ let mut users_b = table("users", vec![column("id", true)], vec![], vec![]);+ users_b.schema = Some("tenant_b".to_string());++ assert!(build_relationships(&[orders, users_a, users_b]).is_empty());+ }+}diff --git a/crates/dbx-core/src/docs/snapshot.rs b/crates/dbx-core/src/docs/snapshot.rsnew file mode 100644index 0000000000..149cf78dd6--- /dev/null+++ b/crates/dbx-core/src/docs/snapshot.rs@@ -0,0 +1,315 @@+use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};++/// The normalized description of a relational schema. Every documentation+/// output (DBML, HTML, future changelog records) is a serializer over this.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SchemaSnapshot {+ /// Guards viewer/data skew. Always 1 for now; bump only on a breaking+ /// change to this model.+ pub format_version: u32,+ pub project: ProjectMeta,+ pub tables: Vec<DocTable>,+ pub relationships: Vec<Relationship>,+ #[serde(default)]+ pub groups: Vec<TableGroup>,+ #[serde(default)]+ pub enums: Vec<DocEnum>,+ #[serde(default)]+ pub warnings: Vec<SnapshotWarning>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ProjectMeta {+ pub name: String,+ pub database_type: String,+ pub database: Option<String>,+ pub schemas: Vec<String>,+ /// RFC3339.+ pub generated_at: String,+ /// Markdown. Rendered as the documentation landing page.+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocTable {+ pub schema: Option<String>,+ pub name: String,+ pub kind: TableKind,+ pub columns: Vec<ColumnInfo>,+ pub indexes: Vec<IndexInfo>,+ pub foreign_keys: Vec<ForeignKeyInfo>,+ /// References `TableGroup::id`. Populated in Part 2.+ pub group_id: Option<String>,+ /// Merged note: local annotation, else database comment.+ pub note: Option<String>,+ pub note_source: NoteSource,+ /// The database comment a local note is overriding, if any. Shown on+ /// hover so a later `COMMENT ON` improvement is never invisible.+ pub shadowed_note: Option<String>,+ #[serde(default)]+ pub column_notes: BTreeMap<String, ColumnNote>,+ pub estimated_rows: Option<i64>,+ pub view_definition: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct TableGroup {+ /// Stable slug. Survives a display-name change.+ pub id: String,+ pub name: String,+ /// 0..=359. Lightness and chroma are theme-controlled in CSS, so any+ /// hue is legible on both grounds by construction.+ pub hue: u16,+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ColumnNote {+ pub note: String,+ pub source: NoteSource,+ pub shadowed: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocEnum {+ pub schema: Option<String>,+ pub name: String,+ pub values: Vec<String>,+ pub note: Option<String>,+ /// True when synthesized from a MySQL inline `ENUM(...)` column rather+ /// than read from a named database type.+ #[serde(default)]+ pub synthesized: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Relationship {+ pub id: String,+ pub name: Option<String>,+ pub from: FieldRef,+ pub to: FieldRef,+ pub cardinality: Cardinality,+ pub on_update: Option<String>,+ pub on_delete: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FieldRef {+ pub schema: Option<String>,+ pub table: String,+ pub column: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum TableKind {+ Table,+ View,+ MaterializedView,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum NoteSource {+ /// Read from a database COMMENT.+ Database,+ /// Authored in DBX, stored in the notes file.+ Local,+ None,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum Cardinality {+ OneToOne,+ ManyToOne,+}++/// Why a snapshot is less complete than it looks. Rendered as a dismissible+/// banner rather than left for the reader to discover.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", tag = "kind")]+pub enum SnapshotWarning {+ TableSkipped { table: String, reason: String },+ NoForeignKeyMetadata { engine: String },+ CommentsUnsupported { engine: String },+ OrphanedNotes { count: usize },+ DbmlOmitted { table: String, item: String, reason: String },+}++/// Human-readable warning text for headless callers.+///+/// The viewer translates these through its own `docs.warnings` namespace; the+/// CLI has no i18n runtime, so the English prose lives here. Without it the+/// only thing to print is the derived `Debug` form, which exposes the struct+/// shape and reads like a panic rather than like advice.+impl std::fmt::Display for SnapshotWarning {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::TableSkipped { table, reason } => {+ write!(formatter, "{table} was skipped: {reason}. It is missing from this documentation.")+ }+ Self::NoForeignKeyMetadata { engine } => {+ write!(+ formatter,+ "{engine} does not report foreign key metadata, so no relationships could be derived."+ )+ }+ Self::CommentsUnsupported { engine } => write!(+ formatter,+ "{engine} does not support table or column comments, so every description comes from your own notes."+ ),+ Self::OrphanedNotes { count } => write!(+ formatter,+ "{count} note(s) refer to a table or column that no longer exists. Nothing was deleted."+ ),+ Self::DbmlOmitted { table, item, reason } => {+ write!(formatter, "{item} on {table} is documented but omitted from the DBML: {reason}.")+ }+ }+ }+}++impl DocTable {+ /// `schema.name` when a schema is present, otherwise bare `name`.+ pub fn qualified_name(&self) -> String {+ match &self.schema {+ Some(schema) if !schema.is_empty() => format!("{schema}.{}", self.name),+ _ => self.name.clone(),+ }+ }+}++impl FieldRef {+ pub fn qualified_table(&self) -> String {+ match &self.schema {+ Some(schema) if !schema.is_empty() => format!("{schema}.{}", self.table),+ _ => self.table.clone(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> SchemaSnapshot {+ SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: "Ecommerce".to_string(),+ database_type: "PostgreSQL".to_string(),+ database: Some("shop".to_string()),+ schemas: vec!["public".to_string()],+ generated_at: "2026-08-02T12:00:00Z".to_string(),+ note: None,+ },+ tables: vec![DocTable {+ schema: Some("public".to_string()),+ name: "orders".to_string(),+ kind: TableKind::Table,+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ group_id: None,+ note: Some("Checkout rows.".to_string()),+ note_source: NoteSource::Database,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: Some(2_400_000),+ view_definition: None,+ }],+ relationships: vec![],+ groups: vec![],+ enums: vec![],+ warnings: vec![],+ }+ }++ #[test]+ fn snapshot_round_trips_through_json() {+ let original = sample();+ let json = serde_json::to_string(&original).expect("serialize");+ let parsed: SchemaSnapshot = serde_json::from_str(&json).expect("deserialize");++ assert_eq!(parsed.format_version, 1);+ assert_eq!(parsed.project.name, "Ecommerce");+ assert_eq!(parsed.tables.len(), 1);+ assert_eq!(parsed.tables[0].name, "orders");+ assert_eq!(parsed.tables[0].note.as_deref(), Some("Checkout rows."));+ assert_eq!(parsed.tables[0].estimated_rows, Some(2_400_000));+ }++ #[test]+ fn snapshot_json_uses_camel_case_keys() {+ let json = serde_json::to_string(&sample()).expect("serialize");+ assert!(json.contains("\"formatVersion\""), "got: {json}");+ assert!(json.contains("\"generatedAt\""), "got: {json}");+ assert!(json.contains("\"noteSource\""), "got: {json}");+ }++ #[test]+ fn table_kind_serializes_as_screaming_snake_case() {+ let json = serde_json::to_string(&TableKind::MaterializedView).expect("serialize");+ assert_eq!(json, "\"MATERIALIZED_VIEW\"");+ }++ #[test]+ fn every_warning_renders_as_prose() {+ // `dbx dbml` prints these to stderr. The derived Debug form leaks the+ // struct shape (`DbmlOmitted { table: "public.t", .. }`), which reads+ // as a crash report rather than as advice, so Display is what the CLI+ // must use. The wording tracks the viewer's own warning strings.+ let cases = [+ (+ SnapshotWarning::TableSkipped { table: "public.orders".into(), reason: "permission denied".into() },+ "public.orders was skipped: permission denied. It is missing from this documentation.",+ ),+ (+ SnapshotWarning::NoForeignKeyMetadata { engine: "ClickHouse".into() },+ "ClickHouse does not report foreign key metadata, so no relationships could be derived.",+ ),+ (+ SnapshotWarning::CommentsUnsupported { engine: "SQLite".into() },+ "SQLite does not support table or column comments, so every description comes from your own notes.",+ ),+ (+ SnapshotWarning::OrphanedNotes { count: 3 },+ "3 note(s) refer to a table or column that no longer exists. Nothing was deleted.",+ ),+ (+ SnapshotWarning::DbmlOmitted {+ table: "public.orders".into(),+ item: "idx_partial".into(),+ reason: "partial index filter has no DBML equivalent".into(),+ },+ "idx_partial on public.orders is documented but omitted from the DBML: partial index filter has no DBML equivalent.",+ ),+ ];++ for (warning, expected) in cases {+ assert_eq!(warning.to_string(), expected);+ }+ }++ #[test]+ fn a_warning_never_renders_as_its_debug_form() {+ // The regression this guards: reverting the CLI to `{warning:?}` is a+ // one-character edit that still compiles and still prints something.+ let warning = SnapshotWarning::OrphanedNotes { count: 1 };+ assert!(!warning.to_string().contains('{'), "got: {warning}");+ assert_ne!(warning.to_string(), format!("{warning:?}"));+ }+}diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex 64cd0ba63e..5e0aa3d0dc 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -33,6 +33,7 @@ pub mod database_search_sql;pub mod db;pub mod db_admin_sql;pub mod dml_binding;+pub mod docs;pub mod document_ops;pub mod driver_runtime;pub mod external;diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rsindex 6d51bbec0a..fd47e2b39f 100644--- a/crates/dbx-core/src/models/connection.rs+++ b/crates/dbx-core/src/models/connection.rs@@ -102,6 +102,10 @@ pub struct ConnectionConfig {pub init_script: Option<String>,#[serde(default)]pub color: Option<String>,+ /// Path to this connection's documentation notes file. Set by the+ /// desktop app; the CLI takes an explicit `--notes` path instead.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub docs_notes_path: Option<String>,#[serde(default, skip_serializing_if = "Vec::is_empty")]pub transport_layers: Vec<TransportLayerConfig>,#[serde(default = "default_connect_timeout_secs")]@@ -586,6 +590,8 @@ struct ConnectionConfigData {#[serde(default)]pub color: Option<String>,#[serde(default)]+ pub docs_notes_path: Option<String>,+ #[serde(default)]pub transport_layers: Vec<TransportLayerConfig>,#[serde(default = "default_connect_timeout_secs")]pub connect_timeout_secs: u64,@@ -675,6 +681,7 @@ impl From<ConnectionConfigData> for ConnectionConfig {attached_databases: data.attached_databases,init_script: data.init_script,color: data.color,+ docs_notes_path: data.docs_notes_path,transport_layers: data.transport_layers,connect_timeout_secs: data.connect_timeout_secs,query_timeout_secs: data.query_timeout_secs,@@ -2277,6 +2284,7 @@ mod tests {fn mysql_config(username: &str, password: &str, database: Option<&str>) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "id".to_string(),name: "name".to_string(),note: String::new(),@@ -2350,6 +2358,40 @@ mod tests {assert!(!legacy.read_only);}+ #[test]+ fn docs_notes_path_defaults_to_none_and_round_trips() {+ // A connection stored before this field existed must still load.+ let legacy: ConnectionConfig = serde_json::from_value(serde_json::json!({+ "id": "c1",+ "name": "local",+ "db_type": "postgres",+ "host": "127.0.0.1",+ "port": 5432,+ "username": "postgres",+ "password": "",+ "database": null+ }))+ .expect("legacy config must still parse");+ assert_eq!(legacy.docs_notes_path, None);++ // And a stored path must actually survive a load — this is the half+ // that fails if the field is added to ConnectionConfig only, without+ // ConnectionConfigData and the From impl.+ let with_path: ConnectionConfig = serde_json::from_value(serde_json::json!({+ "id": "c1",+ "name": "local",+ "db_type": "postgres",+ "host": "127.0.0.1",+ "port": 5432,+ "username": "postgres",+ "password": "",+ "database": null,+ "docs_notes_path": "docs/dbx-docs.json"+ }))+ .expect("config with a notes path must parse");+ assert_eq!(with_path.docs_notes_path.as_deref(), Some("docs/dbx-docs.json"));+ }+#[test]fn connection_note_is_optional_and_round_trips_when_present() {let config = mysql_config("root", "secret", Some("app"));diff --git a/crates/dbx-core/src/mq/config.rs b/crates/dbx-core/src/mq/config.rsindex 49e14cccbe..3fb2afb6e6 100644--- a/crates/dbx-core/src/mq/config.rs+++ b/crates/dbx-core/src/mq/config.rs@@ -156,6 +156,7 @@ mod tests {fn connection_with_external(value: serde_json::Value) -> ConnectionConfig {let mut cfg = ConnectionConfig {+ docs_notes_path: None,id: "c1".to_string(),name: "mq".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/mq/service.rs b/crates/dbx-core/src/mq/service.rsindex 897b998218..146ea56b9c 100644--- a/crates/dbx-core/src/mq/service.rs+++ b/crates/dbx-core/src/mq/service.rs@@ -866,6 +866,7 @@ mod tests {fn mq_connection(read_only: bool) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "readonly-mq".to_string(),name: "Read only MQ".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/nacos/config.rs b/crates/dbx-core/src/nacos/config.rsindex d4ac7b2f6d..5d36d956f6 100644--- a/crates/dbx-core/src/nacos/config.rs+++ b/crates/dbx-core/src/nacos/config.rs@@ -283,6 +283,7 @@ mod tests {fn connection_with_external(value: serde_json::Value) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "nacos-1".to_string(),name: "Nacos".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/nacos/service.rs b/crates/dbx-core/src/nacos/service.rsindex 47b6671eb2..5846d36579 100644--- a/crates/dbx-core/src/nacos/service.rs+++ b/crates/dbx-core/src/nacos/service.rs@@ -353,6 +353,7 @@ mod tests {let storage = crate::storage::Storage::open(&dir.join("storage.db")).await.unwrap();let state = AppState::new(storage);let mut cfg = crate::models::connection::ConnectionConfig {+ docs_notes_path: None,id: "nacos-1".to_string(),name: "Nacos".to_string(),note: String::new(),@@ -425,6 +426,7 @@ mod tests {let storage = crate::storage::Storage::open(&dir.join("storage.db")).await.unwrap();let state = AppState::new(storage);let cfg = crate::models::connection::ConnectionConfig {+ docs_notes_path: None,id: "nacos-rollback".to_string(),name: "Nacos".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/production_safety.rs b/crates/dbx-core/src/production_safety.rsindex acb8b50361..3157e21d07 100644--- a/crates/dbx-core/src/production_safety.rs+++ b/crates/dbx-core/src/production_safety.rs@@ -638,6 +638,7 @@ mod tests {fn config() -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "conn".to_string(),name: "test".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex d87e5c526c..6b63641b15 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -4478,6 +4478,7 @@ for line in sys.stdin:fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "conn-1".to_string(),name: "Connection".to_string(),note: String::new(),@@ -5806,6 +5807,7 @@ for line in sys.stdin:#[test]fn external_driver_query_params_include_database_and_schema_context() {let config = ConnectionConfig {+ docs_notes_path: None,id: "jdbc-1".to_string(),name: "JDBC".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rsindex 2aa0f9c71f..05f158226e 100644--- a/crates/dbx-core/src/schema.rs+++ b/crates/dbx-core/src/schema.rs@@ -2690,6 +2690,7 @@ mod tests {fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "test".to_string(),name: "test".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rsindex 51106e5963..27a6bdbe8a 100644--- a/crates/dbx-core/src/storage.rs+++ b/crates/dbx-core/src/storage.rs@@ -4140,6 +4140,7 @@ mod tests {fn mq_connection(id: &str, token: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: "Pulsar".to_string(),note: String::new(),@@ -4204,6 +4205,7 @@ mod tests {fn nacos_connection(id: &str, password: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: "Nacos".to_string(),note: String::new(),diff --git a/crates/dbx-core/src/table_structure_sql.rs b/crates/dbx-core/src/table_structure_sql.rsindex 661bc2bea7..63f78005d9 100644--- a/crates/dbx-core/src/table_structure_sql.rs+++ b/crates/dbx-core/src/table_structure_sql.rs@@ -36,3 +36,39 @@ pub fn build_table_structure_change_sql(options: TableStructureSqlOptions) -> Tastatements.extend(build_table_comment_sql(&options, &mut warnings));TableStructureSqlResult { statements, warnings }}++/// Whether this engine's structure editor can generate `COMMENT ON`/inline+/// comment DDL for tables and columns — a DDL-generation capability, not an+/// introspection one. The documentation collector uses it as a heuristic for+/// "can this engine report comments at all", but the two questions can+/// diverge: IRIS supports `%DESCRIPTION` while *defining* a table or column,+/// but DBX's editor cannot ALTER an existing one, so this returns `false`+/// for IRIS even though IRIS still reports descriptions on introspection.+/// Callers using this as an introspection signal must corroborate it against+/// what was actually collected rather than trust the flag alone.+pub(crate) fn supports_comments(database_type: crate::models::connection::DatabaseType) -> bool {+ dialect::capabilities_for(Some(database_type)).comment+}++/// Whether this engine's structure editor can generate foreign key DDL — a+/// DDL-generation capability, not an introspection one, used here as a+/// heuristic for "does this engine report foreign key metadata at all".+/// Engines like ClickHouse and Doris genuinely report none, so their ER+/// diagrams have no edges by necessity rather than by accident, but a+/// mismatch analogous to the IRIS comment case is possible for any future+/// engine where DDL support and introspection support diverge — callers+/// should corroborate against what was actually collected.+pub(crate) fn supports_foreign_keys(database_type: crate::models::connection::DatabaseType) -> bool {+ dialect::capabilities_for(Some(database_type)).foreign_key+}++/// Canonical display label for a database engine (e.g. `postgres`,+/// `sqlserver`, `mongodb`) — the same identifier already used throughout+/// this module's own warning prose. The documentation collector uses it for+/// `database_type` and its engine-capability warnings instead of the Rust+/// `Debug` spelling (`Postgres`, `SqlServer`, `MongoDb`), which is an+/// implementation detail, not something a consumer like dbdocs/dbdiagram+/// should key off.+pub(crate) fn database_type_label(database_type: crate::models::connection::DatabaseType) -> String {+ dialect::database_label(Some(database_type))+}diff --git a/crates/dbx-core/src/transfer.rs b/crates/dbx-core/src/transfer.rsindex eb9393387c..74f6f53c83 100644--- a/crates/dbx-core/src/transfer.rs+++ b/crates/dbx-core/src/transfer.rs@@ -9610,6 +9610,7 @@ SELECT 1 FROM dual"##[test]fn resolve_external_transfer_catalog_for_config_accepts_starrocks_driver_profile() {let config = crate::models::connection::ConnectionConfig {+ docs_notes_path: None,id: "sr".to_string(),name: "sr".to_string(),note: String::new(),diff --git a/crates/dbx-core/tests/database_export_prefetch.rs b/crates/dbx-core/tests/database_export_prefetch.rsindex 78bfa09f23..b1bc8085e5 100644--- a/crates/dbx-core/tests/database_export_prefetch.rs+++ b/crates/dbx-core/tests/database_export_prefetch.rs@@ -85,6 +85,7 @@ fn psql(container: &DockerPostgres, sql: &str) {fn postgres_test_config(id: &str, port: u16) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: id.to_string(),note: String::new(),diff --git a/crates/dbx-core/tests/dump_docs_fixture.rs b/crates/dbx-core/tests/dump_docs_fixture.rsnew file mode 100644index 0000000000..3ade979040--- /dev/null+++ b/crates/dbx-core/tests/dump_docs_fixture.rs@@ -0,0 +1,231 @@+// Gating and connection setup copied from live_postgres_docs_annotations.rs.+//+// This is not a test of correctness — it is a generator. Its job is to write+// `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` from a REAL Rust+// snapshot so that `fixtureConformance.spec.ts` can fail whenever the+// hand-maintained `types.ts` drifts from this crate's serialized shape.++use dbx_core::connection::AppState;+use dbx_core::docs::annotations::{+ AnnotationFile, ColumnAnnotation, GroupAnnotation, ProjectAnnotation, TableAnnotation,+};+use dbx_core::models::connection::{ConnectionConfig, DatabaseType};+use dbx_core::storage::Storage;+use std::collections::BTreeMap;++fn live_postgres_config(+ id: &str,+ host: &str,+ port: u16,+ user: &str,+ password: &str,+ database: &str,+) -> ConnectionConfig {+ ConnectionConfig {+ docs_notes_path: None,+ id: id.to_string(),+ name: id.to_string(),+ note: String::new(),+ db_type: DatabaseType::Postgres,+ driver_profile: None,+ driver_label: None,+ url_params: None,+ agent_java_options: Vec::new(),+ host: host.to_string(),+ port,+ username: user.to_string(),+ password: password.to_string(),+ database: Some(database.to_string()),+ visible_databases: None,+ visible_schemas: None,+ attached_databases: Vec::new(),+ init_script: None,+ color: None,+ transport_layers: Vec::new(),+ connect_timeout_secs: 10,+ query_timeout_secs: 30,+ idle_timeout_secs: 60,+ keepalive_interval_secs: 0,+ ssl: false,+ ca_cert_path: String::new(),+ client_cert_path: String::new(),+ client_key_path: String::new(),+ sysdba: false,+ oracle_connection_type: None,+ connection_string: None,+ redis_connection_mode: None,+ redis_sentinel_master: String::new(),+ redis_sentinel_nodes: String::new(),+ redis_sentinel_username: String::new(),+ redis_sentinel_password: String::new(),+ redis_sentinel_tls: false,+ redis_cluster_nodes: String::new(),+ redis_key_separator: dbx_core::models::connection::default_redis_key_separator(),+ redis_scan_page_size: None,+ redis_database_aliases: Default::default(),+ etcd_endpoints: String::new(),+ gbase_server: String::new(),+ informix_server: String::new(),+ external_config: None,+ jdbc_driver_class: None,+ jdbc_driver_paths: Vec::new(),+ one_time: false,+ read_only: false,+ is_production: false,+ production_databases: vec![],+ show_system_schemas: false,+ database_info: None,+ }+}++/// Which tables to keep in the committed fixture.+///+/// Keycloak's public schema has 90 tables; committing all of them with full+/// column/index/FK data would bloat the fixture for no gain. This is an+/// explicit allowlist rather than "the first N alphabetically" because the+/// conformance test needs a CONNECTED foreign-key subgraph — an alphabetical+/// slice can easily keep a table while dropping everything it references,+/// leaving `relationships` empty and `Relationship`/`FieldRef` unexercised.+///+/// The set is chosen for shape coverage: `realm` and `client` are wide+/// (53 and 26 columns), `protocol_mapper` has two foreign keys to DIFFERENT+/// tables, and `composite_role` has two to the SAME table.+const KEEP_TABLES: &[&str] = &[+ "realm",+ "client",+ "client_attributes",+ "client_scope",+ "client_scope_attributes",+ "protocol_mapper",+ "protocol_mapper_config",+ "user_entity",+ "credential",+ "federated_identity",+ "keycloak_role",+ "composite_role",+];++/// The table the fixture's annotations attach to. Must be in `KEEP_TABLES`.+const ANCHOR_TABLE: &str = "client";+const ANCHOR_COLUMN: &str = "client_id";++const TABLE_NOTE: &str = "Every registered OIDC/SAML client. Owned by the platform team.";+const COLUMN_NOTE: &str = "The public client identifier callers send at the token endpoint.";+const PROJECT_NOTE: &str = "# Keycloak\n\nFixture generated for the docs viewer conformance test.";+const GROUP_ID: &str = "client-registry";+const GROUP_NAME: &str = "Client Registry";+const ORPHAN_TABLE_KEY: &str = "public.no_such_table_xyz";++#[tokio::test]+#[ignore = "requires DBX_LIVE_POSTGRES_HOST/PORT/USER/PASSWORD/DATABASE pointing at a live db"]+async fn dump_keycloak_fixture() {+ let host = std::env::var("DBX_LIVE_POSTGRES_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());+ let port = std::env::var("DBX_LIVE_POSTGRES_PORT").ok().and_then(|value| value.parse().ok()).unwrap_or(5432);+ let user = std::env::var("DBX_LIVE_POSTGRES_USER").unwrap_or_else(|_| "postgres".to_string());+ let password = std::env::var("DBX_LIVE_POSTGRES_PASSWORD").unwrap_or_default();+ let database = std::env::var("DBX_LIVE_POSTGRES_DATABASE").unwrap_or_else(|_| "postgres".to_string());++ let suffix = uuid::Uuid::new_v4().simple().to_string();+ let connection_id = format!("dump-docs-fixture-{}", &suffix[..8]);+ let config = live_postgres_config(&connection_id, &host, port, &user, &password, &database);++ let dir = std::env::temp_dir().join(format!("dbx-dump-docs-fixture-{suffix}"));+ std::fs::create_dir_all(&dir).unwrap();+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ state.configs.write().await.insert(config.id.clone(), config.clone());++ let options = dbx_core::docs::CollectOptions {+ database: database.clone(),+ schemas: vec!["public".to_string()],+ tables: vec![],+ project_name: "Keycloak".to_string(),+ };++ let snapshot_result = dbx_core::docs::collect_snapshot(+ &state,+ &config,+ &options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+ )+ .await;++ let _ = std::fs::remove_dir_all(&dir);++ let mut snapshot = snapshot_result.expect("collect");+ assert!(!snapshot.tables.is_empty(), "expected the keycloak schema to have tables");++ // Every field the viewer must render: a table note (LOCAL source), a+ // column note, a group with a hue, and an annotation targeting a table+ // that does not exist (so an `orphanedNotes` warning appears).+ let mut tables = BTreeMap::new();+ tables.insert(+ format!("public.{ANCHOR_TABLE}"),+ TableAnnotation {+ group: Some(GROUP_ID.to_string()),+ note: Some(TABLE_NOTE.to_string()),+ columns: BTreeMap::from([(ANCHOR_COLUMN.to_string(), ColumnAnnotation { note: COLUMN_NOTE.to_string() })]),+ },+ );+ tables.insert(+ ORPHAN_TABLE_KEY.to_string(),+ TableAnnotation {+ note: Some("Orphaned annotation — the table it references does not exist.".to_string()),+ ..Default::default()+ },+ );++ let annotations = AnnotationFile {+ format_version: 1,+ project: Some(ProjectAnnotation { name: Some("Keycloak".to_string()), note: Some(PROJECT_NOTE.to_string()) }),+ groups: vec![GroupAnnotation {+ id: GROUP_ID.to_string(),+ name: GROUP_NAME.to_string(),+ hue: 210,+ note: Some("Tables describing registered clients and their protocol mappers.".to_string()),+ }],+ tables,+ };++ dbx_core::docs::annotations::apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let anchor = snapshot.tables.iter().find(|table| table.name == ANCHOR_TABLE).expect("anchor table collected");+ assert_eq!(anchor.note_source, dbx_core::docs::NoteSource::Local, "annotation setup must have taken effect");+ assert!(+ snapshot+ .warnings+ .iter()+ .any(|warning| matches!(warning, dbx_core::docs::SnapshotWarning::OrphanedNotes { .. })),+ "annotation setup must produce an orphanedNotes warning"+ );++ // Trim to the allowlist, then rebuild relationships over the surviving+ // set. Rebuilding matters: the first pass resolved foreign keys against+ // all 90 tables, so edges pointing at dropped tables would otherwise+ // survive as relationships to nothing.+ snapshot.tables.retain(|table| KEEP_TABLES.contains(&table.name.as_str()));+ assert_eq!(+ snapshot.tables.len(),+ KEEP_TABLES.len(),+ "every allowlisted table must exist in the schema; got {:?}",+ snapshot.tables.iter().map(|table| &table.name).collect::<Vec<_>>()+ );+ snapshot.relationships = dbx_core::docs::build_relationships(&snapshot.tables);+ assert!(!snapshot.relationships.is_empty(), "the allowlist must form a connected foreign-key subgraph");++ let json = serde_json::to_string_pretty(&snapshot).expect("serialize snapshot");++ let out_path = std::env::var("DBX_FIXTURE_OUT").map(std::path::PathBuf::from).unwrap_or_else(|_| {+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../apps/desktop/src/docs/fixtures/keycloak.snapshot.json")+ });++ if let Some(parent) = out_path.parent() {+ std::fs::create_dir_all(parent).expect("create fixture directory");+ }+ std::fs::write(&out_path, &json).expect("write fixture file");++ println!("Wrote {} bytes to {}", json.len(), out_path.display());+ println!("Tables kept: {}", snapshot.tables.len());+}diff --git a/crates/dbx-core/tests/live_postgres_docs_annotations.rs b/crates/dbx-core/tests/live_postgres_docs_annotations.rsnew file mode 100644index 0000000000..b73dc4e2b1--- /dev/null+++ b/crates/dbx-core/tests/live_postgres_docs_annotations.rs@@ -0,0 +1,185 @@+// Gating and connection setup copied from live_postgres_docs_snapshot.rs.+//+// This is the end-to-end proof for Part 2: a hand-authored notes file, read+// off disk, merged into a snapshot collected from a REAL database, and+// showing up verbatim in the generated DBML.++use dbx_core::connection::AppState;+use dbx_core::docs::{NoteSource, SnapshotWarning};+use dbx_core::models::connection::{ConnectionConfig, DatabaseType};+use dbx_core::storage::Storage;++fn live_postgres_config(+ id: &str,+ host: &str,+ port: u16,+ user: &str,+ password: &str,+ database: &str,+) -> ConnectionConfig {+ ConnectionConfig {+ docs_notes_path: None,+ id: id.to_string(),+ name: id.to_string(),+ note: String::new(),+ db_type: DatabaseType::Postgres,+ driver_profile: None,+ driver_label: None,+ url_params: None,+ agent_java_options: Vec::new(),+ host: host.to_string(),+ port,+ username: user.to_string(),+ password: password.to_string(),+ database: Some(database.to_string()),+ visible_databases: None,+ visible_schemas: None,+ attached_databases: Vec::new(),+ init_script: None,+ color: None,+ transport_layers: Vec::new(),+ connect_timeout_secs: 10,+ query_timeout_secs: 30,+ idle_timeout_secs: 60,+ keepalive_interval_secs: 0,+ ssl: false,+ ca_cert_path: String::new(),+ client_cert_path: String::new(),+ client_key_path: String::new(),+ sysdba: false,+ oracle_connection_type: None,+ connection_string: None,+ redis_connection_mode: None,+ redis_sentinel_master: String::new(),+ redis_sentinel_nodes: String::new(),+ redis_sentinel_username: String::new(),+ redis_sentinel_password: String::new(),+ redis_sentinel_tls: false,+ redis_cluster_nodes: String::new(),+ redis_key_separator: dbx_core::models::connection::default_redis_key_separator(),+ redis_scan_page_size: None,+ redis_database_aliases: Default::default(),+ etcd_endpoints: String::new(),+ gbase_server: String::new(),+ informix_server: String::new(),+ external_config: None,+ jdbc_driver_class: None,+ jdbc_driver_paths: Vec::new(),+ one_time: false,+ read_only: false,+ is_production: false,+ production_databases: vec![],+ show_system_schemas: false,+ database_info: None,+ }+}++#[tokio::test]+#[ignore = "requires DBX_LIVE_POSTGRES_HOST/PORT/USER/PASSWORD/DATABASE pointing at a live db"]+async fn annotations_reach_the_generated_dbml() {+ let host = std::env::var("DBX_LIVE_POSTGRES_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());+ let port = std::env::var("DBX_LIVE_POSTGRES_PORT").ok().and_then(|value| value.parse().ok()).unwrap_or(5432);+ let user = std::env::var("DBX_LIVE_POSTGRES_USER").unwrap_or_else(|_| "postgres".to_string());+ let password = std::env::var("DBX_LIVE_POSTGRES_PASSWORD").unwrap_or_default();+ let database = std::env::var("DBX_LIVE_POSTGRES_DATABASE").unwrap_or_else(|_| "postgres".to_string());++ let suffix = uuid::Uuid::new_v4().simple().to_string();+ let connection_id = format!("live-postgres-docs-annotations-{}", &suffix[..8]);+ let config = live_postgres_config(&connection_id, &host, port, &user, &password, &database);++ const TABLE_NOTE: &str = "Every tenant's client roster. Owned by the billing team.";+ const COLUMN_NOTE: &str = "Stable natural key used by the legacy billing export.";+ const PROJECT_NOTE: &str = "# Keycloak\n\nGenerated for live annotation verification.";+ const GROUP_NAME: &str = "Core Accounts";++ let notes_json = format!(+ r#"{{+ "formatVersion": 1,+ "project": {{ "name": "Keycloak", "note": {project_note:?} }},+ "groups": [+ {{ "id": "core-accounts", "name": {group_name:?}, "hue": 210, "note": "Tables owned by the accounts team." }}+ ],+ "tables": {{+ "public.clients": {{+ "group": "core-accounts",+ "note": {table_note:?},+ "columns": {{ "name": {{ "note": {column_note:?} }} }}+ }},+ "public.no_such_table_xyz": {{+ "note": "Orphaned annotation — the table it references does not exist."+ }}+ }}+}}"#,+ project_note = PROJECT_NOTE,+ group_name = GROUP_NAME,+ table_note = TABLE_NOTE,+ column_note = COLUMN_NOTE,+ );++ let notes_path = std::env::temp_dir().join(format!("dbx-live-docs-notes-{}.json", uuid::Uuid::new_v4()));+ std::fs::write(¬es_path, ¬es_json).expect("write temp notes file");++ let dir = std::env::temp_dir().join(format!("dbx-live-postgres-docs-annotations-{suffix}"));+ std::fs::create_dir_all(&dir).unwrap();+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ state.configs.write().await.insert(config.id.clone(), config.clone());++ let options = dbx_core::docs::CollectOptions {+ database: database.clone(),+ schemas: vec!["public".to_string()],+ tables: vec![],+ project_name: "live-test".to_string(),+ };++ let snapshot_result = dbx_core::docs::collect_snapshot(+ &state,+ &config,+ &options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+ )+ .await;++ let annotations_result = dbx_core::docs::annotations::load_annotations(¬es_path);++ // Clean up temp resources before any assertion that can panic.+ let _ = std::fs::remove_file(¬es_path);+ let _ = std::fs::remove_dir_all(&dir);++ let mut snapshot = snapshot_result.expect("collect");+ let annotations = annotations_result.expect("load annotations").expect("annotations file present");++ dbx_core::docs::annotations::apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let clients = snapshot.tables.iter().find(|table| table.name == "clients").expect("clients table collected");++ assert_eq!(clients.note.as_deref(), Some(TABLE_NOTE), "table note must be the annotated text");+ assert_eq!(clients.note_source, NoteSource::Local, "annotated note must be sourced as Local");++ let column_note =+ clients.column_notes.get("name").expect("column note for `name` present, keyed by real column name");+ assert_eq!(column_note.note, COLUMN_NOTE);+ assert_eq!(column_note.source, NoteSource::Local);++ assert_eq!(snapshot.groups.len(), 1, "expected the one group from the notes file");+ let group = &snapshot.groups[0];+ assert_eq!(group.name, GROUP_NAME);+ assert_eq!(clients.group_id.as_deref(), Some(group.id.as_str()), "clients.group_id must point at the group");++ let orphan_count = snapshot+ .warnings+ .iter()+ .find_map(|warning| match warning {+ SnapshotWarning::OrphanedNotes { count } => Some(*count),+ _ => None,+ })+ .expect("an OrphanedNotes warning must be present for the no_such_table_xyz annotation");+ assert_eq!(orphan_count, 1, "exactly one annotation targets a nonexistent table");++ let dbml = dbx_core::docs::to_dbml(&snapshot);+ println!("{}", dbml.text);++ assert!(dbml.text.contains(TABLE_NOTE), "generated DBML must contain the table note text:\n{}", dbml.text);+ assert!(dbml.text.contains(GROUP_NAME), "generated DBML must contain the group name:\n{}", dbml.text);+}diff --git a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs b/crates/dbx-core/tests/live_postgres_docs_snapshot.rsnew file mode 100644index 0000000000..8ad75a389c--- /dev/null+++ b/crates/dbx-core/tests/live_postgres_docs_snapshot.rs@@ -0,0 +1,134 @@+// Gating and connection setup copied from live_postgres_query_result_export.rs.++use dbx_core::connection::AppState;+use dbx_core::models::connection::{ConnectionConfig, DatabaseType};+use dbx_core::storage::Storage;++fn live_postgres_config(+ id: &str,+ host: &str,+ port: u16,+ user: &str,+ password: &str,+ database: &str,+) -> ConnectionConfig {+ ConnectionConfig {+ docs_notes_path: None,+ id: id.to_string(),+ name: id.to_string(),+ note: String::new(),+ db_type: DatabaseType::Postgres,+ driver_profile: None,+ driver_label: None,+ url_params: None,+ agent_java_options: Vec::new(),+ host: host.to_string(),+ port,+ username: user.to_string(),+ password: password.to_string(),+ database: Some(database.to_string()),+ visible_databases: None,+ visible_schemas: None,+ attached_databases: Vec::new(),+ init_script: None,+ color: None,+ transport_layers: Vec::new(),+ connect_timeout_secs: 10,+ query_timeout_secs: 30,+ idle_timeout_secs: 60,+ keepalive_interval_secs: 0,+ ssl: false,+ ca_cert_path: String::new(),+ client_cert_path: String::new(),+ client_key_path: String::new(),+ sysdba: false,+ oracle_connection_type: None,+ connection_string: None,+ redis_connection_mode: None,+ redis_sentinel_master: String::new(),+ redis_sentinel_nodes: String::new(),+ redis_sentinel_username: String::new(),+ redis_sentinel_password: String::new(),+ redis_sentinel_tls: false,+ redis_cluster_nodes: String::new(),+ redis_key_separator: dbx_core::models::connection::default_redis_key_separator(),+ redis_scan_page_size: None,+ redis_database_aliases: Default::default(),+ etcd_endpoints: String::new(),+ gbase_server: String::new(),+ informix_server: String::new(),+ external_config: None,+ jdbc_driver_class: None,+ jdbc_driver_paths: Vec::new(),+ one_time: false,+ read_only: false,+ is_production: false,+ production_databases: vec![],+ show_system_schemas: false,+ database_info: None,+ }+}++#[tokio::test]+#[ignore = "requires DBX_LIVE_POSTGRES_HOST/PORT/USER/PASSWORD/DATABASE pointing at a live db"]+async fn collects_a_snapshot_and_serializes_valid_dbml() {+ let host = std::env::var("DBX_LIVE_POSTGRES_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());+ let port = std::env::var("DBX_LIVE_POSTGRES_PORT").ok().and_then(|value| value.parse().ok()).unwrap_or(5432);+ let user = std::env::var("DBX_LIVE_POSTGRES_USER").unwrap_or_else(|_| "postgres".to_string());+ let password = std::env::var("DBX_LIVE_POSTGRES_PASSWORD").unwrap_or_default();+ let database = std::env::var("DBX_LIVE_POSTGRES_DATABASE").unwrap_or_else(|_| "postgres".to_string());++ let suffix = uuid::Uuid::new_v4().simple().to_string();+ let connection_id = format!("live-postgres-docs-snapshot-{}", &suffix[..8]);+ let config = live_postgres_config(&connection_id, &host, port, &user, &password, &database);++ let dir = std::env::temp_dir().join(format!("dbx-live-postgres-docs-snapshot-{suffix}"));+ std::fs::create_dir_all(&dir).unwrap();+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ state.configs.write().await.insert(config.id.clone(), config.clone());++ let options = dbx_core::docs::CollectOptions {+ database: database.clone(),+ schemas: vec!["public".to_string()],+ tables: vec![],+ project_name: "live-test".to_string(),+ };++ let snapshot = dbx_core::docs::collect_snapshot(+ &state,+ &config,+ &options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+ )+ .await;++ let _ = std::fs::remove_dir_all(&dir);++ let snapshot = snapshot.expect("collect");++ assert_eq!(snapshot.format_version, 1);+ assert!(!snapshot.tables.is_empty(), "expected at least one table");++ let dbml = dbx_core::docs::to_dbml(&snapshot);+ println!("{}", dbml.text);++ assert!(dbml.text.starts_with("Project "), "got:\n{}", dbml.text);++ for table in &snapshot.tables {+ assert!(+ dbml.text.contains(&format!("Table {}", table.name))+ || dbml.text.contains(&format!("Table {}.{}", table.schema.clone().unwrap_or_default(), table.name)),+ "table {} missing from DBML",+ table.name+ );+ }++ // Braces must balance, or the DBML is unparseable.+ let opens = dbml.text.matches('{').count();+ let closes = dbml.text.matches('}').count();+ assert_eq!(opens, closes, "unbalanced braces in:\n{}", dbml.text);++ assert!(dbml.text.ends_with('\n'), "DBML document should end with a newline:\n{}", dbml.text);+}diff --git a/crates/dbx-core/tests/live_postgres_query_result_export.rs b/crates/dbx-core/tests/live_postgres_query_result_export.rsindex ce46c71d0a..fe5a406ded 100644--- a/crates/dbx-core/tests/live_postgres_query_result_export.rs+++ b/crates/dbx-core/tests/live_postgres_query_result_export.rs@@ -18,6 +18,7 @@ fn live_postgres_config(database: &str,) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: id.to_string(),note: String::new(),diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rsindex 0c622211b8..1b2cbab0e9 100644--- a/crates/dbx-core/tests/live_postgres_transfer.rs+++ b/crates/dbx-core/tests/live_postgres_transfer.rs@@ -10,6 +10,7 @@ use serde_json::json;fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: id.to_string(),note: String::new(),diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rsindex ec45101de9..8c1f2fc43e 100644--- a/crates/dbx-core/tests/live_sqlserver_completion.rs+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs@@ -19,6 +19,7 @@ use tokio_util::sync::CancellationToken;fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connection::ConnectionConfig {dbx_core::models::connection::ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: id.to_string(),note: String::new(),diff --git a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs b/crates/dbx-core/tests/live_sqlserver_query_result_export.rsindex 9a447f2a73..919e0e1046 100644--- a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs+++ b/crates/dbx-core/tests/live_sqlserver_query_result_export.rs@@ -8,6 +8,7 @@ use std::time::{Duration, Instant};fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connection::ConnectionConfig {dbx_core::models::connection::ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: id.to_string(),note: String::new(),diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex 75c850a6db..7f179d9c48 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -74,6 +74,19 @@ fn effective_mcp_policy_with_legacy_allow_writes(policy}+/// Wire-level options for a documentation snapshot. Mirrors+/// `dbx_core::docs::CollectOptions` minus the fields the backend fills in.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsSnapshotOptions {+ #[serde(default)]+ pub schemas: Vec<String>,+ #[serde(default)]+ pub tables: Vec<String>,+ #[serde(default)]+ pub project_name: Option<String>,+}+#[async_trait]pub trait DbxBackend: Send + Sync {async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String>;@@ -152,6 +165,15 @@ pub trait DbxBackend: Send + Sync {let _ = (path, body);Err("DBX is not running. Please start DBX first.".to_string())}+ async fn collect_docs_snapshot(+ &self,+ connection: &ConnectionConfig,+ database: &str,+ options: DocsSnapshotOptions,+ ) -> Result<dbx_core::docs::SchemaSnapshot, String> {+ let _ = (connection, database, options);+ Err("Documentation snapshots are not supported by this backend.".to_string())+ }}pub struct LocalBackend {@@ -438,6 +460,28 @@ impl DbxBackend for LocalBackend {dbx_core::schema::get_columns_core(&self.state, &connection.id, database, schema, table).await}+ async fn collect_docs_snapshot(+ &self,+ connection: &ConnectionConfig,+ database: &str,+ options: DocsSnapshotOptions,+ ) -> Result<dbx_core::docs::SchemaSnapshot, String> {+ let collect_options = dbx_core::docs::CollectOptions {+ database: database.to_string(),+ schemas: options.schemas,+ tables: options.tables,+ project_name: options.project_name.unwrap_or_else(|| connection.name.clone()),+ };+ dbx_core::docs::collect_snapshot(+ &self.state,+ connection,+ &collect_options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+ )+ .await+ }+async fn execute_redis_command(&self,connection: &ConnectionConfig,@@ -743,6 +787,30 @@ impl DbxBackend for WebBackend {.map_err(|error| format!("Invalid column list response: {error}"))}+ async fn collect_docs_snapshot(+ &self,+ connection: &ConnectionConfig,+ database: &str,+ options: DocsSnapshotOptions,+ ) -> Result<dbx_core::docs::SchemaSnapshot, String> {+ self.ensure_connected(connection).await?;+ self.request(+ reqwest::Method::POST,+ "/api/docs/snapshot",+ Some(json!({+ "connectionId": connection.id,+ "database": database,+ "schemas": options.schemas,+ "tables": options.tables,+ "projectName": options.project_name.clone().unwrap_or_else(|| connection.name.clone()),+ })),+ )+ .await?+ .json()+ .await+ .map_err(|error| format!("Invalid docs snapshot response: {error}"))+ }+async fn execute_redis_command(&self,connection: &ConnectionConfig,@@ -1447,4 +1515,55 @@ mod tests {assert_eq!(local_plugin_dir(&explicit, data_dir), PathBuf::from("D:/DBX/plugins-custom"));assert_eq!(local_plugin_dir(&legacy, data_dir), PathBuf::from("D:/DBX/drivers/plugins"));}++ struct StubBackend;++ #[async_trait]+ impl DbxBackend for StubBackend {+ async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {+ Err("unused".to_string())+ }+ async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {+ Ok(vec![])+ }+ async fn execute_agent_tool(+ &self,+ _connection: &ConnectionConfig,+ _database: &str,+ _tool_name: &str,+ _arguments: Value,+ _permissions: AgentSqlPermissions,+ ) -> ToolResult {+ unimplemented!("not exercised by this test")+ }+ async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {+ Ok(config)+ }+ async fn remove_connection_for_mcp(&self, _connection_id: &str) -> Result<bool, String> {+ Ok(false)+ }+ }++ #[tokio::test]+ async fn collect_docs_snapshot_defaults_to_unsupported() {+ let backend = StubBackend;+ let connection = new_connection_config(+ "c1".to_string(),+ "local".to_string(),+ DatabaseType::Postgres,+ "127.0.0.1".to_string(),+ 5432,+ "user".to_string(),+ "password".to_string(),+ None,+ false,+ None,+ )+ .unwrap();++ let result = backend.collect_docs_snapshot(&connection, "shop", DocsSnapshotOptions::default()).await;++ assert!(result.is_err());+ assert!(result.unwrap_err().contains("not supported"));+ }}diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 1ce97bef04..f133cb97e1 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -377,6 +377,10 @@ async fn main() {.route("/schema/extensions", get(routes::schema::list_extensions)).route("/schema/available-extensions", get(routes::schema::list_available_extensions)).route("/schema/ddl", get(routes::schema::get_ddl))+ .route("/docs/snapshot", post(routes::docs::collect_snapshot))+ .route("/docs/annotations/load", post(routes::docs::load_annotations))+ .route("/docs/annotations/apply", post(routes::docs::apply_annotations))+ .route("/docs/annotations/save", post(routes::docs::save_annotations)).route("/dialect/data-types", get(routes::dialect::list_data_types)).route("/schema-diff/prepare", post(routes::schema_diff::prepare_schema_diff)).route("/schema-diff/generate-sync-sql", post(routes::schema_diff::generate_schema_sync_sql))diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rsindex 2abcbfc965..fcd385a750 100644--- a/crates/dbx-web/src/routes/connection.rs+++ b/crates/dbx-web/src/routes/connection.rs@@ -505,6 +505,7 @@ mod tests {fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: "SQLite".to_string(),note: String::new(),diff --git a/crates/dbx-web/src/routes/docs.rs b/crates/dbx-web/src/routes/docs.rsnew file mode 100644index 0000000000..071e189577--- /dev/null+++ b/crates/dbx-web/src/routes/docs.rs@@ -0,0 +1,114 @@+use std::sync::atomic::AtomicBool;+use std::sync::Arc;++use axum::extract::State;+use axum::Json;+use dbx_core::docs::{CollectOptions, SchemaSnapshot};+use dbx_core::models::connection::ConnectionConfig;+use serde::Deserialize;++use crate::error::AppError;+use crate::state::WebState;++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsSnapshotRequest {+ pub connection_id: String,+ pub database: String,+ #[serde(default)]+ pub schemas: Vec<String>,+ #[serde(default)]+ pub tables: Vec<String>,+ #[serde(default)]+ pub project_name: Option<String>,+}++async fn load_connection(state: &Arc<WebState>, connection_id: &str) -> Result<ConnectionConfig, AppError> {+ state+ .app+ .storage+ .load_connections()+ .await+ .map_err(AppError::from)?+ .into_iter()+ .find(|config| config.id == connection_id)+ .ok_or_else(|| AppError::from(format!("Connection with id '{connection_id}' not found")))+}++pub async fn collect_snapshot(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsSnapshotRequest>,+) -> Result<Json<SchemaSnapshot>, AppError> {+ let connection = load_connection(&state, &request.connection_id).await?;++ let options = CollectOptions {+ database: request.database.clone(),+ schemas: request.schemas.clone(),+ tables: request.tables.clone(),+ project_name: request.project_name.clone().unwrap_or_else(|| connection.name.clone()),+ };++ let snapshot =+ dbx_core::docs::collect_snapshot(&state.app, &connection, &options, &|_progress| {}, &AtomicBool::new(false))+ .await+ .map_err(AppError::from)?;++ Ok(Json(snapshot))+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsAnnotationsRequest {+ pub connection_id: String,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsApplyRequest {+ pub connection_id: String,+ pub snapshot: SchemaSnapshot,+ pub annotations: dbx_core::docs::annotations::AnnotationFile,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsSaveRequest {+ pub connection_id: String,+ pub annotations: dbx_core::docs::annotations::AnnotationFile,+}++/// `WebState` already carries the data directory (`pub data_dir: PathBuf`), so+/// this needs no lookup and no new dependency — dbx-web does NOT depend on+/// dbx-mcp.+fn notes_path_for(state: &Arc<WebState>, config: &ConnectionConfig) -> std::path::PathBuf {+ dbx_core::docs::annotations::resolve_notes_path(&config.id, config.docs_notes_path.as_deref(), &state.data_dir)+}++pub async fn load_annotations(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsAnnotationsRequest>,+) -> Result<Json<Option<dbx_core::docs::annotations::AnnotationFile>>, AppError> {+ let config = load_connection(&state, &request.connection_id).await?;+ let path = notes_path_for(&state, &config);+ Ok(Json(dbx_core::docs::annotations::load_annotations(&path).map_err(AppError::from)?))+}++pub async fn apply_annotations(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsApplyRequest>,+) -> Result<Json<SchemaSnapshot>, AppError> {+ let config = load_connection(&state, &request.connection_id).await?;+ let mut applied = request.snapshot;+ dbx_core::docs::annotations::apply_annotations(&mut applied, &request.annotations, config.db_type);+ Ok(Json(applied))+}++pub async fn save_annotations(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsSaveRequest>,+) -> Result<Json<()>, AppError> {+ let config = load_connection(&state, &request.connection_id).await?;+ let path = notes_path_for(&state, &config);+ dbx_core::docs::annotations::save_annotations(&path, &request.annotations).map_err(AppError::from)?;+ Ok(Json(()))+}diff --git a/crates/dbx-web/src/routes/mod.rs b/crates/dbx-web/src/routes/mod.rsindex 132f822a2a..8a715cf098 100644--- a/crates/dbx-web/src/routes/mod.rs+++ b/crates/dbx-web/src/routes/mod.rs@@ -6,6 +6,7 @@ pub mod connection;pub mod data_compare;pub mod database_export;pub mod dialect;+pub mod docs;pub mod document_store;pub mod etcd;pub mod hbase;diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rsindex a89e5cce60..de04e267e2 100644--- a/crates/dbx-web/src/routes/transfer.rs+++ b/crates/dbx-web/src/routes/transfer.rs@@ -527,6 +527,7 @@ mod tests {fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: id.to_string(),name: "SQLite".to_string(),note: String::new(),diff --git a/docs/content/docs/database-docs.cn.mdx b/docs/content/docs/database-docs.cn.mdxnew file mode 100644index 0000000000..77dc7d9448--- /dev/null+++ b/docs/content/docs/database-docs.cn.mdx@@ -0,0 +1,108 @@+---+title: 数据库文档+description: 以文档方式浏览 Schema,为表和字段编写笔记并按颜色分组,导出 DBML 用于 dbdiagram.io 或 CI 中的结构漂移检查。+---++数据库文档把线上 Schema 变成可读的资料。DBX 会把表、字段、索引和关系收集成一份快照,与你自己编写的笔记合并后渲染成可浏览的参考文档。同一份快照还能序列化为 DBML,因此图形工具和 CI 检查读到的内容与查看器中显示的完全一致。++笔记保存在一个普通的 JSON 文件中,你可以把它和 migration 放在一起提交,让 Schema 文档能够在 Pull Request 中被评审。++## 打开方式++在[对象浏览器](/cn/docs/object-browser)中右键点击一张表,选择 **Documentation**。查看器会基于当前连接、数据库和 Schema 打开。++侧边栏可在 **Schemas** 和 **Table Groups** 之间切换。搜索会同时覆盖表、字段和分组。每个表页面列出字段、索引、**References** 与 **Referenced by**,因此关系可以双向查看。++## 笔记与分组++| 可标注的内容 | 位置 |+| --- | --- |+| 项目笔记 | 文档首页 |+| 表笔记 | 表页面标题处 |+| 字段笔记 | 表格中的字段行 |+| 表分组及其颜色 | 表页面的分组选择器 |++笔记支持 Markdown,并在索引中内联渲染。每次编辑都会自动保存,标题栏会依次显示 **Saving…** 和 **Saved**。写入失败会被明确提示而不是被吞掉,你的文字会保留下来,下一次编辑时重试。++分组保存的是**色相(hue)**,而不是固定颜色。明度和彩度由当前主题决定,因此同一个分组在浅色和深色模式下都保持清晰可读;导出 DBML 时,这个色相会转换成 `[color: #rrggbb]`。++## 本地笔记与数据库注释++如果某个字段既有数据库的 `COMMENT ON`,又有你在 DBX 中写的笔记,页面会显示你的笔记并标记 **LOCAL**,同时在下方保留原有的数据库注释。数据库中的内容不会被覆盖——DBX 从不为文档执行 DDL,原始注释始终可以找回。++## 笔记的存储位置++默认情况下,每个连接在 DBX 数据目录中拥有各自的笔记文件,因此该功能开箱即用。++你也可以在连接的**高级**设置中填写 **Notes file**(对应配置项 `docs_notes_path`),把它指向仓库中的文件。笔记文件的结构如下:++```json+{+ "formatVersion": 1,+ "project": { "name": "Billing", "note": "# Billing\n\n每个租户一个 schema。" },+ "groups": [{ "id": "core", "name": "Core", "hue": 210 }],+ "tables": {+ "public.orders": {+ "group": "core",+ "note": "每次结算对应一行。",+ "columns": { "status": { "note": "生命周期状态。" } }+ }+ }+}+```++键名为 `schema.table` 和 `schema.table.column`,并按各数据库对标识符大小写的处理方式折叠。写入是原子的——先写入同目录下的临时文件再重命名——因此保存被中断也不会在原有文字的位置留下半个文件。++<Callout type="warn">笔记文件不存在是正常情况,会以空笔记开始;但文件格式损坏会直接报错,这是有意为之:继续执行会渲染出看似完整的文档,同时悄悄丢弃已写好的内容。</Callout>++## 警告提示++文档只会显式降级,不会静默降级。出现以下情况时,查看器会显示提示条:++| 情况 | 含义 |+| --- | --- |+| 某张表无法生成文档 | 单张表的元数据读取失败,Schema 的其余部分仍然可用。 |+| 没有可用的关系 | 该数据库不提供外键元数据,因此无法推导关系连线。 |+| 无法获取数据库注释 | 该数据库不支持注释,所有描述都来自你自己的笔记。 |+| 部分笔记不再匹配任何对象 | 笔记指向的表或字段已不存在。内容不会被删除。 |+| 无法在 DBML 中表示 | 某个结构在 DBX 中有文档,但无法写入导出的 DBML。 |++## DBML 导出++```bash+dbx dbml <connection> [--out path] [--notes path] [--schema name] [--database name] [--tables a,b]+```++不指定 `--out` 时,DBML 会输出到 stdout,便于管道处理。只有在 `--notes` 明确指定文件时才会合并笔记和分组;该参数是显式的,因此路径写错会直接失败,而不是悄悄生成一份没有笔记的结果。++输出包含 `Table`、带推导基数的 `Ref`、`Enum` 和 `TableGroup` 块,可直接粘贴到 [dbdiagram.io](https://dbdiagram.io)。++把结果提交到仓库,就能让 CI 在未经评审的结构漂移时失败:++```yaml+- run: dbx dbml prod --notes docs/dbx-docs.json --out docs/schema.dbml+- run: git diff --exit-code docs/schema.dbml+```++## 支持范围与边界++- 仅支持关系型数据库。文档型数据库和键值存储没有对应的 DBML 表达方式,不在支持范围内。+- 覆盖表、字段、索引、关系和枚举;不包含触发器、存储过程、函数、序列和权限。+- DBML 导出是单向的。`.dbml` 文件只是输出,不会作为数据来源——DBX 不会导入它。+- 缺少外键元数据的数据库会生成没有关系连线的文档,并以警告说明,而不是给出一个空白页面。+- 不记录 Schema 历史,也没有按表的“最近更新”。快照带有版本标记,方便后续增量添加该能力。++<Cards>+ <Card title="对象浏览器" href="/cn/docs/object-browser">+ 文档的入口,也是查看对象源码的地方。+ </Card>+ <Card title="Schema 浏览器" href="/cn/docs/schema-browser">+ 直接查看字段、外键和注释。+ </Card>+ <Card title="字段血缘" href="/cn/docs/field-lineage">+ 追踪字段的来源以及修改会影响到什么。+ </Card>+ <Card title="命令行" href="/cn/docs/cli">+ 完整的命令参考,包括无界面的文档导出。+ </Card>+</Cards>diff --git a/docs/content/docs/database-docs.mdx b/docs/content/docs/database-docs.mdxnew file mode 100644index 0000000000..5831861ffe--- /dev/null+++ b/docs/content/docs/database-docs.mdx@@ -0,0 +1,108 @@+---+title: Database Documentation+description: Browse a schema as documentation, annotate tables and columns with notes and colour-coded groups, and export DBML for dbdiagram.io or CI drift checks.+---++Database documentation turns a live schema into something readable. DBX collects tables, columns, indexes, and relationships into a snapshot, merges it with notes you write yourself, and renders a browsable reference. The same snapshot serializes to DBML, so the diagram tools and CI checks read exactly what the viewer shows.++Notes live in a plain JSON file that you can commit next to your migrations, which makes schema documentation reviewable in pull requests.++## Open Documentation++Right-click a table in [Object Browser](/en/docs/object-browser) and choose **Documentation**. The viewer opens on the current connection, database, and schema.++The sidebar switches between **Schemas** and **Table Groups**. Search covers tables, columns, and groups at once. Each table page lists columns, indexes, **References**, and **Referenced by**, so relationships read in both directions.++## Notes and Groups++| What you annotate | Where |+| --- | --- |+| Project note | Documentation home page |+| Table note | Table page heading |+| Column note | Column row in the table |+| Table group and its colour | Group picker on the table page |++Notes accept Markdown and render inline in the index. Every edit autosaves; the header shows **Saving…**, then **Saved**. A failed write is reported rather than swallowed, and your text is kept so the next edit retries.++Groups store a **hue**, not a fixed colour. Lightness and chroma come from the active theme, so a group stays legible in both light and dark mode — and the same hue becomes a `[color: #rrggbb]` value when exported to DBML.++## Local Notes and Database Comments++A column that has a database `COMMENT ON` value and a note written in DBX shows your note marked **LOCAL**, with the database comment preserved underneath. Nothing is overwritten in the database — DBX never issues DDL for documentation, and the original comment is always recoverable.++## Where Notes Are Stored++By default each connection gets its own notes file inside the DBX data directory, so the feature works with no setup.++Set **Notes file** in the connection's **Advanced** settings (stored as `docs_notes_path`) to point it at a file in your repository instead. The notes file itself looks like this:++```json+{+ "formatVersion": 1,+ "project": { "name": "Billing", "note": "# Billing\n\nOne schema per tenant." },+ "groups": [{ "id": "core", "name": "Core", "hue": 210 }],+ "tables": {+ "public.orders": {+ "group": "core",+ "note": "One row per checkout.",+ "columns": { "status": { "note": "Lifecycle state." } }+ }+ }+}+```++Keys are `schema.table` and `schema.table.column`, folded to match how the engine treats identifier case. Writes are atomic — the file is written beside its target and renamed — so an interrupted save cannot leave a half-written file where your prose used to be.++<Callout type="warn">A missing notes file is fine and starts empty. A malformed one is a hard error, deliberately: proceeding would render apparently-complete documentation while silently discarding writing.</Callout>++## Warnings++Documentation degrades visibly rather than silently. The viewer shows a banner when:++| Situation | What it means |+| --- | --- |+| A table could not be documented | One table's metadata failed to read. The rest of the schema still built. |+| No relationships available | The engine does not report foreign key metadata, so no edges could be derived. |+| Database comments unavailable | The engine has no comment support, so every description comes from your own notes. |+| Some notes no longer match anything | A note refers to a table or column that no longer exists. Nothing was deleted. |+| Not representable in DBML | A construct is documented in DBX but cannot be expressed in exported DBML. |++## DBML Export++```bash+dbx dbml <connection> [--out path] [--notes path] [--schema name] [--database name] [--tables a,b]+```++Without `--out` the DBML goes to stdout, so it pipes. Notes and groups are merged only when `--notes` names a file; the flag is explicit, so a typo in the path fails instead of silently producing note-free output.++Output includes `Table`, `Ref` with inferred cardinality, `Enum`, and `TableGroup` blocks, and pastes directly into [dbdiagram.io](https://dbdiagram.io).++Commit the result and let CI fail on unreviewed schema drift:++```yaml+- run: dbx dbml prod --notes docs/dbx-docs.json --out docs/schema.dbml+- run: git diff --exit-code docs/schema.dbml+```++## Support and Boundaries++- Relational engines only. Document databases and key-value stores have no DBML vocabulary and are not covered.+- Tables, columns, indexes, relationships, and enums are documented. Triggers, procedures, functions, sequences, and grants are not.+- DBML export is one-way. A `.dbml` file is an output, never a source of truth — DBX does not import it.+- Engines without foreign key metadata produce documentation with no relationship edges, reported as a warning rather than an empty page.+- Schema history and per-table "last updated" are not tracked. Snapshots are version-stamped so this can be added later.++<Cards>+ <Card title="Object browser" href="/en/docs/object-browser">+ Where documentation opens from, and where object source lives.+ </Card>+ <Card title="Schema browser" href="/en/docs/schema-browser">+ Inspect columns, foreign keys, and comments directly.+ </Card>+ <Card title="Field lineage" href="/en/docs/field-lineage">+ Trace where a column comes from and what a change affects.+ </Card>+ <Card title="CLI" href="/en/docs/cli">+ Full command reference, including headless documentation export.+ </Card>+</Cards>diff --git a/docs/content/docs/meta.cn.json b/docs/content/docs/meta.cn.jsonindex 70f6ac45ba..7e58a41c23 100644--- a/docs/content/docs/meta.cn.json+++ b/docs/content/docs/meta.cn.json@@ -19,6 +19,7 @@"table-structure","schema-diff","field-lineage",+ "database-docs","table-import","sql-file","database-export",diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex 9dd501d732..464b4917c2 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -19,6 +19,7 @@"table-structure","schema-diff","field-lineage",+ "database-docs","table-import","sql-file","database-export",diff --git a/docs/superpowers/plans/2026-08-02-database-documentation-annotations.md b/docs/superpowers/plans/2026-08-02-database-documentation-annotations.mdnew file mode 100644index 0000000000..f624fa557c--- /dev/null+++ b/docs/superpowers/plans/2026-08-02-database-documentation-annotations.md@@ -0,0 +1,1218 @@+# Database Documentation Part 2: Annotation Store — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Let users author table notes, column notes, project notes and table groups in a git-committable file, and have `dbx dbml --notes <path>` merge them into the generated DBML.++**Architecture:** A new `crates/dbx-core/src/docs/annotations.rs` owns the notes file: load, validate, and merge into the `SchemaSnapshot` that Part 1's collector produces. Keys are `schema.table` / `schema.table.column`, case-folded per engine by a small `docs/keys.rs`. Merge precedence is `local ?? database_comment`, recorded in the `note_source` and `shadowed_note` fields Part 1 already defined but never populated. Notes whose target no longer exists are reported as `SnapshotWarning::OrphanedNotes`, never dropped.++**Tech Stack:** Rust (dbx-core, dbx-cli), serde, serde_json. No new dependencies.++**Branch:** continue on `feature/docs-snapshot-dbml` (Part 1's branch, 19 commits, unmerged) — Part 2 builds directly on its types. Worktree already exists at `/Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml`.++**Spec:** `docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md`, Section 4.++## Global Constraints++- **NO new dependencies.** `serde`, `serde_json`, `chrono`, `futures` are already present in dbx-core.+- **`cargo` is NOT on PATH.** Every cargo command must be prefixed with+ `export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"`.+ A bare `cargo` fails instantly with "Failed to spawn process: No such file or directory (os error 2)" — that is not a hang.+- **A notes file that is ABSENT is fine; a notes file that is MALFORMED is a hard error.** User prose is at stake; proceeding silently would render apparently-complete docs while discarding writing.+- **Never silently drop a note.** A note whose target no longer exists becomes a warning, not a deletion.+- `format_version` in the notes file is `1`.+- Group colour is `hue: u16` in `0..=359`. Never a hex string.+- Run `cargo fmt` before every commit. Conventional Commits.+- **Report mismatches, do not work around them.** If a signature differs from this plan, stop and report the actual compiler error. Part 1 had thirteen plan defects; every one was caught this way.++---++## Pre-resolved facts (verified against the source — these override any assumption in the spec)++1. **`schema/normalization.rs` is NOT where key folding goes.** Every function in it is `pub(super)` and it does table-list *filtering* (YashanDB recyclebin, object-type filters, column dedup) — not identifier case folding, and not reachable from `docs::`. Part 2 creates its own `crates/dbx-core/src/docs/keys.rs`.++2. **`schema_diff::detect_renames` cannot be used for orphan suggestions.** Signature is+ `pub fn detect_renames(removed: &[String], added: &[String], source_details: &[TableSchemaDetail], target_details: &[TableSchemaDetail], threshold: f64) -> Vec<RenameCandidate>` (`schema_diff.rs:817`).+ It needs `TableSchemaDetail` for BOTH sides. The notes file stores prose only — it never retained the old schema — so there is nothing to diff against. **Rename suggestions are deferred** until snapshot history exists (spec Section 12). Part 2 detects and reports orphans; it does not suggest re-maps.++3. **Per-connection persistence.** `DesktopSettings.saved_sql_sync_dir` is a GLOBAL setting, not per-connection — it is not the precedent the spec implies. `ConnectionConfig` already carries per-connection preferences (`note`, `color`, `init_script`, `visible_schemas`) and is serde-persisted into the `connections` table. **Add `docs_notes_path: Option<String>` to `ConnectionConfig` with `#[serde(default)]`** — non-breaking, no migration, no new table.++4. **MySQL `lower_case_table_names`** is read in `transfer.rs:705-727` via `SHOW VARIABLES`, but that helper is private and costs a round-trip. Part 2 does NOT query it. MySQL keys fold to lowercase unconditionally (see Task 2 rationale).++5. **Part 1 fields this plan populates** (all exist, currently hardcoded `None`/`NoteSource::None` at `collector.rs:206-209`): `DocTable::note`, `note_source`, `shadowed_note`, `column_notes`, `group_id`, and `SchemaSnapshot::groups`. `column_notes` is already consumed by the serializer at `dbml.rs:126`; `groups` already render via `render_group` with an empty-member guard. **No Part 1 type changes are required.**++6. **Annotations are applied CLI-side, NOT inside the collector.** The notes file lives on the+ machine running `dbx`, and `WebBackend` talks to a remote DBX instance that cannot read it.+ Applying the merge after the snapshot returns keeps both transports identical — a property a+ Part 1 review specifically verified. Adding an `annotations` field to `CollectOptions` would+ therefore create a field written by nothing and read by nothing, which is exactly the+ "produced but never consumed" defect the Part 1 final review flagged. `collector.rs` is+ deliberately **not modified** by this plan.++---++## File Structure++| File | Responsibility |+| --- | --- |+| `crates/dbx-core/src/docs/keys.rs` | Per-engine identifier folding; `AnnotationKey` construction and matching |+| `crates/dbx-core/src/docs/annotations.rs` | Notes-file model, load/save, merge into snapshot, orphan detection |+| `crates/dbx-core/src/models/connection.rs` | `docs_notes_path` field |+| `crates/dbx-cli/src/main.rs` | `--notes` flag, wiring into `run_dbml` |+| `crates/dbx-core/tests/live_postgres_docs_annotations.rs` | Live verification with a real notes file |++---++## Task 0: Confirm the starting point++- [ ] **Step 1: Verify the branch and a green baseline**++```bash+cd /Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml+git branch --show-current # must print: feature/docs-snapshot-dbml+git status --short # must be empty+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+cargo test -p dbx-core docs::+```++Expected: `feature/docs-snapshot-dbml`, clean tree, 60 tests passing. If any differs, stop and report — Part 2 builds on Part 1 and a dirty starting point makes every later failure ambiguous.++---++## Task 1: Notes-file model++**Files:**+- Create: `crates/dbx-core/src/docs/annotations.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Produces: `AnnotationFile`, `ProjectAnnotation`, `TableAnnotation`, `ColumnAnnotation`, `GroupAnnotation`++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/annotations.rs` containing only this test module:++```rust+#[cfg(test)]+mod tests {+ use super::*;++ const SAMPLE: &str = r#"{+ "formatVersion": 1,+ "project": { "name": "Ecommerce", "note": "# Overview" },+ "groups": [+ { "id": "order-management", "name": "Order Management", "hue": 28, "note": "Checkout to handoff." }+ ],+ "tables": {+ "core.orders": {+ "group": "order-management",+ "note": "One row per checkout.",+ "columns": { "status": { "note": "State machine." } }+ }+ }+ }"#;++ #[test]+ fn parses_a_complete_notes_file() {+ let parsed: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ assert_eq!(parsed.format_version, 1);+ assert_eq!(parsed.project.as_ref().unwrap().name.as_deref(), Some("Ecommerce"));+ assert_eq!(parsed.groups.len(), 1);+ assert_eq!(parsed.groups[0].hue, 28);+ assert_eq!(parsed.tables.len(), 1);++ let orders = parsed.tables.get("core.orders").expect("orders");+ assert_eq!(orders.group.as_deref(), Some("order-management"));+ assert_eq!(orders.note.as_deref(), Some("One row per checkout."));+ assert_eq!(orders.columns.get("status").unwrap().note, "State machine.");+ }++ #[test]+ fn a_minimal_file_needs_only_the_format_version() {+ let parsed: AnnotationFile = serde_json::from_str(r#"{"formatVersion": 1}"#).expect("parse");+ assert!(parsed.tables.is_empty());+ assert!(parsed.groups.is_empty());+ assert!(parsed.project.is_none());+ }++ #[test]+ fn round_trips_through_json() {+ let parsed: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ let written = serde_json::to_string(&parsed).expect("serialize");+ let reparsed: AnnotationFile = serde_json::from_str(&written).expect("reparse");+ assert_eq!(reparsed.tables.len(), 1);+ assert_eq!(reparsed.groups[0].name, "Order Management");+ }++ #[test]+ fn rejects_a_file_with_an_unknown_top_level_field() {+ // Typos in a hand-edited file must not be silently ignored — a+ // misspelled "tabels" key would otherwise discard every note in it.+ let result: Result<AnnotationFile, _> =+ serde_json::from_str(r#"{"formatVersion": 1, "tabels": {}}"#);+ assert!(result.is_err(), "unknown fields must be rejected");+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++Add to `crates/dbx-core/src/docs/mod.rs`, keeping alphabetical order (it currently lists `color`, `collector`, `dbml`, `relations`, `snapshot`):++```rust+pub mod annotations;+```++Run: `cargo test -p dbx-core docs::annotations`+Expected: FAIL — `cannot find type AnnotationFile`.++- [ ] **Step 3: Write the types**++At the top of `crates/dbx-core/src/docs/annotations.rs`:++```rust+use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++/// The on-disk notes file. This IS the store — not a cache of anything.+/// It is meant to be committed to a repository and reviewed in pull+/// requests, so it must stay small, readable, and stable in key order.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct AnnotationFile {+ pub format_version: u32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub project: Option<ProjectAnnotation>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub groups: Vec<GroupAnnotation>,+ /// Keyed by `schema.table` (or bare `table` on schema-less engines).+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub tables: BTreeMap<String, TableAnnotation>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct ProjectAnnotation {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// Markdown. Becomes the documentation landing page.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct GroupAnnotation {+ /// Stable slug, referenced by `TableAnnotation::group`.+ pub id: String,+ pub name: String,+ /// 0..=359. Lightness and chroma are theme-controlled, so any hue is+ /// legible on both light and dark grounds by construction.+ pub hue: u16,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct TableAnnotation {+ /// References `GroupAnnotation::id`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub group: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+ /// Keyed by bare column name.+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub columns: BTreeMap<String, ColumnAnnotation>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct ColumnAnnotation {+ pub note: String,+}+```++`BTreeMap` rather than `HashMap` is deliberate: it serializes in sorted key order, so a committed notes file produces a stable diff instead of a reshuffled one on every save.++- [ ] **Step 4: Run the tests**++Run: `cargo test -p dbx-core docs::annotations`+Expected: PASS, 4 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): add annotation file model"+```++---++## Task 2: Per-engine key folding++**Files:**+- Create: `crates/dbx-core/src/docs/keys.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Consumes: `crate::models::connection::DatabaseType`+- Produces: `pub fn fold_identifier(db_type: DatabaseType, value: &str) -> String`, `pub fn table_key(db_type: DatabaseType, schema: Option<&str>, table: &str) -> String`, `pub fn column_key(db_type: DatabaseType, schema: Option<&str>, table: &str, column: &str) -> String`++**Why this module exists:** the spec said folding belongs in `schema/normalization.rs`. It does not — everything there is `pub(super)` and it filters table lists rather than folding identifiers.++**MySQL rationale:** MySQL's real behaviour depends on the server's `lower_case_table_names` variable. `transfer.rs:705` reads it via `SHOW VARIABLES`, but that helper is private and costs a round-trip per collection. Folding MySQL keys to lowercase unconditionally is correct for the common configurations (1 and 2) and, on the rare `0`, only risks matching a note to a table differing solely by case — which is a matching *hit*, never a wrong note on an unrelated table. The cost is bounded and the round-trip is not.++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/keys.rs` with only this test module:++```rust+#[cfg(test)]+mod tests {+ use super::*;+ use crate::models::connection::DatabaseType;++ #[test]+ fn postgres_folds_to_lowercase() {+ assert_eq!(fold_identifier(DatabaseType::Postgres, "Orders"), "orders");+ assert_eq!(fold_identifier(DatabaseType::Postgres, "ORDERS"), "orders");+ }++ #[test]+ fn mysql_folds_to_lowercase() {+ assert_eq!(fold_identifier(DatabaseType::MySQL, "Orders"), "orders");+ }++ #[test]+ fn table_keys_are_qualified_when_a_schema_is_present() {+ assert_eq!(table_key(DatabaseType::Postgres, Some("Core"), "Orders"), "core.orders");+ assert_eq!(table_key(DatabaseType::Postgres, None, "Orders"), "orders");+ assert_eq!(table_key(DatabaseType::Postgres, Some(""), "Orders"), "orders");+ }++ #[test]+ fn column_keys_extend_the_table_key() {+ assert_eq!(+ column_key(DatabaseType::Postgres, Some("core"), "orders", "Status"),+ "core.orders.status"+ );+ }++ #[test]+ fn folding_is_idempotent() {+ let once = table_key(DatabaseType::Postgres, Some("Core"), "Orders");+ let twice = table_key(DatabaseType::Postgres, Some(&once), "x");+ assert!(twice.starts_with("core.orders"), "got {twice}");+ assert_eq!(fold_identifier(DatabaseType::Postgres, &once), once);+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++Add `pub mod keys;` to `crates/dbx-core/src/docs/mod.rs` (alphabetically, after `dbml`).++Run: `cargo test -p dbx-core docs::keys`+Expected: FAIL — `cannot find function fold_identifier`.++**Note:** the exact `DatabaseType` variant spellings above (`Postgres`, `MySQL`) may differ. Check `crates/dbx-core/src/models/connection.rs` and use the real ones; report which you used.++- [ ] **Step 3: Write the implementation**++```rust+use crate::models::connection::DatabaseType;++/// Fold an identifier to its canonical case for note matching.+///+/// PostgreSQL folds unquoted identifiers to lower case, Oracle to upper.+/// MySQL depends on the server's `lower_case_table_names`; we fold to lower+/// unconditionally rather than pay a `SHOW VARIABLES` round-trip per+/// collection — on the rare case-sensitive configuration the only risk is+/// matching a note to a table differing solely by case, never attaching a+/// note to an unrelated table.+pub fn fold_identifier(db_type: DatabaseType, value: &str) -> String {+ match db_type {+ DatabaseType::Oracle => value.to_uppercase(),+ _ => value.to_lowercase(),+ }+}++/// `schema.table`, or bare `table` when there is no schema.+pub fn table_key(db_type: DatabaseType, schema: Option<&str>, table: &str) -> String {+ match schema.filter(|value| !value.is_empty()) {+ Some(schema) => {+ format!("{}.{}", fold_identifier(db_type, schema), fold_identifier(db_type, table))+ }+ None => fold_identifier(db_type, table),+ }+}++/// `schema.table.column`, or `table.column` when there is no schema.+pub fn column_key(db_type: DatabaseType, schema: Option<&str>, table: &str, column: &str) -> String {+ format!("{}.{}", table_key(db_type, schema, table), fold_identifier(db_type, column))+}+```++Add `pub use keys::{column_key, fold_identifier, table_key};` to `docs/mod.rs`.++- [ ] **Step 4: Run the tests**++Run: `cargo test -p dbx-core docs::keys`+Expected: PASS, 5 tests. Adjust the `DatabaseType::Oracle` arm if that variant is spelled differently.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): add per-engine annotation key folding"+```++---++## Task 3: Load the notes file++**Files:**+- Modify: `crates/dbx-core/src/docs/annotations.rs`++**Interfaces:**+- Produces: `pub fn load_annotations(path: &std::path::Path) -> Result<Option<AnnotationFile>, String>`++**The rule this task encodes:** absent is fine, malformed is fatal.++- [ ] **Step 1: Write the failing test**++Append to the `tests` module in `annotations.rs`:++```rust+ use std::io::Write;++ fn temp_notes(contents: &str) -> std::path::PathBuf {+ let mut path = std::env::temp_dir();+ path.push(format!("dbx-notes-test-{}.json", contents.len()));+ let mut file = std::fs::File::create(&path).expect("create");+ file.write_all(contents.as_bytes()).expect("write");+ path+ }++ #[test]+ fn an_absent_file_is_not_an_error() {+ let missing = std::path::Path::new("/nonexistent/dbx-notes-does-not-exist.json");+ assert!(matches!(load_annotations(missing), Ok(None)));+ }++ #[test]+ fn a_valid_file_loads() {+ let path = temp_notes(SAMPLE);+ let loaded = load_annotations(&path).expect("load").expect("some");+ assert_eq!(loaded.tables.len(), 1);+ let _ = std::fs::remove_file(&path);+ }++ #[test]+ fn a_malformed_file_is_a_hard_error_naming_the_path() {+ let path = temp_notes("{ this is not json");+ let error = load_annotations(&path).expect_err("must fail");+ assert!(error.contains(&path.display().to_string()), "error must name the file: {error}");+ let _ = std::fs::remove_file(&path);+ }++ #[test]+ fn an_unsupported_format_version_is_rejected() {+ let path = temp_notes(r#"{"formatVersion": 99}"#);+ let error = load_annotations(&path).expect_err("must fail");+ assert!(error.contains("99"), "error must name the version: {error}");+ let _ = std::fs::remove_file(&path);+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs::annotations`+Expected: FAIL — `cannot find function load_annotations`.++- [ ] **Step 3: Write the implementation**++```rust+use std::path::Path;++/// The only format version this build understands.+pub const ANNOTATION_FORMAT_VERSION: u32 = 1;++/// Load the notes file.+///+/// An ABSENT file returns `Ok(None)` — that is the normal first-run and+/// first-CI-run state. A MALFORMED file is a hard error: someone's prose is+/// in there, and rendering apparently-complete documentation while silently+/// discarding it is worse than failing.+pub fn load_annotations(path: &Path) -> Result<Option<AnnotationFile>, String> {+ let contents = match std::fs::read_to_string(path) {+ Ok(contents) => contents,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(format!("Failed to read notes file {}: {error}", path.display())),+ };++ let parsed: AnnotationFile = serde_json::from_str(&contents)+ .map_err(|error| format!("Failed to parse notes file {}: {error}", path.display()))?;++ if parsed.format_version != ANNOTATION_FORMAT_VERSION {+ return Err(format!(+ "Notes file {} has formatVersion {}, but this build understands {}.",+ path.display(),+ parsed.format_version,+ ANNOTATION_FORMAT_VERSION+ ));+ }++ Ok(Some(parsed))+}+```++- [ ] **Step 4: Run the tests**++Run: `cargo test -p dbx-core docs::annotations`+Expected: PASS, 8 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): load and validate the notes file"+```++---++## Task 4: Merge annotations into the snapshot++**Files:**+- Modify: `crates/dbx-core/src/docs/annotations.rs`++**Interfaces:**+- Consumes: `AnnotationFile` (Task 1), `table_key`/`column_key` (Task 2), `SchemaSnapshot`/`DocTable`/`ColumnNote`/`NoteSource`/`TableGroup`/`SnapshotWarning` (Part 1)+- Produces: `pub fn apply_annotations(snapshot: &mut SchemaSnapshot, annotations: &AnnotationFile, db_type: DatabaseType)`++**Merge precedence:** `local_annotation ?? database_comment`. When a local note shadows a database comment, the comment is preserved in `shadowed_note` so the UI can show what is being overridden — otherwise a DBA later writing a better `COMMENT ON` would have their improvement silently hidden.++- [ ] **Step 1: Write the failing test**++Append to the `tests` module:++```rust+ use crate::docs::{DocTable, NoteSource, ProjectMeta, SchemaSnapshot, TableKind};+ use crate::models::connection::DatabaseType;++ fn snapshot_with(tables: Vec<DocTable>) -> SchemaSnapshot {+ SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: "conn".to_string(),+ database_type: "postgres".to_string(),+ database: None,+ schemas: vec!["core".to_string()],+ generated_at: String::new(),+ note: None,+ },+ tables,+ relationships: vec![],+ groups: vec![],+ enums: vec![],+ warnings: vec![],+ }+ }++ fn table_named(schema: &str, name: &str, comment: Option<&str>) -> DocTable {+ DocTable {+ schema: Some(schema.to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ group_id: None,+ note: comment.map(ToOwned::to_owned),+ note_source: if comment.is_some() { NoteSource::Database } else { NoteSource::None },+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn a_local_note_shadows_the_database_comment_and_preserves_it() {+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", Some("Old DB comment."))]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let table = &snapshot.tables[0];+ assert_eq!(table.note.as_deref(), Some("One row per checkout."));+ assert_eq!(table.note_source, NoteSource::Local);+ assert_eq!(table.shadowed_note.as_deref(), Some("Old DB comment."));+ }++ #[test]+ fn a_database_comment_survives_when_there_is_no_local_note() {+ let mut snapshot = snapshot_with(vec![table_named("core", "users", Some("From the database."))]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let table = &snapshot.tables[0];+ assert_eq!(table.note.as_deref(), Some("From the database."));+ assert_eq!(table.note_source, NoteSource::Database);+ assert_eq!(table.shadowed_note, None);+ }++ #[test]+ fn keys_match_case_insensitively_on_postgres() {+ // The notes file says "core.orders"; the live schema reports "Core"/"Orders".+ let mut snapshot = snapshot_with(vec![table_named("Core", "Orders", None)]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.tables[0].note.as_deref(), Some("One row per checkout."));+ }++ #[test]+ fn column_notes_are_applied_and_marked_local() {+ let mut table = table_named("core", "orders", None);+ table.columns.push(crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ ..Default::default()+ });+ let mut snapshot = snapshot_with(vec![table]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ let note = snapshot.tables[0].column_notes.get("status").expect("column note");+ assert_eq!(note.note, "State machine.");+ assert_eq!(note.source, NoteSource::Local);+ }++ #[test]+ fn the_project_note_and_name_are_applied() {+ let mut snapshot = snapshot_with(vec![]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.project.name, "Ecommerce");+ assert_eq!(snapshot.project.note.as_deref(), Some("# Overview"));+ }++ #[test]+ fn groups_are_copied_and_membership_is_assigned() {+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.groups.len(), 1);+ assert_eq!(snapshot.groups[0].id, "order-management");+ assert_eq!(snapshot.groups[0].hue, 28);+ assert_eq!(snapshot.tables[0].group_id.as_deref(), Some("order-management"));+ }++ #[test]+ fn a_table_referencing_an_undefined_group_is_left_ungrouped() {+ let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);+ let mut annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ annotations.groups.clear();++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(snapshot.tables[0].group_id, None, "a dangling group reference must not be assigned");+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs::annotations`+Expected: FAIL — `cannot find function apply_annotations`.++- [ ] **Step 3: Write the implementation**++```rust+use crate::docs::{ColumnNote, NoteSource, SchemaSnapshot, TableGroup};+use crate::docs::keys::{column_key, table_key};+use crate::models::connection::DatabaseType;++/// Merge a notes file into a collected snapshot.+///+/// Precedence is `local ?? database_comment`. When a local note shadows a+/// database comment the comment is kept in `shadowed_note`, so a later+/// `COMMENT ON` improvement stays visible rather than being silently hidden.+pub fn apply_annotations(+ snapshot: &mut SchemaSnapshot,+ annotations: &AnnotationFile,+ db_type: DatabaseType,+) {+ if let Some(project) = annotations.project.as_ref() {+ if let Some(name) = project.name.as_deref().filter(|value| !value.trim().is_empty()) {+ snapshot.project.name = name.to_string();+ }+ if project.note.is_some() {+ snapshot.project.note = project.note.clone();+ }+ }++ let known_groups: std::collections::HashSet<&str> =+ annotations.groups.iter().map(|group| group.id.as_str()).collect();++ snapshot.groups = annotations+ .groups+ .iter()+ .map(|group| TableGroup {+ id: group.id.clone(),+ name: group.name.clone(),+ hue: group.hue,+ note: group.note.clone(),+ })+ .collect();++ for table in &mut snapshot.tables {+ let key = table_key(db_type, table.schema.as_deref(), &table.name);+ let Some(annotation) = annotations.tables.get(&key) else { continue };++ if let Some(note) = annotation.note.as_deref().filter(|value| !value.trim().is_empty()) {+ // Preserve whatever the database said before overwriting it.+ if matches!(table.note_source, NoteSource::Database) {+ table.shadowed_note = table.note.clone();+ }+ table.note = Some(note.to_string());+ table.note_source = NoteSource::Local;+ }++ // A group reference that names no defined group is dropped rather+ // than assigned — a dangling id would render an empty group header.+ table.group_id = annotation+ .group+ .as_deref()+ .filter(|id| known_groups.contains(id))+ .map(ToOwned::to_owned);++ for column in &table.columns {+ let column_fold = crate::docs::keys::fold_identifier(db_type, &column.name);+ let annotated = annotation+ .columns+ .iter()+ .find(|(name, _)| crate::docs::keys::fold_identifier(db_type, name) == column_fold);++ let Some((_, column_annotation)) = annotated else { continue };+ if column_annotation.note.trim().is_empty() {+ continue;+ }++ table.column_notes.insert(+ column.name.clone(),+ ColumnNote {+ note: column_annotation.note.clone(),+ source: NoteSource::Local,+ shadowed: column.comment.clone().filter(|value| !value.trim().is_empty()),+ },+ );+ }+ }++ // `column_key` is used by orphan detection in Task 5; referenced here so+ // the import is meaningful in both tasks.+ let _ = column_key;+}+```++**Note for the implementer:** the trailing `let _ = column_key;` is a placeholder to keep the import valid before Task 5 uses it. If the compiler is satisfied without importing `column_key` in this task, omit both the import and that line and add the import in Task 5 instead. Report which you did.++- [ ] **Step 4: Run the tests**++Run: `cargo test -p dbx-core docs::annotations`+Expected: PASS, 15 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): merge annotations into the schema snapshot"+```++---++## Task 5: Orphan detection++**Files:**+- Modify: `crates/dbx-core/src/docs/annotations.rs`++**Interfaces:**+- Produces: `pub fn detect_orphans(snapshot: &SchemaSnapshot, annotations: &AnnotationFile, db_type: DatabaseType) -> Vec<String>`; `apply_annotations` pushes `SnapshotWarning::OrphanedNotes { count }`++**Why no re-map suggestion:** `schema_diff::detect_renames` needs `TableSchemaDetail` for both the old and new schema. The notes file stores prose only — it never retained the old schema — so there is nothing to diff. Suggestions become possible once snapshot history exists (spec Section 12). Part 2 detects and reports; it never deletes.++- [ ] **Step 1: Write the failing test**++Append to the `tests` module:++```rust+ use crate::docs::SnapshotWarning;++ #[test]+ fn a_note_for_a_missing_table_is_reported_as_orphaned() {+ // The notes file describes core.orders; the schema no longer has it.+ let mut snapshot = snapshot_with(vec![table_named("core", "customers", None)]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ let orphans = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);+ assert_eq!(orphans, vec!["core.orders".to_string()]);++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);+ let orphan_warnings: Vec<&SnapshotWarning> = snapshot+ .warnings+ .iter()+ .filter(|warning| matches!(warning, SnapshotWarning::OrphanedNotes { .. }))+ .collect();+ assert_eq!(orphan_warnings.len(), 1);+ match orphan_warnings[0] {+ SnapshotWarning::OrphanedNotes { count } => assert_eq!(*count, 1),+ other => panic!("unexpected: {other:?}"),+ }+ }++ #[test]+ fn a_note_for_a_missing_column_is_reported_as_orphaned() {+ // The table exists but no longer has the annotated column.+ let mut table = table_named("core", "orders", None);+ table.columns.push(crate::types::ColumnInfo {+ name: "id".to_string(),+ data_type: "integer".to_string(),+ ..Default::default()+ });+ let snapshot = snapshot_with(vec![table]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ let orphans = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);+ assert_eq!(orphans, vec!["core.orders.status".to_string()]);+ }++ #[test]+ fn nothing_is_orphaned_when_everything_matches() {+ let mut table = table_named("core", "orders", None);+ table.columns.push(crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ ..Default::default()+ });+ let mut snapshot = snapshot_with(vec![table]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");++ assert!(detect_orphans(&snapshot, &annotations, DatabaseType::Postgres).is_empty());++ apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);+ assert!(+ !snapshot.warnings.iter().any(|w| matches!(w, SnapshotWarning::OrphanedNotes { .. })),+ "no orphan warning when everything matches"+ );+ }++ #[test]+ fn orphan_detection_never_removes_anything_from_the_file() {+ let snapshot = snapshot_with(vec![]);+ let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");+ let before = annotations.tables.len();++ let _ = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);++ assert_eq!(annotations.tables.len(), before, "detection must not mutate the file");+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs::annotations`+Expected: FAIL — `cannot find function detect_orphans`.++- [ ] **Step 3: Write the implementation**++```rust+/// Annotation keys whose target no longer exists in the collected schema.+///+/// Returns fully-qualified keys, sorted, so the caller can list them for a+/// human to re-map. This function NEVER mutates the notes file — user prose+/// is only ever removed by an explicit human action.+///+/// Suggestions for where a renamed target went are deliberately absent:+/// producing them requires the OLD schema to diff against, and the notes+/// file stores prose only. That becomes possible once snapshot history+/// exists (see the spec's deferred versioning seam).+pub fn detect_orphans(+ snapshot: &SchemaSnapshot,+ annotations: &AnnotationFile,+ db_type: DatabaseType,+) -> Vec<String> {+ use std::collections::HashSet;++ let live_tables: HashSet<String> = snapshot+ .tables+ .iter()+ .map(|table| table_key(db_type, table.schema.as_deref(), &table.name))+ .collect();++ let live_columns: HashSet<String> = snapshot+ .tables+ .iter()+ .flat_map(|table| {+ table.columns.iter().map(move |column| {+ column_key(db_type, table.schema.as_deref(), &table.name, &column.name)+ })+ })+ .collect();++ let mut orphans = Vec::new();++ for (key, annotation) in &annotations.tables {+ let folded_table = fold_key(db_type, key);+ if !live_tables.contains(&folded_table) {+ orphans.push(folded_table);+ continue;+ }+ for column in annotation.columns.keys() {+ let folded_column =+ format!("{folded_table}.{}", crate::docs::keys::fold_identifier(db_type, column));+ if !live_columns.contains(&folded_column) {+ orphans.push(folded_column);+ }+ }+ }++ orphans.sort();+ orphans+}++/// Fold an already-dotted key (e.g. `Core.Orders`) segment by segment.+fn fold_key(db_type: DatabaseType, key: &str) -> String {+ key.split('.')+ .map(|segment| crate::docs::keys::fold_identifier(db_type, segment))+ .collect::<Vec<_>>()+ .join(".")+}+```++Then, at the END of `apply_annotations` (replacing the `let _ = column_key;` placeholder from Task 4):++```rust+ let orphans = detect_orphans(snapshot, annotations, db_type);+ if !orphans.is_empty() {+ snapshot.warnings.push(SnapshotWarning::OrphanedNotes { count: orphans.len() });+ }+```++Add `SnapshotWarning` to the `use crate::docs::{...}` line.++- [ ] **Step 4: Run the tests**++Run: `cargo test -p dbx-core docs::annotations`+Expected: PASS, 19 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): detect orphaned annotations without deleting them"+```++---++## Task 6: `--notes` CLI flag++**Files:**+- Modify: `crates/dbx-cli/src/main.rs`++**Interfaces:**+- Consumes: `load_annotations` (Task 3), `apply_annotations` (Task 4)++**Note:** `DocsSnapshotOptions` in `dbx_mcp::backend` carries options across the backend boundary. It does NOT need an `annotations` field — the CLI loads the file locally and, for `LocalBackend`, the annotations reach the collector directly. For `WebBackend` the notes file lives on the CLI's machine, not the server's, so annotations must be applied CLI-side after the snapshot returns. Implement it that way: load the file in `run_dbml`, and apply it to the returned snapshot with `apply_annotations` before calling `to_dbml`. This keeps both transports identical, which a Part 1 review specifically verified.++- [ ] **Step 1: Write the failing test**++Append to `main.rs`'s test module:++```rust+ #[test]+ fn parses_the_notes_flag() {+ let flags = parse_flags(&args(&["dbml", "local", "--notes", "docs/dbx-docs.json"])).expect("parse");+ assert_eq!(flags.args, args(&["dbml", "local"]));+ assert_eq!(flags.notes.as_deref(), Some(std::path::Path::new("docs/dbx-docs.json")));+ }++ #[test]+ fn notes_requires_a_value() {+ let error = parse_flags(&args(&["dbml", "local", "--notes"])).expect_err("should fail");+ assert_eq!(error.code, "INVALID_OPTION");+ }++ #[test]+ fn notes_appears_in_the_usage_text() {+ assert!(usage().contains("--notes"), "got: {}", usage());+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-cli`+Expected: FAIL — `no field named notes on Flags`.++- [ ] **Step 3: Write the implementation**++- Add `notes: Option<PathBuf>` to `Flags` (NO `pub` — the struct and all its fields are private) and initialise it to `None` in `parse_flags`.+- Add the parse arm beside `--out`:+ ```rust+ "--notes" => flags.notes = Some(PathBuf::from(option_value(argv, &mut index, "--notes")?)),+ ```+- In `run_dbml`, after obtaining the snapshot and before `to_dbml`:+ ```rust+ let mut snapshot = snapshot;+ if let Some(path) = flags.notes.as_ref() {+ if let Some(annotations) = dbx_core::docs::annotations::load_annotations(path)+ .map_err(|error| CliError::new("NOTES_INVALID", error))?+ {+ dbx_core::docs::annotations::apply_annotations(+ &mut snapshot,+ &annotations,+ connection.db_type,+ );+ }+ }+ ```+ A malformed notes file must abort with a non-zero exit — it must NOT fall through to producing documentation without the prose.+- Extend the `dbx dbml` line inside the single `usage()` `&'static str` literal so it reads:+ ```+ dbx dbml <connection> [--out path] [--notes path] [--schema name] [--database name] [--tables a,b]+ ```++- [ ] **Step 4: Run the tests**++Run: `cargo test -p dbx-cli`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-cli/src/main.rs+git commit -m "feat(docs): add --notes to dbx dbml"+```++---++## Task 7: `docs_notes_path` on ConnectionConfig++**Files:**+- Modify: `crates/dbx-core/src/models/connection.rs`++**Interfaces:**+- Produces: `ConnectionConfig.docs_notes_path: Option<String>`++**Why here rather than a new table:** `ConnectionConfig` already carries per-connection preferences (`note`, `color`, `init_script`, `visible_schemas`) and is serde-persisted into the `connections` table. `DesktopSettings.saved_sql_sync_dir` is a GLOBAL setting and is not the right precedent despite what the spec implies. `#[serde(default)]` makes this non-breaking for existing stored connections — no migration.++This field is not consumed by anything in Part 2 (the CLI takes an explicit `--notes` path). It exists so Part 3's desktop dialog has somewhere to remember the path per connection.++- [ ] **Step 1: Write the failing test**++Append to `connection.rs`'s test module (or create one following the file's conventions):++```rust+ #[test]+ fn docs_notes_path_defaults_to_none_for_existing_stored_connections() {+ // A connection persisted before this field existed must still load.+ let json = r#"{+ "id": "c1", "name": "local", "note": "", "db_type": "Postgres",+ "host": "127.0.0.1", "port": 5432, "username": "postgres",+ "password": "", "attached_databases": [], "agent_java_options": [],+ "connect_timeout_secs": 10, "transport_layers": []+ }"#;+ let parsed: ConnectionConfig = serde_json::from_str(json).expect("parse");+ assert_eq!(parsed.docs_notes_path, None);+ }+```++The exact JSON must satisfy every non-`default` field on `ConnectionConfig`. Run the test, read the serde error, and add whatever fields it names — do NOT add `#[serde(default)]` to other fields to make it pass.++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs_notes_path`+Expected: FAIL — `no field docs_notes_path`.++- [ ] **Step 3: Write the implementation**++Add to `ConnectionConfig`, beside `init_script` / `color`:++```rust+ /// Path to this connection's documentation notes file. Set by the+ /// desktop app; the CLI takes an explicit `--notes` path instead.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub docs_notes_path: Option<String>,+```++Then fix every `ConnectionConfig { .. }` literal the compiler flags. There are many (including `crates/dbx-core/tests/live_postgres_query_result_export.rs:12`); add `docs_notes_path: None` to each. Let the compiler enumerate them; report the count.++- [ ] **Step 4: Run the tests**++```bash+cargo test -p dbx-core+cargo check --workspace --all-targets+```+Expected: pass and clean.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add -A+git commit -m "feat(docs): remember a notes file path per connection"+```++---++## Task 8: Live verification++**Files:**+- Create: `crates/dbx-core/tests/live_postgres_docs_annotations.rs`++Follow the gating convention of `crates/dbx-core/tests/live_postgres_docs_snapshot.rs` exactly: `#[tokio::test]` + `#[ignore = "requires DBX_LIVE_POSTGRES_..."]`, env vars with defaults, and the `live_postgres_config(...)` builder. Do NOT invent a skip-helper — `#[ignore]` is what keeps the test from silently passing with no database.++- [ ] **Step 1: Write the live test**++The test must: write a temporary notes file annotating a table that genuinely exists in `keycloak` plus one that does not; collect a snapshot with those annotations; then assert+- the real table's note is present with `note_source == NoteSource::Local`,+- an `OrphanedNotes` warning is present with `count >= 1`,+- the generated DBML contains the note text,+- and the temp file is removed on both success and failure paths.++Print the generated DBML with `println!` so `--nocapture` shows it.++- [ ] **Step 2: Run it against the live database**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+DBX_LIVE_POSTGRES_HOST=127.0.0.1 DBX_LIVE_POSTGRES_PORT=5432 \+DBX_LIVE_POSTGRES_USER=postgres DBX_LIVE_POSTGRES_PASSWORD=postgres \+DBX_LIVE_POSTGRES_DATABASE=keycloak \+cargo test -p dbx-core --test live_postgres_docs_annotations -- --ignored --nocapture+```++Paste the ACTUAL generated DBML into the report — specifically a `Table` block showing the merged note and the `Note:` line inside it.++- [ ] **Step 3: Full sweep**++```bash+cargo test --workspace+cargo clippy -p dbx-core -- -D warnings+```++Report clippy honestly. `crates/dbx-core/src/table_structure_sql/triggers.rs:58` fails on `map_or` — that is PRE-EXISTING on main, verified byte-identical, and is NOT yours to fix. Confirm it is the only remaining lint.++- [ ] **Step 4: Commit**++```bash+cargo fmt+git add crates/dbx-core/tests/+git commit -m "test(docs): verify annotations against a live database"+```++---++## Done criteria++- `dbx dbml <connection> --notes docs/dbx-docs.json` merges notes and groups into the emitted DBML.+- An absent notes file is fine; a malformed one aborts with a non-zero exit naming the file.+- A note whose target no longer exists produces an `OrphanedNotes` warning on stderr and is never deleted.+- A local note shadowing a database comment preserves the comment in `shadowed_note`.+- Table groups become `TableGroup` blocks with `[color: #rrggbb]` derived from each group's hue.+- `cargo test --workspace` passes; clippy clean except the pre-existing `triggers.rs` lint.++## Deferred to Part 3++- The docs viewer, in-app editing dialog, group colour picker, and HTML export.+- Rename suggestions for orphaned notes (needs snapshot history — spec Section 12).+- Writing the notes file from DBX (Part 2 only reads it; the file is hand-edited or repo-managed).++---++## Appendix: Corrections found during execution++Defects in this plan's own text, found while executing it. Grouped by failure mode rather than by+task, because the modes repeat and the tasks do not. Every one originated in the plan; none was an+implementer error. The companion plan for the viewer carries its own appendix in the same form.++### Mode A — compiles, passes its own test, and is silently wrong forever++The most dangerous defect found anywhere in this feature, and the only one that would have shipped+undetected.++- **Task 7, `docs_notes_path`.** The plan added the field to `ConnectionConfig` and to its own+ test, which passed. But `ConnectionConfig` is not what deserialization reads — a mirror struct,+ `ConnectionConfigData`, carries the serde attributes, and a `From` impl copies fields across.+ Adding the field in one place compiles cleanly, satisfies a round-trip test written against the+ same struct, and then reads `None` forever after every load, because nothing ever populates it.+ Caught by pre-resolution, not by review: the field had to be added in **three** places, and only+ reading the deserialization path revealed the third.++**The lesson:** when a struct has a serde mirror, "it compiles and the test passes" is evidence+about the wrong object. Follow the value from the file on disk to the field being read.++### Mode B — an assertion too weak to detect the failure it names++Same failure mode as Mode 1 in the viewer plan's appendix, and the most common across both.++- **Task 1, `round_trips_through_json`.** Asserted only `tables.len()` and a single group name. A+ serializer that silently dropped every note, hue, and column annotation would pass it. Fixed by+ asserting the full round-tripped structure.+- **Task 5.** Each headline test individually survived a mutant; only the *pair* caught it.+ Accepted rather than fixed, but recorded, because a later edit that deletes one test would+ silently remove the coverage the other depends on.++### Mode C — plan text written from memory instead of from the code++Four instances, all caught before dispatch by reading the actual source. None would have survived+compilation, so the cost was implementer time rather than correctness — but that cost is real.++- `DatabaseType::Mysql`, which the plan spelled `MySQL`.+- A borrow hazard in a code block the plan supplied verbatim (Task 4).+- `let mut snapshot = snapshot;` in the `run_dbml` shape, which was a guess at the real signature.+- `capabilities_for` is `pub(super)`, not `pub`, and `AppState`'s module path was wrong.++**The lesson:** every identifier a plan names is a claim about the codebase. Checking them costs+minutes; a dispatch that fails on one costs an implementer round-trip.++### Mode D — matching logic that attaches data to the wrong object++- **Task 2, identifier folding.** The original key-matching rule could fold two genuinely distinct+ identifiers to the same key, so a note written for one table would attach to another. The doc+ comment's stated MySQL rationale also described behaviour the code did not implement. Fixed by+ making `fold_identifier` engine-specific (Oracle uppercases, ClickHouse and MongoDB preserve,+ everything else lowercases) and correcting the comment to match.++A related seam was investigated and cleared: Oracle folding is used **only** for matching, never+for output — the serializer emits the collector's reported name verbatim, so folding cannot corrupt+what is written.++### Mode E — a test helper that is itself flaky++- **Task 3.** The plan's own test helper had a race that would produce intermittent failures.+ Caught before dispatch. A flaky test in a new suite is worse than no test: it trains the reader+ to re-run rather than to read.++### A controller hypothesis that was wrong++Recorded because being wrong in this direction is cheap and worth doing more often. I suspected a+second `apply_annotations` call would overwrite `shadowed_note` with the first local note and lose+the database comment. Tracing it showed the guard simply does not fire on the second call, so+`shadowed_note` keeps its first-call value. No defect existed. The check cost one read.diff --git a/docs/superpowers/plans/2026-08-02-database-documentation-snapshot-dbml.md b/docs/superpowers/plans/2026-08-02-database-documentation-snapshot-dbml.mdnew file mode 100644index 0000000000..3eb4ffb27a--- /dev/null+++ b/docs/superpowers/plans/2026-08-02-database-documentation-snapshot-dbml.md@@ -0,0 +1,2712 @@+# Database Documentation Part 1: Snapshot and DBML Export — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Build `SchemaSnapshot` — the normalized model every documentation output serializes from — plus a DBML serializer and a working `dbx dbml <connection>` CLI verb.++**Architecture:** A new `crates/dbx-core/src/docs/` module. `snapshot.rs` defines a serde model composing the existing `crate::types::{TableInfo, ColumnInfo, IndexInfo, ForeignKeyInfo}` rather than redeclaring them. `relations.rs` ports the cardinality-inference half of `apps/desktop/src/lib/diagram/erDiagram.ts` to Rust. `collector.rs` fans out over the existing `schema::providers` functions with a bounded semaphore. `dbml.rs` is a pure function `SchemaSnapshot -> String`. The CLI reaches the database through a single new `DbxBackend::collect_docs_snapshot` method so `WebBackend` makes one HTTP call rather than 3×N.++**Tech Stack:** Rust (dbx-core, dbx-web, dbx-mcp, dbx-cli), tokio, serde. No new dependencies.++**Branch:** create `feature/docs-snapshot-dbml` from current HEAD.++**Spec:** `docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md`.++**Scope note:** This is part 1 of 3, covering Build Order steps 1–2 from the spec. Table groups and notes are *serialized* here but not *authored* — `SchemaSnapshot.groups` and all note fields stay empty until Part 2 adds the annotation store. The serializer is tested against hand-built snapshots that do contain groups and notes, so Part 2 wires in a proven serializer. The docs viewer, HTML export and `dbx docs` are Part 3.++## Global Constraints++- **No new dependencies.** Everything here uses the existing crate graph.+- **Reuse, never redeclare** `crate::types::{TableInfo, ColumnInfo, IndexInfo, ForeignKeyInfo}`.+- `SchemaSnapshot.format_version` is `1` for every snapshot this plan produces.+- Group colour is stored as `hue: u16` in `0..=359`, never a hex string. Hex appears only in DBML output.+- Every DBML-inexpressible construct produces a `SnapshotWarning::DbmlOmitted`; none are silently dropped.+- Conventional Commits (`feat(docs): …`), matching repo history.+- Run `cargo fmt` before each commit; the repo has `rustfmt.toml` and `clippy.toml`.++---++## File Structure++| File | Responsibility |+| --- | --- |+| `crates/dbx-core/src/docs/mod.rs` | Module wiring + public API (`collect_snapshot`, `to_dbml`) |+| `crates/dbx-core/src/docs/snapshot.rs` | `SchemaSnapshot` and all its member types |+| `crates/dbx-core/src/docs/relations.rs` | FK → `Relationship` with cardinality inference |+| `crates/dbx-core/src/docs/collector.rs` | Bounded metadata fan-out, progress, cancellation |+| `crates/dbx-core/src/docs/dbml.rs` | `SchemaSnapshot` → DBML text |+| `crates/dbx-core/src/docs/color.rs` | OKLCH hue → sRGB hex for DBML `[color: …]` |+| `crates/dbx-web/src/routes/docs.rs` | `POST /api/docs/snapshot` |+| `crates/dbx-mcp/src/backend.rs` | `DbxBackend::collect_docs_snapshot` + both impls |+| `crates/dbx-cli/src/main.rs` | `dbx dbml` verb, `--out` flag, usage text |++---++## Task 0: Branch setup++- [ ] **Step 1: Create the branch**++```bash+cd /Users/possebon/workspaces/dbx+git checkout -b feature/docs-snapshot-dbml+```++- [ ] **Step 2: Confirm a clean baseline**++Run: `cargo check -p dbx-core`+Expected: finishes with no errors. If it fails, stop — the baseline is broken and nothing below is diagnosable.++---++## Task 1: Snapshot model++**Files:**+- Create: `crates/dbx-core/src/docs/mod.rs`+- Create: `crates/dbx-core/src/docs/snapshot.rs`+- Modify: `crates/dbx-core/src/lib.rs` (add `pub mod docs;`)++**Interfaces:**+- Consumes: `crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo}`+- Produces: `SchemaSnapshot`, `ProjectMeta`, `DocTable`, `TableGroup`, `Relationship`, `FieldRef`, `ColumnNote`, `DocEnum`, `TableKind`, `NoteSource`, `Cardinality`, `SnapshotWarning`++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/snapshot.rs` with only this test module at the bottom (types come in Step 3):++```rust+#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> SchemaSnapshot {+ SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: "Ecommerce".to_string(),+ database_type: "PostgreSQL".to_string(),+ database: Some("shop".to_string()),+ schemas: vec!["public".to_string()],+ generated_at: "2026-08-02T12:00:00Z".to_string(),+ note: None,+ },+ tables: vec![DocTable {+ schema: Some("public".to_string()),+ name: "orders".to_string(),+ kind: TableKind::Table,+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ group_id: None,+ note: Some("Checkout rows.".to_string()),+ note_source: NoteSource::Database,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: Some(2_400_000),+ view_definition: None,+ }],+ relationships: vec![],+ groups: vec![],+ enums: vec![],+ warnings: vec![],+ }+ }++ #[test]+ fn snapshot_round_trips_through_json() {+ let original = sample();+ let json = serde_json::to_string(&original).expect("serialize");+ let parsed: SchemaSnapshot = serde_json::from_str(&json).expect("deserialize");++ assert_eq!(parsed.format_version, 1);+ assert_eq!(parsed.project.name, "Ecommerce");+ assert_eq!(parsed.tables.len(), 1);+ assert_eq!(parsed.tables[0].name, "orders");+ assert_eq!(parsed.tables[0].note.as_deref(), Some("Checkout rows."));+ assert_eq!(parsed.tables[0].estimated_rows, Some(2_400_000));+ }++ #[test]+ fn snapshot_json_uses_camel_case_keys() {+ let json = serde_json::to_string(&sample()).expect("serialize");+ assert!(json.contains("\"formatVersion\""), "got: {json}");+ assert!(json.contains("\"generatedAt\""), "got: {json}");+ assert!(json.contains("\"noteSource\""), "got: {json}");+ }++ #[test]+ fn table_kind_serializes_as_screaming_snake_case() {+ let json = serde_json::to_string(&TableKind::MaterializedView).expect("serialize");+ assert_eq!(json, "\"MATERIALIZED_VIEW\"");+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++First wire the module so the file compiles at all. Add to `crates/dbx-core/src/lib.rs` alongside the other `pub mod` lines:++```rust+pub mod docs;+```++Create `crates/dbx-core/src/docs/mod.rs`:++```rust+pub mod snapshot;++pub use snapshot::*;+```++Run: `cargo test -p dbx-core docs::snapshot`+Expected: FAIL — `cannot find struct SchemaSnapshot in this scope` and similar for every type.++- [ ] **Step 3: Write the types**++At the top of `crates/dbx-core/src/docs/snapshot.rs`, above the test module:++```rust+use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};++/// The normalized description of a relational schema. Every documentation+/// output (DBML, HTML, future changelog records) is a serializer over this.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SchemaSnapshot {+ /// Guards viewer/data skew. Always 1 for now; bump only on a breaking+ /// change to this model.+ pub format_version: u32,+ pub project: ProjectMeta,+ pub tables: Vec<DocTable>,+ pub relationships: Vec<Relationship>,+ #[serde(default)]+ pub groups: Vec<TableGroup>,+ #[serde(default)]+ pub enums: Vec<DocEnum>,+ #[serde(default)]+ pub warnings: Vec<SnapshotWarning>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ProjectMeta {+ pub name: String,+ pub database_type: String,+ pub database: Option<String>,+ pub schemas: Vec<String>,+ /// RFC3339.+ pub generated_at: String,+ /// Markdown. Rendered as the documentation landing page.+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocTable {+ pub schema: Option<String>,+ pub name: String,+ pub kind: TableKind,+ pub columns: Vec<ColumnInfo>,+ pub indexes: Vec<IndexInfo>,+ pub foreign_keys: Vec<ForeignKeyInfo>,+ /// References `TableGroup::id`. Populated in Part 2.+ pub group_id: Option<String>,+ /// Merged note: local annotation, else database comment.+ pub note: Option<String>,+ pub note_source: NoteSource,+ /// The database comment a local note is overriding, if any. Shown on+ /// hover so a later `COMMENT ON` improvement is never invisible.+ pub shadowed_note: Option<String>,+ #[serde(default)]+ pub column_notes: BTreeMap<String, ColumnNote>,+ pub estimated_rows: Option<i64>,+ pub view_definition: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct TableGroup {+ /// Stable slug. Survives a display-name change.+ pub id: String,+ pub name: String,+ /// 0..=359. Lightness and chroma are theme-controlled in CSS, so any+ /// hue is legible on both grounds by construction.+ pub hue: u16,+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ColumnNote {+ pub note: String,+ pub source: NoteSource,+ pub shadowed: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocEnum {+ pub schema: Option<String>,+ pub name: String,+ pub values: Vec<String>,+ pub note: Option<String>,+ /// True when synthesized from a MySQL inline `ENUM(...)` column rather+ /// than read from a named database type.+ #[serde(default)]+ pub synthesized: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Relationship {+ pub id: String,+ pub name: Option<String>,+ pub from: FieldRef,+ pub to: FieldRef,+ pub cardinality: Cardinality,+ pub on_update: Option<String>,+ pub on_delete: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FieldRef {+ pub schema: Option<String>,+ pub table: String,+ pub column: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum TableKind {+ Table,+ View,+ MaterializedView,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum NoteSource {+ /// Read from a database COMMENT.+ Database,+ /// Authored in DBX, stored in the notes file.+ Local,+ None,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum Cardinality {+ OneToOne,+ ManyToOne,+}++/// Why a snapshot is less complete than it looks. Rendered as a dismissible+/// banner rather than left for the reader to discover.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", tag = "kind")]+pub enum SnapshotWarning {+ TableSkipped { table: String, reason: String },+ NoForeignKeyMetadata { engine: String },+ CommentsUnsupported { engine: String },+ OrphanedNotes { count: usize },+ DbmlOmitted { table: String, item: String, reason: String },+}++impl DocTable {+ /// `schema.name` when a schema is present, otherwise bare `name`.+ pub fn qualified_name(&self) -> String {+ match &self.schema {+ Some(schema) if !schema.is_empty() => format!("{schema}.{}", self.name),+ _ => self.name.clone(),+ }+ }+}++impl FieldRef {+ pub fn qualified_table(&self) -> String {+ match &self.schema {+ Some(schema) if !schema.is_empty() => format!("{schema}.{}", self.table),+ _ => self.table.clone(),+ }+ }+}+```++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::snapshot`+Expected: PASS, 3 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/lib.rs crates/dbx-core/src/docs/+git commit -m "feat(docs): add SchemaSnapshot model"+```++---++## Task 2: Relationship inference++**Files:**+- Create: `crates/dbx-core/src/docs/relations.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Consumes: `DocTable`, `Relationship`, `FieldRef`, `Cardinality` from Task 1+- Produces: `pub fn build_relationships(tables: &[DocTable]) -> Vec<Relationship>`++This ports the data half of `apps/desktop/src/lib/diagram/erDiagram.ts`. The rule, from `foreignKeySourceCardinality`: a foreign key is `OneToOne` **only** when the source columns contain a unique key (unique index or primary key); otherwise `ManyToOne`.++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/relations.rs` with only this test module:++```rust+#[cfg(test)]+mod tests {+ use super::*;+ use crate::docs::{NoteSource, TableKind};+ use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};+ use std::collections::BTreeMap;++ fn column(name: &str, primary: bool) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: "integer".to_string(),+ is_nullable: false,+ is_primary_key: primary,+ ..ColumnInfo::default()+ }+ }++ fn fk(name: &str, column: &str, ref_table: &str, ref_column: &str) -> ForeignKeyInfo {+ ForeignKeyInfo {+ name: name.to_string(),+ column: column.to_string(),+ ref_schema: Some("public".to_string()),+ ref_table: ref_table.to_string(),+ ref_column: ref_column.to_string(),+ on_update: None,+ on_delete: Some("CASCADE".to_string()),+ }+ }++ fn unique_index(name: &str, columns: &[&str]) -> IndexInfo {+ IndexInfo {+ name: name.to_string(),+ columns: columns.iter().map(|c| c.to_string()).collect(),+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ }+ }++ fn table(name: &str, columns: Vec<ColumnInfo>, indexes: Vec<IndexInfo>, fks: Vec<ForeignKeyInfo>) -> DocTable {+ DocTable {+ schema: Some("public".to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns,+ indexes,+ foreign_keys: fks,+ group_id: None,+ note: None,+ note_source: NoteSource::None,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn plain_foreign_key_is_many_to_one() {+ let tables = vec![+ table("orders", vec![column("id", true), column("user_id", false)], vec![],+ vec![fk("fk_orders_user", "user_id", "users", "id")]),+ table("users", vec![column("id", true)], vec![], vec![]),+ ];++ let rels = build_relationships(&tables);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].cardinality, Cardinality::ManyToOne);+ assert_eq!(rels[0].from.table, "orders");+ assert_eq!(rels[0].from.column, "user_id");+ assert_eq!(rels[0].to.table, "users");+ assert_eq!(rels[0].to.column, "id");+ assert_eq!(rels[0].on_delete.as_deref(), Some("CASCADE"));+ }++ #[test]+ fn foreign_key_on_a_unique_column_is_one_to_one() {+ let tables = vec![+ table("shipments",+ vec![column("id", true), column("order_id", false)],+ vec![unique_index("uq_shipments_order", &["order_id"])],+ vec![fk("fk_shipments_order", "order_id", "orders", "id")]),+ table("orders", vec![column("id", true)], vec![], vec![]),+ ];++ let rels = build_relationships(&tables);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].cardinality, Cardinality::OneToOne);+ }++ #[test]+ fn foreign_key_on_a_primary_key_column_is_one_to_one() {+ let tables = vec![+ table("user_profiles", vec![column("user_id", true)], vec![],+ vec![fk("fk_profile_user", "user_id", "users", "id")]),+ table("users", vec![column("id", true)], vec![], vec![]),+ ];++ assert_eq!(build_relationships(&tables)[0].cardinality, Cardinality::OneToOne);+ }++ #[test]+ fn multi_column_unique_index_does_not_make_a_single_column_unique() {+ // uq(a, b) does NOT make `a` alone unique, so the FK stays many-to-one.+ let tables = vec![+ table("order_items",+ vec![column("order_id", false), column("product_id", false)],+ vec![unique_index("uq_items", &["order_id", "product_id"])],+ vec![fk("fk_items_order", "order_id", "orders", "id")]),+ table("orders", vec![column("id", true)], vec![], vec![]),+ ];++ assert_eq!(build_relationships(&tables)[0].cardinality, Cardinality::ManyToOne);+ }++ #[test]+ fn self_referencing_foreign_key_is_supported() {+ let tables = vec![table("categories",+ vec![column("id", true), column("parent_id", false)], vec![],+ vec![fk("fk_cat_parent", "parent_id", "categories", "id")])];++ let rels = build_relationships(&tables);++ assert_eq!(rels.len(), 1);+ assert_eq!(rels[0].from.table, "categories");+ assert_eq!(rels[0].to.table, "categories");+ }++ #[test]+ fn foreign_key_to_an_absent_table_is_dropped() {+ // The target may live outside the selected schema. A dangling edge+ // would render as a relationship to nothing.+ let tables = vec![table("orders", vec![column("user_id", false)], vec![],+ vec![fk("fk_orders_user", "user_id", "users", "id")])];++ assert!(build_relationships(&tables).is_empty());+ }++ #[test]+ fn relationship_ids_are_stable_and_unique() {+ let tables = vec![+ table("orders",+ vec![column("user_id", false), column("merchant_id", false)], vec![],+ vec![fk("fk_a", "user_id", "users", "id"),+ fk("fk_b", "merchant_id", "users", "id")]),+ table("users", vec![column("id", true)], vec![], vec![]),+ ];++ let rels = build_relationships(&tables);+ assert_eq!(rels.len(), 2);+ assert_ne!(rels[0].id, rels[1].id);+ assert_eq!(build_relationships(&tables)[0].id, rels[0].id);+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++Add to `crates/dbx-core/src/docs/mod.rs`:++```rust+pub mod relations;+pub mod snapshot;++pub use relations::build_relationships;+pub use snapshot::*;+```++Run: `cargo test -p dbx-core docs::relations`+Expected: FAIL — `cannot find function build_relationships`.++- [ ] **Step 3: Write the implementation**++At the top of `crates/dbx-core/src/docs/relations.rs`:++```rust+use std::collections::HashSet;++use crate::docs::{Cardinality, DocTable, FieldRef, Relationship};+use crate::types::ForeignKeyInfo;++/// True when `column` alone is guaranteed unique on `table` — either it is a+/// single-column primary key, or a single-column unique index covers it.+///+/// A composite unique index over (a, b) does NOT make `a` unique, which is+/// why the column count is checked.+fn column_is_unique(table: &DocTable, column: &str) -> bool {+ let primary_columns: Vec<&str> =+ table.columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();++ if primary_columns.len() == 1 && primary_columns[0] == column {+ return true;+ }++ table+ .indexes+ .iter()+ .any(|index| (index.is_unique || index.is_primary) && index.columns.len() == 1 && index.columns[0] == column)+}++fn cardinality_for(table: &DocTable, foreign_key: &ForeignKeyInfo) -> Cardinality {+ if column_is_unique(table, &foreign_key.column) {+ Cardinality::OneToOne+ } else {+ Cardinality::ManyToOne+ }+}++fn relationship_id(source: &DocTable, foreign_key: &ForeignKeyInfo) -> String {+ [+ source.qualified_name().as_str(),+ if foreign_key.name.is_empty() { "foreign_key" } else { foreign_key.name.as_str() },+ foreign_key.column.as_str(),+ foreign_key.ref_table.as_str(),+ foreign_key.ref_column.as_str(),+ ]+ .join(":")+}++/// Resolve a foreign key's target against the tables actually present.+///+/// Resolution order mirrors SQL's own: an explicit `ref_schema` wins; an+/// unqualified reference resolves inside the source table's own schema;+/// only then do we consider a bare-name match elsewhere — and an ambiguous+/// one is dropped rather than guessed at, because a wrong edge is worse+/// than a missing one.+///+/// A naive first-match-by-name fallback is NOT safe here: a snapshot can+/// hold `tenant_a.users` and `tenant_b.users` at once (the collector+/// flattens every selected schema into one Vec), so it would silently bind+/// foreign keys to the wrong table.+fn find_target<'a>(+ tables: &'a [DocTable],+ source: &DocTable,+ foreign_key: &ForeignKeyInfo,+) -> Option<&'a DocTable> {+ if let Some(ref_schema) = foreign_key.ref_schema.as_deref().filter(|s| !s.is_empty()) {+ if let Some(found) = tables+ .iter()+ .find(|t| t.name == foreign_key.ref_table && t.schema.as_deref() == Some(ref_schema))+ {+ return Some(found);+ }+ }++ if let Some(found) =+ tables.iter().find(|t| t.name == foreign_key.ref_table && t.schema == source.schema)+ {+ return Some(found);+ }++ let mut matches = tables.iter().filter(|t| t.name == foreign_key.ref_table);+ let first = matches.next()?;+ if matches.next().is_some() {+ return None;+ }+ Some(first)+}++/// Build the relationship set for a snapshot.+///+/// Foreign keys pointing at tables outside the collected set are dropped —+/// the target may live in a schema the user did not select, and a dangling+/// edge renders as a relationship to nothing.+pub fn build_relationships(tables: &[DocTable]) -> Vec<Relationship> {+ let mut seen: HashSet<String> = HashSet::new();+ let mut relationships = Vec::new();++ for source in tables {+ for foreign_key in &source.foreign_keys {+ let Some(target) = find_target(tables, source, foreign_key) else { continue };++ if !source.columns.iter().any(|c| c.name == foreign_key.column) {+ continue;+ }++ let id = relationship_id(source, foreign_key);+ if !seen.insert(id.clone()) {+ continue;+ }++ relationships.push(Relationship {+ id,+ name: (!foreign_key.name.is_empty()).then(|| foreign_key.name.clone()),+ from: FieldRef {+ schema: source.schema.clone(),+ table: source.name.clone(),+ column: foreign_key.column.clone(),+ },+ to: FieldRef {+ schema: target.schema.clone(),+ table: target.name.clone(),+ column: foreign_key.ref_column.clone(),+ },+ cardinality: cardinality_for(source, foreign_key),+ on_update: foreign_key.on_update.clone(),+ on_delete: foreign_key.on_delete.clone(),+ });+ }+ }++ relationships+}+```++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::relations`+Expected: PASS, 7 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): infer relationship cardinality from foreign keys"+```++---++## Task 3: OKLCH hue to sRGB hex++**Files:**+- Create: `crates/dbx-core/src/docs/color.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Produces: `pub fn hue_to_hex(hue: u16) -> String`++DBML's `TableGroup [color: #rrggbb]` needs hex, but groups store a hue. Convert at the theme-neutral lightness `L = 0.55`, `C = 0.15` — the light-theme `--group-c` from the spec — so an exported DBML file opened in dbdocs looks like DBX's light theme.++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/color.rs` with only this test module:++```rust+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn produces_a_six_digit_lowercase_hex_string() {+ let hex = hue_to_hex(28);+ assert_eq!(hex.len(), 7, "got {hex}");+ assert!(hex.starts_with('#'), "got {hex}");+ assert!(hex[1..].chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()), "got {hex}");+ }++ #[test]+ fn hue_28_is_a_warm_orange_red() {+ // Sanity check against the group palette: red channel dominates.+ let hex = hue_to_hex(28);+ let r = u8::from_str_radix(&hex[1..3], 16).unwrap();+ let g = u8::from_str_radix(&hex[3..5], 16).unwrap();+ let b = u8::from_str_radix(&hex[5..7], 16).unwrap();+ assert!(r > g && g > b, "expected r > g > b, got {hex}");+ }++ #[test]+ fn hue_148_is_green_dominant() {+ let hex = hue_to_hex(148);+ let r = u8::from_str_radix(&hex[1..3], 16).unwrap();+ let g = u8::from_str_radix(&hex[3..5], 16).unwrap();+ assert!(g > r, "expected green to dominate, got {hex}");+ }++ #[test]+ fn every_hue_is_in_range_and_never_panics() {+ for hue in 0..=359u16 {+ let hex = hue_to_hex(hue);+ assert_eq!(hex.len(), 7, "hue {hue} produced {hex}");+ }+ }++ #[test]+ fn hue_wraps_past_360() {+ assert_eq!(hue_to_hex(0), hue_to_hex(360));+ assert_eq!(hue_to_hex(28), hue_to_hex(388));+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++Add `pub mod color;` and `pub use color::hue_to_hex;` to `crates/dbx-core/src/docs/mod.rs`.++Run: `cargo test -p dbx-core docs::color`+Expected: FAIL — `cannot find function hue_to_hex`.++- [ ] **Step 3: Write the implementation**++At the top of `crates/dbx-core/src/docs/color.rs`:++```rust+/// Lightness and chroma of the light-theme `--group-c` token. Only hue+/// varies per group, which is what guarantees legible contrast.+const GROUP_LIGHTNESS: f64 = 0.55;+const GROUP_CHROMA: f64 = 0.15;++fn linear_to_srgb(channel: f64) -> f64 {+ if channel <= 0.003_130_8 {+ 12.92 * channel+ } else {+ 1.055 * channel.powf(1.0 / 2.4) - 0.055+ }+}++fn to_byte(channel: f64) -> u8 {+ (linear_to_srgb(channel).clamp(0.0, 1.0) * 255.0).round() as u8+}++/// Convert a group hue to the sRGB hex DBML expects.+///+/// OKLCH -> OKLab -> LMS -> linear sRGB -> gamma-encoded sRGB.+/// Coefficients are Björn Ottosson's published OKLab matrices.+pub fn hue_to_hex(hue: u16) -> String {+ let radians = f64::from(hue % 360) * std::f64::consts::PI / 180.0;+ let a = GROUP_CHROMA * radians.cos();+ let b = GROUP_CHROMA * radians.sin();++ let l_ = GROUP_LIGHTNESS + 0.396_337_777_4 * a + 0.215_803_757_3 * b;+ let m_ = GROUP_LIGHTNESS - 0.105_561_345_8 * a - 0.063_854_172_8 * b;+ let s_ = GROUP_LIGHTNESS - 0.089_484_177_5 * a - 1.291_485_548_0 * b;++ let l = l_ * l_ * l_;+ let m = m_ * m_ * m_;+ let s = s_ * s_ * s_;++ let red = 4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s;+ let green = -1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s;+ let blue = -0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701_0 * s;++ format!("#{:02x}{:02x}{:02x}", to_byte(red), to_byte(green), to_byte(blue))+}+```++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::color`+Expected: PASS, 5 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): convert group hue to sRGB hex for DBML"+```++---++## Task 4: DBML lexical primitives++**Files:**+- Create: `crates/dbx-core/src/docs/dbml.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Produces (crate-internal): `fn quote_identifier(&str) -> String`, `fn render_note(&str) -> String`, `fn render_default(&ColumnInfo) -> Option<String>`, `fn render_type(&ColumnInfo) -> String`++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/dbml.rs` with only this test module:++```rust+#[cfg(test)]+mod tests {+ use super::*;+ use crate::types::ColumnInfo;++ fn col(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo { name: name.to_string(), data_type: data_type.to_string(), ..ColumnInfo::default() }+ }++ #[test]+ fn plain_identifiers_are_not_quoted() {+ assert_eq!(quote_identifier("orders"), "orders");+ assert_eq!(quote_identifier("order_items"), "order_items");+ assert_eq!(quote_identifier("_private"), "_private");+ assert_eq!(quote_identifier("t2"), "t2");+ }++ #[test]+ fn irregular_identifiers_are_quoted() {+ assert_eq!(quote_identifier("order items"), "\"order items\"");+ assert_eq!(quote_identifier("2fast"), "\"2fast\"");+ assert_eq!(quote_identifier("user-profile"), "\"user-profile\"");+ assert_eq!(quote_identifier(""), "\"\"");+ }++ #[test]+ fn embedded_double_quotes_are_escaped() {+ assert_eq!(quote_identifier("we\"ird"), "\"we\\\"ird\"");+ }++ #[test]+ fn notes_always_use_triple_quotes_so_apostrophes_are_safe() {+ assert_eq!(render_note("Bob's orders"), "'''Bob's orders'''");+ }++ #[test]+ fn notes_escape_a_literal_triple_quote() {+ assert_eq!(render_note("a ''' b"), "'''a \\''' b'''");+ }++ #[test]+ fn multiline_notes_are_preserved() {+ assert_eq!(render_note("line one\nline two"), "'''line one\nline two'''");+ }++ #[test]+ fn expression_defaults_use_backticks_and_literals_use_quotes() {+ let mut expression = col("created_at", "timestamptz");+ expression.column_default = Some("now()".to_string());+ assert_eq!(render_default(&expression).as_deref(), Some("default: `now()`"));++ let mut sequence = col("id", "integer");+ sequence.column_default = Some("nextval('orders_id_seq'::regclass)".to_string());+ assert_eq!(render_default(&sequence).as_deref(), Some("default: `nextval('orders_id_seq'::regclass)`"));++ let mut literal = col("status", "text");+ literal.column_default = Some("'pending'".to_string());+ assert_eq!(render_default(&literal).as_deref(), Some("default: 'pending'"));++ let mut number = col("qty", "integer");+ number.column_default = Some("0".to_string());+ assert_eq!(render_default(&number).as_deref(), Some("default: 0"));++ let mut boolean = col("active", "boolean");+ boolean.column_default = Some("true".to_string());+ assert_eq!(render_default(&boolean).as_deref(), Some("default: true"));++ assert_eq!(render_default(&col("plain", "text")), None);+ }++ #[test]+ fn types_pass_through_verbatim_when_already_parameterised() {+ assert_eq!(render_type(&col("total", "numeric(10,2)")), "numeric(10,2)");+ assert_eq!(render_type(&col("meta", "jsonb")), "jsonb");+ assert_eq!(render_type(&col("at", "timestamp with time zone")), "timestamp with time zone");+ }++ #[test]+ fn bare_types_are_reconstructed_from_precision_metadata() {+ let mut varchar = col("email", "character varying");+ varchar.character_maximum_length = Some(255);+ assert_eq!(render_type(&varchar), "character varying(255)");++ let mut decimal = col("total", "numeric");+ decimal.numeric_precision = Some(10);+ decimal.numeric_scale = Some(2);+ assert_eq!(render_type(&decimal), "numeric(10,2)");++ let mut integer = col("count", "numeric");+ integer.numeric_precision = Some(8);+ integer.numeric_scale = Some(0);+ assert_eq!(render_type(&integer), "numeric(8)");+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++Add `pub mod dbml;` to `crates/dbx-core/src/docs/mod.rs`.++Run: `cargo test -p dbx-core docs::dbml`+Expected: FAIL — `cannot find function quote_identifier`.++- [ ] **Step 3: Write the implementation**++At the top of `crates/dbx-core/src/docs/dbml.rs`:++```rust+use crate::types::ColumnInfo;++/// DBML accepts bare identifiers matching `[A-Za-z_][A-Za-z0-9_]*`;+/// everything else needs double quotes.+pub(crate) fn quote_identifier(value: &str) -> String {+ let plain = !value.is_empty()+ && value.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')+ && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');++ if plain {+ value.to_string()+ } else {+ format!("\"{}\"", value.replace('"', "\\\""))+ }+}++/// Notes always use triple quotes so an apostrophe in prose can never break+/// the file.+///+/// Two things need escaping. A literal `'''` inside the prose, obviously —+/// and also a SINGLE trailing quote, which is subtler: the note `he said '`+/// would otherwise render as `'''he said ''''`, four quotes in a row, and a+/// parser scanning for the closing `'''` would close early and strand the+/// fourth. DBML honours `\'` inside triple quotes.+pub(crate) fn render_note(value: &str) -> String {+ let escaped = value.replace("'''", "\\'''");+ let escaped = match escaped.strip_suffix('\'') {+ Some(head) => format!("{head}\\'"),+ None => escaped,+ };+ format!("'''{escaped}'''")+}++fn looks_like_expression(value: &str) -> bool {+ let trimmed = value.trim();+ if trimmed.starts_with('\'') && trimmed.ends_with('\'') && trimmed.len() >= 2 {+ return false;+ }+ if trimmed.parse::<f64>().is_ok() {+ return false;+ }+ if matches!(trimmed.to_ascii_lowercase().as_str(), "true" | "false" | "null") {+ return false;+ }+ true+}++/// `default: …` for a column, or None when it has no default.+/// Expressions go in backticks, literals stay as written.+pub(crate) fn render_default(column: &ColumnInfo) -> Option<String> {+ let value = column.column_default.as_deref()?.trim();+ if value.is_empty() {+ return None;+ }++ if looks_like_expression(value) {+ Some(format!("default: `{value}`"))+ } else {+ Some(format!("default: {value}"))+ }+}++/// DBML does not validate type names, so native types pass through intact.+/// Precision is reconstructed only when the engine reported a bare type.+pub(crate) fn render_type(column: &ColumnInfo) -> String {+ let base = column.data_type.trim();+ if base.contains('(') {+ return base.to_string();+ }++ if let Some(length) = column.character_maximum_length.filter(|value| *value > 0) {+ return format!("{base}({length})");+ }++ if let Some(precision) = column.numeric_precision.filter(|value| *value > 0) {+ return match column.numeric_scale {+ Some(scale) if scale > 0 => format!("{base}({precision},{scale})"),+ _ => format!("{base}({precision})"),+ };+ }++ base.to_string()+}+```++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::dbml`+Expected: PASS, 9 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): add DBML lexical primitives"+```++---++## Task 5: DBML table blocks++**Files:**+- Modify: `crates/dbx-core/src/docs/dbml.rs`++**Interfaces:**+- Consumes: Task 4 primitives, `DocTable`/`ColumnNote` from Task 1+- Produces (crate-internal): `fn render_table(table: &DocTable, qualify: bool, warnings: &mut Vec<SnapshotWarning>) -> String`++- [ ] **Step 1: Write the failing test**++Append to the `tests` module in `crates/dbx-core/src/docs/dbml.rs`:++```rust+ use crate::docs::{ColumnNote, DocTable, NoteSource, SnapshotWarning, TableKind};+ use crate::types::IndexInfo;+ use std::collections::BTreeMap;++ fn doc_table(name: &str, columns: Vec<ColumnInfo>, indexes: Vec<IndexInfo>) -> DocTable {+ DocTable {+ schema: Some("public".to_string()),+ name: name.to_string(),+ kind: TableKind::Table,+ columns,+ indexes,+ foreign_keys: vec![],+ group_id: None,+ note: None,+ note_source: NoteSource::None,+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ }+ }++ #[test]+ fn renders_a_table_with_columns_and_settings() {+ let mut id = col("id", "integer");+ id.is_primary_key = true;+ id.extra = Some("auto_increment".to_string());++ let mut user_id = col("user_id", "integer");+ user_id.is_nullable = false;++ // ColumnInfo::default() gives is_nullable=false (i.e. NOT NULL), so a+ // genuinely nullable column has to say so explicitly.+ let mut nullable = col("shipped_at", "timestamptz");+ nullable.is_nullable = true;++ let mut table = doc_table("orders", vec![id, user_id, nullable], vec![]);+ table.note = Some("Checkout rows.".to_string());+ table.column_notes.insert(+ "user_id".to_string(),+ ColumnNote { note: "Owning customer".to_string(), source: NoteSource::Local, shadowed: None },+ );++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);++ assert!(out.starts_with("Table orders {\n"), "got:\n{out}");+ assert!(out.contains("id integer [pk, increment]"), "got:\n{out}");+ assert!(out.contains("user_id integer [not null, note: '''Owning customer''']"), "got:\n{out}");+ assert!(out.contains("shipped_at timestamptz\n"), "got:\n{out}");+ assert!(out.contains("Note: '''Checkout rows.'''"), "got:\n{out}");+ assert!(out.ends_with("}\n"), "got:\n{out}");+ }++ #[test]+ fn qualifies_the_table_name_when_requested() {+ let table = doc_table("orders", vec![col("id", "integer")], vec![]);+ let mut warnings = Vec::new();+ assert!(render_table(&table, true, &mut warnings).starts_with("Table public.orders {"));+ }++ #[test]+ fn renders_an_indexes_block() {+ let index = IndexInfo {+ name: "idx_orders_user_placed".to_string(),+ columns: vec!["user_id".to_string(), "placed_at".to_string()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let table = doc_table("orders", vec![col("user_id", "integer")], vec![index]);++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);++ assert!(out.contains("Indexes {"), "got:\n{out}");+ assert!(out.contains("(user_id, placed_at) [name: 'idx_orders_user_placed']"), "got:\n{out}");+ assert!(warnings.is_empty());+ }++ #[test]+ fn a_unique_index_carries_the_unique_setting() {+ let index = IndexInfo {+ name: "uq_orders_ref".to_string(),+ columns: vec!["reference".to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let table = doc_table("orders", vec![col("reference", "text")], vec![index]);+ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);+ assert!(out.contains("(reference) [name: 'uq_orders_ref', unique]"), "got:\n{out}");+ }++ #[test]+ fn the_primary_key_index_is_skipped_because_columns_already_carry_pk() {+ let index = IndexInfo {+ name: "orders_pkey".to_string(),+ columns: vec!["id".to_string()],+ is_unique: true,+ is_primary: true,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let mut id = col("id", "integer");+ id.is_primary_key = true;+ let table = doc_table("orders", vec![id], vec![index]);++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);+ assert!(!out.contains("orders_pkey"), "got:\n{out}");+ }++ #[test]+ fn a_filtered_index_is_omitted_and_warned_about() {+ let index = IndexInfo {+ name: "idx_orders_open".to_string(),+ columns: vec!["status".to_string()],+ is_unique: false,+ is_primary: false,+ filter: Some("status <> 'cancelled'".to_string()),+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let table = doc_table("orders", vec![col("status", "text")], vec![index]);++ let mut warnings = Vec::new();+ let out = render_table(&table, false, &mut warnings);++ assert!(!out.contains("idx_orders_open"), "filtered index must not be emitted, got:\n{out}");+ assert_eq!(warnings.len(), 1);+ match &warnings[0] {+ SnapshotWarning::DbmlOmitted { table, item, reason } => {+ assert_eq!(table, "public.orders");+ assert_eq!(item, "idx_orders_open");+ assert!(reason.contains("filter"), "got {reason}");+ }+ other => panic!("unexpected warning: {other:?}"),+ }+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs::dbml`+Expected: FAIL — `cannot find function render_table`.++- [ ] **Step 3: Write the implementation**++Add to `crates/dbx-core/src/docs/dbml.rs` (extend the existing `use` lines at the top):++```rust+use crate::docs::{DocTable, SnapshotWarning};+use crate::types::IndexInfo;++fn column_settings(column: &ColumnInfo, table: &DocTable) -> Vec<String> {+ let mut settings = Vec::new();++ if column.is_primary_key {+ settings.push("pk".to_string());+ }++ let extra = column.extra.as_deref().unwrap_or("").to_ascii_lowercase();+ if extra.contains("auto_increment") || extra.contains("identity") {+ settings.push("increment".to_string());+ }++ if !column.is_nullable && !column.is_primary_key {+ settings.push("not null".to_string());+ }++ if let Some(default) = render_default(column) {+ settings.push(default);+ }++ if let Some(note) = table.column_notes.get(&column.name) {+ settings.push(format!("note: {}", render_note(¬e.note)));+ } else if let Some(comment) = column.comment.as_deref().filter(|value| !value.trim().is_empty()) {+ settings.push(format!("note: {}", render_note(comment)));+ }++ settings+}++fn render_index(index: &IndexInfo) -> String {+ let columns =+ index.columns.iter().map(|c| quote_identifier(c)).collect::<Vec<_>>().join(", ");++ let mut settings = vec![format!("name: '{}'", index.name.replace('\'', "\\'"))];+ if index.is_unique {+ settings.push("unique".to_string());+ }++ format!(" ({columns}) [{}]\n", settings.join(", "))+}++/// Render one `Table` block.+///+/// The primary-key index is skipped because columns already carry `pk`.+/// Indexes DBML cannot express are skipped and recorded in `warnings`+/// rather than dropped silently.+pub(crate) fn render_table(table: &DocTable, qualify: bool, warnings: &mut Vec<SnapshotWarning>) -> String {+ let name = if qualify {+ match table.schema.as_deref().filter(|s| !s.is_empty()) {+ Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&table.name)),+ None => quote_identifier(&table.name),+ }+ } else {+ quote_identifier(&table.name)+ };++ let mut out = format!("Table {name} {{\n");++ for column in &table.columns {+ let settings = column_settings(column, table);+ let rendered_settings =+ if settings.is_empty() { String::new() } else { format!(" [{}]", settings.join(", ")) };+ out.push_str(&format!(+ " {} {}{}\n",+ quote_identifier(&column.name),+ render_type(column),+ rendered_settings+ ));+ }++ let emittable: Vec<&IndexInfo> = table+ .indexes+ .iter()+ .filter(|index| {+ if index.is_primary {+ return false;+ }+ if index.filter.as_deref().is_some_and(|f| !f.trim().is_empty()) {+ warnings.push(SnapshotWarning::DbmlOmitted {+ table: table.qualified_name(),+ item: index.name.clone(),+ reason: "partial index filter has no DBML equivalent".to_string(),+ });+ return false;+ }+ if index.included_columns.as_ref().is_some_and(|columns| !columns.is_empty()) {+ warnings.push(SnapshotWarning::DbmlOmitted {+ table: table.qualified_name(),+ item: index.name.clone(),+ reason: "included columns have no DBML equivalent".to_string(),+ });+ return false;+ }+ !index.columns.is_empty()+ })+ .collect();++ if !emittable.is_empty() {+ out.push_str("\n Indexes {\n");+ for index in emittable {+ out.push_str(&render_index(index));+ }+ out.push_str(" }\n");+ }++ if let Some(note) = table.note.as_deref().filter(|value| !value.trim().is_empty()) {+ out.push_str(&format!("\n Note: {}\n", render_note(note)));+ }++ out.push_str("}\n");+ out+}+```++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::dbml`+Expected: PASS, 15 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): render DBML table blocks"+```++---++## Task 6: DBML refs, enums and table groups++**Files:**+- Modify: `crates/dbx-core/src/docs/dbml.rs`++**Interfaces:**+- Produces (crate-internal): `fn render_ref(&Relationship, bool) -> String`, `fn render_enum(&DocEnum, bool) -> String`, `fn render_group(&TableGroup, &[&DocTable], bool) -> String`++- [ ] **Step 1: Write the failing test**++Append to the `tests` module in `crates/dbx-core/src/docs/dbml.rs`:++```rust+ use crate::docs::{Cardinality, DocEnum, FieldRef, Relationship, TableGroup};++ fn relationship(cardinality: Cardinality) -> Relationship {+ Relationship {+ id: "r1".to_string(),+ name: Some("fk_orders_user".to_string()),+ from: FieldRef {+ schema: Some("public".to_string()),+ table: "orders".to_string(),+ column: "user_id".to_string(),+ },+ to: FieldRef {+ schema: Some("public".to_string()),+ table: "users".to_string(),+ column: "id".to_string(),+ },+ cardinality,+ on_update: None,+ on_delete: Some("CASCADE".to_string()),+ }+ }++ #[test]+ fn many_to_one_uses_the_gt_operator() {+ let out = render_ref(&relationship(Cardinality::ManyToOne), false);+ assert_eq!(out, "Ref fk_orders_user: orders.user_id > users.id [delete: cascade]\n");+ }++ #[test]+ fn one_to_one_uses_the_dash_operator() {+ let out = render_ref(&relationship(Cardinality::OneToOne), false);+ assert!(out.contains("orders.user_id - users.id"), "got {out}");+ }++ #[test]+ fn refs_qualify_both_sides_together() {+ let out = render_ref(&relationship(Cardinality::ManyToOne), true);+ assert!(out.contains("public.orders.user_id > public.users.id"), "got {out}");+ }++ #[test]+ fn referential_actions_are_lowercased_and_both_emitted() {+ let mut rel = relationship(Cardinality::ManyToOne);+ rel.on_update = Some("NO ACTION".to_string());+ rel.on_delete = Some("RESTRICT".to_string());+ let out = render_ref(&rel, false);+ assert!(out.contains("[update: no action, delete: restrict]"), "got {out}");+ }++ #[test]+ fn an_unnamed_ref_omits_the_name() {+ let mut rel = relationship(Cardinality::ManyToOne);+ rel.name = None;+ assert!(render_ref(&rel, false).starts_with("Ref: orders.user_id"), "got {}", render_ref(&rel, false));+ }++ #[test]+ fn renders_an_enum_block() {+ let value = DocEnum {+ schema: Some("public".to_string()),+ name: "order_status".to_string(),+ values: vec!["pending".to_string(), "shipped".to_string()],+ note: None,+ synthesized: false,+ };+ let out = render_enum(&value, false);+ assert_eq!(out, "Enum order_status {\n pending\n shipped\n}\n");+ }++ #[test]+ fn renders_a_table_group_with_colour_and_note() {+ let group = TableGroup {+ id: "order-management".to_string(),+ name: "Order Management".to_string(),+ hue: 28,+ note: Some("Checkout to carrier handoff.".to_string()),+ };+ let orders = doc_table("orders", vec![], vec![]);+ let items = doc_table("order_items", vec![], vec![]);++ let out = render_group(&group, &[&orders, &items], false);++ assert!(out.starts_with("TableGroup \"Order Management\" [color: #"), "got:\n{out}");+ assert!(out.contains("\n orders\n"), "got:\n{out}");+ assert!(out.contains("\n order_items\n"), "got:\n{out}");+ assert!(out.contains("Note: '''Checkout to carrier handoff.'''"), "got:\n{out}");+ }++ #[test]+ fn an_empty_group_renders_nothing() {+ let group = TableGroup {+ id: "empty".to_string(),+ name: "Empty".to_string(),+ hue: 0,+ note: None,+ };+ assert_eq!(render_group(&group, &[], false), "");+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs::dbml`+Expected: FAIL — `cannot find function render_ref`.++- [ ] **Step 3: Write the implementation**++Add to `crates/dbx-core/src/docs/dbml.rs`. Extend the top `use crate::docs::{…}` line so it reads:++```rust+use crate::docs::{Cardinality, DocEnum, DocTable, FieldRef, Relationship, SnapshotWarning, TableGroup};+use crate::docs::color::hue_to_hex;+```++```rust+fn qualified_field(field: &FieldRef, qualify: bool) -> String {+ let table = if qualify {+ match field.schema.as_deref().filter(|s| !s.is_empty()) {+ Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&field.table)),+ None => quote_identifier(&field.table),+ }+ } else {+ quote_identifier(&field.table)+ };+ format!("{table}.{}", quote_identifier(&field.column))+}++/// One `Ref` line. `>` is many-to-one, `-` is one-to-one.+pub(crate) fn render_ref(relationship: &Relationship, qualify: bool) -> String {+ let operator = match relationship.cardinality {+ Cardinality::ManyToOne => ">",+ Cardinality::OneToOne => "-",+ };++ let mut actions = Vec::new();+ if let Some(update) = relationship.on_update.as_deref().filter(|v| !v.trim().is_empty()) {+ actions.push(format!("update: {}", update.to_lowercase()));+ }+ if let Some(delete) = relationship.on_delete.as_deref().filter(|v| !v.trim().is_empty()) {+ actions.push(format!("delete: {}", delete.to_lowercase()));+ }+ let settings = if actions.is_empty() { String::new() } else { format!(" [{}]", actions.join(", ")) };++ let label = match relationship.name.as_deref().filter(|v| !v.trim().is_empty()) {+ Some(name) => format!("Ref {}", quote_identifier(name)),+ None => "Ref".to_string(),+ };++ format!(+ "{label}: {} {operator} {}{settings}\n",+ qualified_field(&relationship.from, qualify),+ qualified_field(&relationship.to, qualify)+ )+}++pub(crate) fn render_enum(value: &DocEnum, qualify: bool) -> String {+ let name = if qualify {+ match value.schema.as_deref().filter(|s| !s.is_empty()) {+ Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&value.name)),+ None => quote_identifier(&value.name),+ }+ } else {+ quote_identifier(&value.name)+ };++ let mut out = format!("Enum {name} {{\n");+ for variant in &value.values {+ out.push_str(&format!(" {}\n", quote_identifier(variant)));+ }+ if let Some(note) = value.note.as_deref().filter(|v| !v.trim().is_empty()) {+ out.push_str(&format!("\n Note: {}\n", render_note(note)));+ }+ out.push_str("}\n");+ out+}++/// A `TableGroup` block. Returns an empty string when the group has no+/// members, since DBML rejects an empty group body.+pub(crate) fn render_group(group: &TableGroup, members: &[&DocTable], qualify: bool) -> String {+ if members.is_empty() {+ return String::new();+ }++ let mut out =+ format!("TableGroup {} [color: {}] {{\n", quote_identifier(&group.name), hue_to_hex(group.hue));++ for member in members {+ let name = if qualify {+ match member.schema.as_deref().filter(|s| !s.is_empty()) {+ Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&member.name)),+ None => quote_identifier(&member.name),+ }+ } else {+ quote_identifier(&member.name)+ };+ out.push_str(&format!(" {name}\n"));+ }++ if let Some(note) = group.note.as_deref().filter(|v| !v.trim().is_empty()) {+ out.push_str(&format!("\n Note: {}\n", render_note(note)));+ }++ out.push_str("}\n");+ out+}+```++Note: `quote_identifier("Order Management")` yields `"Order Management"` with quotes, which is what the test asserts.++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::dbml`+Expected: PASS, 23 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): render DBML refs, enums and table groups"+```++---++## Task 7: Full DBML document assembly++**Files:**+- Modify: `crates/dbx-core/src/docs/dbml.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Produces: `pub fn to_dbml(snapshot: &SchemaSnapshot) -> DbmlOutput` where `pub struct DbmlOutput { pub text: String, pub warnings: Vec<SnapshotWarning> }`++Schema qualification is decided here: bare names for a single-schema snapshot (it reads better), fully qualified when more than one schema is present.++- [ ] **Step 1: Write the failing test**++Append to the `tests` module in `crates/dbx-core/src/docs/dbml.rs`:++```rust+ use crate::docs::{ProjectMeta, SchemaSnapshot};++ fn snapshot(tables: Vec<DocTable>, schemas: Vec<&str>) -> SchemaSnapshot {+ SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: "Ecommerce".to_string(),+ database_type: "PostgreSQL".to_string(),+ database: Some("shop".to_string()),+ schemas: schemas.into_iter().map(str::to_string).collect(),+ generated_at: "2026-08-02T12:00:00Z".to_string(),+ note: Some("Storefront database.".to_string()),+ },+ tables,+ relationships: vec![],+ groups: vec![],+ enums: vec![],+ warnings: vec![],+ }+ }++ #[test]+ fn emits_a_project_block_first() {+ let out = to_dbml(&snapshot(vec![], vec!["public"]));+ assert!(out.text.starts_with("Project Ecommerce {\n"), "got:\n{}", out.text);+ assert!(out.text.contains("database_type: 'PostgreSQL'"), "got:\n{}", out.text);+ assert!(out.text.contains("Note: '''Storefront database.'''"), "got:\n{}", out.text);+ }++ #[test]+ fn a_single_schema_snapshot_uses_bare_table_names() {+ let out = to_dbml(&snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]));+ assert!(out.text.contains("Table orders {"), "got:\n{}", out.text);+ assert!(!out.text.contains("Table public.orders"), "got:\n{}", out.text);+ }++ #[test]+ fn a_multi_schema_snapshot_qualifies_every_table() {+ let mut analytics = doc_table("daily_sales", vec![col("id", "integer")], vec![]);+ analytics.schema = Some("analytics".to_string());++ let out = to_dbml(&snapshot(+ vec![doc_table("orders", vec![col("id", "integer")], vec![]), analytics],+ vec!["public", "analytics"],+ ));++ assert!(out.text.contains("Table public.orders {"), "got:\n{}", out.text);+ assert!(out.text.contains("Table analytics.daily_sales {"), "got:\n{}", out.text);+ }++ #[test]+ fn sections_appear_in_order_project_enums_groups_tables_refs() {+ let mut snap = snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]);+ snap.enums.push(DocEnum {+ schema: Some("public".to_string()),+ name: "order_status".to_string(),+ values: vec!["pending".to_string()],+ note: None,+ synthesized: false,+ });+ snap.groups.push(TableGroup {+ id: "order-management".to_string(),+ name: "Order Management".to_string(),+ hue: 28,+ note: None,+ });+ snap.tables[0].group_id = Some("order-management".to_string());+ snap.relationships.push(relationship(Cardinality::ManyToOne));++ let text = to_dbml(&snap).text;+ let project = text.find("Project ").expect("project");+ let enum_at = text.find("Enum ").expect("enum");+ let group = text.find("TableGroup ").expect("group");+ let table = text.find("Table orders").expect("table");+ let reference = text.find("Ref ").expect("ref");++ assert!(project < enum_at, "project before enums:\n{text}");+ assert!(enum_at < group, "enums before groups:\n{text}");+ assert!(group < table, "groups before tables:\n{text}");+ assert!(table < reference, "tables before refs:\n{text}");+ }++ #[test]+ fn warnings_from_table_rendering_reach_the_output() {+ let index = IndexInfo {+ name: "idx_partial".to_string(),+ columns: vec!["status".to_string()],+ is_unique: false,+ is_primary: false,+ filter: Some("status <> 'x'".to_string()),+ index_type: None,+ included_columns: None,+ comment: None,+ };+ let out = to_dbml(&snapshot(vec![doc_table("orders", vec![col("status", "text")], vec![index])], vec!["public"]));+ assert_eq!(out.warnings.len(), 1);+ }++ #[test]+ fn a_group_referencing_a_missing_table_is_skipped() {+ let mut snap = snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]);+ snap.groups.push(TableGroup {+ id: "ghost".to_string(),+ name: "Ghost".to_string(),+ hue: 200,+ note: None,+ });+ assert!(!to_dbml(&snap).text.contains("Ghost"), "got:\n{}", to_dbml(&snap).text);+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-core docs::dbml`+Expected: FAIL — `cannot find function to_dbml`.++- [ ] **Step 3: Write the implementation**++Add to `crates/dbx-core/src/docs/dbml.rs` (extend the `use crate::docs::{…}` line with `SchemaSnapshot`):++```rust+/// DBML text plus every construct that could not be represented in it.+#[derive(Debug, Clone)]+pub struct DbmlOutput {+ pub text: String,+ pub warnings: Vec<SnapshotWarning>,+}++fn render_project(snapshot: &SchemaSnapshot) -> String {+ let mut out = format!("Project {} {{\n", quote_identifier(&snapshot.project.name));+ out.push_str(&format!(+ " database_type: '{}'\n",+ snapshot.project.database_type.replace('\'', "\\'")+ ));+ if let Some(note) = snapshot.project.note.as_deref().filter(|v| !v.trim().is_empty()) {+ out.push_str(&format!(" Note: {}\n", render_note(note)));+ }+ out.push_str("}\n");+ out+}++/// Serialize a snapshot to DBML.+///+/// DBML is an interchange format, not a backup: check constraints, partial+/// indexes, included columns, collations and generated columns have no+/// representation. Each omission is reported in `warnings` so the HTML+/// documentation — which *is* the complete record — can mark it.+pub fn to_dbml(snapshot: &SchemaSnapshot) -> DbmlOutput {+ let qualify = snapshot.project.schemas.len() > 1;+ let mut warnings = Vec::new();+ let mut sections: Vec<String> = vec![render_project(snapshot)];++ for value in &snapshot.enums {+ sections.push(render_enum(value, qualify));+ }++ for group in &snapshot.groups {+ let members: Vec<&DocTable> = snapshot+ .tables+ .iter()+ .filter(|table| table.group_id.as_deref() == Some(group.id.as_str()))+ .collect();+ let rendered = render_group(group, &members, qualify);+ if !rendered.is_empty() {+ sections.push(rendered);+ }+ }++ for table in &snapshot.tables {+ sections.push(render_table(table, qualify, &mut warnings));+ }++ if !snapshot.relationships.is_empty() {+ let refs: String =+ snapshot.relationships.iter().map(|rel| render_ref(rel, qualify)).collect();+ sections.push(refs);+ }++ DbmlOutput { text: sections.join("\n"), warnings }+}+```++Add to `crates/dbx-core/src/docs/mod.rs`:++```rust+pub use dbml::{to_dbml, DbmlOutput};+```++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::dbml`+Expected: PASS, 29 tests.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/+git commit -m "feat(docs): assemble complete DBML documents"+```++---++## Task 8: Snapshot collector++**Files:**+- Create: `crates/dbx-core/src/docs/collector.rs`+- Modify: `crates/dbx-core/src/docs/mod.rs`++**Interfaces:**+- Produces:+ - `pub struct CollectOptions { pub database: String, pub schemas: Vec<String>, pub tables: Vec<String>, pub project_name: String }`+ - `pub struct CollectProgress { pub completed: usize, pub total: usize, pub current: String }`+ - `pub async fn collect_snapshot(state: &AppState, connection: &ConnectionConfig, options: &CollectOptions, progress: &(dyn Fn(CollectProgress) + Send + Sync), cancel: &AtomicBool) -> Result<SchemaSnapshot, String>`++**Verified metadata API** (`crates/dbx-core/src/schema.rs` — note this is a 357 KB module file paired with the `schema/` directory, and `db::*` re-exports `crate::types::*`, so `db::ColumnInfo` and `crate::types::ColumnInfo` are the same type):++```rust+schema::list_schemas_core(state, connection_id, database) -> Vec<String>+schema::list_tables_core(state, connection_id, database, schema,+ filter, limit, offset, object_types, table_name_filter) -> Vec<db::TableInfo>+schema::get_columns_core(state, connection_id, database, schema, table) -> Vec<db::ColumnInfo>+schema::list_indexes_core(state, connection_id, database, schema, table) -> Vec<db::IndexInfo>+schema::list_foreign_keys_core(state, connection_id, database, schema, table) -> Vec<db::ForeignKeyInfo>+```++These take `&AppState` and a connection id — **not** a pool. They also wrap `retry_metadata_connection` internally, so the collector inherits reconnect-on-drop for free and must not add its own retry layer.++Fan-out is bounded at 8 concurrent table fetches. This is the naive-but-correct version by design: it works for every relational engine on day one because it reuses providers already proven against all of them. Per-engine bulk `information_schema` sweeps come later, only where a benchmark justifies them.++- [ ] **Step 1: Write the failing test**++Create `crates/dbx-core/src/docs/collector.rs` with only this test module. These tests cover the pure helpers; end-to-end collection is covered by the live test in Task 12.++```rust+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn table_kind_maps_from_the_engine_reported_type() {+ assert_eq!(table_kind_from("TABLE"), TableKind::Table);+ assert_eq!(table_kind_from("BASE TABLE"), TableKind::Table);+ assert_eq!(table_kind_from("VIEW"), TableKind::View);+ assert_eq!(table_kind_from("MATERIALIZED VIEW"), TableKind::MaterializedView);+ assert_eq!(table_kind_from("materialized_view"), TableKind::MaterializedView);+ assert_eq!(table_kind_from("something else"), TableKind::Table);+ }++ #[test]+ fn table_filter_is_empty_means_include_everything() {+ let options = CollectOptions {+ database: "shop".to_string(),+ schemas: vec!["public".to_string()],+ tables: vec![],+ project_name: "Ecommerce".to_string(),+ };+ assert!(options.includes_table("public", "orders"));+ assert!(options.includes_table("public", "anything"));+ }++ #[test]+ fn table_filter_matches_bare_and_qualified_names() {+ let options = CollectOptions {+ database: "shop".to_string(),+ schemas: vec!["public".to_string()],+ tables: vec!["orders".to_string(), "analytics.daily_sales".to_string()],+ project_name: "Ecommerce".to_string(),+ };+ assert!(options.includes_table("public", "orders"));+ assert!(options.includes_table("analytics", "daily_sales"));+ assert!(!options.includes_table("public", "users"));+ assert!(!options.includes_table("public", "daily_sales"));+ }++ #[test]+ fn synthesises_a_named_enum_from_an_inline_enum_column() {+ let mut column = crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "enum".to_string(),+ ..Default::default()+ };+ column.enum_values = Some(vec!["pending".to_string(), "shipped".to_string()]);++ let synthesized = synthesize_enum(Some("public"), "orders", &column).expect("enum");++ assert_eq!(synthesized.name, "orders_status");+ assert_eq!(synthesized.values, vec!["pending", "shipped"]);+ assert!(synthesized.synthesized);+ }++ #[test]+ fn a_column_without_enum_values_synthesises_nothing() {+ let column = crate::types::ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ ..Default::default()+ };+ assert!(synthesize_enum(Some("public"), "orders", &column).is_none());+ }+}+```++- [ ] **Step 2: Run the test to verify it fails**++Add `pub mod collector;` and `pub use collector::{collect_snapshot, CollectOptions, CollectProgress};` to `crates/dbx-core/src/docs/mod.rs`.++Run: `cargo test -p dbx-core docs::collector`+Expected: FAIL — `cannot find function table_kind_from`.++- [ ] **Step 3: Write the implementation**++At the top of `crates/dbx-core/src/docs/collector.rs`:++```rust+use std::collections::BTreeMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;++use futures::stream::{self, StreamExt};+use tokio::sync::Semaphore;++use crate::docs::{+ build_relationships, DocEnum, DocTable, NoteSource, ProjectMeta, SchemaSnapshot, SnapshotWarning, TableKind,+};+use crate::models::connection::ConnectionConfig;+use crate::schema;+use crate::state::AppState; // confirm the real path with: grep -rn "pub struct AppState" crates/dbx-core/src+use crate::table_structure_sql::dialect::capabilities_for;+use crate::types::ColumnInfo;++/// Concurrent per-table metadata fetches. Bounded so documenting a large+/// schema cannot starve the connection pool the UI is also using.+const MAX_CONCURRENT_TABLES: usize = 8;++#[derive(Debug, Clone)]+pub struct CollectOptions {+ pub database: String,+ pub schemas: Vec<String>,+ /// Empty means every table. Entries may be bare (`orders`) or+ /// qualified (`analytics.daily_sales`).+ pub tables: Vec<String>,+ pub project_name: String,+}++impl CollectOptions {+ pub fn includes_table(&self, schema: &str, table: &str) -> bool {+ if self.tables.is_empty() {+ return true;+ }+ let qualified = format!("{schema}.{table}");+ self.tables.iter().any(|wanted| wanted == table || wanted == &qualified)+ }+}++#[derive(Debug, Clone)]+pub struct CollectProgress {+ pub completed: usize,+ pub total: usize,+ pub current: String,+}++fn table_kind_from(table_type: &str) -> TableKind {+ let normalized = table_type.trim().to_ascii_uppercase().replace('_', " ");+ match normalized.as_str() {+ "VIEW" => TableKind::View,+ "MATERIALIZED VIEW" => TableKind::MaterializedView,+ _ => TableKind::Table,+ }+}++/// MySQL reports `ENUM('a','b')` inline rather than as a named type.+/// DBML needs a named enum, so synthesize one per table+column.+fn synthesize_enum(schema: Option<&str>, table: &str, column: &ColumnInfo) -> Option<DocEnum> {+ let values = column.enum_values.as_ref().filter(|values| !values.is_empty())?;+ Some(DocEnum {+ schema: schema.map(ToOwned::to_owned),+ name: format!("{table}_{}", column.name),+ values: values.clone(),+ note: None,+ synthesized: true,+ })+}++fn cancelled(cancel: &AtomicBool) -> bool {+ cancel.load(Ordering::Relaxed)+}++/// Collect a documentation snapshot.+///+/// A per-table failure is recorded as a `TableSkipped` warning and does not+/// abort the run — a permissions gap on one table must not kill a+/// 400-table documentation build.+pub async fn collect_snapshot(+ state: &AppState,+ connection: &ConnectionConfig,+ options: &CollectOptions,+ progress: &(dyn Fn(CollectProgress) + Send + Sync),+ cancel: &AtomicBool,+) -> Result<SchemaSnapshot, String> {+ let mut warnings: Vec<SnapshotWarning> = Vec::new();+ let engine = format!("{:?}", connection.db_type);+ let connection_id = connection.id.as_str();++ if !capabilities_for(connection.db_type).comment {+ warnings.push(SnapshotWarning::CommentsUnsupported { engine: engine.clone() });+ }++ let schemas = if options.schemas.is_empty() {+ schema::list_schemas_core(state, connection_id, &options.database).await.unwrap_or_default()+ } else {+ options.schemas.clone()+ };+ let effective_schemas = if schemas.is_empty() { vec![String::new()] } else { schemas };++ // Enumerate every table first so progress has a real total.+ let mut targets: Vec<(String, crate::types::TableInfo)> = Vec::new();+ for schema_name in &effective_schemas {+ match schema::list_tables_core(state, connection_id, &options.database, schema_name, None, None, None, None, None)+ .await+ {+ Ok(tables) => {+ for info in tables {+ if options.includes_table(schema_name, &info.name) {+ targets.push((schema_name.clone(), info));+ }+ }+ }+ Err(error) => warnings.push(SnapshotWarning::TableSkipped {+ table: format!("{schema_name}.*"),+ reason: error,+ }),+ }+ }++ let total = targets.len();+ let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_TABLES));++ let collected: Vec<Result<DocTable, SnapshotWarning>> = stream::iter(targets.into_iter().enumerate())+ .map(|(index, (schema_name, info))| {+ let semaphore = Arc::clone(&semaphore);+ let database = options.database.clone();+ async move {+ let _permit = semaphore.acquire().await.map_err(|_| SnapshotWarning::TableSkipped {+ table: info.name.clone(),+ reason: "collection cancelled".to_string(),+ })?;++ if cancelled(cancel) {+ return Err(SnapshotWarning::TableSkipped {+ table: info.name.clone(),+ reason: "cancelled".to_string(),+ });+ }++ progress(CollectProgress {+ completed: index,+ total,+ current: format!("{schema_name}.{}", info.name),+ });++ let columns = schema::get_columns_core(state, connection_id, &database, &schema_name, &info.name)+ .await+ .map_err(|error| SnapshotWarning::TableSkipped {+ table: format!("{schema_name}.{}", info.name),+ reason: error,+ })?;++ // Indexes and foreign keys degrade to empty rather than failing+ // the table: ClickHouse and friends have no FK metadata at all.+ let indexes = schema::list_indexes_core(state, connection_id, &database, &schema_name, &info.name)+ .await+ .unwrap_or_default();+ let foreign_keys =+ schema::list_foreign_keys_core(state, connection_id, &database, &schema_name, &info.name)+ .await+ .unwrap_or_default();++ Ok(DocTable {+ schema: (!schema_name.is_empty()).then(|| schema_name.clone()),+ name: info.name.clone(),+ kind: table_kind_from(&info.table_type),+ columns,+ indexes,+ foreign_keys,+ group_id: None,+ note: info.comment.clone().filter(|value| !value.trim().is_empty()),+ note_source: if info.comment.as_deref().is_some_and(|v| !v.trim().is_empty()) {+ NoteSource::Database+ } else {+ NoteSource::None+ },+ shadowed_note: None,+ column_notes: BTreeMap::new(),+ estimated_rows: None,+ view_definition: None,+ })+ }+ })+ .buffer_unordered(MAX_CONCURRENT_TABLES)+ .collect()+ .await;++ let mut tables = Vec::new();+ for outcome in collected {+ match outcome {+ Ok(table) => tables.push(table),+ Err(warning) => warnings.push(warning),+ }+ }++ tables.sort_by(|a, b| a.qualified_name().cmp(&b.qualified_name()));++ let mut enums: Vec<DocEnum> = Vec::new();+ for table in &tables {+ for column in &table.columns {+ if let Some(value) = synthesize_enum(table.schema.as_deref(), &table.name, column) {+ enums.push(value);+ }+ }+ }++ let relationships = build_relationships(&tables);+ if relationships.is_empty() && tables.iter().any(|t| !t.columns.is_empty()) {+ warnings.push(SnapshotWarning::NoForeignKeyMetadata { engine: engine.clone() });+ }++ progress(CollectProgress { completed: total, total, current: String::new() });++ Ok(SchemaSnapshot {+ format_version: 1,+ project: ProjectMeta {+ name: options.project_name.clone(),+ database_type: engine,+ database: (!options.database.is_empty()).then(|| options.database.clone()),+ schemas: effective_schemas.into_iter().filter(|s| !s.is_empty()).collect(),+ generated_at: chrono::Utc::now().to_rfc3339(),+ note: None,+ },+ tables,+ relationships,+ groups: Vec::new(),+ enums,+ warnings,+ })+}+```++**Two things to verify before writing this file** (both are one command each, and both change the code above if they come back differently):++1. `grep -rn "pub struct AppState" crates/dbx-core/src` — use the real module path in the `use` line.+2. `grep -nE "^futures|^chrono|futures =|chrono =" crates/dbx-core/Cargo.toml` — the code above uses `futures::stream::buffer_unordered` and `chrono::Utc`. **If either is absent, do not add it** (Global Constraints forbid new dependencies). Substitute:+ - no `futures` → drive the fan-out with `tokio::task::JoinSet`, capping in-flight tasks at `MAX_CONCURRENT_TABLES` by draining with `join_next()` before spawning past the cap;+ - no `chrono` → build the RFC3339 timestamp from `std::time::SystemTime::now().duration_since(UNIX_EPOCH)`.++- [ ] **Step 4: Run the tests to verify they pass**++Run: `cargo test -p dbx-core docs::collector`+Expected: PASS, 5 tests.++- [ ] **Step 5: Verify the whole crate still builds**++Run: `cargo check -p dbx-core`+Expected: no errors.++- [ ] **Step 6: Commit**++```bash+cargo fmt+git add crates/dbx-core/src/docs/ crates/dbx-core/src/schema/+git commit -m "feat(docs): collect schema snapshots with bounded fan-out"+```++---++## Task 9: Web route for snapshot collection++**Files:**+- Create: `crates/dbx-web/src/routes/docs.rs`+- Modify: `crates/dbx-web/src/routes/mod.rs` (register the module and route)++**Interfaces:**+- Consumes: `collect_snapshot`, `CollectOptions` from Task 8+- Produces: `POST /api/docs/snapshot` accepting `{ connectionId, database, schemas, tables, projectName }` and returning a `SchemaSnapshot` as JSON++This exists so `WebBackend` (Task 10) makes **one** HTTP call instead of 3×N.++- [ ] **Step 1: Read the neighbouring route to match its shape**++Run: `sed -n '1,60p' crates/dbx-web/src/routes/database_export.rs`++Copy its handler signature, state extractor, error mapping and JSON response conventions exactly. Do not invent a different shape.++- [ ] **Step 2: Write the route**++Create `crates/dbx-web/src/routes/docs.rs` following that shape. The handler must:++1. Deserialize a `DocsSnapshotRequest { connection_id, database, schemas, tables, project_name }` with `#[serde(rename_all = "camelCase")]`.+2. Resolve the `ConnectionConfig` for `connection_id` the same way the neighbouring routes do. The collector takes `&AppState` directly — `state.app`, exactly as `crates/dbx-web/src/routes/schema.rs:41` passes it to `dbx_core::schema::list_databases_core`. **No pool resolution is needed**; the `*_core` functions handle pooling and retry internally.+3. Call:++```rust+let options = dbx_core::docs::CollectOptions {+ database: request.database.clone(),+ schemas: request.schemas.clone(),+ tables: request.tables.clone(),+ project_name: request.project_name.clone().unwrap_or_else(|| connection.name.clone()),+};++let snapshot = dbx_core::docs::collect_snapshot(+ &state.app,+ &connection,+ &options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+)+.await+.map_err(AppError::from)?;+```++4. Return `Json(snapshot)`, matching how `routes/schema.rs` returns its results.++- [ ] **Step 3: Register the route**++Add `pub mod docs;` to `crates/dbx-web/src/routes/mod.rs` and wire `POST /api/docs/snapshot` into the router beside the other `/api/...` routes, matching how `database_export` is registered.++- [ ] **Step 4: Verify it compiles**++Run: `cargo check -p dbx-web`+Expected: no errors.++- [ ] **Step 5: Commit**++```bash+cargo fmt+git add crates/dbx-web/src/routes/+git commit -m "feat(docs): add snapshot collection route"+```++---++## Task 10: Backend trait method++**Files:**+- Modify: `crates/dbx-mcp/src/backend.rs`++**Interfaces:**+- Produces: `async fn collect_docs_snapshot(&self, connection: &ConnectionConfig, database: &str, options: DocsSnapshotOptions) -> Result<SchemaSnapshot, String>` on `DbxBackend`, with implementations for `LocalBackend` and `WebBackend`++`DbxBackend` currently exposes `list_tables` and `get_columns` but no schemas, indexes or foreign keys. Adding those three separately would make `WebBackend` issue 3×N HTTP requests. One snapshot method keeps it to a single round-trip.++- [ ] **Step 1: Write the failing test**++Append to the existing `#[cfg(test)] mod tests` in `crates/dbx-mcp/src/backend.rs` (or create one following the file's existing conventions):++```rust+ struct StubBackend;++ #[async_trait]+ impl DbxBackend for StubBackend {+ async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {+ Err("unused".to_string())+ }+ async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {+ Ok(vec![])+ }+ async fn execute_agent_tool(+ &self,+ _connection: &ConnectionConfig,+ _database: &str,+ _tool_name: &str,+ _arguments: Value,+ _permissions: AgentSqlPermissions,+ ) -> ToolResult {+ unimplemented!("not exercised by this test")+ }+ async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {+ Ok(config)+ }+ async fn remove_connection_for_mcp(&self, _connection_id: &str) -> Result<bool, String> {+ Ok(false)+ }+ }++ #[tokio::test]+ async fn collect_docs_snapshot_defaults_to_unsupported() {+ let backend = StubBackend;+ let connection = new_connection_config(+ "c1".to_string(),+ "local".to_string(),+ DatabaseType::Postgres,+ "127.0.0.1".to_string(),+ );++ let result = backend+ .collect_docs_snapshot(&connection, "shop", DocsSnapshotOptions::default())+ .await;++ assert!(result.is_err());+ assert!(result.unwrap_err().contains("not supported"));+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-mcp collect_docs_snapshot`+Expected: FAIL — `no method named collect_docs_snapshot`.++- [ ] **Step 3: Add the trait method with a default**++Inside `pub trait DbxBackend`, following the pattern of the other optional methods:++```rust+ async fn collect_docs_snapshot(+ &self,+ connection: &ConnectionConfig,+ database: &str,+ options: DocsSnapshotOptions,+ ) -> Result<dbx_core::docs::SchemaSnapshot, String> {+ let _ = (connection, database, options);+ Err("Documentation snapshots are not supported by this backend.".to_string())+ }+```++Above the trait, add the options type:++```rust+/// Wire-level options for a documentation snapshot. Mirrors+/// `dbx_core::docs::CollectOptions` minus the fields the backend fills in.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsSnapshotOptions {+ #[serde(default)]+ pub schemas: Vec<String>,+ #[serde(default)]+ pub tables: Vec<String>,+ #[serde(default)]+ pub project_name: Option<String>,+}+```++- [ ] **Step 4: Run the test to verify it passes**++Run: `cargo test -p dbx-mcp collect_docs_snapshot`+Expected: PASS.++- [ ] **Step 5: Implement for LocalBackend**++In `impl DbxBackend for LocalBackend`, resolve the pool the same way its `get_columns` does, then:++```rust+ async fn collect_docs_snapshot(+ &self,+ connection: &ConnectionConfig,+ database: &str,+ options: DocsSnapshotOptions,+ ) -> Result<dbx_core::docs::SchemaSnapshot, String> {+ let collect_options = dbx_core::docs::CollectOptions {+ database: database.to_string(),+ schemas: options.schemas,+ tables: options.tables,+ project_name: options.project_name.unwrap_or_else(|| connection.name.clone()),+ };+ dbx_core::docs::collect_snapshot(+ &self.state,+ connection,+ &collect_options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+ )+ .await+ }+```++- [ ] **Step 6: Implement for WebBackend**++In `impl DbxBackend for WebBackend`, POST once to the Task 9 route, following how its other methods build authenticated requests:++```rust+ async fn collect_docs_snapshot(+ &self,+ connection: &ConnectionConfig,+ database: &str,+ options: DocsSnapshotOptions,+ ) -> Result<dbx_core::docs::SchemaSnapshot, String> {+ let body = serde_json::json!({+ "connectionId": connection.id,+ "database": database,+ "schemas": options.schemas,+ "tables": options.tables,+ "projectName": options.project_name.clone().unwrap_or_else(|| connection.name.clone()),+ });+ // Use this impl's existing authenticated-POST helper against+ // "/api/docs/snapshot" and deserialize the response into SchemaSnapshot.+ self.post_json("/api/docs/snapshot", body).await+ }+```++Replace `self.post_json` with whatever helper the impl actually uses — check the neighbouring methods first.++- [ ] **Step 7: Verify everything builds**++Run: `cargo check -p dbx-mcp && cargo test -p dbx-mcp`+Expected: no errors, tests pass.++- [ ] **Step 8: Commit**++```bash+cargo fmt+git add crates/dbx-mcp/src/backend.rs+git commit -m "feat(docs): add collect_docs_snapshot to DbxBackend"+```++---++## Task 11: `dbx dbml` CLI verb++**Files:**+- Modify: `crates/dbx-cli/src/main.rs`++**Interfaces:**+- Consumes: `DbxBackend::collect_docs_snapshot` (Task 10), `dbx_core::docs::to_dbml` (Task 7)+- Produces: `dbx dbml <connection> [--out path] [--schema s] [--database d] [--tables a,b]`++`--out` is a new flag. `--notes` is deliberately **not** added here — it needs the annotation store from Part 2.++- [ ] **Step 1: Write the failing test**++Append to the existing `#[cfg(test)] mod tests` in `crates/dbx-cli/src/main.rs`, matching the style of the existing `parse_flags` tests around line 934:++```rust+ #[test]+ fn parses_the_out_flag() {+ let flags = parse_flags(&args(&["dbml", "local", "--out", "schema.dbml"])).expect("parse");+ assert_eq!(flags.args, args(&["dbml", "local"]));+ assert_eq!(flags.out.as_deref(), Some(std::path::Path::new("schema.dbml")));+ }++ #[test]+ fn out_requires_a_value() {+ let error = parse_flags(&args(&["dbml", "local", "--out"])).expect_err("should fail");+ assert_eq!(error.code, "INVALID_OPTION");+ }++ #[test]+ fn dbml_appears_in_the_usage_text() {+ assert!(usage().contains("dbx dbml <connection>"), "got: {}", usage());+ }+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `cargo test -p dbx-cli`+Expected: FAIL — `no field named out on Flags`.++- [ ] **Step 3: Add the flag**++Add `pub out: Option<PathBuf>` to the `Flags` struct, initialise it to `None` in `parse_flags`, and add the match arm beside `--file`:++```rust+ "--out" => flags.out = Some(PathBuf::from(option_value(argv, &mut index, "--out")?)),+```++- [ ] **Step 4: Add the verb dispatch**++In `run_with_backend`, beside the existing `schema` / `query` / `context` checks:++```rust+ if args.first().is_some_and(|arg| arg == "dbml") {+ return run_dbml(backend, &flags).await;+ }+```++And the handler, modelled on `run_context`:++```rust+async fn run_dbml(backend: &dyn DbxBackend, flags: &Flags) -> Result<String, (CliError, bool)> {+ let name = flags.args.get(1).ok_or_else(|| {+ (CliError::new("MISSING_ARGUMENT", "Usage: dbx dbml <connection> [--out path]"), false)+ })?;++ let connection = find_connection(backend, name).await.map_err(|error| (error, false))?;+ let database = selected_database(&connection, flags.database.as_deref());++ let options = DocsSnapshotOptions {+ schemas: flags.schema.clone().into_iter().collect(),+ tables: flags.tables.clone(),+ project_name: Some(connection.name.clone()),+ };++ let snapshot = backend+ .collect_docs_snapshot(&connection, &database, options)+ .await+ .map_err(|error| (CliError::new("DOCS_SNAPSHOT_FAILED", error), false))?;++ let output = dbx_core::docs::to_dbml(&snapshot);++ for warning in &output.warnings {+ eprintln!("warning: {warning:?}");+ }++ match flags.out.as_ref() {+ Some(path) => {+ std::fs::write(path, &output.text).map_err(|error| {+ (CliError::new("WRITE_FAILED", format!("Failed to write {}: {error}", path.display())), false)+ })?;+ Ok(format!("Wrote {} bytes to {}", output.text.len(), path.display()))+ }+ None => Ok(output.text),+ }+}+```++- [ ] **Step 5: Update the usage text**++In the `usage()` function, add this line to the existing string, after the `dbx context` line:++```+ dbx dbml <connection> [--out path] [--schema name] [--database name] [--tables a,b]+```++- [ ] **Step 6: Run the tests to verify they pass**++Run: `cargo test -p dbx-cli`+Expected: PASS.++- [ ] **Step 7: Commit**++```bash+cargo fmt+git add crates/dbx-cli/src/main.rs+git commit -m "feat(docs): add dbx dbml command"+```++---++## Task 12: Live end-to-end verification++**Files:**+- Create: `crates/dbx-core/tests/live_postgres_docs_snapshot.rs`++**Interfaces:**+- Consumes: everything above++Follow the exact gating convention of `crates/dbx-core/tests/live_postgres_query_result_export.rs` — read it first and copy how it skips when no live database is configured.++- [ ] **Step 1: Read the existing live test's harness**++Run: `sed -n '1,50p' crates/dbx-core/tests/live_postgres_query_result_export.rs`++Copy its env-var gating and connection setup verbatim.++- [ ] **Step 2: Write the live test**++```rust+// Gating and connection setup copied from live_postgres_query_result_export.rs.++#[tokio::test]+async fn collects_a_snapshot_and_serializes_valid_dbml() {+ let Some((state, config)) = live_postgres().await else {+ eprintln!("skipping: no live PostgreSQL configured");+ return;+ };++ let options = dbx_core::docs::CollectOptions {+ database: config.database.clone().unwrap_or_default(),+ schemas: vec!["public".to_string()],+ tables: vec![],+ project_name: "live-test".to_string(),+ };++ let snapshot = dbx_core::docs::collect_snapshot(+ &state,+ &config,+ &options,+ &|_progress| {},+ &std::sync::atomic::AtomicBool::new(false),+ )+ .await+ .expect("collect");++ assert_eq!(snapshot.format_version, 1);+ assert!(!snapshot.tables.is_empty(), "expected at least one table");++ let dbml = dbx_core::docs::to_dbml(&snapshot);+ assert!(dbml.text.starts_with("Project "), "got:\n{}", dbml.text);++ for table in &snapshot.tables {+ assert!(+ dbml.text.contains(&format!("Table {}", table.name))+ || dbml.text.contains(&format!("Table {}.{}", table.schema.clone().unwrap_or_default(), table.name)),+ "table {} missing from DBML",+ table.name+ );+ }++ // Braces must balance, or the DBML is unparseable.+ let opens = dbml.text.matches('{').count();+ let closes = dbml.text.matches('}').count();+ assert_eq!(opens, closes, "unbalanced braces in:\n{}", dbml.text);+}+```++- [ ] **Step 3: Run it**++Run: `cargo test -p dbx-core --test live_postgres_docs_snapshot -- --nocapture`+Expected: PASS, or a clean skip message when no live database is configured.++- [ ] **Step 4: Manual smoke test**++With a real connection configured in DBX:++```bash+cargo run -p dbx-cli -- dbml <your-connection> --schema public+```++Expected: DBML on stdout beginning with `Project`. Paste it into <https://dbdiagram.io> and confirm it renders without a parse error. **This is the acceptance gate for the whole plan** — a DBML file that dbdiagram rejects is a failure regardless of what the unit tests say.++- [ ] **Step 5: Full sweep**++Run: `cargo test -p dbx-core && cargo test -p dbx-cli && cargo test -p dbx-mcp && cargo clippy -p dbx-core -- -D warnings`+Expected: all pass.++- [ ] **Step 6: Commit**++```bash+cargo fmt+git add crates/dbx-core/tests/+git commit -m "test(docs): add live snapshot and DBML verification"+```++---++## Done criteria++- `dbx dbml <connection>` prints DBML that dbdiagram.io parses.+- `dbx dbml <connection> --out schema.dbml` writes the file and reports the byte count.+- Every DBML-inexpressible construct appears on stderr as a warning; none vanish.+- `cargo test -p dbx-core` passes with no live database configured.+- `SchemaSnapshot` serializes to camelCase JSON, ready for Part 2 (annotations) and Part 3 (viewer + HTML export).++---++## Appendix: Corrections found during execution++This plan was written by reading the codebase rather than compiling against it, and thirteen of its+assumptions turned out to be wrong. All were caught and fixed before merge. The sections above have+been amended where a fix was small and local; this appendix records every correction so that nobody+re-derives a wrong fact from the surrounding prose.++The pattern is consistent and worth internalising for future plans: **symbol names are easy to+verify with grep; visibility, arity, module paths, and required call-ordering are not** — and those+are exactly what breaks a build or, worse, compiles and fails at runtime.++### Contract errors (wrong signature, path, or visibility)++| # | Plan said | Reality |+| --- | --- | --- |+| 1 | `use crate::state::AppState` | `crate::connection::AppState` (`connection.rs:200`) |+| 2 | `capabilities_for(db_type).comment` callable from `docs::` | `capabilities_for` **and** `TableStructureCapabilities` are `pub(super)`; it takes `Option<DatabaseType>`. Fixed by adding narrow `pub(crate) fn supports_comments` / `supports_foreign_keys` accessors in `table_structure_sql.rs` |+| 3 | collector takes `&PoolKind` | `schema::*_core` take `&AppState` + connection id, and already wrap `retry_metadata_connection` |+| 4 | `WebBackend::post_json(...)` | No such helper. Real API is `request(Method, path, Option<Value>)` (`backend.rs:247`) |+| 5 | `new_connection_config(a, b, c, d)` | Takes 10 positional args (`backend.rs:1517`) |+| 6 | `run_dbml -> Result<String, (CliError, bool)>` | Siblings return `Result<String, CliError>`; the tuple wrap happens once in `run()` |+| 7 | `DocsSnapshotOptions` at crate root | Only at `dbx_mcp::backend::DocsSnapshotOptions` |+| 8 | `pub out: Option<PathBuf>` on `Flags` | `Flags` is private with private fields — no `pub` |++### Runtime-only errors (compiled and passed tests; would fail only against a live system)++| # | Plan said | Reality |+| --- | --- | --- |+| 9 | Register route as `/api/docs/snapshot` | Router does `.nest("/api", api)` (`main.rs:777`), so routes register bare: `/docs/snapshot`. The literal path would have served `/api/api/docs/snapshot` |+| 10 | `WebBackend` posts directly | Must call `self.ensure_connected(connection).await?` first (`backend.rs:283`) or the remote instance returns connection-not-found |+| 11 | Live test uses a `live_postgres() -> Option<..>` helper with skip-by-return | Repo convention is `#[ignore = "requires DBX_LIVE_POSTGRES_..."]`. The plan's version would have **run and silently passed** with no database configured |++### Logic errors (correct-looking code producing wrong output)++| # | Defect | Fix |+| --- | --- | --- |+| 12 | `find_target` fell back to first-match-by-name, so an FK could bind to a same-named table in another schema | Resolution order is now explicit `ref_schema` → source table's own schema → unique bare name; ambiguous matches are dropped rather than guessed (`relations.rs`) |+| 13 | `render_note` escaped only a literal `'''`, so a note ending in an apostrophe emitted four consecutive quotes and broke parsing | Also escapes a trailing `'` as `\'` (`dbml.rs`) |++### Defects found by review, not present in the plan text++- **`NoForeignKeyMetadata` false positives.** The emptiness heuristic reported healthy PostgreSQL as+ lacking FK support via three paths (schema genuinely has no FKs; `--tables` subset drops dangling+ edges; a swallowed `list_foreign_keys_core` error). Now gated purely on engine capability, and a+ real FK query failure surfaces as `TableSkipped`.+- **Orphan enums.** `synthesize_enum` emitted an `Enum` block that `render_type` never referenced —+ the named-enum feature silently did not land. `render_type` now routes through the same+ `qualified()` helper `render_enum` uses, so the two cannot drift.+- **Dropped `snapshot.warnings`.** `to_dbml` built its warning list from scratch, discarding+ collector-side omissions. Now seeded from `snapshot.warnings`.++### Test-quality lessons++Two regression tests written during the fix rounds were themselves invalid — one too narrow (pinned+a single-schema literal, blind to the multi-schema case), one too loose (`contains` matched a bare+name as a substring of the qualified one, so it passed against the very bug it guarded).++**A regression test is not known to work until it has been observed failing against the bug.**+Deliberately break the fix, watch the test fail, restore, confirm it passes. It costs about ninety+seconds and it is the only way to distinguish a guard from a decoration.diff --git a/docs/superpowers/plans/2026-08-03-database-documentation-in-app.md b/docs/superpowers/plans/2026-08-03-database-documentation-in-app.mdnew file mode 100644index 0000000000..7e09dd838b--- /dev/null+++ b/docs/superpowers/plans/2026-08-03-database-documentation-in-app.md@@ -0,0 +1,1762 @@+# In-App Database Documentation Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Make the Part 3a documentation viewer reachable from inside DBX and editable — table and column notes, table groups, and per-group colour — autosaved to a notes file that can live in the user's repository.++**Architecture:** The viewer components stay pure (snapshot in, DOM out, zero backend calls, enforced by an existing contract test) so Part 3c can bundle them into a standalone HTML file. `DatabaseDocsDialog.vue` sits outside `src/docs/` and owns all I/O. Edits are pure transformations of the `AnnotationFile`, applied by Rust so the `shadowedNote` rule has exactly one implementation.++**Tech Stack:** Rust (`dbx-core`, `dbx-web`, `src-tauri`), Vue 3 `<script setup lang="ts">`, Tailwind, vitest, vue-tsc, oxlint.++## Global Constraints++- **`apps/desktop/src/docs/**/*.vue` must make ZERO backend calls.** `componentContract.spec.ts` forbids `@/lib/backend`, `@tauri-apps`, `invoke(`, `useConnectionStore`, `useQueryStore`, `useSettingsStore`, `fetch(`, `axios`, `innerHTML`, `oklch(`, six-digit hex literals, and any `v-html` binding (either quote style) not naming `renderNote`. Extend that test; never weaken it.+- **Never import `vue-i18n` inside `apps/desktop/src/docs/`.** `useI18n()` throws without a provided instance, which is exactly the Part 3c standalone-export case. Modules there take a translator function as a parameter instead.+- **Every backend operation exists twice.** `apps/desktop/src/lib/backend/api.ts` resolves either `tauri.ts` or `http.ts` via `isTauriRuntime()`. Both must be implemented, plus a Tauri command and a web route.+- **All annotation structs carry `#[serde(rename_all = "camelCase", deny_unknown_fields)]`.** An extra key sent from TypeScript is a hard deserialization error, not a silent ignore. `format_version` serialises as `formatVersion`.+- **`dbx-core` must not depend on `dbx-mcp`.** `app_data_dir()` lives in `dbx-mcp`, so anything in `dbx-core` needing it takes the directory as a parameter.+- **Rust commands:** `export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"` before `cargo` or `git commit` (the pre-commit hook runs `cargo fmt`). Use `pnpm`, never `npm`.+- **Every new test gets a deliberate break:** break the behaviour, watch the named test fail, restore, report the failure message. A test that cannot fail is worse than no test.+- Baseline before this plan: 77 frontend tests, 4428 Rust tests, `vue-tsc` exit 0, `oxlint` clean.++---++## File Structure++**Rust — `dbx-core`**+- `crates/dbx-core/src/docs/annotations.rs` — add `save_annotations`, `resolve_notes_path`++**Rust — Tauri**+- `src-tauri/src/commands/docs.rs` — CREATE: four commands+- `src-tauri/src/commands/mod.rs` — declare the module+- `src-tauri/src/lib.rs:1411` — register in `generate_handler!`++**Rust — web parity**+- `crates/dbx-web/src/routes/docs.rs` — add three handlers+- `crates/dbx-web/src/main.rs:377` — register three routes++**Frontend — data and logic**+- `apps/desktop/src/docs/types.ts` — add annotation types+- `apps/desktop/src/docs/annotationEdits.ts` — CREATE: pure edit transforms+- `apps/desktop/src/docs/docsIndex.ts` — add `columnsUsingEnum`+- `apps/desktop/src/docs/docsWarnings.ts` — take a translator parameter++**Frontend — backend facade**+- `apps/desktop/src/lib/backend/tauri.ts`, `http.ts`, `api.ts` — four operations each++**Frontend — components**+- `apps/desktop/src/docs/components/NoteEditor.vue`, `GroupEditor.vue`, `GroupPicker.vue`, `EnumPage.vue` — CREATE+- `apps/desktop/src/docs/DocsApp.vue` — `readonly` prop, edit events+- `apps/desktop/src/components/docs/DatabaseDocsDialog.vue` — CREATE: owns I/O and autosave++**Frontend — wiring and i18n**+- `apps/desktop/src/stores/connectionStore.ts` — `docsSource`+- `apps/desktop/src/composables/useDialogSources.ts` — watcher+- `apps/desktop/src/components/layout/AppDialogs.vue` — registration+- `apps/desktop/src/i18n/locales/{en,es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` — `docs` namespace+- `apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts` — CREATE++---++## Task 1: Atomic save and notes-path resolution++**Files:**+- Modify: `crates/dbx-core/src/docs/annotations.rs`+- Test: same file's `mod tests`++**Interfaces:**+- Consumes: `AnnotationFile` (existing), `ConnectionConfig` (existing, `docs_notes_path: Option<String>`)+- Produces: `save_annotations(path: &Path, annotations: &AnnotationFile) -> Result<(), String>`, `resolve_notes_path(connection_id: &str, docs_notes_path: Option<&str>, data_dir: &Path) -> PathBuf`++- [x] **Step 1: Write the failing tests**++Add to the existing `mod tests` in `annotations.rs`:++```rust+ #[test]+ fn save_then_load_round_trips() {+ let dir = temp_case_dir("round-trip");+ let path = dir.join("notes.json");+ let file = AnnotationFile {+ format_version: 1,+ project: Some(ProjectAnnotation { name: Some("P".into()), note: Some("hello".into()) }),+ groups: vec![GroupAnnotation { id: "g".into(), name: "G".into(), hue: 200, note: None }],+ tables: BTreeMap::from([(+ "public.t".to_string(),+ TableAnnotation { group: Some("g".into()), note: Some("n".into()), columns: BTreeMap::new() },+ )]),+ };++ save_annotations(&path, &file).expect("save");+ let loaded = load_annotations(&path).expect("load").expect("present");++ assert_eq!(loaded.format_version, 1);+ assert_eq!(loaded.groups[0].hue, 200);+ assert_eq!(loaded.tables["public.t"].note.as_deref(), Some("n"));+ assert_eq!(loaded.project.and_then(|p| p.note).as_deref(), Some("hello"));+ }++ #[test]+ fn save_creates_missing_parent_directories() {+ let dir = temp_case_dir("nested");+ let path = dir.join("nested").join("deeper").join("notes.json");+ let file = AnnotationFile {+ format_version: 1,+ project: None,+ groups: Vec::new(),+ tables: BTreeMap::new(),+ };+ save_annotations(&path, &file).expect("save into a new directory");+ assert!(path.exists());+ }++ #[test]+ fn save_leaves_no_temp_file_behind() {+ // A stray notes.json.tmp would be picked up by nothing, but it means+ // the rename did not happen and the write was not atomic.+ let dir = temp_case_dir("no-temp-left");+ let path = dir.join("notes.json");+ let file = AnnotationFile {+ format_version: 1,+ project: None,+ groups: Vec::new(),+ tables: BTreeMap::new(),+ };+ save_annotations(&path, &file).expect("save");++ let leftovers: Vec<_> = std::fs::read_dir(&dir)+ .expect("read_dir")+ .filter_map(Result::ok)+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .filter(|name| name.ends_with(".tmp"))+ .collect();+ assert!(leftovers.is_empty(), "temp files left behind: {leftovers:?}");+ }++ #[test]+ fn a_failed_save_leaves_the_previous_file_intact() {+ // The reason for writing to a temp file and renaming. If the write+ // fails partway, the reader must still find the last good notes —+ // load_annotations errors loudly on malformed JSON, so a torn write+ // would read as "your notes file is corrupt".+ let dir = temp_case_dir("failed-save");+ let path = dir.join("notes.json");+ let good = AnnotationFile {+ format_version: 1,+ project: None,+ groups: Vec::new(),+ tables: BTreeMap::from([(+ "public.keep".to_string(),+ TableAnnotation { group: None, note: Some("survives".into()), columns: BTreeMap::new() },+ )]),+ };+ save_annotations(&path, &good).expect("first save");++ // A directory where the temp file wants to be makes File::create fail.+ std::fs::create_dir(path.with_extension("json.tmp")).expect("block the temp path");+ let result = save_annotations(&path, &good);++ assert!(result.is_err(), "save must fail when the temp path is unusable");+ let loaded = load_annotations(&path).expect("load").expect("present");+ assert_eq!(loaded.tables["public.keep"].note.as_deref(), Some("survives"));+ }++ #[test]+ fn an_explicit_notes_path_wins_over_the_default() {+ let resolved =+ resolve_notes_path("conn-1", Some("/tmp/team/schema-notes.json"), std::path::Path::new("/data"));+ assert_eq!(resolved, std::path::PathBuf::from("/tmp/team/schema-notes.json"));+ }++ #[test]+ fn the_default_notes_path_is_keyed_by_connection_id() {+ let resolved = resolve_notes_path("conn-1", None, std::path::Path::new("/data"));+ assert_eq!(resolved, std::path::PathBuf::from("/data/docs-notes/conn-1.json"));+ }++ #[test]+ fn a_blank_notes_path_falls_back_to_the_default() {+ // An empty string in the config is a cleared field, not a path to a+ // file named "". Treating it as explicit would resolve to garbage.+ let resolved = resolve_notes_path("conn-1", Some(" "), std::path::Path::new("/data"));+ assert_eq!(resolved, std::path::PathBuf::from("/data/docs-notes/conn-1.json"));+ }+```++Callers pass `&config.id, config.docs_notes_path.as_deref(), data_dir`.++`dbx-core` has NO `[dev-dependencies]` section and therefore no `tempfile`. The idiom already used+in this file (around line 319) is `std::env::temp_dir()` plus a uuid suffix — `uuid` is a regular+dependency of this crate. Add this helper inside `mod tests` beside the others:++```rust+ fn temp_case_dir(label: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("dbx-notes-{label}-{}", uuid::Uuid::new_v4().simple()));+ std::fs::create_dir_all(&dir).expect("create temp dir");+ dir+ }+```++- [x] **Step 2: Run and watch them fail**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+cargo test -p dbx-core --lib docs::annotations+```+Expected: FAIL — `save_annotations` and `resolve_notes_path` are not defined.++- [x] **Step 3: Implement**++Add to `annotations.rs`. It already has `use std::path::Path`; add `std::io::Write` and `std::path::PathBuf`.++```rust+/// Write the notes file atomically.+///+/// A partial write destroys prose a human typed, and `load_annotations`+/// errors loudly on malformed JSON — so a torn write becomes "your notes file+/// is corrupt" the next time the viewer opens. Write a sibling temp file,+/// flush it to disk, then rename: rename within a directory is atomic on+/// every platform DBX targets.+pub fn save_annotations(path: &Path, annotations: &AnnotationFile) -> Result<(), String> {+ let json = serde_json::to_string_pretty(annotations)+ .map_err(|error| format!("Failed to serialize notes: {error}"))?;++ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|error| format!("Failed to create {}: {error}", parent.display()))?;+ }++ let temp = path.with_extension("json.tmp");+ {+ let mut file = std::fs::File::create(&temp)+ .map_err(|error| format!("Failed to create {}: {error}", temp.display()))?;+ file.write_all(json.as_bytes())+ .map_err(|error| format!("Failed to write {}: {error}", temp.display()))?;+ file.sync_all().map_err(|error| format!("Failed to flush {}: {error}", temp.display()))?;+ }++ std::fs::rename(&temp, path).map_err(|error| format!("Failed to replace {}: {error}", path.display()))+}++/// Where a connection's notes file lives.+///+/// An explicit `docs_notes_path` wins — that is the entire point of the field.+/// Pointing it at a file inside a repository is what lets schema documentation+/// be reviewed in pull requests. Otherwise the file lives under the app data+/// directory keyed by connection id, so the feature works with no setup.+///+/// Takes the two fields it needs rather than a whole `ConnectionConfig`:+/// that struct has no `Default` and ~60 fields, so passing it would force+/// every test to build a literal full of values the function never reads.+/// `data_dir` is a parameter because `dbx-core` cannot reach the caller's+/// data directory on its own.+pub fn resolve_notes_path(connection_id: &str, docs_notes_path: Option<&str>, data_dir: &Path) -> PathBuf {+ if let Some(path) = docs_notes_path.map(str::trim).filter(|value| !value.is_empty()) {+ return PathBuf::from(path);+ }+ data_dir.join("docs-notes").join(format!("{connection_id}.json"))+}+```++Add `use crate::models::connection::ConnectionConfig;` if the file does not already import it.++- [x] **Step 4: Run and watch them pass**++```bash+cargo test -p dbx-core --lib docs::annotations+```++- [x] **Step 5: Verify two guards bite**++One at a time, restoring between each. Report both failure messages.++1. Replace the temp-file-and-rename body with a direct `std::fs::write(path, json)` → `a_failed_save_leaves_the_previous_file_intact` must fail.+2. Delete the `.filter(|value| !value.is_empty())` from `resolve_notes_path` → `a_blank_notes_path_falls_back_to_the_default` must fail.++- [x] **Step 6: Commit**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+cargo clippy -p dbx-core --all-targets+git add crates/dbx-core/src/docs/annotations.rs+git commit -m "feat(docs): add atomic annotation save and notes path resolution"+```++---++## Task 2: Tauri commands++**Files:**+- Create: `src-tauri/src/commands/docs.rs`+- Modify: `src-tauri/src/commands/mod.rs`, `src-tauri/src/lib.rs:1411`++**Interfaces:**+- Consumes: `save_annotations`, `resolve_notes_path` (Task 1); existing `collect_snapshot`, `load_annotations`, `apply_annotations`+- Produces: commands `docs_collect_snapshot`, `docs_load_annotations`, `docs_apply_annotations`, `docs_save_annotations`++- [x] **Step 1: Create the command module**++`src-tauri/src/commands/docs.rs`:++```rust+use std::sync::atomic::AtomicBool;+use std::sync::Arc;++use dbx_core::connection::AppState;+// `apply_annotations` is NOT re-exported at `dbx_core::docs` — that module's+// `pub use` list covers collector, color, dbml, keys, relations and snapshot,+// but not annotations. It must come from the submodule path.+use dbx_core::docs::annotations::{+ apply_annotations, load_annotations, resolve_notes_path, save_annotations, AnnotationFile,+};+use dbx_core::docs::{collect_snapshot, CollectOptions, SchemaSnapshot};+use dbx_core::models::connection::ConnectionConfig;+use tauri::State;++async fn connection_of(state: &Arc<AppState>, connection_id: &str) -> Result<ConnectionConfig, String> {+ let configs = state.configs.read().await;+ configs.get(connection_id).cloned().ok_or_else(|| format!("Connection {connection_id} not found."))+}++/// The notes file for a connection, resolved against DBX's data directory.+///+/// `AppState.storage.data_dir()` is the directory DBX is actually using — it+/// honours a custom data dir, which a fresh `app_data_dir()` lookup would not.+/// (`dbx-mcp::paths::app_data_dir()` is NOT available here: src-tauri does not+/// depend on dbx-mcp.)+async fn notes_path_of(state: &Arc<AppState>, connection_id: &str) -> Result<std::path::PathBuf, String> {+ let config = connection_of(state, connection_id).await?;+ Ok(resolve_notes_path(&config.id, config.docs_notes_path.as_deref(), state.storage.data_dir()))+}++/// Collect a RAW snapshot — annotations are applied separately, so the+/// frontend can re-derive after an edit without touching the database.+#[tauri::command]+pub async fn docs_collect_snapshot(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ schemas: Vec<String>,+ tables: Vec<String>,+ project_name: Option<String>,+) -> Result<SchemaSnapshot, String> {+ let config = connection_of(&state, &connection_id).await?;+ let options = CollectOptions {+ database,+ schemas,+ tables,+ project_name: project_name.unwrap_or_else(|| config.name.clone()),+ };+ collect_snapshot(&state, &config, &options, &|_progress| {}, &AtomicBool::new(false)).await+}++#[tauri::command]+pub async fn docs_load_annotations(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+) -> Result<Option<AnnotationFile>, String> {+ let path = notes_path_of(&state, &connection_id).await?;+ load_annotations(&path)+}++/// Apply annotations to a raw snapshot. Pure — no database access.+///+/// This exists so the `shadowedNote` rule has exactly ONE implementation.+/// Re-implementing it in TypeScript to update the view optimistically is the+/// drift this feature has repeatedly suffered from.+#[tauri::command]+pub async fn docs_apply_annotations(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ snapshot: SchemaSnapshot,+ annotations: AnnotationFile,+) -> Result<SchemaSnapshot, String> {+ let config = connection_of(&state, &connection_id).await?;+ let mut applied = snapshot;+ apply_annotations(&mut applied, &annotations, config.db_type);+ Ok(applied)+}++#[tauri::command]+pub async fn docs_save_annotations(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ annotations: AnnotationFile,+) -> Result<(), String> {+ let path = notes_path_of(&state, &connection_id).await?;+ save_annotations(&path, &annotations)+}+```++The `use` lines above are correct as written — I verified them against `crates/dbx-core/src/docs/mod.rs`. `collect_snapshot`, `CollectOptions` and `SchemaSnapshot` ARE re-exported at the `docs` root; `apply_annotations` and friends are NOT, and come from `docs::annotations`.++- [x] **Step 2: Declare and register**++Add `pub mod docs;` to `src-tauri/src/commands/mod.rs` beside its siblings. Add these four to the `generate_handler![` list at `src-tauri/src/lib.rs:1411`, matching the surrounding entries' formatting:++```rust+ commands::docs::docs_collect_snapshot,+ commands::docs::docs_load_annotations,+ commands::docs::docs_apply_annotations,+ commands::docs::docs_save_annotations,+```++- [x] **Step 3: Build**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+cargo check -p dbx+cargo clippy -p dbx --all-targets+```+Both must be clean. There are no unit tests for this task: the commands are thin adapters over Task 1's tested functions, and a test asserting a delegation reimplements the delegation.++- [x] **Step 4: Commit**++```bash+git add src-tauri/src/commands/docs.rs src-tauri/src/commands/mod.rs src-tauri/src/lib.rs+git commit -m "feat(docs): add Tauri commands for docs snapshot and annotations"+```++---++## Task 3: Web route parity++**Files:**+- Modify: `crates/dbx-web/src/routes/docs.rs`, `crates/dbx-web/src/main.rs:377`++**Interfaces:**+- Consumes: the same `dbx-core` functions as Task 2+- Produces: `POST /api/docs/annotations/load`, `/api/docs/annotations/apply`, `/api/docs/annotations/save`++- [x] **Step 1: Add three handlers**++Append to `crates/dbx-web/src/routes/docs.rs`, matching the existing `collect_snapshot` handler's style and its `#[serde(rename_all = "camelCase")]` request structs:++```rust+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsAnnotationsRequest {+ pub connection_id: String,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsApplyRequest {+ pub connection_id: String,+ pub snapshot: SchemaSnapshot,+ pub annotations: dbx_core::docs::annotations::AnnotationFile,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DocsSaveRequest {+ pub connection_id: String,+ pub annotations: dbx_core::docs::annotations::AnnotationFile,+}++/// `WebState` already carries the data directory (`pub data_dir: PathBuf`), so+/// this needs no lookup and no new dependency — dbx-web does NOT depend on+/// dbx-mcp.+fn notes_path_for(state: &Arc<WebState>, config: &ConnectionConfig) -> std::path::PathBuf {+ dbx_core::docs::annotations::resolve_notes_path(&config.id, config.docs_notes_path.as_deref(), &state.data_dir)+}++pub async fn load_annotations(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsAnnotationsRequest>,+) -> Result<Json<Option<dbx_core::docs::annotations::AnnotationFile>>, AppError> {+ let config = load_connection(&state, &request.connection_id).await?;+ let path = notes_path_for(&state, &config);+ Ok(Json(dbx_core::docs::annotations::load_annotations(&path).map_err(AppError::from)?))+}++pub async fn apply_annotations(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsApplyRequest>,+) -> Result<Json<SchemaSnapshot>, AppError> {+ let config = load_connection(&state, &request.connection_id).await?;+ let mut applied = request.snapshot;+ dbx_core::docs::annotations::apply_annotations(&mut applied, &request.annotations, config.db_type);+ Ok(Json(applied))+}++pub async fn save_annotations(+ State(state): State<Arc<WebState>>,+ Json(request): Json<DocsSaveRequest>,+) -> Result<Json<()>, AppError> {+ let config = load_connection(&state, &request.connection_id).await?;+ let path = notes_path_for(&state, &config);+ dbx_core::docs::annotations::save_annotations(&path, &request.annotations).map_err(AppError::from)?;+ Ok(Json(()))+}+```++Do NOT add a `dbx-mcp` dependency to `dbx-web` — it has none, and it does not need one. `WebState` already carries `pub data_dir: PathBuf`, which is what the handlers use.++- [x] **Step 2: Register the routes**++At `crates/dbx-web/src/main.rs:377`, beside the existing `/docs/snapshot` line:++```rust+ .route("/docs/annotations/load", post(routes::docs::load_annotations))+ .route("/docs/annotations/apply", post(routes::docs::apply_annotations))+ .route("/docs/annotations/save", post(routes::docs::save_annotations))+```++- [x] **Step 3: Build**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+cargo check -p dbx-web && cargo clippy -p dbx-web --all-targets+```++- [x] **Step 4: Commit**++```bash+git add crates/dbx-web/src/routes/docs.rs crates/dbx-web/src/main.rs+git commit -m "feat(docs): add web routes for annotation load, apply and save"+```++---++## Task 4: Frontend backend facade and annotation types++**Files:**+- Modify: `apps/desktop/src/docs/types.ts`, `apps/desktop/src/lib/backend/tauri.ts`, `apps/desktop/src/lib/backend/http.ts`, `apps/desktop/src/lib/backend/api.ts`+- Test: `apps/desktop/src/docs/__tests__/annotationTypes.spec.ts` (create)++**Interfaces:**+- Produces: TS types `AnnotationFile`, `ProjectAnnotation`, `GroupAnnotation`, `TableAnnotation`, `ColumnAnnotation`; and `collectDocsSnapshot`, `loadDocsAnnotations`, `applyDocsAnnotations`, `saveDocsAnnotations` exported from `@/lib/backend/api`++- [x] **Step 1: Add the types**++Append to `apps/desktop/src/docs/types.ts`. These mirror Rust structs carrying `deny_unknown_fields`, so an extra property is a hard deserialization error on the Rust side — the shapes must match exactly.++```ts+/** Mirrors `dbx_core::docs::annotations::ColumnAnnotation`. */+export interface ColumnAnnotation {+ note: string;+}++/** Mirrors `TableAnnotation`. Absent keys are omitted, never sent as null. */+export interface TableAnnotation {+ group?: string;+ note?: string;+ columns?: Record<string, ColumnAnnotation>;+}++/** Mirrors `GroupAnnotation`. `hue` is 0–359; lightness and chroma are the theme's. */+export interface GroupAnnotation {+ id: string;+ name: string;+ hue: number;+ note?: string;+}++/** Mirrors `ProjectAnnotation`. */+export interface ProjectAnnotation {+ name?: string;+ note?: string;+}++/**+ * The on-disk notes file. Rust declares `deny_unknown_fields`, so adding a+ * property here without adding it in Rust makes every save fail.+ */+export interface AnnotationFile {+ formatVersion: number;+ project?: ProjectAnnotation;+ groups?: GroupAnnotation[];+ tables?: Record<string, TableAnnotation>;+}+```++- [x] **Step 2: Write the failing conformance test**++`apps/desktop/src/docs/__tests__/annotationTypes.spec.ts`:++```ts+import { readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";++// The Rust structs carry deny_unknown_fields, so any property TypeScript adds+// that Rust does not declare turns every save into a deserialization error at+// runtime. vue-tsc cannot see across the language boundary, so this reads the+// Rust source and compares the field sets directly.+const rustSource = readFileSync(+ path.resolve(__dirname, "../../../../../crates/dbx-core/src/docs/annotations.rs"),+ "utf8",+);++function rustFields(structName: string): string[] {+ const start = rustSource.indexOf(`pub struct ${structName} {`);+ expect(start, `struct ${structName} not found in annotations.rs`).toBeGreaterThan(-1);+ const body = rustSource.slice(start, rustSource.indexOf("\n}", start));+ return [...body.matchAll(/^\s{4}pub ([a-z_]+):/gm)].map((match) => toCamel(match[1])).sort();+}++function toCamel(value: string): string {+ return value.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());+}++describe("annotation types match the Rust structs", () => {+ it.each([+ ["AnnotationFile", ["formatVersion", "groups", "project", "tables"]],+ ["ProjectAnnotation", ["name", "note"]],+ ["GroupAnnotation", ["hue", "id", "name", "note"]],+ ["TableAnnotation", ["columns", "group", "note"]],+ ["ColumnAnnotation", ["note"]],+ ])("%s", (structName, expected) => {+ expect(rustFields(structName as string)).toEqual(expected);+ });+});+```++- [x] **Step 3: Run and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/annotationTypes.spec.ts+```+Expected: PASS, 5 cases. If a field set mismatches, the TypeScript above is wrong — fix the TypeScript, not the test, and report what differed.++- [x] **Step 4: Verify it bites**++Add `extra?: string;` to the TS `GroupAnnotation` and confirm the `GroupAnnotation` case FAILS. Restore. Report the message.++- [x] **Step 5: Add the four backend functions**++In `apps/desktop/src/lib/backend/tauri.ts`, following the file's existing `invoke` idiom:++```ts+export async function collectDocsSnapshot(+ connectionId: string,+ database: string,+ schemas: string[],+ tables: string[],+ projectName?: string,+): Promise<SchemaSnapshot> {+ return invoke("docs_collect_snapshot", { connectionId, database, schemas, tables, projectName });+}++export async function loadDocsAnnotations(connectionId: string): Promise<AnnotationFile | null> {+ return invoke("docs_load_annotations", { connectionId });+}++export async function applyDocsAnnotations(+ connectionId: string,+ snapshot: SchemaSnapshot,+ annotations: AnnotationFile,+): Promise<SchemaSnapshot> {+ return invoke("docs_apply_annotations", { connectionId, snapshot, annotations });+}++export async function saveDocsAnnotations(connectionId: string, annotations: AnnotationFile): Promise<void> {+ return invoke("docs_save_annotations", { connectionId, annotations });+}+```++In `http.ts`, the same four signatures using that file's `post<T>(url, body)` helper (defined at+`http.ts:222`, which throws `backendResponseError` on a non-OK status and returns `res.json()`):++```ts+export async function collectDocsSnapshot(+ connectionId: string,+ database: string,+ schemas: string[],+ tables: string[],+ projectName?: string,+): Promise<SchemaSnapshot> {+ return post("/api/docs/snapshot", { connectionId, database, schemas, tables, projectName });+}++export async function loadDocsAnnotations(connectionId: string): Promise<AnnotationFile | null> {+ return post("/api/docs/annotations/load", { connectionId });+}++export async function applyDocsAnnotations(+ connectionId: string,+ snapshot: SchemaSnapshot,+ annotations: AnnotationFile,+): Promise<SchemaSnapshot> {+ return post("/api/docs/annotations/apply", { connectionId, snapshot, annotations });+}++export async function saveDocsAnnotations(connectionId: string, annotations: AnnotationFile): Promise<void> {+ return post("/api/docs/annotations/save", { connectionId, annotations });+}+```++**The two transports must expose identical signatures.** `api.ts` types the backend as `typeof TauriModule` and `forward()` re-exports by name, so a signature that differs between `tauri.ts` and `http.ts` is a type error at the facade — which is the only place it would ever be caught.++**Tauri serialises command arguments BY NAME.** The Rust commands take `connection_id`, `database`, `schemas`, `tables`, `project_name`, `snapshot`, `annotations`; Tauri converts camelCase to snake_case automatically, so the `invoke` object keys above must be exactly `connectionId`, `database`, `schemas`, `tables`, `projectName`, `snapshot`, `annotations`. A mismatch compiles cleanly on both sides and fails only at runtime when a user clicks.++In `api.ts`, beside the other forwards:++```ts+export const collectDocsSnapshot = forward("collectDocsSnapshot");+export const loadDocsAnnotations = forward("loadDocsAnnotations");+export const applyDocsAnnotations = forward("applyDocsAnnotations");+export const saveDocsAnnotations = forward("saveDocsAnnotations");+```++- [x] **Step 6: Verify and commit**++```bash+pnpm vitest run apps/desktop/src/docs+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs apps/desktop/src/lib/backend+git commit -m "feat(docs): expose docs snapshot and annotations to the frontend"+```++`vue-tsc` must be clean — `tauri.ts` and `http.ts` are type-checked, and a signature mismatch between them is exactly what `forward()` cannot catch.++---++## Task 5: Pure annotation edits++**Files:**+- Create: `apps/desktop/src/docs/annotationEdits.ts`+- Test: `apps/desktop/src/docs/__tests__/annotationEdits.spec.ts`++**Interfaces:**+- Consumes: `AnnotationFile`, `TableAnnotation`, `GroupAnnotation` (Task 4)+- Produces: `emptyAnnotations()`, `setProjectNote`, `setTableNote`, `setColumnNote`, `setTableGroup`, `upsertGroup`, `removeGroup` — every one `(file, ...args) => AnnotationFile`++- [x] **Step 1: Write the failing tests**++```ts+import { describe, expect, it } from "vitest";+import {+ emptyAnnotations,+ removeGroup,+ setColumnNote,+ setProjectNote,+ setTableGroup,+ setTableNote,+ upsertGroup,+} from "../annotationEdits";++const base = emptyAnnotations();++describe("annotationEdits", () => {+ it("starts from a valid empty file", () => {+ expect(emptyAnnotations()).toEqual({ formatVersion: 1 });+ });++ it("never mutates its input", () => {+ // Every function returns a new file. Mutating in place would make Vue's+ // reactivity miss the change and make undo impossible to add later.+ const before = JSON.stringify(base);+ setTableNote(base, "public.orders", "hello");+ expect(JSON.stringify(base)).toBe(before);+ });++ it("sets and clears a table note", () => {+ const withNote = setTableNote(base, "public.orders", "One row per checkout.");+ expect(withNote.tables?.["public.orders"].note).toBe("One row per checkout.");++ const cleared = setTableNote(withNote, "public.orders", " ");+ expect(cleared.tables?.["public.orders"]).toBeUndefined();+ });++ it("keeps a table entry when it still carries a group after the note clears", () => {+ // Dropping the whole entry here would silently unassign the group.+ const grouped = setTableGroup(setTableNote(base, "public.orders", "n"), "public.orders", "g1");+ const cleared = setTableNote(grouped, "public.orders", "");+ expect(cleared.tables?.["public.orders"].group).toBe("g1");+ expect(cleared.tables?.["public.orders"].note).toBeUndefined();+ });++ it("sets and clears a column note", () => {+ const withNote = setColumnNote(base, "public.orders", "status", "Lifecycle state.");+ expect(withNote.tables?.["public.orders"].columns?.status.note).toBe("Lifecycle state.");++ const cleared = setColumnNote(withNote, "public.orders", "status", "");+ expect(cleared.tables?.["public.orders"]).toBeUndefined();+ });++ it("upserts a group by id", () => {+ const created = upsertGroup(base, { id: "g1", name: "Core", hue: 28 });+ expect(created.groups).toEqual([{ id: "g1", name: "Core", hue: 28 }]);++ const renamed = upsertGroup(created, { id: "g1", name: "Core Accounts", hue: 200 });+ expect(renamed.groups).toHaveLength(1);+ expect(renamed.groups?.[0]).toEqual({ id: "g1", name: "Core Accounts", hue: 200 });+ });++ it("removing a group also clears every table that referenced it", () => {+ // A dangling groupId renders as no group at all, so the file would look+ // correct while carrying a reference to something that does not exist.+ const withGroup = setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1");+ const removed = removeGroup(withGroup, "g1");++ expect(removed.groups ?? []).toEqual([]);+ expect(removed.tables?.["public.orders"]).toBeUndefined();+ });++ it("removing a group keeps a table that still has a note", () => {+ const seeded = setTableNote(+ setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1"),+ "public.orders",+ "keep me",+ );+ const removed = removeGroup(seeded, "g1");+ expect(removed.tables?.["public.orders"].note).toBe("keep me");+ expect(removed.tables?.["public.orders"].group).toBeUndefined();+ });++ it("sets and clears the project note", () => {+ const withNote = setProjectNote(base, "# Sales\n\nThe billing schema.");+ expect(withNote.project?.note).toBe("# Sales\n\nThe billing schema.");+ expect(setProjectNote(withNote, "").project).toBeUndefined();+ });+});+```++- [x] **Step 2: Run and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/annotationEdits.spec.ts+```+Expected: FAIL — cannot resolve `../annotationEdits`.++- [x] **Step 3: Implement**++```ts+import type { AnnotationFile, GroupAnnotation, TableAnnotation } from "./types";++/**+ * Every function here returns a NEW file rather than mutating.+ *+ * Empty or whitespace-only prose removes the entry instead of storing "" —+ * the notes file is meant to be committed and reviewed, so it must not+ * accumulate keys holding nothing.+ */+export function emptyAnnotations(): AnnotationFile {+ return { formatVersion: 1 };+}++function blank(value: string): boolean {+ return value.trim() === "";+}++/** Drop a table entry once it carries neither a note nor a group. */+function pruneTable(tables: Record<string, TableAnnotation>, key: string): Record<string, TableAnnotation> {+ const entry = tables[key];+ const empty =+ entry !== undefined &&+ entry.note === undefined &&+ entry.group === undefined &&+ Object.keys(entry.columns ?? {}).length === 0;+ if (!empty) {+ return tables;+ }+ const { [key]: _dropped, ...rest } = tables;+ return rest;+}++function withTable(file: AnnotationFile, key: string, change: (entry: TableAnnotation) => TableAnnotation): AnnotationFile {+ const tables = { ...(file.tables ?? {}) };+ tables[key] = change(tables[key] ?? {});+ const pruned = pruneTable(tables, key);+ return { ...file, tables: Object.keys(pruned).length > 0 ? pruned : undefined };+}++export function setTableNote(file: AnnotationFile, tableKey: string, note: string): AnnotationFile {+ return withTable(file, tableKey, (entry) => {+ const { note: _old, ...rest } = entry;+ return blank(note) ? rest : { ...rest, note };+ });+}++export function setColumnNote(file: AnnotationFile, tableKey: string, column: string, note: string): AnnotationFile {+ return withTable(file, tableKey, (entry) => {+ const columns = { ...(entry.columns ?? {}) };+ if (blank(note)) {+ delete columns[column];+ } else {+ columns[column] = { note };+ }+ const { columns: _old, ...rest } = entry;+ return Object.keys(columns).length > 0 ? { ...rest, columns } : rest;+ });+}++export function setTableGroup(file: AnnotationFile, tableKey: string, groupId: string | null): AnnotationFile {+ return withTable(file, tableKey, (entry) => {+ const { group: _old, ...rest } = entry;+ return groupId === null ? rest : { ...rest, group: groupId };+ });+}++export function upsertGroup(file: AnnotationFile, group: GroupAnnotation): AnnotationFile {+ const groups = [...(file.groups ?? [])];+ const index = groups.findIndex((candidate) => candidate.id === group.id);+ if (index >= 0) {+ groups[index] = group;+ } else {+ groups.push(group);+ }+ return { ...file, groups };+}++/**+ * Remove a group and every reference to it.+ *+ * `docsIndex` already drops a dangling groupId when rendering, so the viewer+ * degrades correctly either way — but the committed file should not carry a+ * reference to a group that no longer exists.+ */+export function removeGroup(file: AnnotationFile, groupId: string): AnnotationFile {+ const groups = (file.groups ?? []).filter((group) => group.id !== groupId);+ let next: AnnotationFile = { ...file, groups };+ for (const [key, entry] of Object.entries(file.tables ?? {})) {+ if (entry.group === groupId) {+ next = setTableGroup(next, key, null);+ }+ }+ return next;+}++export function setProjectNote(file: AnnotationFile, note: string): AnnotationFile {+ const project = { ...(file.project ?? {}) };+ if (blank(note)) {+ delete project.note;+ } else {+ project.note = note;+ }+ return { ...file, project: Object.keys(project).length > 0 ? project : undefined };+}+```++- [x] **Step 4: Run and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/annotationEdits.spec.ts+```++- [x] **Step 5: Verify two guards bite**++One at a time, restoring between each. Report both failure messages.++1. In `removeGroup`, delete the loop that clears table references → `removing a group also clears every table that referenced it` must fail.+2. In `pruneTable`, drop the `entry.group === undefined` condition → `keeps a table entry when it still carries a group after the note clears` must fail.++- [x] **Step 6: Commit**++```bash+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs+git commit -m "feat(docs): add pure annotation edit transforms"+```++---++## Task 6: i18n namespace and the parity guard++**Files:**+- Create: `apps/desktop/src/i18n/locales/docs/{en,es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` — the namespace, one module per locale+- Modify: all 8 files in `apps/desktop/src/i18n/locales/` — import and spread their docs module+- Modify: `apps/desktop/src/docs/docsWarnings.ts` and its spec+- Create: `apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts`++**Why the namespace gets its own modules.** Every non-English locale is+`export default withEnglishFallback({ … })` — the fallback is applied AT MODULE LEVEL, inside the+locale file. Only `en.ts` is a bare object. So `import ja from "../locales/ja"` yields the+ALREADY-MERGED object, and a parity test comparing default exports would find every key present in+every locale and pass while translations were missing. The test written to catch silent English+fallback would be silently defeated by it.++Putting the new namespace in its own per-locale modules makes each locale's OWN keys importable+without the merge, which is the only way this property is observable at all. It is a small+structural change scoped entirely to the new namespace; the existing 315 KB of keys are untouched.++**Interfaces:**+- Produces: `describeWarning(warning: SnapshotWarning, translate: Translate): WarningNotice` — the existing return type, unchanged — where `type Translate = (key: string, params?: Record<string, string | number>) => string`++- [x] **Step 1: Write the failing parity test**++```ts+import { describe, expect, it } from "vitest";+import en from "../locales/docs/en";+import es from "../locales/docs/es";+import it_ from "../locales/docs/it";+import ja from "../locales/docs/ja";+import ko from "../locales/docs/ko";+import ptBR from "../locales/docs/pt-BR";+import zhCN from "../locales/docs/zh-CN";+import zhTW from "../locales/docs/zh-TW";++// These import the per-locale DOCS modules, NOT ../locales/<name>.+//+// Every non-English locale file is `export default withEnglishFallback({...})`,+// which deep-merges `en` UNDER the locale at module level. Importing those+// default exports yields the ALREADY-MERGED object, so every locale appears to+// have every key and this test would pass while translations were missing —+// the fallback would silently defeat the test written to catch it.+const locales: Array<[string, Record<string, unknown>]> = [+ ["es", es],+ ["it", it_],+ ["ja", ja],+ ["ko", ko],+ ["pt-BR", ptBR],+ ["zh-CN", zhCN],+ ["zh-TW", zhTW],+];++function leafKeys(value: unknown, prefix = ""): string[] {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return [prefix];+ }+ return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>+ leafKeys(child, prefix ? `${prefix}.${key}` : key),+ );+}++describe("docs i18n namespace parity", () => {+ const expected = leafKeys(en as Record<string, unknown>).sort();++ it("english declares the docs namespace", () => {+ expect(expected.length, "locales/docs/en.ts must declare keys").toBeGreaterThan(0);+ });++ it.each(locales)("%s declares exactly the same docs keys as en", (_name, locale) => {+ expect(leafKeys(locale).sort()).toEqual(expected);+ });+});+```++- [x] **Step 2: Run and watch it fail**++```bash+pnpm vitest run apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts+```+Expected: FAIL — no locale declares `docs`, so `leafKeys(undefined)` yields `[""]` and the English assertion fails first.++- [x] **Step 3: Create `apps/desktop/src/i18n/locales/docs/en.ts`**++```ts+export default {+ title: "Documentation",+ groupBySchema: "Schemas",+ groupByTableGroup: "Table Groups",+ noGroup: "(no group)",+ noSchema: "(no schema)",+ search: "Search tables, columns, groups…",+ columns: "Columns",+ indexes: "Indexes",+ references: "References",+ referencedBy: "Referenced by",+ localNote: "LOCAL",+ shadowedComment: "Database comment: {comment}",+ addNote: "Add a note",+ editNote: "Edit note",+ newGroup: "New group…",+ groupName: "Group name",+ groupColour: "Colour",+ deleteGroup: "Delete group",+ enumValues: "Values",+ usedBy: "Used by",+ openDiagram: "Open schema diagram",+ saving: "Saving…",+ saved: "Saved",+ saveFailed: "Could not save notes: {error}",+ warnings: {+ tableSkipped: "{table} could not be read: {reason}",+ noForeignKeyMetadata: "{engine} does not report foreign key metadata, so this schema has no relationships to show.",+ commentsUnsupported: "{engine} does not support table or column comments, so notes here come only from DBX.",+ orphanedNotes: "{count} note(s) refer to tables or columns that no longer exist. Nothing was deleted.",+ dbmlOmitted: "{item} on {table} was left out of the DBML: {reason}",+ },+};+```++Then in `apps/desktop/src/i18n/locales/en.ts`, import it and spread it in alphabetical position:++```ts+import docs from "./docs/en";+// …+ docs,+```++- [x] **Step 4: Translate into the other 7 locales**++Create `locales/docs/{es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` with the same key structure and translated+values, and wire each into its locale file the same way (`import docs from "./docs/ja";` … `docs,`). Keep every interpolation placeholder (`{table}`, `{engine}`, `{count}`, `{reason}`, `{item}`, `{comment}`, `{error}`) exactly as written — a translated placeholder name renders literally.++Keep technical terms in English where a developer would say them in English: for `pt-BR` that means "schema", "commit", "cache", "index" stay English while "banco de dados", "arquivo", "fila" are Portuguese.++- [x] **Step 5: Run the parity test**++```bash+pnpm vitest run apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts+```+Expected: PASS, 8 cases.++- [x] **Step 6: Verify it bites**++Delete one key from `locales/docs/ja.ts` and confirm the `ja` case FAILS naming that key. Restore. Report the message.++Then verify the test could not have been vacuous: temporarily point the imports at `../locales/<name>` instead of `../locales/docs/<name>`, delete a key from `locales/docs/ja.ts` again, and confirm the test now PASSES despite the missing key — that is the trap this structure exists to avoid. Restore both. Report what you saw.++- [x] **Step 7: Change `describeWarning` to take a translator**++`docsWarnings.ts` currently returns hardcoded English. Change its signature so `src/docs/` never imports vue-i18n — `useI18n()` throws without a provided instance, which is exactly the Part 3c export case:++```ts+export type Translate = (key: string, params?: Record<string, string | number>) => string;++export function describeWarning(warning: SnapshotWarning, translate: Translate): WarningNotice {+ switch (warning.kind) {+ case "tableSkipped":+ return { severity: "warning", text: translate("docs.warnings.tableSkipped", { table: warning.table, reason: warning.reason }) };+ // …one arm per variant, each calling translate with the same params the+ // existing English strings interpolate. Keep the exhaustive switch with+ // NO default arm — the missing-arm compile error is the guard.+ }+}+```++Update `docsWarnings.spec.ts` to pass a fake translator that returns `` `${key}:${JSON.stringify(params)}` ``, and assert on that rather than on English prose. The tests then check the key and params, which is what actually matters now.++- [x] **Step 8: Verify and commit**++```bash+pnpm vitest run apps/desktop/src/docs apps/desktop/src/i18n+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+git add apps/desktop/src/docs apps/desktop/src/i18n+git commit -m "feat(docs): add the docs i18n namespace with a parity guard"+```++---++## Task 7: Editing components++**Files:**+- Create: `apps/desktop/src/docs/components/NoteEditor.vue`, `GroupEditor.vue`, `GroupPicker.vue`+- Modify: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`++**Interfaces:**+- Consumes: `renderNote` (Part 3a), `groupStyle` (Part 3a), `GroupAnnotation` (Task 4)+- Produces: `NoteEditor` (`modelValue: string`, `readonly: boolean`, emits `update:modelValue`), `GroupEditor` (`group: GroupAnnotation`, emits `update:group`, `delete`), `GroupPicker` (`groups: GroupAnnotation[]`, `modelValue: string | null`, emits `update:modelValue`, `create`)++- [x] **Step 1: Extend the contract test**++In `componentContract.spec.ts`, update `EXPECTED` to include the three new files, and add:++```ts+ it("editing components accept a readonly mode", () => {+ // Part 3c renders these same components with editing off inside an+ // exported HTML file. A component that cannot be made read-only would+ // have to be forked for the export.+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ const editors = files.filter((file) => path.basename(file) === "NoteEditor.vue");+ expect(editors.length).toBe(1);+ expect(readFileSync(editors[0], "utf8")).toContain("readonly");+ });+```++- [x] **Step 2: Run and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts+```+Expected: FAIL on the file list — the three components do not exist.++- [x] **Step 3: Build the three components**++`NoteEditor.vue` — renders `renderNote` output until clicked, then a raw markdown textarea. The `v-html` must bind `renderNote(...)`; the contract test enforces it in either quote style. When `readonly` is true it never becomes editable.++`GroupEditor.vue` — a name input plus the hue picker from the approved mock: 12 preset swatches, a+`<input type="range" min="0" max="359">`, and a preview element rendering the colour on light and+dark grounds at once.++**Match the swatch idiom DBX already uses**, in `ConnectionDialog.vue:4921-4931` — a row of+`h-6 w-6 rounded-full border` buttons inside `flex items-center gap-1.5`, selected state+`ring-2 ring-ring ring-offset-2`, unselected `border-border`, each with a `:title` from an i18n key.+Read it before writing yours so the new picker looks native rather than invented.++**But do NOT copy how it fills them.** Connection colours are hex values painted with Tailwind+classes (`bg-green-500`, `#22c55e`). Group colours are hues: the swatch must carry+`class="docs-group"` and `:style="groupStyle(hue)"` on the SAME element, and the colour is decided+by `docs.css`. The contract test forbids `oklch(` and six-digit hex literals in these components,+so a naive copy of `ConnectionDialog`'s approach fails the test — correctly, because a hardcoded+hex cannot stay legible on both light and dark grounds, which is the entire reason groups store a+hue rather than a colour.++`GroupPicker.vue` — a `<select>` over `groups` plus a "New group…" option emitting `create`.++All three: `<script setup lang="ts">`, Tailwind with DBX token names (`bg-background`, `text-foreground`, `border-border`, `text-muted-foreground`), no store or backend imports, all strings via a `translate` prop or `t` passed from the parent — never `useI18n()` inside `src/docs/`.++- [x] **Step 4: Run the contract test**++```bash+pnpm vitest run apps/desktop/src/docs+```++- [x] **Step 5: Verify the v-html guard still bites on the new file**++Change `NoteEditor.vue`'s `v-html="renderNote(modelValue)"` to `v-html='modelValue'` (single quotes, raw value) and confirm the contract test FAILS. Restore. Report the message. This is the single most dangerous thing a template here can do — a database `COMMENT ON` value going straight to the DOM.++- [x] **Step 6: Commit**++```bash+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs+git commit -m "feat(docs): add note editor, group editor and group picker"+```++---++## Task 8: Enum page++**Files:**+- Create: `apps/desktop/src/docs/components/EnumPage.vue`+- Create: `apps/desktop/src/docs/docsKeys.ts`+- Modify: `apps/desktop/src/docs/docsIndex.ts`, `docsSearch.ts`, `DocsApp.vue`, `components/DocsSidebar.vue`, `components/WikiIndex.vue` (and any other component holding a `tableKey` copy), `apps/desktop/src/docs/__tests__/docsIndex.spec.ts`, `componentContract.spec.ts` (`EXPECTED`)++**Interfaces:**+- Produces: `columnsUsingEnum(snapshot: SchemaSnapshot, enumName: string): Array<{ tableKey: string; table: string; column: string }>`++- [x] **Step 1: Write the failing test**++Add to `docsIndex.spec.ts`:++```ts+ // The file's existing helper is `table(schema, name, groupId)` and builds a+ // table with NO columns, so these tests need columns attached. Add this+ // helper beside it rather than changing the existing signature — the other+ // tests in this file call it positionally.+ function withColumns(base: DocTable, columns: Array<{ name: string; type: string }>): DocTable {+ return {+ ...base,+ columns: columns.map((column) => ({+ name: column.name,+ data_type: column.type,+ is_nullable: false,+ column_default: null,+ is_primary_key: false,+ extra: "",+ comment: null,+ numeric_precision: null,+ numeric_scale: null,+ character_maximum_length: null,+ })),+ };+ }++ function snapshotOf(tables: DocTable[], enums: SchemaSnapshot["enums"]): SchemaSnapshot {+ return {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables,+ relationships: [],+ groups: [],+ enums,+ warnings: [],+ };+ }++ it("finds every column using an enum, across tables", () => {+ const snapshot = snapshotOf(+ [+ withColumns(table("public", "orders"), [{ name: "status", type: "order_status" }]),+ withColumns(table("public", "returns"), [{ name: "state", type: "order_status" }]),+ withColumns(table("public", "users"), [{ name: "id", type: "integer" }]),+ ],+ [{ schema: "public", name: "order_status", values: ["new"], note: null, synthesized: false }],+ );++ expect(columnsUsingEnum(snapshot, "order_status")).toEqual([+ { tableKey: "public.orders", table: "orders", column: "status" },+ { tableKey: "public.returns", table: "returns", column: "state" },+ ]);+ });++ it("returns nothing for an enum no column references", () => {+ // Must not fall back to "every column" or to a substring match — an enum+ // named `state` would otherwise claim every column whose type contains it.+ const snapshot = snapshotOf(+ [withColumns(table("public", "users"), [{ name: "id", type: "integer" }])],+ [{ schema: "public", name: "state", values: ["a"], note: null, synthesized: false }],+ );+ expect(columnsUsingEnum(snapshot, "state")).toEqual([]);+ });+```++Import `DocTable` and `SchemaSnapshot` as types if the spec file does not already. The `ColumnInfo` field list above is the full required set the conformance test pins — omitting one is a type error.++- [ ] **Step 2: Run and watch it fail** <!-- not performed: columnsUsingEnum was already implemented and committed before this step was reached, so the failure was never observed. The exact-match guard was instead verified by Step 5. -->++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsIndex.spec.ts+```+Expected: FAIL — `columnsUsingEnum` is not exported.++- [x] **Step 3: Implement**++```ts+/**+ * Every column whose declared type is this enum.+ *+ * Exact match on `data_type`, never a substring: an enum named `state` would+ * otherwise claim every column of type `estado` or `statement`.+ */+export function columnsUsingEnum(+ snapshot: SchemaSnapshot,+ enumName: string,+): Array<{ tableKey: string; table: string; column: string }> {+ const hits: Array<{ tableKey: string; table: string; column: string }> = [];+ for (const table of snapshot.tables) {+ for (const column of table.columns) {+ if (column.data_type === enumName) {+ hits.push({ tableKey: qualifiedTableKey(table), table: table.name, column: column.name });+ }+ }+ }+ return hits;+}+```++**The qualified table key is currently duplicated at least four times**, and this task would add a+fifth. Extract it first, into a new `apps/desktop/src/docs/docsKeys.ts`:++```ts+import type { DocTable } from "./types";++/**+ * The key that identifies a table across the viewer — `schema.name`, or the+ * bare name on schema-less engines like SQLite and MySQL.+ *+ * This rule was copied into four places before it lived here. It is the key+ * that annotations are stored under, so two call sites disagreeing would+ * attach a note to the wrong table.+ */+export function qualifiedTableKey(table: DocTable): string {+ return table.schema ? `${table.schema}.${table.name}` : table.name;+}+```++Then replace every existing copy with an import of it:+- `docsSearch.ts:12` — the private `qualified(schema, name)`. It is called with loose arguments in+ places, so either adapt those call sites or keep a thin local wrapper that delegates; say which+ you did.+- `DocsApp.vue:22`, `components/DocsSidebar.vue:19`, `components/WikiIndex.vue:15` — each has its+ own `tableKey(table)`. Check the remaining components for further copies and replace those too;+ report how many you found in total.++Note `docsIndex.ts` does NOT contain a copy — it groups by `table.schema ?? ""`, which is a+*section* key, not a table key. Do not change that.++This extraction is in scope deliberately: Part 3a's final review flagged the duplication as a+Minor and it was deferred, and this task is the moment a new consumer appears.++- [x] **Step 4: Run and watch it pass, then build `EnumPage.vue`**++A thin template: the enum's qualified name, its values, its note via `NoteEditor`, and the `columnsUsingEnum` list with each entry clickable to that table. Add it to `EXPECTED` in the contract test.++- [x] **Step 5: Verify it bites**++Change `column.data_type === enumName` to `column.data_type.includes(enumName)` and confirm `returns nothing for an enum no column references` FAILS. Restore. Report the message.++- [x] **Step 6: Commit**++```bash+pnpm vitest run apps/desktop/src/docs+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+git add apps/desktop/src/docs+git commit -m "feat(docs): add the enum page and its reverse column lookup"+```++---++## Task 9: Wire editing through `DocsApp`++**Files:**+- Modify: `apps/desktop/src/docs/DocsApp.vue` and the components it renders+- Modify: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`++**Interfaces:**+- Produces: `DocsApp` props `snapshot: SchemaSnapshot`, `annotations: AnnotationFile`, `readonly?: boolean`, `translate: Translate`; emits `edit` with a discriminated payload++**`snapshot` and `translate` already exist** on `DocsApp` (`translate` was added when the i18n task+made `describeWarning` take a translator). You are ADDING `annotations` and `readonly` to the+existing `defineProps`, not writing it from scratch. `readonly` is the only optional one.++- [x] **Step 1: Define the edit payload**++In `apps/desktop/src/docs/types.ts`:++```ts+/**+ * What the viewer asks its host to do. The viewer never persists anything —+ * that is what keeps `src/docs/` free of backend calls and bundleable into a+ * standalone HTML file.+ */+export type DocsEdit =+ | { kind: "projectNote"; note: string }+ | { kind: "tableNote"; tableKey: string; note: string }+ | { kind: "columnNote"; tableKey: string; column: string; note: string }+ | { kind: "tableGroup"; tableKey: string; groupId: string | null }+ | { kind: "upsertGroup"; group: GroupAnnotation }+ | { kind: "removeGroup"; groupId: string };+```++- [x] **Step 2: Add the contract test**++```ts+ it("the viewer emits edits rather than persisting them", () => {+ // src/docs/ must stay free of I/O so Part 3c can bundle it. Editing works+ // by emitting upward; the dialog outside this directory does the saving.+ const files = vueFiles();+ expect(files.length).toBe(EXPECTED.length);+ for (const file of files) {+ const source = readFileSync(file, "utf8");+ for (const needle of ["saveDocsAnnotations", "loadDocsAnnotations", "applyDocsAnnotations"]) {+ expect(source.includes(needle), `${path.basename(file)} must not call ${needle}`).toBe(false);+ }+ }+ });+```++- [x] **Step 3: Thread `readonly` and `annotations` down; emit `edit` up**++`translate` is already threaded to `WarningBanner`; extend the same pattern to the other components as they gain strings.++`DocsApp` gains the props and re-emits `edit` from its children. Each component renders a `NoteEditor` where a note belongs and emits the matching `DocsEdit`. When `readonly` is true, no editor is interactive and `GroupEditor` / `GroupPicker` are not rendered.++- [x] **Step 4: Verify and commit**++```bash+pnpm vitest run apps/desktop/src/docs+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs+git commit -m "feat(docs): thread editing through the viewer as emitted events"+```++`vue-tsc` is the only thing type-checking these templates — treat any error as the real test and report it rather than suppressing it.++---++## Task 10: The dialog, autosave, and wiring++**Files:**+- Create: `apps/desktop/src/components/docs/DatabaseDocsDialog.vue`+- Create: `apps/desktop/src/components/docs/__tests__/docsAutosave.spec.ts`+- Create: `apps/desktop/src/components/docs/docsAutosave.ts`+- Modify: `apps/desktop/src/stores/connectionStore.ts`, `apps/desktop/src/composables/useDialogSources.ts`, `apps/desktop/src/components/layout/AppDialogs.vue`++**Interfaces:**+- Consumes: everything above+- Produces: `createAutosave(save, delayMs)` returning `{ schedule(file), status, flush() }`++- [x] **Step 1: Write the failing autosave tests**++Autosave logic goes in a `.ts` file so it is testable without mounting anything:++```ts+import { describe, expect, it, vi } from "vitest";+import { createAutosave } from "../docsAutosave";++const file = { formatVersion: 1 } as const;++describe("createAutosave", () => {+ it("coalesces rapid edits into one save", async () => {+ vi.useFakeTimers();+ const save = vi.fn().mockResolvedValue(undefined);+ const autosave = createAutosave(save, 500);++ autosave.schedule(file);+ autosave.schedule(file);+ autosave.schedule(file);+ expect(save).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(500);+ expect(save).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it("surfaces a failure instead of swallowing it", async () => {+ // A silently swallowed write failure is the worst outcome this feature+ // can produce: the user keeps typing and believes their notes are saved.+ vi.useFakeTimers();+ const save = vi.fn().mockRejectedValue(new Error("disk full"));+ const autosave = createAutosave(save, 500);++ autosave.schedule(file);+ await vi.advanceTimersByTimeAsync(500);++ expect(autosave.status.value.state).toBe("failed");+ expect(autosave.status.value.message).toContain("disk full");+ vi.useRealTimers();+ });++ it("reports saved after a successful write", async () => {+ vi.useFakeTimers();+ const autosave = createAutosave(vi.fn().mockResolvedValue(undefined), 500);+ autosave.schedule(file);+ await vi.advanceTimersByTimeAsync(500);+ expect(autosave.status.value.state).toBe("saved");+ vi.useRealTimers();+ });++ it("never runs two saves concurrently", async () => {+ // flush() clears the timer, but a debounced write may already be awaiting+ // save. Starting a second one issues two concurrent writes of the same+ // file — a wasted round trip, a stale-write race, and the exact+ // concurrency that corrupts the notes file.+ let concurrent = 0;+ let maxConcurrent = 0;+ const save = vi.fn().mockImplementation(async () => {+ concurrent += 1;+ maxConcurrent = Math.max(maxConcurrent, concurrent);+ await new Promise((resolve) => setTimeout(resolve, 10));+ concurrent -= 1;+ });++ const autosave = createAutosave(save, 0);+ autosave.schedule(file);+ await Promise.all([autosave.flush(), autosave.flush(), autosave.flush()]);++ expect(maxConcurrent).toBe(1);+ });++ it("flush writes immediately without waiting for the timer", async () => {+ // The dialog calls this on close, so a note typed a moment earlier is+ // not lost to a pending debounce.+ const save = vi.fn().mockResolvedValue(undefined);+ const autosave = createAutosave(save, 500);+ autosave.schedule(file);+ await autosave.flush();+ expect(save).toHaveBeenCalledTimes(1);+ });+});+```++- [x] **Step 2: Run and watch it fail**++```bash+pnpm vitest run apps/desktop/src/components/docs/__tests__/docsAutosave.spec.ts+```+Expected: FAIL — cannot resolve `../docsAutosave`.++- [x] **Step 3: Implement `docsAutosave.ts`**++```ts+import { ref, type Ref } from "vue";+import type { AnnotationFile } from "@/docs/types";++export type SaveStatus =+ | { state: "idle" }+ | { state: "saving" }+ | { state: "saved" }+ | { state: "failed"; message: string };++export interface Autosave {+ schedule: (file: AnnotationFile) => void;+ flush: () => Promise<void>;+ status: Ref<SaveStatus>;+}++/**+ * Debounced autosave.+ *+ * A failed write MUST become visible: the user keeps typing and believes+ * their notes are saved otherwise. The pending file is retained on failure so+ * the next edit retries rather than discarding what they wrote.+ */+export function createAutosave(save: (file: AnnotationFile) => Promise<void>, delayMs: number): Autosave {+ const status = ref<SaveStatus>({ state: "idle" });+ let timer: ReturnType<typeof setTimeout> | undefined;+ let pending: AnnotationFile | undefined;+ // The write currently in flight, if any. `flush()` clearing the timer is not+ // enough: a debounced write may already be awaiting `save`, and starting a+ // second one issues two concurrent saves of the same file. Beyond wasting a+ // round trip, the later one can land stale, and it is the exact concurrency+ // that corrupted the notes file before the Rust side used a unique temp path.+ let inFlight: Promise<void> | undefined;++ async function write(): Promise<void> {+ if (inFlight !== undefined) {+ // Wait for the current write, then run again if an edit arrived while it+ // was going — never two at once.+ await inFlight;+ if (pending === undefined) {+ return;+ }+ }+ if (pending === undefined) {+ return;+ }+ const file = pending;+ status.value = { state: "saving" };+ const attempt = (async () => {+ try {+ await save(file);+ // Only clear if no newer edit arrived while this was in flight.+ if (pending === file) {+ pending = undefined;+ }+ status.value = { state: "saved" };+ } catch (error) {+ status.value = { state: "failed", message: error instanceof Error ? error.message : String(error) };+ }+ })();+ inFlight = attempt;+ try {+ await attempt;+ } finally {+ if (inFlight === attempt) {+ inFlight = undefined;+ }+ }+ }++ return {+ status,+ schedule(file) {+ pending = file;+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ timer = setTimeout(() => void write(), delayMs);+ },+ async flush() {+ if (timer !== undefined) {+ clearTimeout(timer);+ timer = undefined;+ }+ await write();+ },+ };+}+```++- [x] **Step 4: Run and watch it pass**++- [x] **Step 5: Build the dialog**++**The dialog shell, matching `SchemaDiagramDialog.vue` — the closest comparable feature:**++```vue+<script setup lang="ts">+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import DocsApp from "@/docs/DocsApp.vue";++const props = defineProps<{+ open: boolean;+ prefillConnectionId: string;+ prefillDatabase: string;+ prefillSchema?: string;+}>();++const emit = defineEmits<{ "update:open": [value: boolean] }>();++// The get/set computed is how every dialog in this codebase bridges the+// `open` prop to `v-model:open` on <Dialog>.+const dialogOpen = computed({+ get: () => props.open,+ set: (value) => emit("update:open", value),+});++// This component lives OUTSIDE src/docs/, so it may and must use useI18n():+// it is what supplies the `translate` prop that the viewer components need,+// since they are banned from importing vue-i18n themselves.+const { t } = useI18n();+</script>++<template>+ <Dialog v-model:open="dialogOpen">+ <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>+ <DialogTitle>{{ t("docs.title") }}</DialogTitle>+ </DialogHeader>+ <!-- snapshot / annotations / translate / readonly=false down, `edit` up -->+ </DialogContent>+ </Dialog>+</template>+```++The sizing class is copied verbatim from `SchemaDiagramDialog.vue:827`. The docs viewer is the same+kind of thing — a full-window workspace rather than a form — so it should not invent its own+dimensions.+++`DatabaseDocsDialog.vue` — props `open`, `prefillConnectionId`, `prefillDatabase`, `prefillSchema`. On open: `collectDocsSnapshot(...)` for the raw snapshot, `loadDocsAnnotations(...)` for the file (falling back to `emptyAnnotations()` when null), then `applyDocsAnnotations(...)` for what it displays. Holds the raw snapshot for re-derivation.++On an `edit` event from `DocsApp`: apply the matching `annotationEdits` function, `schedule` the autosave, and call `applyDocsAnnotations` to refresh the display. Show the save status. Call `flush()` before closing. Use `useI18n()` HERE — the dialog is outside `src/docs/` — and pass `t` down as the `translate` prop. Add a button opening the existing schema diagram via `connectionStore.diagramSource`.++- [x] **Step 6: Wire the trigger**++The schema diagram uses this exact five-point wiring. Mirror it — I verified every location:++1. **`apps/desktop/src/stores/connectionStore.ts:381`** — `diagramSource` is+ `ref<{ connectionId: string; database: string; schema?: string; tableName?: string } | null>(null)`,+ returned from the store at line 6928. Add `docsSource` with the same shape beside it, and export it+ the same way.++2. **`apps/desktop/src/composables/useDialogSources.ts` (~line 162)** — a `watch` on+ `connectionStore.diagramSource` copies the prefills, sets `showDiagramDialog.value = true`, then+ clears the source back to `null`. **Clearing it is what makes the dialog re-openable** — without+ that, setting the same value twice does not re-trigger the watcher. Add the docs equivalent.++3. **`apps/desktop/src/components/layout/AppDialogs.vue:13`** — `defineAsyncComponent(() => import(...))`,+ and **line 198** — rendered with `v-if="dialogs.showDiagramDialog.value"`,+ `v-model:open`, and the prefill props. Follow both.++4. **`apps/desktop/src/components/objects/ObjectBrowser.vue:1428`** — `openDiagram(row)` sets+ `connectionStore.diagramSource = { connectionId: props.connection.id, database: props.database,+ schema: row.schema || selectedSchema.value, tableName: ... }`. Add `openDocs(row)` the same way.++5. **`apps/desktop/src/components/objects/ObjectBrowser.vue:2605`** — the context-menu entry, shaped+ `...(canOpenDiagram.value ? [{ label: t("diagram.open"), action: () => openDiagram(row) }] : [])`.+ Add the docs entry beside it using `t("docs.title")` from the namespace Task 6 added.++**ObjectBrowser is the right entry point**, not the connection tree: the tree has no `diagram.open`+entry either, and the docs dialog takes exactly the prefills ObjectBrowser already supplies+(connection, database, schema). If a tree-level entry is wanted later it is one more call site+setting the same `docsSource`.++- [x] **Step 7: Verify two guards bite**++One at a time, restoring between each. Report both failure messages.++1. Make the `catch` in `write()` swallow its error (`catch { pending = undefined; }`) → `surfaces a failure instead of swallowing it` must fail.+2. Delete the `inFlight` guard at the top of `write()` → `never runs two saves concurrently` must fail.++- [x] **Step 8: Full verification and commit**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+pnpm vitest run apps/desktop/src+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+pnpm exec oxlint --vue-plugin apps/desktop/src/docs apps/desktop/src/components/docs+cargo test --workspace+git add apps/desktop/src src-tauri+git commit -m "feat(docs): mount the documentation viewer in DBX with autosaved editing"+```++---++## Done criteria++- Documentation opens from the connection tree, and edits to notes and group colours survive closing and reopening the dialog.+- Pointing `docs_notes_path` at a repository file produces a reviewable diff.+- `apps/desktop/src/docs/**/*.vue` still makes zero backend calls and persists nothing, enforced by the contract test.+- All 8 locales declare the same `docs` keys, enforced by a test.+- A failed save is visible and does not discard the user's work.+- `cargo test --workspace` and `pnpm vitest run apps/desktop/src` pass; `vue-tsc` and `oxlint` clean.++## Deferred to Part 3c++The standalone Vite bundle and self-contained HTML export; the `dbx docs` verb; hash routing; a minimal read-only ER renderer for the export; inlining `apps/desktop/public/fonts/geist-latin-wght-normal.woff2`; and closing the `DocEnum` fixture gap, since an exportable demo wants an enum-bearing schema anyway.diff --git a/docs/superpowers/plans/2026-08-03-database-documentation-viewer.md b/docs/superpowers/plans/2026-08-03-database-documentation-viewer.mdnew file mode 100644index 0000000000..6f4b755149--- /dev/null+++ b/docs/superpowers/plans/2026-08-03-database-documentation-viewer.md@@ -0,0 +1,1536 @@+# Database Documentation Part 3a: Docs Viewer — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Build the dbdocs-style documentation viewer as a standalone Vue app that renders a `SchemaSnapshot` and makes **zero backend calls** — the contract that later lets the same components run inside DBX and inside an exported HTML file.++**Architecture:** All decision-making logic lives in pure `.ts` modules under `apps/desktop/src/docs/` with thorough vitest coverage. The `.vue` files are thin templates verified by static SFC parsing, matching this repo's established `erDiagram.ts` (tested) / `SchemaDiagramDialog.vue` (untested) split. TypeScript interfaces mirror the Rust `SchemaSnapshot`; a committed fixture generated from **real Rust output** plus a conformance test turns model drift into a failing test rather than a silent bug.++**Tech Stack:** Vue 3 + TypeScript + Tailwind v4, vitest. No new dependencies.++**Branch:** continue on `feature/docs-snapshot-dbml` (Parts 1+2, 31 commits, unmerged). Worktree at `/Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml`.++**Spec:** `docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md`, Section 6.++**Approved visual reference:** the mock at the group/table/diagram level — sidebar with `Group by: Schemas | Table Groups`, wiki index with inline markdown notes, table page with columns/indexes/bidirectional relationships, `⬤ LOCAL` shadow marker, warning banner.++## Global Constraints++- **NO new dependencies.** In particular **do NOT add `@vue/test-utils`** — this repo has never mounted a component in a test and deliberately has no such harness.+- **`cargo` is NOT on PATH.** Prefix Rust commands with+ `export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"`.+- **`apps/desktop/src/docs/` makes NO backend calls.** No `@/lib/backend/*`, no Tauri, no Pinia stores, no `fetch`. Snapshot in, DOM out. A test enforces this.+- **Logic in `.ts`, templates thin.** If a `.vue` file contains a non-trivial decision (filtering, sorting, formatting, colour maths), that decision belongs in a `.ts` module with a test.+- **Group colour is a hue integer.** Lightness/chroma are theme-controlled in CSS; never store or compute hex in the viewer.+- Run `pnpm lint` scoped to the touched directory, never repo-wide (root `pnpm lint` OOMs on this repo).+- Conventional Commits.+- **Report mismatches, do not work around them.** Twenty plan defects across Parts 1-2 were caught that way.++---++## Pre-resolved facts (verified — these override any assumption in the spec)++1. **The spec's testing plan does not work here.** Section 6 says "every docs component rendered against fixture snapshot JSON". This repo has **no component-mount harness**: `@vue/test-utils` is not a dependency and zero specs call `mount()`. `packages/app-tests/aiAssistantSendGuard.test.ts:13` documents this in a comment. The established pattern for verifying a `.vue` file is **static SFC parsing** via `readFileSync` + `vue/compiler-sfc`'s `parse`.++2. **No Rust→TypeScript codegen exists.** `apps/desktop/src/types/database.ts` is a hand-maintained 1167-line mirror. Part 3a therefore hand-writes TS interfaces for `SchemaSnapshot` — a genuine drift seam. Task 2's conformance test is the mitigation.++3. **vitest config** (`vitest.config.ts`): `@vitejs/plugin-vue` loaded; alias `@` → `apps/desktop/src`; `include` covers `apps/desktop/src/**/*.spec.ts`; `maxWorkers: 4`; `globalSetup: packages/test-globals.ts`. **No `environment:` is set**, so there is no DOM — another reason component mounting is out of scope.++4. **`node_modules` does not exist** in this worktree or the main checkout. `pnpm install` is Task 0.++5. **Rust field names arrive as camelCase.** `SchemaSnapshot` and friends use `#[serde(rename_all = "camelCase")]`, so the JSON has `formatVersion`, `noteSource`, `shadowedNote`, `columnNotes`, `groupId`, `estimatedRows`, `viewDefinition`.++6. **`SnapshotWarning` is the exception.** It uses `#[serde(rename_all = "camelCase", tag = "kind")]`, so its discriminant is `{ "kind": "tableSkipped", ... }` — **camelCase**, unlike `TableKind`/`NoteSource`/`Cardinality` which are SCREAMING_SNAKE (`"MATERIALIZED_VIEW"`, `"LOCAL"`, `"MANY_TO_ONE"`). Getting this wrong silently breaks warning rendering.++---++## File Structure++| File | Responsibility |+| --- | --- |+| `apps/desktop/src/docs/types.ts` | TS interfaces mirroring the Rust `SchemaSnapshot` |+| `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` | Real snapshot from a live database, committed |+| `apps/desktop/src/docs/docsIndex.ts` | Sidebar/index model: schema grouping, table-group grouping, `(no group)` bucket |+| `apps/desktop/src/docs/docsSearch.ts` | Client-side search over tables, columns, groups, enums |+| `apps/desktop/src/docs/docsWarnings.ts` | `SnapshotWarning` → human-readable banner text |+| `apps/desktop/src/docs/groupColor.ts` | Hue → CSS custom properties (never hex) |+| `apps/desktop/src/docs/DocsApp.vue` + `components/*.vue` | Thin templates |+| `apps/desktop/src/docs/__tests__/*.spec.ts` | vitest coverage for every `.ts` module + SFC guards |++---++## Task 0: Environment setup++- [ ] **Step 1: Install dependencies**++There is no `node_modules` in this worktree. From the worktree root:++```bash+cd /Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml+pnpm install+```++This takes several minutes and downloads 1-3GB. **Disk is at ~45Gi free — if you hit ENOSPC, STOP and report it; do not delete anything.**++- [ ] **Step 2: Confirm the baseline**++```bash+pnpm vitest run apps/desktop/src/lib/__tests__ --reporter=dot+git branch --show-current # must be feature/docs-snapshot-dbml+git status --short # must be empty apart from node_modules being ignored+```++Expected: tests pass, branch correct. If `pnpm install` fails or tests fail before you have changed anything, STOP and report — Part 3a builds on Parts 1-2 and a broken baseline makes every later failure ambiguous.++---++## Task 1: Snapshot types++**Files:**+- Create: `apps/desktop/src/docs/types.ts`+- Test: `apps/desktop/src/docs/__tests__/types.spec.ts`++**Interfaces:**+- Produces: `SchemaSnapshot`, `ProjectMeta`, `DocTable`, `TableGroup`, `Relationship`, `FieldRef`, `ColumnNote`, `DocEnum`, `TableKind`, `NoteSource`, `Cardinality`, `SnapshotWarning`++**Casing is load-bearing.** Struct fields are camelCase; `TableKind`/`NoteSource`/`Cardinality` are SCREAMING_SNAKE strings; `SnapshotWarning` is internally tagged with a **camelCase** `kind`.++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, it } from "vitest";+import type { SchemaSnapshot, SnapshotWarning } from "../types";++describe("snapshot types", () => {+ it("accepts a minimal snapshot shaped like the Rust output", () => {+ const snapshot: SchemaSnapshot = {+ formatVersion: 1,+ project: {+ name: "Ecommerce",+ databaseType: "postgres",+ database: "shop",+ schemas: ["public"],+ generatedAt: "2026-08-03T00:00:00Z",+ note: null,+ },+ tables: [+ {+ schema: "public",+ name: "orders",+ kind: "TABLE",+ columns: [],+ indexes: [],+ foreignKeys: [],+ groupId: null,+ note: "Checkout rows.",+ noteSource: "DATABASE",+ shadowedNote: null,+ columnNotes: {},+ estimatedRows: null,+ viewDefinition: null,+ },+ ],+ relationships: [],+ groups: [],+ enums: [],+ warnings: [],+ };++ expect(snapshot.tables[0].noteSource).toBe("DATABASE");+ expect(snapshot.tables[0].kind).toBe("TABLE");+ });++ it("discriminates warnings on a camelCase kind", () => {+ // Rust: #[serde(rename_all = "camelCase", tag = "kind")] — so the+ // discriminant is camelCase even though sibling enums are SCREAMING_SNAKE.+ const warning: SnapshotWarning = {+ kind: "tableSkipped",+ table: "public.secret",+ reason: "permission denied",+ };+ expect(warning.kind).toBe("tableSkipped");++ const orphans: SnapshotWarning = { kind: "orphanedNotes", count: 3 };+ if (orphans.kind === "orphanedNotes") {+ expect(orphans.count).toBe(3);+ } else {+ throw new Error("discriminated union must narrow on kind");+ }+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/types.spec.ts+```+Expected: FAIL — cannot resolve `../types`.++- [ ] **Step 3: Write the types**++Create `apps/desktop/src/docs/types.ts`:++```ts+// Mirrors crates/dbx-core/src/docs/snapshot.rs. There is no Rust->TS codegen+// in this repo, so this file is maintained by hand — see+// __tests__/fixtureConformance.spec.ts, which validates it against a snapshot+// generated by the real Rust code and fails if the two drift apart.++export type TableKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW";+export type NoteSource = "DATABASE" | "LOCAL" | "NONE";+export type Cardinality = "ONE_TO_ONE" | "MANY_TO_ONE";++export interface ColumnInfo {+ name: string;+ data_type: string;+ is_nullable: boolean;+ column_default: string | null;+ is_primary_key: boolean;+ extra: string | null;+ comment?: string | null;+ numeric_precision?: number | null;+ numeric_scale?: number | null;+ character_maximum_length?: number | null;+ enum_values?: string[] | null;+}++export interface IndexInfo {+ name: string;+ columns: string[];+ is_unique: boolean;+ is_primary: boolean;+ filter?: string | null;+ index_type?: string | null;+ included_columns?: string[] | null;+ comment?: string | null;+}++export interface ForeignKeyInfo {+ name: string;+ column: string;+ ref_schema?: string | null;+ ref_table: string;+ ref_column: string;+ on_update?: string | null;+ on_delete?: string | null;+}++export interface ProjectMeta {+ name: string;+ databaseType: string;+ database: string | null;+ schemas: string[];+ generatedAt: string;+ note: string | null;+}++export interface ColumnNote {+ note: string;+ source: NoteSource;+ shadowed: string | null;+}++export interface DocTable {+ schema: string | null;+ name: string;+ kind: TableKind;+ columns: ColumnInfo[];+ indexes: IndexInfo[];+ foreignKeys: ForeignKeyInfo[];+ groupId: string | null;+ note: string | null;+ noteSource: NoteSource;+ shadowedNote: string | null;+ columnNotes: Record<string, ColumnNote>;+ estimatedRows: number | null;+ viewDefinition: string | null;+}++export interface TableGroup {+ id: string;+ name: string;+ /** 0-359. Lightness and chroma are theme-controlled in CSS. */+ hue: number;+ note: string | null;+}++export interface FieldRef {+ schema: string | null;+ table: string;+ column: string;+}++export interface Relationship {+ id: string;+ name: string | null;+ from: FieldRef;+ to: FieldRef;+ cardinality: Cardinality;+ onUpdate: string | null;+ onDelete: string | null;+}++export interface DocEnum {+ schema: string | null;+ name: string;+ values: string[];+ note: string | null;+ synthesized: boolean;+}++/**+ * Internally tagged on a camelCase `kind`. Note this differs from+ * TableKind/NoteSource/Cardinality, which are SCREAMING_SNAKE — the Rust enum+ * carries both `tag = "kind"` and `rename_all = "camelCase"`.+ */+export type SnapshotWarning =+ | { kind: "tableSkipped"; table: string; reason: string }+ | { kind: "noForeignKeyMetadata"; engine: string }+ | { kind: "commentsUnsupported"; engine: string }+ | { kind: "orphanedNotes"; count: number }+ | { kind: "dbmlOmitted"; table: string; item: string; reason: string };++export interface SchemaSnapshot {+ formatVersion: number;+ project: ProjectMeta;+ tables: DocTable[];+ relationships: Relationship[];+ groups: TableGroup[];+ enums: DocEnum[];+ warnings: SnapshotWarning[];+}+```++Note `ColumnInfo`/`IndexInfo`/`ForeignKeyInfo` keep **snake_case** field names: those Rust structs come from `crate::types` and do NOT carry `rename_all`. Task 2's conformance test will confirm this against real output — if it disagrees, fix this file, not the test.++- [ ] **Step 4: Run it and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/types.spec.ts+```+Expected: PASS, 2 tests.++- [ ] **Step 5: Commit**++```bash+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs/+git commit -m "feat(docs): add snapshot types for the docs viewer"+```++---++## Task 2: Real fixture + drift guard++**Files:**+- Create: `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` (generated, committed)+- Create: `apps/desktop/src/docs/__tests__/fixtureConformance.spec.ts`+- Create: `crates/dbx-core/tests/dump_docs_fixture.rs`++**This is the task that closes the drift seam.** The fixture must come from the real Rust serializer, not be hand-written — a hand-written fixture would encode the same assumptions as `types.ts` and prove nothing.++**A live PostgreSQL is available:** `127.0.0.1:5432`, `postgres`/`postgres`, database `keycloak` (90 tables).++- [ ] **Step 1: Write the Rust dumper**++Create `crates/dbx-core/tests/dump_docs_fixture.rs`, copying the gating and setup from `crates/dbx-core/tests/live_postgres_docs_annotations.rs` (`#[tokio::test]`, `#[ignore = "..."]`, env vars with defaults, the `live_postgres_config(...)` builder). It must collect a snapshot of schema `public` from `keycloak`, apply a small in-memory `AnnotationFile` so that notes, a group and an orphan all appear, then write `serde_json::to_string_pretty(&snapshot)` to the path given by `DBX_FIXTURE_OUT`, defaulting to `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` relative to the repo root.++Include annotations covering every field the viewer must render: a table note, a column note, a group with a hue, and an annotation for a nonexistent table so an `orphanedNotes` warning is present.++- [ ] **Step 2: Generate the fixture**++```bash+export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"+DBX_LIVE_POSTGRES_HOST=127.0.0.1 DBX_LIVE_POSTGRES_PORT=5432 \+DBX_LIVE_POSTGRES_USER=postgres DBX_LIVE_POSTGRES_PASSWORD=postgres \+DBX_LIVE_POSTGRES_DATABASE=keycloak \+cargo test -p dbx-core --test dump_docs_fixture -- --ignored --nocapture+```++Then confirm the file exists and contains real data:++```bash+head -30 apps/desktop/src/docs/fixtures/keycloak.snapshot.json+grep -c '"name"' apps/desktop/src/docs/fixtures/keycloak.snapshot.json+```++**Report the file size.** If it exceeds ~500KB, trim to the first 12 tables inside the dumper (keeping the annotated table, the group and the orphan warning) rather than committing a huge fixture.++- [ ] **Step 3: Write the conformance test**++```ts+import { readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import type { SchemaSnapshot } from "../types";++const fixturePath = path.resolve(__dirname, "../fixtures/keycloak.snapshot.json");++function loadFixture(): SchemaSnapshot {+ return JSON.parse(readFileSync(fixturePath, "utf8")) as SchemaSnapshot;+}++describe("fixture conformance", () => {+ // This fixture is generated by the REAL Rust serializer. Its job is to fail+ // when the Rust model changes shape, so the hand-maintained types.ts cannot+ // drift silently.++ it("has the shape types.ts declares", () => {+ const snapshot = loadFixture();+ expect(snapshot.formatVersion).toBe(1);+ expect(Array.isArray(snapshot.tables)).toBe(true);+ expect(snapshot.tables.length).toBeGreaterThan(0);+ expect(typeof snapshot.project.databaseType).toBe("string");+ expect(Array.isArray(snapshot.project.schemas)).toBe(true);+ });++ it("uses camelCase for snapshot-owned fields", () => {+ const raw = JSON.parse(readFileSync(fixturePath, "utf8")) as Record<string, unknown>;+ expect(raw).toHaveProperty("formatVersion");+ expect(raw).not.toHaveProperty("format_version");++ const table = (raw.tables as Record<string, unknown>[])[0];+ expect(table).toHaveProperty("noteSource");+ expect(table).toHaveProperty("columnNotes");+ expect(table).toHaveProperty("foreignKeys");+ expect(table).not.toHaveProperty("note_source");+ });++ it("keeps snake_case on columns, which come from crate::types", () => {+ const snapshot = loadFixture();+ const withColumns = snapshot.tables.find((table) => table.columns.length > 0);+ expect(withColumns, "fixture must contain at least one table with columns").toBeDefined();+ const column = withColumns!.columns[0] as unknown as Record<string, unknown>;+ expect(column).toHaveProperty("data_type");+ expect(column).toHaveProperty("is_nullable");+ expect(column).not.toHaveProperty("dataType");+ });++ it("carries an annotated note, a group and an orphan warning", () => {+ const snapshot = loadFixture();++ const annotated = snapshot.tables.find((table) => table.noteSource === "LOCAL");+ expect(annotated, "fixture must include a LOCAL-sourced note").toBeDefined();+ expect(annotated!.note).toBeTruthy();++ expect(snapshot.groups.length).toBeGreaterThan(0);+ expect(typeof snapshot.groups[0].hue).toBe("number");++ const orphan = snapshot.warnings.find((warning) => warning.kind === "orphanedNotes");+ expect(orphan, "fixture must include an orphanedNotes warning").toBeDefined();+ });++ it("every warning discriminant is one types.ts knows", () => {+ const known = new Set([+ "tableSkipped",+ "noForeignKeyMetadata",+ "commentsUnsupported",+ "orphanedNotes",+ "dbmlOmitted",+ ]);+ for (const warning of loadFixture().warnings) {+ expect(known.has(warning.kind), `unknown warning kind: ${warning.kind}`).toBe(true);+ }+ });+});+```++- [ ] **Step 4: Run it**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/fixtureConformance.spec.ts+```+Expected: PASS, 5 tests.++**If any assertion fails, the fixture is telling you `types.ts` is wrong — fix `types.ts`, not the test.** Report exactly which field disagreed; that is a real Rust/TS mismatch and I want to know about it.++- [ ] **Step 5: Commit**++```bash+git add apps/desktop/src/docs/ crates/dbx-core/tests/dump_docs_fixture.rs+git commit -m "feat(docs): add a real-output fixture and drift conformance test"+```++---++## Task 3: Index model (grouping)++**Files:**+- Create: `apps/desktop/src/docs/docsIndex.ts`+- Test: `apps/desktop/src/docs/__tests__/docsIndex.spec.ts`++**Interfaces:**+- Produces: `groupBySchema(snapshot): IndexSection[]`, `groupByTableGroup(snapshot): IndexSection[]`, `interface IndexSection { key: string; label: string; hue: number | null; note: string | null; tables: DocTable[] }`++This is the `Group by: Schemas | Table Groups` switch from the approved mock, including the `(no group)` bucket.++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, it } from "vitest";+import { groupBySchema, groupByTableGroup } from "../docsIndex";+import type { DocTable, SchemaSnapshot, TableGroup } from "../types";++function table(schema: string | null, name: string, groupId: string | null = null): DocTable {+ return {+ schema, name, kind: "TABLE", columns: [], indexes: [], foreignKeys: [],+ groupId, note: null, noteSource: "NONE", shadowedNote: null,+ columnNotes: {}, estimatedRows: null, viewDefinition: null,+ };+}++function snapshot(tables: DocTable[], groups: TableGroup[] = []): SchemaSnapshot {+ return {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables, relationships: [], groups, enums: [], warnings: [],+ };+}++describe("groupBySchema", () => {+ it("groups tables under their schema, sorted by schema then name", () => {+ const sections = groupBySchema(snapshot([+ table("public", "orders"),+ table("analytics", "daily_sales"),+ table("public", "customers"),+ ]));++ expect(sections.map((section) => section.key)).toEqual(["analytics", "public"]);+ expect(sections[1].tables.map((t) => t.name)).toEqual(["customers", "orders"]);+ });++ it("puts schema-less tables in a single bare section", () => {+ const sections = groupBySchema(snapshot([table(null, "orders")]));+ expect(sections).toHaveLength(1);+ expect(sections[0].tables[0].name).toBe("orders");+ });+});++describe("groupByTableGroup", () => {+ const groups: TableGroup[] = [+ { id: "order-mgmt", name: "Order Management", hue: 28, note: "Checkout." },+ { id: "product-mgmt", name: "Product Management", hue: 148, note: null },+ ];++ it("groups tables by their group, preserving the snapshot's group order", () => {+ const sections = groupByTableGroup(snapshot([+ table("product", "products", "product-mgmt"),+ table("core", "orders", "order-mgmt"),+ ], groups));++ expect(sections.map((section) => section.key)).toEqual(["order-mgmt", "product-mgmt"]);+ expect(sections[0].label).toBe("Order Management");+ expect(sections[0].hue).toBe(28);+ expect(sections[0].note).toBe("Checkout.");+ });++ it("collects ungrouped tables into a trailing (no group) section", () => {+ const sections = groupByTableGroup(snapshot([+ table("core", "orders", "order-mgmt"),+ table("core", "users", null),+ ], groups));++ const last = sections[sections.length - 1];+ expect(last.key).toBe("");+ expect(last.hue).toBeNull();+ expect(last.tables.map((t) => t.name)).toEqual(["users"]);+ });++ it("omits a group that has no members", () => {+ // render_group in the serializer skips empty groups; the viewer must not+ // show an empty header where the DBML shows nothing.+ const sections = groupByTableGroup(snapshot([table("core", "orders", "order-mgmt")], groups));+ expect(sections.map((section) => section.key)).not.toContain("product-mgmt");+ });++ it("treats a table whose groupId names no group as ungrouped", () => {+ const sections = groupByTableGroup(snapshot([table("core", "orders", "ghost")], groups));+ expect(sections).toHaveLength(1);+ expect(sections[0].key).toBe("");+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsIndex.spec.ts+```+Expected: FAIL — cannot resolve `../docsIndex`.++- [ ] **Step 3: Implement**++```ts+import type { DocTable, SchemaSnapshot } from "./types";++export interface IndexSection {+ /** Schema name, group id, or "" for the ungrouped bucket. */+ key: string;+ label: string;+ /** Group hue, or null for schema sections and the ungrouped bucket. */+ hue: number | null;+ note: string | null;+ tables: DocTable[];+}++function byName(a: DocTable, b: DocTable): number {+ return a.name.localeCompare(b.name);+}++export function groupBySchema(snapshot: SchemaSnapshot): IndexSection[] {+ const sections = new Map<string, DocTable[]>();+ for (const table of snapshot.tables) {+ const key = table.schema ?? "";+ const bucket = sections.get(key);+ if (bucket) {+ bucket.push(table);+ } else {+ sections.set(key, [table]);+ }+ }++ return [...sections.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([key, tables]) => ({+ key,+ label: key,+ hue: null,+ note: null,+ tables: [...tables].sort(byName),+ }));+}++export function groupByTableGroup(snapshot: SchemaSnapshot): IndexSection[] {+ const known = new Map(snapshot.groups.map((group) => [group.id, group]));+ const sections: IndexSection[] = [];++ // Snapshot order is the notes file's order — the user's own arrangement.+ for (const group of snapshot.groups) {+ const tables = snapshot.tables.filter((table) => table.groupId === group.id).sort(byName);+ // An empty group renders nothing, matching render_group in the serializer.+ if (tables.length === 0) {+ continue;+ }+ sections.push({+ key: group.id,+ label: group.name,+ hue: group.hue,+ note: group.note,+ tables,+ });+ }++ // A groupId naming no known group is treated as ungrouped rather than+ // creating a phantom section.+ const ungrouped = snapshot.tables+ .filter((table) => table.groupId === null || !known.has(table.groupId))+ .sort(byName);++ if (ungrouped.length > 0) {+ sections.push({ key: "", label: "(no group)", hue: null, note: null, tables: ungrouped });+ }++ return sections;+}+```++- [ ] **Step 4: Run it and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsIndex.spec.ts+```+Expected: PASS, 6 tests.++- [ ] **Step 5: Commit**++```bash+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs/+git commit -m "feat(docs): add index grouping for the docs viewer"+```++---++## Task 4: Warning presentation++**Files:**+- Create: `apps/desktop/src/docs/docsWarnings.ts`+- Test: `apps/desktop/src/docs/__tests__/docsWarnings.spec.ts`++**Interfaces:**+- Produces: `describeWarning(warning: SnapshotWarning): WarningNotice`, `interface WarningNotice { severity: "info" | "warning"; title: string; detail: string }`++**Why this matters:** the feature's stated principle is "degrade visibly, never silently". These strings are how degradation becomes visible. A warning rendered as `[object Object]` — which is what happens if the camelCase discriminant is mismatched — defeats the whole mechanism.++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, it } from "vitest";+import { describeWarning } from "../docsWarnings";+import type { SnapshotWarning } from "../types";++describe("describeWarning", () => {+ it("explains a skipped table as a warning naming the table and reason", () => {+ const notice = describeWarning({ kind: "tableSkipped", table: "public.secret", reason: "permission denied" });+ expect(notice.severity).toBe("warning");+ expect(notice.detail).toContain("public.secret");+ expect(notice.detail).toContain("permission denied");+ });++ it("explains missing foreign-key metadata as an engine limitation, not a fault", () => {+ const notice = describeWarning({ kind: "noForeignKeyMetadata", engine: "ClickHouse" });+ expect(notice.detail).toContain("ClickHouse");+ // The diagram will have no edges — the user must learn why.+ expect(notice.detail.toLowerCase()).toContain("relationship");+ });++ it("explains unsupported comments", () => {+ const notice = describeWarning({ kind: "commentsUnsupported", engine: "SQLite" });+ expect(notice.detail).toContain("SQLite");+ });++ it("reports orphaned notes with the count", () => {+ const notice = describeWarning({ kind: "orphanedNotes", count: 3 });+ expect(notice.detail).toContain("3");+ });++ it("explains a DBML omission naming the item", () => {+ const notice = describeWarning({+ kind: "dbmlOmitted",+ table: "public.orders",+ item: "idx_orders_open",+ reason: "partial index filter has no DBML equivalent",+ });+ expect(notice.severity).toBe("info");+ expect(notice.detail).toContain("idx_orders_open");+ });++ it("never returns an empty or placeholder string for any known kind", () => {+ const samples: SnapshotWarning[] = [+ { kind: "tableSkipped", table: "t", reason: "r" },+ { kind: "noForeignKeyMetadata", engine: "e" },+ { kind: "commentsUnsupported", engine: "e" },+ { kind: "orphanedNotes", count: 1 },+ { kind: "dbmlOmitted", table: "t", item: "i", reason: "r" },+ ];+ for (const sample of samples) {+ const notice = describeWarning(sample);+ expect(notice.title.length, `empty title for ${sample.kind}`).toBeGreaterThan(0);+ expect(notice.detail.length, `empty detail for ${sample.kind}`).toBeGreaterThan(0);+ expect(notice.detail).not.toContain("[object Object]");+ expect(notice.detail).not.toContain("undefined");+ }+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsWarnings.spec.ts+```+Expected: FAIL — cannot resolve `../docsWarnings`.++- [ ] **Step 3: Implement**++```ts+import type { SnapshotWarning } from "./types";++export interface WarningNotice {+ severity: "info" | "warning";+ title: string;+ detail: string;+}++/**+ * Turn a snapshot warning into something a reader can act on.+ *+ * This is where "degrade visibly, never silently" becomes literal: if a table+ * could not be read, or an engine cannot report relationships, the reader has+ * to learn that from the page rather than infer it from an absence.+ */+export function describeWarning(warning: SnapshotWarning): WarningNotice {+ switch (warning.kind) {+ case "tableSkipped":+ return {+ severity: "warning",+ title: "A table could not be documented",+ detail: `${warning.table} was skipped: ${warning.reason}. It is missing from this documentation.`,+ };+ case "noForeignKeyMetadata":+ return {+ severity: "info",+ title: "No relationships available",+ detail: `${warning.engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.`,+ };+ case "commentsUnsupported":+ return {+ severity: "info",+ title: "Database comments unavailable",+ detail: `${warning.engine} does not support table or column comments, so every description here comes from this project's own notes.`,+ };+ case "orphanedNotes":+ return {+ severity: "warning",+ title: "Some notes no longer match anything",+ detail: `${warning.count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.`,+ };+ case "dbmlOmitted":+ return {+ severity: "info",+ title: "Not representable in DBML",+ detail: `${warning.item} on ${warning.table} is documented here but omitted from the exported DBML: ${warning.reason}.`,+ };+ }+}+```++- [ ] **Step 4: Run it and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsWarnings.spec.ts+```+Expected: PASS, 6 tests.++- [ ] **Step 5: Commit**++```bash+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs/+git commit -m "feat(docs): describe snapshot warnings for the viewer"+```++---++## Task 5: Search++**Files:**+- Create: `apps/desktop/src/docs/docsSearch.ts`+- Test: `apps/desktop/src/docs/__tests__/docsSearch.spec.ts`++**Interfaces:**+- Produces: `searchDocs(snapshot, query): SearchHit[]`, `interface SearchHit { kind: "table" | "column" | "group" | "enum"; label: string; context: string; tableKey: string | null }`++This is the ⌘K palette from the approved mock.++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, it } from "vitest";+import { searchDocs } from "../docsSearch";+import type { DocTable, SchemaSnapshot } from "../types";++function column(name: string) {+ return {+ name, data_type: "text", is_nullable: true, column_default: null,+ is_primary_key: false, extra: null,+ };+}++function table(schema: string, name: string, columns: string[] = []): DocTable {+ return {+ schema, name, kind: "TABLE", columns: columns.map(column), indexes: [], foreignKeys: [],+ groupId: null, note: null, noteSource: "NONE", shadowedNote: null,+ columnNotes: {}, estimatedRows: null, viewDefinition: null,+ };+}++const snapshot: SchemaSnapshot = {+ formatVersion: 1,+ project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },+ tables: [table("public", "orders", ["status", "total"]), table("public", "customers", ["status"])],+ relationships: [],+ groups: [{ id: "g1", name: "Order Management", hue: 28, note: null }],+ enums: [{ schema: "public", name: "order_status", values: ["pending"], note: null, synthesized: false }],+ warnings: [],+};++describe("searchDocs", () => {+ it("returns nothing for an empty query", () => {+ expect(searchDocs(snapshot, "")).toEqual([]);+ expect(searchDocs(snapshot, " ")).toEqual([]);+ });++ it("matches table names case-insensitively", () => {+ const hits = searchDocs(snapshot, "ORD");+ expect(hits.some((hit) => hit.kind === "table" && hit.label === "orders")).toBe(true);+ });++ it("matches columns and reports which table they belong to", () => {+ const hits = searchDocs(snapshot, "total");+ const hit = hits.find((candidate) => candidate.kind === "column");+ expect(hit).toBeDefined();+ expect(hit!.label).toBe("total");+ expect(hit!.context).toContain("orders");+ });++ it("returns one hit per table for a column name shared by several tables", () => {+ const hits = searchDocs(snapshot, "status").filter((hit) => hit.kind === "column");+ expect(hits).toHaveLength(2);+ expect(hits.map((hit) => hit.context).sort()).toEqual(["public.customers", "public.orders"]);+ });++ it("matches groups and enums", () => {+ expect(searchDocs(snapshot, "Order Man").some((hit) => hit.kind === "group")).toBe(true);+ expect(searchDocs(snapshot, "order_status").some((hit) => hit.kind === "enum")).toBe(true);+ });++ it("ranks table matches above column matches for the same term", () => {+ // Someone typing "orders" almost always wants the table.+ const hits = searchDocs(snapshot, "orders");+ expect(hits[0].kind).toBe("table");+ });++ it("carries a tableKey so a hit can navigate", () => {+ const hit = searchDocs(snapshot, "total").find((candidate) => candidate.kind === "column");+ expect(hit!.tableKey).toBe("public.orders");+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsSearch.spec.ts+```+Expected: FAIL — cannot resolve `../docsSearch`.++- [ ] **Step 3: Implement**++```ts+import type { SchemaSnapshot } from "./types";++export interface SearchHit {+ kind: "table" | "column" | "group" | "enum";+ label: string;+ /** Where the hit lives — a qualified table name, or a count for groups. */+ context: string;+ /** Qualified table name for navigation, or null for groups and enums. */+ tableKey: string | null;+}++function qualified(schema: string | null, name: string): string {+ return schema ? `${schema}.${name}` : name;+}++/**+ * Case-insensitive substring search over the whole snapshot.+ *+ * Tables rank first: someone typing a table's name almost always wants the+ * table, not a column that happens to share the word.+ */+export function searchDocs(snapshot: SchemaSnapshot, query: string): SearchHit[] {+ const needle = query.trim().toLowerCase();+ if (needle.length === 0) {+ return [];+ }++ const tables: SearchHit[] = [];+ const columns: SearchHit[] = [];++ for (const table of snapshot.tables) {+ const key = qualified(table.schema, table.name);+ if (table.name.toLowerCase().includes(needle)) {+ tables.push({ kind: "table", label: table.name, context: key, tableKey: key });+ }+ for (const column of table.columns) {+ if (column.name.toLowerCase().includes(needle)) {+ columns.push({ kind: "column", label: column.name, context: key, tableKey: key });+ }+ }+ }++ const groups: SearchHit[] = snapshot.groups+ .filter((group) => group.name.toLowerCase().includes(needle))+ .map((group) => ({+ kind: "group",+ label: group.name,+ context: `${snapshot.tables.filter((table) => table.groupId === group.id).length} tables`,+ tableKey: null,+ }));++ const enums: SearchHit[] = snapshot.enums+ .filter((value) => value.name.toLowerCase().includes(needle))+ .map((value) => ({+ kind: "enum",+ label: value.name,+ context: `${value.values.length} values`,+ tableKey: null,+ }));++ return [...tables, ...columns, ...groups, ...enums];+}+```++- [ ] **Step 4: Run it and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/docsSearch.spec.ts+```+Expected: PASS, 7 tests.++- [ ] **Step 5: Commit**++```bash+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs/+git commit -m "feat(docs): add client-side search for the docs viewer"+```++---++## Task 6: Group colour++**Files:**+- Create: `apps/desktop/src/docs/groupColor.ts`+- Test: `apps/desktop/src/docs/__tests__/groupColor.spec.ts`++**Interfaces:**+- Produces: `groupStyle(hue: number | null): Record<string, string>`++**The design rule:** a group stores ONE number, a hue. Lightness and chroma are fixed per theme in CSS, so every hue is legible on both light and dark grounds by construction. The viewer must never compute hex — that would defeat the whole scheme and reintroduce the dark-mode mud problem the mock solved.++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, it } from "vitest";+import { groupStyle } from "../groupColor";++describe("groupStyle", () => {+ it("exposes the hue as a CSS custom property", () => {+ expect(groupStyle(28)).toEqual({ "--h": "28" });+ });++ it("returns no custom property for an ungrouped section", () => {+ expect(groupStyle(null)).toEqual({});+ });++ it("wraps hues into 0-359 rather than emitting an out-of-range value", () => {+ expect(groupStyle(360)).toEqual({ "--h": "0" });+ expect(groupStyle(388)).toEqual({ "--h": "28" });+ expect(groupStyle(-1)).toEqual({ "--h": "359" });+ });++ it("never emits a colour value", () => {+ // Lightness and chroma belong to the theme. If this function ever returns+ // a hex or oklch string, the dark-mode contrast guarantee is gone.+ const style = groupStyle(200);+ const serialized = JSON.stringify(style);+ expect(serialized).not.toContain("#");+ expect(serialized).not.toContain("oklch");+ expect(serialized).not.toContain("rgb");+ });++ it("coerces a non-integer hue to an integer", () => {+ expect(groupStyle(28.7)).toEqual({ "--h": "28" });+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/groupColor.spec.ts+```+Expected: FAIL — cannot resolve `../groupColor`.++- [ ] **Step 3: Implement**++```ts+/**+ * Inline style exposing a table group's hue to CSS.+ *+ * A group stores ONE number. Lightness and chroma are fixed per theme in the+ * stylesheet — `--group-c: oklch(0.55 0.15 var(--h))` in light,+ * `oklch(0.76 0.13 var(--h))` in dark — so every hue is legible on both+ * grounds by construction. Computing a colour here would throw that away.+ */+export function groupStyle(hue: number | null): Record<string, string> {+ if (hue === null) {+ return {};+ }+ const wrapped = ((Math.trunc(hue) % 360) + 360) % 360;+ return { "--h": String(wrapped) };+}+```++- [ ] **Step 4: Run it and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/groupColor.spec.ts+```+Expected: PASS, 5 tests.++- [ ] **Step 5: Commit**++```bash+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs/+git commit -m "feat(docs): expose group hue as a CSS custom property"+```++---++## Task 7: Note markdown rendering++> **This brief was corrected by the controller after empirically probing `[email protected]`.**+> The original plan text contained three defects: an assertion that fails against a correct+> implementation, a suggested approach that double-escapes HTML entities, and a URL filter+> with several live bypasses. Everything below has been run against the installed `marked`+> and its exact output verified. Use it verbatim.++**Files:**+- Create: `apps/desktop/src/docs/renderNote.ts`+- Test: `apps/desktop/src/docs/__tests__/renderNote.spec.ts`++**Interfaces:**+- Produces: `renderNote(markdown: string | null): string`++**Notes are markdown.** `[email protected]` is already a dependency — do NOT add one, and do NOT+add a sanitiser (no DOMPurify).++**This is the security-relevant task in Part 3a.** Note text comes from two places, and one of+them — `COMMENT ON` values — lives in the *database*, which is not always under the document+author's control. In Part 3b the same renderer runs inside a standalone HTML file people forward+to colleagues. So raw HTML must be escaped, not rendered, and unsafe URL schemes must be dropped.++**Verified facts about `marked@18` you must not re-derive:**+- It escapes nothing by default. `<script>alert(1)</script>` passes straight through.+- It does **not** block `javascript:`, `vbscript:`, or `data:` URLs in links or images.+- Pre-escaping the source string before parsing is **wrong** — it double-escapes entities, so+ `a & b` renders as the literal text `a & b` instead of `a & b`.+- In the `link` renderer, the `text` property is the **raw markdown source**, not parsed HTML.+ Returning it directly is an XSS hole and also breaks `**bold**` inside link text. You must use+ `this.parser.parseInline(tokens)` instead.++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, it } from "vitest";+import { renderNote } from "../renderNote";++describe("renderNote", () => {+ it("renders ordinary markdown", () => {+ expect(renderNote("One row per **checkout**.")).toContain("<strong>checkout</strong>");+ });++ it("renders inline code and fenced blocks", () => {+ expect(renderNote("see `order_status`")).toContain("<code>order_status</code>");+ expect(renderNote("```sql\nSELECT 1;\n```")).toContain("<pre>");+ });++ it("returns an empty string for null or blank input", () => {+ expect(renderNote(null)).toBe("");+ expect(renderNote(" ")).toBe("");+ });++ it("escapes a script tag rather than rendering it", () => {+ const html = renderNote("<script>alert(1)</script>");+ expect(html).not.toContain("<script>");+ expect(html).toContain("<script>");+ });++ it("escapes an img onerror payload", () => {+ // NB: asserting !contains("onerror=") would FAIL against a correct+ // implementation — the escaped text legitimately still contains that+ // substring. What matters is that no <img> ELEMENT is produced.+ const html = renderNote('<img src=x onerror="alert(1)">');+ expect(html.toLowerCase()).not.toContain("<img");+ expect(html).toContain("<img");+ });++ it("escapes raw HTML even when it looks harmless", () => {+ // Blanket rule: no author-supplied HTML is rendered, ever. A rule with+ // exceptions is a rule someone will find a way around.+ const html = renderNote("<b>bold</b>");+ expect(html).not.toContain("<b>bold</b>");+ expect(html).toContain("<b>");+ });++ it("does not preserve HTML entities twice", () => {+ // Guards the pre-escaping approach, which turns "a & b" into+ // "a &amp; b" and renders the entity visibly to the reader.+ expect(renderNote("a & b")).toContain("a & b");+ expect(renderNote("a & b")).not.toContain("&amp;");+ });++ it.each([+ ["javascript:alert(1)", "javascript"],+ ["JaVaScRiPt:alert(1)", "javascript"],+ ["javascript:alert(1)", "avascript"],+ ["vbscript:alert(1)", "vbscript"],+ ["data:text/html;base64,PHNjcmlwdD4=", "data:"],+ ])("drops the unsafe link scheme %s", (href, forbidden) => {+ const html = renderNote(`[click](${href})`).toLowerCase();+ expect(html).not.toContain(forbidden);+ expect(html).toContain("click"); // the text survives; only the href is dropped+ });++ it("drops an unsafe image scheme", () => {+ const html = renderNote(")").toLowerCase();+ expect(html).not.toContain("javascript");+ expect(html).not.toContain("<img");+ });++ it.each(["https://example.com", "http://example.com", "mailto:[email protected]", "#anchor", "./rel.html"])(+ "keeps the safe link target %s",+ (href) => {+ expect(renderNote(`[ok](${href})`)).toContain(`href="${href}"`);+ },+ );++ it("parses markdown inside link text instead of emitting it raw", () => {+ // marked hands the renderer the RAW source text. Emitting it directly+ // both breaks formatting and injects unescaped HTML.+ expect(renderNote("[**keep**](https://example.com)")).toContain("<strong>keep</strong>");+ const dropped = renderNote('[<img src=x onerror="alert(1)">](javascript:alert(1))');+ expect(dropped.toLowerCase()).not.toContain("<img");+ expect(dropped).toContain("<img");+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/renderNote.spec.ts+```+Expected: FAIL — cannot resolve `../renderNote`.++- [ ] **Step 3: Implement**++This exact implementation was run against `[email protected]` and every assertion above verified.++```ts+import { Marked } from "marked";++/** Escape the five characters that can break out of text or an attribute value. */+function escapeHtml(value: unknown): string {+ return String(value ?? "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """);+}++/**+ * URL allowlist. Blocklists lose: `javascript:` alone misses `JaVaScRiPt:`,+ * the entity-encoded `javascript:`, `vbscript:` and `data:text/html`.+ * Permitting only what we understand is both shorter and complete.+ */+const SAFE_SCHEME = /^(https?:|mailto:)/i;++function safeUrl(raw: unknown): string | null {+ const url = String(raw ?? "").trim();+ if (url === "") {+ return null;+ }+ if (url.startsWith("#") || url.startsWith("/") || url.startsWith("./") || url.startsWith("../")) {+ return url;+ }+ return SAFE_SCHEME.test(url) ? url : null;+}++const renderer = new Marked({+ renderer: {+ // Raw HTML in the source is shown as text, never rendered.+ html({ text }) {+ return escapeHtml(text);+ },+ link({ href, title, tokens }) {+ // `tokens`, not `text` — `text` is the raw markdown source, so returning+ // it would emit author HTML unescaped and swallow inline formatting.+ const inner = this.parser.parseInline(tokens);+ const safe = safeUrl(href);+ if (safe === null) {+ return inner;+ }+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";+ return `<a href="${escapeHtml(safe)}"${titleAttr}>${inner}</a>`;+ },+ image({ href, title, text }) {+ const safe = safeUrl(href);+ if (safe === null) {+ return escapeHtml(text);+ }+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";+ return `<img src="${escapeHtml(safe)}" alt="${escapeHtml(text)}"${titleAttr}>`;+ },+ },+});++/** Render a note's markdown to HTML with all author-supplied HTML escaped. */+export function renderNote(markdown: string | null): string {+ if (markdown === null || markdown.trim() === "") {+ return "";+ }+ return renderer.parse(markdown) as string;+}+```++If `vue-tsc` objects to the renderer callback signatures, fix the types rather than the+behaviour, and report what you changed. Do NOT loosen the escaping to satisfy the compiler.++- [ ] **Step 4: Run it and watch it pass**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/renderNote.spec.ts+```++- [ ] **Step 5: Verify the guards are real — three deliberate breaks**++One at a time, restoring between each. Report each failure message.++1. Delete the `html` renderer override entirely → the script-tag, img and `<b>` tests must fail.+2. Change `safeUrl` to `return url;` unconditionally → the unsafe-scheme cases must fail.+3. In `link`, replace `this.parser.parseInline(tokens)` with the token's `text` property →+ the "parses markdown inside link text" test must fail.++If any deliberate break does NOT produce a failure, stop and tell me — that means the test is+not actually pinning the guard, which is the exact defect this step exists to catch.++- [ ] **Step 6: Commit**++```bash+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+git add apps/desktop/src/docs/+git commit -m "feat(docs): render note markdown with raw HTML escaped"+```++Confirm `git status` is clean after your restores, so no deliberate break leaks into the commit.++---++## Task 8: Components++**Files:**+- Create: `apps/desktop/src/docs/DocsApp.vue`+- Create: `apps/desktop/src/docs/components/DocsSidebar.vue`, `WikiIndex.vue`, `TablePage.vue`, `ColumnTable.vue`, `RelationshipList.vue`, `WarningBanner.vue`, `DocsSearch.vue`+- Test: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`++Templates only. Every decision they display comes from Tasks 3-7. The visual reference is the approved mock: sidebar with the Group-by switch, wiki index with inline notes, table page with columns / indexes / bidirectional relationships, the `⬤ LOCAL` shadow marker, and the warning banner.++**Because this repo has no component-mount harness, verification is static SFC parsing** — copy the technique from `packages/app-tests/aiAssistantSendGuard.test.ts` (`readFileSync` + `parse` from `vue/compiler-sfc`).++- [ ] **Step 1: Write the contract test**++```ts+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { parse } from "vue/compiler-sfc";++const docsRoot = path.resolve(__dirname, "..");++function vueFiles(): string[] {+ const found: string[] = [];+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory() && entry.name !== "__tests__" && entry.name !== "fixtures") {+ walk(full);+ } else if (entry.isFile() && entry.name.endsWith(".vue")) {+ found.push(full);+ }+ }+ };+ walk(docsRoot);+ return found;+}++function scriptOf(file: string): string {+ const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });+ return `${descriptor.script?.content ?? ""}\n${descriptor.scriptSetup?.content ?? ""}`;+}++describe("docs viewer component contract", () => {+ it("finds the expected components", () => {+ const names = vueFiles().map((file) => path.basename(file)).sort();+ expect(names).toContain("DocsApp.vue");+ expect(names).toContain("DocsSidebar.vue");+ expect(names).toContain("WikiIndex.vue");+ expect(names).toContain("TablePage.vue");+ expect(names).toContain("WarningBanner.vue");+ });++ it("makes no backend calls", () => {+ // The whole point of this directory: snapshot in, DOM out. If a component+ // ever reaches for the backend, the same code cannot run inside an+ // exported HTML file on a machine that has never installed DBX.+ const forbidden = [+ "@/lib/backend",+ "@tauri-apps",+ "invoke(",+ "useConnectionStore",+ "useQueryStore",+ "useSettingsStore",+ "fetch(",+ "axios",+ ];+ for (const file of vueFiles()) {+ const script = scriptOf(file);+ for (const needle of forbidden) {+ expect(script.includes(needle), `${path.basename(file)} must not reference ${needle}`).toBe(false);+ }+ }+ });++ it("keeps colour decisions out of templates", () => {+ // Hue -> CSS belongs in groupColor.ts so the theme keeps control of+ // lightness and chroma.+ for (const file of vueFiles()) {+ const source = readFileSync(file, "utf8");+ expect(source.includes("oklch("), `${path.basename(file)} must not compute colour`).toBe(false);+ }+ });++ it("uses <script setup lang=\"ts\">", () => {+ for (const file of vueFiles()) {+ const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });+ expect(descriptor.scriptSetup, `${path.basename(file)} must use <script setup>`).toBeTruthy();+ expect(descriptor.scriptSetup?.lang, `${path.basename(file)} must be TypeScript`).toBe("ts");+ }+ });+});+```++- [ ] **Step 2: Run it and watch it fail**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts+```+Expected: FAIL — no `.vue` files exist yet.++- [ ] **Step 3: Build the components**++Write the seven components as thin templates. Rules:++- `DocsApp.vue` takes a single prop `snapshot: SchemaSnapshot` and a `readonly = true` prop, holds the current view (`index` | `table`) and the group-by mode, and renders the others. No editing affordances in Part 3a — `readonly` exists so Part 3b can flip it.+- `DocsSidebar.vue` renders the `Group by: Schemas | Table Groups` segmented control and the section list, using `groupBySchema` / `groupByTableGroup` from Task 3 and `groupStyle` from Task 6.+- `WikiIndex.vue` renders each section header (name, count, note) and its table list.+- `TablePage.vue` renders the table's note with a `⬤ LOCAL` marker when `noteSource === "LOCAL"`, the shadowed database comment in a `title` attribute when `shadowedNote` is present, then `ColumnTable`, indexes, and `RelationshipList`.+- `ColumnTable.vue` renders name / type / settings / note, reading notes from `columnNotes` by the column's real name.+- `RelationshipList.vue` renders outgoing and incoming relationships in two lists, derived from `snapshot.relationships` filtered on the current table.+- `WarningBanner.vue` renders `describeWarning` output from Task 4.+- `DocsSearch.vue` renders the ⌘K palette using `searchDocs` from Task 5.++Style with Tailwind classes and DBX's existing token names (`bg-background`, `text-foreground`, `border-border`, `text-muted-foreground`). Group colours come only from `var(--group-c)` / `var(--group-tint)` driven by the `--h` custom property.++- [ ] **Step 4: Run the contract test**++```bash+pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts+```+Expected: PASS, 4 tests.++- [ ] **Step 5: Run everything and lint**++```bash+pnpm vitest run apps/desktop/src/docs+pnpm exec oxlint --vue-plugin apps/desktop/src/docs+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json+```+All must pass. `vue-tsc` is the only thing that type-checks the templates, so it is doing the work a mount test would otherwise do — report any error rather than suppressing it.++- [ ] **Step 6: Commit**++```bash+git add apps/desktop/src/docs/+git commit -m "feat(docs): add docs viewer components"+```++---++## Done criteria++- `apps/desktop/src/docs/` contains a viewer that renders a `SchemaSnapshot` with zero backend calls, enforced by a test.+- Every decision (grouping, search, warning text, group colour) lives in a tested `.ts` module.+- A fixture generated from real Rust output guards the hand-maintained TS types against drift.+- `pnpm vitest run apps/desktop/src/docs` passes; `vue-tsc` and `oxlint` are clean.++## Deferred to Part 3b++- Mounting the viewer inside DBX (`DatabaseDocsDialog.vue`) and the editing affordances behind `readonly=false`.+- The standalone Vite bundle, the committed `docs-viewer.js` artifact, and the self-contained HTML export — including inlining the real Geist font, which IS in the repo at `apps/desktop/public/fonts/geist-latin-wght-normal.woff2`.+- The `dbx docs` CLI verb.+- Hash routing (`#/table/public.orders`). Part 3a keeps the current view in `DocsApp` state; hash routing belongs with the standalone entry point, since its whole purpose is surviving a `file://` load.+- The `EnumPage` view listing enum values.+- The ER diagram view (reuses `layoutDiagramTables` from `lib/diagram/erDiagram.ts`, which imports only types and is therefore safe for the standalone bundle).+- i18n: Part 3a hardcodes English strings in `docsWarnings.ts`; Part 3b extracts them into a `docs` namespace across all 8 locales.++---++## Appendix: Corrections found during execution++Defects in this plan's own text, found while executing it. Recorded by failure mode rather than+by task, because the modes repeat and the tasks do not. Every one originated in the plan; none+was an implementer error.++### Mode 1 — a test whose fixture cannot distinguish the property from its negation++The most common failure by a wide margin, and the hardest to see on a green run. The assertion+names a real property; the data supplied cannot tell that property apart from its opposite.++- **Task 5, ranking.** `expect(hits[0].kind).toBe("table")` for query `"orders"`. No column in+ the fixture contained that substring, so exactly one hit came back and the assertion held+ trivially. Reversing the concatenation order produced byte-identical output. Fixed by adding an+ `orders_count` column to a second table so the query yields both kinds, and by asserting+ `indexOf(first table) < indexOf(first column)` instead of inspecting element zero.+- **Task 5, case-insensitivity.** Every identifier in the fixture was already lowercase, so a+ mutant lowercasing only the needle and not each candidate passed all seven tests. Fixed by+ adding a mixed-case `Invoices` table and `Amount` column.++**The lesson:** write the assertion, then ask what fixture would make it fail. If no such fixture+exists, the test is decorative. Watching the test fail once is the only cheap proof.++### Mode 2 — an assertion that fails against a *correct* implementation++- **Task 7.** `expect(html).not.toContain("onerror=")` for the input `<img src=x onerror="…">`.+ Correctly escaped output is `<img src=x onerror="alert(1)">`, which legitimately+ contains that substring as inert text. The test would have driven an implementer to strip+ attributes from text content — wrong, and a plausible route to breaking the escaping entirely.+ Fixed by asserting no `<img` *element* is produced and that `<img` is present.++**The lesson:** an assertion about a security property must target the dangerous *structure*, not+a scary-looking *string*. Escaped text is supposed to still read like the attack.++### Mode 3 — offering two approaches as equivalent when one is broken++- **Task 7.** Step 3 presented "escape the source before parsing" and "override the renderer's+ html hook" as interchangeable. Pre-escaping double-escapes entities: `a & b` renders as the+ literal text `a & b`. Fixed by mandating the renderer hook and stating why.++**The lesson:** when a plan says "either approach works", it usually means neither was tested.++### Mode 4 — a blocklist where an allowlist was needed++- **Task 7.** The instruction was to drop any `href` starting with `javascript:` after trimming and+ lowercasing. Probing `[email protected]` showed it blocks nothing and emits verbatim hrefs for+ `JaVaScRiPt:`, the entity-encoded `javascript:` (which the browser decodes and fires),+ `vbscript:`, and `data:text/html;base64,…`. The instruction also covered only `href`, never+ `<img src>`. Replaced with an allowlist of `https?:`, `mailto:`, and relative/anchor forms —+ shorter than the blocklist and complete without enumerating a single bypass.++**The lesson:** enumerating what is forbidden requires knowing every attack; enumerating what is+permitted requires knowing only the feature.++### Mode 5 — assuming a library parameter contains what its name suggests++- **Task 7.** Found while verifying the *replacement* for Mode 4, not in the original text. In+ `marked@18` the `link` renderer's `text` property is the **raw markdown source**, not the parsed+ inner HTML. Returning it emits author HTML unescaped — `[<img src=x onerror=…>](javascript:…)`+ renders a live element even though the URL was correctly dropped — and it also swallows inline+ formatting, so `[**keep**](…)` loses its emphasis. Fixed with `this.parser.parseInline(tokens)`.++**The lesson:** the first ten payloads all put the attack in the URL, because that is where the+danger was assumed to be. The hole was in the field nobody was thinking about. Passing security+tests confirm the threat model they were written from; they do not probe it.++### Mode 6 — a verification step that verifies nothing++- **Task 1.** The drift check instructed renaming `types.ts` to confirm the conformance test would+ catch schema drift. Renaming the type file breaks the *import*, which fails for reasons having+ nothing to do with drift. Caught by the implementer, who proposed mutating the fixture instead —+ the only change that actually exercises the check. Fixed in the executed task.diff --git a/docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md b/docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.mdnew file mode 100644index 0000000000..06cdff7289--- /dev/null+++ b/docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md@@ -0,0 +1,388 @@+# Database Documentation and DBML Export Design++Date: 2026-08-02++## Summary++DBX can inspect a schema but cannot document it. There is no way to produce a browsable, shareable description of a database, and no occurrence of DBML anywhere in the repository.++This change adds a **documentation subsystem** built around one idea: `SchemaSnapshot` is the product, and every output is a serializer over it. `crates/dbx-core/src/docs/` collects a normalized snapshot of a relational schema, merges it with user-authored notes and table groups, and serializes it to two artifacts — a `.dbml` interchange file and a self-contained HTML documentation site in the style of [dbdocs.io](https://dbdocs.io/Holistics/Ecommerce).++The documentation UI is a **standalone Vue application that makes no backend calls**. The same component tree renders inside DBX as a dialog and inside an exported single-file HTML page. Generation is available headless through `dbx docs` and `dbx dbml`, so documentation can be regenerated in CI and schema drift can fail a build.++Schema versioning (a Changelog tab and per-table "Last Updated") is explicitly deferred, but the snapshot is version-stamped and storable from day one so that adding it later is additive rather than a refactor.++## Goals++- Collect a normalized `SchemaSnapshot` for any relational engine DBX already supports, reusing the existing `schema::providers` metadata layer.+- Serialize the snapshot to valid DBML, including `TableGroup` blocks, `Enum` blocks, and `Ref` cardinality.+- Render dbdocs-style documentation: project overview, per-group table index with inline markdown notes, per-table pages with columns/indexes/bidirectional relationships, an ER diagram with group containers, and client-side search.+- Let users author table notes, column notes, project notes, and **table groups** in DBX, persisted in a human-readable, git-committable file.+- Export a self-contained HTML file that works over `file://` with no network access.+- Provide `dbx docs` and `dbx dbml` CLI verbs producing byte-identical output to the desktop app.+- Degrade visibly, never silently, when an engine cannot supply metadata.++## Non-goals++- **Schema versioning / Changelog / "Last Updated"** — deferred. Live databases mostly cannot report a DDL timestamp (PostgreSQL has none; MySQL's `information_schema.tables.update_time` is NULL for most InnoDB tables), so this is a derivative of stored snapshot history, not of metadata. Section 12 defines the seam.+- **DBML import / parsing.** The serializer is one-way. A `.dbml` file is an output, never a source of truth.+- **Non-relational engines** (MongoDB, Redis, Elasticsearch, InfluxDB, HBase). DBML has no vocabulary for them and schema inference from documents is a separate feature.+- **Non-table objects** — triggers, procedures, functions, sequences, packages, grants, partitions. `ObjectInfo` exists for these but none map to DBML and dbdocs does not document them. `format_version` makes adding them additive.+- **Write-back to the database.** DBX never issues `COMMENT ON` as a side effect of documentation.+- **Publishing/hosting.** DBX writes a file; distributing it is the user's business.++## Existing Design to Reuse++- `crates/dbx-core/src/types.rs:57-141` — `TableInfo`, `ColumnInfo`, `IndexInfo`, `ForeignKeyInfo`. These are serde mirrors of the TS interfaces in `apps/desktop/src/types/database.ts` and are **composed directly** into the snapshot rather than re-declared.+- `crates/dbx-core/src/schema/providers/native.rs` — `list_databases`, `list_schemas`, `list_tables`, `get_columns`, `list_foreign_keys`, `list_indexes`, already dispatching across every supported engine.+- `crates/dbx-core/src/schema/normalization.rs` — identifier normalization; the home for per-engine case folding of annotation keys.+- `crates/dbx-core/src/table_structure_sql/dialect.rs` — `capabilities_for(database_type).comment`, the authority on whether an engine supports comments at all.+- `crates/dbx-core/src/schema_diff.rs:772` — `RenameCandidate { source_name, target_name, score, column_jaccard, type_similarity }` plus `jaccard_similarity` and `column_type_similarity`. Reused to *suggest* re-mapping orphaned notes after a rename.+- `crates/dbx-core/src/database_export.rs` — the established progress-callback and cancellation shape.+- `apps/desktop/src/lib/diagram/erDiagram.ts` — `layoutDiagramTables` and `diagramZoom.ts`. This module imports **only types**, so the standalone docs bundle can import it without pulling in DBX runtime code. `buildDiagramRelationships` / `foreignKeySourceCardinality` are the reference implementation for the Rust port in Section 3.+- `apps/desktop/src/lib/export/diagramSvgExport.ts` — existing SVG serialization for diagram export.+- `apps/desktop/src/styles/globals.css:1310+` — the DBX token palette (strictly achromatic, `oklch(… 0 0)`), from which the docs theme subset is derived.+- `marked@18` and `shiki@4` are already dependencies. **No new dependency is required by this design.**++## Design++### 1. Snapshot model (`crates/dbx-core/src/docs/snapshot.rs`)++```rust+use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};++#[derive(Serialize, Deserialize)]+pub struct SchemaSnapshot {+ pub format_version: u32, // 1+ pub project: ProjectMeta,+ pub tables: Vec<DocTable>,+ pub relationships: Vec<Relationship>,+ pub groups: Vec<TableGroup>,+ pub enums: Vec<DocEnum>,+ pub warnings: Vec<SnapshotWarning>,+}++pub struct ProjectMeta {+ pub name: String,+ pub database_type: String,+ pub database: Option<String>,+ pub schemas: Vec<String>,+ pub generated_at: String, // RFC3339+ pub note: Option<String>, // markdown, the landing page+}++pub struct DocTable {+ pub schema: Option<String>,+ pub name: String,+ pub kind: TableKind, // Table | View | MaterializedView+ pub columns: Vec<ColumnInfo>,+ pub indexes: Vec<IndexInfo>,+ pub foreign_keys: Vec<ForeignKeyInfo>,+ pub group_id: Option<String>,+ pub note: Option<String>,+ pub note_source: NoteSource, // Database | Local | None+ pub shadowed_note: Option<String>, // db comment a local note overrides+ pub column_notes: BTreeMap<String, ColumnNote>,+ pub estimated_rows: Option<i64>,+ pub view_definition: Option<String>,+}++pub struct TableGroup {+ pub id: String, // slug, stable across renames+ pub name: String,+ pub hue: u16, // 0-359 — see Section 4+ pub note: Option<String>,+}++pub struct Relationship {+ pub id: String,+ pub name: Option<String>,+ pub from: FieldRef,+ pub to: FieldRef,+ pub cardinality: Cardinality,+ pub on_update: Option<String>,+ pub on_delete: Option<String>,+}++pub struct FieldRef { pub schema: Option<String>, pub table: String, pub column: String }+pub struct ColumnNote { pub note: String, pub source: NoteSource, pub shadowed: Option<String> }+pub struct DocEnum { pub schema: Option<String>, pub name: String,+ pub values: Vec<String>, pub note: Option<String>,+ pub synthesized: bool } // true for MySQL inline ENUM(...)++pub enum TableKind { Table, View, MaterializedView }+pub enum NoteSource { Database, Local, None }+pub enum Cardinality { OneToOne, ManyToOne }++pub enum SnapshotWarning {+ TableSkipped { table: String, reason: String },+ NoForeignKeyMetadata { engine: String },+ CommentsUnsupported { engine: String },+ OrphanedNotes { count: usize },+ DbmlOmitted { table: String, item: String, reason: String },+}+```++Four decisions are embedded here:++- **`format_version`** guards viewer/data skew. The exported HTML pins a snapshot beside a viewer built from the same commit, but an in-app viewer may load a snapshot produced by an older DBX. One integer prevents a class of blank-render bugs and makes future additions additive.+- **`note_source` and `shadowed_note`** exist so the UI can show *where* prose came from. When a local note shadows a database comment, both are available; the original is shown on hover. Without this, a DBA later writing a better `COMMENT ON` would have their improvement silently hidden forever.+- **`warnings`** is the honest-degradation channel (Section 10).+- **Enums are first-class** because DBML has native `enum` blocks. `ColumnInfo.enum_values` is already populated for MySQL inline `ENUM(...)`; PostgreSQL named enums are collected from `pg_type`/`pg_enum`. MySQL inline enums are synthesized into a named enum per `table_column`. This is the one place the snapshot normalizes rather than passes through.++### 2. Collection (`crates/dbx-core/src/docs/collector.rs`)++v1 fetches through the **existing** provider functions, fanned out with a bounded semaphore (8 concurrent). No new per-engine SQL.++This is deliberately the naive-but-correct version: it works for every supported relational engine on day one because it reuses code already proven against all of them. A 400-table schema costs roughly 1200 queries — bounded, cancellable, and measurable.++The optimization path is targeted rather than speculative: PostgreSQL and MySQL can collect all columns, FKs and indexes for a schema in three `information_schema` sweeps instead of 3×N. That belongs in a `collector::bulk` specialization behind the same interface, added only where a benchmark under `scripts/bench/` shows it matters.++Progress is reported through an `impl Fn(DocsProgress)` callback and cancellation via a checked `AtomicBool`, matching `database_export.rs`.++### 3. Relationship inference (`crates/dbx-core/src/docs/relations.rs`)++A port of the data half of `erDiagram.ts`. The split is deliberate:++- **Data logic moves to Rust** — given foreign keys and unique indexes, is an edge 1:1 or N:1? This is the `foreignKeySourceCardinality` check: a relationship is `OneToOne` only when the source columns contain a unique key, otherwise `ManyToOne`.+- **Layout stays in the renderer** — `layoutDiagramTables` is a view concern and remains in TypeScript, imported by the docs bundle.++This keeps the port to roughly 100 lines rather than a rewrite of the diagram feature. `SchemaDiagramDialog.vue` is **not modified** by this change; once `relations.rs` is proven it becomes the obvious candidate to consume the same inference, removing the duplicate.++### 4. Annotations and table groups (`crates/dbx-core/src/docs/annotations.rs`)++**The notes file is the store** — not a cache, not an export. `dbx.db` persists exactly one thing per connection: the path to this file.++```jsonc+// default: <app-data>/docs-notes/<connection-id>.json+// overridable per connection to e.g. ./docs/dbx-docs.json inside a repository+{+ "format_version": 1,+ "project": { "name": "Ecommerce", "note": "# Overview\n\nMarkdown." },+ "groups": [+ { "id": "order-management", "name": "Order Management", "hue": 28,+ "note": "Everything from checkout to carrier handoff." }+ ],+ "tables": {+ "core.orders": {+ "group": "order-management",+ "note": "One row per completed checkout.",+ "columns": { "status": { "note": "State machine; only moves forward." } }+ }+ }+}+```++This shape is required by the CI goal. If notes lived only in `dbx.db`, `dbx docs` in CI would render documentation with every note missing — polished pages, empty of the prose that justifies them. As a file, notes are also reviewable in pull requests, which is arguably better than `COMMENT ON` (invisible to code review). `DesktopSettings.saved_sql_sync_dir` is the existing precedent for a user-chosen path.++**Table groups** are cross-schema domain groupings, authored by the user, stored here alongside notes, and serialized to DBML `TableGroup` blocks. A table belongs to at most one group; unassigned tables render under `(no group)`. Grouping is documentation, not configuration — it never affects what is collected.++**Group colour is stored as a hue integer (0–359), not a hex string.** Lightness and chroma are fixed per theme in CSS and only the hue varies per group:++```css+.group { --h: 28; }+/* light */ --group-c: oklch(0.55 0.15 var(--h)); --group-tint: oklch(0.965 0.022 var(--h));+/* dark */ --group-c: oklch(0.76 0.13 var(--h)); --group-tint: oklch(0.27 0.038 var(--h));+```++Storing a hex colour the dbdocs way would force either an unreadable dark mode (pastels tuned for a white page turn to mud on `rgb(19 20 22)`) or two colours per group that the user must choose twice. One hue guarantees legible contrast on both grounds by construction, and converts to hex on DBML export.++**Group editor UI.** Groups are created and edited in a dialog reached from the group header on the wiki index, the group badge on a table page, and the diagram group popover. Fields: name, note (markdown), colour, and member tables.++The colour control is **12 curated swatches plus a full 0–359 hue slider** — every hue is reachable, but lightness and chroma remain theme-controlled, so no selection can produce an illegible group. The dialog renders a **two-ground preview**, showing the group chrome on a forced-light and a forced-dark tile simultaneously, because the user may be editing in one theme while a colleague reads the exported HTML in the other.++A native hex/RGB picker is deliberately not offered. It would let a user choose a colour that disappears against one of the two grounds, and the only remedies are to render something different from what the picker showed, or to ship an unreadable group. Hue-plus-fixed-lightness makes the illegible state unrepresentable rather than merely discouraged.++On save, the group is written to the notes file. Since colour is one integer, a group's full definition is a four-field object and diffs cleanly in review.++**Keys and renames.** Keys are `schema.table` and `schema.table.column`, case-folded per engine (PostgreSQL lower, Oracle upper, MySQL per `lower_case_table_names`) in `schema/normalization.rs`.++When a table or column is renamed its note orphans. **User prose is never silently deleted.** Orphans remain in the file, the collector emits `SnapshotWarning::OrphanedNotes { count }`, and the dialog shows an "Unmatched notes" panel. For each orphan, `schema_diff::RenameCandidate` is used to **suggest** the most likely new owner along with its confidence score; the user confirms, re-maps manually, or deletes. Suggestion plus confirmation, never automatic re-attachment — a wrong auto-guess would attach misleading documentation to the wrong column, which is worse than an honest orphan.++**Merge precedence** is `local_annotation ?? database_comment`, recorded in `note_source`. On engines where `capabilities_for(db_type).comment == false` (SQLite, ClickHouse) the annotation layer is the only prose channel, and the UI states this once rather than offering an inert "read from database" affordance.++### 5. DBML serialization (`crates/dbx-core/src/docs/dbml.rs`)++A hand-written serializer, roughly 250 lines. The `@dbml/core` npm package is unusable from Rust and the grammar is small enough not to warrant a dependency.++```dbml+Project ecommerce {+ database_type: 'PostgreSQL'+ Note: '''Generated by DBX on 2026-08-02'''+}++Enum order_status { pending shipped cancelled }++TableGroup order_management [color: #c2410c] {+ core.orders+ core.order_items+ Note: '''Everything from checkout to carrier handoff.'''+}++Table core.orders {+ id integer [pk, increment]+ user_id integer [not null, note: 'Owning customer']+ status order_status [not null, default: 'pending']+ placed_at timestamptz [default: `now()`]++ Indexes {+ (user_id, placed_at) [name: 'idx_orders_user_placed']+ }++ Note: '''One row per completed checkout.'''+}++Ref fk_orders_user: core.orders.user_id > core.users.id [delete: restrict]+```++Rules:++- **Types pass through verbatim.** DBML does not validate type names, so `timestamptz`, `jsonb` and `numeric(10,2)` survive. Where `data_type` arrives bare, precision is reconstructed from `character_maximum_length` / `numeric_precision` / `numeric_scale`.+- **Cardinality comes from `relations.rs`**: `>` for many-to-one, `-` for one-to-one.+- **Schema qualification is conditional** — bare names for a single-schema snapshot (it reads better), fully qualified for multi-schema, since DBML has no `search_path`.+- **Escaping** — identifiers quoted when not `[A-Za-z_][A-Za-z0-9_]*`; notes always in `'''triple quotes'''` so apostrophes cannot break the file; expression defaults in backticks, literals in single quotes.+- **Group colour** is converted from hue to hex at the theme-neutral lightness.++**DBML is lossy and this is documented in the output.** It cannot express check constraints, partial or filtered indexes (`IndexInfo.filter`), included columns, collations, or generated columns. Composite foreign keys are emitted in the grouped `(a, b) > (c, d)` form, whose support across dbdocs/dbdiagram is uneven. Every omission produces a `SnapshotWarning`, and the HTML documentation renders the omitted item with a "not in DBML" marker.++The asymmetry is intentional: **DBML is the interchange format; the HTML documentation is the complete record.** Treating DBML as a source of truth would silently drop constraints.++### 6. Docs viewer (`apps/desktop/src/docs/`)++```+main.ts — standalone entry; reads window.__DBX_DOCS__, mounts+DocsApp.vue — root; hash routing+components/+ DocsShell.vue — sidebar + main+ DocsSidebar.vue — Group by: Schemas | Table Groups switch, trees, enums+ DocsSearch.vue — ⌘K palette, client-side fuzzy over tables/columns/groups+ WikiIndex.vue — stats, project note, per-group table index+ TablePage.vue — orchestrates the sections below+ ColumnTable.vue — columns grid; inline note editing when !readonly+ IndexList.vue RelationshipList.vue GroupHeader.vue EnumPage.vue+ GroupEditorDialog.vue — name/note/hue/members; rendered only when !readonly+ ErdView.vue — pan/zoom SVG with group containers; reuses layoutDiagramTables()+ NoteMarkdown.vue — marked → sanitized HTML+ WarningBanner.vue — renders snapshot.warnings+__tests__/ — fixture snapshots in, rendered output asserted+```++**The contract: this directory makes no backend calls.** No `api.*`, no Tauri, no Pinia stores. Snapshot in, DOM out. This is what allows the same code to run inside an HTML file on a machine that has never installed DBX, and what makes the entire documentation UI testable without a database.++Editing is expressed as a `readonly` prop — `true` in exported HTML, `false` in-app. Components emit `@update:note`, `@update:group` and `@update:table-group`; `DatabaseDocsDialog.vue` performs the writes. `GroupEditorDialog.vue` is not rendered at all when `readonly`, so the exported HTML never ships an editor that cannot save.++Six further decisions:++- **Hash routing** (`#/table/core.orders`), not the History API, which breaks over `file://`. Also makes every table deep-linkable.+- **Raw HTML is stripped from markdown.** `marked` removed `sanitize` in v5 and DOMPurify is not in the tree. Notes come partly from `COMMENT ON` values living in the database, which is not always under the document author's control, and the output is a file people forward to colleagues. `marked` is configured to escape raw HTML: markdown formatting works, `<script>` and `<img onerror>` do not.+- **The information architecture follows dbdocs**: the Wiki tab is a scrolling per-group index whose Table Notes column renders **full markdown inline** (headings, prose, code blocks), with table detail pages behind it — not a bare list of links.+- **Theme tokens are a curated subset**, not `globals.css` (2362 lines). The viewer has its own Tailwind v4 entry scanning only `src/docs/**` plus roughly 25 hand-picked tokens matching DBX's variable names, so it inherits live tokens in-app and ships its own values (with `prefers-color-scheme` and a manual toggle) when exported.+- **No Shiki in the exported bundle.** View definitions render in a plain `<pre>`. Shiki's grammars would dominate the artifact weight for a feature nobody generates documentation to obtain.+- **i18n uses a `docs` namespace only** — roughly 40 keys, imported directly, never `i18n/locales/en.ts` wholesale, or the standalone bundle inherits the whole application translation table. All 8 locales ship, selected from `navigator.language`, with a switcher.++### 7. Static HTML export (`crates/dbx-core/src/docs/html.rs`)++Output is `HTML shell + inlined CSS + inlined viewer bundle + window.__DBX_DOCS__ = {snapshot}`.++The viewer bundle is produced by `pnpm build:docs-viewer` into `crates/dbx-core/src/docs/assets/docs-viewer.js`, and **that artifact is committed to git**. `cargo build` never invokes Vite; it only `include_str!`s what is present.++This is the one piece of build coupling in the design, accepted deliberately:++- Rust-only contributors can still `cargo build` without a Node toolchain.+- The artifact is reviewable in diffs.+- A CI job rebuilds the bundle and fails if the committed copy is stale.++The cost is a generated file in the tree that must be regenerated when the viewer changes. The CI check is what makes that safe.++**Budget: under 400 KB uncompressed** for a self-contained page documenting a 50-table schema, asserted by test (Section 11). If the real figure lands materially above this, the correct response is to question the Vue-in-a-file approach, not to ship something sluggish.++### 8. Desktop integration (`apps/desktop/src/components/docs/DatabaseDocsDialog.vue`)++The dialog owns all I/O: connection/database/schema selection, invoking the collector, progress and cancellation, note and group writes, the orphan re-map panel, and the two export actions. It mounts `<DocsApp :snapshot :readonly="false">`.++Entry point follows `SchemaDiagramDialog.vue` — a dialog reached from the connection context menu and the toolbar, not a new tab kind.++### 9. CLI (`crates/dbx-cli/src/main.rs`)++```+dbx docs <connection> --out <dir-or-file> [--schema s] [--database d]+ [--notes path] [--tables a,b] [--open]+dbx dbml <connection> [--out path] [--schema s] [--database d] [--notes path]+```++`dbx docs` writes a self-contained `index.html`. `dbx dbml` writes to `--out` or stdout so it pipes.++The existing `--format table|json|csv` flag is **not** extended with `html|dbml`. That flag means "how do I tabulate result rows"; overloading it would invite `dbx query --format dbml`. Two verbs, one output each, matching the existing `dbx schema list` / `dbx schema describe` style.++Target CI shape:++```yaml+- run: dbx dbml prod --notes docs/dbx-docs.json --out docs/schema.dbml+- run: git diff --exit-code docs/schema.dbml # migration drift fails the build+```++### 10. Error handling++| Situation | Behavior | Rationale |+| --- | --- | --- |+| Notes file absent | Proceed with empty notes | First CI run, or a user who has not annotated yet. Not an error. |+| Notes file malformed | **Hard fail**, non-zero exit | User prose is at stake. Proceeding would render apparently-complete docs while discarding writing. |+| One table's metadata fails | `SnapshotWarning::TableSkipped`, continue | A permission gap on one table must not kill a 400-table build. |+| Engine lacks FK metadata | Warning banner; ERD with no edges | ClickHouse, Doris, StarRocks. Honest degradation over a blank page. |+| Engine lacks comment support | Stated once in the UI | SQLite, ClickHouse — via `capabilities_for()`. |+| Orphaned notes after rename | Warning + re-map panel with suggestions | Section 4. |+| DBML-inexpressible construct | Warning + "not in DBML" marker in HTML | Section 5. |+| Connection failure | Existing error path | Already solved. |+| Stale committed viewer bundle | CI job fails | Guards the Section 7 build coupling. |++The through-line: **fail loudly when user-authored content is at risk; degrade visibly when the database simply cannot answer.**++### 11. Testing++**Rust**++- DBML snapshot tests following `crates/dbx-core/src/sql_dialect/snapshots/`.+- `relations.rs`: FK with unique source → `OneToOne`; without → `ManyToOne`; composite FK grouping; self-referencing FK.+- `annotations.rs`: merge precedence; per-engine key folding; orphan detection; `RenameCandidate` suggestion ranking; group assignment and hue round-trip through DBML hex.+- Live-engine tests as `crates/dbx-core/tests/live_postgres_docs_snapshot.rs`, matching the existing `live_postgres_query_result_export.rs` convention.++**Frontend** (`packages/app-tests/`, following `erDiagram.test.ts` and `diagramSvgExport.test.ts`)++- Every docs component rendered against **fixture snapshot JSON** — no database, no Tauri. This is the payoff of the Section 6 contract.+- `NoteMarkdown` tested explicitly against `<script>`, `<img onerror=…>` and `javascript:` hrefs.+- **Self-containment test**: generate HTML from a fixture and assert zero `http://` / `https://` in any `src`, `href` or `@import`. This catches a stray CDN font before it breaks someone's offline documentation.+- **Artifact size assertion** against the 400 KB budget, so bloat fails a test rather than accumulating.+- Group colour contrast: assert computed `--group-c` meets the contrast floor against both grounds **across all 360 hues**, not only the 12 curated swatches — the slider makes every hue reachable, so the guarantee must hold for every one of them.+- `GroupEditorDialog` is absent from the rendered tree when `readonly` is true.++### 12. Deferred: the versioning seam++The Changelog tab and per-table "Last Updated" are out of scope, but the design must not preclude them. Three constraints carry forward:++1. `SchemaSnapshot` is `Serialize + Deserialize` and carries `format_version` and `generated_at`, so it is already storable as a version record.+2. `crates/dbx-core/src/schema_diff.rs` (8728 lines) already computes `TableDiff` / `ColumnDiff` / `ForeignKeyDiff` between two schemas. A future Changelog is a storage and UI problem, not an algorithm problem.+3. The docs viewer's tab strip reserves the Changelog slot.++No storage, retention policy, or snapshot history is built in this change.++## Build Order++Each step is independently verifiable; steps 1–2 have standalone value if work stops there.++1. `SchemaSnapshot` + `collector.rs` + `relations.rs` — pure data, fully testable, no UI.+2. `dbml.rs` + `dbx dbml` — first shippable user value, small surface.+3. `annotations.rs` — notes, groups, merge, orphan handling.+4. Docs viewer against fixture snapshots — UI with no backend at all.+5. `DatabaseDocsDialog.vue` — wire into DBX.+6. `html.rs` + committed bundle + `dbx docs` — the build coupling last, once the UI has settled.++## Versioning and Documentation++- Version bump `0.5.73 → 0.6.0` (feature, pre-1.0) in `package.json`.+- Changelog entry through the existing CDN JSON flow (`crates/dbx-core/src/changelog.rs`), not a root `CHANGELOG.md` — this repository does not use one.+- A feature page in the `docs/` Next.js site.+- A `docs` i18n namespace across all 8 locales (`en`, `es`, `it`, `ja`, `ko`, `pt-BR`, `zh-CN`, `zh-TW`).++## Validated Mock++The UI was prototyped and approved before this spec was written. The throwaway mock covered: the wiki index with inline markdown notes, a table page with the shadowed-note marker, table groups across sidebar/index/diagram/search, the `Group by` switch, group containers in the ERD, the DBML-lossiness banner, and both themes. It is not part of the implementation.diff --git a/docs/superpowers/specs/2026-08-03-database-documentation-in-app-design.md b/docs/superpowers/specs/2026-08-03-database-documentation-in-app-design.mdnew file mode 100644index 0000000000..8dfc058420--- /dev/null+++ b/docs/superpowers/specs/2026-08-03-database-documentation-in-app-design.md@@ -0,0 +1,218 @@+# Database documentation in DBX — design++**Part 3b of the database-documentation feature.** Parts 1, 2 and 3a are complete and merged into+`feature/docs-snapshot-dbml`: `SchemaSnapshot` collection with a DBML serializer and a `dbx dbml`+verb, a file-backed annotation store for notes and table groups, and a read-only Vue viewer tested+against a real backend-generated fixture.++This part makes the viewer reachable and editable inside DBX. The standalone HTML export, the+`dbx docs` verb and hash routing are deliberately **not** here — they are Part 3c.++## Goal++A user opens a connection's documentation from the tree, reads a dbdocs.io-style wiki of their+schema, and edits it in place: table and column notes, table groups, and each group's colour.+Everything they write persists to a JSON notes file that can live inside their repository.++## Scope++**In scope**++- `DatabaseDocsDialog.vue`, mounted through the existing dialog pattern+- Backend reachability: the desktop frontend currently cannot call the docs collector at all+- Editing: table notes, column notes, project note, group create/rename/delete/assign, group hue+- Debounced autosave to the notes file, with a visible saved/failed indicator+- `EnumPage.vue`+- An i18n `docs` namespace across all 8 locales, with a parity guard+- A link from the docs viewer to the existing `SchemaDiagramDialog`++**Out of scope (Part 3c)**++- The standalone Vite bundle and self-contained HTML export+- The `dbx docs` CLI verb+- Hash routing (`#/table/public.orders`) — its purpose is surviving a `file://` load+- A minimal read-only ER renderer for the export+- Inlining the Geist woff2 at `apps/desktop/public/fonts/geist-latin-wght-normal.woff2`++**Explicitly not built**: a second ER diagram. DBX already ships `SchemaDiagramDialog.vue`+(51.6 KB) with custom relationships, join-SQL generation and zoom. In-app, the docs viewer links+to it. Only the export needs its own minimal renderer, because that dialog reaches into stores and+the backend and therefore cannot be inlined.++## Architecture++### The viewer stays pure; the dialog owns all I/O++Part 3a's contract test forbids `apps/desktop/src/docs/**/*.vue` from referencing `@/lib/backend`,+`@tauri-apps`, `invoke(`, `fetch(`, or any store. Editing preserves that rule: components emit+edit intents upward, and only `DatabaseDocsDialog.vue` — which lives outside `src/docs/` — talks to+the backend.++This is not ceremony. It is what allows Part 3c to bundle the identical components into an HTML+file that runs on a machine with no DBX installed.++```+connectionStore.docsSource set by the connection-tree context menu+ → useDialogSources.ts watcher mirrors the existing diagramSource pattern+ → showDocsDialog + prefills+ → DatabaseDocsDialog.vue owns: collect, load notes, save notes, autosave+ │ props: snapshot, annotations ↓ emits: update:note, update:group, …+ └─ DocsApp.vue Part 3a, unchanged apart from readonly=false+```++### Four backend operations, five touchpoints each++`apps/desktop/src/lib/backend/api.ts` is a facade that lazily resolves either `tauri.ts` or+`http.ts` via `isTauriRuntime()` and re-exports each function through `forward()`. Every operation+therefore exists twice, once per transport. There is currently **no docs entry in `api.ts` at+all** — Part 1's collector is reachable from the CLI, MCP and the web route, but never from the+desktop frontend.++| Operation | Returns | Existing | New |+|---|---|---|---|+| `collectDocsSnapshot` | raw `SchemaSnapshot` | web route | Tauri command, both transports, `api.ts` forward |+| `loadDocsAnnotations` | `AnnotationFile \| null` | `load_annotations` | path resolution, command, routes, forward |+| `applyDocsAnnotations` | applied `SchemaSnapshot` | `apply_annotations` | command, routes, forward |+| `saveDocsAnnotations` | `()` | — | **`save_annotations` does not exist** |++### Why `applyDocsAnnotations` is a separate call++The viewer renders a snapshot with annotations already applied, but edits target the+`AnnotationFile`. After an edit the displayed snapshot is stale.++Applying the edit optimistically in TypeScript would mean reimplementing `apply_annotations`,+including the `shadowedNote` rule where a local note displaces a database `COMMENT ON` and+preserves it underneath. A second implementation of that rule in a second language is exactly the+drift this feature has repeatedly suffered from.++Instead, `collect` returns the **raw** snapshot, and `applyDocsAnnotations(raw, file)` is a pure+Rust call with no database access. The dialog keeps the raw snapshot from open and re-derives on+demand. One implementation of the rule, in the language where it is already tested.++While the user types, nothing is re-derived: the editor binds to the raw note text in the+`AnnotationFile`, not to rendered output. The round trip happens on blur, not per keystroke.++### Notes file location++`config.docs_notes_path` when set; otherwise `<app_data>/docs-notes/<connection_id>.json`.++The default makes the feature work with no setup. The override is the point: pointing it at a file+inside a repository is what lets schema documentation be code-reviewed and committed alongside the+schema it describes.++`docs_notes_path` already exists on `ConnectionConfig`, `ConnectionConfigData` and the `From` impl+(Part 2). Nothing reads it yet.++### `save_annotations` must be atomic++Write to a temporary file in the same directory, fsync, then rename. A partial write destroys prose+a human typed, and `load_annotations` errors loudly on malformed JSON — so a torn write becomes+"your notes file is corrupt" the next time the dialog opens.++A failed save must surface in the UI. A silently swallowed write failure is the worst outcome this+feature can produce.++## Editing++### Edits are pure transformations of the `AnnotationFile`++`apps/desktop/src/docs/annotationEdits.ts` — every function takes an `AnnotationFile` and returns a+new one, with no I/O:++- `setProjectNote(file, note)`+- `setTableNote(file, tableKey, note)`+- `setColumnNote(file, tableKey, column, note)`+- `setTableGroup(file, tableKey, groupId | null)`+- `upsertGroup(file, group)` — create or update name, hue, note+- `removeGroup(file, groupId)` — also clears the reference from every table that used it++Empty or whitespace-only notes remove the entry rather than storing an empty string, so the file+does not accumulate dead keys.++**Deleting a group clears its references.** `docsIndex.ts` already drops a dangling `groupId` when+rendering, so the viewer degrades correctly either way — but the file should not carry references+to a group that no longer exists.++### Components++All thin; every decision lives in `annotationEdits.ts` or an existing Part 3a module.++- **`NoteEditor.vue`** — renders `renderNote(...)` output until clicked, then swaps to a raw+ markdown textarea. Reused for table, column, group and project notes. The `v-html` contract rule+ applies here as everywhere: only `renderNote` output may be bound.+- **`GroupEditor.vue`** — name field plus the hue picker from the approved mock: 12 swatches, a+ 360° slider, and a preview showing the colour on light and dark grounds simultaneously. The+ two-ground preview is why the hue-only model exists, so it belongs in front of the user while+ they choose.+- **`GroupPicker.vue`** — assigns a table to a group; a select plus "New group…".+- **`EnumPage.vue`** — a `DocEnum`'s values, its note, and the columns using it. The reverse lookup+ from enum to using columns is a tested function in `docsIndex.ts`, not template logic.++### `readonly` returns++Part 3a removed the `readonly` prop as YAGNI, since nothing read it. Part 3b reintroduces it+because Part 3c renders the identical components with editing disabled.++### Autosave++Debounced ~500 ms after the last edit, owned by the dialog. A small indicator shows saved / saving+/ failed. Failure is visible and the in-memory state is retained so the user can retry rather than+losing what they wrote.++## i18n++A `docs` namespace added to all 8 locales: `en`, `es`, `it`, `ja`, `ko`, `pt-BR`, `zh-CN`, `zh-TW`.++`withEnglishFallback` deep-merges `en` underneath every locale, so a key missing from `ja.ts`+silently renders English with no error, no warning, and no failing test. Translation completeness+is therefore unobservable at runtime.++**A key-parity test is required**: import the raw locale modules — not the merged output — and+assert every locale declares the same key set under `docs` as `en` does. Scoped to the new+namespace only; parity across the existing 315 KB of keys is out of scope and would fail+immediately.++Part 3a hardcoded English strings in `docsWarnings.ts`. Those move into the namespace, which is a+breaking change to that module: `describeWarning(warning)` becomes+`describeWarning(warning, translate)`, and its existing tests change with it.++It takes a **translator function** rather than importing `useI18n` directly, and that is+deliberate. `useI18n()` throws without a provided instance, which is exactly the Part 3c+standalone-export case — a bare HTML file with no Vue app bootstrapped around it. Passing the+translator in keeps `docsWarnings.ts` a pure module the export can call with an English identity+function. Importing vue-i18n inside `src/docs/` would make the export impossible.++## Testing++| Layer | Approach |+|---|---|+| `annotationEdits.ts` | Pure unit tests — the bulk of the coverage |+| `save_annotations` | Rust: atomicity; a failed write leaves the previous file intact |+| Path resolution | Rust: override wins; default when unset |+| Components | The Part 3a static SFC contract test, extended to the new files |+| i18n | Key parity across 8 locales for the `docs` namespace |+| Dialog | Autosave debounce; the failure indicator |++**Every new test gets the deliberate-break treatment**: break the behaviour, watch the named test+fail, restore, report the failure message. In Part 3a this caught a vacuous ranking test, a CSS+ordering bug that let a whole theme's colours be deleted silently, and a capability warning that+contradicted its own data. It is the highest-yield practice carried forward.++### Known gap: `DocEnum` drift is unguarded++The conformance fixture is generated from `keycloak`, which declares no PostgreSQL enum types, so+`snapshot.enums` is empty and `DocEnum` field renames are not detectable. `EnumPage` tests use+in-memory snapshots, which prove the rendering logic but not the Rust↔TS boundary.++`fixtureConformance.spec.ts` carries a self-correcting assertion that fails the day the fixture+source gains an enum, with the exact `pinShape` call to restore. Part 3c is the natural time to+close this, since an exportable demo wants an enum-bearing schema anyway.++## Success criteria++- A user opens documentation from the connection tree, reads it, edits notes and group colours, and+ the changes survive closing and reopening the dialog.+- Pointing `docs_notes_path` at a repository file produces a diff a colleague can review.+- `apps/desktop/src/docs/**/*.vue` still makes zero backend calls, enforced by the contract test.+- All 8 locales declare the same `docs` keys, enforced by a test.+- A failed save is visible to the user and does not discard their work.diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rsindex 6b3c59919c..f842ea4279 100644--- a/src-tauri/src/commands/connection.rs+++ b/src-tauri/src/commands/connection.rs@@ -178,6 +178,7 @@ mod tests {fn mongodb_config() -> ConnectionConfig {ConnectionConfig {+ docs_notes_path: None,id: "mongo".to_string(),name: "MongoDB".to_string(),note: String::new(),diff --git a/src-tauri/src/commands/docs.rs b/src-tauri/src/commands/docs.rsnew file mode 100644index 0000000000..a5ac446886--- /dev/null+++ b/src-tauri/src/commands/docs.rs@@ -0,0 +1,83 @@+use std::sync::atomic::AtomicBool;+use std::sync::Arc;++use dbx_core::connection::AppState;+// `apply_annotations` is NOT re-exported at `dbx_core::docs` — that module's+// `pub use` list covers collector, color, dbml, keys, relations and snapshot,+// but not annotations. It must come from the submodule path.+use dbx_core::docs::annotations::{+ apply_annotations, load_annotations, resolve_notes_path, save_annotations, AnnotationFile,+};+use dbx_core::docs::{collect_snapshot, CollectOptions, SchemaSnapshot};+use dbx_core::models::connection::ConnectionConfig;+use tauri::State;++async fn connection_of(state: &Arc<AppState>, connection_id: &str) -> Result<ConnectionConfig, String> {+ let configs = state.configs.read().await;+ configs.get(connection_id).cloned().ok_or_else(|| format!("Connection {connection_id} not found."))+}++/// The notes file for a connection, resolved against DBX's data directory.+///+/// `AppState.storage.data_dir()` is the directory DBX is actually using — it+/// honours a custom data dir, which a fresh `app_data_dir()` lookup would not.+/// (`dbx-mcp::paths::app_data_dir()` is NOT available here: src-tauri does not+/// depend on dbx-mcp.)+async fn notes_path_of(state: &Arc<AppState>, connection_id: &str) -> Result<std::path::PathBuf, String> {+ let config = connection_of(state, connection_id).await?;+ Ok(resolve_notes_path(&config.id, config.docs_notes_path.as_deref(), state.storage.data_dir()))+}++/// Collect a RAW snapshot — annotations are applied separately, so the+/// frontend can re-derive after an edit without touching the database.+#[tauri::command]+pub async fn docs_collect_snapshot(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ schemas: Vec<String>,+ tables: Vec<String>,+ project_name: Option<String>,+) -> Result<SchemaSnapshot, String> {+ let config = connection_of(&state, &connection_id).await?;+ let options =+ CollectOptions { database, schemas, tables, project_name: project_name.unwrap_or_else(|| config.name.clone()) };+ collect_snapshot(&state, &config, &options, &|_progress| {}, &AtomicBool::new(false)).await+}++#[tauri::command]+pub async fn docs_load_annotations(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+) -> Result<Option<AnnotationFile>, String> {+ let path = notes_path_of(&state, &connection_id).await?;+ load_annotations(&path)+}++/// Apply annotations to a raw snapshot. Pure — no database access.+///+/// This exists so the `shadowedNote` rule has exactly ONE implementation.+/// Re-implementing it in TypeScript to update the view optimistically is the+/// drift this feature has repeatedly suffered from.+#[tauri::command]+pub async fn docs_apply_annotations(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ snapshot: SchemaSnapshot,+ annotations: AnnotationFile,+) -> Result<SchemaSnapshot, String> {+ let config = connection_of(&state, &connection_id).await?;+ let mut applied = snapshot;+ apply_annotations(&mut applied, &annotations, config.db_type);+ Ok(applied)+}++#[tauri::command]+pub async fn docs_save_annotations(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ annotations: AnnotationFile,+) -> Result<(), String> {+ let path = notes_path_of(&state, &connection_id).await?;+ save_annotations(&path, &annotations)+}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 0e4cf50b28..1ca267d7b8 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -12,6 +12,7 @@ pub mod data_compare;pub mod database_export;pub mod deep_link;pub mod dialect_cmd;+pub mod docs;pub mod document_cmd;pub mod etcd_cmd;pub mod external_db;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex cde649da4c..2e218ddfdb 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1869,6 +1869,10 @@ pub fn run() {commands::mongo_cmd::mongo_drop_database,commands::mongo_cmd::mongo_drop_collection,commands::mongo_cmd::mongo_rename_collection,+ commands::docs::docs_collect_snapshot,+ commands::docs::docs_load_annotations,+ commands::docs::docs_apply_annotations,+ commands::docs::docs_save_annotations,commands::document_cmd::document_list_databases,commands::document_cmd::document_list_collections,commands::document_cmd::document_find_documents,