-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathclient.test.ts
More file actions
1694 lines (1516 loc) · 54.7 KB
/
client.test.ts
File metadata and controls
1694 lines (1516 loc) · 54.7 KB
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import console from "node:console";
import { expect } from "@jest/globals";
import type { MatcherFunction } from "expect";
import type { Request, Response } from "@libsql/hrana-client";
import { fetch } from "@libsql/hrana-client";
import "./helpers.js";
import type * as libsql from "../node.js";
import { createClient } from "../node.js";
const config = {
url: process.env.URL ?? "ws://localhost:8080",
syncUrl: process.env.SYNC_URL,
authToken: process.env.AUTH_TOKEN,
};
const isWs =
config.url.startsWith("ws:") ||
config.url.startsWith("wss:") ||
config.url.startsWith("libsql:");
const isHttp =
config.url.startsWith("http:") || config.url.startsWith("https:");
const isFile = config.url.startsWith("file:");
// This allows us to skip tests based on the Hrana server that we are targeting:
// - "test_v3" is the v3 test server in Python
// - "test_v2" is the v2 test server in Python
// - "test_v1" is the v1 test server in Python
// - "sqld" is sqld
const server = process.env.SERVER ?? "test_v3";
const isSqld = server === "sqld";
const hasHrana2 = server !== "test_v1";
const hasHrana3 =
server !== "test_v1" && server !== "test_v2" && server !== "sqld";
const hasNetworkErrors =
isWs &&
(server === "test_v1" || server === "test_v2" || server === "test_v3");
function withClient(
f: (c: libsql.Client) => Promise<void>,
extraConfig: Partial<libsql.Config> = {},
): () => Promise<void> {
return async () => {
const c = createClient({ ...config, ...extraConfig });
try {
await f(c);
} finally {
c.close();
}
};
}
function withInMemoryClient(
f: (c: libsql.Client) => Promise<void>,
): () => Promise<void> {
return async () => {
const c = createClient({ url: ":memory:" });
try {
await f(c);
} finally {
c.close();
}
};
}
describe("createClient()", () => {
test("URL scheme not supported", () => {
expect(() => createClient({ url: "ftp://localhost" })).toThrow(
expect.toBeLibsqlError("URL_SCHEME_NOT_SUPPORTED", /"ftp:"/),
);
});
test("URL param not supported", () => {
expect(() => createClient({ url: "ws://localhost?foo=bar" })).toThrow(
expect.toBeLibsqlError("URL_PARAM_NOT_SUPPORTED", /"foo"/),
);
});
test("URL scheme incompatible with ?tls", () => {
const urls = [
"ws://localhost?tls=1",
"wss://localhost?tls=0",
"http://localhost?tls=1",
"https://localhost?tls=0",
];
for (const url of urls) {
expect(() => createClient({ url })).toThrow(
expect.toBeLibsqlError("URL_INVALID", /TLS/),
);
}
});
test("missing port in libsql URL with tls=0", () => {
expect(() => createClient({ url: "libsql://localhost?tls=0" })).toThrow(
expect.toBeLibsqlError("URL_INVALID", /port/),
);
});
test("invalid value of tls query param", () => {
expect(() =>
createClient({ url: "libsql://localhost?tls=yes" }),
).toThrow(expect.toBeLibsqlError("URL_INVALID", /"tls".*"yes"/));
});
test("passing URL instead of config object", () => {
// @ts-expect-error
expect(() => createClient("ws://localhost")).toThrow(
/as object, got string/,
);
});
test("invalid value for `intMode`", () => {
// @ts-expect-error
expect(() => createClient({ ...config, intMode: "foo" })).toThrow(
/"foo"/,
);
});
test("supports in-memory database", () => {
expect(() => createClient({ url: ":memory:" })).not.toThrow();
});
});
describe("execute()", () => {
test(
"query a single value",
withClient(async (c) => {
const rs = await c.execute("SELECT 42");
expect(rs.columns.length).toStrictEqual(1);
expect(rs.columnTypes.length).toStrictEqual(1);
expect(rs.rows.length).toStrictEqual(1);
expect(rs.rows[0].length).toStrictEqual(1);
expect(rs.rows[0][0]).toStrictEqual(42);
}),
);
test(
"query a single row",
withClient(async (c) => {
const rs = await c.execute(
"SELECT 1 AS one, 'two' AS two, 0.5 AS three",
);
expect(rs.columns).toStrictEqual(["one", "two", "three"]);
expect(rs.columnTypes).toStrictEqual(["", "", ""]);
expect(rs.rows.length).toStrictEqual(1);
const r = rs.rows[0];
expect(r.length).toStrictEqual(3);
expect(Array.from(r)).toStrictEqual([1, "two", 0.5]);
expect(Object.entries(r)).toStrictEqual([
["one", 1],
["two", "two"],
["three", 0.5],
]);
}),
);
test(
"query multiple rows",
withClient(async (c) => {
const rs = await c.execute(
"VALUES (1, 'one'), (2, 'two'), (3, 'three')",
);
expect(rs.columns.length).toStrictEqual(2);
expect(rs.columnTypes.length).toStrictEqual(2);
expect(rs.rows.length).toStrictEqual(3);
expect(Array.from(rs.rows[0])).toStrictEqual([1, "one"]);
expect(Array.from(rs.rows[1])).toStrictEqual([2, "two"]);
expect(Array.from(rs.rows[2])).toStrictEqual([3, "three"]);
}),
);
test(
"statement that produces error",
withClient(async (c) => {
await expect(c.execute("SELECT foobar")).rejects.toBeLibsqlError();
}),
);
test(
"rowsAffected with INSERT",
withClient(async (c) => {
await c.batch(
["DROP TABLE IF EXISTS t", "CREATE TABLE t (a)"],
"write",
);
const rs = await c.execute("INSERT INTO t VALUES (1), (2)");
expect(rs.rowsAffected).toStrictEqual(2);
}),
);
test(
"rowsAffected with DELETE",
withClient(async (c) => {
await c.batch(
[
"DROP TABLE IF EXISTS t",
"CREATE TABLE t (a)",
"INSERT INTO t VALUES (1), (2), (3), (4), (5)",
],
"write",
);
const rs = await c.execute("DELETE FROM t WHERE a >= 3");
expect(rs.rowsAffected).toStrictEqual(3);
}),
);
test(
"lastInsertRowid with INSERT",
withClient(async (c) => {
await c.batch(
[
"DROP TABLE IF EXISTS t",
"CREATE TABLE t (a)",
"INSERT INTO t VALUES ('one'), ('two')",
],
"write",
);
const insertRs = await c.execute("INSERT INTO t VALUES ('three')");
expect(insertRs.lastInsertRowid).not.toBeUndefined();
const selectRs = await c.execute({
sql: "SELECT a FROM t WHERE ROWID = ?",
args: [insertRs.lastInsertRowid!],
});
expect(Array.from(selectRs.rows[0])).toStrictEqual(["three"]);
}),
);
test(
"rows from INSERT RETURNING",
withClient(async (c) => {
await c.batch(
["DROP TABLE IF EXISTS t", "CREATE TABLE t (a)"],
"write",
);
const rs = await c.execute(
"INSERT INTO t VALUES (1) RETURNING 42 AS x, 'foo' AS y",
);
expect(rs.columns).toStrictEqual(["x", "y"]);
expect(rs.columnTypes).toStrictEqual(["", ""]);
expect(rs.rows.length).toStrictEqual(1);
expect(Array.from(rs.rows[0])).toStrictEqual([42, "foo"]);
}),
);
(hasHrana2 ? test : test.skip)(
"rowsAffected with WITH INSERT",
withClient(async (c) => {
await c.batch(
[
"DROP TABLE IF EXISTS t",
"CREATE TABLE t (a)",
"INSERT INTO t VALUES (1), (2), (3)",
],
"write",
);
const rs = await c.execute(`
WITH x(a) AS (SELECT 2*a FROM t)
INSERT INTO t SELECT a+1 FROM x
`);
expect(rs.rowsAffected).toStrictEqual(3);
}),
);
test(
"query a single value using an in memory database",
withInMemoryClient(async (c) => {
await c.batch(
[
"DROP TABLE IF EXISTS t",
"CREATE TABLE t (a)",
"INSERT INTO t VALUES ('one'), ('two')",
],
"write",
);
const insertRs = await c.execute("INSERT INTO t VALUES ('three')");
expect(insertRs.lastInsertRowid).not.toBeUndefined();
const selectRs = await c.execute({
sql: "SELECT a FROM t WHERE ROWID = ?",
args: [insertRs.lastInsertRowid!],
});
expect(Array.from(selectRs.rows[0])).toStrictEqual(["three"]);
}),
);
// see issue https://github.com/tursodatabase/libsql/issues/1411
test(
"execute transaction against in memory database with shared cache",
withClient(
async (c) => {
await c.execute("CREATE TABLE t (a)");
const transaction = await c.transaction();
transaction.close();
await c.execute("SELECT * FROM t");
},
{ url: "file::memory:?cache=shared" },
),
);
test(
"execute transaction against in memory database with private cache",
withClient(
async (c) => {
await c.execute("CREATE TABLE t (a)");
const transaction = await c.transaction();
transaction.close();
expect(() => c.execute("SELECT * FROM t")).rejects.toThrow();
},
{ url: "file::memory:?cache=private" },
),
);
test(
"execute transaction against in memory database with default cache",
withClient(
async (c) => {
await c.execute("CREATE TABLE t (a)");
const transaction = await c.transaction();
transaction.close();
expect(() => c.execute("SELECT * FROM t")).rejects.toThrow();
},
{ url: ":memory:" },
),
);
});
describe("values", () => {
function testRoundtrip(
name: string,
passed: libsql.InValue,
expected: libsql.Value,
intMode?: libsql.IntMode,
): void {
test(
name,
withClient(
async (c) => {
const rs = await c.execute({
sql: "SELECT ?",
args: [passed],
});
expect(rs.rows[0][0]).toStrictEqual(expected);
},
{ intMode },
),
);
}
function testRoundtripError(
name: string,
passed: libsql.InValue,
expectedError: unknown,
intMode?: libsql.IntMode,
): void {
test(
name,
withClient(
async (c) => {
await expect(
c.execute({
sql: "SELECT ?",
args: [passed],
}),
).rejects.toBeInstanceOf(expectedError);
},
{ intMode },
),
);
}
testRoundtrip("string", "boomerang", "boomerang");
testRoundtrip("string with weird characters", "a\n\r\t ", "a\n\r\t ");
testRoundtrip(
"string with unicode",
"žluťoučký kůň úpěl ďábelské ódy",
"žluťoučký kůň úpěl ďábelské ódy",
);
describe("number", () => {
const intModes: Array<libsql.IntMode> = ["number", "bigint", "string"];
for (const intMode of intModes) {
testRoundtrip("zero", 0, 0, intMode);
testRoundtrip("integer", -2023, -2023, intMode);
testRoundtrip("float", 12.345, 12.345, intMode);
testRoundtrip("large positive float", 1e18, 1e18, intMode);
testRoundtrip("large negative float", -1e18, -1e18, intMode);
testRoundtrip(
"MAX_VALUE",
Number.MAX_VALUE,
Number.MAX_VALUE,
intMode,
);
testRoundtrip(
"-MAX_VALUE",
-Number.MAX_VALUE,
-Number.MAX_VALUE,
intMode,
);
testRoundtrip(
"MIN_VALUE",
Number.MIN_VALUE,
Number.MIN_VALUE,
intMode,
);
}
});
describe("bigint", () => {
describe("'number' int mode", () => {
testRoundtrip("zero integer", 0n, 0, "number");
testRoundtrip("small integer", -42n, -42, "number");
testRoundtrip(
"largest safe integer",
9007199254740991n,
9007199254740991,
"number",
);
testRoundtripError(
"smallest unsafe integer",
9007199254740992n,
RangeError,
"number",
);
testRoundtripError(
"large unsafe integer",
-1152921504594532842n,
RangeError,
"number",
);
});
describe("'bigint' int mode", () => {
testRoundtrip("zero integer", 0n, 0n, "bigint");
testRoundtrip("small integer", -42n, -42n, "bigint");
testRoundtrip(
"large positive integer",
1152921504608088318n,
1152921504608088318n,
"bigint",
);
testRoundtrip(
"large negative integer",
-1152921504594532842n,
-1152921504594532842n,
"bigint",
);
testRoundtrip(
"largest positive integer",
9223372036854775807n,
9223372036854775807n,
"bigint",
);
testRoundtrip(
"largest negative integer",
-9223372036854775808n,
-9223372036854775808n,
"bigint",
);
});
describe("'string' int mode", () => {
testRoundtrip("zero integer", 0n, "0", "string");
testRoundtrip("small integer", -42n, "-42", "string");
testRoundtrip(
"large positive integer",
1152921504608088318n,
"1152921504608088318",
"string",
);
testRoundtrip(
"large negative integer",
-1152921504594532842n,
"-1152921504594532842",
"string",
);
testRoundtrip(
"largest positive integer",
9223372036854775807n,
"9223372036854775807",
"string",
);
testRoundtrip(
"largest negative integer",
-9223372036854775808n,
"-9223372036854775808",
"string",
);
});
});
const buf = new ArrayBuffer(256);
const array = new Uint8Array(buf);
for (let i = 0; i < 256; ++i) {
array[i] = i ^ 0xab;
}
testRoundtrip("ArrayBuffer", buf, buf);
testRoundtrip("Uint8Array", array, buf);
testRoundtrip("null", null, null);
testRoundtrip("true", true, 1n, "bigint");
testRoundtrip("false", false, 0n, "bigint");
testRoundtrip("true", true, 1, "number");
testRoundtrip("false", false, 0, "number");
testRoundtrip("true", true, "1", "string");
testRoundtrip("false", false, "0", "string");
testRoundtrip("true", true, 1);
testRoundtrip("false", false, 0);
testRoundtrip(
"Date",
new Date("2023-01-02T12:34:56Z"),
1672662896000,
"bigint",
);
// @ts-expect-error
testRoundtripError("undefined produces error", undefined, TypeError);
testRoundtripError("NaN produces error", NaN, RangeError);
testRoundtripError("Infinity produces error", Infinity, RangeError);
testRoundtripError(
"large bigint produces error",
-1267650600228229401496703205376n,
RangeError,
);
test(
"max 64-bit bigint",
withClient(async (c) => {
const rs = await c.execute({
sql: "SELECT ?||''",
args: [9223372036854775807n],
});
expect(rs.rows[0][0]).toStrictEqual("9223372036854775807");
}),
);
test(
"min 64-bit bigint",
withClient(async (c) => {
const rs = await c.execute({
sql: "SELECT ?||''",
args: [-9223372036854775808n],
});
expect(rs.rows[0][0]).toStrictEqual("-9223372036854775808");
}),
);
});
describe("ResultSet.toJSON()", () => {
test(
"simple result set",
withClient(async (c) => {
const rs = await c.execute("SELECT 1 AS a");
const json = rs.toJSON();
expect(
json["lastInsertRowid"] === null ||
json["lastInsertRowid"] === "0",
).toBe(true);
expect(json["columns"]).toStrictEqual(["a"]);
expect(json["columnTypes"]).toStrictEqual([""]);
expect(json["rows"]).toStrictEqual([[1]]);
expect(json["rowsAffected"]).toStrictEqual(0);
const str = JSON.stringify(rs);
expect(
str ===
'{"columns":["a"],"columnTypes":[""],"rows":[[1]],"rowsAffected":0,"lastInsertRowid":null}' ||
str ===
'{"columns":["a"],"columnTypes":[""],"rows":[[1]],"rowsAffected":0,"lastInsertRowid":"0"}',
).toBe(true);
}),
);
test(
"lastInsertRowid",
withClient(async (c) => {
await c.execute("DROP TABLE IF EXISTS t");
await c.execute("CREATE TABLE t (id INTEGER PRIMARY KEY NOT NULL)");
const rs = await c.execute("INSERT INTO t VALUES (12345)");
expect(rs.toJSON()).toStrictEqual({
columns: [],
columnTypes: [],
rows: [],
rowsAffected: 1,
lastInsertRowid: "12345",
});
}),
);
test(
"computed values",
withClient(async (c) => {
const rs = await c.execute(
"SELECT 42 AS integer, 0.5 AS float, NULL AS \"null\", 'foo' AS text, X'626172' AS blob",
);
const json = rs.toJSON();
expect(json["columns"]).toStrictEqual([
"integer",
"float",
"null",
"text",
"blob",
]);
expect(json["columnTypes"]).toStrictEqual(["", "", "", "", ""]);
expect(json["rows"]).toStrictEqual([
[42, 0.5, null, "foo", "YmFy"],
]);
}),
);
(hasHrana2 ? test : test.skip)(
"row values",
withClient(async (c) => {
await c.execute("DROP TABLE IF EXISTS t");
await c.execute(
"CREATE TABLE t (i INTEGER, f FLOAT, t TEXT, b BLOB)",
);
await c.execute("INSERT INTO t VALUES (42, 0.5, 'foo', X'626172')");
const rs = await c.execute("SELECT i, f, t, b FROM t LIMIT 1");
const json = rs.toJSON();
expect(json["columns"]).toStrictEqual(["i", "f", "t", "b"]);
expect(json["columnTypes"]).toStrictEqual([
"INTEGER",
"FLOAT",
"TEXT",
"BLOB",
]);
expect(json["rows"]).toStrictEqual([[42, 0.5, "foo", "YmFy"]]);
}),
);
test(
"bigint row value",
withClient(
async (c) => {
const rs = await c.execute("SELECT 42");
const json = rs.toJSON();
expect(json["rows"]).toStrictEqual([["42"]]);
},
{ intMode: "bigint" },
),
);
});
describe("arguments", () => {
test(
"? arguments",
withClient(async (c) => {
const rs = await c.execute({
sql: "SELECT ?, ?",
args: ["one", "two"],
});
expect(Array.from(rs.rows[0])).toStrictEqual(["one", "two"]);
}),
);
(!isFile ? test : test.skip)(
"?NNN arguments",
withClient(async (c) => {
const rs = await c.execute({
sql: "SELECT ?2, ?3, ?1",
args: ["one", "two", "three"],
});
expect(Array.from(rs.rows[0])).toStrictEqual([
"two",
"three",
"one",
]);
}),
);
(!isFile ? test : test.skip)(
"?NNN arguments with holes",
withClient(async (c) => {
const rs = await c.execute({
sql: "SELECT ?3, ?1",
args: ["one", "two", "three"],
});
expect(Array.from(rs.rows[0])).toStrictEqual(["three", "one"]);
}),
);
(!isFile ? test : test.skip)(
"?NNN and ? arguments",
withClient(async (c) => {
const rs = await c.execute({
sql: "SELECT ?2, ?, ?3",
args: ["one", "two", "three"],
});
expect(Array.from(rs.rows[0])).toStrictEqual([
"two",
"three",
"three",
]);
}),
);
for (const sign of [":", "@", "$"]) {
test(
`${sign}AAAA arguments`,
withClient(async (c) => {
const rs = await c.execute({
sql: `SELECT ${sign}b, ${sign}a`,
args: { a: "one", [`${sign}b`]: "two" },
});
expect(Array.from(rs.rows[0])).toStrictEqual(["two", "one"]);
}),
);
test(
`${sign}AAAA arguments used multiple times`,
withClient(async (c) => {
const rs = await c.execute({
sql: `SELECT ${sign}b, ${sign}a, ${sign}b || ${sign}a`,
args: { a: "one", [`${sign}b`]: "two" },
});
expect(Array.from(rs.rows[0])).toStrictEqual([
"two",
"one",
"twoone",
]);
}),
);
test(
`${sign}AAAA arguments and ?NNN arguments`,
withClient(async (c) => {
const rs = await c.execute({
sql: `SELECT ${sign}b, ${sign}a, ?1`,
args: { a: "one", [`${sign}b`]: "two" },
});
expect(Array.from(rs.rows[0])).toStrictEqual([
"two",
"one",
"two",
]);
}),
);
}
});
describe("batch()", () => {
test(
"multiple queries",
withClient(async (c) => {
const rss = await c.batch(
[
"SELECT 1+1",
"SELECT 1 AS one, 2 AS two",
{ sql: "SELECT ?", args: ["boomerang"] },
{ sql: "VALUES (?), (?)", args: ["big", "ben"] },
],
"read",
);
expect(rss.length).toStrictEqual(4);
const [rs0, rs1, rs2, rs3] = rss;
expect(rs0.rows.length).toStrictEqual(1);
expect(Array.from(rs0.rows[0])).toStrictEqual([2]);
expect(rs1.rows.length).toStrictEqual(1);
expect(Array.from(rs1.rows[0])).toStrictEqual([1, 2]);
expect(rs2.rows.length).toStrictEqual(1);
expect(Array.from(rs2.rows[0])).toStrictEqual(["boomerang"]);
expect(rs3.rows.length).toStrictEqual(2);
expect(Array.from(rs3.rows[0])).toStrictEqual(["big"]);
expect(Array.from(rs3.rows[1])).toStrictEqual(["ben"]);
}),
);
test(
"statements are executed sequentially",
withClient(async (c) => {
const rss = await c.batch(
[
/* 0 */ "DROP TABLE IF EXISTS t",
/* 1 */ "CREATE TABLE t (a, b)",
/* 2 */ "INSERT INTO t VALUES (1, 'one')",
/* 3 */ "SELECT * FROM t ORDER BY a",
/* 4 */ "INSERT INTO t VALUES (2, 'two')",
/* 5 */ "SELECT * FROM t ORDER BY a",
/* 6 */ "DROP TABLE t",
],
"write",
);
expect(rss.length).toStrictEqual(7);
expect(rss[3].rows).toEqual([{ a: 1, b: "one" }]);
expect(rss[5].rows).toEqual([
{ a: 1, b: "one" },
{ a: 2, b: "two" },
]);
}),
);
test(
"statements are executed in a transaction",
withClient(async (c) => {
await c.batch(
[
"DROP TABLE IF EXISTS t1",
"DROP TABLE IF EXISTS t2",
"CREATE TABLE t1 (a)",
"CREATE TABLE t2 (a)",
],
"write",
);
const n = 100;
const promises = [] as Array<any>;
for (let i = 0; i < n; ++i) {
const ii = i;
promises.push(
(async () => {
const rss = await c.batch(
[
{
sql: "INSERT INTO t1 VALUES (?)",
args: [ii],
},
{
sql: "INSERT INTO t2 VALUES (?)",
args: [ii * 10],
},
"SELECT SUM(a) FROM t1",
"SELECT SUM(a) FROM t2",
],
"write",
);
const sum1 = rss[2].rows[0][0] as number;
const sum2 = rss[3].rows[0][0] as number;
expect(sum2).toStrictEqual(sum1 * 10);
})(),
);
}
await Promise.all(promises);
const rs1 = await c.execute("SELECT SUM(a) FROM t1");
expect(rs1.rows[0][0]).toStrictEqual((n * (n - 1)) / 2);
const rs2 = await c.execute("SELECT SUM(a) FROM t2");
expect(rs2.rows[0][0]).toStrictEqual(((n * (n - 1)) / 2) * 10);
}),
10000,
);
test(
"error in batch",
withClient(async (c) => {
await expect(
c.batch(["SELECT 1+1", "SELECT foobar"], "read"),
).rejects.toBeLibsqlError();
}),
);
test(
"error in batch rolls back transaction",
withClient(async (c) => {
await c.execute("DROP TABLE IF EXISTS t");
await c.execute("CREATE TABLE t (a)");
await c.execute("INSERT INTO t VALUES ('one')");
await expect(
c.batch(
[
"INSERT INTO t VALUES ('two')",
"SELECT foobar",
"INSERT INTO t VALUES ('three')",
],
"write",
),
).rejects.toBeLibsqlError();
const rs = await c.execute("SELECT COUNT(*) FROM t");
expect(rs.rows[0][0]).toStrictEqual(1);
}),
);
test(
"batch error reports statement index - error at index 0",
withClient(async (c) => {
try {
await c.batch(
["SELECT invalid_column", "SELECT 1", "SELECT 2"],
"read",
);
throw new Error("Expected batch to fail");
} catch (e: any) {
expect(e.name).toBe("LibsqlBatchError");
expect(e.statementIndex).toBe(0);
expect(e.code).toBeDefined();
}
}),
);
test(
"batch error reports statement index - error at index 1",
withClient(async (c) => {
try {
await c.batch(
["SELECT 1", "SELECT invalid_column", "SELECT 2"],
"read",
);
throw new Error("Expected batch to fail");
} catch (e: any) {
expect(e.name).toBe("LibsqlBatchError");
expect(e.statementIndex).toBe(1);
expect(e.code).toBeDefined();
}
}),
);
test(
"batch error reports statement index - error at index 2",
withClient(async (c) => {
try {
await c.batch(
["SELECT 1", "SELECT 2", "SELECT invalid_column"],
"read",
);
throw new Error("Expected batch to fail");
} catch (e: any) {
expect(e.name).toBe("LibsqlBatchError");
expect(e.statementIndex).toBe(2);
expect(e.code).toBeDefined();
}
}),
);
test(
"batch error with write mode reports statement index",
withClient(async (c) => {
await c.execute("DROP TABLE IF EXISTS t");
await c.execute("CREATE TABLE t (a UNIQUE)");
await c.execute("INSERT INTO t VALUES (1)");
try {
await c.batch(
[
"INSERT INTO t VALUES (2)",
"INSERT INTO t VALUES (3)",
"INSERT INTO t VALUES (1)", // Duplicate, will fail
"INSERT INTO t VALUES (4)",
],
"write",
);
throw new Error("Expected batch to fail");
} catch (e: any) {
expect(e.name).toBe("LibsqlBatchError");
expect(e.statementIndex).toBe(2);
expect(e.code).toBeDefined();
}
// Verify rollback happened
const rs = await c.execute("SELECT COUNT(*) FROM t");
expect(rs.rows[0][0]).toBe(1);
}),
);
test(
"batch error in in-memory database reports statement index",
withInMemoryClient(async (c) => {
await c.execute("CREATE TABLE t (a)");
try {
await c.batch(
[
"INSERT INTO t VALUES (1)",
"SELECT invalid_column FROM t",
"INSERT INTO t VALUES (2)",
],
"write",
);
throw new Error("Expected batch to fail");
} catch (e: any) {
expect(e.name).toBe("LibsqlBatchError");
expect(e.statementIndex).toBe(1);
expect(e.code).toBeDefined();
}
}),
);
test(
"batch with a lot of different statements",
withClient(async (c) => {
const stmts = [] as Array<any>;
for (let i = 0; i < 1000; ++i) {
stmts.push(`SELECT ${i}`);
}
const rss = await c.batch(stmts, "read");
for (let i = 0; i < stmts.length; ++i) {
expect(rss[i].rows[0][0]).toStrictEqual(i);
}
}),