2026-10-08 14:43:34 +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 { applicationSnapshot } from "./configuration-snapshots" ;
2026-10-06 15:15:42 +00:00
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 }
) ;
2026-10-10 10:01:58 +00:00
2026-10-06 15:15:42 +00:00
const fk = ( table : string ) = > ( {
type : DataTypes . UUID ,
allowNull : false ,
references : { model : table , key : "id" } ,
onDelete : "RESTRICT" ,
} ) ;
2026-10-10 10:01:58 +00:00
2026-10-06 15:15:42 +00:00
if ( ! tables . some ( ( t ) = > t . name === "application_configurations" ) ) {
await q . createTable ( "application_configurations" , {
id : { type : DataTypes . UUID , primaryKey : true } ,
companyId : fk ( "companies" ) ,
2026-10-10 11:32:40 +00:00
. . . applicationSnapshot . columns ,
2026-10-06 15:15:42 +00:00
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 } ,
2026-10-10 11:32:40 +00:00
. . . applicationSnapshot . columns ,
2026-10-06 15:15:42 +00:00
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 }
) ;
2026-10-10 10:01:58 +00:00
2026-10-06 15:15:42 +00:00
if ( ! indexes . some ( ( item ) = > item . name === "application_configuration_position" ) ) {
await q . addIndex ( "application_configuration_revisions" , [ "configurationId" , "position" ] , {
unique : true ,
name : "application_configuration_position" ,
} ) ;
}
}