-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathNpgsqlFSharpTests.fs
1842 lines (1558 loc) · 78.2 KB
/
NpgsqlFSharpTests.fs
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
module NgpsqlFSharpTests
open Expecto
open Npgsql.FSharp
open System
open Npgsql
open System.Data
open System.Linq
open Testcontainers.PostgreSql
type FsTest = {
test_id: int
test_name: string
}
type TimeSpanTest = {
id: int
at: TimeSpan
}
type StringArrayTest = {
id: int
values:string array
}
type IntArrayTest = {
id: int
integers: int array
}
type RealArrayTest = {
id: int
reals: float32 array
}
type DoubleArrayTest = {
id: int
doubles: double array
}
type DecimalArrayTest = {
id: int
decimals: decimal array
}
type UuidArrayTest = {
id: int
guids: Guid array
}
type PointTest = {
id: int
point: NpgsqlTypes.NpgsqlPoint
}
type NullablePointTest = {
id: int
nullablepoint: NpgsqlTypes.NpgsqlPoint option
}
[<CLIMutable>]
type JsonBlob =
{
prop1: int
prop2: string
}
let buildDatabase() : PostgreSqlContainer =
let createFSharpTable = "create table if not exists fsharp_test (test_id int, test_name text)"
let createJsonbTable = "create table if not exists data_with_jsonb (data jsonb)"
let createTimestampzTable = "create table if not exists timestampz_test (version integer, date1 timestamptz, date2 timestamptz)"
let createTimespanTable = "create table if not exists timespan_test (id int, at time without time zone)"
let createStringArrayTable = "create table if not exists string_array_test (id int, values text [])"
let createUuidArrayTable = "create table if not exists uuid_array_test (id int, values uuid [])"
let createIntArrayTable = "create table if not exists int_array_test (id int, integers int [])"
let createRealArrayTable = "create table if not exists real_array_test (id int, reals real [])"
let createDoubleArrayTable = "create table if not exists double_array_test (id int, doubles double precision [])"
let createDecimalArrayTable = "create table if not exists decimal_array_test (id int, decimals money [])"
let createPointTable = "create table if not exists point_test (id int, test_point point)"
let createExtensionHStore = "create extension if not exists hstore"
let createExtensionUuid = "create extension if not exists \"uuid-ossp\""
let postgreSqlContainer = (new PostgreSqlBuilder()).WithImage("postgres:16").Build();
postgreSqlContainer.StartAsync().Wait()
postgreSqlContainer.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
createFSharpTable, [ ]
createJsonbTable, [ ]
createTimestampzTable, [ ]
createTimespanTable, [ ]
createStringArrayTable, [ ]
createExtensionHStore, [ ]
createIntArrayTable, [ ]
createRealArrayTable, [ ]
createDoubleArrayTable, [ ]
createDecimalArrayTable, [ ]
createExtensionUuid, [ ]
createUuidArrayTable, []
createPointTable, []
]
|> ignore
postgreSqlContainer
let tests =
testList "Integration tests" [
testList "RowReader tests used in Sql.read and Sql.readAsync" [
test "Sql.executeTransaction works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT * FROM users"
|> Sql.execute (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
|> fun users -> Expect.equal users expected "Users can be read correctly"
}
test "Sql.executeRow works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.executeRow (fun read -> read.int64 "user_count")
|> fun count -> Expect.equal count 0L "Count is zero"
}
test "Sql.iter works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
let mutable count = -1
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.iter (fun read -> count <- read.int "user_count")
|> fun () -> Expect.equal count 0 "The count is zero"
}
test "Manual transaction handling works with Sql.executeNonQuery" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
use transaction = connection.BeginTransaction()
let results = ResizeArray()
for username in ["John"; "Jane"] do
connection
|> Sql.existingConnection
|> Sql.query "INSERT INTO users (username) VALUES(@username)"
|> Sql.parameters [ "@username", Sql.text username ]
|> Sql.executeNonQuery
|> results.Add
if (results.Sum() <> 2) then
transaction.Rollback()
else
transaction.Commit()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.executeRow (fun read -> read.int "user_count")
|> fun count -> Expect.equal 2 count "There are 2 users added"
}
test "Manual transaction handling works with Sql.executeNonQuery and can be rolled back" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
use transaction = connection.BeginTransaction()
let results = ResizeArray()
try
for username in [Some "John"; Some "Jane"; None] do
connection
|> Sql.existingConnection
|> Sql.query "INSERT INTO users (username) VALUES(@username)"
|> Sql.parameters [ "@username", Sql.textOrNone username ]
|> Sql.executeNonQuery
|> results.Add
transaction.Commit()
with
| _ -> transaction.Rollback()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.executeRow (fun read -> read.int "user_count")
|> fun count -> Expect.equal 0 count "There are 0 users added because the transaction is rolled back"
}
testAsync "Sql.iterAsync works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
let mutable count = -1
do!
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.iterAsync (fun read -> count <- read.int "user_count")
|> Async.AwaitTask
Expect.equal count 0 "The count is zero"
}
test "Reading count as int works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.executeRow (fun read -> read.int "user_count")
|> fun count -> Expect.equal count 0 "Count is zero"
}
test "Sql.executeTransaction works with DateTime" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, birthdate date)"
|> Sql.executeNonQuery
|> ignore
let date = DateTime.Now
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO users (birthdate) VALUES (@birthdate)", [
[ ("@birthdate", Sql.dateOrNone (Some date)) ]
[ ("@birthdate", Sql.dateOrNone Option<DateTime>.None) ]
]
]
|> ignore
}
test "Sql.executeTransaction works with DateOnly" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, birthdate date)"
|> Sql.executeNonQuery
|> ignore
let date = DateOnly.FromDateTime DateTime.Now
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO users (birthdate) VALUES (@birthdate)", [
[ ("@birthdate", Sql.dateOrNone (Some date)) ]
[ ("@birthdate", Sql.dateOrNone Option<DateOnly>.None) ]
]
]
|> ignore
}
test "Parameter names can contain trailing spaces" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
Sql.existingConnection connection
|> Sql.query "CREATE TABLE test (test_id serial primary key, integers int [])"
|> Sql.executeNonQuery
|> ignore
let result =
Sql.existingConnection connection
|> Sql.executeTransaction [
"INSERT INTO test (integers) VALUES (@integers)", [
[ ("@integers ", Sql.intArray [| 1; 3; 7; |] ) ]
[ (" @integers" , Sql.intArray [| 1; 3; 7; |] ) ]
[ (" integers ", Sql.intArray [| 1; 3; 7; |] ) ]
]
]
Expect.equal result [3] "parameters can contain trailing spaces"
}
testAsync "Sql.executeRowAsync works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
let! count =
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT COUNT(*) as user_count FROM users"
|> Sql.executeRowAsync (fun read -> read.int64 "user_count")
|> Async.AwaitTask
Expect.equal count 0L "Count is zero"
}
test "Sql.executeTransaction doesn't error out on parameterized queries with empty parameter sets" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO users (username) VALUES (@username)", [ ]
]
|> fun affectedRows -> Expect.equal affectedRows [0] "No rows will be affected"
}
testAsync "Sql.executeTransactionAsync doesn't error out on parameterized queries with empty parameter sets" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null)"
|> Sql.executeNonQuery
|> ignore
let! affectedRows =
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransactionAsync [
"INSERT INTO users (username) VALUES (@username)", [ ]
]
|> Async.AwaitTask
Expect.equal affectedRows [0] "No rows will be affected"
}
test "Sql.executeTransaction works with existing open connection" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
Sql.existingConnection connection
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.existingConnection connection
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
Sql.existingConnection connection
|> Sql.query "SELECT * FROM users"
|> Sql.execute (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
|> fun users -> Expect.equal users expected "Users can be read correctly"
}
test "Sql.executeTransaction works with existing connection" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
Sql.existingConnection connection
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.existingConnection connection
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
Sql.existingConnection connection
|> Sql.query "SELECT * FROM users"
|> Sql.execute (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
|> fun users -> Expect.equal users expected "Users can be read correctly"
}
test "Sql.executeTransaction leaves existing connection open" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
Sql.existingConnection connection
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.existingConnection connection
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
Sql.existingConnection connection
|> Sql.query "SELECT * FROM users"
|> Sql.execute (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
|> ignore
Expect.equal ConnectionState.Open connection.State "Check existing connection is still open after executeTransaction"
}
test "Sql.executeTransaction works with data source" {
let db = buildDatabase()
use dataSource = NpgsqlDataSource.Create(db.GetConnectionString())
Sql.fromDataSource dataSource
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.fromDataSource dataSource
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
Sql.fromDataSource dataSource
|> Sql.query "SELECT * FROM users"
|> Sql.execute (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
|> fun users -> Expect.equal users expected "Users can be read correctly"
}
test "Sql.executeNonQuery works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.query "DELETE FROM users"
|> Sql.executeNonQuery
|> fun rowsAffected -> Expect.equal 3 rowsAffected "Three entries are deleted"
}
test "Sql.executeNonQuery works with existing connection" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
Sql.existingConnection connection
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.existingConnection connection
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
Sql.existingConnection connection
|> Sql.query "DELETE FROM users"
|> Sql.executeNonQuery
|> fun rowsAffected -> Expect.equal 3 rowsAffected "Three entries are deleted"
}
test "Sql.executeNonQuery leaves existing connection open" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
Sql.existingConnection connection
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.existingConnection connection
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
Sql.existingConnection connection
|> Sql.query "DELETE FROM users"
|> Sql.executeNonQuery
|> ignore
Expect.equal ConnectionState.Open connection.State "Check existing connection is still open after executeNonQuery"
}
test "Sql.executeNonQuery works with data source" {
let db = buildDatabase()
use dataSource = NpgsqlDataSource.Create(db.GetConnectionString())
Sql.fromDataSource dataSource
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
Sql.fromDataSource dataSource
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
Sql.fromDataSource dataSource
|> Sql.query "DELETE FROM users"
|> Sql.executeNonQuery
|> fun rowsAffected -> Expect.equal 3 rowsAffected "Three entries are deleted"
}
test "Sql.toSeq works" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQuery
|> ignore
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
let sequence =
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT * FROM users"
|> Sql.toSeq (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
let expectCorrectResults message =
sequence
|> Seq.toList
|> List.sortBy (fun u -> u.userId)
|> fun users -> Expect.equal users expected message
// Iterate over the sequence the first time
expectCorrectResults "Users can be read correctly on first iteration"
// Iterate over the sequence a second time
expectCorrectResults "Users can be read correctly on second iteration"
}
]
testAsync "async query execution works" {
let db = buildDatabase()
do!
db.GetConnectionString()
|> Sql.connect
|> Sql.query "CREATE TABLE users (user_id serial primary key, username text not null, active bit not null, salary money not null)"
|> Sql.executeNonQueryAsync
|> Async.AwaitTask
|> Async.Ignore
do!
db.GetConnectionString()
|> Sql.connect
|> Sql.executeTransactionAsync [
"INSERT INTO users (username, active, salary) VALUES (@username, @active, @salary)", [
[ ("@username", Sql.text "first"); ("active", Sql.bit true); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "second"); ("active", Sql.bit false); ("salary", Sql.money 1.0M) ]
[ ("@username", Sql.text "third"); ("active", Sql.bit true);("salary", Sql.money 1.0M) ]
]
]
|> Async.AwaitTask
|> Async.Ignore
let expected = [
{| userId = 1; username = "first"; active = true; salary = 1.0M |}
{| userId = 2; username = "second"; active = false ; salary = 1.0M |}
{| userId = 3; username = "third"; active = true ; salary = 1.0M |}
]
let! users =
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT * FROM users"
|> Sql.executeAsync (fun read ->
{|
userId = read.int "user_id"
username = read.string "username"
active = read.bool "active"
salary = read.decimal "salary"
|})
|> Async.AwaitTask
Expect.equal users expected "Users can be read correctly"
}
testList "Query-only parallel tests without recreating database" [
test "Null roundtrip" {
let db = buildDatabase()
let connection : string = db.GetConnectionString()
connection
|> Sql.connect
|> Sql.query "SELECT @nullValue::text as output"
|> Sql.parameters [ "nullValue", Sql.dbnull ]
|> Sql.execute (fun read -> read.textOrNone "output")
|> fun output -> Expect.isNone output.[0] "Output was null"
}
test "Bytea roundtrip" {
let db = buildDatabase()
let input : array<byte> = [1 .. 5] |> List.map byte |> Array.ofList
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @manyBytes as output"
|> Sql.parameters [ "manyBytes", Sql.bytea input ]
|> Sql.execute (fun read -> read.bytea "output")
|> fun output -> Expect.equal input output.[0] "Check bytes read from database are the same sent"
}
test "bit/bool roundtrip" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @logical as output"
|> Sql.parameters [ "logical", Sql.bit true ]
|> Sql.execute (fun read -> read.bool "output")
|> fun output -> Expect.equal true output.[0] "Check bytes read from database are the same sent"
}
test "Uuid roundtrip" {
let db = buildDatabase()
let id : Guid = Guid.NewGuid()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @uuid_input as output"
|> Sql.parameters [ "uuid_input", Sql.uuid id ]
|> Sql.execute (fun read -> read.uuid "output")
|> fun output -> Expect.equal id output.[0] "Check uuid read from database is the same sent"
}
test "Interval roundtrip" {
let db = buildDatabase()
let oneHourInterval : TimeSpan = TimeSpan.FromHours 1.0
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @interval_input as output"
|> Sql.parameters [ "interval_input", Sql.interval oneHourInterval ]
|> Sql.execute (fun read -> read.interval "output")
|> fun output -> Expect.equal oneHourInterval output.[0] "Check interval read from database is the same sent"
}
test "Money roundtrip with @ sign" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @money_input::money as value"
|> Sql.parameters [ "@money_input", Sql.money 12.5M ]
|> Sql.execute (fun read -> read.decimal "value")
|> fun money -> Expect.equal money.[0] 12.5M "Check money as decimal read from database is the same sent"
}
test "DateTimeOffset roundtrip when input is UTC" {
let db = buildDatabase()
let value = DateTimeOffset.UtcNow
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @timestamp::timestamptz as value"
|> Sql.parameters [ "@timestamp", Sql.timestamptz value ]
|> Sql.executeRow (fun read -> read.datetimeOffset "value")
|> fun timestamp -> Expect.equal (timestamp.ToUnixTimeSeconds()) (value.ToUnixTimeSeconds()) "The values are the same"
}
test "DateTime as date roundtrip" {
let db = buildDatabase()
let value = DateTime.Today
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @date::date as value"
|> Sql.parameters [ "@date", Sql.date value ]
|> Sql.executeRow (fun read -> read.dateTime "value")
|> fun dateTime -> Expect.equal dateTime value "The values are the same"
}
test "DateOnly as date roundtrip" {
let db = buildDatabase()
let value = DateOnly.FromDateTime DateTime.Now
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @date::date as value"
|> Sql.parameters [ "@date", Sql.date value ]
|> Sql.executeRow (fun read -> read.dateTime "value")
|> fun dateTime -> Expect.equal (DateOnly.FromDateTime dateTime) value "The values are the same"
}
test "None DateOnly as date roundtrip" {
let db = buildDatabase()
let value: DateOnly option = None
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @date::date as value"
|> Sql.parameters [ "@date", Sql.dateOrNone value ]
|> Sql.executeRow (fun read -> read.dateOnlyOrNone "value")
|> fun date -> Expect.equal date value "The values are the same"
}
test "ValueSome DateOnly option as date roundtrip" {
let db = buildDatabase()
let value = DateOnly.FromDateTime DateTime.Now |> ValueSome
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT @date::date as value"
|> Sql.parameters [ "@date", Sql.dateOrValueNone value ]
|> Sql.executeRow (fun read -> read.dateOnlyOrValueNone "value")
|> fun date -> Expect.equal date value "The values are the same"
}
test "uuid_generate_v4()" {
let db = buildDatabase()
db.GetConnectionString()
|> Sql.connect
|> Sql.query "SELECT uuid_generate_v4() as id"
|> Sql.execute (fun read -> read.uuid "id")
|> function
| [ uuid ] -> Expect.isNotNull (uuid.ToString()) "Check database generates an UUID"
| _ -> failwith "Should not happpen"
}
test "String option roundtrip" {
let db = buildDatabase()
let connection : string = db.GetConnectionString()
let a : string option = Some "abc"
let b : string option = None
let row =
connection
|> Sql.connect
|> Sql.query "SELECT @a::text as first, @b::text as second"
|> Sql.parameters [ "a", Sql.textOrNone a; "b", Sql.textOrNone b ]
|> Sql.execute (fun read -> read.textOrNone "first", read.textOrNone "second")
match row with
| [ (Some output, None) ] ->
Expect.equal a (Some output) "Check Option value read from database is the same as the one sent"
| _ ->
failwith "Unexpected results"
}
test "String option roundtrip with existing connection" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
let a : string option = Some "abc"
let b : string option = None
let row =
connection
|> Sql.existingConnection
|> Sql.query "SELECT @a::text as first, @b::text as second"
|> Sql.parameters [ "a", Sql.textOrNone a; "b", Sql.textOrNone b ]
|> Sql.execute (fun read -> read.textOrNone "first", read.textOrNone "second")
match row with
| [ (Some output, None) ] ->
Expect.equal a (Some output) "Check Option value read from database is the same as the one sent"
| _ ->
failwith "Unexpected results"
}
test "String option roundtrip leaves existing connection open" {
let db = buildDatabase()
use connection = new NpgsqlConnection(db.GetConnectionString())
connection.Open()
let a : string option = Some "abc"
let b : string option = None
connection
|> Sql.existingConnection
|> Sql.query "SELECT @a::text as first, @b::text as second"
|> Sql.parameters [ "a", Sql.textOrNone a; "b", Sql.textOrNone b ]
|> Sql.execute (fun read -> read.textOrNone "first", read.textOrNone "second")
|> ignore
Expect.equal ConnectionState.Open connection.State "Check existing connection is still open after query"
}
test "String option roundtrip with data source" {
let db = buildDatabase()
use dataSource = NpgsqlDataSource.Create(db.GetConnectionString())
let a : string option = Some "abc"
let b : string option = None
let row =
dataSource
|> Sql.fromDataSource
|> Sql.query "SELECT @a::text as first, @b::text as second"
|> Sql.parameters [ "a", Sql.textOrNone a; "b", Sql.textOrNone b ]
|> Sql.execute (fun read -> read.textOrNone "first", read.textOrNone "second")
match row with
| [ (Some output, None) ] ->
Expect.equal a (Some output) "Check Option value read from database is the same as the one sent"
| _ ->
failwith "Unexpected results"
}
]
testList "Sequential tests that update database state" [
test "Sql.execute" {
let seedDatabase (connection: string) =
connection
|> Sql.connect
|> Sql.executeTransaction [
"INSERT INTO fsharp_test (test_id, test_name) values (@id, @name)", [
[ "@id", Sql.int 1; "@name", Sql.text "first test" ]
[ "@id", Sql.int 2; "@name", Sql.text "second test" ]
[ "@id", Sql.int 3; "@name", Sql.text "third test" ]
]
]
|> ignore
let db = buildDatabase()
let connection : string = db.GetConnectionString()
seedDatabase connection
let table =
Sql.connect connection
|> Sql.query "SELECT * FROM fsharp_test"
|> Sql.prepare
|> Sql.execute (fun read -> {
test_id = read.int "test_id";
test_name = read.string "test_name"
})
let expected = [
{ test_id = 1; test_name = "first test" }