Sync shared snapshot from df68167
This commit is contained in:
1 parent
588ef139a6
commit
06efc832ca
79 files changed
+10035
-3
No files matched your search
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 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]);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user