-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
MiscTests.cs
1325 lines (1140 loc) · 50 KB
/
MiscTests.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
#if NETCOREAPP3_1 || NET462 || NET472
namespace System.Runtime.CompilerServices
{
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit // yeah, don't do this!
{
}
}
#endif
namespace Dapper.Tests
{
[Collection("MiscTests")]
public sealed class SystemSqlClientMiscTests : MiscTests<SystemSqlClientProvider> { }
#if MSSQLCLIENT
[Collection("MiscTests")]
public sealed class MicrosoftSqlClientMiscTests : MiscTests<MicrosoftSqlClientProvider> { }
#endif
public abstract class MiscTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider
{
[Fact]
public void TestNullableGuidSupport()
{
var guid = connection.Query<Guid?>("select null").First();
Assert.Null(guid);
guid = Guid.NewGuid();
var guid2 = connection.Query<Guid?>("select @guid", new { guid }).First();
Assert.Equal(guid, guid2);
}
[Fact]
public void TestNonNullableGuidSupport()
{
var guid = Guid.NewGuid();
var guid2 = connection.Query<Guid?>("select @guid", new { guid }).First();
Assert.True(guid == guid2);
}
private struct Car
{
public enum TrapEnum : int
{
A = 1,
B = 2
}
#pragma warning disable 0649
public string Name;
#pragma warning restore 0649
public int Age { get; set; }
public TrapEnum Trap { get; set; }
}
private struct CarWithAllProps
{
public string Name { get; set; }
public int Age { get; init; }
public Car.TrapEnum Trap { get; init; }
}
private record PositionalCarRecord(int Age, Car.TrapEnum Trap, string? Name)
{
public PositionalCarRecord() : this(default, default, default) { }
}
private record NominalCarRecord
{
public int Age { get; init; }
public Car.TrapEnum Trap { get; init; }
public string? Name { get; init; }
}
[Fact]
public void TestStructs()
{
var car = connection.Query<Car>("select 'Ford' Name, 21 Age, 2 Trap").First();
Assert.Equal(21, car.Age);
Assert.Equal("Ford", car.Name);
Assert.Equal(2, (int)car.Trap);
}
[Fact]
public void TestPositionalRecord()
{
var car = connection.Query<PositionalCarRecord>("select 'Ford' Name, 21 Age, 2 Trap").First();
Assert.Equal(21, car.Age);
Assert.Equal("Ford", car.Name);
Assert.Equal(2, (int)car.Trap);
}
[Fact]
public void TestNominalRecord()
{
var car = connection.Query<NominalCarRecord>("select 'Ford' Name, 21 Age, 2 Trap").First();
Assert.Equal(21, car.Age);
Assert.Equal("Ford", car.Name);
Assert.Equal(2, (int)car.Trap);
}
[Fact]
public void TestStructAsParam()
{
var car1 = new CarWithAllProps { Name = "Ford", Age = 21, Trap = Car.TrapEnum.B };
// note Car has Name as a field; parameters only respect properties at the moment
var car2 = connection.Query<CarWithAllProps>("select @Name Name, @Age Age, @Trap Trap", car1).First();
Assert.Equal(car2.Name, car1.Name);
Assert.Equal(car2.Age, car1.Age);
Assert.Equal(car2.Trap, car1.Trap);
}
[Fact]
public void SelectListInt()
{
Assert.Equal(new[] { 1, 2, 3 }, connection.Query<int>("select 1 union all select 2 union all select 3"));
}
[Fact]
public void SelectBinary()
{
connection.Query<byte[]>("select cast(1 as varbinary(4))").First().SequenceEqual(new byte[] { 1 });
}
[Fact]
public void TestSchemaChanged()
{
connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')");
try
{
var d = connection.Query<Dog>("select * from #dog").Single();
Assert.Equal("Alf", d.Name);
Assert.Equal(1, d.Age);
connection.Execute("alter table #dog drop column Name");
d = connection.Query<Dog>("select * from #dog").Single();
Assert.Null(d.Name);
Assert.Equal(1, d.Age);
}
finally
{
connection.Execute("drop table #dog");
}
}
[Fact]
public void TestSchemaChangedViaFirstOrDefault()
{
connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')");
try
{
var d = connection.QueryFirstOrDefault<Dog>("select * from #dog");
Assert.NotNull(d);
Assert.Equal("Alf", d.Name);
Assert.Equal(1, d.Age);
connection.Execute("alter table #dog drop column Name");
d = connection.QueryFirstOrDefault<Dog>("select * from #dog");
Assert.NotNull(d);
Assert.Null(d.Name);
Assert.Equal(1, d.Age);
}
finally
{
connection.Execute("drop table #dog");
}
}
[Fact]
public void Test_Single_First_Default()
{
var sql = "select 0 where 1 = 0;"; // no rows
var ex = Assert.Throws<InvalidOperationException>(() => connection.QueryFirst<int>(sql));
Assert.Equal("Sequence contains no elements", ex.Message);
ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingle<int>(sql));
Assert.Equal("Sequence contains no elements", ex.Message);
Assert.Equal(0, connection.QueryFirstOrDefault<int>(sql));
Assert.Equal(0, connection.QuerySingleOrDefault<int>(sql));
sql = "select 1;"; // one row
Assert.Equal(1, connection.QueryFirst<int>(sql));
Assert.Equal(1, connection.QuerySingle<int>(sql));
Assert.Equal(1, connection.QueryFirstOrDefault<int>(sql));
Assert.Equal(1, connection.QuerySingleOrDefault<int>(sql));
sql = "select 2 union select 3 order by 1;"; // two rows
Assert.Equal(2, connection.QueryFirst<int>(sql));
ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingle<int>(sql));
Assert.Equal("Sequence contains more than one element", ex.Message);
Assert.Equal(2, connection.QueryFirstOrDefault<int>(sql));
ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingleOrDefault<int>(sql));
Assert.Equal("Sequence contains more than one element", ex.Message);
}
/// <summary>
/// This test is ensuring our "single row" methods also behave like a type being deserialized
/// and give a useful error message when the types don't match.
/// </summary>
[Fact]
public async Task TestConversionExceptionMessages()
{
const string sql = "Select Null;";
// Nullable is expected to work if we get a null in all cases
// List paths
var list = connection.Query<int?>(sql);
Assert.Null(Assert.Single(list));
list = await connection.QueryAsync<int?>(sql);
Assert.Null(Assert.Single(list));
// Single row paths
Assert.Null(connection.QueryFirst<int?>(sql));
Assert.Null(connection.QueryFirstOrDefault<int?>(sql));
Assert.Null(connection.QuerySingle<int?>(sql));
Assert.Null(connection.QuerySingleOrDefault<int?>(sql));
Assert.Null(await connection.QueryFirstAsync<int?>(sql));
Assert.Null(await connection.QueryFirstOrDefaultAsync<int?>(sql));
Assert.Null(await connection.QuerySingleAsync<int?>(sql));
Assert.Null(await connection.QuerySingleOrDefaultAsync<int?>(sql));
static async Task TestExceptionsAsync<T>(DbConnection connection, string sql, string exception)
{
var ex = Assert.Throws<DataException>(() => connection.Query<T>(sql));
Assert.Equal(exception, ex.Message);
ex = Assert.Throws<DataException>(() => connection.QueryFirst<T>(sql));
Assert.Equal(exception, ex.Message);
ex = Assert.Throws<DataException>(() => connection.QueryFirstOrDefault<T>(sql));
Assert.Equal(exception, ex.Message);
ex = Assert.Throws<DataException>(() => connection.QuerySingle<T>(sql));
Assert.Equal(exception, ex.Message);
ex = Assert.Throws<DataException>(() => connection.QuerySingleOrDefault<T>(sql));
Assert.Equal(exception, ex.Message);
ex = await Assert.ThrowsAsync<DataException>(() => connection.QueryAsync<T>(sql));
Assert.Equal(exception, ex.Message);
ex = await Assert.ThrowsAsync<DataException>(() => connection.QueryFirstAsync<T>(sql));
Assert.Equal(exception, ex.Message);
ex = await Assert.ThrowsAsync<DataException>(() => connection.QueryFirstOrDefaultAsync<T>(sql));
Assert.Equal(exception, ex.Message);
ex = await Assert.ThrowsAsync<DataException>(() => connection.QuerySingleAsync<T>(sql));
Assert.Equal(exception, ex.Message);
ex = await Assert.ThrowsAsync<DataException>(() => connection.QuerySingleOrDefaultAsync<T>(sql));
Assert.Equal(exception, ex.Message);
}
// Null value throws
await TestExceptionsAsync<int>(
connection,
"Select null as Foo",
"Error parsing column 0 (Foo=<null>)");
// Incompatible value throws (testing unnamed column bits here too)
await TestExceptionsAsync<int>(
connection,
"Select 'bar'",
"Error parsing column 0 ((Unnamed Column)=bar - String)");
// Null with a full type (testing position too)
await TestExceptionsAsync<NullTestType>(
connection,
"Select 1 Id, 'bar' Foo",
"Error parsing column 1 (Foo=bar - String)");
// And a ValueTuple! (testing position too)
// Still needs love, because we handle ValueTuple differently today
// It'll yield a raw: typeof(System.FormatException): Input string was not in a correct format.
// Note: not checking the "Select 1 Id, null Foo" case here, because we won't attempt to set the column
// ...and there will no error in that case.
//await TestExceptionsAsync<(int Id, int Foo)>(
// connection,
// "Select 1 Id, 'bar' Foo",
// "Error parsing column 1 (Foo=bar - String)");
}
private class NullTestType
{
public int Id { get; }
public int Foo { get; }
}
[Fact]
public void TestStrings()
{
Assert.Equal(new[] { "a", "b" }, connection.Query<string>("select 'a' a union select 'b'"));
}
// see https://stackoverflow.com/questions/16726709/string-format-with-sql-wildcard-causing-dapper-query-to-break
[Fact]
public void CheckComplexConcat()
{
const string end_wildcard = @"
SELECT * FROM #users16726709
WHERE (first_name LIKE CONCAT(@search_term, '%') OR last_name LIKE CONCAT(@search_term, '%'));";
const string both_wildcards = @"
SELECT * FROM #users16726709
WHERE (first_name LIKE CONCAT('%', @search_term, '%') OR last_name LIKE CONCAT('%', @search_term, '%'));";
const string formatted = @"
SELECT * FROM #users16726709
WHERE (first_name LIKE {0} OR last_name LIKE {0});";
const string use_end_only = "CONCAT(@search_term, '%')";
const string use_both = "CONCAT('%', @search_term, '%')";
// if true, slower query due to not being able to use indices, but will allow searching inside strings
const bool allow_start_wildcards = false;
string query = string.Format(formatted, allow_start_wildcards ? use_both : use_end_only);
const string term = "F"; // the term the user searched for
connection.Execute(@"create table #users16726709 (first_name varchar(200), last_name varchar(200))
insert #users16726709 values ('Fred','Bloggs') insert #users16726709 values ('Tony','Farcus') insert #users16726709 values ('Albert','TenoF')");
// Using Dapper
Assert.Equal(2, connection.Query(end_wildcard, new { search_term = term }).Count());
Assert.Equal(3, connection.Query(both_wildcards, new { search_term = term }).Count());
Assert.Equal(2, connection.Query(query, new { search_term = term }).Count());
}
[Fact]
public void TestExtraFields()
{
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select '' as Extra, 1 as Age, 0.1 as Name1 , Id = @id", new { id = guid });
Assert.Single(dog);
Assert.Equal(1, dog.First().Age);
Assert.Equal(dog.First().Id, guid);
}
[Fact]
public void TestStrongType()
{
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
Assert.Single(dog);
Assert.Null(dog.First().Age);
Assert.Equal(dog.First().Id, guid);
}
[Fact]
public void TestSimpleNull()
{
Assert.Null(connection.Query<DateTime?>("select null").First());
}
[Fact]
public void TestExpando()
{
var rows = connection.Query("select 1 A, 2 B union all select 3, 4").ToList();
Assert.Equal(1, (int)rows[0].A);
Assert.Equal(2, (int)rows[0].B);
Assert.Equal(3, (int)rows[1].A);
Assert.Equal(4, (int)rows[1].B);
}
[Fact]
public void TestStringList()
{
Assert.Equal(
new[] { "a", "b", "c" },
connection.Query<string>("select * from (select 'a' as x union all select 'b' union all select 'c') as T where x in @strings", new { strings = new[] { "a", "b", "c" } })
);
Assert.Equal(
new string[0],
connection.Query<string>("select * from (select 'a' as x union all select 'b' union all select 'c') as T where x in @strings", new { strings = new string[0] })
);
}
[Fact]
public void TestExecuteCommand()
{
Assert.Equal(2, connection.Execute(@"
set nocount on
create table #t(i int)
set nocount off
insert #t
select @a a union all select @b
set nocount on
drop table #t", new { a = 1, b = 2 }));
}
[Fact]
public void TestExecuteMultipleCommand()
{
connection.Execute("create table #t(i int)");
try
{
int tally = connection.Execute("insert #t (i) values(@a)", new[] { new { a = 1 }, new { a = 2 }, new { a = 3 }, new { a = 4 } });
int sum = connection.Query<int>("select sum(i) from #t").First();
Assert.Equal(4, tally);
Assert.Equal(10, sum);
}
finally
{
connection.Execute("drop table #t");
}
}
private class Student
{
public string? Name { get; set; }
public int Age { get; set; }
}
[Fact]
public void TestExecuteMultipleCommandStrongType()
{
connection.Execute("create table #t(Name nvarchar(max), Age int)");
try
{
int tally = connection.Execute("insert #t (Name,Age) values(@Name, @Age)", new List<Student>(2)
{
new Student{Age = 1, Name = "sam"},
new Student{Age = 2, Name = "bob"}
});
int sum = connection.Query<int>("select sum(Age) from #t").First();
Assert.Equal(2, tally);
Assert.Equal(3, sum);
}
finally
{
connection.Execute("drop table #t");
}
}
[Fact]
public void TestExecuteMultipleCommandObjectArray()
{
connection.Execute("create table #t(i int)");
int tally = connection.Execute("insert #t (i) values(@a)", new object[] { new { a = 1 }, new { a = 2 }, new { a = 3 }, new { a = 4 } });
int sum = connection.Query<int>("select sum(i) from #t drop table #t").First();
Assert.Equal(4, tally);
Assert.Equal(10, sum);
}
private class TestObj
{
public int _internal;
internal int Internal
{
set { _internal = value; }
}
public int _priv;
private int Priv
{
set { _priv = value; }
}
private int PrivGet => _priv;
}
[Fact]
public void TestSetInternal()
{
Assert.Equal(10, connection.Query<TestObj>("select 10 as [Internal]").First()._internal);
}
[Fact]
public void TestSetPrivate()
{
Assert.Equal(10, connection.Query<TestObj>("select 10 as [Priv]").First()._priv);
}
[Fact]
public void TestExpandWithNullableFields()
{
var row = connection.Query("select null A, 2 B").Single();
Assert.Null((int?)row.A);
Assert.Equal(2, (int?)row.B);
}
[Fact]
public void TestEnumeration()
{
var en = connection.Query<int>("select 1 as one union all select 2 as one", buffered: false);
var i = en.GetEnumerator();
i.MoveNext();
bool gotException = false;
try
{
var x = connection.Query<int>("select 1 as one", buffered: false).First();
}
catch (Exception)
{
gotException = true;
}
while (i.MoveNext())
{
}
// should not exception, since enumerated
en = connection.Query<int>("select 1 as one", buffered: false);
Assert.True(gotException);
}
[Fact]
public void TestEnumerationDynamic()
{
var en = connection.Query("select 1 as one union all select 2 as one", buffered: false);
var i = en.GetEnumerator();
i.MoveNext();
bool gotException = false;
try
{
var x = connection.Query("select 1 as one", buffered: false).First();
}
catch (Exception)
{
gotException = true;
}
while (i.MoveNext())
{
}
// should not exception, since enumertated
en = connection.Query("select 1 as one", buffered: false);
Assert.True(gotException);
}
[Fact]
public void TestNakedBigInt()
{
const long foo = 12345;
var result = connection.Query<long>("select @foo", new { foo }).Single();
Assert.Equal(foo, result);
}
[Fact]
public void TestBigIntMember()
{
const long foo = 12345;
var result = connection.Query<WithBigInt>(@"
declare @bar table(Value bigint)
insert @bar values (@foo)
select * from @bar", new { foo }).Single();
Assert.Equal(foo, result.Value);
}
private class WithBigInt
{
public long Value { get; set; }
}
[Fact]
public void TestFieldsAndPrivates()
{
var data = connection.Query<TestFieldCaseAndPrivatesEntity>(
"select a=1,b=2,c=3,d=4,f='5'").Single();
Assert.Equal(1, data.a);
Assert.Equal(2, data.GetB());
Assert.Equal(3, data.c);
Assert.Equal(4, data.GetD());
Assert.Equal(5, data.e);
}
private class TestFieldCaseAndPrivatesEntity
{
#pragma warning disable IDE1006 // Naming Styles
public int a { get; set; }
private int b { get; set; }
public int GetB() { return b; }
public int c = 0;
#pragma warning disable RCS1169 // Mark field as read-only.
private int d = 0;
#pragma warning restore RCS1169 // Mark field as read-only.
public int GetD() { return d; }
public int e { get; set; }
private string f
{
get { return e.ToString(); }
set { e = int.Parse(value); }
}
#pragma warning restore IDE1006 // Naming Styles
}
private class InheritanceTest1
{
public string? Base1 { get; set; }
public string? Base2 { get; private set; }
}
private class InheritanceTest2 : InheritanceTest1
{
public string? Derived1 { get; set; }
public string? Derived2 { get; private set; }
}
[Fact]
public void TestInheritance()
{
// Test that inheritance works.
var list = connection.Query<InheritanceTest2>("select 'One' as Derived1, 'Two' as Derived2, 'Three' as Base1, 'Four' as Base2");
Assert.Equal("One", list.First().Derived1);
Assert.Equal("Two", list.First().Derived2);
Assert.Equal("Three", list.First().Base1);
Assert.Equal("Four", list.First().Base2);
}
[Fact]
public void ExecuteReader()
{
var dt = new DataTable();
dt.Load(connection.ExecuteReader("select 3 as [three], 4 as [four]"));
Assert.Equal(2, dt.Columns.Count);
Assert.Equal("three", dt.Columns[0].ColumnName);
Assert.Equal("four", dt.Columns[1].ColumnName);
Assert.Equal(1, dt.Rows.Count);
Assert.Equal(3, (int)dt.Rows[0][0]);
Assert.Equal(4, (int)dt.Rows[0][1]);
}
[Fact]
public void TestDbString()
{
var obj = connection.Query("select datalength(@a) as a, datalength(@b) as b, datalength(@c) as c, datalength(@d) as d, datalength(@e) as e, datalength(@f) as f",
new
{
a = new DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi = true },
b = new DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi = false },
c = new DbString { Value = "abcde", IsFixedLength = false, Length = 10, IsAnsi = true },
d = new DbString { Value = "abcde", IsFixedLength = false, Length = 10, IsAnsi = false },
e = new DbString { Value = "abcde", IsAnsi = true },
f = new DbString { Value = "abcde", IsAnsi = false },
}).First();
Assert.Equal(10, (int)obj.a);
Assert.Equal(20, (int)obj.b);
Assert.Equal(5, (int)obj.c);
Assert.Equal(10, (int)obj.d);
Assert.Equal(5, (int)obj.e);
Assert.Equal(10, (int)obj.f);
}
[Fact]
public void DbStringNullHandling()
{
// without lengths
var obj = new { x = new DbString("abc"), y = (DbString?)new DbString(null) };
var row = connection.QuerySingle<(string? x,string? y)>("select @x as x, @y as y", obj);
Assert.Equal("abc", row.x);
Assert.Null(row.y);
// with lengths
obj = new { x = new DbString("abc", 200), y = (DbString?)new DbString(null, 200) };
row = connection.QuerySingle<(string? x, string? y)>("select @x as x, @y as y", obj);
Assert.Equal("abc", row.x);
Assert.Null(row.y);
// null raw value - give clear message, at least
obj = obj with { y = null };
var ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingle<(string? x, string? y)>("select @x as x, @y as y", obj));
Assert.Equal("Member 'y' is an ICustomQueryParameter and cannot be null", ex.Message);
}
[Fact]
public void TestDbStringToString()
{
Assert.Equal("Dapper.DbString (Value: 'abcde', Length: 10, IsAnsi: True, IsFixedLength: True)",
new DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi = true }.ToString());
Assert.Equal("Dapper.DbString (Value: 'abcde', Length: 10, IsAnsi: False, IsFixedLength: True)",
new DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi = false }.ToString());
Assert.Equal("Dapper.DbString (Value: 'abcde', Length: 10, IsAnsi: True, IsFixedLength: False)",
new DbString { Value = "abcde", IsFixedLength = false, Length = 10, IsAnsi = true }.ToString());
Assert.Equal("Dapper.DbString (Value: 'abcde', Length: 10, IsAnsi: False, IsFixedLength: False)",
new DbString { Value = "abcde", IsFixedLength = false, Length = 10, IsAnsi = false }.ToString());
Assert.Equal("Dapper.DbString (Value: null, Length: -1, IsAnsi: False, IsFixedLength: False)",
new DbString { Value = null }.ToString());
Assert.Equal("Dapper.DbString (Value: 'abcde', Length: -1, IsAnsi: True, IsFixedLength: False)",
new DbString { Value = "abcde", IsAnsi = true }.ToString());
Assert.Equal("Dapper.DbString (Value: 'abcde', Length: -1, IsAnsi: False, IsFixedLength: False)",
new DbString { Value = "abcde", IsAnsi = false }.ToString());
}
[Fact]
public void TestDefaultDbStringDbType()
{
var origDefaultStringDbType = DbString.IsAnsiDefault;
try
{
DbString.IsAnsiDefault = true;
var a = new DbString { Value = "abcde" };
var b = new DbString { Value = "abcde", IsAnsi = false };
Assert.True(a.IsAnsi);
Assert.False(b.IsAnsi);
}
finally
{
DbString.IsAnsiDefault = origDefaultStringDbType;
}
}
[Fact]
public void TestFastExpandoSupportsIDictionary()
{
var row = connection.Query("select 1 A, 'two' B").First() as IDictionary<string, object>;
Assert.NotNull(row);
Assert.Equal(1, row["A"]);
Assert.Equal("two", row["B"]);
}
[Fact]
public void TestDapperSetsPrivates()
{
Assert.Equal(1, connection.Query<PrivateDan>("select 'one' ShadowInDB").First().Shadow);
Assert.Equal(1, connection.QueryFirstOrDefault<PrivateDan>("select 'one' ShadowInDB")?.Shadow);
}
private class PrivateDan
{
public int Shadow { get; set; }
private string ShadowInDB
{
set { Shadow = value == "one" ? 1 : 0; }
}
}
[Fact]
public void TestUnexpectedDataMessage()
{
string? msg = null;
try
{
connection.Query<int>("select count(1) where 1 = @Foo", new WithBizarreData { Foo = new GenericUriParser(GenericUriParserOptions.Default), Bar = 23 }).First();
}
catch (Exception ex)
{
msg = ex.Message;
}
Assert.Equal("The member Foo of type System.GenericUriParser cannot be used as a parameter value", msg);
}
[Fact]
public void TestUnexpectedButFilteredDataMessage()
{
int i = connection.Query<int>("select @Bar", new WithBizarreData { Foo = new GenericUriParser(GenericUriParserOptions.Default), Bar = 23 }).Single();
Assert.Equal(23, i);
}
private class WithBizarreData
{
public GenericUriParser? Foo { get; set; }
public int Bar { get; set; }
}
private class WithCharValue
{
public char Value { get; set; }
public char? ValueNullable { get; set; }
}
[Fact]
public void TestCharInputAndOutput()
{
const char test = '〠';
char c = connection.Query<char>("select @c", new { c = test }).Single();
Assert.Equal(test, c);
var obj = connection.Query<WithCharValue>("select @Value as Value", new WithCharValue { Value = c }).Single();
Assert.Equal(test, obj.Value);
}
[Fact]
public void TestNullableCharInputAndOutputNonNull()
{
char? test = '〠';
char? c = connection.Query<char?>("select @c", new { c = test }).Single();
Assert.Equal(c, test);
var obj = connection.Query<WithCharValue>("select @ValueNullable as ValueNullable", new WithCharValue { ValueNullable = c }).Single();
Assert.Equal(obj.ValueNullable, test);
}
[Fact]
public void TestNullableCharInputAndOutputNull()
{
char? test = null;
char? c = connection.Query<char?>("select @c", new { c = test }).Single();
Assert.Equal(c, test);
var obj = connection.Query<WithCharValue>("select @ValueNullable as ValueNullable", new WithCharValue { ValueNullable = c }).Single();
Assert.Equal(obj.ValueNullable, test);
}
[Fact]
public void WorkDespiteHavingWrongStructColumnTypes()
{
var hazInt = connection.Query<CanHazInt>("select cast(1 as bigint) Value").Single();
Assert.Equal(1, hazInt.Value);
}
private struct CanHazInt
{
public int Value { get; set; }
}
[Fact]
public void TestInt16Usage()
{
Assert.Equal((short)42, connection.Query<short>("select cast(42 as smallint)").Single());
Assert.Equal((short?)42, connection.Query<short?>("select cast(42 as smallint)").Single());
Assert.Equal((short?)null, connection.Query<short?>("select cast(null as smallint)").Single());
Assert.Equal((ShortEnum)42, connection.Query<ShortEnum>("select cast(42 as smallint)").Single());
Assert.Equal((ShortEnum?)42, connection.Query<ShortEnum?>("select cast(42 as smallint)").Single());
Assert.Equal((ShortEnum?)null, connection.Query<ShortEnum?>("select cast(null as smallint)").Single());
var row =
connection.Query<WithInt16Values>(
"select cast(1 as smallint) as NonNullableInt16, cast(2 as smallint) as NullableInt16, cast(3 as smallint) as NonNullableInt16Enum, cast(4 as smallint) as NullableInt16Enum")
.Single();
Assert.Equal((short)1, row.NonNullableInt16);
Assert.Equal((short)2, row.NullableInt16);
Assert.Equal(ShortEnum.Three, row.NonNullableInt16Enum);
Assert.Equal(ShortEnum.Four, row.NullableInt16Enum);
row =
connection.Query<WithInt16Values>(
"select cast(5 as smallint) as NonNullableInt16, cast(null as smallint) as NullableInt16, cast(6 as smallint) as NonNullableInt16Enum, cast(null as smallint) as NullableInt16Enum")
.Single();
Assert.Equal((short)5, row.NonNullableInt16);
Assert.Equal((short?)null, row.NullableInt16);
Assert.Equal(ShortEnum.Six, row.NonNullableInt16Enum);
Assert.Equal((ShortEnum?)null, row.NullableInt16Enum);
}
[Fact]
public void TestInt32Usage()
{
Assert.Equal((int)42, connection.Query<int>("select cast(42 as int)").Single());
Assert.Equal((int?)42, connection.Query<int?>("select cast(42 as int)").Single());
Assert.Equal((int?)null, connection.Query<int?>("select cast(null as int)").Single());
Assert.Equal((IntEnum)42, connection.Query<IntEnum>("select cast(42 as int)").Single());
Assert.Equal((IntEnum?)42, connection.Query<IntEnum?>("select cast(42 as int)").Single());
Assert.Equal((IntEnum?)null, connection.Query<IntEnum?>("select cast(null as int)").Single());
var row =
connection.Query<WithInt32Values>(
"select cast(1 as int) as NonNullableInt32, cast(2 as int) as NullableInt32, cast(3 as int) as NonNullableInt32Enum, cast(4 as int) as NullableInt32Enum")
.Single();
Assert.Equal((int)1, row.NonNullableInt32);
Assert.Equal((int)2, row.NullableInt32);
Assert.Equal(IntEnum.Three, row.NonNullableInt32Enum);
Assert.Equal(IntEnum.Four, row.NullableInt32Enum);
row =
connection.Query<WithInt32Values>(
"select cast(5 as int) as NonNullableInt32, cast(null as int) as NullableInt32, cast(6 as int) as NonNullableInt32Enum, cast(null as int) as NullableInt32Enum")
.Single();
Assert.Equal((int)5, row.NonNullableInt32);
Assert.Equal((int?)null, row.NullableInt32);
Assert.Equal(IntEnum.Six, row.NonNullableInt32Enum);
Assert.Equal((IntEnum?)null, row.NullableInt32Enum);
}
public class WithInt16Values
{
public short NonNullableInt16 { get; set; }
public short? NullableInt16 { get; set; }
public ShortEnum NonNullableInt16Enum { get; set; }
public ShortEnum? NullableInt16Enum { get; set; }
}
public class WithInt32Values
{
public int NonNullableInt32 { get; set; }
public int? NullableInt32 { get; set; }
public IntEnum NonNullableInt32Enum { get; set; }
public IntEnum? NullableInt32Enum { get; set; }
}
public enum IntEnum : int
{
Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6
}
[Fact]
public void Issue_40_AutomaticBoolConversion()
{
var user = connection.Query<Issue40_User>("select UserId=1,Email='abc',Password='changeme',Active=cast(1 as tinyint)").Single();
Assert.True(user.Active);
Assert.Equal(1, user.UserID);
Assert.Equal("abc", user.Email);
Assert.Equal("changeme", user.Password);
}
public class Issue40_User
{
public Issue40_User()
{
Email = Password = string.Empty;
}
public int UserID { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool Active { get; set; }
}
[Fact]
public void ExecuteFromClosed()
{
using var conn = GetClosedConnection();
conn.Execute("-- nop");
Assert.Equal(ConnectionState.Closed, conn.State);
}
[Fact]
public void ExecuteInvalidFromClosed()
{
using var conn = GetClosedConnection();
var ex = Assert.ThrowsAny<Exception>(() => conn.Execute("nop"));
Assert.Equal(ConnectionState.Closed, conn.State);
}
[Fact]
public void QueryFromClosed()
{
using var conn = GetClosedConnection();
var i = conn.Query<int>("select 1").Single();
Assert.Equal(ConnectionState.Closed, conn.State);
Assert.Equal(1, i);
}
[Fact]
public void QueryInvalidFromClosed()
{
using var conn = GetClosedConnection();
Assert.ThrowsAny<Exception>(() => conn.Query<int>("select gibberish").Single());
Assert.Equal(ConnectionState.Closed, conn.State);
}
[Fact]
public void TestDynamicMutation()
{
var obj = connection.Query("select 1 as [a], 2 as [b], 3 as [c]").Single();
Assert.Equal(1, (int)obj.a);
IDictionary<string, object> dict = obj;
Assert.Equal(3, dict.Count);
Assert.True(dict.Remove("a"));
Assert.False(dict.Remove("d"));
Assert.Equal(2, dict.Count);
dict.Add("d", 4);
Assert.Equal(3, dict.Count);
Assert.Equal("b,c,d", string.Join(",", dict.Keys.OrderBy(x => x)));
Assert.Equal("2,3,4", string.Join(",", dict.OrderBy(x => x.Key).Select(x => x.Value)));
Assert.Equal(2, (int)obj.b);
Assert.Equal(3, (int)obj.c);
Assert.Equal(4, (int)obj.d);
try
{
Assert.Equal(1, (int)obj.a);
throw new InvalidOperationException("should have thrown");
}
catch (RuntimeBinderException)
{
// pass
}
}
[Fact]
public void TestIssue131()
{
var results = connection.Query<dynamic, int, dynamic>(