metis-desk/modules/resources/src/api/infrastructure/persistence/resource.model.ts

61 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-10-10 11:32:40 +00:00
import type { Sequelize } from "sequelize";
import { DataTypes, QueryTypes } from "sequelize";
2026-10-10 10:01:58 +00:00
2026-10-10 11:32:40 +00:00
import {
inventoryColumns,
normalizeResourceInventory,
specificationColumns,
} from "./resource-normalization-migration";
2026-10-10 10:01:58 +00:00
2026-10-05 11:13:51 +00:00
const id = { type: DataTypes.UUID, primaryKey: true };
2026-10-10 10:01:58 +00:00
2026-10-05 11:13:51 +00:00
const fk = (model: string) => ({
type: DataTypes.UUID,
allowNull: false,
references: { model, key: "id" },
onDelete: "RESTRICT",
});
2026-10-10 10:01:58 +00:00
2026-10-05 11:13:51 +00:00
export async function migrateInventory(database: Sequelize) {
const query = database.getQueryInterface();
const tables = await database.query<{ name: string }>(
"SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()",
{ type: QueryTypes.SELECT }
);
const resource = {
id,
companyId: fk("companies"),
templateId: fk("resource_definitions"),
2026-10-10 11:32:40 +00:00
...inventoryColumns,
...specificationColumns,
2026-10-05 11:13:51 +00:00
};
const revision = {
id,
resourceId: fk("resources"),
actorId: fk("users"),
recordedAt: { type: DataTypes.STRING(30), allowNull: false },
2026-10-10 11:32:40 +00:00
...inventoryColumns,
templateId: fk("resource_definitions"),
2026-10-05 11:13:51 +00:00
position: { type: DataTypes.INTEGER, allowNull: false },
};
2026-10-10 10:01:58 +00:00
2026-10-05 11:13:51 +00:00
if (!tables.some((table) => table.name === "resources")) {
await query.createTable("resources", resource);
}
if (!tables.some((table) => table.name === "resource_revisions")) {
await query.createTable("resource_revisions", revision);
}
const indexes = await database.query<{ name: string }>(
"SELECT DISTINCT INDEX_NAME AS name FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='resource_revisions'",
{ type: QueryTypes.SELECT }
);
2026-10-10 10:01:58 +00:00
2026-10-05 11:13:51 +00:00
if (!indexes.some((index) => index.name === "resource_revision_position_unique")) {
await query.addIndex("resource_revisions", ["resourceId", "position"], {
unique: true,
name: "resource_revision_position_unique",
});
}
2026-10-10 11:32:40 +00:00
await normalizeResourceInventory(database);
2026-10-05 11:13:51 +00:00
}