Skip to content

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

Add unique constraint management (#1042)

1ilit7265fd8528bb
diff --git a/src/components/EditorHeader/ControlPanel.jsx b/src/components/EditorHeader/ControlPanel.jsx
index 51f169df..864e05f6 100644
--- a/src/components/EditorHeader/ControlPanel.jsx
+++ b/src/components/EditorHeader/ControlPanel.jsx
@@ -261,6 +261,34 @@ export default function ControlPanel({
updateTable(a.tid, {
indices: updatedIndices.map((t, i) => ({ ...t, id: i })),
});
+ } else if (a.component === "unique_constraint_add") {
+ const constraints = table.uniqueConstraints || [];
+ updateTable(a.tid, {
+ uniqueConstraints: constraints
+ .filter((e) => e.id !== constraints.length - 1)
+ .map((t, i) => ({ ...t, id: i })),
+ });
+ } else if (a.component === "unique_constraint") {
+ updateTable(a.tid, {
+ uniqueConstraints: (table.uniqueConstraints || []).map(
+ (constraint) =>
+ constraint.id === a.cid
+ ? {
+ ...constraint,
+ ...a.undo,
+ }
+ : constraint,
+ ),
+ });
+ } else if (a.component === "unique_constraint_delete") {
+ const updatedConstraints = (table.uniqueConstraints || []).slice();
+ updatedConstraints.splice(a.data.id, 0, a.data);
+ updateTable(a.tid, {
+ uniqueConstraints: updatedConstraints.map((t, i) => ({
+ ...t,
+ id: i,
+ })),
+ });
} else if (a.component === "self") {
updateTable(a.tid, a.undo);
}
@@ -442,6 +470,36 @@ export default function ControlPanel({
.filter((e) => e.id !== a.data.id)
.map((t, i) => ({ ...t, id: i })),
});
+ } else if (a.component === "unique_constraint_add") {
+ const constraints = table.uniqueConstraints || [];
+ updateTable(a.tid, {
+ uniqueConstraints: [
+ ...constraints,
+ {
+ id: constraints.length,
+ name: `${table.name}_unique_${constraints.length}`,
+ fields: [],
+ },
+ ],
+ });
+ } else if (a.component === "unique_constraint") {
+ updateTable(a.tid, {
+ uniqueConstraints: (table.uniqueConstraints || []).map(
+ (constraint) =>
+ constraint.id === a.cid
+ ? {
+ ...constraint,
+ ...a.redo,
+ }
+ : constraint,
+ ),
+ });
+ } else if (a.component === "unique_constraint_delete") {
+ updateTable(a.tid, {
+ uniqueConstraints: (table.uniqueConstraints || [])
+ .filter((e) => e.id !== a.data.id)
+ .map((t, i) => ({ ...t, id: i })),
+ });
} else if (a.component === "self") {
updateTable(a.tid, a.redo, false);
}
diff --git a/src/components/EditorSidePanel/TablesTab/TableInfo.jsx b/src/components/EditorSidePanel/TablesTab/TableInfo.jsx
index 85da449a..27166bce 100644
--- a/src/components/EditorSidePanel/TablesTab/TableInfo.jsx
+++ b/src/components/EditorSidePanel/TablesTab/TableInfo.jsx
@@ -6,9 +6,10 @@ import {
Button,
Card,
Select,
+ Dropdown,
} from "@douyinfe/semi-ui";
import ColorPicker from "../ColorPicker";
-import { IconDeleteStroked } from "@douyinfe/semi-icons";
+import { IconDeleteStroked, IconPlus } from "@douyinfe/semi-icons";
import {
useDiagram,
useLayout,
@@ -18,6 +19,7 @@ import {
import { Action, ObjectType, State, DB } from "../../../data/constants";
import TableField from "./TableField";
import IndexDetails from "./IndexDetails";
+import UniqueConstraintDetails from "./UniqueConstraintDetails";
import { useTranslation } from "react-i18next";
import { SortableList } from "../../SortableList/SortableList";
import { nanoid } from "nanoid";
@@ -26,6 +28,9 @@ export default function TableInfo({ data }) {
const { tables, database } = useDiagram();
const { t } = useTranslation();
const [indexActiveKey, setIndexActiveKey] = useState("");
+ const [uniqueActiveKey, setUniqueActiveKey] = useState("");
+ const [commentActiveKey, setCommentActiveKey] = useState("");
+ const [showComment, setShowComment] = useState(false);
const { layout } = useLayout();
const { deleteTable, updateTable, setTables } = useDiagram();
const { setUndoStack, setRedoStack } = useUndoRedo();
@@ -79,6 +84,69 @@ export default function TableInfo({ data }) {
.flat()
: [];
+ const addIndex = () => {
+ setIndexActiveKey("1");
+ setUndoStack((prev) => [
+ ...prev,
+ {
+ action: Action.EDIT,
+ element: ObjectType.TABLE,
+ component: "index_add",
+ tid: data.id,
+ message: t("edit_table", {
+ tableName: data.name,
+ extra: "[add index]",
+ }),
+ },
+ ]);
+ setRedoStack([]);
+ updateTable(data.id, {
+ indices: [
+ ...data.indices,
+ {
+ id: data.indices.length,
+ name: `${data.name}_index_${data.indices.length}`,
+ unique: false,
+ fields: [],
+ },
+ ],
+ });
+ };
+
+ const addUniqueConstraint = () => {
+ setUniqueActiveKey("1");
+ const constraints = data.uniqueConstraints || [];
+ setUndoStack((prev) => [
+ ...prev,
+ {
+ action: Action.EDIT,
+ element: ObjectType.TABLE,
+ component: "unique_constraint_add",
+ tid: data.id,
+ message: t("edit_table", {
+ tableName: data.name,
+ extra: "[add unique constraint]",
+ }),
+ },
+ ]);
+ setRedoStack([]);
+ updateTable(data.id, {
+ uniqueConstraints: [
+ ...constraints,
+ {
+ id: constraints.length,
+ name: `${data.name}_unique_${constraints.length}`,
+ fields: [],
+ },
+ ],
+ });
+ };
+
+ const addComment = () => {
+ setShowComment(true);
+ setCommentActiveKey("1");
+ };
+
return (
<div>
<div className="flex items-center mb-2.5">
@@ -203,15 +271,53 @@ export default function TableInfo({ data }) {
</Card>
)}
- <Card
- bodyStyle={{ padding: "4px" }}
- style={{ marginTop: "12px", marginBottom: "12px" }}
- headerLine={false}
- >
- <Collapse keepDOM={false} lazyRender>
- <Collapse.Panel header={t("comment")} itemKey="1">
- <TextArea
- field="comment"
+ {(data.uniqueConstraints || []).length > 0 && (
+ <Card
+ bodyStyle={{ padding: "4px" }}
+ style={{ marginTop: "12px", marginBottom: "12px" }}
+ headerLine={false}
+ >
+ <Collapse
+ activeKey={uniqueActiveKey}
+ keepDOM={false}
+ lazyRender
+ onChange={(itemKey) => setUniqueActiveKey(itemKey)}
+ accordion
+ >
+ <Collapse.Panel header={t("unique_constraints")} itemKey="1">
+ {data.uniqueConstraints.map((uc, k) => (
+ <UniqueConstraintDetails
+ key={"unique_constraint_" + k}
+ data={uc}
+ cid={k}
+ tid={data.id}
+ fields={data.fields.map((e) => ({
+ value: e.name,
+ label: e.name,
+ }))}
+ />
+ ))}
+ </Collapse.Panel>
+ </Collapse>
+ </Card>
+ )}
+
+ {((data.comment && data.comment.trim() !== "") || showComment) && (
+ <Card
+ bodyStyle={{ padding: "4px" }}
+ style={{ marginTop: "12px", marginBottom: "12px" }}
+ headerLine={false}
+ >
+ <Collapse
+ activeKey={commentActiveKey}
+ onChange={(itemKey) => setCommentActiveKey(itemKey)}
+ keepDOM={false}
+ lazyRender
+ accordion
+ >
+ <Collapse.Panel header={t("comment")} itemKey="1">
+ <TextArea
+ field="comment"
value={data.comment}
readonly={layout.readOnly}
autosize
@@ -240,10 +346,11 @@ export default function TableInfo({ data }) {
]);
setRedoStack([]);
}}
- />
- </Collapse.Panel>
- </Collapse>
- </Card>
+ />
+ </Collapse.Panel>
+ </Collapse>
+ </Card>
+ )}
<div className="flex justify-between items-center gap-1 mb-2">
<ColorPicker
@@ -254,40 +361,29 @@ export default function TableInfo({ data }) {
onColorPick={(color) => handleColorPick(color)}
/>
<div className="flex gap-1">
- <Button
- block
- disabled={layout.readOnly}
- onClick={() => {
- setIndexActiveKey("1");
- setUndoStack((prev) => [
- ...prev,
- {
- action: Action.EDIT,
- element: ObjectType.TABLE,
- component: "index_add",
- tid: data.id,
- message: t("edit_table", {
- tableName: data.name,
- extra: "[add index]",
- }),
- },
- ]);
- setRedoStack([]);
- updateTable(data.id, {
- indices: [
- ...data.indices,
- {
- id: data.indices.length,
- name: `${data.name}_index_${data.indices.length}`,
- unique: false,
- fields: [],
- },
- ],
- });
- }}
+ <Dropdown
+ position="bottomLeft"
+ trigger="click"
+ render={
+ <Dropdown.Menu>
+ <Dropdown.Item onClick={addComment}>
+ {t("add_comment")}
+ </Dropdown.Item>
+ <Dropdown.Item onClick={addUniqueConstraint}>
+ {t("add_unique_constraint")}
+ </Dropdown.Item>
+ <Dropdown.Item onClick={addIndex}>
+ {t("add_index")}
+ </Dropdown.Item>
+ </Dropdown.Menu>
+ }
>
- {t("add_index")}
- </Button>
+ <Button
+ icon={<IconPlus />}
+ disabled={layout.readOnly}
+ title={t("add")}
+ />
+ </Dropdown>
<Button
block
disabled={layout.readOnly}
diff --git a/src/components/EditorSidePanel/TablesTab/UniqueConstraintDetails.jsx b/src/components/EditorSidePanel/TablesTab/UniqueConstraintDetails.jsx
new file mode 100644
index 00000000..4c5e9b50
--- /dev/null
+++ b/src/components/EditorSidePanel/TablesTab/UniqueConstraintDetails.jsx
@@ -0,0 +1,158 @@
+import { Action, ObjectType } from "../../../data/constants";
+import { Input, Button, Popover, Select } from "@douyinfe/semi-ui";
+import { IconMore, IconDeleteStroked } from "@douyinfe/semi-icons";
+import { useDiagram, useLayout, useUndoRedo } from "../../../hooks";
+import { useTranslation } from "react-i18next";
+import { useMemo, useState } from "react";
+
+export default function UniqueConstraintDetails({ data, fields, cid, tid }) {
+ const { t } = useTranslation();
+ const { layout } = useLayout();
+ const { tables, updateTable } = useDiagram();
+ const { setUndoStack, setRedoStack } = useUndoRedo();
+ const [editField, setEditField] = useState({});
+ const table = useMemo(() => tables.find((t) => t.id === tid), [tables, tid]);
+
+ const constraints = table.uniqueConstraints ?? [];
+
+ return (
+ <div className="flex justify-between items-center mb-2">
+ <Select
+ placeholder={t("select_fields")}
+ multiple
+ validateStatus={data.fields.length === 0 ? "error" : "default"}
+ optionList={fields}
+ className="w-full"
+ value={data.fields}
+ onChange={(value) => {
+ if (layout.readOnly) return;
+
+ setUndoStack((prev) => [
+ ...prev,
+ {
+ action: Action.EDIT,
+ element: ObjectType.TABLE,
+ component: "unique_constraint",
+ tid: tid,
+ cid: cid,
+ undo: {
+ fields: [...data.fields],
+ },
+ redo: {
+ fields: [...value],
+ },
+ message: t("edit_table", {
+ tableName: table.name,
+ extra: "[unique constraint field]",
+ }),
+ },
+ ]);
+ setRedoStack([]);
+ updateTable(tid, {
+ uniqueConstraints: constraints.map((constraint) =>
+ constraint.id === cid
+ ? {
+ ...constraint,
+ fields: [...value],
+ }
+ : constraint,
+ ),
+ });
+ }}
+ />
+ <Popover
+ content={
+ <div className="px-1 popover-theme">
+ <div className="font-semibold mb-1">{t("name")}: </div>
+ <Input
+ value={data.name}
+ placeholder={t("name")}
+ readonly={layout.readOnly}
+ validateStatus={data.name.trim() === "" ? "error" : "default"}
+ onFocus={() =>
+ setEditField({
+ name: data.name,
+ })
+ }
+ onChange={(value) =>
+ updateTable(tid, {
+ uniqueConstraints: constraints.map((constraint) =>
+ constraint.id === cid
+ ? {
+ ...constraint,
+ name: value,
+ }
+ : constraint,
+ ),
+ })
+ }
+ onBlur={(e) => {
+ if (e.target.value === editField.name) return;
+ setUndoStack((prev) => [
+ ...prev,
+ {
+ action: Action.EDIT,
+ element: ObjectType.TABLE,
+ component: "unique_constraint",
+ tid: tid,
+ cid: cid,
+ undo: editField,
+ redo: { name: e.target.value },
+ message: t("edit_table", {
+ tableName: table.name,
+ extra: "[unique constraint]",
+ }),
+ },
+ ]);
+ setRedoStack([]);
+ }}
+ />
+ <Button
+ block
+ type="danger"
+ className="mt-2"
+ disabled={layout.readOnly}
+ icon={<IconDeleteStroked />}
+ onClick={() => {
+ setUndoStack((prev) => [
+ ...prev,
+ {
+ action: Action.EDIT,
+ element: ObjectType.TABLE,
+ component: "unique_constraint_delete",
+ tid: tid,
+ data: data,
+ message: t("edit_table", {
+ tableName: table.name,
+ extra: "[delete unique constraint]",
+ }),
+ },
+ ]);
+ setRedoStack([]);
+ updateTable(tid, {
+ uniqueConstraints: constraints
+ .filter((e) => e.id !== cid)
+ .map((e, j) => ({
+ ...e,
+ id: j,
+ })),
+ });
+ }}
+ >
+ {t("delete")}
+ </Button>
+ </div>
+ }
+ trigger="click"
+ position="rightTop"
+ showArrow
+ >
+ <Button
+ icon={<IconMore />}
+ type="tertiary"
+ style={{ marginLeft: "12px" }}
+ />
+ </Popover>
+ </div>
+ );
+}
diff --git a/src/context/DiagramContext.jsx b/src/context/DiagramContext.jsx
index 9632d889..61488f5f 100644
--- a/src/context/DiagramContext.jsx
+++ b/src/context/DiagramContext.jsx
@@ -59,6 +59,7 @@ export default function DiagramContextProvider({ children }) {
],
comment: "",
indices: [],
+ uniqueConstraints: [],
color: defaultBlue,
collapsed: false,
};
diff --git a/src/data/schemas.js b/src/data/schemas.js
index c6f2734f..4972b4df 100644
--- a/src/data/schemas.js
+++ b/src/data/schemas.js
@@ -56,6 +56,20 @@ export const tableSchema = {
required: ["name", "unique", "fields"],
},
},
+ uniqueConstraints: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: { type: "string" },
+ fields: {
+ type: "array",
+ items: { type: "string" },
+ },
+ },
+ required: ["name", "fields"],
+ },
+ },
color: { type: "string", pattern: "^#[0-9a-fA-F]{6}$" },
inherits: {
type: "array",
diff --git a/src/i18n/locales/en.js b/src/i18n/locales/en.js
index f3af35c8..f0930657 100644
--- a/src/i18n/locales/en.js
+++ b/src/i18n/locales/en.js
@@ -127,6 +127,8 @@ const en = {
check: "Check expression",
this_will_appear_as_is: "*This will appear in the generated script as is.",
comment: "Comment",
+ add: "Add",
+ add_comment: "Add comment",
add_field: "Add field",
values: "Values",
size: "Size",
@@ -135,6 +137,8 @@ const en = {
use_for_batch_input: "Use , for batch input",
indices: "Indices",
add_index: "Add index",
+ unique_constraints: "Unique constraints",
+ add_unique_constraint: "Add unique constraint",
select_fields: "Select fields",
title: "Title",
not_set: "Not set",
diff --git a/src/utils/exportAs/dbml.js b/src/utils/exportAs/dbml.js
index e313b111..a99ae3a1 100644
--- a/src/utils/exportAs/dbml.js
+++ b/src/utils/exportAs/dbml.js
@@ -157,22 +157,28 @@ export function toDBML(diagram) {
diagram.database,
)}${columnSettings(field, diagram.database)}`,
)
- .join("\n")}${
- table.indices.length > 0
- ? "\n\n\tindexes {\n" +
- table.indices
- .map(
- (index) =>
- `\t\t(${index.fields
- .map((f) => quoteIdentifier(f))
- .join(", ")}) [ name: '${
- index.name
- }'${index.unique ? ", unique" : ""} ]`,
- )
- .join("\n") +
- "\n\t}"
- : ""
- }${
+ .join("\n")}${(() => {
+ const indexEntries = table.indices.map(
+ (index) =>
+ `\t\t(${index.fields
+ .map((f) => quoteIdentifier(f))
+ .join(", ")}) [ name: '${index.name}'${
+ index.unique ? ", unique" : ""
+ } ]`,
+ );
+ const uniqueEntries = (table.uniqueConstraints || [])
+ .filter((uc) => Array.isArray(uc.fields) && uc.fields.length > 0)
+ .map(
+ (uc) =>
+ `\t\t(${uc.fields
+ .map((f) => quoteIdentifier(f))
+ .join(", ")}) [ name: '${uc.name}', unique ]`,
+ );
+ const entries = [...indexEntries, ...uniqueEntries];
+ return entries.length > 0
+ ? "\n\n\tindexes {\n" + entries.join("\n") + "\n\t}"
+ : "";
+ })()}${
table.comment && table.comment.trim() !== ""
? `\n\n\tNote: ${processComment(table.comment)}`
: ""
diff --git a/src/utils/exportAs/documentation.js b/src/utils/exportAs/documentation.js
index c20e938e..a8b3ea04 100644
--- a/src/utils/exportAs/documentation.js
+++ b/src/utils/exportAs/documentation.js
@@ -77,10 +77,22 @@ export function jsonToDocumentation(obj) {
formatMarkdownTable(["Name", "Unique", "Fields"], indexRows);
}
+ let uniqueConstraintsSection = "";
+ if ((table.uniqueConstraints || []).length > 0) {
+ const ucRows = table.uniqueConstraints.map((uc) => [
+ uc.name,
+ uc.fields.join(", "),
+ ]);
+ uniqueConstraintsSection =
+ "\n#### Unique constraints\n" +
+ formatMarkdownTable(["Name", "Fields"], ucRows);
+ }
+
return (
`### ${table.name}\n${table.comment ? table.comment : ""}\n` +
`${fieldsTable} \n${enums.length > 0 ? "\n#### Enums\n" + enums : ""}\n` +
- indexesSection
+ indexesSection +
+ uniqueConstraintsSection
);
})
.join("\n");
diff --git a/src/utils/exportSQL/generic.js b/src/utils/exportSQL/generic.js
index 04d22083..f61c582a 100644
--- a/src/utils/exportSQL/generic.js
+++ b/src/utils/exportSQL/generic.js
@@ -1,6 +1,11 @@
import { DB } from "../../data/constants";
import { dbToTypes, defaultTypes } from "../../data/datatypes";
-import { escapeQuotes, getInlineFK, parseDefault } from "./shared";
+import {
+ escapeQuotes,
+ getInlineFK,
+ parseDefault,
+ uniqueConstraintClause,
+} from "./shared";
export function getJsonType(f) {
if (!Object.keys(defaultTypes).includes(f.type)) {
@@ -218,7 +223,7 @@ export function jsonToMySQL(obj) {
.map((f) => `\`${f.name}\``)
.join(", ")})`
: ""
- }\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};\n${`\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `\`${s}\``)}\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};\n${`\n${table.indices
.map(
(i) =>
`CREATE ${i.unique ? "UNIQUE " : ""}INDEX \`${i.name}\`\nON \`${table.name}\` (${i.fields
@@ -317,7 +322,7 @@ export function jsonToPostgreSQL(obj) {
.map((f) => `"${f.name}"`)
.join(", ")})`
: ""
- }\n);\n${table.comment != "" ? `\nCOMMENT ON TABLE ${table.name} IS '${escapeQuotes(table.comment)}';\n` : ""}${table.fields
+ }${uniqueConstraintClause(table, (s) => `"${s}"`)}\n);\n${table.comment != "" ? `\nCOMMENT ON TABLE ${table.name} IS '${escapeQuotes(table.comment)}';\n` : ""}${table.fields
.map((field) =>
field.comment.trim() !== ""
? `COMMENT ON COLUMN ${table.name}.${field.name} IS '${escapeQuotes(field.comment)}';\n`
@@ -412,7 +417,7 @@ export function jsonToSQLite(obj) {
.map((f) => `"${f.name}"`)
.join(", ")})${inlineFK !== "" ? ",\n" : ""}`
: ""
- }${inlineFK}\n);\n${table.indices
+ }${inlineFK}${uniqueConstraintClause(table, (s) => `"${s}"`)}\n);\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS "${
@@ -461,7 +466,7 @@ export function jsonToMariaDB(obj) {
.map((f) => `\`${f.name}\``)
.join(", ")})`
: ""
- }\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};${`\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `\`${s}\``)}\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};${`\n${table.indices
.map(
(i) =>
`CREATE ${i.unique ? "UNIQUE " : ""}INDEX \`${
@@ -533,7 +538,7 @@ export function jsonToSQLServer(obj) {
.map((f) => `[${f.name}]`)
.join(", ")})`
: ""
- }\n);\nGO\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `[${s}]`)}\n);\nGO\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX [${
@@ -608,7 +613,7 @@ export function jsonToOracleSQL(obj) {
.map((f) => `"${f.name}"`)
.join(", ")})`
: ""
- }\n);\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `"${s}"`)}\n);\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX "${i.name}"\n ON "${
diff --git a/src/utils/exportSQL/mariadb.js b/src/utils/exportSQL/mariadb.js
index 59255d41..4a04abf0 100644
--- a/src/utils/exportSQL/mariadb.js
+++ b/src/utils/exportSQL/mariadb.js
@@ -1,4 +1,4 @@
-import { escapeQuotes, parseDefault } from "./shared";
+import { escapeQuotes, parseDefault, uniqueConstraintClause } from "./shared";
import { dbToTypes } from "../../data/datatypes";
import { DB } from "../../data/constants";
@@ -47,7 +47,7 @@ export function toMariaDB(diagram) {
.map((f) => `\`${f.name}\``)
.join(", ")})`
: ""
- }\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};${`\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `\`${s}\``)}\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};${`\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX \`${
diff --git a/src/utils/exportSQL/mssql.js b/src/utils/exportSQL/mssql.js
index a2354d35..dae5db68 100644
--- a/src/utils/exportSQL/mssql.js
+++ b/src/utils/exportSQL/mssql.js
@@ -1,4 +1,4 @@
-import { parseDefault, escapeQuotes } from "./shared";
+import { parseDefault, escapeQuotes, uniqueConstraintClause } from "./shared";
import { dbToTypes } from "../../data/datatypes";
import { DB } from "../../data/constants";
@@ -64,7 +64,9 @@ export function toMSSQL(diagram) {
.join(", ")})`
: "";
- const createTableSql = `CREATE TABLE [${table.name}] (\n${fieldsSql}${primaryKeySql}\n);\nGO\n`;
+ const uniqueSql = uniqueConstraintClause(table, (s) => `[${s}]`);
+
+ const createTableSql = `CREATE TABLE [${table.name}] (\n${fieldsSql}${primaryKeySql}${uniqueSql}\n);\nGO\n`;
const tableCommentSql = generateAddExtendedPropertySQL(
table.comment,
diff --git a/src/utils/exportSQL/mysql.js b/src/utils/exportSQL/mysql.js
index f35dbda3..58fa2534 100644
--- a/src/utils/exportSQL/mysql.js
+++ b/src/utils/exportSQL/mysql.js
@@ -1,4 +1,4 @@
-import { escapeQuotes, parseDefault } from "./shared";
+import { escapeQuotes, parseDefault, uniqueConstraintClause } from "./shared";
import { dbToTypes } from "../../data/datatypes";
import { DB } from "../../data/constants";
@@ -51,7 +51,7 @@ export function toMySQL(diagram) {
.map((f) => `\`${f.name}\``)
.join(", ")})`
: ""
- }\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};\n${`\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `\`${s}\``)}\n)${table.comment ? ` COMMENT='${escapeQuotes(table.comment)}'` : ""};\n${`\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX \`${
diff --git a/src/utils/exportSQL/oraclesql.js b/src/utils/exportSQL/oraclesql.js
index 0a44c565..4a746f5a 100644
--- a/src/utils/exportSQL/oraclesql.js
+++ b/src/utils/exportSQL/oraclesql.js
@@ -1,5 +1,5 @@
import { dbToTypes } from "../../data/datatypes";
-import { parseDefault } from "./shared";
+import { parseDefault, uniqueConstraintClause } from "./shared";
export function toOracleSQL(diagram) {
return `${diagram.tables
@@ -36,7 +36,7 @@ export function toOracleSQL(diagram) {
.map((f) => `"${f.name}"`)
.join(", ")})`
: ""
- }\n)${table.comment ? ` -- ${table.comment}` : ""};\n${`\n${table.indices
+ }${uniqueConstraintClause(table, (s) => `"${s}"`)}\n)${table.comment ? ` -- ${table.comment}` : ""};\n${`\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX "${i.name}"\nON "${table.name}" (${i.fields
diff --git a/src/utils/exportSQL/postgres.js b/src/utils/exportSQL/postgres.js
index 3dc6c0e1..52a9aa6f 100644
--- a/src/utils/exportSQL/postgres.js
+++ b/src/utils/exportSQL/postgres.js
@@ -1,4 +1,9 @@
-import { escapeQuotes, exportFieldComment, parseDefault } from "./shared";
+import {
+ escapeQuotes,
+ exportFieldComment,
+ parseDefault,
+ uniqueConstraintClause,
+} from "./shared";
import { dbToTypes } from "../../data/datatypes";
export function toPostgres(diagram) {
@@ -59,6 +64,8 @@ export function toPostgres(diagram) {
.join(", ")})`
: "";
+ const uniqueClause = uniqueConstraintClause(table, (s) => `"${s}"`);
+
const commentStatements = [
table.comment?.trim()
? `COMMENT ON TABLE "${table.name}" IS '${escapeQuotes(table.comment)}';`
@@ -81,7 +88,7 @@ export function toPostgres(diagram) {
)
.join("\n");
- return `CREATE TABLE IF NOT EXISTS "${table.name}" (\n${fieldDefinitions}${primaryKeyClause}${inheritsClause};\n\n${commentStatements}\n${indexStatements}`;
+ return `CREATE TABLE IF NOT EXISTS "${table.name}" (\n${fieldDefinitions}${primaryKeyClause}${uniqueClause}${inheritsClause};\n\n${commentStatements}\n${indexStatements}`;
})
.join("\n\n");
diff --git a/src/utils/exportSQL/shared.js b/src/utils/exportSQL/shared.js
index 64100bc7..f6219a46 100644
--- a/src/utils/exportSQL/shared.js
+++ b/src/utils/exportSQL/shared.js
@@ -30,6 +30,25 @@ export function exportFieldComment(comment) {
.join("");
}
+export function uniqueConstraintClause(table, quote) {
+ const constraints = (table.uniqueConstraints || []).filter(
+ (uc) => Array.isArray(uc.fields) && uc.fields.length > 0,
+ );
+ if (constraints.length === 0) return "";
+
+ return (
+ ",\n" +
+ constraints
+ .map(
+ (uc) =>
+ `\tCONSTRAINT ${quote(uc.name)} UNIQUE (${uc.fields
+ .map((f) => quote(f))
+ .join(", ")})`,
+ )
+ .join(",\n")
+ );
+}
+
export function getInlineFK(table, obj) {
let fks = [];
obj.references.forEach((r) => {
diff --git a/src/utils/exportSQL/sqlite.js b/src/utils/exportSQL/sqlite.js
index 25ae186c..a6d6743c 100644
--- a/src/utils/exportSQL/sqlite.js
+++ b/src/utils/exportSQL/sqlite.js
@@ -1,4 +1,9 @@
-import { exportFieldComment, getInlineFK, parseDefault } from "./shared";
+import {
+ exportFieldComment,
+ getInlineFK,
+ parseDefault,
+ uniqueConstraintClause,
+} from "./shared";
import { dbToTypes } from "../../data/datatypes";
@@ -29,7 +34,7 @@ export function toSqlite(diagram) {
.map((f) => `"${f.name}"`)
.join(", ")})${inlineFK !== "" ? ",\n" : ""}`
: ""
- }${inlineFK}\n);\n${table.indices
+ }${inlineFK}${uniqueConstraintClause(table, (s) => `"${s}"`)}\n);\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS "${
diff --git a/src/utils/importFrom/dbml.js b/src/utils/importFrom/dbml.js
index 08cb6b4c..8699aa25 100644
--- a/src/utils/importFrom/dbml.js
+++ b/src/utils/importFrom/dbml.js
@@ -21,6 +21,7 @@ export function fromDBML(src) {
parsedTable.color = table.headerColor ?? "#175e7a";
parsedTable.fields = [];
parsedTable.indices = [];
+ parsedTable.uniqueConstraints = [];
for (const column of table.fields) {
const field = {};
diff --git a/src/utils/importSQL/mariadb.js b/src/utils/importSQL/mariadb.js
index b3a2a85e..0b83cbfd 100644
--- a/src/utils/importSQL/mariadb.js
+++ b/src/utils/importSQL/mariadb.js
@@ -33,6 +33,7 @@ export function fromMariaDB(ast, diagramDb = DB.GENERIC) {
table.color = "#175e7a";
table.fields = [];
table.indices = [];
+ table.uniqueConstraints = [];
table.id = nanoid();
e.create_definitions.forEach((d) => {
if (d.resource === "column") {
@@ -160,6 +161,19 @@ export function fromMariaDB(ast, diagramDb = DB.GENERIC) {
}
relationships.push(relationship);
+ } else if (
+ d.constraint_type &&
+ d.constraint_type.toLowerCase().includes("unique")
+ ) {
+ const fields = d.definition.map((c) => c.column);
+ const name =
+ d.constraint ||
+ d.index ||
+ `${table.name}_unique_${table.uniqueConstraints.length}`;
+ table.uniqueConstraints.push({ name, fields });
+ table.uniqueConstraints.forEach((u, j) => {
+ u.id = j;
+ });
}
}
});
diff --git a/src/utils/importSQL/mssql.js b/src/utils/importSQL/mssql.js
index 0decdaa5..b402e568 100644
--- a/src/utils/importSQL/mssql.js
+++ b/src/utils/importSQL/mssql.js
@@ -45,6 +45,7 @@ export function fromMSSQL(ast, diagramDb = DB.GENERIC) {
table.color = "#175e7a";
table.fields = [];
table.indices = [];
+ table.uniqueConstraints = [];
table.id = nanoid();
e.create_definitions.forEach((d) => {
if (d.resource === "column") {
@@ -173,6 +174,19 @@ export function fromMSSQL(ast, diagramDb = DB.GENERIC) {
}
relationships.push(relationship);
+ } else if (
+ d.constraint_type &&
+ d.constraint_type.toLowerCase().includes("unique")
+ ) {
+ const fields = d.definition.map((c) => c.column);
+ const name =
+ d.constraint ||
+ d.index ||
+ `${table.name}_unique_${table.uniqueConstraints.length}`;
+ table.uniqueConstraints.push({ name, fields });
+ table.uniqueConstraints.forEach((u, j) => {
+ u.id = j;
+ });
}
}
});
diff --git a/src/utils/importSQL/mysql.js b/src/utils/importSQL/mysql.js
index dfc878cc..874b4097 100644
--- a/src/utils/importSQL/mysql.js
+++ b/src/utils/importSQL/mysql.js
@@ -33,6 +33,7 @@ export function fromMySQL(ast, diagramDb = DB.GENERIC) {
table.color = "#175e7a";
table.fields = [];
table.indices = [];
+ table.uniqueConstraints = [];
table.id = nanoid();
e.create_definitions.forEach((d) => {
if (d.resource === "column") {
@@ -160,6 +161,19 @@ export function fromMySQL(ast, diagramDb = DB.GENERIC) {
}
relationships.push(relationship);
+ } else if (
+ d.constraint_type &&
+ d.constraint_type.toLowerCase().includes("unique")
+ ) {
+ const fields = d.definition.map((c) => c.column);
+ const name =
+ d.constraint ||
+ d.index ||
+ `${table.name}_unique_${table.uniqueConstraints.length}`;
+ table.uniqueConstraints.push({ name, fields });
+ table.uniqueConstraints.forEach((u, j) => {
+ u.id = j;
+ });
}
}
});
diff --git a/src/utils/importSQL/oraclesql.js b/src/utils/importSQL/oraclesql.js
index 40da5a58..7a057458 100644
--- a/src/utils/importSQL/oraclesql.js
+++ b/src/utils/importSQL/oraclesql.js
@@ -35,6 +35,7 @@ export function fromOracleSQL(ast, diagramDb = DB.GENERIC) {
table.color = "#175e7a";
table.fields = [];
table.indices = [];
+ table.uniqueConstraints = [];
table.id = nanoid();
e.table.relational_properties.forEach((d) => {
if (d.resource === "column") {
@@ -80,6 +81,24 @@ export function fromOracleSQL(ast, diagramDb = DB.GENERIC) {
table.fields.push(field);
} else if (d.resource === "constraint") {
+ if (
+ d.constraint?.unique === "unique" &&
+ Array.isArray(d.constraint.columns)
+ ) {
+ const fields = d.constraint.columns;
+ const name =
+ d.name && Boolean(d.name.trim())
+ ? d.name
+ : `${table.name}_unique_${table.uniqueConstraints.length}`;
+ table.uniqueConstraints.push({ name, fields });
+ table.uniqueConstraints.forEach((u, j) => {
+ u.id = j;
+ });
+ return;
+ }
+
+ if (!d.constraint?.reference) return;
+
const relationship = {};
const startFieldName = d.constraint.columns[0];
const endFieldName = d.constraint.reference.columns[0];
diff --git a/src/utils/importSQL/postgres.js b/src/utils/importSQL/postgres.js
index 0e517e6e..ea739cf8 100644
--- a/src/utils/importSQL/postgres.js
+++ b/src/utils/importSQL/postgres.js
@@ -34,6 +34,7 @@ export function fromPostgres(ast, diagramDb = DB.GENERIC) {
table.color = "#175e7a";
table.fields = [];
table.indices = [];
+ table.uniqueConstraints = [];
table.id = nanoid();
e.create_definitions.forEach((d) => {
const field = {};
@@ -178,6 +179,21 @@ export function fromPostgres(ast, diagramDb = DB.GENERIC) {
relationship.cardinality = Cardinality.MANY_TO_ONE;
}
relationships.push(relationship);
+ } else if (
+ d.constraint_type &&
+ d.constraint_type.toLowerCase().includes("unique")
+ ) {
+ const fields = d.definition.map(
+ (c) => c.column?.expr?.value ?? c.column,
+ );
+ const name =
+ d.constraint ||
+ d.index ||
+ `${table.name}_unique_${table.uniqueConstraints.length}`;
+ table.uniqueConstraints.push({ name, fields });
+ table.uniqueConstraints.forEach((u, j) => {
+ u.id = j;
+ });
}
}
diff --git a/src/utils/importSQL/sqlite.js b/src/utils/importSQL/sqlite.js
index 5ef6303e..f9a95a14 100644
--- a/src/utils/importSQL/sqlite.js
+++ b/src/utils/importSQL/sqlite.js
@@ -101,6 +101,7 @@ export function fromSQLite(ast, diagramDb = DB.GENERIC) {
table.color = "#175e7a";
table.fields = [];
table.indices = [];
+ table.uniqueConstraints = [];
table.id = nanoid();
e.create_definitions.forEach((d) => {
if (d.resource === "column") {
@@ -188,6 +189,16 @@ export function fromSQLite(ast, diagramDb = DB.GENERIC) {
d.definition[0].column,
d.reference_definition,
);
+ } else if (d.constraint_type.toLowerCase().includes("unique")) {
+ const fields = d.definition.map((c) => c.column);
+ const name =
+ d.constraint ||
+ d.index ||
+ `${table.name}_unique_${table.uniqueConstraints.length}`;
+ table.uniqueConstraints.push({ name, fields });
+ table.uniqueConstraints.forEach((u, j) => {
+ u.id = j;
+ });
}
}
});
diff --git a/src/utils/issues.js b/src/utils/issues.js
index 0ef471b9..02892113 100644
--- a/src/utils/issues.js
+++ b/src/utils/issues.js
@@ -129,6 +129,23 @@ export function getIssues(diagram) {
}
});
+ const duplicateUniqueConstraints = {};
+ (table.uniqueConstraints || []).forEach((uc) => {
+ if (duplicateUniqueConstraints[uc.name]) {
+ issues.push(
+ i18n.t("duplicate_index", {
+ tableName: table.name,
+ indexName: uc.name,
+ }),
+ );
+ } else {
+ duplicateUniqueConstraints[uc.name] = true;
+ }
+ if (uc.fields.length === 0) {
+ issues.push(i18n.t("empty_index", { tableName: table.name }));
+ }
+ });
+
if (!hasPrimaryKey) {
issues.push(i18n.t("no_primary_key", { tableName: table.name }));
}
diff --git a/src/utils/migrations/diffToSQL.js b/src/utils/migrations/diffToSQL.js
index 026e1a50..97120332 100644
--- a/src/utils/migrations/diffToSQL.js
+++ b/src/utils/migrations/diffToSQL.js
@@ -2,6 +2,7 @@ import {
escapeQuotes,
parseDefault,
exportFieldComment,
+ uniqueConstraintClause,
} from "../exportSQL/shared";
import { DB } from "../../data/constants";
import { databases } from "../../data/databases";
@@ -116,6 +117,8 @@ function toTable(table, db) {
? `,\n\tPRIMARY KEY(${pk.map((f) => q(f.name)).join(", ")})`
: "";
+ const ucClause = uniqueConstraintClause(table, q);
+
let inheritsClause = "";
if (
db === DB.POSTGRES &&
@@ -129,13 +132,13 @@ function toTable(table, db) {
let create = "";
if (db === DB.POSTGRES || db === DB.MYSQL || db === DB.SQLITE) {
- create = `CREATE TABLE IF NOT EXISTS ${q(table.name)} (\n${fieldDefs}${pkClause}${inheritsClause};`;
+ create = `CREATE TABLE IF NOT EXISTS ${q(table.name)} (\n${fieldDefs}${pkClause}${ucClause}${inheritsClause};`;
} else if (db === DB.MARIADB) {
- create = `CREATE OR REPLACE TABLE ${q(table.name)} (\n${fieldDefs}${pkClause}\n)`;
+ create = `CREATE OR REPLACE TABLE ${q(table.name)} (\n${fieldDefs}${pkClause}${ucClause}\n)`;
} else if (db === DB.MSSQL) {
- create = `CREATE TABLE ${q(table.name)} (\n${fieldDefs}${pkClause}\n);\nGO`;
+ create = `CREATE TABLE ${q(table.name)} (\n${fieldDefs}${pkClause}${ucClause}\n);\nGO`;
} else if (db === DB.ORACLESQL) {
- create = `CREATE TABLE ${q(table.name)} (\n${fieldDefs}${pkClause}\n)`;
+ create = `CREATE TABLE ${q(table.name)} (\n${fieldDefs}${pkClause}${ucClause}\n)`;
}
if (db === DB.MARIADB || db === DB.ORACLESQL) create += ";";
@@ -619,6 +622,66 @@ export const generateMigrationSQL = (
}
}
+ if (childPart.startsWith("uniqueConstraints")) {
+ const property = keys[2];
+ const ucFields = (arr) => (arr || []).map((f) => q(f)).join(", ");
+ const addUC = (cname, fields) =>
+ database === DB.SQLITE
+ ? `CREATE UNIQUE INDEX IF NOT EXISTS ${q(cname)} ON ${q(name)} (${ucFields(fields)});`
+ : `ALTER TABLE ${q(name)} ADD CONSTRAINT ${q(cname)} UNIQUE (${ucFields(fields)});`;
+ const dropUC = (cname) =>
+ database === DB.SQLITE
+ ? `DROP INDEX ${q(cname)};`
+ : `ALTER TABLE ${q(name)} DROP CONSTRAINT ${q(cname)};`;
+
+ if (!property) {
+ if (change.to && !change.from) {
+ up.push(addUC(change.to.name, change.to.fields));
+ down.push(dropUC(change.to.name));
+ }
+ if (change.from && !change.to) {
+ up.push(dropUC(change.from.name));
+ down.push(addUC(change.from.name, change.from.fields));
+ }
+ }
+
+ if (property === "name") {
+ if (database === DB.POSTGRES || database === DB.ORACLESQL) {
+ up.push(
+ `ALTER TABLE ${q(name)} RENAME CONSTRAINT ${q(change.from)} TO ${q(change.to)};`,
+ );
+ down.push(
+ `ALTER TABLE ${q(name)} RENAME CONSTRAINT ${q(change.to)} TO ${q(change.from)};`,
+ );
+ } else {
+ up.push(
+ `-- Rename unique constraint: DROP ${q(change.from)} then ADD with new name`,
+ );
+ down.push(
+ `-- Rename unique constraint: DROP ${q(change.to)} then ADD with old name`,
+ );
+ }
+ }
+
+ if (property === "fields") {
+ const ns = childPart.indexOf("name=");
+ const constraintName =
+ ns >= 0
+ ? childPart.substring(ns + 5, childPart.indexOf("]", ns))
+ : "";
+ if (
+ constraintName &&
+ Array.isArray(change.from) &&
+ Array.isArray(change.to)
+ ) {
+ up.push(dropUC(constraintName));
+ up.push(addUC(constraintName, change.to));
+ down.push(dropUC(constraintName));
+ down.push(addUC(constraintName, change.from));
+ }
+ }
+ }
+
if (childPart === "inherits" && keys[2] !== undefined) {
if (database !== DB.POSTGRES) break;