import { z } from "zod"; import { type ModuleId, moduleIdSchema } from "./identifiers.js"; export const POSTGRES_IDENTIFIER_MAX_LENGTH = 63; export const moduleTableLocalNameSchema = z .string() .min(1) .regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u, "Must be a lowercase snake-case table name."); export const physicalModuleTableNameSchema = moduleTableLocalNameSchema.max( POSTGRES_IDENTIFIER_MAX_LENGTH, `Must not exceed ${POSTGRES_IDENTIFIER_MAX_LENGTH} characters.`, ); export function moduleTableNamespace(moduleId: ModuleId): string { return moduleIdSchema.parse(moduleId).replaceAll("-", "_"); } export function moduleTablePrefix(moduleId: ModuleId): string { return `${moduleTableNamespace(moduleId)}_`; } export function moduleTableName(moduleId: ModuleId, localName: string): string { const parsedLocalName = moduleTableLocalNameSchema.parse(localName); const tableName = `${moduleTablePrefix(moduleId)}${parsedLocalName}`; if (!physicalModuleTableNameSchema.safeParse(tableName).success) { throw new RangeError("The namespaced PostgreSQL table name is invalid or too long."); } return tableName; }