immich/server/src/sql-tools/processors/index.processor.ts

75 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-07-03 10:59:17 -04:00
import { Processor } from 'src/sql-tools/types';
2025-04-17 14:41:06 -04:00
export const processIndexes: Processor = (builder, items, config) => {
for (const {
item: { object, options },
} of items.filter((item) => item.type === 'index')) {
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('@Check', object);
continue;
}
table.indexes.push({
2025-07-03 10:59:17 -04:00
name: options.name || builder.asIndexName(table.name, options.columns, options.where),
tableName: table.name,
unique: options.unique ?? false,
expression: options.expression,
using: options.using,
with: options.with,
where: options.where,
columnNames: options.columns,
synchronize: options.synchronize ?? true,
});
}
2025-04-17 14:41:06 -04:00
// column indexes
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 (options.index === false) {
continue;
}
const isIndexRequested =
options.indexName || options.index || (type === 'foreignKeyColumn' && config.createForeignKeyIndexes);
if (!isIndexRequested) {
continue;
}
2025-07-03 10:59:17 -04:00
const indexName = options.indexName || builder.asIndexName(table.name, [column.name]);
2025-04-17 14:41:06 -04:00
const isIndexPresent = table.indexes.some((index) => index.name === indexName);
if (isIndexPresent) {
continue;
}
const isOnlyPrimaryColumn = options.primary && table.columns.filter(({ primary }) => primary === true).length === 1;
if (isOnlyPrimaryColumn) {
// will have an index created by the primary key constraint
continue;
}
table.indexes.push({
name: indexName,
tableName: table.name,
unique: false,
columnNames: [column.name],
synchronize: options.synchronize ?? true,
});
}
};