-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
mysql.js
72 lines (66 loc) · 2.46 KB
/
mysql.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { parseDefault } from "./shared";
import { dbToTypes } from "../../data/datatypes";
import { DB } from "../../data/constants";
function parseType(field) {
let res = field.type;
if (field.type === "SET" || field.type === "ENUM") {
res += `${field.values ? "(" + field.values.map((value) => "'" + value + "'").join(", ") + ")" : ""}`;
}
if (dbToTypes[DB.MYSQL][field.type].isSized) {
res += `${field.size && field.size !== "" ? "(" + field.size + ")" : ""}`;
}
return res;
}
export function toMySQL(diagram) {
return `${diagram.tables
.map(
(table) =>
`CREATE TABLE \`${table.name}\` (\n${table.fields
.map(
(field) =>
`\t\`${field.name}\` ${parseType(field)}${field.unsigned ? " UNSIGNED" : ""}${
field.notNull ? " NOT NULL" : ""
}${
field.increment ? " AUTO_INCREMENT" : ""
}${field.unique ? " UNIQUE" : ""}${
field.default !== ""
? ` DEFAULT ${parseDefault(field, diagram.database)}`
: ""
}${
field.check === "" ||
!dbToTypes[diagram.database][field.type].hasCheck
? ""
: ` CHECK(${field.check})`
}${field.comment ? ` COMMENT '${field.comment}'` : ""}`,
)
.join(",\n")}${
table.fields.filter((f) => f.primary).length > 0
? `,\n\tPRIMARY KEY(${table.fields
.filter((f) => f.primary)
.map((f) => `\`${f.name}\``)
.join(", ")})`
: ""
}\n)${table.comment ? ` COMMENT='${table.comment}'` : ""};\n${`\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX \`${
i.name
}\`\nON \`${table.name}\` (${i.fields
.map((f) => `\`${f}\``)
.join(", ")});`,
)
.join("")}`}`,
)
.join("\n")}\n${diagram.references
.map(
(r) =>
`ALTER TABLE \`${
diagram.tables[r.startTableId].name
}\`\nADD FOREIGN KEY(\`${
diagram.tables[r.startTableId].fields[r.startFieldId].name
}\`) REFERENCES \`${diagram.tables[r.endTableId].name}\`(\`${
diagram.tables[r.endTableId].fields[r.endFieldId].name
}\`)\nON UPDATE ${r.updateConstraint.toUpperCase()} ON DELETE ${r.deleteConstraint.toUpperCase()};`,
)
.join("\n")}`;
}