Files
kooltab-backoffice/apps/api/prisma/deploy.js
T
brammie15 072cda111c
CI / build-and-test (push) Canceled after 0s
feat: do final stress tests
2026-10-24 21:06:06 +02:00

76 lines
2.8 KiB
JavaScript

/**
* Applies database migrations on container start.
*
* Databases created before migrations were used (via `prisma db push`) have no
* `_prisma_migrations` table. Those are brought up to date with a non-destructive
* `db push` (which refuses to drop data) and then baselined, so every later deploy
* can use plain `prisma migrate deploy`.
*/
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const { PrismaClient } = require('@prisma/client');
// Migrations that were first created with dates in the future, renamed to when they were written.
// The SQL is unchanged, so databases that already applied them only need the recorded name updated.
const RENAMED_MIGRATIONS = {
'20261020120000_tab_events': '20261019212336_tab_events',
'20261021120000_stock': '20261020124522_stock',
'20261022120000_server_tabs_and_stock': '20261020141836_server_tabs_and_stock',
'20261023120000_products_on_dashboard': '20261020215540_products_on_dashboard',
'20261024120000_product_images_and_events': '20261021104519_product_images_and_events',
'20261025120000_sold_unit_view': '20261021225808_sold_unit_view',
'20261026120000_drop_tab_snapshots': '20261021233219_drop_tab_snapshots',
};
function run(command) {
console.log(`[deploy] ${command}`);
execSync(command, { stdio: 'inherit' });
}
async function main() {
const prisma = new PrismaClient();
let hasMigrationsTable;
let hasTables;
try {
const [{ migrations, tables }] = await prisma.$queryRaw`
SELECT
to_regclass('public._prisma_migrations') IS NOT NULL AS migrations,
EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public') AS tables`;
hasMigrationsTable = migrations;
hasTables = tables;
if (hasMigrationsTable) {
for (const [oldName, newName] of Object.entries(RENAMED_MIGRATIONS)) {
const renamed = await prisma.$executeRaw`
UPDATE "_prisma_migrations" SET "migration_name" = ${newName} WHERE "migration_name" = ${oldName}`;
if (renamed > 0) console.log(`[deploy] Renamed migration ${oldName} -> ${newName}`);
}
}
} finally {
await prisma.$disconnect();
}
if (!hasMigrationsTable && hasTables) {
console.log('[deploy] Existing database without migration history, baselining');
run('npx prisma db push --skip-generate');
const migrationsDir = path.join(__dirname, 'migrations');
const migrations = fs
.readdirSync(migrationsDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort();
for (const name of migrations) {
run(`npx prisma migrate resolve --applied ${name}`);
}
}
run('npx prisma migrate deploy');
}
main().catch((error) => {
console.error('[deploy] Migration failed:', error);
process.exit(1);
});