Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 16x 24x 24x 52x 8x 8x | 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 ${reference.table} (${reference.key})`,
)
: []),
].join(`,${EOL}`),
`);`,
...foreignKeys.map(
({ key }) =>
`CREATE INDEX idx_${table.name}_${key} ON ${table.name} (${key});`,
),
].join(EOL);
})
.join(`${EOL}${EOL}`);
}
|