metis-desk/modules/companies/src/api/infrastructure/persistence/application-configuration-migration.ts
2026-10-10 17:57:05 +02:00

50 lines
1.9 KiB
TypeScript

import type { Sequelize } from "sequelize";
import { DataTypes, QueryTypes } from "sequelize";
import { applicationSnapshot } from "./configuration-snapshots";
export async function migrateApplicationConfigurations(database: Sequelize) {
const q = 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 fk = (table: string) => ({
type: DataTypes.UUID,
allowNull: false,
references: { model: table, key: "id" },
onDelete: "RESTRICT",
});
if (!tables.some((t) => t.name === "application_configurations")) {
await q.createTable("application_configurations", {
id: { type: DataTypes.UUID, primaryKey: true },
companyId: fk("companies"),
...applicationSnapshot.columns,
currentKey: { type: DataTypes.STRING(80), allowNull: true, unique: true },
});
}
if (!tables.some((t) => t.name === "application_configuration_revisions")) {
await q.createTable("application_configuration_revisions", {
id: { type: DataTypes.UUID, primaryKey: true },
configurationId: fk("application_configurations"),
position: { type: DataTypes.INTEGER, allowNull: false },
...applicationSnapshot.columns,
actorId: fk("users"),
recordedAt: { type: DataTypes.STRING(24), allowNull: false },
});
}
const indexes = await database.query<{ name: string }>(
"SELECT DISTINCT INDEX_NAME AS name FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='application_configuration_revisions'",
{ type: QueryTypes.SELECT }
);
if (!indexes.some((item) => item.name === "application_configuration_position")) {
await q.addIndex("application_configuration_revisions", ["configurationId", "position"], {
unique: true,
name: "application_configuration_position",
});
}
}