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 | 136x 136x 136x 136x 595x 595x 595x 595x 595x 152x 14x 12x 2x 2x 2x 1x 1x 358x 358x 2x 356x 594x 594x 6x 6x 588x 4x 4x 584x 10x 2x 11x 11x 1x 10x 13x 13x 591x 113x 10x 84x 383x 1x 10x 5x 5x 84x 1x 83x 83x 83x 83x 383x 383x 1x 382x 385x 382x 155x | import { SqlCompiler } from '../sql/compile.ts';
import { WhereCompiler } from '../where/where.ts';
import { DdlGuards } from './ddl-guards.ts';
import type { ConstraintOptions } from './ddl-types.ts';
import { IndexElementDdl } from './index-element-ddl.ts';
import { SqlLiteral, type TableName } from './sql-literal.ts';
const guards = new DdlGuards();
const elements = new IndexElementDdl();
const identity = new WhereCompiler({ resolve: (field) => ({ field }) });
const sqlLiteral = new SqlLiteral();
/**
* `ALTER TABLE ... ADD CONSTRAINT` statements (check, unique, primary, foreign key and exclusion constraints).
*
* @internal
*/
export class ConstraintDdl {
/**
* `ALTER TABLE ... ADD CONSTRAINT` statement.
*
* @param table - Table name or `{ tableName, schema }`.
* @param options - Constraint definition.
* @param defaultSchema - Schema used when a table reference has none.
* @returns Statement.
* @throws Error for an unknown constraint type, a foreign key without references, an `exclude`
* without elements or a `notValid` on a constraint that cannot be `NOT VALID`.
*/
addConstraintSql(table: TableName, options: ConstraintOptions, defaultSchema?: string): string {
const type = options.type.toLowerCase();
const name = options.name ?? this.#defaultName(table, this.#nameFields(type, options), type);
const fields = this.#fieldList(type, options);
const body = this.#body(type, fields, options, defaultSchema);
return `ALTER TABLE ${sqlLiteral.quoteTable(table, defaultSchema)} ADD CONSTRAINT ${SqlCompiler.quoteIdent(name)} ${body}${this.#attributes(type, options)}`;
}
/**
* `ALTER TABLE ... VALIDATE CONSTRAINT` statement.
*
* @param table - Table name or `{ tableName, schema }`.
* @param name - Constraint name.
* @param defaultSchema - Schema used when the table reference has none.
* @returns Statement.
*/
validateConstraintSql(table: TableName, name: string, defaultSchema?: string): string {
return `ALTER TABLE ${sqlLiteral.quoteTable(table, defaultSchema)} VALIDATE CONSTRAINT ${SqlCompiler.quoteIdent(name)}`;
}
#nameFields(type: string, options: ConstraintOptions): readonly string[] {
if (type !== 'exclude') {
return options.fields ?? [];
}
return (options.exclude ?? []).map((element) => {
const name = element.name;
if (name === undefined) {
throw new Error('An exclusion constraint on an expression requires an explicit name');
}
return name;
});
}
#attributes(type: string, options: ConstraintOptions): string {
const checkable = type === 'check' || type === 'foreign key';
if ((options.notValid === true || options.enforced === false) && !checkable) {
throw new Error('notValid and enforced apply to check and foreign key constraints only');
}
return `${options.enforced === false ? ' NOT ENFORCED' : ''}${options.notValid === true ? ' NOT VALID' : ''}`;
}
#fieldList(type: string, options: ConstraintOptions): string {
const names = (options.fields ?? []).map(SqlCompiler.quoteIdent);
if (options.withoutOverlaps === true) {
this.#requireType(type, ['unique', 'primary key'], 'withoutOverlaps');
return this.#withLast(names, (last) => `${last} WITHOUT OVERLAPS`);
}
if (options.period === true) {
this.#requireType(type, ['foreign key'], 'period');
return this.#withLast(names, (last) => `PERIOD ${last}`);
}
return names.join(', ');
}
#requireType(type: string, allowed: readonly string[], option: string): void {
if (!allowed.includes(type)) {
throw new Error(`${option} applies to ${allowed.join(' and ')} constraints only`);
}
}
#withLast(names: readonly string[], mark: (last: string) => string): string {
const last = names.at(-1);
if (last === undefined) {
throw new Error('withoutOverlaps and period need at least one field');
}
return [...names.slice(0, -1), mark(last)].join(', ');
}
#defaultName(table: TableName, fields: readonly string[], type: string): string {
const suffix = type
.replace(' ', '_')
.replace('primary_key', 'pk')
.replace('foreign_key', 'fkey')
.replace('check', 'ck')
.replace('unique', 'uk')
.replace('exclude', 'excl');
return `${sqlLiteral.tableParts(table).name}_${fields.join('_')}_${suffix}`;
}
#body(
type: string,
fields: string,
options: ConstraintOptions,
defaultSchema: string | undefined,
): string {
switch (type) {
case 'check':
return `CHECK (${sqlLiteral.inlineExpr(identity.compile(options.where))})`;
case 'unique':
case 'primary key':
return this.#key(type, fields, options);
case 'foreign key':
return this.#foreignKey(fields, options, defaultSchema);
case 'exclude':
return this.#exclude(options);
default:
throw new Error(`Constraint type must be specified through options.type: ${options.type}`);
}
}
#key(type: string, fields: string, options: ConstraintOptions): string {
if (type === 'primary key') {
return `PRIMARY KEY (${fields})`;
}
return `UNIQUE${options.nullsNotDistinct === true ? ' NULLS NOT DISTINCT' : ''} (${fields})`;
}
#foreignKey(
fields: string,
options: ConstraintOptions,
defaultSchema: string | undefined,
): string {
if (options.references === undefined) {
throw new Error('Foreign key constraint requires references');
}
const target = `FOREIGN KEY (${fields}) REFERENCES ${sqlLiteral.quoteTable(options.references.table, defaultSchema)} (${this.#referenced(options.references, options.period === true)})`;
return `${target}${guards.foreignKeySuffix(options.onDelete, options.onUpdate, options.deferrable)}`;
}
#referenced(references: NonNullable<ConstraintOptions['references']>, period: boolean): string {
const names = (references.fields ?? [references.field]).map(SqlCompiler.quoteIdent);
return period ? this.#withLast(names, (last) => `PERIOD ${last}`) : names.join(', ');
}
#exclude(options: ConstraintOptions): string {
const items = options.exclude ?? [];
if (items.length === 0) {
throw new Error('Exclusion constraint requires exclude elements');
}
const list = items
.map((item) => `${elements.elementSql(item, undefined)} WITH ${guards.operator(item.with)}`)
.join(', ');
return [
'EXCLUDE',
options.using === undefined ? '' : ` USING ${guards.word(options.using, 'index method')}`,
` (${list})`,
this.#excludeTail(options),
].join('');
}
#excludeTail(options: ConstraintOptions): string {
return [
options.include === undefined || options.include.length === 0
? ''
: ` INCLUDE (${options.include.map(SqlCompiler.quoteIdent).join(', ')})`,
options.where === undefined
? ''
: ` WHERE (${sqlLiteral.inlineExpr(identity.compile(options.where))})`,
options.deferrable === undefined ? '' : ` ${guards.deferrableSql(options.deferrable)}`,
].join('');
}
}
|