MCPcopy
hub / github.com/drawdb-io/drawdb / toPostgres

Function toPostgres

src/utils/exportSQL/postgres.js:10–130  ·  view source on GitHub ↗
(diagram)

Source from the content-addressed store, hash-verified

8import { dbToTypes } from "../../data/datatypes";
9
10export function toPostgres(diagram) {
11 const enumStatements = diagram.enums
12 .map(
13 (e) =>
14 `CREATE TYPE "${e.name}" AS ENUM (\n${e.values
15 .map((v) => `\t'${v}'`)
16 .join(",\n")}\n);\n`,
17 )
18 .join("\n");
19
20 const typeStatements = diagram.types
21 .map(
22 (type) =>
23 `CREATE TYPE ${type.name} AS (\n${type.fields
24 .map((f) => `\t${f.name} ${f.type}`)
25 .join(",\n")}\n);\n\n${
26 type.comment?.trim()
27 ? `COMMENT ON TYPE "${type.name}" IS '${escapeQuotes(type.comment)}';\n`
28 : ""
29 }`,
30 )
31 .join("\n");
32
33 const tableStatements = diagram.tables
34 .map((table) => {
35 const inheritsClause =
36 Array.isArray(table.inherits) && table.inherits.length > 0
37 ? `\n) INHERITS (${table.inherits.map((parent) => `"${parent}"`).join(", ")})`
38 : "\n)";
39
40 const fieldDefinitions = table.fields
41 .map(
42 (field) =>
43 `${exportFieldComment(field.comment)}\t"${
44 field.name
45 }" ${field.type}${
46 field.size ? `(${field.size})` : ""
47 }${field.isArray ? " ARRAY" : ""}${field.notNull ? " NOT NULL" : ""}${
48 field.unique ? " UNIQUE" : ""
49 }${field.increment ? " GENERATED BY DEFAULT AS IDENTITY" : ""}${
50 field.default?.trim()
51 ? ` DEFAULT ${parseDefault(field, diagram.database)}`
52 : ""
53 }${
54 field.check && dbToTypes[diagram.database][field.type]?.hasCheck
55 ? ` CHECK(${field.check})`
56 : ""
57 }`,
58 )
59 .join(",\n");
60
61 const primaryKeyClause = table.fields.some((f) => f.primary)
62 ? `,\n\tPRIMARY KEY(${table.fields
63 .filter((f) => f.primary)
64 .map((f) => `"${f.name}"`)
65 .join(", ")})`
66 : "";
67

Callers 1

exportSQLFunction · 0.90

Calls 5

escapeQuotesFunction · 0.90
exportFieldCommentFunction · 0.90
parseDefaultFunction · 0.90
uniqueConstraintClauseFunction · 0.90
getFkColumnNamesFunction · 0.90

Tested by

no test coverage detected