Files
immich/server/src/sql-tools/processors/unique-constraint.processor.ts

56 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-04-17 14:41:06 -04:00
import { asKey } from 'src/sql-tools/helpers';
2025-07-03 10:59:17 -04:00
import { ConstraintType, Processor } from 'src/sql-tools/types';
export const processUniqueConstraints: Processor = (builder, items) => {
for (const {
item: { object, options },
} of items.filter((item) => item.type === 'uniqueConstraint')) {
2025-07-03 10:59:17 -04:00
const table = builder.getTableByObject(object);
if (!table) {
2025-07-03 10:59:17 -04:00
builder.warnMissingTable('@Unique', object);
continue;
}
const tableName = table.name;
const columnNames = options.columns;
table.constraints.push({
2025-07-03 10:59:17 -04:00
type: ConstraintType.UNIQUE,
name: options.name || asUniqueConstraintName(tableName, columnNames),
tableName,
columnNames,
synchronize: options.synchronize ?? true,
});
}
2025-04-17 14:41:06 -04:00
// column level constraints
for (const {
type,
item: { object, propertyName, options },
} of items.filter((item) => item.type === 'column' || item.type === 'foreignKeyColumn')) {
2025-07-03 10:59:17 -04:00
const { table, column } = builder.getColumnByObjectAndPropertyName(object, propertyName);
2025-04-17 14:41:06 -04:00
if (!table) {
2025-07-03 10:59:17 -04:00
builder.warnMissingTable('@Column', object);
2025-04-17 14:41:06 -04:00
continue;
}
if (!column) {
// should be impossible since they are created in `column.processor.ts`
2025-07-03 10:59:17 -04:00
builder.warnMissingColumn('@Column', object, propertyName);
2025-04-17 14:41:06 -04:00
continue;
}
if (type === 'column' && !options.primary && (options.unique || options.uniqueConstraintName)) {
table.constraints.push({
2025-07-03 10:59:17 -04:00
type: ConstraintType.UNIQUE,
2025-04-17 14:41:06 -04:00
name: options.uniqueConstraintName || asUniqueConstraintName(table.name, [column.name]),
tableName: table.name,
columnNames: [column.name],
synchronize: options.synchronize ?? true,
});
}
}
};
2025-04-17 14:41:06 -04:00
const asUniqueConstraintName = (table: string, columns: string[]) => asKey('UQ_', table, columns);