74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
import type { BUN_MARIADB_FieldSchemaType } from "../../types";
|
|
import isVectorField from "./is-vector-field";
|
|
import mapDataType from "./map-data-types";
|
|
import MariaDBQuoteGen from "./mariadb-quote-gen";
|
|
|
|
export type BuildColumnDefinitionOptions = {
|
|
/** UNIQUE is managed by syncUniqueConstraints on existing tables */
|
|
omitUnique?: boolean;
|
|
};
|
|
|
|
export default function buildColumnDefinition(
|
|
field: BUN_MARIADB_FieldSchemaType,
|
|
options: BuildColumnDefinitionOptions = {},
|
|
): string {
|
|
if (!field.fieldName) {
|
|
throw new Error("Field name is required");
|
|
}
|
|
|
|
const parts: string[] = [MariaDBQuoteGen(field.fieldName)];
|
|
parts.push(mapDataType(field));
|
|
|
|
if (field.autoIncrement) {
|
|
parts.push("AUTO_INCREMENT");
|
|
}
|
|
|
|
// Vector columns used in VECTOR INDEX must be NOT NULL
|
|
if (
|
|
field.notNullValue ||
|
|
field.primaryKey ||
|
|
isVectorField(field)
|
|
) {
|
|
if (!field.primaryKey) {
|
|
parts.push("NOT NULL");
|
|
}
|
|
}
|
|
|
|
// VECTOR columns cannot be UNIQUE in the usual sense
|
|
if (
|
|
!options.omitUnique &&
|
|
field.unique &&
|
|
!field.primaryKey &&
|
|
!isVectorField(field)
|
|
) {
|
|
parts.push("UNIQUE");
|
|
}
|
|
|
|
if (field.defaultValue !== undefined) {
|
|
if (typeof field.defaultValue === "string") {
|
|
parts.push(`DEFAULT '${field.defaultValue.replace(/'/g, "''")}'`);
|
|
} else {
|
|
parts.push(`DEFAULT ${field.defaultValue}`);
|
|
}
|
|
} else if (field.defaultValueLiteral) {
|
|
parts.push(`DEFAULT ${field.defaultValueLiteral}`);
|
|
}
|
|
|
|
if (field.onUpdate) {
|
|
parts.push(`ON UPDATE ${field.onUpdate}`);
|
|
} else if (field.onUpdateLiteral) {
|
|
parts.push(`ON UPDATE ${field.onUpdateLiteral}`);
|
|
}
|
|
|
|
return parts.join(" ");
|
|
}
|
|
|
|
/** Whether schema field requires NOT NULL */
|
|
export function fieldRequiresNotNull(
|
|
field: BUN_MARIADB_FieldSchemaType,
|
|
): boolean {
|
|
return Boolean(
|
|
field.notNullValue || field.primaryKey || isVectorField(field),
|
|
);
|
|
}
|