-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
connection.ts
307 lines (279 loc) · 8.49 KB
/
connection.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { byteFormat, delay } from "../deps.ts";
import { ClientConfig } from "./client.ts";
import {
ConnnectionError,
ProtocolError,
ReadError,
ResponseTimeoutError,
} from "./constant/errors.ts";
import { log } from "./logger.ts";
import { buildAuth } from "./packets/builders/auth.ts";
import { buildQuery } from "./packets/builders/query.ts";
import { ReceivePacket, SendPacket } from "./packets/packet.ts";
import { parseError } from "./packets/parsers/err.ts";
import {
AuthResult,
parseAuth,
parseHandshake,
} from "./packets/parsers/handshake.ts";
import { FieldInfo, parseField, parseRow } from "./packets/parsers/result.ts";
import { PacketType } from "./constant/packet.ts";
import authPlugin from "./auth_plugin/index.ts";
/**
* Connection state
*/
export enum ConnectionState {
CONNECTING,
CONNECTED,
CLOSING,
CLOSED,
}
/**
* Result for excute sql
*/
export type ExecuteResult = {
affectedRows?: number;
lastInsertId?: number;
fields?: FieldInfo[];
rows?: any[];
};
/** Connection for mysql */
export class Connection {
state: ConnectionState = ConnectionState.CONNECTING;
capabilities: number = 0;
serverVersion: string = "";
private conn?: Deno.Conn = undefined;
private _timedOut = false;
get remoteAddr(): string {
return this.config.socketPath
? `unix:${this.config.socketPath}`
: `${this.config.hostname}:${this.config.port}`;
}
constructor(readonly config: ClientConfig) {}
private async _connect() {
// TODO: implement connect timeout
const { hostname, port = 3306, socketPath, username = "", password } =
this.config;
log.info(`connecting ${this.remoteAddr}`);
this.conn = !socketPath
? await Deno.connect({
transport: "tcp",
hostname,
port,
})
: await Deno.connect({
transport: "unix",
path: socketPath,
} as any);
try {
let receive = await this.nextPacket();
const handshakePacket = parseHandshake(receive.body);
const data = buildAuth(handshakePacket, {
username,
password,
db: this.config.db,
});
await new SendPacket(data, 0x1).send(this.conn);
this.state = ConnectionState.CONNECTING;
this.serverVersion = handshakePacket.serverVersion;
this.capabilities = handshakePacket.serverCapabilities;
receive = await this.nextPacket();
const authResult = parseAuth(receive);
let handler;
switch (authResult) {
case AuthResult.AuthMoreRequired:
const adaptedPlugin =
(authPlugin as any)[handshakePacket.authPluginName];
handler = adaptedPlugin;
break;
case AuthResult.MethodMismatch:
// TODO: Negotiate
throw new Error("Currently cannot support auth method mismatch!");
}
let result;
if (handler) {
result = handler.start(handshakePacket.seed, password!);
while (!result.done) {
if (result.data) {
const sequenceNumber = receive.header.no + 1;
await new SendPacket(result.data, sequenceNumber).send(this.conn);
receive = await this.nextPacket();
}
if (result.quickRead) {
await this.nextPacket();
}
if (result.next) {
result = result.next(receive);
}
}
}
const header = receive.body.readUint8();
if (header === 0xff) {
const error = parseError(receive.body, this);
log.error(`connect error(${error.code}): ${error.message}`);
this.close();
throw new Error(error.message);
} else {
log.info(`connected to ${this.remoteAddr}`);
this.state = ConnectionState.CONNECTED;
}
if (this.config.charset) {
await this.execute(`SET NAMES ${this.config.charset}`);
}
} catch (error) {
// Call close() to avoid leaking socket.
this.close();
throw error;
}
}
/** Connect to database */
async connect(): Promise<void> {
await this._connect();
}
private async nextPacket(): Promise<ReceivePacket> {
if (!this.conn) {
throw new ConnnectionError("Not connected");
}
const timeoutTimer = this.config.timeout
? setTimeout(
this._timeoutCallback,
this.config.timeout,
)
: null;
let packet: ReceivePacket | null;
try {
packet = await new ReceivePacket().parse(this.conn!);
} catch (error) {
if (this._timedOut) {
// Connection has been closed by timeoutCallback.
throw new ResponseTimeoutError("Connection read timed out");
}
timeoutTimer && clearTimeout(timeoutTimer);
this.close();
throw error;
}
timeoutTimer && clearTimeout(timeoutTimer);
if (!packet) {
// Connection is half-closed by the remote host.
// Call close() to avoid leaking socket.
this.close();
throw new ReadError("Connection closed unexpectedly");
}
if (packet.type === PacketType.ERR_Packet) {
packet.body.skip(1);
const error = parseError(packet.body, this);
throw new Error(error.message);
}
return packet!;
}
private _timeoutCallback = () => {
log.info("connection read timed out");
this._timedOut = true;
this.close();
};
/**
* Check if database server version is less than 5.7.0
*
* MySQL version is "x.y.z"
* eg "5.5.62"
*
* MariaDB version is "5.5.5-x.y.z-MariaDB[-build-infos]" for versions after 5 (10.0 etc)
* eg "5.5.5-10.4.10-MariaDB-1:10.4.10+maria~bionic"
* and "x.y.z-MariaDB-[build-infos]" for 5.x versions
* eg "5.5.64-MariaDB-1~trusty"
*/
private lessThan5_7(): Boolean {
const version = this.serverVersion;
if (!version.includes("MariaDB")) return version < "5.7.0";
const segments = version.split("-");
// MariaDB v5.x
if (segments[1] === "MariaDB") return segments[0] < "5.7.0";
// MariaDB v10+
return false;
}
/** Check if the MariaDB version is 10.0 or 10.1 */
private isMariaDBAndVersion10_0Or10_1(): Boolean {
const version = this.serverVersion;
if (!version.includes("MariaDB")) return false;
return version.includes("5.5.5-10.1") || version.includes("5.5.5-10.0");
}
/** Close database connection */
close(): void {
if (this.state != ConnectionState.CLOSED) {
log.info("close connection");
this.conn?.close();
this.state = ConnectionState.CLOSED;
}
}
/**
* excute query sql
* @param sql query sql string
* @param params query params
*/
async query(sql: string, params?: any[]): Promise<ExecuteResult | any[]> {
const result = await this.execute(sql, params);
if (result && result.rows) {
return result.rows;
} else {
return result;
}
}
/**
* excute sql
* @param sql sql string
* @param params query params
*/
async execute(sql: string, params?: any[]): Promise<ExecuteResult> {
if (this.state != ConnectionState.CONNECTED) {
if (this.state == ConnectionState.CLOSED) {
throw new ConnnectionError("Connection is closed");
} else {
throw new ConnnectionError("Must be connected first");
}
}
const data = buildQuery(sql, params);
try {
await new SendPacket(data, 0).send(this.conn!);
let receive = await this.nextPacket();
if (receive.type === PacketType.OK_Packet) {
receive.body.skip(1);
return {
affectedRows: receive.body.readEncodedLen(),
lastInsertId: receive.body.readEncodedLen(),
};
} else if (receive.type !== PacketType.Result) {
throw new ProtocolError();
}
let fieldCount = receive.body.readEncodedLen();
const fields: FieldInfo[] = [];
while (fieldCount--) {
const packet = await this.nextPacket();
if (packet) {
const field = parseField(packet.body);
fields.push(field);
}
}
const rows = [];
if (this.lessThan5_7() || this.isMariaDBAndVersion10_0Or10_1()) {
// EOF(less than 5.7 or mariadb version is 10.0 or 10.1)
receive = await this.nextPacket();
if (receive.type !== PacketType.EOF_Packet) {
throw new ProtocolError();
}
}
while (true) {
receive = await this.nextPacket();
if (receive.type === PacketType.EOF_Packet) {
break;
} else {
const row = parseRow(receive.body, fields);
rows.push(row);
}
}
return { rows, fields };
} catch (error) {
this.close();
throw error;
}
}
}