-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathpostgres-driver.ts
173 lines (146 loc) · 4.51 KB
/
postgres-driver.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import {
DatabaseConnection,
QueryResult,
} from '../../driver/database-connection.js'
import { Driver, TransactionSettings } from '../../driver/driver.js'
import { CompiledQuery } from '../../query-compiler/compiled-query.js'
import { isFunction, freeze } from '../../util/object-utils.js'
import { extendStackTrace } from '../../util/stack-trace-utils.js'
import {
PostgresCursorConstructor,
PostgresDialectConfig,
PostgresPool,
PostgresPoolClient,
} from './postgres-dialect-config.js'
const PRIVATE_RELEASE_METHOD = Symbol()
export class PostgresDriver implements Driver {
readonly #config: PostgresDialectConfig
readonly #connections = new WeakMap<PostgresPoolClient, DatabaseConnection>()
#pool?: PostgresPool
constructor(config: PostgresDialectConfig) {
this.#config = freeze({ ...config })
}
async init(): Promise<void> {
this.#pool = isFunction(this.#config.pool)
? await this.#config.pool()
: this.#config.pool
}
async acquireConnection(): Promise<DatabaseConnection> {
const client = await this.#pool!.connect()
let connection = this.#connections.get(client)
if (!connection) {
connection = new PostgresConnection(client, {
cursor: this.#config.cursor ?? null,
})
this.#connections.set(client, connection)
// The driver must take care of calling `onCreateConnection` when a new
// connection is created. The `pg` module doesn't provide an async hook
// for the connection creation. We need to call the method explicitly.
if (this.#config?.onCreateConnection) {
await this.#config.onCreateConnection(connection)
}
}
return connection
}
async beginTransaction(
connection: DatabaseConnection,
settings: TransactionSettings
): Promise<void> {
if (settings.isolationLevel) {
await connection.executeQuery(
CompiledQuery.raw(
`start transaction isolation level ${settings.isolationLevel}`
)
)
} else {
await connection.executeQuery(CompiledQuery.raw('begin'))
}
}
async commitTransaction(connection: DatabaseConnection): Promise<void> {
await connection.executeQuery(CompiledQuery.raw('commit'))
}
async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
await connection.executeQuery(CompiledQuery.raw('rollback'))
}
async releaseConnection(connection: PostgresConnection): Promise<void> {
connection[PRIVATE_RELEASE_METHOD]()
}
async destroy(): Promise<void> {
if (this.#pool) {
const pool = this.#pool
this.#pool = undefined
await pool.end()
}
}
}
interface PostgresConnectionOptions {
cursor: PostgresCursorConstructor | null
}
class PostgresConnection implements DatabaseConnection {
#client: PostgresPoolClient
#options: PostgresConnectionOptions
constructor(client: PostgresPoolClient, options: PostgresConnectionOptions) {
this.#client = client
this.#options = options
}
async executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>> {
try {
const result = await this.#client.query<O>(compiledQuery.sql, [
...compiledQuery.parameters,
])
if (
result.command === 'INSERT' ||
result.command === 'UPDATE' ||
result.command === 'DELETE'
) {
const numAffectedRows = BigInt(result.rowCount)
return {
// TODO: remove.
numUpdatedOrDeletedRows: numAffectedRows,
numAffectedRows,
rows: result.rows ?? [],
}
}
return {
rows: result.rows ?? [],
}
} catch (err) {
throw extendStackTrace(err, new Error())
}
}
async *streamQuery<O>(
compiledQuery: CompiledQuery,
chunkSize: number
): AsyncIterableIterator<QueryResult<O>> {
if (!this.#options.cursor) {
throw new Error(
"'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres."
)
}
if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
throw new Error('chunkSize must be a positive integer')
}
const cursor = this.#client.query(
new this.#options.cursor<O>(
compiledQuery.sql,
compiledQuery.parameters.slice()
)
)
try {
while (true) {
const rows = await cursor.read(chunkSize)
if (rows.length === 0) {
break
}
yield {
rows,
}
}
} finally {
await cursor.close()
}
}
[PRIVATE_RELEASE_METHOD](): void {
this.#client.release()
}
}