46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
import { readdir, readFile } from 'node:fs/promises'
|
|
import { dirname, resolve } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { PGlite } from '@electric-sql/pglite'
|
|
import { Pool } from 'pg'
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const migrationsDir = resolve(__dirname, '../src/migrations')
|
|
|
|
function createSchemaName() {
|
|
return `ca_test_${Date.now()}_${Math.random().toString(16).slice(2)}`
|
|
}
|
|
|
|
export async function createTestDb() {
|
|
const postgresUrl = process.env.CA_STUDIO_TEST_DATABASE_URL
|
|
const migrationFiles = (await readdir(migrationsDir))
|
|
.filter((file) => file.endsWith('.sql'))
|
|
.sort()
|
|
const migrationSql = await Promise.all(
|
|
migrationFiles.map(async (file) => readFile(resolve(migrationsDir, file), 'utf8'))
|
|
)
|
|
|
|
if (postgresUrl) {
|
|
const schema = createSchemaName()
|
|
const bootstrapPool = new Pool({ connectionString: postgresUrl })
|
|
await bootstrapPool.query(`CREATE SCHEMA "${schema}"`)
|
|
await bootstrapPool.end()
|
|
|
|
const pool = new Pool({
|
|
connectionString: postgresUrl,
|
|
options: `-c search_path=${schema},public`,
|
|
allowExitOnIdle: true
|
|
})
|
|
for (const sql of migrationSql) {
|
|
await pool.query(sql)
|
|
}
|
|
return pool
|
|
}
|
|
|
|
const db = new PGlite()
|
|
for (const sql of migrationSql) {
|
|
await db.exec(sql)
|
|
}
|
|
return db
|
|
}
|