-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathDataTypes.cs
1899 lines (1736 loc) · 89.9 KB
/
DataTypes.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.Globalization;
using System.Runtime.InteropServices;
#if MYSQL_DATA
using MySql.Data.Types;
#endif
// mysql-connector-net will throw SqlNullValueException, which is an exception type related to SQL Server:
// "The exception that is thrown when the Value property of a System.Data.SqlTypes structure is set to null."
// However, DbDataReader.GetString etc. are documented as throwing InvalidCastException: https://msdn.microsoft.com/en-us/library/system.data.common.dbdatareader.getstring.aspx
// Additionally, that is what DbDataReader.GetFieldValue<T> throws. For consistency, we prefer InvalidCastException.
#if MYSQL_DATA
using GetBytesWhenNullException = System.NullReferenceException;
using GetGeometryWhenNullException = System.Exception;
using GetGuidWhenNullException = MySql.Data.MySqlClient.MySqlException;
using GetStreamWhenNullException = System.ArgumentNullException;
using GetValueWhenNullException = System.Data.SqlTypes.SqlNullValueException;
#else
using GetBytesWhenNullException = System.InvalidCastException;
using GetGeometryWhenNullException = System.InvalidCastException;
using GetGuidWhenNullException = System.InvalidCastException;
using GetStreamWhenNullException = System.InvalidCastException;
using GetValueWhenNullException = System.InvalidCastException;
#endif
namespace IntegrationTests;
public sealed class DataTypes : IClassFixture<DataTypesFixture>, IDisposable
{
public DataTypes(DataTypesFixture database)
{
Connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString);
Connection.Open();
}
public void Dispose() => Connection.Dispose();
[Theory]
[InlineData("SByte", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, true, true, true })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, false, true, true })]
[InlineData("Int16", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, true, true, true })]
[InlineData("UInt16", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, false, true, true })]
[InlineData("Int24", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, true, true, true })]
[InlineData("UInt24", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, false, true, true })]
[InlineData("Int32", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, true, true, true })]
[InlineData("UInt32", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, false, true, true })]
[InlineData("Int64", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, true, true, true })]
[InlineData("UInt64", new[] { 1, 0, 0, 0, 0 }, new[] { false, false, false, true, true })]
public async Task GetBoolean(string column, int[] flags, bool[] values)
{
await DoGetValue(column, (r, n) => r.GetBoolean(n), (r, s) => r.GetBoolean(s), flags, values).ConfigureAwait(false);
}
[Theory]
[InlineData("SByte", new[] { 1, 0, 0, 0, 0 }, new short[] { 0, 0, -128, 127, 123 })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new short[] { 0, 0, 0, 255, 123 })]
[InlineData("Int16", new[] { 1, 0, 0, 0, 0 }, new short[] { 0, 0, -32768, 32767, 12345 })]
[InlineData("UInt16", new[] { 1, 0, 0, 2, 0 }, new short[] { 0, 0, 0, 0, 12345 })]
[InlineData("Int24", new[] { 1, 0, 2, 2, 2 }, new short[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt24", new[] { 1, 0, 0, 2, 2 }, new short[] { 0, 0, 0, 0, 0 })]
[InlineData("Int32", new[] { 1, 0, 2, 2, 2 }, new short[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt32", new[] { 1, 0, 0, 2, 2 }, new short[] { 0, 0, 0, 0, 0 })]
[InlineData("Int64", new[] { 1, 0, 2, 2, 2 }, new short[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt64", new[] { 1, 0, 0, 2, 2 }, new short[] { 0, 0, 0, 0, 0 })]
public async Task GetInt16(string column, int[] flags, short[] values)
{
await DoGetValue(column, (r, n) => r.GetInt16(n), (r, s) => r.GetInt16(s), flags, values).ConfigureAwait(false);
}
[Theory]
[InlineData("SByte", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, -128, 127, 123 })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, 0, 255, 123 })]
[InlineData("Int16", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, -32768, 32767, 12345 })]
[InlineData("UInt16", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, 0, 65535, 12345 })]
[InlineData("Int24", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, -8388608, 8388607, 1234567 })]
[InlineData("UInt24", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, 0, 16777215, 1234567 })]
[InlineData("Int32", new[] { 1, 0, 0, 0, 0 }, new[] { 0, 0, -2147483648, 2147483647, 123456789 })]
[InlineData("UInt32", new[] { 1, 0, 0, 2, 0 }, new[] { 0, 0, 0, 0, 123456789 })]
[InlineData("Int64", new[] { 1, 0, 2, 2, 2 }, new[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt64", new[] { 1, 0, 0, 2, 2 }, new[] { 0, 0, 0, 0, 0 })]
public async Task GetInt32(string column, int[] flags, int[] values)
{
await DoGetValue(column, (r, n) => r.GetInt32(n), (r, s) => r.GetInt32(s), flags, values).ConfigureAwait(false);
}
[Theory]
[InlineData("SByte", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, -128, 127, 123 })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, 0, 255, 123 })]
[InlineData("Int16", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, -32768, 32767, 12345 })]
[InlineData("UInt16", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, 0, 65535, 12345 })]
[InlineData("Int24", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, -8388608, 8388607, 1234567 })]
[InlineData("UInt24", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, 0, 16777215, 1234567 })]
[InlineData("Int32", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, -2147483648, 2147483647, 123456789 })]
[InlineData("UInt32", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, 0, 4294967295L, 123456789 })]
[InlineData("Int64", new[] { 1, 0, 0, 0, 0 }, new[] { 0L, 0, -9223372036854775808, 9223372036854775807, 1234567890123456789 })]
[InlineData("UInt64", new[] { 1, 0, 0, 2, 0 }, new[] { 0L, 0, 0, 0, 1234567890123456789 })]
public async Task GetInt64(string column, int[] flags, long[] values)
{
await DoGetValue(column, (r, n) => r.GetInt64(n), (r, s) => r.GetInt64(s), flags, values).ConfigureAwait(false);
}
[Theory]
[InlineData("SByte", new[] { 1, 0, 2, 0, 0 }, new ushort[] { 0, 0, 0, 127, 123 })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new ushort[] { 0, 0, 0, 255, 123 })]
[InlineData("Int16", new[] { 1, 0, 2, 0, 0 }, new ushort[] { 0, 0, 0, 32767, 12345 })]
[InlineData("UInt16", new[] { 1, 0, 0, 0, 0 }, new ushort[] { 0, 0, 0, 65535, 12345 })]
[InlineData("Int24", new[] { 1, 0, 2, 2, 2 }, new ushort[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt24", new[] { 1, 0, 0, 2, 2 }, new ushort[] { 0, 0, 0, 0, 0 })]
[InlineData("Int32", new[] { 1, 0, 2, 2, 2 }, new ushort[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt32", new[] { 1, 0, 0, 2, 2 }, new ushort[] { 0, 0, 0, 0, 0 })]
[InlineData("Int64", new[] { 1, 0, 2, 2, 2 }, new ushort[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt64", new[] { 1, 0, 0, 2, 2 }, new ushort[] { 0, 0, 0, 0, 0 })]
public async Task GetUInt16(string column, int[] flags, ushort[] values)
{
await DoGetValue(column, (r, n) => r.GetUInt16(n), (r, s) => r.GetUInt16(s), flags, values).ConfigureAwait(false);
}
[Theory]
[InlineData("SByte", new[] { 1, 0, 2, 0, 0 }, new uint[] { 0, 0, 0, 127, 123 })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new uint[] { 0, 0, 0, 255, 123 })]
[InlineData("Int16", new[] { 1, 0, 2, 0, 0 }, new uint[] { 0, 0, 0, 32767, 12345 })]
[InlineData("UInt16", new[] { 1, 0, 0, 0, 0 }, new uint[] { 0, 0, 0, 65535, 12345 })]
[InlineData("Int24", new[] { 1, 0, 2, 0, 0 }, new uint[] { 0, 0, 0, 8388607, 1234567 })]
[InlineData("UInt24", new[] { 1, 0, 0, 0, 0 }, new uint[] { 0, 0, 0, 16777215, 1234567 })]
[InlineData("Int32", new[] { 1, 0, 2, 0, 0 }, new uint[] { 0, 0, 0, 2147483647, 123456789 })]
[InlineData("UInt32", new[] { 1, 0, 0, 0, 0 }, new uint[] { 0, 0, 0, 4294967295, 123456789 })]
[InlineData("Int64", new[] { 1, 0, 2, 2, 2 }, new uint[] { 0, 0, 0, 0, 0 })]
[InlineData("UInt64", new[] { 1, 0, 0, 2, 2 }, new uint[] { 0, 0, 0, 0, 0 })]
public async Task GetUInt32(string column, int[] flags, uint[] values)
{
await DoGetValue(column, (r, n) => r.GetUInt32(n), (r, s) => r.GetUInt32(s), flags, values).ConfigureAwait(false);
}
[Theory]
[InlineData("SByte", new[] { 1, 0, 2, 0, 0 }, new ulong[] { 0, 0, 0, 127, 123 })]
[InlineData("Byte", new[] { 1, 0, 0, 0, 0 }, new ulong[] { 0, 0, 0, 255, 123 })]
[InlineData("Int16", new[] { 1, 0, 2, 0, 0 }, new ulong[] { 0, 0, 0, 32767, 12345 })]
[InlineData("UInt16", new[] { 1, 0, 0, 0, 0 }, new ulong[] { 0, 0, 0, 65535, 12345 })]
[InlineData("Int24", new[] { 1, 0, 2, 0, 0 }, new ulong[] { 0, 0, 0, 8388607, 1234567 })]
[InlineData("UInt24", new[] { 1, 0, 0, 0, 0 }, new ulong[] { 0, 0, 0, 16777215, 1234567 })]
[InlineData("Int32", new[] { 1, 0, 2, 0, 0 }, new ulong[] { 0, 0, 0, 2147483647, 123456789 })]
[InlineData("UInt32", new[] { 1, 0, 0, 0, 0 }, new ulong[] { 0, 0, 0, 4294967295, 123456789 })]
[InlineData("Int64", new[] { 1, 0, 2, 0, 0 }, new ulong[] { 0, 0, 0, 9223372036854775807, 1234567890123456789 })]
[InlineData("UInt64", new[] { 1, 0, 0, 0, 0 }, new ulong[] { 0, 0, 0, 18446744073709551615, 1234567890123456789 })]
public async Task GetUInt64(string column, int[] flags, ulong[] values)
{
await DoGetValue(column, (r, n) => r.GetUInt64(n), (r, s) => r.GetUInt64(s), flags, values).ConfigureAwait(false);
}
private async Task DoGetValue<T>(string column, Func<MySqlDataReader, int, T> getInt, Func<MySqlDataReader, string, T> getIntByName, int[] flags, T[] values)
{
using var cmd = Connection.CreateCommand();
cmd.CommandText = $"select {column} from datatypes_integers order by rowid";
using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync().ConfigureAwait(false);
for (int i = 0; i < flags.Length; i++)
{
Assert.True(await reader.ReadAsync().ConfigureAwait(false));
switch (flags[i])
{
case 0: // normal
Assert.Equal(values[i], getInt(reader, 0));
Assert.Equal(values[i], getIntByName(reader, column));
break;
case 1: // null
Assert.True(await reader.IsDBNullAsync(0).ConfigureAwait(false));
break;
case 2: // overflow
Assert.Throws<OverflowException>(() => getInt(reader, 0));
Assert.Throws<OverflowException>(() => getIntByName(reader, column));
break;
}
}
Assert.False(await reader.ReadAsync().ConfigureAwait(false));
Assert.False(await reader.NextResultAsync().ConfigureAwait(false));
}
[Theory]
[InlineData("size", "ENUM", new object[] { null, "small", "medium" })]
[InlineData("color", "ENUM", new object[] { "red", "orange", "green" })]
public void QueryEnum(string column, string dataTypeName, object[] expected)
{
#if MYSQL_DATA
// mysql-connector-net incorrectly returns "VARCHAR" for "ENUM"
dataTypeName = "VARCHAR";
#endif
DoQuery("enums", column, dataTypeName, expected, reader => reader.GetString(0));
}
[Theory]
[InlineData("value", "SET", new object[] { null, "", "one", "two", "one,two", "four", "one,four", "two,four", "one,two,four" })]
public void QuerySet(string column, string dataTypeName, object[] expected)
{
#if MYSQL_DATA
// mysql-connector-net incorrectly returns "VARCHAR" for "ENUM"
dataTypeName = "VARCHAR";
#endif
DoQuery("set", column, dataTypeName, expected, reader => reader.GetString(column));
}
[Theory]
[InlineData("Boolean", "BOOL", new object[] { null, false, true, false, true, true, true })]
[InlineData("TinyInt1", "BOOL", new object[] { null, false, true, false, true, true, true })]
public void QueryBoolean(string column, string dataTypeName, object[] expected)
{
#if MYSQL_DATA
// Connector/NET returns "TINYINT" for "BOOL"
dataTypeName = "TINYINT";
#endif
DoQuery<InvalidCastException>("bools", column, dataTypeName, expected, reader => reader.GetBoolean(0));
}
[Theory]
[InlineData("TinyInt1", "TINYINT", new object[] { null, (sbyte) 0, (sbyte) 1, (sbyte) 0, (sbyte) 1, (sbyte) -1, (sbyte) 123 })]
[InlineData("Boolean", "TINYINT", new object[] { null, (sbyte) 0, (sbyte) 1, (sbyte) 0, (sbyte) 1, (sbyte) -1, (sbyte) 123 })]
public void QueryTinyIntSbyte(string column, string dataTypeName, object[] expected)
{
var csb = CreateConnectionStringBuilder();
csb.TreatTinyAsBoolean = false;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
DoQuery("bools", column, dataTypeName, expected, reader => reader.GetSByte(0), mySqlDataCoercedNullValue: default(sbyte), connection: connection);
}
[Theory]
[InlineData("TinyInt1U", "TINYINT", new object[] { null, (byte) 0, (byte) 1, (byte) 0, (byte) 1, (byte) 255, (byte) 123 })]
public void QueryTinyInt1Unsigned(string column, string dataTypeName, object[] expected)
{
DoQuery("bools", column, dataTypeName, expected, reader => reader.GetByte(0), mySqlDataCoercedNullValue: default(byte));
}
[Theory]
[InlineData("SByte", "TINYINT", new object[] { null, default(sbyte), sbyte.MinValue, sbyte.MaxValue, (sbyte) 123 })]
public void QuerySByte(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetSByte(column), mySqlDataCoercedNullValue: default(sbyte));
}
[Theory]
[InlineData("Byte", "TINYINT", new object[] { null, default(byte), byte.MinValue, byte.MaxValue, (byte) 123 })]
public void QueryByte(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetByte(0), mySqlDataCoercedNullValue: default(byte));
}
[Theory]
[InlineData("Int16", "SMALLINT", new object[] { null, default(short), short.MinValue, short.MaxValue, (short) 12345 })]
public void QueryInt16(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetInt16(0));
}
[Theory]
[InlineData("UInt16", "SMALLINT", new object[] { null, default(ushort), ushort.MinValue, ushort.MaxValue, (ushort) 12345 })]
public void QueryUInt16(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetUInt16(column));
}
[Theory]
[InlineData("Int24", "MEDIUMINT", new object[] { null, default(int), -8388608, 8388607, 1234567 })]
[InlineData("Int32", "INT", new object[] { null, default(int), int.MinValue, int.MaxValue, 123456789 })]
public void QueryInt32(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetInt32(0));
}
[Theory]
[InlineData("UInt24", "MEDIUMINT", new object[] { null, default(uint), 0u, 16777215u, 1234567u })]
[InlineData("UInt32", "INT", new object[] { null, default(uint), uint.MinValue, uint.MaxValue, 123456789u })]
public void QueryUInt32(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetUInt32(column));
}
[Theory]
[InlineData("Int64", "BIGINT", new object[] { null, default(long), long.MinValue, long.MaxValue, 1234567890123456789 })]
public void QueryInt64(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetInt64(0));
}
[Theory]
[InlineData("UInt64", "BIGINT", new object[] { null, default(ulong), ulong.MinValue, ulong.MaxValue, 1234567890123456789u })]
public void QueryUInt64(string column, string dataTypeName, object[] expected)
{
DoQuery("integers", column, dataTypeName, expected, reader => reader.GetUInt64(0));
}
[Theory]
[InlineData("Bit1", new object[] { null, 0UL, 1UL, 1UL })]
[InlineData("Bit32", new object[] { null, 0UL, 1UL, (ulong) uint.MaxValue })]
[InlineData("Bit64", new object[] { null, 0UL, 1UL, ulong.MaxValue })]
public void QueryBits(string column, object[] expected)
{
DoQuery("bits", column, "BIT", expected, reader => reader.GetUInt64(column));
}
[Theory]
[InlineData("Single", "FLOAT", new object[] { null, default(float), -3.40282e38f, -1.4013e-45f, 3.40282e38f, 1.4013e-45f })]
public void QueryFloat(string column, string dataTypeName, object[] expected)
{
// don't perform exact queries for floating-point values; they may fail: http://dev.mysql.com/doc/refman/5.7/en/problems-with-float.html
DoQuery("reals", column, dataTypeName, expected, reader => reader.GetFloat(0), omitWhereTest: true);
}
[Theory]
[InlineData("`Double`", "DOUBLE", new object[] { null, default(double), -1.7976931348623157e308, -5e-324, 1.7976931348623157e308, 5e-324 })]
public void QueryDouble(string column, string dataTypeName, object[] expected)
{
DoQuery("reals", column, dataTypeName, expected, reader => reader.GetDouble(0));
}
[Theory]
[InlineData("SmallDecimal", new object[] { null, "0", "-999.99", "-0.01", "999.99", "0.01" })]
[InlineData("MediumDecimal", new object[] { null, "0", "-999999999999.99999999", "-0.00000001", "999999999999.99999999", "0.00000001" })]
//// value exceeds the range of a decimal and cannot be deserialized
//// [InlineData("BigDecimal", new object[] { null, "0", "-99999999999999999999.999999999999999999999999999999", "-0.000000000000000000000000000001", "99999999999999999999.999999999999999999999999999999", "0.000000000000000000000000000001" })]
public void QueryDecimal(string column, object[] expected)
{
for (int i = 0; i < expected.Length; i++)
if (expected[i] is string expectedValue)
expected[i] = decimal.Parse(expectedValue, CultureInfo.InvariantCulture);
DoQuery("reals", column, "DECIMAL", expected, reader => reader.GetDecimal(0));
}
[Theory]
[InlineData("utf8", new[] { null, "", "ASCII", "Ũńıċōđĕ", c_251ByteString })]
[InlineData("utf8bin", new[] { null, "", "ASCII", "Ũńıċōđĕ", c_251ByteString })]
[InlineData("latin1", new[] { null, "", "ASCII", "Lãtïñ", c_251ByteString })]
[InlineData("latin1bin", new[] { null, "", "ASCII", "Lãtïñ", c_251ByteString })]
[InlineData("cp1251", new[] { null, "", "ASCII", "АБВГабвг", c_251ByteString })]
public void QueryString(string column, string[] expected)
{
DoQuery("strings", column, "VARCHAR", expected, reader => reader.GetString(0));
#if !MYSQL_DATA
DoQuery("strings", column, "VARCHAR", expected, reader => reader.GetTextReader(0), matchesDefaultType: false, assertEqual: (e, a) =>
{
using var actualReader = (TextReader) a;
Assert.Equal(e, actualReader.ReadToEnd());
}, getFieldValueType: typeof(TextReader));
#endif
}
private const string c_251ByteString = "This string has exactly 251 characters in it. The encoded length is stored as 0xFC 0xFB 0x00. 0xFB (i.e., 251) is the sentinel byte indicating \"this field is null\". Incorrectly interpreting the (decoded) length as the sentinel byte would corrupt data.";
[Theory]
[InlineData("guid", "CHAR(36)", new object[] { null, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-c000-000000000046", "fd24a0e8-c3f2-4821-a456-35da2dc4bb8f", "6A0E0A40-6228-11D3-A996-0050041896C8" })]
[InlineData("guidbin", "CHAR(36)", new object[] { null, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-c000-000000000046", "fd24a0e8-c3f2-4821-a456-35da2dc4bb8f", "6A0E0A40-6228-11D3-A996-0050041896C8" })]
public void QueryGuid(string column, string dataTypeName, object[] expected)
{
for (int i = 0; i < expected.Length; i++)
if (expected[i] is string expectedValue)
expected[i] = Guid.Parse(expectedValue);
DoQuery<GetGuidWhenNullException>("strings", column, dataTypeName, expected, reader => reader.GetGuid(0));
}
[Theory]
[InlineData("utf8", new[] { null, "", "ASCII", "Ũńıċōđĕ", c_251ByteString })]
[InlineData("cp1251", new[] { null, "", "ASCII", "АБВГабвг", c_251ByteString })]
public void QueryChar(string column, string[] expected)
{
using var cmd = Connection.CreateCommand();
cmd.CommandText = $@"select `{column}` from datatypes_strings order by rowid;";
using var reader = cmd.ExecuteReader();
for (var i = 0; i < expected.Length; i++)
{
Assert.True(reader.Read());
if (expected[i] is null)
Assert.True(reader.IsDBNull(0));
else if (expected[i].Length == 0)
#if MYSQL_DATA
Assert.Throws<IndexOutOfRangeException>(() => reader.GetChar(0));
#else
Assert.Throws<InvalidCastException>(() => reader.GetChar(0));
#endif
else
Assert.Equal(expected[i][0], reader.GetChar(0));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void QueryBinaryGuid(bool oldGuids)
{
var csb = CreateConnectionStringBuilder();
csb.OldGuids = oldGuids;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
using var cmd = connection.CreateCommand();
cmd.CommandText = @"select guidbin from datatypes_blobs order by rowid;";
using (var reader = cmd.ExecuteReader())
{
Assert.True(reader.Read());
Assert.Equal(DBNull.Value, reader.GetValue(0));
Assert.True(reader.Read());
var expectedBytes = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
var expectedGuid = new Guid(expectedBytes);
if (oldGuids)
{
Assert.Equal(typeof(Guid), reader.GetFieldType(0));
Assert.Equal(expectedGuid, reader.GetValue(0));
}
else
{
Assert.Equal(typeof(byte[]), reader.GetFieldType(0));
Assert.Equal(expectedBytes, reader.GetValue(0));
}
Assert.Equal(expectedGuid, reader.GetGuid(0));
Assert.Equal(expectedBytes, GetBytes(reader));
#if !MYSQL_DATA
Assert.Equal(expectedBytes, GetStreamBytes(reader));
#endif
Assert.False(reader.Read());
}
cmd.CommandText = @"select guidbin from datatypes_strings order by rowid;";
using (var reader = cmd.ExecuteReader())
{
Assert.True(reader.Read());
Assert.Equal(DBNull.Value, reader.GetValue(0));
Assert.True(reader.Read());
if (oldGuids)
{
Assert.Equal(typeof(string), reader.GetFieldType(0));
Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetValue(0));
Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetString("guidbin"));
}
else
{
Assert.Equal(typeof(Guid), reader.GetFieldType(0));
Assert.Equal(Guid.Empty, reader.GetValue(0));
}
Assert.Equal(Guid.Empty, reader.GetGuid("guidbin"));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task QueryWithGuidParameter(bool oldGuids)
{
var csb = CreateConnectionStringBuilder();
csb.OldGuids = oldGuids;
using var connection = new MySqlConnection(csb.ConnectionString);
await connection.OpenAsync().ConfigureAwait(false);
try
{
Assert.Equal(oldGuids ? 0L : 1L, (await connection.QueryAsync<long>(@"select count(*) from datatypes_strings where guid = @guid", new { guid = new Guid("fd24a0e8-c3f2-4821-a456-35da2dc4bb8f") }).ConfigureAwait(false)).SingleOrDefault());
Assert.Equal(oldGuids ? 0L : 1L, (await connection.QueryAsync<long>(@"select count(*) from datatypes_strings where guidbin = @guid", new { guid = new Guid("fd24a0e8-c3f2-4821-a456-35da2dc4bb8f") }).ConfigureAwait(false)).SingleOrDefault());
}
catch (MySqlException ex) when (oldGuids && ex.Number is 1300 or 3854) //// InvalidCharacterString, CannotConvertString
{
// new error in MySQL 8.0.24, MariaDB 10.5
}
Assert.Equal(oldGuids ? 1L : 0L, (await connection.QueryAsync<long>(@"select count(*) from datatypes_blobs where guidbin = @guid", new { guid = new Guid(0x33221100, 0x5544, 0x7766, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF) }).ConfigureAwait(false)).SingleOrDefault());
}
[Theory]
[InlineData("char38", typeof(string))]
[InlineData("char38bin", typeof(string))]
[InlineData("text", typeof(string))]
[InlineData("blob", typeof(byte[]))]
public async Task GetGuid(string column, Type fieldType)
{
using var cmd = Connection.CreateCommand();
cmd.CommandText = $"select `{column}` from datatypes_guids order by rowid";
using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
Assert.Equal(fieldType, reader.GetFieldType(0));
Assert.True(await reader.ReadAsync().ConfigureAwait(false));
Assert.True(reader.IsDBNull(0));
Assert.Throws<GetGuidWhenNullException>(() => reader.GetGuid(0));
Assert.True(await reader.ReadAsync().ConfigureAwait(false));
Assert.False(reader.IsDBNull(0));
Assert.NotNull(reader.GetValue(0));
Assert.IsType(fieldType, reader.GetValue(0));
Type exceptionType = typeof(GetGuidWhenNullException);
#if MYSQL_DATA
// MySql.Data throws FormatException when conversion from string fails
if (fieldType == typeof(string))
exceptionType = typeof(FormatException);
#endif
Assert.Throws(exceptionType, () => reader.GetGuid(0));
Assert.True(await reader.ReadAsync().ConfigureAwait(false));
Assert.NotNull(reader.GetValue(0));
Assert.IsType(fieldType, reader.GetValue(0));
Assert.Equal(new Guid("33221100-5544-7766-8899-aabbccddeeff"), reader.GetGuid(0));
Assert.True(await reader.ReadAsync().ConfigureAwait(false));
Assert.NotNull(reader.GetValue(0));
Assert.IsType(fieldType, reader.GetValue(0));
Assert.Equal(new Guid("33221100-5544-7766-8899-aabbccddeeff"), reader.GetGuid(0));
Assert.False(await reader.ReadAsync().ConfigureAwait(false));
}
#if !MYSQL_DATA
[Theory]
[InlineData(MySqlGuidFormat.Default, false)]
[InlineData(MySqlGuidFormat.Default, true)]
[InlineData(MySqlGuidFormat.None, false)]
[InlineData(MySqlGuidFormat.Char36, false)]
[InlineData(MySqlGuidFormat.Char32, false)]
[InlineData(MySqlGuidFormat.Binary16, false)]
[InlineData(MySqlGuidFormat.TimeSwapBinary16, false)]
[InlineData(MySqlGuidFormat.LittleEndianBinary16, false)]
public void QueryGuidFormat(MySqlGuidFormat guidFormat, bool oldGuids)
{
bool isChar36 = guidFormat == MySqlGuidFormat.Char36 || (guidFormat == MySqlGuidFormat.Default && !oldGuids);
bool isChar32 = guidFormat == MySqlGuidFormat.Char32;
bool isBinary16 = guidFormat == MySqlGuidFormat.Binary16;
bool isTimeSwapBinary16 = guidFormat == MySqlGuidFormat.TimeSwapBinary16;
bool isLittleEndianBinary16 = guidFormat == MySqlGuidFormat.LittleEndianBinary16 || (guidFormat == MySqlGuidFormat.Default && oldGuids);
Guid guid = new Guid("00112233-4455-6677-8899-AABBCCDDEEFF");
string guidAsChar36 = "00112233-4455-6677-8899-AABBCCDDEEFF";
string guidAsChar32 = "00112233445566778899AABBCCDDEEFF";
byte[] guidAsBinary16 = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
byte[] guidAsTimeSwapBinary16 = { 0x66, 0x77, 0x44, 0x55, 0x00, 0x11, 0x22, 0x33, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
byte[] guidAsLittleEndianBinary16 = { 0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
bool uuidToBin = AppConfig.SupportedFeatures.HasFlag(ServerFeatures.UuidToBin);
string sql = $@"drop table if exists guid_format;
create table guid_format(
rowid integer not null primary key auto_increment,
c36 char(36),
c32 char(32),
b16 binary(16),
tsb16 binary(16),
leb16 binary(16),
t text,
b blob);
insert into guid_format(c36, c32, b16, tsb16, leb16, t, b) values(?, ?, ?, ?, ?, ?, ?);
insert into guid_format(c36, c32, b16, tsb16, leb16, t, b) values(?, ?, ?, ?, ?, ?, ?);
insert into guid_format(c36, c32, b16, tsb16, leb16, t, b) values(
'00112233-4455-6677-8899-AABBCCDDEEFF',
'00112233445566778899AABBCCDDEEFF',
{(uuidToBin ? "UUID_TO_BIN('00112233-4455-6677-8899-AABBCCDDEEFF', FALSE)" : "UNHEX('00112233445566778899AABBCCDDEEFF')")},
{(uuidToBin ? "UUID_TO_BIN('00112233-4455-6677-8899-AABBCCDDEEFF', TRUE)" : "UNHEX('66774455001122338899AABBCCDDEEFF')")},
UNHEX('33221100554477668899AABBCCDDEEFF'),
{(uuidToBin ? "BIN_TO_UUID(UNHEX('00112233445566778899AABBCCDDEEFF'))" : "'00112233-4455-6677-8899-AABBCCDDEEFF'")},
{(isBinary16 ? (uuidToBin ? "UUID_TO_BIN('00112233-4455-6677-8899-AABBCCDDEEFF')" : "UNHEX('00112233445566778899AABBCCDDEEFF')") : isTimeSwapBinary16 ? (uuidToBin ? "UUID_TO_BIN('00112233-4455-6677-8899-AABBCCDDEEFF', TRUE)" : "UNHEX('66774455001122338899AABBCCDDEEFF')") : "UNHEX('33221100554477668899AABBCCDDEEFF')")});
";
var csb = CreateConnectionStringBuilder();
csb.GuidFormat = guidFormat;
csb.OldGuids = oldGuids;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
using var cmd = new MySqlCommand(sql, connection)
{
Parameters =
{
new() { Value = guidAsChar36 },
new() { Value = guidAsChar32 },
new() { Value = guidAsBinary16 },
new() { Value = guidAsTimeSwapBinary16 },
new() { Value = guidAsLittleEndianBinary16 },
new() { Value = guidAsChar36 },
new() { Value = isBinary16 ? guidAsBinary16 : isTimeSwapBinary16 ? guidAsTimeSwapBinary16 : guidAsLittleEndianBinary16 },
new() { Value = isChar36 ? guid : guidAsChar36 },
new() { Value = isChar32 ? guid : guidAsChar32 },
new() { Value = isBinary16 ? guid : guidAsBinary16 },
new() { Value = isTimeSwapBinary16 ? guid : guidAsTimeSwapBinary16 },
new() { Value = isLittleEndianBinary16 ? guid : guidAsLittleEndianBinary16 },
new() { Value = guidAsChar32 },
new() { Value = isBinary16 ? guidAsBinary16 : isTimeSwapBinary16 ? guidAsTimeSwapBinary16 : guidAsLittleEndianBinary16 },
},
};
cmd.ExecuteNonQuery();
cmd.CommandText = "select c36, c32, b16, tsb16, leb16, t, b from guid_format;";
using var reader = cmd.ExecuteReader();
for (int row = 0; row < 3; row++)
{
Assert.True(reader.Read());
object c36 = reader.GetValue(0);
if (isChar36)
Assert.Equal(guid, (Guid) c36);
else
Assert.Equal(guidAsChar36, (string) c36);
Assert.Equal(guid, reader.GetGuid(0));
object c32 = reader.GetValue(1);
if (isChar32)
Assert.Equal(guid, (Guid) c32);
else
Assert.Equal(guidAsChar32, (string) c32);
Assert.Equal(guid, reader.GetGuid(1));
object b16 = reader.GetValue(2);
if (isBinary16)
Assert.Equal(guid, (Guid) b16);
else if (isTimeSwapBinary16 || isLittleEndianBinary16)
Assert.NotEqual(guid, (Guid) b16);
else
Assert.Equal(guidAsBinary16, (byte[]) b16);
if (isBinary16)
Assert.Equal(guid, reader.GetGuid(2));
object tsb16 = reader.GetValue(3);
if (isTimeSwapBinary16)
Assert.Equal(guid, (Guid) tsb16);
else if (isBinary16 || isLittleEndianBinary16)
Assert.NotEqual(guid, (Guid) tsb16);
else
Assert.Equal(guidAsTimeSwapBinary16, (byte[]) tsb16);
if (isTimeSwapBinary16)
Assert.Equal(guid, reader.GetGuid(3));
object leb16 = reader.GetValue(4);
if (isLittleEndianBinary16)
Assert.Equal(guid, (Guid) leb16);
else if (isBinary16 || isTimeSwapBinary16)
Assert.NotEqual(guid, (Guid) leb16);
else
Assert.Equal(guidAsLittleEndianBinary16, (byte[]) leb16);
if (!isBinary16 && !isTimeSwapBinary16)
Assert.Equal(guid, reader.GetGuid(4));
Assert.IsType<string>(reader.GetValue(5));
Assert.Equal(guid, reader.GetGuid(5));
Assert.IsType<byte[]>(reader.GetValue(6));
Assert.Equal(guid, reader.GetGuid(6));
}
Assert.False(reader.Read());
}
#endif
[Theory]
[InlineData("`Date`", "DATE", new object[] { null, "1000 01 01", "9999 12 31", null, "2016 04 05" })]
[InlineData("`DateTime`", "DATETIME", new object[] { null, "1000 01 01 0 0 0", "9999 12 31 23 59 59 999999", null, "2016 4 5 14 3 4 567890" })]
[InlineData("`Timestamp`", "TIMESTAMP", new object[] { null, "1970 01 01 0 0 1", "2038 1 18 3 14 7 999999", null, "2016 4 5 14 3 4 567890" })]
public void QueryDate(string column, string dataTypeName, object[] expected)
{
DoQuery("times", column, dataTypeName, ConvertToDateTime(expected, DateTimeKind.Unspecified), reader => reader.GetDateTime(column.Replace("`", "")));
#if !MYSQL_DATA
DoQuery("times", column, dataTypeName, ConvertToDateTimeOffset(expected), reader => reader.GetDateTimeOffset(0), matchesDefaultType: false);
#endif
}
#if NET6_0_OR_GREATER && !MYSQL_DATA
[Theory]
[InlineData("`Date`", "DATE", new object[] { null, "1000 01 01", "9999 12 31", null, "2016 04 05" })]
public void QueryDateOnly(string column, string dataTypeName, object[] expected)
{
DoQuery("times", column, dataTypeName, ConvertToDateOnly(expected), reader => reader.GetDateOnly(column.Replace("`", "")),
matchesDefaultType: false, assertEqual: (x, y) => Assert.Equal((DateOnly) x, y is DateTime dt ? DateOnly.FromDateTime(dt) : (DateOnly) y));
}
#endif
[SkippableTheory(ServerFeatures.ZeroDateTime)]
[InlineData(false)]
[InlineData(true)]
public void QueryZeroDateTime(bool convertZeroDateTime)
{
var csb = CreateConnectionStringBuilder();
csb.ConvertZeroDateTime = convertZeroDateTime;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
using var cmd = connection.CreateCommand();
cmd.CommandText = @"select cast(0 as date), cast(0 as datetime);";
using var reader = cmd.ExecuteReader();
Assert.True(reader.Read());
if (convertZeroDateTime)
{
Assert.Equal(DateTime.MinValue, reader.GetDateTime(0));
Assert.Equal(DateTime.MinValue, reader.GetDateTime(1));
#if !MYSQL_DATA
Assert.Equal(DateTimeOffset.MinValue, reader.GetDateTimeOffset(0));
Assert.Equal(DateTimeOffset.MinValue, reader.GetDateTimeOffset(1));
#endif
}
else
{
#if MYSQL_DATA
Assert.Throws<MySql.Data.Types.MySqlConversionException>(() => reader.GetDateTime(0));
Assert.Throws<MySql.Data.Types.MySqlConversionException>(() => reader.GetDateTime(1));
#else
Assert.Throws<InvalidCastException>(() => reader.GetDateTime(0));
Assert.Throws<InvalidCastException>(() => reader.GetDateTime(1));
Assert.Throws<InvalidCastException>(() => reader.GetDateTimeOffset(0));
Assert.Throws<InvalidCastException>(() => reader.GetDateTimeOffset(1));
#endif
}
}
#if !MYSQL_DATA
[Theory]
[InlineData(MySqlDateTimeKind.Unspecified, DateTimeKind.Unspecified, true)]
[InlineData(MySqlDateTimeKind.Unspecified, DateTimeKind.Local, true)]
[InlineData(MySqlDateTimeKind.Unspecified, DateTimeKind.Utc, true)]
[InlineData(MySqlDateTimeKind.Utc, DateTimeKind.Unspecified, true)]
[InlineData(MySqlDateTimeKind.Utc, DateTimeKind.Local, false)]
[InlineData(MySqlDateTimeKind.Utc, DateTimeKind.Utc, true)]
[InlineData(MySqlDateTimeKind.Local, DateTimeKind.Unspecified, true)]
[InlineData(MySqlDateTimeKind.Local, DateTimeKind.Local, true)]
[InlineData(MySqlDateTimeKind.Local, DateTimeKind.Utc, false)]
public void QueryDateTimeKind(MySqlDateTimeKind kindOption, DateTimeKind kindIn, bool success)
{
var csb = CreateConnectionStringBuilder();
csb.DateTimeKind = kindOption;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
var dateTimeIn = new DateTime(2001, 2, 3, 14, 5, 6, 789, kindIn);
using var cmd = new MySqlCommand(@"drop table if exists date_time_kind;
create table date_time_kind(
rowid integer not null primary key auto_increment,
d date,
dt0 datetime(0),
dt1 datetime(1),
dt2 datetime(2),
dt3 datetime(3),
dt4 datetime(4),
dt5 datetime(5),
dt6 datetime(6));
insert into date_time_kind(d, dt0, dt1, dt2, dt3, dt4, dt5, dt6) values(?, ?, ?, ?, ?, ?, ?, ?)", connection)
{
Parameters =
{
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
new() { Value = dateTimeIn },
},
};
if (success)
{
cmd.ExecuteNonQuery();
long lastInsertId = cmd.LastInsertedId;
cmd.CommandText = $"select d, dt0, dt1, dt2, dt3, dt4, dt5, dt6 from date_time_kind where rowid = {lastInsertId};";
using var reader = cmd.ExecuteReader();
Assert.True(reader.Read());
Assert.Equal(new DateTime(2001, 2, 3), reader.GetValue(0));
Assert.Equal(new DateTime(2001, 2, 3, 14, 5, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 7 : 6, kindIn), reader.GetValue(1));
Assert.Equal(new DateTime(2001, 2, 3, 14, 5, 6, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 800 : 700, kindIn), reader.GetValue(2));
Assert.Equal(new DateTime(2001, 2, 3, 14, 5, 6, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 790 : 780, kindIn), reader.GetValue(3));
Assert.Equal(dateTimeIn, reader.GetValue(4));
Assert.Equal(dateTimeIn, reader.GetValue(5));
Assert.Equal(dateTimeIn, reader.GetValue(6));
Assert.Equal(dateTimeIn, reader.GetValue(7));
for (int i = 0; i < 7; i++)
Assert.Equal(kindOption, (MySqlDateTimeKind) reader.GetDateTime(i).Kind);
}
else
{
Assert.Throws<MySqlException>(() => cmd.ExecuteNonQuery());
}
}
#endif
[Theory]
[InlineData("`Time`", "TIME", new object[] { null, "-838 -59 -59", "838 59 59", "0 0 0", "0 14 3 4 567890" })]
public void QueryTime(string column, string dataTypeName, object[] expected)
{
DoQuery("times", column, dataTypeName, ConvertToTimeSpan(expected), reader => reader.GetTimeSpan(0));
}
#if NET6_0_OR_GREATER && !MYSQL_DATA
[Theory]
[InlineData("TimeOnly", "TIME", new object[] { null, "0 0 0", "0 23 59 59 999999", "0 0 0", "0 14 3 4 567890" })]
public void QueryTimeOnly(string column, string dataTypeName, object[] expected)
{
DoQuery("times", column, dataTypeName, ConvertToTimeOnly(expected), reader => reader.GetTimeOnly(0),
matchesDefaultType: false, assertEqual: (x, y) => Assert.Equal((TimeOnly) x, y is TimeSpan ts ? TimeOnly.FromTimeSpan(ts) : (TimeOnly) y));
}
#endif
[Theory]
[InlineData("`Year`", "YEAR", new object[] { null, 1901, 2155, 0, 2016 })]
public void QueryYear(string column, string dataTypeName, object[] expected)
{
Func<MySqlDataReader, object> getValue = reader => reader.GetInt32(0);
#if MYSQL_DATA
// Connector/NET incorrectly returns "SMALLINT" for "YEAR", and returns all YEAR values as short values
dataTypeName = "SMALLINT";
expected = expected.Select(x => x is null ? null : (object) (short) (int) x).ToArray();
getValue = reader => reader.GetInt16(0);
#endif
DoQuery("times", column, dataTypeName, expected, getValue);
}
[Theory]
[InlineData("Binary", 100)]
[InlineData("VarBinary", 0)]
[InlineData("TinyBlob", 0)]
[InlineData("Blob", 0)]
[InlineData("MediumBlob", 0)]
[InlineData("LongBlob", 0)]
public void QueryBlob(string column, int padLength)
{
var data = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
if (data.Length < padLength)
Array.Resize(ref data, padLength);
DoQuery<GetBytesWhenNullException>("blobs", "`" + column + "`", "BLOB", new object[] { null, data }, GetBytes);
DoQuery<GetStreamWhenNullException>("blobs", "`" + column + "`", "BLOB", new object[] { null, data }, GetStreamBytes);
DoQuery<GetStreamWhenNullException>("blobs", "`" + column + "`", "BLOB", new object[] { null, data }, reader => reader.GetStream(0), matchesDefaultType: false, assertEqual: (e, a) =>
{
using var stream = (Stream) a;
Assert.True(stream.CanRead);
Assert.False(stream.CanWrite);
var bytes = new byte[stream.Length];
Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length));
Assert.Equal(e, bytes);
}, getFieldValueType: typeof(Stream));
}
[Theory]
[InlineData("TinyBlob", 255)]
[InlineData("Blob", 65535)]
[InlineData("MediumBlob", 16777215)]
[InlineData("LongBlob", 33554432)]
[InlineData("LongBlob", 67108864)]
public async Task InsertLargeBlobAsync(string column, int size)
{
// NOTE: MySQL Server will reset the connection when it receives an oversize packet, so we need to create a test-specific connection here
using var connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString);
await connection.OpenAsync();
var data = CreateByteArray(size);
var isSupported = size < 1048576 || AppConfig.SupportedFeatures.HasFlag(ServerFeatures.LargePackets);
long lastInsertId;
using (var cmd = new MySqlCommand($"insert into datatypes_blob_insert(`{column}`) values(@data)", connection))
{
try
{
cmd.Parameters.AddWithValue("@data", data);
await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
lastInsertId = cmd.LastInsertedId;
Assert.True(isSupported);
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
lastInsertId = -1;
Assert.False(isSupported);
Assert.True(ex.Message.IndexOf("packet") >= 0 || ex.Message.IndexOf("innodb_log_file_size") >= 0);
}
}
if (isSupported)
{
var queryResult = (await connection.QueryAsync<byte[]>($"select `{column}` from datatypes_blob_insert where rowid = {lastInsertId}").ConfigureAwait(false)).Single();
TestUtilities.AssertEqual(data, queryResult);
await connection.ExecuteAsync($"delete from datatypes_blob_insert where rowid = {lastInsertId}").ConfigureAwait(false);
}
}
[Theory]
[InlineData("TinyBlob", 255)]
[InlineData("Blob", 65535)]
[InlineData("MediumBlob", 16777215)]
[InlineData("LongBlob", 67108864)]
public void InsertLargeBlobSync(string column, int size)
{
// NOTE: MySQL Server will reset the connection when it receives an oversize packet, so we need to create a test-specific connection here
using var connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString);
connection.Open();
var data = CreateByteArray(size);
var isSupported = size < 1048576 || AppConfig.SupportedFeatures.HasFlag(ServerFeatures.LargePackets);
long lastInsertId;
using (var cmd = new MySqlCommand($"insert into datatypes_blob_insert(`{column}`) values(@data)", connection))
{
try
{
cmd.Parameters.AddWithValue("@data", data);
cmd.ExecuteNonQuery();
lastInsertId = cmd.LastInsertedId;
Assert.True(isSupported);
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
lastInsertId = -1;
Assert.False(isSupported);
Assert.True(ex.Message.IndexOf("packet") >= 0 || ex.Message.IndexOf("innodb_log_file_size") >= 0);
}
}
if (isSupported)
{
var queryResult = connection.Query<byte[]>($"select `{column}` from datatypes_blob_insert where rowid = {lastInsertId}").Single();
TestUtilities.AssertEqual(data, queryResult);
connection.Execute($"delete from datatypes_blob_insert where rowid = {lastInsertId}");
}
}
[Theory]
[InlineData(false, "Date", typeof(DateTime), "1000 01 01")]
[InlineData(true, "Date", typeof(MySqlDateTime), "1000 01 01")]
[InlineData(false, "DateTime", typeof(DateTime), "1000 01 01")]
[InlineData(true, "DateTime", typeof(MySqlDateTime), "1000 01 01")]
[InlineData(false, "TimeStamp", typeof(DateTime), "1970 01 01 0 0 1")]
[InlineData(true, "TimeStamp", typeof(MySqlDateTime), "1970 01 01 0 0 1")]
[InlineData(false, "Time", typeof(TimeSpan), null)]
[InlineData(true, "Time", typeof(TimeSpan), null)]
public void AllowZeroDateTime(bool allowZeroDateTime, string columnName, Type expectedType, string expectedDateTime)
{
var csb = CreateConnectionStringBuilder();
csb.AllowZeroDateTime = allowZeroDateTime;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
using var cmd = new MySqlCommand($"SELECT `{columnName}` FROM datatypes_times WHERE `{columnName}` IS NOT NULL ORDER BY rowid", connection);
using var reader = cmd.ExecuteReader();
Assert.True(reader.Read());
Assert.Equal(expectedType, reader.GetFieldType(0));
Assert.IsType(expectedType, reader.GetValue(0));
var dt = reader.GetSchemaTable();
Assert.Equal(expectedType, dt.Rows[0]["DataType"]);
if (expectedDateTime is not null)
{
var expected = (DateTime) ConvertToDateTime(new object[] { expectedDateTime }, DateTimeKind.Unspecified)[0];
Assert.Equal(expected, reader.GetDateTime(0));
Assert.Equal(new MySqlDateTime(expected), reader.GetMySqlDateTime(0));
}
}
[Theory]
[InlineData("Date")]
[InlineData("DateTime")]
[InlineData("Timestamp")]
public void GetMySqlDateTime(string columnName)
{
using var cmd = new MySqlCommand($"SELECT `{columnName}` FROM datatypes_times WHERE `{columnName}` IS NOT NULL", Connection);
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
var dt = reader.GetDateTime(0);
var msdt = reader.GetMySqlDateTime(0);
Assert.True(msdt.IsValidDateTime);
Assert.Equal(dt, msdt.GetDateTime());
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReadNewDate(bool prepare)
{
// returns a NEWDATE in MySQL < 5.7.22; see https://github.com/mysql-net/MySqlConnector/issues/1007
using var cmd = new MySqlCommand($"SELECT `Date` FROM datatypes_times UNION ALL SELECT `Date` FROM datatypes_times", Connection);
if (prepare)
cmd.Prepare();
using var reader = cmd.ExecuteReader();
#if !MYSQL_DATA
var columnSchema = reader.GetColumnSchema()[0];
Assert.Equal("Date", columnSchema.ColumnName);
Assert.Equal(typeof(DateTime), columnSchema.DataType);
Assert.Equal("DATE", columnSchema.DataTypeName);
#endif
var schemaRow = reader.GetSchemaTable().Rows[0];
Assert.Equal("Date", schemaRow["ColumnName"]);
Assert.Equal(typeof(DateTime), schemaRow["DataType"]);
while (reader.Read())
{
if (!reader.IsDBNull(0))
reader.GetDateTime(0);
}
}
[Theory]
[InlineData("Date", false, "9999 12 31")]
[InlineData("Date", true, "9999 12 31")]
[InlineData("DateTime", false, "9999 12 31 23 59 59 999999")]
[InlineData("DateTime", true, "9999 12 31 23 59 59 999999")]
[InlineData("Time", false, null)]
[InlineData("Time", true, null)]
public void ReadVarCharFromNestedQueryAsDate(string columnName, bool prepare, string expectedValue)
{
var expectedDate = (DateTime?) ConvertToDateTime(new object[] { expectedValue }, DateTimeKind.Unspecified)[0];
// returns VARCHAR in MySQL 5.7; DATE in MySQL 8.0