[+] Completed lab 4
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readdir, readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { db, transaction } from './repositories/postgres';
|
||||
|
||||
async function migrate(): Promise<void> {
|
||||
const directory = join(__dirname, '..', 'migrations');
|
||||
const files = (await readdir(directory)).filter((name) => /^\d{3}_.+\.sql$/.test(name)).sort();
|
||||
if (files.length === 0) throw new Error('No migrations found');
|
||||
|
||||
await transaction(async (client) => {
|
||||
await client.query('SELECT pg_advisory_xact_lock(20261116, 1)');
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
`);
|
||||
for (const version of files) {
|
||||
const sql = await readFile(join(directory, version), 'utf8');
|
||||
const checksum = createHash('sha256').update(sql).digest('hex');
|
||||
const previous = await client.query<{ checksum: string }>(
|
||||
'SELECT checksum FROM schema_migrations WHERE version = $1', [version],
|
||||
);
|
||||
if (previous.rows[0]) {
|
||||
if (previous.rows[0].checksum !== checksum) throw new Error(`Migration changed: ${version}`);
|
||||
continue;
|
||||
}
|
||||
await client.query(sql);
|
||||
await client.query(
|
||||
'INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)', [version, checksum],
|
||||
);
|
||||
console.log(`Applied ${version}`);
|
||||
}
|
||||
});
|
||||
console.log('Migrations up to date');
|
||||
}
|
||||
|
||||
migrate().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : 'Migration failed');
|
||||
process.exitCode = 1;
|
||||
}).finally(() => db.end());
|
||||
Reference in New Issue
Block a user