const sequelize = require("./database"); /** * Lightweight, idempotent schema migrations. * * `sequelize.sync()` runs without `alter`, so new model attributes never reach * existing tables. This adds any column a model defines but the table lacks * (additive only — nothing is dropped) and widens the few columns whose type * changed. Safe to run on every start. */ // [model name, attribute name, expected DB type prefix (from describeTable)] const TYPE_CHANGES = [ ["entry", "certification", "VARCHAR(20)"], ["entry", "last_fetch", "DATETIME"], ["entry", "network_studio", "VARCHAR(100)"], ["network", "name", "VARCHAR(100)"], ]; async function addMissingColumns(queryInterface) { for (const model of Object.values(sequelize.models)) { const table = model.getTableName(); let columns; try { columns = await queryInterface.describeTable(table); } catch { continue; // table not created yet; sync handles it } for (const [name, attribute] of Object.entries(model.rawAttributes)) { const column = attribute.field || name; if (columns[column] || attribute.type?.key === "VIRTUAL") continue; console.log(`[MIGRATION] Adding column ${table}.${column}`); await queryInterface.addColumn(table, column, { type: attribute.type, allowNull: attribute.allowNull !== false, defaultValue: attribute.defaultValue, }); } } } async function applyTypeChanges(queryInterface) { for (const [modelName, attributeName, expectedType] of TYPE_CHANGES) { const model = sequelize.models[modelName]; if (!model) continue; const attribute = model.rawAttributes[attributeName]; const column = attribute.field || attributeName; const table = model.getTableName(); const columns = await queryInterface.describeTable(table); const current = columns[column]?.type?.toUpperCase(); if (!current || current.startsWith(expectedType)) continue; console.log( `[MIGRATION] Changing ${table}.${column} from ${current} to ${expectedType}`, ); await queryInterface.changeColumn(table, column, { type: attribute.type, allowNull: attribute.allowNull !== false, defaultValue: attribute.defaultValue, }); } } async function runMigrations() { const queryInterface = sequelize.getQueryInterface(); await addMissingColumns(queryInterface); await applyTypeChanges(queryInterface); } module.exports = { runMigrations };