-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-initial-migration.ts
More file actions
44 lines (42 loc) · 1.42 KB
/
create-initial-migration.ts
File metadata and controls
44 lines (42 loc) · 1.42 KB
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
import { EOL } from "node:os";
import type { RelationalTable } from "../create-relational-structure";
import { getForeignKeys, getPrimaryKeys } from "../create-relational-structure";
import { getFullTableName } from "../utils";
import { getFieldType } from "./get-field-type";
export function createInitialMigration({
tables,
schemaName,
}: {
tables: RelationalTable[];
schemaName?: string | undefined;
}): string {
return tables
.map((table) => {
const foreignKeys = getForeignKeys(table);
return [
`CREATE TABLE ${getFullTableName({ tableName: table.name, schemaName })} (`,
[
...table.fields.map(
(field) =>
` ${field.key} ${getFieldType(field)}${field.isNullable ? "" : " NOT NULL"}`,
),
` PRIMARY KEY (${getPrimaryKeys(table).join(", ")})`,
...(foreignKeys.length
? foreignKeys.map(
({ key, reference }) =>
` FOREIGN KEY (${key}) REFERENCES ${getFullTableName({ tableName: reference.table, schemaName })} (${reference.key})`,
)
: []),
].join(`,${EOL}`),
`);`,
...foreignKeys.map(
({ key }) =>
`CREATE INDEX idx_${table.name}_${key} ON ${getFullTableName({
tableName: table.name,
schemaName,
})} (${key});`,
),
].join(EOL);
})
.join(`${EOL}${EOL}`);
}