-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
test.ts
390 lines (351 loc) · 10.8 KB
/
test.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { assertEquals, assertThrowsAsync, semver } from "./test.deps.ts";
import {
ConnnectionError,
ResponseTimeoutError,
} from "./src/constant/errors.ts";
import {
createTestDB,
delay,
isMariaDB,
registerTests,
testWithClient,
} from "./test.util.ts";
import { log as stdlog } from "./deps.ts";
import { log } from "./src/logger.ts";
import { configLogger } from "./mod.ts";
testWithClient(async function testCreateDb(client) {
await client.query(`CREATE DATABASE IF NOT EXISTS enok`);
});
testWithClient(async function testCreateTable(client) {
await client.query(`DROP TABLE IF EXISTS users`);
await client.query(`
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
is_top tinyint(1) default 0,
created_at timestamp not null default current_timestamp,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`);
});
testWithClient(async function testInsert(client) {
let result = await client.execute(`INSERT INTO users(name) values(?)`, [
"manyuanrong",
]);
assertEquals(result, { affectedRows: 1, lastInsertId: 1 });
result = await client.execute(`INSERT INTO users ?? values ?`, [
["id", "name"],
[2, "MySQL"],
]);
assertEquals(result, { affectedRows: 1, lastInsertId: 2 });
});
testWithClient(async function testUpdate(client) {
let result = await client.execute(
`update users set ?? = ?, ?? = ? WHERE id = ?`,
["name", "MYR🦕", "created_at", new Date(), 1],
);
assertEquals(result, { affectedRows: 1, lastInsertId: 0 });
});
testWithClient(async function testQuery(client) {
let result = await client.query(
"select ??,`is_top`,`name` from ?? where id = ?",
["id", "users", 1],
);
assertEquals(result, [{ id: 1, name: "MYR🦕", is_top: 0 }]);
});
testWithClient(async function testQueryErrorOccurred(client) {
assertEquals(client.pool, {
size: 0,
maxSize: client.config.poolSize,
available: 0,
});
await assertThrowsAsync(
() => client.query("select unknownfield from `users`"),
Error,
);
await client.query("select 1");
assertEquals(client.pool, {
size: 1,
maxSize: client.config.poolSize,
available: 1,
});
});
testWithClient(async function testQueryList(client) {
const sql = "select ??,?? from ??";
let result = await client.query(sql, ["id", "name", "users"]);
assertEquals(result, [
{ id: 1, name: "MYR🦕" },
{ id: 2, name: "MySQL" },
]);
});
testWithClient(async function testQueryTime(client) {
const sql = `SELECT CAST("09:04:10" AS time) as time`;
let result = await client.query(sql);
assertEquals(result, [{ time: "09:04:10" }]);
});
testWithClient(async function testQueryBigint(client) {
await client.query(`DROP TABLE IF EXISTS test_bigint`);
await client.query(`CREATE TABLE test_bigint (
id int(11) NOT NULL AUTO_INCREMENT,
bigint_column bigint NOT NULL,
PRIMARY KEY (id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4`);
const value = "9223372036854775807";
await client.execute(
"INSERT INTO test_bigint(bigint_column) VALUES (?)",
[value],
);
const result = await client.query("SELECT bigint_column FROM test_bigint");
assertEquals(result, [{ bigint_column: BigInt(value) }]);
});
testWithClient(async function testQueryDecimal(client) {
await client.query(`DROP TABLE IF EXISTS test_decimal`);
await client.query(`CREATE TABLE test_decimal (
id int(11) NOT NULL AUTO_INCREMENT,
decimal_column decimal(65,30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4`);
const value = "0.012345678901234567890123456789";
await client.execute(
"INSERT INTO test_decimal(decimal_column) VALUES (?)",
[value],
);
const result = await client.query("SELECT decimal_column FROM test_decimal");
assertEquals(result, [{ decimal_column: value }]);
});
testWithClient(async function testQueryDatetime(client) {
await client.useConnection(async (connection) => {
if (isMariaDB(connection) || semver.lt(connection.serverVersion, "5.6.0")) {
return;
}
await client.query(`DROP TABLE IF EXISTS test_datetime`);
await client.query(`CREATE TABLE test_datetime (
id int(11) NOT NULL AUTO_INCREMENT,
datetime datetime(6) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4`);
const datetime = new Date();
await client.execute(
`
INSERT INTO test_datetime (datetime)
VALUES (?)`,
[datetime],
);
const [row] = await client.query("SELECT datetime FROM test_datetime");
assertEquals(row.datetime.toISOString(), datetime.toISOString()); // See https://github.com/denoland/deno/issues/6643
});
});
testWithClient(async function testDelete(client) {
let result = await client.execute(`delete from users where ?? = ?`, [
"id",
1,
]);
assertEquals(result, { affectedRows: 1, lastInsertId: 0 });
});
testWithClient(async function testPool(client) {
assertEquals(client.pool, {
maxSize: client.config.poolSize,
available: 0,
size: 0,
});
const expect = new Array(10).fill([{ "1": 1 }]);
const result = await Promise.all(expect.map(() => client.query(`select 1`)));
assertEquals(client.pool, {
maxSize: client.config.poolSize,
available: 3,
size: 3,
});
assertEquals(result, expect);
});
testWithClient(async function testQueryOnClosed(client) {
for (const i of [0, 0, 0]) {
await assertThrowsAsync(async () => {
await client.transaction(async (conn) => {
conn.close();
await conn.query("SELECT 1");
});
}, ConnnectionError);
}
assertEquals(client.pool?.size, 0);
await client.query("select 1");
});
testWithClient(async function testTransactionSuccess(client) {
const success = await client.transaction(async (connection) => {
await connection.execute("insert into users(name) values(?)", [
"transaction1",
]);
await connection.execute("delete from users where id = ?", [2]);
return true;
});
assertEquals(true, success);
const result = await client.query("select name,id from users");
assertEquals([{ name: "transaction1", id: 3 }], result);
});
testWithClient(async function testTransactionRollback(client) {
let success;
await assertThrowsAsync(async () => {
success = await client.transaction(async (connection) => {
// Insert an existing id
await connection.execute("insert into users(name,id) values(?,?)", [
"transaction2",
3,
]);
return true;
});
});
assertEquals(undefined, success);
const result = await client.query("select name from users");
assertEquals([{ name: "transaction1" }], result);
});
testWithClient(async function testIdleTimeout(client) {
assertEquals(client.pool, {
maxSize: 3,
available: 0,
size: 0,
});
await Promise.all(new Array(10).fill(0).map(() => client.query("select 1")));
assertEquals(client.pool, {
maxSize: 3,
available: 3,
size: 3,
});
await delay(500);
assertEquals(client.pool, {
maxSize: 3,
available: 3,
size: 3,
});
await client.query("select 1");
await delay(500);
assertEquals(client.pool, {
maxSize: 3,
available: 1,
size: 1,
});
await delay(500);
assertEquals(client.pool, {
maxSize: 3,
available: 0,
size: 0,
});
}, {
idleTimeout: 750,
});
testWithClient(async function testReadTimeout(client) {
await client.execute("select sleep(0.3)");
await assertThrowsAsync(async () => {
await client.execute("select sleep(0.7)");
}, ResponseTimeoutError);
assertEquals(client.pool, {
maxSize: 3,
available: 0,
size: 0,
});
}, {
timeout: 500,
});
testWithClient(async function testLargeQueryAndResponse(client) {
function buildLargeString(len: number) {
let str = "";
for (let i = 0; i < len; i++) {
str += i % 10;
}
return str;
}
const largeString = buildLargeString(512 * 1024);
assertEquals(
await client.query(`select "${largeString}" as str`),
[{ str: largeString }],
);
});
testWithClient(async function testExecuteIterator(client) {
await client.useConnection(async (conn) => {
await conn.execute(`DROP TABLE IF EXISTS numbers`);
await conn.execute(`CREATE TABLE numbers (num INT NOT NULL)`);
await conn.execute(
`INSERT INTO numbers (num) VALUES ${
new Array(64).fill(0).map((v, idx) => `(${idx})`).join(",")
}`,
);
const r = await conn.execute(`SELECT num FROM numbers`, [], true);
let count = 0;
for await (const row of r.iterator) {
assertEquals(row.num, count);
count++;
}
assertEquals(count, 64);
});
});
// For MySQL 8, the default auth plugin is `caching_sha2_password`. Create user
// using `mysql_native_password` to test Authentication Method Mismatch.
testWithClient(async function testCreateUserWithMysqlNativePassword(client) {
const { version } = (await client.query(`SELECT VERSION() as version`))[0];
if (version.startsWith("8.")) {
// MySQL 8 does not have `PASSWORD()` function
await client.execute(
`CREATE USER 'testuser'@'%' IDENTIFIED WITH mysql_native_password BY 'testpassword'`,
);
} else {
await client.execute(
`CREATE USER 'testuser'@'%' IDENTIFIED WITH mysql_native_password`,
);
await client.execute(
`SET PASSWORD FOR 'testuser'@'%' = PASSWORD('testpassword')`,
);
}
await client.execute(`GRANT ALL ON test.* TO 'testuser'@'%'`);
});
testWithClient(async function testConnectWithMysqlNativePassword(client) {
assertEquals(
await client.query(`SELECT CURRENT_USER() AS user`),
[{ user: "testuser@%" }],
);
}, { username: "testuser", password: "testpassword" });
testWithClient(async function testDropUserWithMysqlNativePassword(client) {
await client.execute(`DROP USER 'testuser'@'%'`);
});
testWithClient(async function testSelectEmptyString(client) {
assertEquals(
await client.query(`SELECT '' AS a`),
[{ a: "" }],
);
assertEquals(
await client.query(`SELECT '' AS a, '' AS b, '' AS c`),
[{ a: "", b: "", c: "" }],
);
assertEquals(
await client.query(`SELECT '' AS a, 'b' AS b, '' AS c`),
[{ a: "", b: "b", c: "" }],
);
});
registerTests();
Deno.test("configLogger()", async () => {
let logCount = 0;
const fakeHandler = new class extends stdlog.handlers.BaseHandler {
constructor() {
super("INFO");
}
log(msg: string) {
logCount++;
}
}();
await stdlog.setup({
handlers: {
fake: fakeHandler,
},
loggers: {
mysql: {
handlers: ["fake"],
},
},
});
await configLogger({ logger: stdlog.getLogger("mysql") });
log.info("Test log");
assertEquals(logCount, 1);
await configLogger({ enable: false });
log.info("Test log");
assertEquals(logCount, 1);
});
await createTestDB();
await new Promise((r) => setTimeout(r, 0));
// Workaround to https://github.com/denoland/deno/issues/7844