66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
import type {
|
|
BUN_MARIADB_TableSchemaType,
|
|
BunMariaDBConfig,
|
|
} from "../../types";
|
|
import buildColumnDefinition from "./build-column-definition";
|
|
import buildTableOptions from "./build-table-options";
|
|
import MariaDBQuoteGen from "./mariadb-quote-gen";
|
|
import runSchemaQuery from "./run-schema-query";
|
|
|
|
export default async function createTable({
|
|
table,
|
|
config,
|
|
}: {
|
|
table: BUN_MARIADB_TableSchemaType;
|
|
config?: BunMariaDBConfig;
|
|
}): Promise<void> {
|
|
if (!table.tableName.match(/_temp_\d+$/)) {
|
|
console.log(`Creating table: ${table.tableName}`);
|
|
}
|
|
|
|
const columnDefinitions: string[] = [];
|
|
const primaryKeys: string[] = [];
|
|
|
|
for (const field of table.fields || []) {
|
|
columnDefinitions.push(buildColumnDefinition(field));
|
|
|
|
if (field.primaryKey && field.fieldName) {
|
|
primaryKeys.push(field.fieldName);
|
|
}
|
|
}
|
|
|
|
if (primaryKeys.length > 0) {
|
|
const pkCols = primaryKeys.map((k) => MariaDBQuoteGen(k)).join(", ");
|
|
columnDefinitions.push(`PRIMARY KEY (${pkCols})`);
|
|
}
|
|
|
|
if (table.uniqueConstraints) {
|
|
for (const constraint of table.uniqueConstraints) {
|
|
const columns = (constraint.constraintTableFields || [])
|
|
.map((field) => field.value)
|
|
.filter((value): value is string => Boolean(value));
|
|
|
|
if (columns.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
const fields = columns.map((col) => MariaDBQuoteGen(col)).join(", ");
|
|
const constraintName =
|
|
constraint.constraintName || `unique_${columns.join("_")}`;
|
|
|
|
columnDefinitions.push(
|
|
`CONSTRAINT ${MariaDBQuoteGen(constraintName)} UNIQUE (${fields})`,
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Foreign keys are not declared inline. `handleDBSchemaTables` adds them
|
|
* with `ensureForeignKeys` once every table exists, so forward references,
|
|
* self references and FK cycles all work regardless of table order.
|
|
*/
|
|
const sql = `CREATE TABLE IF NOT EXISTS ${MariaDBQuoteGen(table.tableName)} (${columnDefinitions.join(", ")})${buildTableOptions(table)}`;
|
|
|
|
await runSchemaQuery({ query: sql, config });
|
|
}
|