Files
errors.bitreport.pt/api/src/plugins/db.ts
T
1sonhadorandPaperclip 4604606033 feat(errors): migrate error-reporting stack from PostgreSQL to MariaDB (BIT-255)
Replace Postgres with MariaDB 11 in docker-compose; convert all
database/error_reporting and db/migrations SQL to InnoDB-friendly syntax
(DATETIME(6), AUTO_INCREMENT, ON DUPLICATE KEY). Run admin portal DDL in the
same migrate one-shot as error_reporting.

Switch ingest-api, collector-worker, and api from pg to mysql2 (pools,
parameterized queries, transactions). Align ingest writes with
er_incident_occurrences and include project_id on idempotency inserts.

Add scripts/run-mysql-migrations.sh for host-side applies; update LXC
run-migrate/verify, deployment docs, and .env.example (mysql://, ER_MYSQL_*).

Verified: npm run build + npm test in ingest-api and collector-worker;
npm run build in api. Full docker compose not run here (no local daemon).

Co-Authored-By: Paperclip <[email protected]>
2026-03-22 19:29:11 +00:00

43 lines
1.1 KiB
TypeScript

/**
* MariaDB / MySQL connection pool plugin.
* Decorates app with app.db (mysql2 Pool).
* Env: DATABASE_URL (mysql://user:pass@host:port/db) or discrete DB_* vars.
*/
import fp from 'fastify-plugin';
import mysql, { type Pool } from 'mysql2/promise';
import type { FastifyInstance } from 'fastify';
declare module 'fastify' {
interface FastifyInstance {
db: Pool;
}
}
export default fp(async function dbPlugin(app: FastifyInstance) {
const _url = process.env.DATABASE_URL;
if (typeof _url !== 'string' || _url.trim() === '') {
throw new Error('DATABASE_URL is required');
}
const pool = mysql.createPool({
uri: _url.trim(),
connectionLimit: parseInt(process.env.DB_POOL_MAX ?? '10', 10),
waitForConnections: true,
enableKeepAlive: true,
});
const client = await pool.getConnection();
try {
await client.query('SELECT 1');
app.log.info('MariaDB connected');
} finally {
client.release();
}
app.decorate('db', pool);
app.addHook('onClose', async () => {
await pool.end();
app.log.info('MariaDB pool closed');
});
}, { name: 'db' });