-
Notifications
You must be signed in to change notification settings - Fork 330
Expand file tree
/
Copy pathAdapterTest.cs
More file actions
1984 lines (1716 loc) · 93.1 KB
/
Copy pathAdapterTest.cs
File metadata and controls
1984 lines (1716 loc) · 93.1 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using Xunit;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests
{
public class AdapterTest
{
private char[] _appendNewLineIndentBuffer = new char[0];
// data value and server consts
private const string MagicName = "Magic";
// Use a union statement so that Identity columns don't carry over
private const string _createTableQuery = "select * into {0} from Employees where EmployeeID < 3 union all (select * from Employees where 1 = 0)";
private string _tempTable;
private string _tempKey;
private string _randomGuid;
// data type
private decimal _c_numeric_val;
private long _c_bigint_val;
private byte[] _c_unique_val;
private Guid _c_guid_val;
private byte[] _c_varbinary_val;
private byte[] _c_binary_val;
private decimal _c_money_val;
private decimal _c_smallmoney_val;
private DateTime _c_datetime_val;
private DateTime _c_smalldatetime_val;
private string _c_nvarchar_val;
private string _c_nchar_val;
private string _c_varchar_val;
private string _c_char_val;
private int _c_int_val;
private short _c_smallint_val;
private byte _c_tinyint_val;
private bool _c_bit_val;
private double _c_float_val;
private float _c_real_val;
private object[] _values;
public AdapterTest()
{
// create random name for temp tables
_tempTable = DataTestUtility.GetShortName("AdapterTest");
_tempTable = _tempTable.Replace('-', '_');
_randomGuid = Guid.NewGuid().ToString();
_tempKey = "employee_id_key_" + Environment.TickCount.ToString() + _randomGuid;
_tempKey = _tempKey.Replace('-', '_');
InitDataValues();
}
// TODO Synapse: Remove Northwind dependency by creating required tables in setup.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void SimpleFillTest()
{
using SqlConnection conn = new(DataTestUtility.TCPConnectionString);
using SqlDataAdapter adapter = new("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM Employees", conn);
DataSet employeesSet = new();
DataTestUtility.AssertEqualsWithDescription(0, employeesSet.Tables.Count, "Unexpected tables count before fill.");
adapter.Fill(employeesSet, "Employees");
DataTestUtility.AssertEqualsWithDescription(1, employeesSet.Tables.Count, "Unexpected tables count after fill.");
DataTestUtility.AssertEqualsWithDescription("Employees", employeesSet.Tables[0].TableName, "Unexpected table name.");
DataTestUtility.AssertEqualsWithDescription(9, employeesSet.Tables["Employees"].Columns.Count, "Unexpected columns count.");
employeesSet.Tables["Employees"].Columns.Remove("LastName");
employeesSet.Tables["Employees"].Columns.Remove("FirstName");
employeesSet.Tables["Employees"].Columns.Remove("Title");
DataTestUtility.AssertEqualsWithDescription(6, employeesSet.Tables["Employees"].Columns.Count, "Unexpected columns count after column removal.");
DataSet dataSet = new();
adapter.Fill(dataSet);
DataTestUtility.AssertEqualsWithDescription(1, dataSet.Tables.Count, "Unexpected tables count after fill.");
DataTestUtility.AssertEqualsWithDescription(9, dataSet.Tables[0].Columns.Count, "Unexpected column after fill.");
DataSet dataSet2 = new();
adapter.Fill(dataSet2, 0, 2, "Employees");
DataTestUtility.AssertEqualsWithDescription(1, dataSet2.Tables.Count, "Unexpected tables count after fill.");
DataTestUtility.AssertEqualsWithDescription(2, dataSet2.Tables[0].Rows.Count, "Unexpected row count after fill.");
DataTestUtility.AssertEqualsWithDescription(9, dataSet2.Tables[0].Columns.Count, "Unexpected column after fill.");
DataTable table = new();
adapter.Fill(table);
DataTestUtility.AssertEqualsWithDescription(9, table.Columns.Count, "Unexpected columns count.");
DataTable table2 = new();
adapter.Fill(0, 2, table2);
DataTestUtility.AssertEqualsWithDescription(9, table2.Columns.Count, "Unexpected columns count.");
DataTestUtility.AssertEqualsWithDescription(2, table2.Rows.Count, "Unexpected rows count.");
}
// TODO Synapse: Remove Northwind dependency by creating required tables in setup.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
// https://github.com/dotnet/SqlClient/issues/4135
[Trait("Category", "flaky")]
public void FillShouldAllowRetryLogicProviderToBeInvoked()
{
int maxRetries = 3;
int expectedAttempts = maxRetries - 1;
int retryCount = 0;
SqlRetryLogicOption options = new()
{
NumberOfTries = maxRetries,
DeltaTime = TimeSpan.FromMilliseconds(100),
MaxTimeInterval = TimeSpan.FromMilliseconds(500),
TransientErrors = new int[] { 26, 4060, 233, -1, 17142, -2, 2812 }
};
SqlRetryLogicBaseProvider provider = SqlConfigurableRetryFactory.CreateFixedRetryProvider(options);
string query = "WAITFOR DELAY '00:00:02';SELECT 1";
SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionString)
{
ConnectTimeout = 1
};
using var connection = new SqlConnection(builder.ConnectionString);
using SqlCommand command = new(query, connection);
command.CommandTimeout = 1;
command.RetryLogicProvider = provider;
command.RetryLogicProvider.Retrying += (object sender, SqlRetryingEventArgs e) =>
{
retryCount = e.RetryCount;
Assert.Equal(e.RetryCount, e.Exceptions.Count);
Assert.NotEqual(TimeSpan.Zero, e.Delay);
};
connection.Open();
AggregateException exception = Assert.Throws<AggregateException>(() =>
{
DataTable dt = new();
using (SqlDataAdapter adapter = new(command))
{
adapter.Fill(dt);
}
});
Assert.Contains($"The number of retries has exceeded the maximum of {maxRetries} attempt(s)", exception.Message);
Assert.Equal(expectedAttempts, retryCount);
}
// TODO Synapse: Remove Northwind dependency by creating required tables in setup.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void PrepUnprepTest()
{
// share the connection
using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = new SqlCommand("select * from shippers", connection))
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
cmd.Connection.Open();
DataSet dataSet = new DataSet();
sqlAdapter.TableMappings.Add("Table", "shippers");
cmd.CommandText = "Select * from shippers";
sqlAdapter.SelectCommand = cmd;
sqlAdapter.Fill(dataSet);
DataTestUtility.AssertEqualsWithDescription(
3, dataSet.Tables[0].Rows.Count,
"Exec1: Unexpected number of shipper rows.");
dataSet.Reset();
sqlAdapter.Fill(dataSet);
DataTestUtility.AssertEqualsWithDescription(
3, dataSet.Tables[0].Rows.Count,
"Exec2: Unexpected number of shipper rows.");
dataSet.Reset();
cmd.CommandText = "select * from shippers where shipperId < 3";
sqlAdapter.Fill(dataSet);
DataTestUtility.AssertEqualsWithDescription(
2, dataSet.Tables[0].Rows.Count,
"Exec3: Unexpected number of shipper rows.");
dataSet.Reset();
sqlAdapter.Fill(dataSet);
DataTestUtility.AssertEqualsWithDescription(
2, dataSet.Tables[0].Rows.Count,
"Exec4: Unexpected number of shipper rows.");
cmd.CommandText = "select * from shippers";
cmd.Prepare();
int i = 0;
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTestUtility.AssertEqualsWithDescription(3, reader.FieldCount, "Unexpected FieldCount.");
while (reader.Read())
{
i++;
}
}
DataTestUtility.AssertEqualsWithDescription(3, i, "Unexpected read count.");
cmd.CommandText = "select * from orders where orderid < @p1";
cmd.Parameters.AddWithValue("@p1", 10250);
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTestUtility.AssertEqualsWithDescription(14, reader.FieldCount, "Unexpected FieldCount.");
i = 0;
while (reader.Read())
{
i++;
}
}
DataTestUtility.AssertEqualsWithDescription(2, i, "Unexpected read count.");
cmd.Parameters["@p1"].Value = 10249;
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTestUtility.AssertEqualsWithDescription(14, reader.FieldCount, "Unexpected FieldCount.");
i = 0;
while (reader.Read())
{
i++;
}
}
DataTestUtility.AssertEqualsWithDescription(1, i, "Unexpected read count.");
}
}
// Synapse: Create table statement contains a data type that is unsupported in Parallel Data Warehouse.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void SqlVariantTest()
{
string tableName = DataTestUtility.GenerateObjectName();
// good test for null values and unicode strings
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = new SqlCommand(null, conn))
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
try
{
ExecuteNonQueryCommand("CREATE TABLE " + tableName + " (c0_bigint bigint, c1_variant sql_variant)");
cmd.Connection.Open();
// the ORDER BY clause tests that we correctly ignore the ORDER token
cmd.CommandText = "select * from " + tableName;
sqlAdapter.SelectCommand = cmd;
sqlAdapter.TableMappings.Add(tableName, "rowset");
// insert
sqlAdapter.InsertCommand = new SqlCommand()
{
CommandText = "INSERT INTO " + tableName + "(c0_bigint, c1_variant) " +
"VALUES (@bigint, @variant)"
};
SqlParameter p = sqlAdapter.InsertCommand.Parameters.Add(new SqlParameter("@bigint", SqlDbType.BigInt));
p.SourceColumn = "c0_bigint";
p = sqlAdapter.InsertCommand.Parameters.Add(new SqlParameter("@variant", SqlDbType.Variant));
p.SourceColumn = "c1_variant";
sqlAdapter.InsertCommand.Connection = cmd.Connection;
DataSet dataSet = new DataSet();
sqlAdapter.FillSchema(dataSet, SchemaType.Mapped, tableName);
DataRow datarow = null;
for (int i = 0; i < _values.Length; i++)
{
// add each variant type
datarow = dataSet.Tables[0].NewRow();
datarow.ItemArray = new object[] { 1, _values[i] };
datarow.Table.Rows.Add(datarow);
}
sqlAdapter.Update(dataSet, tableName);
// now reload and make sure we got the values we wrote out
dataSet.Reset();
sqlAdapter.Fill(dataSet, tableName);
DataColumnCollection cols = dataSet.Tables[0].Columns;
DataRowCollection rows = dataSet.Tables[0].Rows;
Assert.True(rows.Count == _values.Length, "FAILED: SqlVariant didn't update all the rows!");
for (int i = 0; i < rows.Count; i++)
{
DataRow row = rows[i];
object value = row[1];
if (_values[i].GetType() == typeof(byte[]) || _values[i].GetType() == typeof(Guid))
{
byte[] bsrc;
byte[] bdst;
if (_values[i].GetType() == typeof(Guid))
{
bsrc = ((Guid)value).ToByteArray();
bdst = ((Guid)(_values[i])).ToByteArray();
}
else
{
bsrc = (byte[])value;
bdst = (byte[])_values[i];
}
Assert.True(ByteArraysEqual(bsrc, bdst), "FAILED: Byte arrays are unequal");
}
else if (_values[i].GetType() == typeof(bool))
{
Assert.True(Convert.ToBoolean(value) == (bool)_values[i], "FAILED: " + DBConvertToString(value) + " is not equal to " + DBConvertToString(_values[i]));
}
else
{
Assert.True(value.Equals(_values[i]), "FAILED: " + DBConvertToString(value) + " is not equal to " + DBConvertToString(_values[i]));
}
}
}
finally
{
DataTestUtility.DropTable(conn, tableName);
}
}
}
// Synapse: The RETURN statement can only be used in user-defined functions.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void ParameterTest_AllTypes()
{
string procName = DataTestUtility.GenerateObjectName();
string spCreateAllTypes =
"CREATE PROCEDURE " + procName + " " +
"@Cnumeric numeric(10,2) OUTPUT, " +
"@Cunique uniqueidentifier OUTPUT, " +
"@Cnvarchar nvarchar(10) OUTPUT, " +
"@Cnchar nchar(10) OUTPUT, " +
"@Cbit bit OUTPUT, " +
"@Ctinyint tinyint OUTPUT, " +
"@Cvarbinary varbinary(16) OUTPUT, " +
"@Cbinary binary(16) OUTPUT, " +
"@Cchar char(10) OUTPUT, " +
"@Cmoney money OUTPUT, " +
"@Csmallmoney smallmoney OUTPUT, " +
"@Cint int OUTPUT, " +
"@Csmallint smallint OUTPUT, " +
"@Cfloat float OUTPUT, " +
"@Creal real OUTPUT, " +
"@Cdatetime datetime OUTPUT, " +
"@Csmalldatetime smalldatetime OUTPUT, " +
"@Cvarchar varchar(10) OUTPUT " +
"AS SELECT " +
"@Cnumeric=@Cnumeric, " +
"@Cunique=@Cunique, " +
"@Cnvarchar=@Cnvarchar, " +
"@Cnchar=@Cnchar, " +
"@Cbit=@Cbit, " +
"@Ctinyint=@Ctinyint, " +
"@Cvarbinary=@Cvarbinary, " +
"@Cbinary=@Cbinary, " +
"@Cchar=@Cchar, " +
"@Cmoney=@Cmoney, " +
"@Csmallmoney=@Csmallmoney, " +
"@Cint=@Cint, " +
"@Csmallint=@Csmallint, " +
"@Cfloat=@Cfloat, " +
"@Creal=@Creal, " +
"@Cdatetime=@Cdatetime, " +
"@Csmalldatetime=@Csmalldatetime, " +
"@Cvarchar=@Cvarchar " +
"RETURN(42)";
string spDropAllTypes = "DROP PROCEDURE " + procName;
bool dropSP = false;
try
{
ExecuteNonQueryCommand(spCreateAllTypes);
dropSP = true;
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = new SqlCommand(procName, conn))
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
conn.Open();
SqlParameter param = cmd.Parameters.Add(new SqlParameter("@Cnumeric", SqlDbType.Decimal));
param.Precision = 10;
param.Scale = 2;
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[0].Value = _c_numeric_val;
param = cmd.Parameters.Add(new SqlParameter("@Cunique", SqlDbType.UniqueIdentifier));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[1].Value = _c_guid_val;
cmd.Parameters.Add(new SqlParameter("@Cnvarchar", SqlDbType.NVarChar, 10));
cmd.Parameters[2].Direction = ParameterDirection.InputOutput;
cmd.Parameters[2].Value = _c_nvarchar_val;
cmd.Parameters.Add(new SqlParameter("@Cnchar", SqlDbType.NChar, 10));
cmd.Parameters[3].Direction = ParameterDirection.InputOutput;
cmd.Parameters[3].Value = _c_nchar_val;
param = cmd.Parameters.Add(new SqlParameter("@Cbit", SqlDbType.Bit));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[4].Value = _c_bit_val;
param = cmd.Parameters.Add(new SqlParameter("@Ctinyint", SqlDbType.TinyInt));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[5].Value = _c_tinyint_val;
cmd.Parameters.Add(new SqlParameter("@Cvarbinary", SqlDbType.VarBinary, 16));
cmd.Parameters[6].Direction = ParameterDirection.InputOutput;
cmd.Parameters[6].Value = _c_varbinary_val;
cmd.Parameters.Add(new SqlParameter("@Cbinary", SqlDbType.Binary, 16));
cmd.Parameters[7].Direction = ParameterDirection.InputOutput;
cmd.Parameters[7].Value = _c_binary_val;
cmd.Parameters.Add(new SqlParameter("@Cchar", SqlDbType.Char, 10));
cmd.Parameters[8].Direction = ParameterDirection.InputOutput;
cmd.Parameters[8].Value = _c_char_val;
param = cmd.Parameters.Add(new SqlParameter("@Cmoney", SqlDbType.Money));
param.Direction = ParameterDirection.InputOutput;
param.Scale = 4;
cmd.Parameters[9].Value = _c_money_val;
param = cmd.Parameters.Add(new SqlParameter("@Csmallmoney", SqlDbType.SmallMoney));
param.Direction = ParameterDirection.InputOutput;
param.Scale = 4;
cmd.Parameters[10].Value = _c_smallmoney_val;
param = cmd.Parameters.Add(new SqlParameter("@Cint", SqlDbType.Int));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[11].Value = _c_int_val;
param = cmd.Parameters.Add(new SqlParameter("@Csmallint", SqlDbType.SmallInt));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[12].Value = _c_smallint_val;
param = cmd.Parameters.Add(new SqlParameter("@Cfloat", SqlDbType.Float));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[13].Value = _c_float_val;
param = cmd.Parameters.Add(new SqlParameter("@Creal", SqlDbType.Real));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[14].Value = _c_real_val;
param = cmd.Parameters.Add(new SqlParameter("@Cdatetime", SqlDbType.DateTime));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[15].Value = _c_datetime_val;
param = cmd.Parameters.Add(new SqlParameter("@Csmalldatetime", SqlDbType.SmallDateTime));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[16].Value = _c_smalldatetime_val;
param = cmd.Parameters.Add(new SqlParameter("@Cvarchar", SqlDbType.VarChar, 10));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[17].Value = _c_varchar_val;
param = cmd.Parameters.Add(new SqlParameter("@return", SqlDbType.Int));
param.Direction = ParameterDirection.ReturnValue;
cmd.Parameters[18].Value = 17; // will be overwritten
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
string[] expectedStringValues =
{
"@Cnumeric : Decimal<42424242.42>",
null,
"@Cnvarchar : String:10<1234567890>",
"@Cnchar : String:10<1234567890>",
"@Cbit : Boolean<True>",
"@Ctinyint : Byte<255>",
null,
null,
"@Cchar : String:10<1234567890>",
null,
null,
"@Cint : Int32<-1>",
"@Csmallint : Int16<-1>",
"@Cfloat : Double<12345678.2>",
"@Creal : Single<12345.1>",
null,
null,
"@Cvarchar : String:10<1234567890>",
"@return : Int32<42>"
};
for (int i = 0; i < cmd.Parameters.Count; i++)
{
param = cmd.Parameters[i];
switch (param.SqlDbType)
{
case SqlDbType.Binary:
Assert.True(ByteArraysEqual(_c_binary_val, (byte[])param.Value), "FAILED: " + procName + ", Binary parameter");
break;
case SqlDbType.VarBinary:
Assert.True(ByteArraysEqual(_c_varbinary_val, (byte[])param.Value), "FAILED: " + procName + ", VarBinary parameter");
break;
case SqlDbType.UniqueIdentifier:
DataTestUtility.AssertEqualsWithDescription(_c_guid_val, (Guid)param.Value, "FAILED: " + procName + ", UniqueIdentifier parameter");
break;
case SqlDbType.DateTime:
Assert.True(0 == DateTime.Compare((DateTime)param.Value, _c_datetime_val), "FAILED: " + procName + ", DateTime parameter");
break;
case SqlDbType.SmallDateTime:
Assert.True(0 == DateTime.Compare((DateTime)param.Value, _c_smalldatetime_val), "FAILED: " + procName + ", SmallDateTime parameter");
break;
case SqlDbType.Money:
Assert.True(
0 == decimal.Compare((decimal)param.Value, _c_money_val),
string.Format("FAILED: " + procName + ", Money parameter. Expected: {0}. Actual: {1}.", _c_money_val, (decimal)param.Value));
break;
case SqlDbType.SmallMoney:
Assert.True(
0 == decimal.Compare((decimal)param.Value, _c_smallmoney_val),
string.Format("FAILED: " + procName + ", SmallMoney parameter. Expected: {0}. Actual: {1}.", _c_smallmoney_val, (decimal)param.Value));
break;
default:
string actualValue = param.ParameterName + " : " + DBConvertToString(cmd.Parameters[i].Value);
DataTestUtility.AssertEqualsWithDescription(actualValue, expectedStringValues[i], "Unexpected parameter value.");
break;
}
}
}
}
finally
{
if (dropSP)
{
ExecuteNonQueryCommand(spDropAllTypes);
}
}
}
// Synapse: The RETURN statement can only be used in user-defined functions.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void ParameterTest_InOut()
{
string procName = DataTestUtility.GetShortName("P");
// input, output
string spCreateInOut =
"CREATE PROCEDURE " + procName + " @in int, @inout int OUTPUT, @out nvarchar(8) OUTPUT " +
"AS SELECT @inout = (@in + @inout), @out = 'Success!' " +
"SELECT * From shippers where ShipperID = @in " +
"RETURN(42)";
string spDropInOut = "DROP PROCEDURE " + procName;
bool dropSP = false;
try
{
ExecuteNonQueryCommand(spCreateInOut);
dropSP = true;
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = new SqlCommand(procName, conn))
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@in", SqlDbType.Int));
cmd.Parameters[0].Value = 2;
SqlParameter param = cmd.Parameters.Add(new SqlParameter("@inout", SqlDbType.Int));
param.Direction = ParameterDirection.InputOutput;
cmd.Parameters[1].Value = 1998;
param = cmd.Parameters.Add(new SqlParameter("@out", SqlDbType.NVarChar, 8));
param.Direction = ParameterDirection.Output;
param = cmd.Parameters.Add(new SqlParameter("@ret", SqlDbType.Int));
param.Direction = ParameterDirection.ReturnValue;
DataSet dataSet = new DataSet();
sqlAdapter.TableMappings.Add("Table", "shipper");
sqlAdapter.SelectCommand = cmd;
sqlAdapter.Fill(dataSet);
// check our output and return value params
Assert.True(VerifyOutputParams(cmd.Parameters), "FAILED: InputOutput parameter test with returned rows and bound return value!");
Assert.True(1 == dataSet.Tables[0].Rows.Count, "FAILED: Expected 1 row to be loaded in the dataSet!");
DataRow row = dataSet.Tables[0].Rows[0];
Assert.True((int)row["ShipperId"] == 2, "FAILED: ShipperId column should be 2, not " + DBConvertToString(row["ShipperId"]));
// remember to reset params
cmd.Parameters[0].Value = 2;
cmd.Parameters[1].Value = 1998;
cmd.Parameters[2].Value = Convert.DBNull;
cmd.Parameters[3].Value = Convert.DBNull;
// now exec the same thing without a data set
cmd.ExecuteNonQuery();
// check our output and return value params
Assert.True(VerifyOutputParams(cmd.Parameters), "FAILED: InputOutput parameter test with no returned rows and bound return value!");
// now unbind the return value
cmd.Parameters.RemoveAt(3);
// remember to reset input params
cmd.Parameters[0].Value = 1; // use 1, just for the heck of it
cmd.Parameters[1].Value = 1999;
cmd.Parameters[2].Value = Convert.DBNull;
dataSet.Reset();
sqlAdapter.Fill(dataSet);
// verify the ouptut parameter
Assert.True(
((int)cmd.Parameters[1].Value == 2000) &&
(0 == string.Compare(cmd.Parameters[2].Value.ToString(), "Success!", false, CultureInfo.InvariantCulture)),
"FAILED: unbound return value case, output param is not correct!");
Assert.True(1 == dataSet.Tables[0].Rows.Count, "FAILED: Expected 1 row to be loaded in the dataSet!");
row = dataSet.Tables[0].Rows[0];
Assert.True((int)row["ShipperId"] == 1, "FAILED: ShipperId column should be 1, not " + DBConvertToString(row["ShipperId"]));
}
}
finally
{
if (dropSP)
{
ExecuteNonQueryCommand(spDropInOut);
}
}
}
// TODO Synapse: Remove Northwind dependency by creating required tables in setup.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void UpdateTest()
{
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter adapter = new SqlDataAdapter())
using (SqlDataAdapter adapterVerify = new SqlDataAdapter())
{
conn.Open();
cmd.CommandText = string.Format(_createTableQuery, _tempTable);
cmd.ExecuteNonQuery();
cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)";
cmd.ExecuteNonQuery();
try
{
PrepareUpdateCommands(adapter, conn, _tempTable);
adapter.SelectCommand = new SqlCommand(string.Format("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country from {0} where EmployeeID < 3", _tempTable), conn);
adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn);
adapter.TableMappings.Add(_tempTable, "rowset");
adapterVerify.TableMappings.Add(_tempTable, "rowset");
DataSet dataSet = new DataSet();
VerifyFillSchemaResult(adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable), new string[] { "rowset" });
// FillSchema
dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] };
adapter.Fill(dataSet, _tempTable);
// Fill from Database
Assert.True(dataSet.Tables[0].Rows.Count == 2, "FAILED: Fill after FillSchema should populate the dataSet with two rows!");
dataSet.AcceptChanges();
// Verify that set is empty
DataSet dataSetVerify = new DataSet();
VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
// Insert
DataRow datarow = dataSet.Tables["rowset"].NewRow();
datarow.ItemArray = new object[] { "11", "The Original", MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" };
datarow.Table.Rows.Add(datarow);
adapter.Update(dataSet, _tempTable);
// Verify that set has one 'Magic' entry
VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
dataSet.AcceptChanges();
// Update
datarow = dataSet.Tables["rowset"].Rows.Find("11");
datarow.BeginEdit();
datarow.ItemArray = new object[] { "11", "The New and Improved", MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" };
datarow.EndEdit();
adapter.Update(dataSet, _tempTable);
// Verify that set has updated 'Magic' entry
VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
dataSet.AcceptChanges();
// Delete
dataSet.Tables["rowset"].Rows.Find("11").Delete();
adapter.Update(dataSet, _tempTable);
// Verify that set is empty
VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
dataSet.AcceptChanges();
}
finally
{
DataTestUtility.DropTable(conn, _tempTable);
}
}
}
// these next texts verify that 'bulk' operations work. If each command type modifies more than three rows, then we do a Prep/Exec instead of
// adhoc ExecuteSql.
// TODO Synapse: Remove Northwind dependency by creating required tables in setup.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void BulkUpdateTest()
{
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter adapter = new SqlDataAdapter())
using (SqlDataAdapter adapterVerify = new SqlDataAdapter())
{
conn.Open();
cmd.CommandText = string.Format(_createTableQuery, _tempTable);
cmd.ExecuteNonQuery();
cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)";
cmd.ExecuteNonQuery();
try
{
PrepareUpdateCommands(adapter, conn, _tempTable);
adapter.SelectCommand = new SqlCommand("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM " + _tempTable + " WHERE EmployeeID < 3", conn);
adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn);
adapter.TableMappings.Add(_tempTable, "rowset");
adapterVerify.TableMappings.Add(_tempTable, "rowset");
DataSet dataSet = new DataSet();
adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable);
dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] };
adapter.Fill(dataSet, _tempTable);
dataSet.AcceptChanges();
// Verify that set is empty
DataSet dataSetVerify = new DataSet();
VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
// Bulk Insert (10 records)
DataRow datarow = null;
const int cOps = 5;
for (int i = 0; i < cOps * 2; i++)
{
datarow = dataSet.Tables["rowset"].NewRow();
string sid = "99999000" + i.ToString();
datarow.ItemArray = new object[] { sid, "Bulk Insert" + i.ToString(), MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" };
datarow.Table.Rows.Add(datarow);
}
adapter.Update(dataSet, _tempTable);
// Verify that set has 10 'Magic' entries
VerifyUpdateRow(adapterVerify, dataSetVerify, 10, _tempTable);
dataSet.AcceptChanges();
// Bulk Update (first 5)
for (int i = 0; i < cOps; i++)
{
string sid = "99999000" + i.ToString();
datarow = dataSet.Tables["rowset"].Rows.Find(sid);
datarow.BeginEdit();
datarow.ItemArray = new object[] { sid, "Bulk Update" + i.ToString(), MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" };
datarow.EndEdit();
}
// Bulk Delete (last 5)
for (int i = cOps; i < cOps * 2; i++)
{
string sid = "99999000" + i.ToString();
dataSet.Tables["rowset"].Rows.Find(sid).Delete();
}
// now update the dataSet with the insert and delete changes
adapter.Update(dataSet, _tempTable);
// Verify that set has 5 'Magic' updated entries
VerifyUpdateRow(adapterVerify, dataSetVerify, 5, _tempTable);
dataSet.AcceptChanges();
// clean up the remaining 5 rows
for (int i = 0; i < cOps; i++)
{
string sid = "99999000" + i.ToString();
dataSet.Tables["rowset"].Rows.Find(sid).Delete();
}
adapter.Update(dataSet, _tempTable);
// Verify that set has no entries
VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
dataSet.AcceptChanges();
}
finally
{
DataTestUtility.DropTable(conn, _tempTable);
}
}
}
// Makes sure that we can refresh an identity column in the dataSet
// for a newly inserted row
// Synapse: Must declare the scalar variable "@@IDENTITY".
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void UpdateRefreshTest()
{
string identTableName = DataTestUtility.GetShortName("ID_");
string createIdentTable =
$"CREATE TABLE {identTableName} (id int IDENTITY," +
"LastName nvarchar(50) NULL," +
"Firstname nvarchar(50) NULL)";
string spName = DataTestUtility.GetShortName("sp_insert", withBracket: false);
string spCreateInsert =
$"CREATE PROCEDURE {spName}" +
"(@FirstName nvarchar(50), @LastName nvarchar(50), @id int OUTPUT) " +
"AS INSERT INTO " + _tempTable + " (FirstName, LastName) " +
"VALUES (@FirstName, @LastName); " +
"SELECT @id=@@IDENTITY";
string spDropInsert = $"DROP PROCEDURE {spName}";
bool dropSP = false;
using (SqlDataAdapter adapter = new SqlDataAdapter())
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmd = new SqlCommand(null, conn))
using (SqlCommand temp = new SqlCommand("SELECT id, LastName, FirstName into " + _tempTable + $" from {identTableName}", conn))
using (SqlCommand tableClean = new SqlCommand("", conn))
{
ExecuteNonQueryCommand(createIdentTable);
try
{
adapter.InsertCommand = new SqlCommand()
{
CommandText = spName,
CommandType = CommandType.StoredProcedure
};
adapter.InsertCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName"));
adapter.InsertCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName"));
SqlParameter param = adapter.InsertCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
param.SourceColumn = "id";
param.Direction = ParameterDirection.Output;
adapter.InsertCommand.Parameters.Add(new SqlParameter("@badapple", SqlDbType.NVarChar, 50, "LastName"));
adapter.RowUpdating += new SqlRowUpdatingEventHandler(RowUpdating_UpdateRefreshTest);
adapter.RowUpdated += new SqlRowUpdatedEventHandler(RowUpdated_UpdateRefreshTest);
adapter.InsertCommand.Connection = conn;
conn.Open();
temp.ExecuteNonQuery();
// start clean
tableClean.CommandText = "delete " + _tempTable;
tableClean.ExecuteNonQuery();
tableClean.CommandText = spCreateInsert;
tableClean.ExecuteNonQuery();
dropSP = true;
DataSet ds = new DataSet();
adapter.TableMappings.Add("Table", _tempTable);
cmd.CommandText = "select * from " + _tempTable;
adapter.SelectCommand = cmd;
adapter.Fill(ds, "Table");
// Insert
DataRow row1 = ds.Tables[_tempTable].NewRow();
row1.ItemArray = new object[] { 0, "Bond", "James" };
row1.Table.Rows.Add(row1);
DataRow row2 = ds.Tables[_tempTable].NewRow();
row2.ItemArray = new object[] { 0, "Lee", "Bruce" };
row2.Table.Rows.Add(row2);
Assert.True((int)row1["id"] == 0 && (int)row2["id"] == 0, "FAILED: UpdateRefresh should not have values for identity columns");
adapter.Update(ds, "Table");
// should have values now
int i1 = (int)row1["id"];
int i2 = (int)row2["id"];
Assert.True(
(i1 != 0) && (i2 != 0) && (i2 == (i1 + 1)),
string.Format("FAILED: UpdateRefresh, i2 should equal (i1 + 1). i1: {0}. i2: {1}.", i1, i2));
}
finally
{
if (dropSP)
{
DataTestUtility.DropStoredProcedure(conn, spName);
DataTestUtility.DropTable(conn, _tempTable);
DataTestUtility.DropTable(conn, identTableName);
}
}
}
}
// Synapse: Create table statement contains a data type that is unsupported in Parallel Data Warehouse.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void UpdateNullTest()
{
string tableName = DataTestUtility.GenerateObjectName();
string procName = DataTestUtility.GenerateObjectName();
string createTable = "CREATE TABLE " + tableName + "(cvarbin VARBINARY(7000), cimage IMAGE)";
string createSP =
"CREATE PROCEDURE " + procName + " (@val_cvarbin VARBINARY(7000), @val_cimage IMAGE)" +
"AS INSERT INTO " + tableName + " (cvarbin, cimage)" +
"VALUES (@val_cvarbin, @val_cimage)";
bool dropSP = false;
using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
using (SqlCommand cmdInsert = new SqlCommand(procName, conn))
using (SqlCommand cmdSelect = new SqlCommand("select * from " + tableName, conn))
using (SqlCommand tableClean = new SqlCommand("delete " + tableName, conn))
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
try
{
ExecuteNonQueryCommand(createTable);
ExecuteNonQueryCommand(createSP);
dropSP = true;
conn.Open();
cmdInsert.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = cmdInsert.Parameters.Add(new SqlParameter("@val_cvarbin", SqlDbType.VarBinary, 7000));
SqlParameter p2 = cmdInsert.Parameters.Add(new SqlParameter("@val_cimage", SqlDbType.Image, 8000));
tableClean.ExecuteNonQuery();
p1.Value = Convert.DBNull;
p2.Value = Convert.DBNull;
int rowsAffected = cmdInsert.ExecuteNonQuery();
DataTestUtility.AssertEqualsWithDescription(1, rowsAffected, "Unexpected number of rows inserted.");
DataSet ds = new DataSet();
adapter.SelectCommand = cmdSelect;
adapter.Fill(ds, "goofy");
// should have 1 row in table (with two null entries)
DataTestUtility.AssertEqualsWithDescription(1, ds.Tables[0].Rows.Count, "Unexpected rows count.");
DataTestUtility.AssertEqualsWithDescription(DBNull.Value, ds.Tables[0].Rows[0][0], "Unexpected value.");
DataTestUtility.AssertEqualsWithDescription(DBNull.Value, ds.Tables[0].Rows[0][1], "Unexpected value.");
}
finally
{
if (dropSP)
{
DataTestUtility.DropStoredProcedure(conn, procName);
DataTestUtility.DropTable(conn, tableName);
}
}
}
}
// Synapse: Create table statement contains a data type that is unsupported in Parallel Data Warehouse.
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))]
public void UpdateOffsetTest()
{
string tableName = DataTestUtility.GenerateObjectName();
string procName = DataTestUtility.GenerateObjectName();
string createTable = "CREATE TABLE " + tableName + "(cvarbin VARBINARY(7000), cimage IMAGE)";
string createSP =
"CREATE PROCEDURE " + procName + " (@val_cvarbin VARBINARY(7000), @val_cimage IMAGE)" +