Skip to content

Free, simple, and intuitive online database diagram editor and SQL generator.

Add relationship auto-generation (#1104)

Suraj Kumardd1cf2a2e1f5
diff --git a/src/components/EditorHeader/ControlPanel.jsx b/src/components/EditorHeader/ControlPanel.jsx
index 78a842bd..37e12cf1 100644
--- a/src/components/EditorHeader/ControlPanel.jsx
+++ b/src/components/EditorHeader/ControlPanel.jsx
@@ -25,6 +25,7 @@ import {
Toast,
Popconfirm,
Typography,
+ Modal as SemiModal,
} from "@douyinfe/semi-ui";
import { toPng, toJpeg, toSvg } from "html-to-image";
import {
@@ -88,6 +89,7 @@ import { exportSavedData } from "../../utils/exportSavedData";
import { nanoid } from "nanoid";
import { getTableHeight } from "../../utils/utils";
import { autoArrange } from "../../utils/autoArrange";
+import { findAutoFKRelationships } from "../../utils/autoRelationships";
import { deleteFromCache, STORAGE_KEY } from "../../utils/cache";
import { DateTime } from "luxon";
import ConfigureCustomTypes from "./ConfigureCustomTypes";
@@ -111,6 +113,7 @@ export default function ControlPanel({
const [modal, setModal] = useState(MODAL.NONE);
const [sidesheet, setSidesheet] = useState(SIDESHEET.NONE);
const [showEditName, setShowEditName] = useState(false);
+ const [showAutoConnectModal, setShowAutoConnectModal] = useState(false);
const [importDb, setImportDb] = useState("");
const [exportData, setExportData] = useState({
data: null,
@@ -178,6 +181,12 @@ export default function ControlPanel({
setUndoStack((prev) => prev.filter((_, i) => i !== prev.length - 1));
if (a.bulk) {
+ if (a.element === ObjectType.RELATIONSHIP && a.action === Action.ADD) {
+ const idsToDelete = new Set((a.relationships || []).map((r) => r.id));
+ setRelationships((prev) => prev.filter((r) => !idsToDelete.has(r.id)));
+ setRedoStack((prev) => [...prev, a]);
+ return;
+ }
for (const element of a.elements) {
if (element.type === ObjectType.TABLE) {
updateTable(element.id, element.undo);
@@ -383,6 +392,11 @@ export default function ControlPanel({
setRedoStack((prev) => prev.filter((e, i) => i !== prev.length - 1));
if (a.bulk) {
+ if (a.element === ObjectType.RELATIONSHIP && a.action === Action.ADD) {
+ setRelationships((prev) => [...prev, ...(a.relationships || [])]);
+ setUndoStack((prev) => [...prev, a]);
+ return;
+ }
for (const element of a.elements) {
if (element.type === ObjectType.TABLE) {
updateTable(element.id, element.redo);
@@ -714,6 +728,31 @@ export default function ControlPanel({
setRedoStack([]);
fitToView(arrangedTables);
};
+ const autoConnectFKs = () => {
+ if (layout.readOnly) return;
+ setShowAutoConnectModal(true);
+ };
+ const confirmAutoConnectFKs = () => {
+ setShowAutoConnectModal(false);
+ const newRels = findAutoFKRelationships(tables, relationships);
+ if (newRels.length === 0) {
+ Toast.info(t("all_relations_already_connected"));
+ return;
+ }
+ setRelationships((prev) => [...prev, ...newRels]);
+ setUndoStack((prev) => [
+ ...prev,
+ {
+ action: Action.ADD,
+ element: ObjectType.RELATIONSHIP,
+ bulk: true,
+ message: t("auto_connect_fk"),
+ relationships: newRels,
+ },
+ ]);
+ setRedoStack([]);
+ Toast.success(t("auto_connect_fk_success", { count: newRels.length }));
+ };
const edit = () => {
if (selectedElement.element === ObjectType.TABLE) {
if (!layout.sidebar) {
@@ -1562,6 +1601,10 @@ export default function ControlPanel({
function: autoArrangeTables,
disabled: layout.readOnly,
},
+ auto_connect_fk: {
+ function: autoConnectFKs,
+ disabled: layout.readOnly,
+ },
copy_as_image: {
function: copyAsImage,
shortcut: "Ctrl+Alt+C",
@@ -1887,6 +1930,28 @@ export default function ControlPanel({
open={modal === MODAL.CONFIG_CUSTOM_TYPES}
onClose={() => setModal(MODAL.NONE)}
/>
+ <SemiModal
+ title={t("auto_connect_fk_modal_title")}
+ centered
+ visible={showAutoConnectModal}
+ onOk={confirmAutoConnectFKs}
+ onCancel={() => setShowAutoConnectModal(false)}
+ okText={t("auto_connect_fk")}
+ cancelText={t("cancel")}
+ >
+ <div className="space-y-3">
+ <p className="text-sm">
+ {t("auto_connect_fk_modal_description")}
+ </p>
+ <ol className="list-decimal ps-5 space-y-1 text-sm">
+ <li>{t("auto_connect_fk_rule_1")}</li>
+ <li>{t("auto_connect_fk_rule_2")}</li>
+ </ol>
+ <p className="text-sm font-medium mt-2">
+ {t("auto_connect_fk_modal_question")}
+ </p>
+ </div>
+ </SemiModal>
</>
);
diff --git a/src/i18n/locales/en.js b/src/i18n/locales/en.js
index 7aaaea3f..78a05833 100644
--- a/src/i18n/locales/en.js
+++ b/src/i18n/locales/en.js
@@ -254,6 +254,19 @@ const en = {
supported_types: "Supported file types:",
bulk_update: "Bulk update",
auto_arrange: "Auto arrange",
+ auto_connect_fk: "Auto-connect foreign keys",
+ auto_connect_fk_success: "Created {{count}} foreign key reference(s)",
+ no_foreign_keys_found: "No relationships found",
+ all_relations_already_connected: "All relations are already connected",
+ auto_connect_fk_modal_title: "Auto-Connect Foreign Keys",
+ auto_connect_fk_modal_description:
+ "To automatically establish PK/FK relationships, your columns should follow standard naming conventions:",
+ auto_connect_fk_rule_1:
+ "Table Prefix + PK Column (e.g., user_id or users_id for table 'users' with primary key 'id')",
+ auto_connect_fk_rule_2:
+ "Matching PK Column Name (e.g., author_id matching author_id in parent table)",
+ auto_connect_fk_modal_question:
+ "Would you like to scan the diagram and build matching relationships?",
multiselect: "Multiselect",
export_saved_data: "Export saved data",
dbml_view: "DBML view",
diff --git a/src/utils/autoRelationships.js b/src/utils/autoRelationships.js
new file mode 100644
index 00000000..a9a1d584
--- /dev/null
+++ b/src/utils/autoRelationships.js
@@ -0,0 +1,102 @@
+import { nanoid } from "nanoid";
+import { Cardinality, Constraint } from "../data/constants";
+import { getRelationshipFields } from "./utils";
+
+function singularize(name) {
+ if (!name || typeof name !== "string") return "";
+ const lower = name.trim().toLowerCase();
+ if (lower.endsWith("ies")) return lower.slice(0, -3) + "y";
+ if (lower.endsWith("es") && !lower.endsWith("sses")) return lower.slice(0, -2);
+ if (lower.endsWith("s") && !lower.endsWith("ss")) return lower.slice(0, -1);
+ return lower;
+}
+
+export function findAutoFKRelationships(tables = [], existingRelationships = []) {
+ const newRelationships = [];
+ const currentRelationships = [...existingRelationships];
+
+ const isFieldAlreadyLinked = (childTableId, fieldId) => {
+ return currentRelationships.some((r) => {
+ const pairs = getRelationshipFields(r);
+ if (r.startTableId === childTableId) {
+ return pairs.some((p) => p.startFieldId === fieldId);
+ }
+ return false;
+ });
+ };
+
+ const isPairAlreadyLinked = (childTableId, fkFieldId, parentTableId, pkFieldId) => {
+ return currentRelationships.some((r) => {
+ const pairs = getRelationshipFields(r);
+ const forward =
+ r.startTableId === childTableId &&
+ r.endTableId === parentTableId &&
+ pairs.some((p) => p.startFieldId === fkFieldId && p.endFieldId === pkFieldId);
+ const backward =
+ r.startTableId === parentTableId &&
+ r.endTableId === childTableId &&
+ pairs.some((p) => p.startFieldId === pkFieldId && p.endFieldId === fkFieldId);
+ return forward || backward;
+ });
+ };
+
+ tables.forEach((parentTable) => {
+ const pkFields = (parentTable.fields || []).filter((f) => f.primary);
+ if (pkFields.length === 0) return;
+
+ const pTableName = parentTable.name.trim().toLowerCase();
+ const pSingularName = singularize(pTableName);
+
+ pkFields.forEach((pkField) => {
+ const pkFieldName = pkField.name.trim().toLowerCase();
+
+ // Candidate matching names for the foreign key column in child tables
+ const candidateNames = new Set([
+ `${pTableName}_${pkFieldName}`,//users_id
+ `${pSingularName}_${pkFieldName}`,//user_id
+ `${pTableName}${pkFieldName}`,//usersid
+ `${pSingularName}${pkFieldName}`,//userid
+ ]);
+
+ if (pkFieldName !== "id") {
+ candidateNames.add(pkFieldName);
+ }
+
+ tables.forEach((childTable) => {
+ if (childTable.id === parentTable.id) return;
+
+ (childTable.fields || []).forEach((fkField) => {
+ const fkFieldName = fkField.name.trim().toLowerCase();
+
+ if (!candidateNames.has(fkFieldName)) return;
+
+ if (
+ isFieldAlreadyLinked(childTable.id, fkField.id) ||
+ isPairAlreadyLinked(childTable.id, fkField.id, parentTable.id, pkField.id)
+ ) {
+ return;
+ }
+
+ const rel = {
+ id: nanoid(),
+ name: `fk_${childTable.name}_${fkField.name}_${parentTable.name}`,
+ startTableId: childTable.id,
+ startFieldId: fkField.id,
+ endTableId: parentTable.id,
+ endFieldId: pkField.id,
+ cardinality: fkField.unique
+ ? Cardinality.ONE_TO_ONE
+ : Cardinality.MANY_TO_ONE,
+ updateConstraint: Constraint.NONE,
+ deleteConstraint: Constraint.NONE,
+ };
+
+ newRelationships.push(rel);
+ currentRelationships.push(rel);
+ });
+ });
+ });
+ });
+
+ return newRelationships;
+}