|
| 1 | +import path from 'node:path'; |
| 2 | +import process from 'node:process'; |
| 3 | +import knex from 'knex'; |
| 4 | + |
| 5 | +const TEMPLATE_DB = 'rocketadmin_test_template'; |
| 6 | +const TEMPLATE_LOCK_ID = 4242424242; |
| 7 | + |
| 8 | +const workerId = process.pid; |
| 9 | +const pgLiteFolderPath = process.env.PGLITE_FOLDER_PATH; |
| 10 | + |
| 11 | +if (pgLiteFolderPath && pgLiteFolderPath.length > 0) { |
| 12 | + process.env.PGLITE_FOLDER_PATH = path.join(pgLiteFolderPath, `worker-${workerId}`); |
| 13 | +} else if (process.env.DATABASE_URL) { |
| 14 | + const url = new URL(process.env.DATABASE_URL); |
| 15 | + const sourceDb = url.pathname.replace(/^\//, '') || 'postgres'; |
| 16 | + const workerDbName = `rocketadmin_test_w${workerId}`; |
| 17 | + const baseConnection = { |
| 18 | + host: url.hostname, |
| 19 | + port: Number.parseInt(url.port, 10) || 5432, |
| 20 | + user: decodeURIComponent(url.username), |
| 21 | + password: decodeURIComponent(url.password), |
| 22 | + }; |
| 23 | + |
| 24 | + const admin = knex({ |
| 25 | + client: 'pg', |
| 26 | + connection: { ...baseConnection, database: 'template1' }, |
| 27 | + }); |
| 28 | + |
| 29 | + try { |
| 30 | + await admin.raw('SELECT pg_advisory_lock(?)', [TEMPLATE_LOCK_ID]); |
| 31 | + try { |
| 32 | + const existing = await admin.raw('SELECT 1 FROM pg_database WHERE datname = ?', [TEMPLATE_DB]); |
| 33 | + if (existing.rows.length === 0) { |
| 34 | + await admin.raw(`CREATE DATABASE "${TEMPLATE_DB}" TEMPLATE "${sourceDb}"`); |
| 35 | + const templateConn = knex({ |
| 36 | + client: 'pg', |
| 37 | + connection: { ...baseConnection, database: TEMPLATE_DB }, |
| 38 | + }); |
| 39 | + try { |
| 40 | + await templateConn.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); |
| 41 | + } finally { |
| 42 | + await templateConn.destroy(); |
| 43 | + } |
| 44 | + await admin.raw('UPDATE pg_database SET datistemplate = TRUE WHERE datname = ?', [TEMPLATE_DB]); |
| 45 | + } |
| 46 | + } finally { |
| 47 | + await admin.raw('SELECT pg_advisory_unlock(?)', [TEMPLATE_LOCK_ID]); |
| 48 | + } |
| 49 | + |
| 50 | + try { |
| 51 | + await admin.raw(`DROP DATABASE IF EXISTS "${workerDbName}" WITH (FORCE)`); |
| 52 | + } catch { |
| 53 | + await admin.raw(`DROP DATABASE IF EXISTS "${workerDbName}"`); |
| 54 | + } |
| 55 | + await admin.raw(`CREATE DATABASE "${workerDbName}" TEMPLATE "${TEMPLATE_DB}"`); |
| 56 | + } finally { |
| 57 | + await admin.destroy(); |
| 58 | + } |
| 59 | + |
| 60 | + url.pathname = `/${workerDbName}`; |
| 61 | + process.env.DATABASE_URL = url.toString(); |
| 62 | +} |
0 commit comments