-
Notifications
You must be signed in to change notification settings - Fork 37
/
test.ts
614 lines (517 loc) · 16 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
import {
assert,
assertEquals,
assertMatch,
assertThrows,
} from "https://deno.land/std@0.53.0/testing/asserts.ts";
import { DB, Empty, Status } from "./mod.ts";
import SqliteError from "./src/error.ts";
// file used for fs io tests
const testDbFile = "test.db";
// permissions for skipping tests which require them
// if the permission can't be read, it is assumed granted
// TODO(dyedgreen): Update these once permissions can be introspected
let permWrite = true;
try {
await Deno.remove(testDbFile);
} catch (e) {
if (e instanceof Deno.errors.PermissionDenied) {
permWrite = false;
}
}
let permRead = true;
try {
await Deno.stat(testDbFile);
} catch (e) {
if (e instanceof Deno.errors.PermissionDenied) {
permRead = false;
}
}
/** Ensure README example works as advertised. */
Deno.test("readmeExample", function () {
// Open a database (no file permission version of open)
const db = new DB();
db.query(
"CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
);
const name =
["Peter Parker", "Clark Kent", "Bruce Wane"][Math.floor(Math.random() * 3)];
// Run a simple query
db.query("INSERT INTO people (name) VALUES (?)", [name]);
// Print out data in table
for (const [name] of db.query("SELECT name FROM people")) continue; // no console.log ;)
db.close();
});
/** Ensure the old README examples works as advertised. */
Deno.test("readmeExampleOld", async function () {
const db = new DB();
const first = ["Bruce", "Clark", "Peter"];
const last = ["Wane", "Kent", "Parker"];
db.query(
"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, subscribed INTEGER)",
);
for (let i = 0; i < 100; i++) {
const name = `${first[Math.floor(Math.random() * first.length)]} ${
last[
Math.floor(
Math.random() * last.length,
)
]
}`;
const email = `${name.replace(" ", "-")}@deno.land`;
const subscribed = Math.random() > 0.5 ? true : false;
db.query("INSERT INTO users (name, email, subscribed) VALUES (?, ?, ?)", [
name,
email,
subscribed,
]);
}
for (
const [
name,
email,
] of db.query(
"SELECT name, email FROM users WHERE subscribed = ? LIMIT 100",
[true],
)
) {
assertMatch(name, /(Bruce|Clark|Peter) (Wane|Kent|Parker)/);
assertEquals(email, `${name.replace(" ", "-")}@deno.land`);
}
const res = db.query("SELECT email FROM users WHERE name LIKE ?", [
"Robert Parr",
]);
assertEquals(res, Empty);
res.done();
// Omit write tests, as we don't want to require ---allow-write
// and have a write test, which checks for the flag and skips itself.
const subscribers = db.query(
"SELECT name, email FROM users WHERE subscribed = ?",
[true],
);
for (const [name, email] of subscribers) {
if (Math.random() > 0.5) continue;
subscribers.done();
}
db.close();
});
/** Ensure binding values works correctly. */
Deno.test("bindValues", function () {
const db = new DB();
let vals, rows;
// string
db.query(
"CREATE TABLE strings (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)",
);
vals = ["Hello World!", "I love Deno.", "Täst strüng..."];
for (const val of vals) {
db.query("INSERT INTO strings (val) VALUES (?)", [val]);
}
rows = [...db.query("SELECT val FROM strings")].map(([v]) => v);
assertEquals(rows.length, vals.length);
assertEquals(rows, vals);
// integer
db.query(
"CREATE TABLE ints (id INTEGER PRIMARY KEY AUTOINCREMENT, val INTEGER)",
);
vals = [42, 1, 2, 3, 4, 3453246, 4536787093, 45536787093];
for (const val of vals) db.query("INSERT INTO ints (val) VALUES (?)", [val]);
rows = [...db.query("SELECT val FROM ints")].map(([v]) => v);
assertEquals(rows.length, vals.length);
assertEquals(rows, vals);
// float
db.query(
"CREATE TABLE floats (id INTEGER PRIMARY KEY AUTOINCREMENT, val REAL)",
);
vals = [42.1, 1.235, 2.999, 1 / 3, 4.2345, 345.3246, 4536787.953e-8];
for (const val of vals) {
db.query("INSERT INTO floats (val) VALUES (?)", [val]);
}
rows = [...db.query("SELECT val FROM floats")].map(([v]) => v);
assertEquals(rows.length, vals.length);
assertEquals(rows, vals);
// boolean
db.query(
"CREATE TABLE bools (id INTEGER PRIMARY KEY AUTOINCREMENT, val INTEGER)",
);
vals = [true, false];
for (const val of vals) {
db.query(
"INSERT INTO bools (val) VALUES (?)",
[val],
);
}
rows = [...db.query("SELECT val FROM bools")].map(([v]) => v);
assertEquals(rows.length, vals.length);
assertEquals(rows, [1, 0]);
// date
db.query("CREATE TABLE dates (date TEXT NOT NULL)");
vals = [new Date(), new Date("2018-11-20"), new Date(123456789)];
for (const val of vals) {
db.query("INSERT INTO dates (date) VALUES (?)", [val]);
}
rows = [...db.query("SELECT date FROM dates")].map(([d]) => new Date(d));
assertEquals(rows, vals);
// blob
db.query(
"CREATE TABLE blobs (id INTEGER PRIMARY KEY AUTOINCREMENT, val BLOB)",
);
vals = [
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
new Uint8Array([3, 57, 45]),
];
for (const val of vals) {
db.query(
"INSERT INTO blobs (val) VALUES (?)",
[val],
);
}
rows = [...db.query("SELECT val FROM blobs")].map(([v]) => v);
assertEquals(rows.length, vals.length);
assertEquals(rows, vals);
// null & undefined
db.query(
"CREATE TABLE nulls (id INTEGER PRIMARY KEY AUTOINCREMENT, val INTEGER)",
);
vals = [null, undefined];
for (const val of vals) {
db.query(
"INSERT INTO nulls (val) VALUES (?)",
[val],
);
}
rows = [...db.query("SELECT val FROM nulls")].map(([v]) => v);
assertEquals(rows.length, vals.length);
assertEquals(rows, [null, null]); // TODO(hsjoberg) undefined -> null
// mixed
db.query(
"CREATE TABLE mix (id INTEGER PRIMARY KEY AUTOINCREMENT, val1 INTEGER, val2 TEXT, val3 REAL, val4 TEXT)",
);
vals = [42, "Hello World!", 0.33333, null];
db.query(
"INSERT INTO mix (val1, val2, val3, val4) VALUES (?, ?, ?, ?)",
vals,
);
rows = [...db.query("SELECT val1, val2, val3, val4 FROM mix")];
assertEquals(rows.length, 1);
assertEquals(rows[0], vals);
// too many
assertThrows(() => {
db.query("SELECT * FROM strings", [null]);
});
assertThrows(() => {
db.query("SELECT * FROM strings LIMIT ?", [5, "extra"]);
});
// too few
assertThrows(() => {
db.query("SELECT * FROM strings LIMIT ?");
});
assertThrows(() => {
db.query(
"SELECT * FROM mix WHERE val1 = ? AND val2 = ? AND val3 = ? LIMIT ?",
[
1,
"second",
],
);
});
// omitted is null
db.query(
"CREATE TABLE omit_is_null (idx INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)",
);
db.query("INSERT INTO omit_is_null (val) VALUES (?)");
rows = [...db.query("SELECT val FROM omit_is_null")].map(([val]) => val);
assertEquals(rows, [null]);
db.close();
});
/** Ensure binding named values works as advertised. */
Deno.test("bindNamedParameters", function () {
const db = new DB();
db.query(
"CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)",
);
// default named syntax
db.query("INSERT INTO test (val) VALUES (:val)", { val: "value" });
db.query(
"INSERT INTO test (val) VALUES (:otherVal)",
{ otherVal: "value other" },
);
// @ named syntax
db.query(
"INSERT INTO test (val) VALUES (@someName)",
{ ["@someName"]: "@value" },
);
// $ names syntax
db.query(
"INSERT INTO test (val) VALUES ($var::Name)",
{ ["$var::Name"]: "$value" },
);
// explicit positional syntax
db.query("INSERT INTO test (id, val) VALUES (?2, ?1)", ["this-is-it", 1000]);
// names must exist
assertThrows(() => {
db.query(
"INSERT INTO test (val) VALUES (:val)",
{ Val: "miss-spelled :(" },
);
});
// Make sure the data came through correctly
const vals = [...db.query("SELECT val FROM test ORDER BY id ASC")].map(
(row) => row[0],
);
assertEquals(
vals,
["value", "value other", "@value", "$value", "this-is-it"],
);
db.close();
});
/** Ensure blob data is copied and not viewed. */
Deno.test("blobsAreCopies", function () {
const db = new DB();
db.query(
"CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, val BLOB)",
);
const data = new Uint8Array([1, 2, 3, 4, 5]);
db.query("INSERT INTO test (val) VALUES (?)", [data]);
const [[a]] = [...db.query("SELECT val FROM test")];
const [[b]] = [...db.query("SELECT val FROM test")];
assertEquals(data, a);
assertEquals(data, b);
assertEquals(a, b);
a[0] = 100;
assertEquals(a[0], 100);
assertEquals(b[0], 1);
assertEquals(data[0], 1);
data[0] = 5;
const [[c]] = [...db.query("SELECT val FROM test")];
assertEquals(c[0], 1);
db.close();
});
/** Ensure saving to file works. */
Deno.test({
name: "saveToFile",
ignore: !permRead || !permWrite,
fn: async function () {
const data = [
"Hello World!",
"Hello Deno!",
"JavaScript <3",
"This costs 0€!",
"Wéll, hällö thėrè¿",
];
// Ensure test file does not exist
try {
await Deno.remove(testDbFile);
} catch {}
// Write data to db
const db = new DB(testDbFile);
db.query(
"CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)",
);
for (const val of data) {
db.query("INSERT INTO test (val) VALUES (?)", [val]);
}
// Read db and check the data is restored
const db2 = await new DB(testDbFile);
for (const [id, val] of db2.query("SELECT * FROM test")) {
assertEquals(data[id - 1], val);
}
// Clean up
await Deno.remove(testDbFile);
db.close();
db2.close();
},
});
/** Ensure temporary databases work. */
Deno.test({
name: "tempDB",
ignore: !permRead || !permWrite,
fn: function () {
const data = [
"Hello World!",
"Hello Deno!",
"JavaScript <3",
"This costs 0€!",
"Wéll, hällö thėrè¿",
];
const db = new DB("");
db.query(
"CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)",
);
for (const val of data) {
db.query("INSERT INTO test (val) VALUES (?)", [val]);
}
// Read db and check the data is restored
for (const [id, val] of db.query("SELECT * FROM test")) {
assertEquals(data[id - 1], val);
}
db.close();
},
});
/** Test error is thrown on invalid SQL. */
Deno.test("invalidSQL", function () {
const db = new DB();
const queries = [
"INSERT INTO does_not_exist (balance) VALUES (5)",
"this is not sql",
";;;",
];
for (const query of queries) assertThrows(() => db.query(query));
db.close();
});
/** Test default is enforcing foreign key constraints. */
Deno.test("foreignKeys", function () {
const db = new DB();
db.query("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT)");
db.query(
"CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, user INTEGER, FOREIGN KEY(user) REFERENCES users(id))",
);
db.query("INSERT INTO users (id) VALUES (1)");
const [[id]] = [...db.query("SELECT id FROM users")];
// User must exist
assertThrows(() => {
db.query("INSERT INTO orders (user) VALUES (?)", [id + 1]);
});
db.query("INSERT INTO orders (user) VALUES (?)", [id]);
// Can't delete if that violates the constraint
assertThrows(() => {
db.query("DELETE FROM users WHERE id = ?", [id]);
});
// Now deleting is OK
db.query("DELETE FROM orders WHERE user = ?", [id]);
db.query("DELETE FROM users WHERE id = ?", [id]);
db.close();
});
/** Test close behaves correctly. */
Deno.test("closeDB", function () {
const db = new DB();
db.close();
assertThrows(() => db.query("CREATE TABLE test (name TEXT PRIMARY KEY)"));
});
/** Test having open queries blocks closing. */
Deno.test("openQueriesBlockClose", function () {
const db = new DB();
db.query("CREATE TABLE test (name TEXT PRIMARY KEY)");
db.query("INSERT INTO test (name) VALUES (?)", ["Deno"]);
const rows = db.query("SELECT name FROM test");
// We have an open query
assertThrows(() => db.close());
rows.done();
db.close();
});
/** Test close with forced option. */
Deno.test("openQueriesCleanedUpByForcedClose", function () {
const db = new DB();
db.query("CREATE TABLE test (name TEXT PRIMARY KEY)");
db.query("INSERT INTO test (name) VALUES (?)", ["Deno"]);
const rows = db.query("SELECT name FROM test");
assertThrows(() => db.close());
db.close(true);
});
/** Test SQLite constraint error code. */
Deno.test("constraintErrorCode", function () {
const db = new DB();
db.query("CREATE TABLE test (name TEXT PRIMARY KEY)");
db.query("INSERT INTO test (name) VALUES (?)", ["A"]);
const e = assertThrows(() =>
db.query("INSERT INTO test (name) VALUES (?)", ["A"])
) as SqliteError;
assertEquals(e.code, Status.SqliteConstraint, "Got wrong error code");
assertEquals(
Status[e.codeName],
Status.SqliteConstraint,
"Got wrong error code name",
);
});
/** Test SQLite syntax error error code. */
Deno.test("syntaxErrorErrorCode", function () {
const db = new DB();
const e = assertThrows(() =>
db.query("CREATE TABLEX test (name TEXT PRIMARY KEY)")
) as SqliteError;
assertEquals(e.code, Status.SqliteError, "Got wrong error code");
assertEquals(
Status[e.codeName],
Status.SqliteError,
"Got wrong error code name",
);
});
/** Test invalid value does not cause statement leakage. */
Deno.test("invalidBindDoesNotLeakStatements", function () {
const db = new DB();
db.query("CREATE TABLE test (id INTEGER)");
for (let n = 0; n < 100; n++) {
try {
db.query("INSERT INTO test (id) VALUES (?)", [{}]);
} catch {}
}
db.query("INSERT INTO test (id) VALUES (1)");
db.close();
});
Deno.test("getColumnsWithoutNames", function () {
const db = new DB();
db.query(
"CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
);
db.query("INSERT INTO test (name) VALUES (?)", ["name"]);
const rows = db.query("SELECT id, name from test");
const columns = rows.columns();
assertEquals(columns, [
{ name: "id", originName: "id", tableName: "test" },
{ name: "name", originName: "name", tableName: "test" },
]);
});
Deno.test("getColumnsWithNames", function () {
const db = new DB();
db.query(
"CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
);
db.query("INSERT INTO test (name) VALUES (?)", ["name"]);
const rows = db.query("SELECT id AS test_id, name AS test_name from test");
const columns = rows.columns();
assertEquals(columns, [
{ name: "test_id", originName: "id", tableName: "test" },
{ name: "test_name", originName: "name", tableName: "test" },
]);
});
Deno.test("getColumnsFromFinalizedRows", function () {
const db = new DB();
db.query("CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT)");
const rows = db.query("SELECT id from test");
rows.done();
// after iteration is done
assertThrows(() => {
rows.columns();
});
});
Deno.test("dateTimeIsCorrect", function () {
const db = new DB();
// the date/ time is passed from JS and should be current (note that it is GMT)
const [[now]] = [...db.query("SELECT current_timestamp")];
assertEquals(new Date(now + "Z"), new Date());
db.close();
});
Deno.test("lastInsertedId", function () {
const db = new DB();
// By default, lastInsertRowId must be 0
assertEquals(db.lastInsertRowId, 0);
// Create table and insert value
db.query(`CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR(255))`);
const insertRowIds = [];
// Insert data to table and collect their ids
for (let i = 0; i < 10; i++) {
db.query("INSERT INTO users (name) VALUES ('John Doe')");
insertRowIds.push(db.lastInsertRowId);
}
// Now, the last inserted row id must be 10
assertEquals(db.lastInsertRowId, 10);
// All collected row ids must be the same as in the database
assertEquals(
insertRowIds,
[...db.query("SELECT id FROM users")].map(([i]) => i),
);
db.close();
// When the database is closed, the value
// will be resetted to 0 again
assertEquals(db.lastInsertRowId, 0);
});