-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathpostgres.js
89 lines (85 loc) · 3.12 KB
/
postgres.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { exportFieldComment, parseDefault } from "./shared";
import { dbToTypes } from "../../data/datatypes";
export function toPostgres(diagram) {
const enumStatements = diagram.enums
.map(
(e) =>
`CREATE TYPE "${e.name}" AS ENUM (\n${e.values.map((v) => `\t'${v}'`).join(",\n")}\n);\n`,
)
.join("\n");
const typeStatements = diagram.types
.map(
(type) =>
`CREATE TYPE ${type.name} AS (\n${type.fields
.map((f) => `\t${f.name} ${f.type}`)
.join(",\n")}\n);\n\n${
type.comment && type.comment.trim() !== ""
? `\nCOMMENT ON TYPE "${type.name}" IS '${type.comment}';\n\n`
: ""
}`,
)
.join("\n");
return `${enumStatements}${enumStatements.trim() !== "" ? `\n${typeStatements}` : typeStatements}${diagram.tables
.map(
(table) =>
`CREATE TABLE "${table.name}" (\n${table.fields
.map(
(field) =>
`${exportFieldComment(field.comment)}\t"${
field.name
}" ${field.type}${
field.size !== undefined && field.size !== ""
? "(" + field.size + ")"
: ""
}${field.isArray ? " ARRAY" : ""}${field.notNull ? " NOT NULL" : ""}${field.unique ? " UNIQUE" : ""}${
field.increment ? " GENERATED BY DEFAULT AS IDENTITY" : ""
}${
field.default.trim() !== ""
? ` DEFAULT ${parseDefault(field, diagram.database)}`
: ""
}${
field.check === "" ||
!dbToTypes[diagram.database][field.type].hasCheck
? ""
: ` CHECK(${field.check})`
}`,
)
.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.trim() !== ""
? `\nCOMMENT ON TABLE "${table.name}" IS '${table.comment}';\n`
: ""
}${table.fields
.map((field) =>
field.comment.trim() !== ""
? `COMMENT ON COLUMN ${table.name}.${field.name} IS '${field.comment}';\n`
: "",
)
.join("")}${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX "${
i.name
}"\nON "${table.name}" (${i.fields
.map((f) => `"${f}"`)
.join(", ")});`,
)
.join("\n")}\n`,
)
.join("\n")}${diagram.references
.map(
(r) =>
`\nALTER 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")}`;
}