forked from mtusi2026/mtusi2026lab7
45 lines
2.4 KiB
JavaScript
45 lines
2.4 KiB
JavaScript
'use strict';
|
|
const { readFileSync, readdirSync } = require('node:fs');
|
|
const path = require('node:path');
|
|
const { createHash, randomBytes } = require('node:crypto');
|
|
const { pool } = require('./db');
|
|
async function migrate() {
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query('SELECT pg_advisory_lock(202602)');
|
|
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations
|
|
(version text PRIMARY KEY, checksum text NOT NULL)`);
|
|
const dir = path.join(__dirname, '..', 'migrations');
|
|
for (const version of readdirSync(dir).filter(f => /^\d+.*\.sql$/.test(f)).sort()) {
|
|
const sql = readFileSync(path.join(dir, version), 'utf8').replace(/\r\n/g, '\n');
|
|
const checksum = createHash('sha256').update(sql).digest('hex');
|
|
const existing = await client.query('SELECT checksum FROM schema_migrations WHERE version=$1', [version]);
|
|
if (existing.rowCount) {
|
|
// Git may normalize Windows line endings; accept only equivalent LF/CRLF text.
|
|
const windowsChecksum = createHash('sha256').update(sql.replace(/\n/g, '\r\n')).digest('hex');
|
|
if (![checksum, windowsChecksum].includes(existing.rows[0].checksum)) throw new Error('Migration checksum mismatch');
|
|
continue;
|
|
}
|
|
await client.query('BEGIN');
|
|
try {
|
|
await client.query(sql);
|
|
await client.query('INSERT INTO schema_migrations VALUES ($1,$2)', [version, checksum]);
|
|
await client.query('COMMIT');
|
|
} catch (error) { await client.query('ROLLBACK'); throw error; }
|
|
console.log('Applied migration ' + version);
|
|
}
|
|
await client.query(`INSERT INTO app_settings VALUES ('cursor_secret',$1) ON CONFLICT DO NOTHING`, [randomBytes(32).toString('hex')]);
|
|
await client.query(`GRANT CONNECT ON DATABASE messenger TO api,worker;
|
|
GRANT USAGE ON SCHEMA public TO api,worker;
|
|
GRANT SELECT,INSERT,UPDATE,DELETE ON users,sessions,chats,chat_members,messages,message_requests,message_attachments,attachments,attachment_jobs,login_limits TO api;
|
|
GRANT SELECT ON app_settings TO api;
|
|
GRANT SELECT,UPDATE ON attachments,attachment_jobs TO worker;`);
|
|
} finally {
|
|
await client.query('SELECT pg_advisory_unlock(202602)').catch(() => {});
|
|
client.release();
|
|
}
|
|
}
|
|
module.exports = { migrate };
|
|
if (require.main === module) migrate().then(() => console.log('Migrations up to date'))
|
|
.catch(() => { console.error('Migration failed'); process.exitCode = 1; }).finally(() => pool.end());
|