forked from porsager/postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2598 lines (2163 loc) · 65.7 KB
/
index.js
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 { exec } from './bootstrap.js'
import { t, nt, ot } from './test.js' // eslint-disable-line
import net from 'net'
import fs from 'fs'
import crypto from 'crypto'
import postgres from '../src/index.js'
const delay = ms => new Promise(r => setTimeout(r, ms))
const rel = x => new URL(x, import.meta.url)
const idle_timeout = 1
const login = {
user: 'postgres_js_test'
}
const login_md5 = {
user: 'postgres_js_test_md5',
pass: 'postgres_js_test_md5'
}
const login_scram = {
user: 'postgres_js_test_scram',
pass: 'postgres_js_test_scram'
}
const options = {
db: 'postgres_js_test',
user: login.user,
pass: login.pass,
idle_timeout,
connect_timeout: 1,
max: 1
}
const sql = postgres(options)
t('Connects with no options', async() => {
const sql = postgres({ max: 1 })
const result = (await sql`select 1 as x`)[0].x
await sql.end()
return [1, result]
})
t('Uses default database without slash', async() => {
const sql = postgres('postgres://localhost')
return [sql.options.user, sql.options.database]
})
t('Uses default database with slash', async() => {
const sql = postgres('postgres://localhost/')
return [sql.options.user, sql.options.database]
})
t('Result is array', async() =>
[true, Array.isArray(await sql`select 1`)]
)
t('Result has count', async() =>
[1, (await sql`select 1`).count]
)
t('Result has command', async() =>
['SELECT', (await sql`select 1`).command]
)
t('Create table', async() =>
['CREATE TABLE', (await sql`create table test(int int)`).command, await sql`drop table test`]
)
t('Drop table', { timeout: 2 }, async() => {
await sql`create table test(int int)`
return ['DROP TABLE', (await sql`drop table test`).command]
})
t('null', async() =>
[null, (await sql`select ${ null } as x`)[0].x]
)
t('Integer', async() =>
['1', (await sql`select ${ 1 } as x`)[0].x]
)
t('String', async() =>
['hello', (await sql`select ${ 'hello' } as x`)[0].x]
)
t('Boolean false', async() =>
[false, (await sql`select ${ false } as x`)[0].x]
)
t('Boolean[] [true, false]', async() =>
["[true,false]", JSON.stringify((await sql`select ${ [true, false] }::bool[] as x`)[0].x)]
)
t('Number[] [1, 2]', async() =>
["[1,2]", JSON.stringify((await sql`select ${ [1, 2] }::int4[] as x`)[0].x)]
)
t('String[] ["a", "b"]', async() =>
['["a","b"]', JSON.stringify((await sql`select ${ ["a", "b"] }::text[] as x`)[0].x)]
)
t('BigInt[] [BigInt(1), BigInt(2)]', async() =>
['[1,2]', JSON.stringify((await sql`select ${ [BigInt(1), BigInt(2)] }::float4[] as x`)[0].x)]
)
t('Boolean true', async() =>
[true, (await sql`select ${ true } as x`)[0].x]
)
t('Date', async() => {
const now = new Date()
return [0, now - (await sql`select ${ now } as x`)[0].x]
})
t('Json', async() => {
const x = (await sql`select ${ sql.json({ a: 'hello', b: 42 }) } as x`)[0].x
return ['hello,42', [x.a, x.b].join()]
})
t('implicit json', async() => {
const x = (await sql`select ${ { a: 'hello', b: 42 } }::json as x`)[0].x
return ['hello,42', [x.a, x.b].join()]
})
t('implicit jsonb', async() => {
const x = (await sql`select ${ { a: 'hello', b: 42 } }::jsonb as x`)[0].x
return ['hello,42', [x.a, x.b].join()]
})
t('Empty array', async() =>
[true, Array.isArray((await sql`select ${ sql.array([], 1009) } as x`)[0].x)]
)
t('String array', async() =>
['123', (await sql`select ${ '{1,2,3}' }::int[] as x`)[0].x.join('')]
)
t('Array of Integer', async() =>
[3, (await sql`select ${ sql.array([1, 2, 3]) } as x`)[0].x[2]]
)
t('Array of String', async() =>
['c', (await sql`select ${ sql.array(['a', 'b', 'c']) } as x`)[0].x[2]]
)
t('Array of Date', async() => {
const now = new Date()
return [now.getTime(), (await sql`select ${ sql.array([now, now, now]) } as x`)[0].x[2].getTime()]
})
t('Array of Box', async() => [
'(3,4),(1,2);(6,7),(4,5)',
(await sql`select ${ '{(1,2),(3,4);(4,5),(6,7)}' }::box[] as x`)[0].x.join(';')
])
t('Nested array n2', async() =>
[4, (await sql`select ${ sql.array([[1, 2], [3, 4]]) } as x`)[0].x[1][1]]
)
t('Nested array n3', async() =>
[6, (await sql`select ${ sql.array([[[1, 2]], [[3, 4]], [[5, 6]]]) } as x`)[0].x[2][0][1]]
)
t('Escape in arrays', async() =>
['Hello "you",c:\\windows', (await sql`select ${ sql.array(['Hello "you"', 'c:\\windows']) } as x`)[0].x.join(',')]
)
t('Escapes', async() => {
return ['hej"hej', Object.keys((await sql`select 1 as ${ sql('hej"hej') }`)[0])[0]]
})
t('null for int', async() => {
await sql`create table test (x int)`
return [1, (await sql`insert into test values(${ null })`).count, await sql`drop table test`]
})
t('Throws on illegal transactions', async() => {
const sql = postgres({ ...options, max: 2, fetch_types: false })
const error = await sql`begin`.catch(e => e)
return [
error.code,
'UNSAFE_TRANSACTION'
]
})
t('Transaction throws', async() => {
await sql`create table test (a int)`
return ['22P02', await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql`insert into test values('hej')`
}).catch(x => x.code), await sql`drop table test`]
})
t('Transaction rolls back', async() => {
await sql`create table test (a int)`
await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql`insert into test values('hej')`
}).catch(() => { /* ignore */ })
return [0, (await sql`select a from test`).count, await sql`drop table test`]
})
t('Transaction throws on uncaught savepoint', async() => {
await sql`create table test (a int)`
return ['fail', (await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql.savepoint(async sql => {
await sql`insert into test values(2)`
throw new Error('fail')
})
}).catch((err) => err.message)), await sql`drop table test`]
})
t('Transaction throws on uncaught named savepoint', async() => {
await sql`create table test (a int)`
return ['fail', (await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql.savepoit('watpoint', async sql => {
await sql`insert into test values(2)`
throw new Error('fail')
})
}).catch(() => 'fail')), await sql`drop table test`]
})
t('Transaction succeeds on caught savepoint', async() => {
await sql`create table test (a int)`
await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql.savepoint(async sql => {
await sql`insert into test values(2)`
throw new Error('please rollback')
}).catch(() => { /* ignore */ })
await sql`insert into test values(3)`
})
return ['2', (await sql`select count(1) from test`)[0].count, await sql`drop table test`]
})
t('Savepoint returns Result', async() => {
let result
await sql.begin(async sql => {
result = await sql.savepoint(sql =>
sql`select 1 as x`
)
})
return [1, result[0].x]
})
t('Prepared transaction', async() => {
await sql`create table test (a int)`
await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql.prepare('tx1')
})
await sql`commit prepared 'tx1'`
return ['1', (await sql`select count(1) from test`)[0].count, await sql`drop table test`]
})
t('Transaction requests are executed implicitly', async() => {
const sql = postgres({ debug: true, idle_timeout: 1, fetch_types: false })
return [
'testing',
(await sql.begin(sql => [
sql`select set_config('postgres_js.test', 'testing', true)`,
sql`select current_setting('postgres_js.test') as x`
]))[1][0].x
]
})
t('Uncaught transaction request errors bubbles to transaction', async() => [
'42703',
(await sql.begin(sql => [
sql`select wat`,
sql`select current_setting('postgres_js.test') as x, ${ 1 } as a`
]).catch(e => e.code))
])
t('Fragments in transactions', async() => [
true,
(await sql.begin(sql => sql`select true as x where ${ sql`1=1` }`))[0].x
])
t('Transaction rejects with rethrown error', async() => [
'WAT',
await sql.begin(async sql => {
try {
await sql`select exception`
} catch (ex) {
throw new Error('WAT')
}
}).catch(e => e.message)
])
t('Parallel transactions', async() => {
await sql`create table test (a int)`
return ['11', (await Promise.all([
sql.begin(sql => sql`select 1`),
sql.begin(sql => sql`select 1`)
])).map(x => x.count).join(''), await sql`drop table test`]
})
t('Many transactions at beginning of connection', async() => {
const sql = postgres(options)
const xs = await Promise.all(Array.from({ length: 100 }, () => sql.begin(sql => sql`select 1`)))
return [100, xs.length]
})
t('Transactions array', async() => {
await sql`create table test (a int)`
return ['11', (await sql.begin(sql => [
sql`select 1`.then(x => x),
sql`select 1`
])).map(x => x.count).join(''), await sql`drop table test`]
})
t('Transaction waits', async() => {
await sql`create table test (a int)`
await sql.begin(async sql => {
await sql`insert into test values(1)`
await sql.savepoint(async sql => {
await sql`insert into test values(2)`
throw new Error('please rollback')
}).catch(() => { /* ignore */ })
await sql`insert into test values(3)`
})
return ['11', (await Promise.all([
sql.begin(sql => sql`select 1`),
sql.begin(sql => sql`select 1`)
])).map(x => x.count).join(''), await sql`drop table test`]
})
t('Helpers in Transaction', async() => {
return ['1', (await sql.begin(async sql =>
await sql`select ${ sql({ x: 1 }) }`
))[0].x]
})
t('Undefined values throws', async() => {
let error
await sql`
select ${ undefined } as x
`.catch(x => error = x.code)
return ['UNDEFINED_VALUE', error]
})
t('Transform undefined', async() => {
const sql = postgres({ ...options, transform: { undefined: null } })
return [null, (await sql`select ${ undefined } as x`)[0].x]
})
t('Transform undefined in array', async() => {
const sql = postgres({ ...options, transform: { undefined: null } })
return [null, (await sql`select * from (values ${ sql([undefined, undefined]) }) as x(x, y)`)[0].y]
})
t('Null sets to null', async() =>
[null, (await sql`select ${ null } as x`)[0].x]
)
t('Throw syntax error', async() =>
['42601', (await sql`wat 1`.catch(x => x)).code]
)
t('Connect using uri', async() =>
[true, await new Promise((resolve, reject) => {
const sql = postgres('postgres://' + login.user + ':' + (login.pass || '') + '@localhost:5432/' + options.db, {
idle_timeout
})
sql`select 1`.then(() => resolve(true), reject)
})]
)
t('Options from uri with special characters in user and pass', async() => {
const opt = postgres({ user: 'öla', pass: 'pass^word' }).options
return [[opt.user, opt.pass].toString(), 'öla,pass^word']
})
t('Fail with proper error on no host', async() =>
['ECONNREFUSED', (await new Promise((resolve, reject) => {
const sql = postgres('postgres://localhost:33333/' + options.db, {
idle_timeout
})
sql`select 1`.then(reject, resolve)
})).code]
)
t('Connect using SSL', async() =>
[true, (await new Promise((resolve, reject) => {
postgres({
ssl: { rejectUnauthorized: false },
idle_timeout
})`select 1`.then(() => resolve(true), reject)
}))]
)
t('Connect using SSL require', async() =>
[true, (await new Promise((resolve, reject) => {
postgres({
ssl: 'require',
idle_timeout
})`select 1`.then(() => resolve(true), reject)
}))]
)
t('Connect using SSL prefer', async() => {
await exec('psql', ['-c', 'alter system set ssl=off'])
await exec('psql', ['-c', 'select pg_reload_conf()'])
const sql = postgres({
ssl: 'prefer',
idle_timeout
})
return [
1, (await sql`select 1 as x`)[0].x,
await exec('psql', ['-c', 'alter system set ssl=on']),
await exec('psql', ['-c', 'select pg_reload_conf()'])
]
})
t('Reconnect using SSL', { timeout: 2 }, async() => {
const sql = postgres({
ssl: 'require',
idle_timeout: 0.1
})
await sql`select 1`
await delay(200)
return [1, (await sql`select 1 as x`)[0].x]
})
t('Login without password', async() => {
return [true, (await postgres({ ...options, ...login })`select true as x`)[0].x]
})
t('Login using MD5', async() => {
return [true, (await postgres({ ...options, ...login_md5 })`select true as x`)[0].x]
})
t('Login using scram-sha-256', async() => {
return [true, (await postgres({ ...options, ...login_scram })`select true as x`)[0].x]
})
t('Parallel connections using scram-sha-256', {
timeout: 2
}, async() => {
const sql = postgres({ ...options, ...login_scram })
return [true, (await Promise.all([
sql`select true as x, pg_sleep(0.01)`,
sql`select true as x, pg_sleep(0.01)`,
sql`select true as x, pg_sleep(0.01)`
]))[0][0].x]
})
t('Support dynamic password function', async() => {
return [true, (await postgres({
...options,
...login_scram,
pass: () => 'postgres_js_test_scram'
})`select true as x`)[0].x]
})
t('Support dynamic async password function', async() => {
return [true, (await postgres({
...options,
...login_scram,
pass: () => Promise.resolve('postgres_js_test_scram')
})`select true as x`)[0].x]
})
t('Point type', async() => {
const sql = postgres({
...options,
types: {
point: {
to: 600,
from: [600],
serialize: ([x, y]) => '(' + x + ',' + y + ')',
parse: (x) => x.slice(1, -1).split(',').map(x => +x)
}
}
})
await sql`create table test (x point)`
await sql`insert into test (x) values (${ sql.types.point([10, 20]) })`
return [20, (await sql`select x from test`)[0].x[1], await sql`drop table test`]
})
t('Point type array', async() => {
const sql = postgres({
...options,
types: {
point: {
to: 600,
from: [600],
serialize: ([x, y]) => '(' + x + ',' + y + ')',
parse: (x) => x.slice(1, -1).split(',').map(x => +x)
}
}
})
await sql`create table test (x point[])`
await sql`insert into test (x) values (${ sql.array([sql.types.point([10, 20]), sql.types.point([20, 30])]) })`
return [30, (await sql`select x from test`)[0].x[1][1], await sql`drop table test`]
})
t('sql file', async() =>
[1, (await sql.file(rel('select.sql')))[0].x]
)
t('sql file has forEach', async() => {
let result
await sql
.file(rel('select.sql'), { cache: false })
.forEach(({ x }) => result = x)
return [1, result]
})
t('sql file throws', async() =>
['ENOENT', (await sql.file(rel('selectomondo.sql')).catch(x => x.code))]
)
t('sql file cached', async() => {
await sql.file(rel('select.sql'))
await delay(20)
return [1, (await sql.file(rel('select.sql')))[0].x]
})
t('Parameters in file', async() => {
const result = await sql.file(
rel('select-param.sql'),
['hello']
)
return ['hello', result[0].x]
})
t('Connection ended promise', async() => {
const sql = postgres(options)
await sql.end()
return [undefined, await sql.end()]
})
t('Connection ended timeout', async() => {
const sql = postgres(options)
await sql.end({ timeout: 10 })
return [undefined, await sql.end()]
})
t('Connection ended error', async() => {
const sql = postgres(options)
await sql.end()
return ['CONNECTION_ENDED', (await sql``.catch(x => x.code))]
})
t('Connection end does not cancel query', async() => {
const sql = postgres(options)
const promise = sql`select 1 as x`.execute()
await sql.end()
return [1, (await promise)[0].x]
})
t('Connection destroyed', async() => {
const sql = postgres(options)
process.nextTick(() => sql.end({ timeout: 0 }))
return ['CONNECTION_DESTROYED', await sql``.catch(x => x.code)]
})
t('Connection destroyed with query before', async() => {
const sql = postgres(options)
, error = sql`select pg_sleep(0.2)`.catch(err => err.code)
sql.end({ timeout: 0 })
return ['CONNECTION_DESTROYED', await error]
})
t('transform column', async() => {
const sql = postgres({
...options,
transform: { column: x => x.split('').reverse().join('') }
})
await sql`create table test (hello_world int)`
await sql`insert into test values (1)`
return ['dlrow_olleh', Object.keys((await sql`select * from test`)[0])[0], await sql`drop table test`]
})
t('column toPascal', async() => {
const sql = postgres({
...options,
transform: { column: postgres.toPascal }
})
await sql`create table test (hello_world int)`
await sql`insert into test values (1)`
return ['HelloWorld', Object.keys((await sql`select * from test`)[0])[0], await sql`drop table test`]
})
t('column toCamel', async() => {
const sql = postgres({
...options,
transform: { column: postgres.toCamel }
})
await sql`create table test (hello_world int)`
await sql`insert into test values (1)`
return ['helloWorld', Object.keys((await sql`select * from test`)[0])[0], await sql`drop table test`]
})
t('column toKebab', async() => {
const sql = postgres({
...options,
transform: { column: postgres.toKebab }
})
await sql`create table test (hello_world int)`
await sql`insert into test values (1)`
return ['hello-world', Object.keys((await sql`select * from test`)[0])[0], await sql`drop table test`]
})
t('Transform nested json in arrays', async() => {
const sql = postgres({
...options,
transform: postgres.camel
})
return ['aBcD', (await sql`select '[{"a_b":1},{"c_d":2}]'::jsonb as x`)[0].x.map(Object.keys).join('')]
})
t('Transform deeply nested json object in arrays', async() => {
const sql = postgres({
...options,
transform: postgres.camel
})
return [
'childObj_deeplyNestedObj_grandchildObj',
(await sql`
select '[{"nested_obj": {"child_obj": 2, "deeply_nested_obj": {"grandchild_obj": 3}}}]'::jsonb as x
`)[0].x.map(x => {
let result
for (const key in x)
result = [...Object.keys(x[key]), ...Object.keys(x[key].deeplyNestedObj)]
return result
})[0]
.join('_')
]
})
t('Transform deeply nested json array in arrays', async() => {
const sql = postgres({
...options,
transform: postgres.camel
})
return [
'childArray_deeplyNestedArray_grandchildArray',
(await sql`
select '[{"nested_array": [{"child_array": 2, "deeply_nested_array": [{"grandchild_array":3}]}]}]'::jsonb AS x
`)[0].x.map((x) => {
let result
for (const key in x)
result = [...Object.keys(x[key][0]), ...Object.keys(x[key][0].deeplyNestedArray[0])]
return result
})[0]
.join('_')
]
})
t('Bypass transform for json primitive', async() => {
const sql = postgres({
...options,
transform: postgres.camel
})
const x = (
await sql`select 'null'::json as a, 'false'::json as b, '"a"'::json as c, '1'::json as d`
)[0]
return [
JSON.stringify({ a: null, b: false, c: 'a', d: 1 }),
JSON.stringify(x)
]
})
t('Bypass transform for jsonb primitive', async() => {
const sql = postgres({
...options,
transform: postgres.camel
})
const x = (
await sql`select 'null'::jsonb as a, 'false'::jsonb as b, '"a"'::jsonb as c, '1'::jsonb as d`
)[0]
return [
JSON.stringify({ a: null, b: false, c: 'a', d: 1 }),
JSON.stringify(x)
]
})
t('unsafe', async() => {
await sql`create table test (x int)`
return [1, (await sql.unsafe('insert into test values ($1) returning *', [1]))[0].x, await sql`drop table test`]
})
t('unsafe simple', async() => {
return [1, (await sql.unsafe('select 1 as x'))[0].x]
})
t('unsafe simple includes columns', async() => {
return ['x', (await sql.unsafe('select 1 as x').values()).columns[0].name]
})
t('unsafe describe', async() => {
const q = 'insert into test values (1)'
await sql`create table test(a int unique)`
await sql.unsafe(q).describe()
const x = await sql.unsafe(q).describe()
return [
q,
x.string,
await sql`drop table test`
]
})
t('simple query using unsafe with multiple statements', async() => {
return [
'1,2',
(await sql.unsafe('select 1 as x;select 2 as x')).map(x => x[0].x).join()
]
})
t('simple query using simple() with multiple statements', async() => {
return [
'1,2',
(await sql`select 1 as x;select 2 as x`.simple()).map(x => x[0].x).join()
]
})
t('listen and notify', async() => {
const sql = postgres(options)
const channel = 'hello'
const result = await new Promise(async r => {
await sql.listen(channel, r)
sql.notify(channel, 'works')
})
return [
'works',
result,
sql.end()
]
})
t('double listen', async() => {
const sql = postgres(options)
, channel = 'hello'
let count = 0
await new Promise((resolve, reject) =>
sql.listen(channel, resolve)
.then(() => sql.notify(channel, 'world'))
.catch(reject)
).then(() => count++)
await new Promise((resolve, reject) =>
sql.listen(channel, resolve)
.then(() => sql.notify(channel, 'world'))
.catch(reject)
).then(() => count++)
// for coverage
sql.listen('weee', () => { /* noop */ }).then(sql.end)
return [2, count]
})
t('multiple listeners work after a reconnect', async() => {
const sql = postgres(options)
, xs = []
const s1 = await sql.listen('test', x => xs.push('1', x))
await sql.listen('test', x => xs.push('2', x))
await sql.notify('test', 'a')
await delay(50)
await sql`select pg_terminate_backend(${ s1.state.pid })`
await delay(200)
await sql.notify('test', 'b')
await delay(50)
sql.end()
return ['1a2a1b2b', xs.join('')]
})
t('listen and notify with weird name', async() => {
const sql = postgres(options)
const channel = 'wat-;.ø.§'
const result = await new Promise(async r => {
const { unlisten } = await sql.listen(channel, r)
sql.notify(channel, 'works')
await delay(50)
await unlisten()
})
return [
'works',
result,
sql.end()
]
})
t('listen and notify with upper case', async() => {
const sql = postgres(options)
const channel = 'withUpperChar'
const result = await new Promise(async r => {
await sql.listen(channel, r)
sql.notify(channel, 'works')
})
return [
'works',
result,
sql.end()
]
})
t('listen reconnects', { timeout: 2 }, async() => {
const sql = postgres(options)
, resolvers = {}
, a = new Promise(r => resolvers.a = r)
, b = new Promise(r => resolvers.b = r)
let connects = 0
const { state: { pid } } = await sql.listen(
'test',
x => x in resolvers && resolvers[x](),
() => connects++
)
await sql.notify('test', 'a')
await a
await sql`select pg_terminate_backend(${ pid })`
await delay(100)
await sql.notify('test', 'b')
await b
sql.end()
return [connects, 2]
})
t('listen result reports correct connection state after reconnection', async() => {
const sql = postgres(options)
, xs = []
const result = await sql.listen('test', x => xs.push(x))
const initialPid = result.state.pid
await sql.notify('test', 'a')
await sql`select pg_terminate_backend(${ initialPid })`
await delay(50)
sql.end()
return [result.state.pid !== initialPid, true]
})
t('unlisten removes subscription', async() => {
const sql = postgres(options)
, xs = []
const { unlisten } = await sql.listen('test', x => xs.push(x))
await sql.notify('test', 'a')
await delay(50)
await unlisten()
await sql.notify('test', 'b')
await delay(50)
sql.end()
return ['a', xs.join('')]
})
t('listen after unlisten', async() => {
const sql = postgres(options)
, xs = []
const { unlisten } = await sql.listen('test', x => xs.push(x))
await sql.notify('test', 'a')
await delay(50)
await unlisten()
await sql.notify('test', 'b')
await delay(50)
await sql.listen('test', x => xs.push(x))
await sql.notify('test', 'c')
await delay(50)
sql.end()
return ['ac', xs.join('')]
})
t('multiple listeners and unlisten one', async() => {
const sql = postgres(options)
, xs = []
await sql.listen('test', x => xs.push('1', x))
const s2 = await sql.listen('test', x => xs.push('2', x))
await sql.notify('test', 'a')
await delay(50)
await s2.unlisten()
await sql.notify('test', 'b')
await delay(50)
sql.end()
return ['1a2a1b', xs.join('')]
})
t('responds with server parameters (application_name)', async() =>
['postgres.js', await new Promise((resolve, reject) => postgres({
...options,
onparameter: (k, v) => k === 'application_name' && resolve(v)
})`select 1`.catch(reject))]
)
t('has server parameters', async() => {
return ['postgres.js', (await sql`select 1`.then(() => sql.parameters.application_name))]
})
t('big query body', { timeout: 2 }, async() => {
await sql`create table test (x int)`
return [50000, (await sql`insert into test ${
sql([...Array(50000).keys()].map(x => ({ x })))
}`).count, await sql`drop table test`]
})
t('Throws if more than 65534 parameters', async() => {
await sql`create table test (x int)`
return ['MAX_PARAMETERS_EXCEEDED', (await sql`insert into test ${
sql([...Array(65535).keys()].map(x => ({ x })))
}`.catch(e => e.code)), await sql`drop table test`]
})
t('let postgres do implicit cast of unknown types', async() => {
await sql`create table test (x timestamp with time zone)`
const [{ x }] = await sql`insert into test values (${ new Date().toISOString() }) returning *`
return [true, x instanceof Date, await sql`drop table test`]
})
t('only allows one statement', async() =>
['42601', await sql`select 1; select 2`.catch(e => e.code)]
)
t('await sql() throws not tagged error', async() => {
let error
try {
await sql('select 1')
} catch (e) {
error = e.code
}
return ['NOT_TAGGED_CALL', error]
})
t('sql().then throws not tagged error', async() => {
let error
try {
sql('select 1').then(() => { /* noop */ })
} catch (e) {
error = e.code
}
return ['NOT_TAGGED_CALL', error]
})
t('sql().catch throws not tagged error', async() => {
let error
try {
await sql('select 1')
} catch (e) {
error = e.code
}
return ['NOT_TAGGED_CALL', error]
})