Repository navigation
Expand file tree
/
Copy pathpostgres.ts
More file actions
57 lines (51 loc) · 1.5 KB
/
Copy pathpostgres.ts
File metadata and controls
57 lines (51 loc) · 1.5 KB
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
/**
* PostgreSQL dialect adapter.
*
* Uses the 'pg' package for PostgreSQL connections.
* Install with: npm install pg @types/pg
*/
import { Kysely, PostgresDialect } from 'kysely';
import type { ConnectionConfig, ConnectionResult } from '../types.js';
import { DEFAULT_PORTS, connectTimeoutFor } from '../defaults.js';
/**
* Create a PostgreSQL connection.
*
* @example
* ```typescript
* const conn = createPostgresConnection({
* dialect: 'postgres',
* host: 'localhost',
* database: 'myapp',
* user: 'postgres',
* password: 'secret',
* })
* ```
*/
export async function createPostgresConnection(
config: ConnectionConfig,
): Promise<ConnectionResult> {
// Dynamic import to avoid compile-time dependency
const pg = await import('pg');
const Pool = pg.default?.Pool ?? pg.Pool;
const pool = new Pool({
host: config.host ?? 'localhost',
port: config.port ?? DEFAULT_PORTS.postgres,
user: config.user,
password: config.password,
database: config.database,
min: config.pool?.min ?? 0,
max: config.pool?.max ?? 10,
ssl: config.ssl,
// pg's own default is 0, meaning wait forever: an unreachable host
// never comes back without this.
connectionTimeoutMillis: connectTimeoutFor(config),
});
const db = new Kysely<unknown>({
dialect: new PostgresDialect({ pool }),
});
return {
db,
dialect: 'postgres',
destroy: () => db.destroy(),
};
}