-
Notifications
You must be signed in to change notification settings - Fork 348
/
database.ts
69 lines (58 loc) · 1.67 KB
/
database.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { Pool, PoolClient } from 'pg';
import { MedplumServerConfig } from './config';
import { globalLogger } from './logger';
import { migrate } from './migrations/migrations';
let pool: Pool | undefined;
export function getDatabasePool(): Pool {
if (!pool) {
throw new Error('Database not setup');
}
return pool;
}
export const locks = {
migration: 1,
};
export async function initDatabase(serverConfig: MedplumServerConfig, runMigrations = true): Promise<void> {
const config = serverConfig.database;
const poolConfig = {
host: config.host,
port: config.port,
database: config.dbname,
user: config.username,
password: config.password,
ssl: config.ssl,
};
if (serverConfig.databaseProxyEndpoint) {
poolConfig.host = serverConfig.databaseProxyEndpoint;
poolConfig.ssl = poolConfig.ssl ?? {};
poolConfig.ssl.require = true;
}
pool = new Pool(poolConfig);
pool.on('error', (err) => {
globalLogger.error('Database connection error', err);
});
pool.on('connect', (client) => {
client.query(`SET statement_timeout TO ${config.queryTimeout ?? 60000}`).catch((err) => {
globalLogger.warn('Failed to set query timeout', err);
});
});
let client: PoolClient | undefined;
try {
client = await pool.connect();
await client.query('SELECT pg_advisory_lock($1)', [locks.migration]);
if (runMigrations) {
await migrate(client);
}
} finally {
if (client) {
await client.query('SELECT pg_advisory_unlock($1)', [locks.migration]);
client.release();
}
}
}
export async function closeDatabase(): Promise<void> {
if (pool) {
await pool.end();
pool = undefined;
}
}