/** * Before deploying Hub 2.0: checks the database can take the 2.0 migrations, and lists what to * sort out first. Changes nothing. * * npm run check:hub2 * * Works before and after the 2.0 migrations (it reads the tables directly). * - Hub 2.0 allows one licence per product per customer that isn't revoked. Every licence before * 2.0 is an Events licence, so a customer with two open licences stops the migration: revoke * the one that isn't used (its install, if any, stops reporting). */ require('dotenv').config(); const prisma = require('../src/config/db'); async function main() { const columns = await prisma.$queryRaw`SELECT column_name FROM information_schema.columns WHERE table_name = 'Licence' AND column_name = 'product'`; const hasProduct = columns.length > 0; const rows = hasProduct ? await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", l.product::text AS product, count(*)::int AS n, string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId" WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId", l.product HAVING count(*) > 1 ORDER BY c.name`) : await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", 'events' AS product, count(*)::int AS n, string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId" WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId" HAVING count(*) > 1 ORDER BY c.name`); if (!rows.length) { console.log('OK: every customer has at most one open licence per product. Hub 2.0 can be deployed.'); return 0; } console.log('Hub 2.0 allows one open (not revoked) licence per product per customer. Revoke the extra ones first:'); for (const r of rows) console.log(` - ${r.name}: ${r.n} ${r.product} licences: ${r.keys}`); return 1; } main() .then(code => prisma.$disconnect().then(() => process.exit(code))) .catch(async e => { console.error('The check failed:', e.message); await prisma.$disconnect().catch(() => {}); process.exit(2); });