import type { Sequelize } from "sequelize"; import { DataTypes, QueryTypes } from "sequelize"; import { profileSnapshot } from "./configuration-snapshots"; export async function migrateWorkProfiles(database: Sequelize) { const query = database.getQueryInterface(); const rows = await database.query<{ name: string }>( "SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()", { type: QueryTypes.SELECT } ); const reference = (table: string) => ({ type: DataTypes.UUID, allowNull: false, references: { model: table, key: "id" }, onDelete: "RESTRICT", }); if (!rows.some((row) => row.name === "work_profiles")) { await query.createTable("work_profiles", { id: { type: DataTypes.UUID, primaryKey: true }, companyId: reference("companies"), ...profileSnapshot.columns, currentKey: { type: DataTypes.STRING(110), allowNull: true, unique: true }, }); } if (!rows.some((row) => row.name === "work_profile_revisions")) { await query.createTable("work_profile_revisions", { id: { type: DataTypes.UUID, primaryKey: true }, profileId: reference("work_profiles"), position: { type: DataTypes.INTEGER, allowNull: false }, actorId: reference("users"), recordedAt: { type: DataTypes.STRING(24), allowNull: false }, ...profileSnapshot.columns, }); } const indexes = await database.query<{ name: string }>( "SELECT DISTINCT INDEX_NAME AS name FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='work_profile_revisions'", { type: QueryTypes.SELECT } ); if (!indexes.some((index) => index.name === "profile_revision_position")) { await query.addIndex("work_profile_revisions", ["profileId", "position"], { unique: true, name: "profile_revision_position", }); } }