import { tableKey, type DbColumn, type DbTable } from '../db/model' import type { TableDdl } from './table-ddl' const ident = (name: string) => `"${name.replaceAll('"', '""')}"` const qualified = (table: Pick) => `${ident(table.schema)}.${ident(table.name)}` const identity = (column: DbColumn) => (column.identityAlways ? ' generated always as identity' : ' generated by default as identity') const columnSql = (table: DbTable, column: DbColumn) => { // A table users add never has one, and its expression and kind (stored or virtual) are not read. if (column.generated) throw new Error(`${tableKey(table)}.${column.name} is a generated column, which eject does not write: Not implemented`) const kept = column.identity ? identity(column) : `${column.defaultExpr === undefined ? '' : ` default ${column.defaultExpr}`}${column.notNull ? ' not null' : ''}` return ` ${ident(column.name)} ${column.formatted}${kept}` } // `CREATE INDEX name ON ...`, as pg_get_indexdef writes it, made to leave an index of that name alone. const ifNotExists = (definition: string) => { // The name is quoted when it is not a plain lowercase identifier, and may then hold spaces. const statement = /^CREATE (UNIQUE )?INDEX ("(?:[^"]|"")*"|\S+) ON / if (!statement.test(definition)) throw new Error(`Unexpected index definition: ${definition}`) return definition.replace(statement, (_, unique: string | undefined, name: string) => `create ${unique ? 'unique ' : ''}index if not exists ${name} on `) } const trigramIndex = /\b(gin|gist)_trgm_ops\b/ /** * The statements that make `table` as the catalogue has it, each a no-op where it is already there: its schema, the * pg_trgm extension when an index needs it, the table with its columns and constraints, then its indexes. On the * database it was read from they change nothing; on an empty one they make the table again, without its rows. */ export const tableMigration = (table: DbTable, ddl: TableDdl) => { const body = [ ...table.columns.map((column) => columnSql(table, column)), ...ddl.constraints.map(({ name, definition }) => ` constraint ${ident(name)} ${definition}`), ] return [ `create schema if not exists ${ident(table.schema)}`, ...(ddl.indexes.some((index) => trigramIndex.test(index)) ? ['create extension if not exists pg_trgm'] : []), `create table if not exists ${qualified(table)} (\n${body.join(',\n')}\n)`, ...ddl.indexes.map(ifNotExists), ].map((statement) => `${statement};`) }