42 lines
1.5 KiB
JavaScript
42 lines
1.5 KiB
JavaScript
/**
|
|||
|
|
* Apply ordered SQL migrations using the shared Database transaction wrapper.
|
||
|
|
* Each migration is { id: string, up: async (client) => void }.
|
||
|
|
*/
|
||
|
|
export async function runMigrations(
|
||
|
|
database,
|
||
|
|
migrations,
|
||
|
|
{ lockKey = 70420320, tableName = 'schema_migrations' } = {}
|
||
|
|
) {
|
||
|
|
if (!database || typeof database.transaction !== 'function') {
|
||
|
|
throw new TypeError('runMigrations requires a Database-like transaction object');
|
||
|
|
}
|
||
|
|
if (!Array.isArray(migrations)) throw new TypeError('migrations must be an array');
|
||
|
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tableName)) {
|
||
|
|
throw new TypeError('migration tableName must be a simple SQL identifier');
|
||
|
|
}
|
||
|
|
const table = `"${tableName}"`;
|
||
|
|
|
||
|
|
const ordered = [...migrations].sort((left, right) => String(left.id).localeCompare(String(right.id)));
|
||
|
|
await database.transaction(async client => {
|
||
|
|
await client.query('SELECT pg_advisory_xact_lock($1)', [lockKey]);
|
||
|
|
await client.query(`
|
||
|
|
CREATE TABLE IF NOT EXISTS ${table} (
|
||
|
|
id TEXT PRIMARY KEY,
|
||
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||
|
|
)
|
||
|
|
`);
|
||
|
|
|
||
|
|
for (const migration of ordered) {
|
||
|
|
if (!migration?.id || typeof migration.up !== 'function') {
|
||
|
|
throw new TypeError('each migration requires an id and up(client) function');
|
||
|
|
}
|
||
|
|
const existing = await client.query(
|
||
|
|
`SELECT 1 FROM ${table} WHERE id = $1`,
|
||
|
|
[migration.id]
|
||
|
|
);
|
||
|
|
if (existing.rowCount > 0) continue;
|
||
|
|
await migration.up(client);
|
||
|
|
await client.query(`INSERT INTO ${table} (id) VALUES ($1)`, [migration.id]);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|