forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresNIOTests.swift
1444 lines (1322 loc) · 63.5 KB
/
PostgresNIOTests.swift
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 Logging
@testable import PostgresNIO
import XCTest
import NIOCore
import NIOPosix
import NIOTestUtils
import NIOSSL
final class PostgresNIOTests: XCTestCase {
private var group: EventLoopGroup!
private var eventLoop: EventLoop { self.group.next() }
override func setUpWithError() throws {
try super.setUpWithError()
XCTAssertTrue(isLoggingConfigured)
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
}
override func tearDownWithError() throws {
try self.group?.syncShutdownGracefully()
self.group = nil
try super.tearDownWithError()
}
// MARK: Tests
func testConnectAndClose() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
XCTAssertNoThrow(try conn?.close().wait())
}
func testConnectUDSAndClose() throws {
try XCTSkipUnless(env("POSTGRES_SOCKET") != nil)
let conn = try PostgresConnection.testUDS(on: eventLoop).wait()
try conn.close().wait()
}
func testConnectEstablishedChannelAndClose() throws {
let channel = try ClientBootstrap(group: self.group).connect(to: PostgresConnection.address()).wait()
let conn = try PostgresConnection.testChannel(channel, on: self.eventLoop).wait()
try conn.close().wait()
}
func testSimpleQueryVersion() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: [PostgresRow]?
XCTAssertNoThrow(rows = try conn?.simpleQuery("SELECT version()").wait())
XCTAssertEqual(rows?.count, 1)
XCTAssertEqual(try rows?.first?.decode(String.self, context: .default).contains("PostgreSQL"), true)
}
func testSimpleQueryVersionUsingUDS() throws {
try XCTSkipUnless(env("POSTGRES_SOCKET") != nil)
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.testUDS(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: [PostgresRow]?
XCTAssertNoThrow(rows = try conn?.simpleQuery("SELECT version()").wait())
XCTAssertEqual(rows?.count, 1)
XCTAssertEqual(try rows?.first?.decode(String.self, context: .default).contains("PostgreSQL"), true)
}
func testSimpleQueryVersionUsingEstablishedChannel() throws {
let channel = try ClientBootstrap(group: self.group).connect(to: PostgresConnection.address()).wait()
let conn = try PostgresConnection.testChannel(channel, on: self.eventLoop).wait()
defer { XCTAssertNoThrow(try conn.close().wait()) }
let rows = try conn.simpleQuery("SELECT version()").wait()
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(try rows.first?.decode(String.self, context: .default).contains("PostgreSQL"), true)
}
func testQueryVersion() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("SELECT version()", .init()).wait())
XCTAssertEqual(rows?.count, 1)
XCTAssertEqual(try rows?.first?.decode(String.self, context: .default).contains("PostgreSQL"), true)
}
func testQuerySelectParameter() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("SELECT $1::TEXT as foo", ["hello"]).wait())
XCTAssertEqual(rows?.count, 1)
XCTAssertEqual(try rows?.first?.decode(String.self, context: .default), "hello")
}
func testSQLError() throws {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
XCTAssertThrowsError(_ = try conn?.simpleQuery("SELECT &").wait()) { error in
XCTAssertEqual((error as? PostgresError)?.code, .syntaxError)
}
}
func testNotificationsEmptyPayload() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var receivedNotifications: [PostgresMessage.NotificationResponse] = []
conn?.addListener(channel: "example") { context, notification in
receivedNotifications.append(notification)
}
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
// Notifications are asynchronous, so we should run at least one more query to make sure we'll have received the notification response by then
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
XCTAssertEqual(receivedNotifications.count, 1)
XCTAssertEqual(receivedNotifications.first?.channel, "example")
XCTAssertEqual(receivedNotifications.first?.payload, "")
}
func testNotificationsNonEmptyPayload() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var receivedNotifications: [PostgresMessage.NotificationResponse] = []
conn?.addListener(channel: "example") { context, notification in
receivedNotifications.append(notification)
}
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example, 'Notification payload example'").wait())
// Notifications are asynchronous, so we should run at least one more query to make sure we'll have received the notification response by then
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
XCTAssertEqual(receivedNotifications.count, 1)
XCTAssertEqual(receivedNotifications.first?.channel, "example")
XCTAssertEqual(receivedNotifications.first?.payload, "Notification payload example")
}
func testNotificationsRemoveHandlerWithinHandler() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var receivedNotifications = 0
conn?.addListener(channel: "example") { context, notification in
receivedNotifications += 1
context.stop()
}
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
XCTAssertEqual(receivedNotifications, 1)
}
func testNotificationsRemoveHandlerOutsideHandler() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var receivedNotifications = 0
let context = conn?.addListener(channel: "example") { context, notification in
receivedNotifications += 1
}
XCTAssertNotNil(context)
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
context?.stop()
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
XCTAssertEqual(receivedNotifications, 1)
}
func testNotificationsMultipleRegisteredHandlers() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var receivedNotifications1 = 0
conn?.addListener(channel: "example") { context, notification in
receivedNotifications1 += 1
}
var receivedNotifications2 = 0
conn?.addListener(channel: "example") { context, notification in
receivedNotifications2 += 1
}
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
XCTAssertEqual(receivedNotifications1, 1)
XCTAssertEqual(receivedNotifications2, 1)
}
func testNotificationsMultipleRegisteredHandlersRemoval() throws {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var receivedNotifications1 = 0
XCTAssertNotNil(conn?.addListener(channel: "example") { context, notification in
receivedNotifications1 += 1
context.stop()
})
var receivedNotifications2 = 0
XCTAssertNotNil(conn?.addListener(channel: "example") { context, notification in
receivedNotifications2 += 1
})
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY example").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
XCTAssertEqual(receivedNotifications1, 1)
XCTAssertEqual(receivedNotifications2, 2)
}
func testNotificationHandlerFiltersOnChannel() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
XCTAssertNotNil(conn?.addListener(channel: "desired") { context, notification in
XCTFail("Received notification on channel that handler was not registered for")
})
XCTAssertNoThrow(_ = try conn?.simpleQuery("LISTEN undesired").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("NOTIFY undesired").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("SELECT 1").wait())
}
func testSelectTypes() throws {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var results: [PostgresRow]?
XCTAssertNoThrow(results = try conn?.simpleQuery("SELECT * FROM pg_type").wait())
XCTAssert((results?.count ?? 0) > 350, "Results count not large enough")
}
func testSelectType() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var results: [PostgresRow]?
XCTAssertNoThrow(results = try conn?.simpleQuery("SELECT * FROM pg_type WHERE typname = 'float8'").wait())
// [
// "typreceive": "float8recv",
// "typelem": "0",
// "typarray": "1022",
// "typalign": "d",
// "typanalyze": "-",
// "typtypmod": "-1",
// "typname": "float8",
// "typnamespace": "11",
// "typdefault": "<null>",
// "typdefaultbin": "<null>",
// "typcollation": "0",
// "typispreferred": "t",
// "typrelid": "0",
// "typbyval": "t",
// "typnotnull": "f",
// "typinput": "float8in",
// "typlen": "8",
// "typcategory": "N",
// "typowner": "10",
// "typtype": "b",
// "typdelim": ",",
// "typndims": "0",
// "typbasetype": "0",
// "typacl": "<null>",
// "typisdefined": "t",
// "typmodout": "-",
// "typmodin": "-",
// "typsend": "float8send",
// "typstorage": "p",
// "typoutput": "float8out"
// ]
XCTAssertEqual(results?.count, 1)
let row = results?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "typname"].string, "float8")
XCTAssertEqual(row?[data: "typnamespace"].int, 11)
XCTAssertEqual(row?[data: "typowner"].int, 10)
XCTAssertEqual(row?[data: "typlen"].int, 8)
}
func testIntegers() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
struct Integers: Decodable {
let smallint: Int16
let smallint_min: Int16
let smallint_max: Int16
let int: Int32
let int_min: Int32
let int_max: Int32
let bigint: Int64
let bigint_min: Int64
let bigint_max: Int64
}
var results: PostgresQueryResult?
XCTAssertNoThrow(results = try conn?.query("""
SELECT
1::SMALLINT as smallint,
-32767::SMALLINT as smallint_min,
32767::SMALLINT as smallint_max,
1::INT as int,
-2147483647::INT as int_min,
2147483647::INT as int_max,
1::BIGINT as bigint,
-9223372036854775807::BIGINT as bigint_min,
9223372036854775807::BIGINT as bigint_max
""").wait())
XCTAssertEqual(results?.count, 1)
let row = results?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "smallint"].int16, 1)
XCTAssertEqual(row?[data: "smallint_min"].int16, -32_767)
XCTAssertEqual(row?[data: "smallint_max"].int16, 32_767)
XCTAssertEqual(row?[data: "int"].int32, 1)
XCTAssertEqual(row?[data: "int_min"].int32, -2_147_483_647)
XCTAssertEqual(row?[data: "int_max"].int32, 2_147_483_647)
XCTAssertEqual(row?[data: "bigint"].int64, 1)
XCTAssertEqual(row?[data: "bigint_min"].int64, -9_223_372_036_854_775_807)
XCTAssertEqual(row?[data: "bigint_max"].int64, 9_223_372_036_854_775_807)
}
func testPi() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
struct Pi: Decodable {
let text: String
let numeric_string: String
let numeric_decimal: Decimal
let double: Double
let float: Float
}
var results: PostgresQueryResult?
XCTAssertNoThrow(results = try conn?.query("""
SELECT
pi()::TEXT as text,
pi()::NUMERIC as numeric_string,
pi()::NUMERIC as numeric_decimal,
pi()::FLOAT8 as double,
pi()::FLOAT4 as float
""").wait())
XCTAssertEqual(results?.count, 1)
let row = results?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "text"].string?.hasPrefix("3.14159265"), true)
XCTAssertEqual(row?[data: "numeric_string"].string?.hasPrefix("3.14159265"), true)
XCTAssertTrue(row?[data: "numeric_decimal"].decimal?.isLess(than: 3.14159265358980) ?? false)
XCTAssertFalse(row?[data: "numeric_decimal"].decimal?.isLess(than: 3.14159265358978) ?? true)
XCTAssertTrue(row?[data: "double"].double?.description.hasPrefix("3.141592") ?? false)
XCTAssertTrue(row?[data: "float"].float?.description.hasPrefix("3.141592") ?? false)
}
func testUUID() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
struct Model: Decodable {
let id: UUID
let string: String
}
var results: PostgresQueryResult?
XCTAssertNoThrow(results = try conn?.query("""
SELECT
'123e4567-e89b-12d3-a456-426655440000'::UUID as id,
'123e4567-e89b-12d3-a456-426655440000'::UUID as string
""").wait())
XCTAssertEqual(results?.count, 1)
let row = results?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "id"].uuid, UUID(uuidString: "123E4567-E89B-12D3-A456-426655440000"))
XCTAssertEqual(UUID(uuidString: row?[data: "id"].string ?? ""), UUID(uuidString: "123E4567-E89B-12D3-A456-426655440000"))
}
func testInt4Range() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
try await conn.close()
}
struct Model: Decodable {
let range: Range<Int32>
}
let results1: PostgresQueryResult = try await conn.query("""
SELECT
'[\(Int32.min), \(Int32.max))'::int4range AS range
""").get()
XCTAssertEqual(results1.count, 1)
var row = results1.first?.makeRandomAccess()
let expectedRange: Range<Int32> = Int32.min..<Int32.max
let decodedRange = try row?.decode(column: "range", as: Range<Int32>.self, context: .default)
XCTAssertEqual(decodedRange, expectedRange)
let results2 = try await conn.query("""
SELECT
ARRAY[
'[0, 1)'::int4range,
'[10, 11)'::int4range
] AS ranges
""").get()
XCTAssertEqual(results2.count, 1)
row = results2.first?.makeRandomAccess()
let decodedRangeArray = try row?.decode(column: "ranges", as: [Range<Int32>].self, context: .default)
let decodedClosedRangeArray = try row?.decode(column: "ranges", as: [ClosedRange<Int32>].self, context: .default)
XCTAssertEqual(decodedRangeArray, [0..<1, 10..<11])
XCTAssertEqual(decodedClosedRangeArray, [0...0, 10...10])
}
func testEmptyInt4Range() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
try await conn.close()
}
struct Model: Decodable {
let range: Range<Int32>
}
let randomValue = Int32.random(in: Int32.min...Int32.max)
let results: PostgresQueryResult = try await conn.query("""
SELECT
'[\(randomValue),\(randomValue))'::int4range AS range
""").get()
XCTAssertEqual(results.count, 1)
let row = results.first?.makeRandomAccess()
let expectedRange: Range<Int32> = Int32.valueForEmptyRange..<Int32.valueForEmptyRange
let decodedRange = try row?.decode(column: "range", as: Range<Int32>.self, context: .default)
XCTAssertEqual(decodedRange, expectedRange)
XCTAssertThrowsError(
try row?.decode(column: "range", as: ClosedRange<Int32>.self, context: .default)
)
}
func testInt8Range() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
try await conn.close()
}
struct Model: Decodable {
let range: Range<Int64>
}
let results1: PostgresQueryResult = try await conn.query("""
SELECT
'[\(Int64.min), \(Int64.max))'::int8range AS range
""").get()
XCTAssertEqual(results1.count, 1)
var row = results1.first?.makeRandomAccess()
let expectedRange: Range<Int64> = Int64.min..<Int64.max
let decodedRange = try row?.decode(column: "range", as: Range<Int64>.self, context: .default)
XCTAssertEqual(decodedRange, expectedRange)
let results2: PostgresQueryResult = try await conn.query("""
SELECT
ARRAY[
'[0, 1)'::int8range,
'[10, 11)'::int8range
] AS ranges
""").get()
XCTAssertEqual(results2.count, 1)
row = results2.first?.makeRandomAccess()
let decodedRangeArray = try row?.decode(column: "ranges", as: [Range<Int64>].self, context: .default)
let decodedClosedRangeArray = try row?.decode(column: "ranges", as: [ClosedRange<Int64>].self, context: .default)
XCTAssertEqual(decodedRangeArray, [0..<1, 10..<11])
XCTAssertEqual(decodedClosedRangeArray, [0...0, 10...10])
}
func testEmptyInt8Range() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
try await conn.close()
}
struct Model: Decodable {
let range: Range<Int64>
}
let randomValue = Int64.random(in: Int64.min...Int64.max)
let results: PostgresQueryResult = try await conn.query("""
SELECT
'[\(randomValue),\(randomValue))'::int8range AS range
""").get()
XCTAssertEqual(results.count, 1)
let row = results.first?.makeRandomAccess()
let expectedRange: Range<Int64> = Int64.valueForEmptyRange..<Int64.valueForEmptyRange
let decodedRange = try row?.decode(column: "range", as: Range<Int64>.self, context: .default)
XCTAssertEqual(decodedRange, expectedRange)
XCTAssertThrowsError(
try row?.decode(column: "range", as: ClosedRange<Int64>.self, context: .default)
)
}
func testDates() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
struct Dates: Decodable {
var date: Date
var timestamp: Date
var timestamptz: Date
}
var results: PostgresQueryResult?
XCTAssertNoThrow(results = try conn?.query("""
SELECT
'2016-01-18 01:02:03 +0042'::DATE as date,
'2016-01-18 01:02:03 +0042'::TIMESTAMP as timestamp,
'2016-01-18 01:02:03 +0042'::TIMESTAMPTZ as timestamptz
""").wait())
XCTAssertEqual(results?.count, 1)
let row = results?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "date"].date?.description, "2016-01-18 00:00:00 +0000")
XCTAssertEqual(row?[data: "timestamp"].date?.description, "2016-01-18 01:02:03 +0000")
XCTAssertEqual(row?[data: "timestamptz"].date?.description, "2016-01-18 00:20:03 +0000")
}
/// https://github.com/vapor/nio-postgres/issues/20
func testBindInteger() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
XCTAssertNoThrow(_ = try conn?.simpleQuery("drop table if exists person;").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("create table person(id serial primary key, first_name text, last_name text);").wait())
defer { XCTAssertNoThrow(_ = try conn?.simpleQuery("drop table person;").wait()) }
let id = PostgresData(int32: 5)
XCTAssertNoThrow(_ = try conn?.query("SELECT id, first_name, last_name FROM person WHERE id = $1", [id]).wait())
}
// https://github.com/vapor/nio-postgres/issues/21
func testAverageLengthNumeric() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var results: PostgresQueryResult?
XCTAssertNoThrow(results = try conn?.query("select avg(length('foo')) as average_length").wait())
let row = results?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: 0].double, 3.0)
}
func testNumericParsing() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'1234.5678'::numeric as a,
'-123.456'::numeric as b,
'123456.789123'::numeric as c,
'3.14159265358979'::numeric as d,
'10000'::numeric as e,
'0.00001'::numeric as f,
'100000000'::numeric as g,
'0.000000001'::numeric as h,
'100000000000'::numeric as i,
'0.000000000001'::numeric as j,
'123000000000'::numeric as k,
'0.000000000123'::numeric as l,
'0.5'::numeric as m
""").wait())
XCTAssertEqual(rows?.count, 1)
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "a"].string, "1234.5678")
XCTAssertEqual(row?[data: "b"].string, "-123.456")
XCTAssertEqual(row?[data: "c"].string, "123456.789123")
XCTAssertEqual(row?[data: "d"].string, "3.14159265358979")
XCTAssertEqual(row?[data: "e"].string, "10000")
XCTAssertEqual(row?[data: "f"].string, "0.00001")
XCTAssertEqual(row?[data: "g"].string, "100000000")
XCTAssertEqual(row?[data: "h"].string, "0.000000001")
XCTAssertEqual(row?[data: "k"].string, "123000000000")
XCTAssertEqual(row?[data: "l"].string, "0.000000000123")
XCTAssertEqual(row?[data: "m"].string, "0.5")
}
func testSingleNumericParsing() {
// this seemingly duped test is useful for debugging numeric parsing
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
let numeric = "790226039477542363.6032384900176272473"
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'\(numeric)'::numeric as n
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "n"].string, numeric)
}
func testRandomlyGeneratedNumericParsing() throws {
// this test takes a long time to run
try XCTSkipUnless(Self.shouldRunLongRunningTests)
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
for _ in 0..<1_000_000 {
let integer = UInt.random(in: UInt.min..<UInt.max)
let fraction = UInt.random(in: UInt.min..<UInt.max)
let number = "\(integer).\(fraction)"
.trimmingCharacters(in: CharacterSet(["0"]))
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'\(number)'::numeric as n
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "n"].string, number)
}
}
func testNumericSerialization() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
let a = PostgresNumeric(string: "123456.789123")!
let b = PostgresNumeric(string: "-123456.789123")!
let c = PostgresNumeric(string: "3.14159265358979")!
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
$1::numeric as a,
$2::numeric as b,
$3::numeric as c
""", [
.init(numeric: a),
.init(numeric: b),
.init(numeric: c)
]).wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "a"].decimal, Decimal(string: "123456.789123")!)
XCTAssertEqual(row?[data: "b"].decimal, Decimal(string: "-123456.789123")!)
XCTAssertEqual(row?[data: "c"].decimal, Decimal(string: "3.14159265358979")!)
}
func testDecimalStringSerialization() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
XCTAssertNoThrow(_ = try conn?.simpleQuery("DROP TABLE IF EXISTS \"table1\"").wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("""
CREATE TABLE table1 (
"balance" text NOT NULL
);
""").wait())
defer { XCTAssertNoThrow(_ = try conn?.simpleQuery("DROP TABLE \"table1\"").wait()) }
XCTAssertNoThrow(_ = try conn?.query("INSERT INTO table1 VALUES ($1)", [.init(decimal: Decimal(string: "123456.789123")!)]).wait())
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
SELECT
"balance"
FROM table1
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "balance"].decimal, Decimal(string: "123456.789123")!)
}
func testMoney() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'0'::money as a,
'0.05'::money as b,
'0.23'::money as c,
'3.14'::money as d,
'12345678.90'::money as e
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "a"].string, "0.00")
XCTAssertEqual(row?[data: "b"].string, "0.05")
XCTAssertEqual(row?[data: "c"].string, "0.23")
XCTAssertEqual(row?[data: "d"].string, "3.14")
XCTAssertEqual(row?[data: "e"].string, "12345678.90")
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testIntegerArrayParse() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'{1,2,3}'::int[] as array
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int.self), [1, 2, 3])
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testEmptyIntegerArrayParse() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'{}'::int[] as array
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int.self), [])
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testOptionalIntegerArrayParse() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
'{1, 2, NULL, 4}'::int8[] as array
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int?.self), [1, 2, nil, 4])
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testNullIntegerArrayParse() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
null::int[] as array
""").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int.self), nil)
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testIntegerArraySerialize() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
$1::int8[] as array
""", [
PostgresData(array: [1, 2, 3])
]).wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int.self), [1, 2, 3])
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testEmptyIntegerArraySerialize() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
$1::int8[] as array
""", [
PostgresData(array: [] as [Int])
]).wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int.self), [])
}
@available(*, deprecated, message: "Testing deprecated functionality")
func testOptionalIntegerArraySerialize() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("""
select
$1::int8[] as array
""", [
PostgresData(array: [1, nil, 3] as [Int64?])
]).wait())
XCTAssertEqual(rows?.count, 1)
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "array"].array(of: Int64?.self), [1, nil, 3])
}
// https://github.com/vapor/postgres-nio/issues/143
func testEmptyStringFromNonNullColumn() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
XCTAssertNoThrow(_ = try conn?.simpleQuery(#"DROP TABLE IF EXISTS "non_null_empty_strings""#).wait())
XCTAssertNoThrow(_ = try conn?.simpleQuery("""
CREATE TABLE non_null_empty_strings (
"id" SERIAL,
"nonNullString" text NOT NULL,
PRIMARY KEY ("id")
);
""").wait())
defer { XCTAssertNoThrow(_ = try conn?.simpleQuery(#"DROP TABLE "non_null_empty_strings""#).wait()) }
XCTAssertNoThrow(_ = try conn?.simpleQuery("""
INSERT INTO non_null_empty_strings ("nonNullString") VALUES ('')
""").wait())
var rows: [PostgresRow]?
XCTAssertNoThrow(rows = try conn?.simpleQuery(#"SELECT * FROM "non_null_empty_strings""#).wait())
XCTAssertEqual(rows?.count, 1)
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "nonNullString"].string, "") // <--- this fails
}
func testBoolSerialize() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
do {
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("select $1::bool as bool", [true]).wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "bool"].bool, true)
}
do {
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("select $1::bool as bool", [false]).wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "bool"].bool, false)
}
do {
var rows: [PostgresRow]?
XCTAssertNoThrow(rows = try conn?.simpleQuery("select true::bool as bool").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "bool"].bool, true)
}
do {
var rows: [PostgresRow]?
XCTAssertNoThrow(rows = try conn?.simpleQuery("select false::bool as bool").wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "bool"].bool, false)
}
}
func testBytesSerialize() {
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow( try conn?.close().wait() ) }
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("select $1::bytea as bytes", [
PostgresData(bytes: [1, 2, 3])
]).wait())
let row = rows?.first?.makeRandomAccess()
XCTAssertEqual(row?[data: "bytes"].bytes, [1, 2, 3])
}
func testJSONBSerialize() {
struct Object: Codable, PostgresCodable {
let foo: Int
let bar: Int
}
var conn: PostgresConnection?
XCTAssertNoThrow(conn = try PostgresConnection.test(on: eventLoop).wait())
defer { XCTAssertNoThrow(try conn?.close().wait()) }
do {
var postgresData: PostgresData?
XCTAssertNoThrow(postgresData = try PostgresData(jsonb: Object(foo: 1, bar: 2)))
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("select $1::jsonb as jsonb", [XCTUnwrap(postgresData)]).wait())
var object: Object?
XCTAssertNoThrow(object = try rows?.first?.decode(Object.self, context: .default))
XCTAssertEqual(object?.foo, 1)
XCTAssertEqual(object?.bar, 2)
}
do {
var rows: PostgresQueryResult?
XCTAssertNoThrow(rows = try conn?.query("select jsonb_build_object('foo',1,'bar',2) as jsonb").wait())
var object: Object?
XCTAssertNoThrow(object = try rows?.first?.decode(Object.self, context: .default))
XCTAssertEqual(object?.foo, 1)
XCTAssertEqual(object?.bar, 2)
}
}
func testInt4RangeSerialize() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
try await conn.close()
}
do {
let range: Range<Int32> = Int32.min..<Int32.max
var binds = PostgresBindings()
binds.append(range, context: .default)
let query = PostgresQuery(
unsafeSQL: "select $1::int4range as range",
binds: binds
)
let rowSequence: PostgresRowSequence? = try await conn.query(query, logger: .psqlTest)
var rowIterator: PostgresRowSequence.AsyncIterator? = rowSequence?.makeAsyncIterator()
let row: PostgresRow? = try await rowIterator?.next()
let decodedRange: Range<Int32>? = try row?.decode(Range<Int32>.self, context: .default)
XCTAssertEqual(range, decodedRange)
}
do {
let emptyRange: Range<Int32> = Int32.min..<Int32.min
var binds = PostgresBindings()
binds.append(emptyRange, context: .default)
let query = PostgresQuery(
unsafeSQL: "select $1::int4range as range",
binds: binds
)
let rowSequence: PostgresRowSequence? = try await conn.query(query, logger: .psqlTest)
var rowIterator: PostgresRowSequence.AsyncIterator? = rowSequence?.makeAsyncIterator()
let row: PostgresRow? = try await rowIterator?.next()
let decodedEmptyRange: Range<Int32>? = try row?.decode(Range<Int32>.self, context: .default)
let expectedRange: Range<Int32> = Int32.valueForEmptyRange..<Int32.valueForEmptyRange
XCTAssertNotEqual(emptyRange, expectedRange)
XCTAssertEqual(expectedRange, decodedEmptyRange)
}
do {
let closedRange: ClosedRange<Int32> = Int32.min...(Int32.max - 1)
var binds = PostgresBindings()
binds.append(closedRange, context: .default)
let query = PostgresQuery(
unsafeSQL: "select $1::int4range as range",
binds: binds
)
let rowSequence: PostgresRowSequence? = try await conn.query(query, logger: .psqlTest)
var rowIterator: PostgresRowSequence.AsyncIterator? = rowSequence?.makeAsyncIterator()
let row: PostgresRow? = try await rowIterator?.next()
let decodedClosedRange: ClosedRange<Int32>? = try row?.decode(ClosedRange<Int32>.self, context: .default)
XCTAssertEqual(closedRange, decodedClosedRange)
}
}
func testInt8RangeSerialize() async throws {
let conn: PostgresConnection = try await PostgresConnection.test(on: eventLoop).get()
self.addTeardownBlock {
try await conn.close()
}
do {
let range: Range<Int64> = Int64.min..<Int64.max
var binds = PostgresBindings()
binds.append(range, context: .default)
let query = PostgresQuery(
unsafeSQL: "select $1::int8range as range",
binds: binds
)
let rowSequence: PostgresRowSequence? = try await conn.query(query, logger: .psqlTest)
var rowIterator: PostgresRowSequence.AsyncIterator? = rowSequence?.makeAsyncIterator()
let row: PostgresRow? = try await rowIterator?.next()
let decodedRange: Range<Int64>? = try row?.decode(Range<Int64>.self, context: .default)
XCTAssertEqual(range, decodedRange)
}
do {
let emptyRange: Range<Int64> = Int64.min..<Int64.min
var binds = PostgresBindings()
binds.append(emptyRange, context: .default)
let query = PostgresQuery(
unsafeSQL: "select $1::int8range as range",
binds: binds
)
let rowSequence: PostgresRowSequence? = try await conn.query(query, logger: .psqlTest)
var rowIterator: PostgresRowSequence.AsyncIterator? = rowSequence?.makeAsyncIterator()
let row: PostgresRow? = try await rowIterator?.next()
let decodedEmptyRange: Range<Int64>? = try row?.decode(Range<Int64>.self, context: .default)
let expectedRange: Range<Int64> = Int64.valueForEmptyRange..<Int64.valueForEmptyRange
XCTAssertNotEqual(emptyRange, expectedRange)
XCTAssertEqual(expectedRange, decodedEmptyRange)
}
do {
let closedRange: ClosedRange<Int64> = Int64.min...(Int64.max - 1)
var binds = PostgresBindings()
binds.append(closedRange, context: .default)
let query = PostgresQuery(
unsafeSQL: "select $1::int8range as range",
binds: binds
)
let rowSequence: PostgresRowSequence? = try await conn.query(query, logger: .psqlTest)
var rowIterator: PostgresRowSequence.AsyncIterator? = rowSequence?.makeAsyncIterator()
let row: PostgresRow? = try await rowIterator?.next()
let decodedClosedRange: ClosedRange<Int64>? = try row?.decode(ClosedRange<Int64>.self, context: .default)
XCTAssertEqual(closedRange, decodedClosedRange)
}
}
func testRemoteTLSServer() {
// postgres://uymgphwj:7_tHbREdRwkqAdu4KoIS7hQnNxr8J1LA@elmer.db.elephantsql.com:5432/uymgphwj
var conn: PostgresConnection?
let logger = Logger(label: "test")
let sslContext = try! NIOSSLContext(configuration: .makeClientConfiguration())
let config = PostgresConnection.Configuration(
host: "elmer.db.elephantsql.com",
port: 5432,
username: "uymgphwj",
password: "7_tHbREdRwkqAdu4KoIS7hQnNxr8J1LA",
database: "uymgphwj",