-
Notifications
You must be signed in to change notification settings - Fork 280
/
mysql-driver.ts
206 lines (178 loc) · 5.4 KB
/
mysql-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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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, isObject, freeze } from '../../util/object-utils.js'
import { extendStackTrace } from '../../util/stack-trace-utils.js'
import {
MysqlDialectConfig,
MysqlOkPacket,
MysqlPool,
MysqlPoolConnection,
MysqlQueryResult,
} from './mysql-dialect-config.js'
const PRIVATE_RELEASE_METHOD = Symbol()
export class MysqlDriver implements Driver {
readonly #config: MysqlDialectConfig
readonly #connections = new WeakMap<MysqlPoolConnection, DatabaseConnection>()
#pool?: MysqlPool
constructor(configOrPool: MysqlDialectConfig) {
this.#config = freeze({ ...configOrPool })
}
async init(): Promise<void> {
this.#pool = isFunction(this.#config.pool)
? await this.#config.pool()
: this.#config.pool
}
async acquireConnection(): Promise<DatabaseConnection> {
const rawConnection = await this.#acquireConnection()
let connection = this.#connections.get(rawConnection)
if (!connection) {
connection = new MysqlConnection(rawConnection)
this.#connections.set(rawConnection, connection)
// The driver must take care of calling `onCreateConnection` when a new
// connection is created. The `mysql2` 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 #acquireConnection(): Promise<MysqlPoolConnection> {
return new Promise((resolve, reject) => {
this.#pool!.getConnection(async (err, rawConnection) => {
if (err) {
reject(err)
} else {
resolve(rawConnection)
}
})
})
}
async beginTransaction(
connection: DatabaseConnection,
settings: TransactionSettings
): Promise<void> {
if (settings.isolationLevel) {
// On MySQL this sets the isolation level of the next transaction.
await connection.executeQuery(
CompiledQuery.raw(
`set transaction isolation level ${settings.isolationLevel}`
)
)
}
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: MysqlConnection): Promise<void> {
connection[PRIVATE_RELEASE_METHOD]()
}
async destroy(): Promise<void> {
return new Promise((resolve, reject) => {
this.#pool!.end((err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
}
function isOkPacket(obj: unknown): obj is MysqlOkPacket {
return isObject(obj) && 'insertId' in obj && 'affectedRows' in obj
}
class MysqlConnection implements DatabaseConnection {
readonly #rawConnection: MysqlPoolConnection
constructor(rawConnection: MysqlPoolConnection) {
this.#rawConnection = rawConnection
}
async executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>> {
try {
const result = await this.#executeQuery(compiledQuery)
if (isOkPacket(result)) {
const { insertId, affectedRows } = result
const numAffectedRows =
affectedRows !== undefined && affectedRows !== null
? BigInt(affectedRows)
: undefined
return {
insertId:
insertId !== undefined &&
insertId !== null &&
insertId.toString() !== '0'
? BigInt(insertId)
: undefined,
// TODO: remove.
numUpdatedOrDeletedRows: numAffectedRows,
numAffectedRows,
rows: [],
}
} else if (Array.isArray(result)) {
return {
rows: result as O[],
}
}
return {
rows: [],
}
} catch (err) {
throw extendStackTrace(err, new Error())
}
}
#executeQuery(compiledQuery: CompiledQuery): Promise<MysqlQueryResult> {
return new Promise((resolve, reject) => {
this.#rawConnection.query(
compiledQuery.sql,
compiledQuery.parameters,
(err, result) => {
if (err) {
reject(err)
} else {
resolve(result)
}
}
)
})
}
async *streamQuery<O>(
compiledQuery: CompiledQuery,
chunkSize: number
): AsyncIterableIterator<QueryResult<O>> {
const stream = this.#rawConnection
.query(compiledQuery.sql, compiledQuery.parameters)
.stream<O>({
objectMode: true,
})
try {
for await (const row of stream) {
yield {
rows: [row],
}
}
} catch (ex) {
if (
ex &&
typeof ex === 'object' &&
'code' in ex &&
// @ts-ignore
ex.code === 'ERR_STREAM_PREMATURE_CLOSE'
) {
// Most likely because of https://github.com/mysqljs/mysql/blob/master/lib/protocol/sequences/Query.js#L220
return
}
throw ex
}
}
[PRIVATE_RELEASE_METHOD](): void {
this.#rawConnection.release()
}
}