47 lines
1.4 KiB
JavaScript
47 lines
1.4 KiB
JavaScript
import { readdir, readFile } from 'node:fs/promises'
|
|
import { dirname, resolve } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { Pool } from 'pg'
|
|
import { loadEnv } from './load-env.mjs'
|
|
|
|
loadEnv()
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const migrationsDir = resolve(__dirname, '../src/migrations')
|
|
const connectionString =
|
|
process.env.DATABASE_URL ?? 'postgres://ca_studio:ca_studio@localhost:54329/ca_studio_test'
|
|
|
|
const pool = new Pool({ connectionString })
|
|
|
|
function redactConnectionString(value) {
|
|
try {
|
|
const url = new URL(value)
|
|
if (url.password) url.password = '***'
|
|
return url.toString()
|
|
} catch {
|
|
return value
|
|
}
|
|
}
|
|
|
|
try {
|
|
const migrationFiles = (await readdir(migrationsDir))
|
|
.filter((file) => file.endsWith('.sql'))
|
|
.sort()
|
|
|
|
for (const file of migrationFiles) {
|
|
const migrationPath = resolve(migrationsDir, file)
|
|
const sql = await readFile(migrationPath, 'utf8')
|
|
await pool.query(sql)
|
|
console.log(`Applied migration ${migrationPath}`)
|
|
}
|
|
} catch (error) {
|
|
if (error?.code === 'ECONNREFUSED') {
|
|
console.error(`Unable to connect to Postgres at ${redactConnectionString(connectionString)}`)
|
|
console.error('For the local Docker database, start it with `docker compose up -d postgres` from the repo root.')
|
|
console.error('Then use DATABASE_URL=postgres://ca_studio:ca_studio@localhost:54329/ca_studio_test')
|
|
}
|
|
throw error
|
|
} finally {
|
|
await pool.end()
|
|
}
|