Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(schema-diagram): foreign key lines (#4043)

Liu Ji6d46d91eda06
diff --git a/frontend/package.json b/frontend/package.json
index 6b1f95c8b8..b5785b2860 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -24,6 +24,7 @@
"axios": "1.1.3",
"bootstrap": "5.2.2",
"canvas-confetti": "1.6.0",
+ "d3-shape": "^3.2.0",
"dagre": "^0.8.5",
"dayjs": "1.11.6",
"dompurify": "2.4.0",
@@ -71,6 +72,7 @@
"@tailwindcss/line-clamp": "0.4.2",
"@tailwindcss/typography": "0.5.8",
"@types/canvas-confetti": "1.4.3",
+ "@types/d3-shape": "^3.1.0",
"@types/dagre": "^0.7.48",
"@types/dompurify": "2.3.4",
"@types/downloadjs": "1.4.3",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 7cc87b4173..fd19f96bd1 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -16,6 +16,7 @@ specifiers:
'@tanstack/table-core': 8.5.22
'@tanstack/vue-table': 8.5.22
'@types/canvas-confetti': 1.4.3
+ '@types/d3-shape': ^3.1.0
'@types/dagre': ^0.7.48
'@types/dompurify': 2.3.4
'@types/downloadjs': 1.4.3
@@ -42,6 +43,7 @@ specifiers:
axios: 1.1.3
bootstrap: 5.2.2
canvas-confetti: 1.6.0
+ d3-shape: ^3.2.0
dagre: ^0.8.5
dayjs: 1.11.6
dompurify: 2.4.0
@@ -112,6 +114,7 @@ dependencies:
axios: 1.1.3
bootstrap: 5.2.2_@[email protected]
canvas-confetti: 1.6.0
+ d3-shape: 3.2.0
dagre: 0.8.5
dayjs: 1.11.6
dompurify: 2.4.0
@@ -159,6 +162,7 @@ devDependencies:
'@tailwindcss/line-clamp': [email protected]
'@tailwindcss/typography': [email protected]
'@types/canvas-confetti': 1.4.3
+ '@types/d3-shape': 3.1.0
'@types/dagre': 0.7.48
'@types/dompurify': 2.3.4
'@types/downloadjs': 1.4.3
@@ -432,8 +436,8 @@ packages:
vue-i18n:
optional: true
dependencies:
- '@intlify/message-compiler': 9.3.0-beta.10
- '@intlify/shared': 9.3.0-beta.10
+ '@intlify/message-compiler': 9.3.0-beta.11
+ '@intlify/shared': 9.3.0-beta.11
jsonc-eslint-parser: 1.4.1
source-map: 0.6.1
@@ -462,11 +466,11 @@ packages:
'@intlify/shared': 9.2.2
source-map: 0.6.1
- /@intlify/message-compiler/9.3.0-beta.10:
- resolution: {integrity: sha512-RoOC6yceOykLRhN0NlbkNOBUx1el6iphx3W8NfOx3jHVNtfT1FYokx14/5sU3F1F0uxeG4sp6q+ppKvaF8o+ww==}
+ /@intlify/message-compiler/9.3.0-beta.11:
+ resolution: {integrity: sha512-gGGfBGzM7JBXp1Q9gbDAy5jELz9ho3ILqnpxp2yp64+gkqohrqc2YXIvCdwZoc6AtKIh/Zmv4sWVqxkvMsBWtQ==}
engines: {node: '>= 14'}
dependencies:
- '@intlify/shared': 9.3.0-beta.10
+ '@intlify/shared': 9.3.0-beta.11
source-map: 0.6.1
dev: true
@@ -474,8 +478,8 @@ packages:
resolution: {integrity: sha512-wRwTpsslgZS5HNyM7uDQYZtxnbI12aGiBZURX3BTR9RFIKKRWpllTsgzHWvj3HKm3Y2Sh5LPC1r0PDCKEhVn9Q==}
engines: {node: '>= 14'}
- /@intlify/shared/9.3.0-beta.10:
- resolution: {integrity: sha512-h93uAanbAt/XgjDHclrVB7xix6r7Uz11wx0iGNOCdHP7aA2LCJjUT3uNbekJjjbo+Fl5jzTSJZdm2SexzoqhRA==}
+ /@intlify/shared/9.3.0-beta.11:
+ resolution: {integrity: sha512-CtbotesxTRiC3bRyXyv1NG39fkqJ790f8z8xFaeIXSZpOdiyxoh5BIyypCzSFQZDGLwz0Q9gyWbW1XpxQJm68Q==}
engines: {node: '>= 14'}
dev: true
@@ -495,7 +499,7 @@ packages:
optional: true
dependencies:
'@intlify/bundle-utils': [email protected]
- '@intlify/shared': 9.3.0-beta.10
+ '@intlify/shared': 9.3.0-beta.11
'@rollup/pluginutils': 4.2.1
debug: 4.3.4
fast-glob: 3.2.12
@@ -791,7 +795,6 @@ packages:
/@types/d3-path/3.0.0:
resolution: {integrity: sha512-0g/A+mZXgFkQxN3HniRDbXMN79K3CdTpLsevj+PXiTcb2hVyvkZUBg37StmgCQkaD84cUJ4uaDAWq7UJOQy2Tg==}
- dev: false
/@types/d3-polygon/3.0.0:
resolution: {integrity: sha512-D49z4DyzTKXM0sGKVqiTDTYr+DHg/uxsiWDAkNrwXYuiZVd9o9wXZIo+YsHkifOiyBkmSWlEngHCQme54/hnHw==}
@@ -823,7 +826,6 @@ packages:
resolution: {integrity: sha512-jYIYxFFA9vrJ8Hd4Se83YI6XF+gzDL1aC5DCsldai4XYYiVNdhtpGbA/GM6iyQ8ayhSp3a148LY34hy7A4TxZA==}
dependencies:
'@types/d3-path': 3.0.0
- dev: false
/@types/d3-time-format/4.0.0:
resolution: {integrity: sha512-yjfBUe6DJBsDin2BMIulhSHmr5qNR5Pxs17+oW4DoVPyVIXZ+m6bs7j1UVKP08Emv6jRmYrYqxYzO63mQxy1rw==}
@@ -1714,7 +1716,7 @@ packages:
resolution: {integrity: sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==}
engines: {node: '>=12'}
dependencies:
- d3-path: 3.0.1
+ d3-path: 3.1.0
dev: false
/d3-color/3.1.0:
@@ -1819,6 +1821,11 @@ packages:
engines: {node: '>=12'}
dev: false
+ /d3-path/3.1.0:
+ resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}
+ engines: {node: '>=12'}
+ dev: false
+
/d3-polygon/3.0.1:
resolution: {integrity: sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==}
engines: {node: '>=12'}
@@ -1858,11 +1865,11 @@ packages:
engines: {node: '>=12'}
dev: false
- /d3-shape/3.1.0:
- resolution: {integrity: sha512-tGDh1Muf8kWjEDT/LswZJ8WF85yDZLvVJpYU9Nq+8+yW1Z5enxrmXOhTArlkaElU+CTn0OTVNli+/i+HP45QEQ==}
+ /d3-shape/3.2.0:
+ resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
engines: {node: '>=12'}
dependencies:
- d3-path: 3.0.1
+ d3-path: 3.1.0
dev: false
/d3-time-format/4.1.0:
@@ -1937,7 +1944,7 @@ packages:
d3-scale: 4.0.2
d3-scale-chromatic: 3.0.0
d3-selection: 3.0.0
- d3-shape: 3.1.0
+ d3-shape: 3.2.0
d3-time: 3.0.0
d3-time-format: 4.1.0
d3-timer: 3.0.1
diff --git a/frontend/src/bbkit/BBModal.vue b/frontend/src/bbkit/BBModal.vue
index 08b29a5e39..b1da5ec281 100644
--- a/frontend/src/bbkit/BBModal.vue
+++ b/frontend/src/bbkit/BBModal.vue
@@ -25,7 +25,7 @@
<heroicons-solid:x class="w-6 h-6" />
</button>
</div>
- <div class="modal-container">
+ <div class="modal-container" :class="containerClass">
<slot />
</div>
</div>
@@ -41,11 +41,13 @@ import {
onBeforeMount,
onMounted,
onUnmounted,
+ PropType,
provide,
ref,
Ref,
RenderFunction,
} from "vue";
+import type { VueClass } from "@/utils";
import { useModalStack } from "./BBModalStack.vue";
type Overrides = {
@@ -72,6 +74,10 @@ export default defineComponent({
type: Boolean,
default: true,
},
+ containerClass: {
+ type: [String, Object, Array] as PropType<VueClass>,
+ default: undefined,
+ },
escClosable: {
type: Boolean,
default: true,
diff --git a/frontend/src/components/SchemaDiagram/ER/ForeignKeyLine.vue b/frontend/src/components/SchemaDiagram/ER/ForeignKeyLine.vue
new file mode 100644
index 0000000000..771484aae9
--- /dev/null
+++ b/frontend/src/components/SchemaDiagram/ER/ForeignKeyLine.vue
@@ -0,0 +1,132 @@
+<template>
+ <SVGLine
+ :path="path"
+ :decorators="[]"
+ :bb-edge-from="`${fk.from.table.name}.${fk.from.column}`"
+ :bb-edge-to="`${fk.to.table.name}.${fk.to.column}`"
+ :bb-fk-name="fk.metadata.name"
+ :bb-fk-on-update="fk.metadata.onUpdate"
+ :bb-fk-on-delete="fk.metadata.onDelete"
+ :bb-fk-match-type="fk.metadata.matchType"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed, onMounted, ref } from "vue";
+
+import { TableMetadata } from "@/types/proto/store/database";
+import { Position, Rect, Path, ForeignKey } from "../types";
+import {
+ segmentOverlap1D,
+ SegmentOverlap1D,
+ useSchemaDiagramContext,
+} from "../common";
+
+type Direction = "LEFT" | "RIGHT";
+type Segment1D = [number, number];
+
+const props = withDefaults(
+ defineProps<{
+ fk: ForeignKey;
+ }>(),
+ {}
+);
+
+const { zoom, idOfTable, rectOfTable, events } = useSchemaDiagramContext();
+const fromRect = ref<Rect>({ x: 0, y: 0, width: 0, height: 0 });
+const toRect = ref<Rect>({ x: 0, y: 0, width: 0, height: 0 });
+const path = computed((): Path => {
+ const from = fromRect.value;
+ const to = toRect.value;
+
+ if (from.width === 0 || to.width === 0) {
+ return [];
+ }
+
+ const fromPorts: Segment1D = [from.x, from.x + from.width];
+ const toPorts: Segment1D = [to.x, to.x + to.width];
+
+ const rel = segmentOverlap1D(
+ fromPorts[0],
+ fromPorts[1],
+ toPorts[0],
+ toPorts[1]
+ );
+ const [fromPort, toPort] = pickPorts(rel, fromPorts, toPorts);
+
+ return generateLine(from, fromPort, to, toPort);
+});
+const findRect = (table: TableMetadata, columnName: string): Rect => {
+ const id = idOfTable(table);
+ const tableRect = rectOfTable(table);
+ const tableElement = document.querySelector(`[bb-node-id="${id}"]`);
+ if (!tableElement) {
+ return { x: 0, y: 0, width: 0, height: 0 };
+ }
+ const columnElement = tableElement.querySelector(
+ `[bb-column-name="${columnName}"]`
+ );
+ if (columnElement) {
+ const tableView = tableElement.getBoundingClientRect();
+ const columnView = columnElement.getBoundingClientRect();
+ const columnRect = {
+ x: tableRect.x + (columnView.left - tableView.left) / zoom.value,
+ y: tableRect.y + (columnView.top - tableView.top) / zoom.value,
+ width: columnView.width / zoom.value,
+ height: columnView.height / zoom.value,
+ };
+ return columnRect;
+ }
+ return tableRect;
+};
+
+// A field has two "ports" - left and right.
+// For a field-field relationship a-b, we need to find which ports
+// of a and b we should use to make the connection line looks natural.
+const pickPorts = (
+ rel: SegmentOverlap1D,
+ a: Segment1D,
+ b: Segment1D
+): [Direction, Direction] => {
+ switch (rel) {
+ case "BEFORE":
+ return ["RIGHT", "LEFT"];
+ case "AFTER":
+ return ["LEFT", "RIGHT"];
+ case "CONTAINS":
+ case "OVERLAPS":
+ return b[0] <= (a[0] + a[1]) / 2 ? ["LEFT", "LEFT"] : ["RIGHT", "RIGHT"];
+ case "OVERLAPPED":
+ case "CONTAINED":
+ return a[0] <= (b[0] + b[1]) / 2 ? ["LEFT", "LEFT"] : ["RIGHT", "RIGHT"];
+ }
+};
+
+const grow = (pos: Position, dir: Direction, length: number): Position => {
+ const x = dir === "LEFT" ? pos.x - length : pos.x + length;
+ return { x, y: pos.y };
+};
+const anchor = (rect: Rect, edge: Direction): Position => {
+ const x = edge === "LEFT" ? rect.x : rect.x + rect.width;
+ const y = rect.y + rect.height / 2;
+ return { x, y };
+};
+const generateLine = (src: Rect, se: Direction, dest: Rect, de: Direction) => {
+ const GROWTH_LEN = 16;
+ const sp = anchor(src, se); // source point
+ const dp = anchor(dest, de); // destination point
+ const sc = grow(sp, se, GROWTH_LEN); // source corner
+ const dc = grow(dp, de, GROWTH_LEN); // destination corner
+ return [sp, sc, dc, dp];
+};
+
+const updatePath = () => {
+ const { from, to } = props.fk;
+ fromRect.value = findRect(from.table, from.column);
+ toRect.value = findRect(to.table, to.column);
+};
+
+events.on("render", () => void updatePath());
+
+onMounted(updatePath);
+</script>
diff --git a/frontend/src/components/SchemaDiagram/ER/index.ts b/frontend/src/components/SchemaDiagram/ER/index.ts
index 9aacf6f7eb..3af863a59d 100644
--- a/frontend/src/components/SchemaDiagram/ER/index.ts
+++ b/frontend/src/components/SchemaDiagram/ER/index.ts
@@ -1,4 +1,5 @@
import TableNode from "./TableNode.vue";
+import ForeignKeyLine from "./ForeignKeyLine.vue";
-export { TableNode };
+export { TableNode, ForeignKeyLine };
export * from "./libs/autoLayout";
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue b/frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue
new file mode 100644
index 0000000000..43b8806155
--- /dev/null
+++ b/frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue
@@ -0,0 +1,94 @@
+<template>
+ <svg
+ version="1.1"
+ xmlns="http://www.w3.org/2000/svg"
+ class="absolute"
+ :style="{
+ left: `${bbox.x - AA_OFFSET[0]}px`,
+ top: `${bbox.y - AA_OFFSET[1]}px`,
+ width: `${bbox.width + AA_OFFSET[0] * 2}px`,
+ height: `${bbox.height + AA_OFFSET[1] * 2}px`,
+ }"
+ >
+ <path
+ version="1.1"
+ xmlns="http://www.w3.org/2000/svg"
+ :d="svgLine"
+ v-bind="aaProps"
+ pointer-events="visibleStroke"
+ fill="none"
+ stroke="11.5"
+ stroke-width="11.5"
+ class="opacity-40"
+ ></path>
+ <path
+ v-for="(decorator, i) in svgDecorators"
+ :key="i"
+ version="1.1"
+ xmlns="http://www.w3.org/2000/svg"
+ :d="decorator"
+ v-bind="aaProps"
+ stroke="rgb(40, 40, 40)"
+ fill="none"
+ stroke-width="1"
+ pointer-events="visibleStroke"
+ />
+ <path
+ version="1.1"
+ xmlns="http://www.w3.org/2000/svg"
+ :d="svgLine"
+ v-bind="aaProps"
+ pointer-events="visibleStroke"
+ fill="none"
+ stroke="rgb(40, 40, 40)"
+ stroke-width="1.5"
+ ></path>
+ </svg>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { Path } from "../../types";
+import { line as d3Line } from "d3-shape";
+import { calcBBox } from "../../common";
+
+// For SVG anti-aliasing, especially a line aligned to the x-axis
+// Just a simple workaround, not perfect.
+const AA_OFFSET = [2.25, 2.25];
+
+const props = withDefaults(
+ defineProps<{
+ path: Path;
+ decorators?: Path[];
+ }>(),
+ {
+ decorators: () => [],
+ }
+);
+
+const bbox = computed(() => {
+ const points = [...props.path];
+ props.decorators.forEach((decorator) => points.push(...decorator));
+ return calcBBox(points);
+});
+
+const aaProps = computed(() => ({
+ transform: `translate(${AA_OFFSET.join(",")})`,
+}));
+
+const normalize = (x: number, y: number): [number, number] => {
+ const dx = bbox.value.x;
+ const dy = bbox.value.y;
+ return [x - dx, y - dy];
+};
+
+const svgLine = computed(() => {
+ return d3Line()(props.path.map((p) => normalize(p.x, p.y))) ?? "";
+});
+
+const svgDecorators = computed(() => {
+ return props.decorators.map((path) => {
+ return d3Line()(path.map((p) => normalize(p.x, p.y))) ?? "";
+ });
+});
+</script>
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.ts b/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.ts
index 2f48af7090..a436b04001 100644
--- a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.ts
+++ b/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.ts
@@ -1,5 +1,5 @@
+import { Path, Rect, Size } from "../../types";
import dagre from "dagre";
-import { Rect, Size } from "../../types";
export type GraphNodeItem = {
id: string;
@@ -7,36 +7,54 @@ export type GraphNodeItem = {
};
export type GraphEdgeItem = {
+ id: string;
from: string;
to: string;
};
-export const autoLayout = (
+export type Layout = {
+ rects: Map<string, Rect>;
+ paths: Map<string, Path>;
+};
+
+export const layoutDagre = async (
nodeList: GraphNodeItem[],
edgeList: GraphEdgeItem[]
-) => {
- const g = new dagre.graphlib.Graph();
+): Promise<Layout> => {
+ const g = new dagre.graphlib.Graph({ multigraph: true });
g.setGraph({
- rankdir: "TD",
- nodesep: 100, // x gap
- ranksep: 100, // y gap
+ rankdir: "LR",
+ nodesep: 160, // gap between nodes in a layer
+ ranksep: 160, // gap between layers
});
g.setDefaultEdgeLabel(() => ({}));
-
nodeList.forEach(({ id, size }) => {
g.setNode(id, {
...size,
});
});
- edgeList.forEach(({ from, to }) => {
- g.setEdge({ v: from, w: to });
+ edgeList.forEach(({ id, from, to }) => {
+ g.setEdge({ name: id, v: from, w: to });
});
dagre.layout(g);
-
- const rectsByTableId = new Map<string, Rect>();
+ const rects = new Map<string, Rect>();
g.nodes().forEach((id) => {
const node = g.node(id);
- rectsByTableId.set(id, node);
+ rects.set(id, node);
+ });
+ const paths = new Map<string, Path>();
+ g.edges().forEach((e) => {
+ const edge = g.edge(e);
+ const { points } = edge;
+ paths.set(e.name!, points);
});
- return rectsByTableId;
+
+ return { rects, paths };
+};
+
+export const autoLayout = async (
+ nodeList: GraphNodeItem[],
+ edgeList: GraphEdgeItem[]
+): Promise<Layout> => {
+ return layoutDagre(nodeList, edgeList);
};
diff --git a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue b/frontend/src/components/SchemaDiagram/SchemaDiagram.vue
index 4ebfad5740..e460015ee9 100644
--- a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue
+++ b/frontend/src/components/SchemaDiagram/SchemaDiagram.vue
@@ -2,6 +2,8 @@
<Canvas>
<template #desktop>
<TableNode v-for="(table, i) in tableList" :key="i" :table="table" />
+
+ <ForeignKeyLine v-for="(fk, i) in foreignKeys" :key="i" :fk="fk" />
</template>
</Canvas>
</template>
@@ -13,9 +15,15 @@ import Emittery from "emittery";
import { Database } from "@/types";
import { TableMetadata } from "@/types/proto/store/database";
-import { Position, Rect, Size, SchemaDiagramContext } from "./types";
+import {
+ Position,
+ Rect,
+ Size,
+ SchemaDiagramContext,
+ ForeignKey,
+} from "./types";
import Canvas from "./Canvas";
-import { TableNode, autoLayout } from "./ER";
+import { TableNode, autoLayout, GraphNodeItem } from "./ER";
import { provideSchemaDiagramContext } from "./common";
const props = withDefaults(
@@ -38,6 +46,28 @@ const events: SchemaDiagramContext["events"] = new Emittery();
const tableIds = ref(new WeakMap<TableMetadata, string>());
const rectsByTableId = ref(new Map<string, Rect>());
+const foreignKeys = computed((): ForeignKey[] => {
+ const find = (t: string, c: string) => {
+ const table = props.tableList.find((table) => table.name === t)!;
+ const column = c;
+ return { table, column };
+ };
+ const fks: ForeignKey[] = [];
+ props.tableList.forEach((table) => {
+ table.foreignKeys.forEach((fkMetadata) => {
+ const { columns, referencedTable, referencedColumns } = fkMetadata;
+ for (let i = 0; i < columns.length; i++) {
+ fks.push({
+ from: { table, column: columns[i] },
+ to: find(referencedTable, referencedColumns[i]),
+ metadata: fkMetadata,
+ });
+ }
+ });
+ });
+
+ return fks;
+});
const idOfTable = (table: TableMetadata): string => {
const ids = tableIds.value;
@@ -53,7 +83,7 @@ const rectOfTable = (table: TableMetadata): Rect => {
};
const layout = () => {
- nextTick(() => {
+ return nextTick(async () => {
const nodeList = props.tableList
.map((table) => {
const id = idOfTable(table);
@@ -65,7 +95,7 @@ const layout = () => {
};
})
.filter((item) => !!item.elem)
- .map((item) => {
+ .map<GraphNodeItem>((item) => {
const size: Size = {
width: item.elem.clientWidth,
height: item.elem.clientHeight,
@@ -73,15 +103,23 @@ const layout = () => {
return {
...item,
size,
+ ports: [],
};
});
- const layout = autoLayout(nodeList, []);
- for (const [id, rect] of layout) {
+ const edgeList = foreignKeys.value.map((fk) => {
+ return {
+ id: `${fk.from.table.name}.${fk.from.column}->${fk.to.table.name}.${fk.to.column}`,
+ from: idOfTable(fk.from.table),
+ to: idOfTable(fk.to.table),
+ };
+ });
+ const { rects } = await autoLayout(nodeList, edgeList);
+ for (const [id, rect] of rects) {
rectsByTableId.value.set(id, rect);
}
- });
- render();
+ render();
+ });
};
events.on("layout", layout);
@@ -98,8 +136,8 @@ provideSchemaDiagramContext({
});
// autoLayout and fit view at the first time the diagram is mounted.
-onMounted(() => {
- layout();
+onMounted(async () => {
+ await layout();
nextTick(() => {
events.emit("fit-view");
});
diff --git a/frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue b/frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue
new file mode 100644
index 0000000000..1d8a663f1e
--- /dev/null
+++ b/frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue
@@ -0,0 +1,3 @@
+<template>
+ <heroicons-outline:rectangle-group class="w-4 h-4" />
+</template>
diff --git a/frontend/src/components/SchemaDiagram/common/geometry.ts b/frontend/src/components/SchemaDiagram/common/geometry.ts
index 7f95e3d1b4..125cb65e5e 100644
--- a/frontend/src/components/SchemaDiagram/common/geometry.ts
+++ b/frontend/src/components/SchemaDiagram/common/geometry.ts
@@ -25,3 +25,40 @@ export const calcBBox = (points: Position[]): Rect => {
height: max.y - min.y,
};
};
+
+export type SegmentOverlap1D =
+ | "BEFORE"
+ | "OVERLAPS"
+ | "CONTAINS"
+ | "OVERLAPPED"
+ | "CONTAINED"
+ | "AFTER";
+
+export const segmentOverlap1D = (
+ a: number,
+ b: number,
+ c: number,
+ d: number
+): SegmentOverlap1D => {
+ /**
+ * Giving two segments `AB` and `CD` on a line,
+ * find the intersection relationship of them.
+ * 1. A-B C-D -> AB before CD
+ * 2. A-C-B-D -> AB overlaps CD
+ * 3. A-C-D-B -> AB contains CD
+ * 4. C-A-D-B -> AB overlapped by CD
+ * 5. C-A-B-D -> AB contained by CD
+ * 6. C-D A-B -> AB after CD
+ */
+ console.assert(a <= b, `expected a=${a} to < b=${b}`);
+ console.assert(c <= d, `expected c=${c} to < d=${d}`);
+
+ if (b < c) return "BEFORE";
+ if (a < c && b >= c && b < d) return "OVERLAPS";
+ if (a < c && d < b) return "CONTAINS";
+ if (a >= c && a < d && b >= d) return "OVERLAPPED";
+ if (a >= c && b < d) return "CONTAINED";
+ if (a >= d) return "AFTER";
+
+ throw new Error(`should never be here a=${a}, b=${b}, c=${c}, d=${d}`);
+};
diff --git a/frontend/src/components/SchemaDiagram/index.ts b/frontend/src/components/SchemaDiagram/index.ts
index 921a4cebc5..86e4ff52b0 100644
--- a/frontend/src/components/SchemaDiagram/index.ts
+++ b/frontend/src/components/SchemaDiagram/index.ts
@@ -1,5 +1,6 @@
import SchemaDiagram from "./SchemaDiagram.vue";
+import SchemaDiagramIcon from "./SchemaDiagramIcon.vue";
-export { SchemaDiagram };
+export { SchemaDiagram, SchemaDiagramIcon };
export default SchemaDiagram;
diff --git a/frontend/src/components/SchemaDiagram/types/index.ts b/frontend/src/components/SchemaDiagram/types/index.ts
index 63ed988d65..8be96ecc35 100644
--- a/frontend/src/components/SchemaDiagram/types/index.ts
+++ b/frontend/src/components/SchemaDiagram/types/index.ts
@@ -1,2 +1,3 @@
export * from "./context";
export * from "./geometry";
+export * from "./schema";
diff --git a/frontend/src/components/SchemaDiagram/types/schema.ts b/frontend/src/components/SchemaDiagram/types/schema.ts
new file mode 100644
index 0000000000..dfd24326d8
--- /dev/null
+++ b/frontend/src/components/SchemaDiagram/types/schema.ts
@@ -0,0 +1,16 @@
+import {
+ ForeignKeyMetadata,
+ TableMetadata,
+} from "@/types/proto/store/database";
+
+export type ForeignKey = {
+ from: {
+ table: TableMetadata;
+ column: string;
+ };
+ to: {
+ table: TableMetadata;
+ column: string;
+ };
+ metadata: ForeignKeyMetadata;
+};
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index 1e5da33db1..8960c87db1 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -113,7 +113,7 @@
@click.prevent="state.showSchemaDiagram = true"
>
<span class="mr-1">{{ $t("schema-diagram.self") }}</span>
- <heroicons-solid:table-cells class="w-4 h-4" />
+ <SchemaDiagramIcon />
</dd>
<DatabaseLabelProps
:label-list="database.labels"
@@ -304,9 +304,11 @@
<BBModal
v-if="state.showSchemaDiagram"
:title="$t('schema-diagram.self')"
+ class="h-[calc(100vh-40px)] !max-h-[calc(100vh-40px)]"
+ container-class="flex-1 !pt-0 !border-0"
@close="state.showSchemaDiagram = false"
>
- <div class="w-[80vw] h-[70vh]">
+ <div class="w-[80vw] h-full">
<SchemaDiagram
:database="database"
:table-list="dbSchemaStore.getTableListByDatabaseId(database.id)"
@@ -357,7 +359,7 @@ import {
import { BBTabFilterItem } from "@/bbkit/types";
import { useI18n } from "vue-i18n";
import { GhostDialog } from "@/components/AlterSchemaPrepForm";
-import SchemaDiagram from "@/components/SchemaDiagram";
+import { SchemaDiagram, SchemaDiagramIcon } from "@/components/SchemaDiagram";
import {
pushNotification,
useCurrentUser,