Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | 134x 134x 134x 134x 920x 2812x 2811x 5x 2806x 724x 2082x 84x 1998x 1x 1997x 2808x 2808x 2491x 317x 7x 310x 5x 305x 6x 299x 2748x 2748x 2664x 84x 2748x 2748x 2748x 2746x 2729x 61x 724x 2746x 2746x 2746x 2690x 56x 5492x 84x 1x 83x 83x 6x 77x | import { DefaultValueGenerator } from '../data-types/default-value-generator.ts';
import { SqlExpression } from '../expressions/methods.ts';
import type { AttributeDefinition } from '../model/model-definition.ts';
import { SqlCompiler } from '../sql/compile.ts';
import { WhereCompiler } from '../where/where.ts';
import { DdlGuards } from './ddl-guards.ts';
import type { ColumnDefinition, ColumnSqlOptions, DeferrableValue } from './ddl-types.ts';
import type { EnumDdl } from './enum-ddl.ts';
import { SqlLiteral, type TableName } from './sql-literal.ts';
const guards = new DdlGuards();
const noContext = new WhereCompiler({ resolve: () => undefined });
const sqlLiteral = new SqlLiteral();
/** Types whose object defaults are serialized to their text form before escaping. */
const SERIALIZED_DEFAULTS = /^(HSTORE|POINT|LINE|LSEG|BOX|PATH|POLYGON|CIRCLE)$/;
/**
* Column parts of DDL: the SQL type, `DEFAULT`, `REFERENCES`, column definitions and comments.
*
* @internal
*/
export class ColumnDdl {
readonly #enums: EnumDdl;
/**
* @param enums - Enum type names.
*/
constructor(enums: EnumDdl) {
this.#enums = enums;
}
/**
* Converts a normalized attribute to a column definition.
*
* @param attribute - Normalized attribute.
* @returns Column definition.
*/
columnOf(attribute: AttributeDefinition): ColumnDefinition {
return {
name: attribute.fieldName,
field: attribute.field,
type: attribute.type,
allowNull: attribute.allowNull,
primaryKey: attribute.primaryKey === true,
autoIncrement: attribute.autoIncrement === true,
defaultValue: attribute.defaultValue,
unique: attribute.unique,
comment: attribute.comment,
references: attribute.references,
onDelete: attribute.onDelete,
onUpdate: attribute.onUpdate,
identity: attribute.identity,
generated: attribute.generated,
};
}
/**
* SQL type of a column (SERIAL for auto-increment integers, enum type names).
*
* @param table - Table name or `{ tableName, schema }`.
* @param column - Column definition.
* @returns SQL type.
*/
columnType(table: TableName, column: ColumnDefinition): string {
if (column.identity !== undefined) {
return `${column.type.sqlType} GENERATED ${column.identity === 'always' ? 'ALWAYS' : 'BY DEFAULT'} AS IDENTITY`;
}
if (column.autoIncrement) {
return this.#serialType(column);
}
if (column.type.key === 'ENUM') {
return this.#enums.quotedType(table, column.field);
}
if (column.type.key === 'ARRAY' && column.type.subtype?.key === 'ENUM') {
return `${this.#enums.quotedType(table, column.field)}[]`;
}
return column.type.sqlType;
}
/**
* `DEFAULT ...` clause value.
*
* @param column - Column definition.
* @returns SQL of the default, or `undefined` for client-side defaults.
*/
defaultSql(column: ColumnDefinition): string | undefined {
const value = column.defaultValue;
if (value === undefined || column.autoIncrement || column.generated !== undefined) {
return undefined;
}
if (value instanceof DefaultValueGenerator || typeof value === 'function') {
return value instanceof DefaultValueGenerator && value.key === 'NOW' ? 'now()' : undefined;
}
if (value instanceof SqlExpression) {
return sqlLiteral.inlineExpr(noContext.toExpr(value));
}
if (column.type.isJson === true) {
return sqlLiteral.escape(JSON.stringify(value));
}
return sqlLiteral.escape(
SERIALIZED_DEFAULTS.test(column.type.key) ? column.type.serialize?.(value) : value,
);
}
/**
* `REFERENCES ...` clause.
*
* @param column - Column definition.
* @param defaultSchema - Schema of the referenced table when it has none.
* @returns SQL of the clause, or `undefined` without references.
*/
referencesSql(column: ColumnDefinition, defaultSchema?: string): string | undefined {
const references = column.references;
if (references === undefined) {
return undefined;
}
const key = typeof references === 'string' ? 'id' : (references.key ?? 'id');
const deferrable =
typeof references === 'object'
? (references as { deferrable?: DeferrableValue }).deferrable
: undefined;
const target = `REFERENCES ${sqlLiteral.quoteTable(this.#referencedTable(references), defaultSchema)} (${SqlCompiler.quoteIdent(key)})`;
return `${target}${guards.foreignKeySuffix(column.onDelete, column.onUpdate, deferrable)}`;
}
/**
* One column of `CREATE TABLE` / `ADD COLUMN`.
*
* @param table - Table name or `{ tableName, schema }`.
* @param column - Column definition.
* @param options - `inlinePrimaryKey` and the default schema of references.
* @returns Column SQL.
*/
columnSql(table: TableName, column: ColumnDefinition, options: ColumnSqlOptions = {}): string {
return [
`${SqlCompiler.quoteIdent(column.field)} ${this.columnType(table, column)}`,
column.allowNull || column.primaryKey ? '' : ' NOT NULL',
options.inlinePrimaryKey === true && column.primaryKey ? ' PRIMARY KEY' : '',
this.#generatedSql(column),
this.#uniqueSql(column.unique),
this.#prefixed(' DEFAULT ', this.defaultSql(column)),
this.#prefixed(' ', this.referencesSql(column, options.defaultSchema)),
].join('');
}
/**
* `COMMENT ON COLUMN` for a column with a comment.
*
* @param table - Table name or `{ tableName, schema }`.
* @param column - Column name and comment.
* @returns The statement, or nothing without a comment.
*/
commentSql(
table: TableName,
column: Readonly<{ field: string; comment?: string }>,
): readonly string[] {
return column.comment === undefined
? []
: [
`COMMENT ON COLUMN ${sqlLiteral.quoteTable(table)}.${SqlCompiler.quoteIdent(column.field)} IS ${sqlLiteral.escape(column.comment)}`,
];
}
/**
* Whether a `unique` option has `nullsNotDistinct: true`.
*
* @param unique - `unique` option of a column.
* @returns The flag.
*/
nullsNotDistinct(unique: ColumnDefinition['unique']): boolean {
return (
typeof unique === 'object' &&
unique !== null &&
(unique as { nullsNotDistinct?: boolean }).nullsNotDistinct === true
);
}
#serialType(column: ColumnDefinition): string {
return column.type.key === 'BIGINT'
? 'BIGSERIAL'
: column.type.key === 'SMALLINT'
? 'SMALLSERIAL'
: 'SERIAL';
}
#generatedSql(column: ColumnDefinition): string {
return column.generated === undefined
? ''
: ` GENERATED ALWAYS AS (${sqlLiteral.inlineExpr(noContext.toExpr(column.generated.as))}) ${column.generated.stored === false ? 'VIRTUAL' : 'STORED'}`;
}
#uniqueSql(unique: ColumnDefinition['unique']): string {
const unnamed =
unique === true ||
(typeof unique === 'object' && unique !== null && unique.name === undefined);
if (!unnamed) {
return '';
}
return this.nullsNotDistinct(unique) ? ' UNIQUE NULLS NOT DISTINCT' : ' UNIQUE';
}
#prefixed(prefix: string, sql: string | undefined): string {
return sql === undefined ? '' : `${prefix}${sql}`;
}
#referencedTable(references: NonNullable<ColumnDefinition['references']>): TableName {
if (typeof references === 'string') {
return references;
}
const model = references.model;
if (typeof model === 'string') {
return model;
}
return 'getTableName' in model ? model.getTableName() : model;
}
}
|