33 lines
1.5 KiB
JavaScript
33 lines
1.5 KiB
JavaScript
import { sqlQuoteIdent as q } from "../../utils/sql-safe";
|
|
import buildColumnDefinition from "./build-column-definition";
|
|
import buildForeignKeyConstraint from "./build-foreign-key-constraint";
|
|
import resolveTable from "./resolve-table";
|
|
/**
|
|
* Build the `CREATE TABLE` (or `CREATE VIRTUAL TABLE`) statement for a table
|
|
*/
|
|
export default function buildCreateTableSql({ db_schema, table }) {
|
|
const new_table = resolveTable({ table, db_schema });
|
|
const columns = [];
|
|
const foreignKeys = [];
|
|
for (const field of new_table.fields) {
|
|
columns.push(buildColumnDefinition(field, new_table.isVector));
|
|
if (field.foreignKey && !new_table.isVector) {
|
|
foreignKeys.push(buildForeignKeyConstraint(field));
|
|
}
|
|
}
|
|
// Add unique constraints
|
|
for (const constraint of new_table.uniqueConstraints || []) {
|
|
if (!constraint.constraintTableFields?.length)
|
|
continue;
|
|
const fieldNames = constraint.constraintTableFields.map((f) => String(f.value));
|
|
const constraintName = constraint.constraintName || `unique_${fieldNames.join(", ")}`;
|
|
columns.push(`CONSTRAINT ${q(constraintName)} UNIQUE (${fieldNames
|
|
.map(q)
|
|
.join(", ")})`);
|
|
}
|
|
const allConstraints = [...columns, ...foreignKeys];
|
|
return new_table.isVector
|
|
? `CREATE VIRTUAL TABLE ${q(new_table.tableName)} USING ${new_table.vectorType || "vec0"}(${allConstraints.join(", ")})`
|
|
: `CREATE TABLE ${q(new_table.tableName)} (${allConstraints.join(", ")})`;
|
|
}
|