-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathTvpTest.cs
More file actions
1469 lines (1304 loc) · 54.8 KB
/
Copy pathTvpTest.cs
File metadata and controls
1469 lines (1304 loc) · 54.8 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.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Data.SqlClient.Server;
using Xunit;
using System.Linq;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests
{
[Trait("Set", "3")]
public class TvpTest
{
private const string TvpName = "@tvp";
private static readonly IList<SteAttributeKey> s_boundariesTestKeys = new List<SteAttributeKey>(
new SteAttributeKey[] {
SteAttributeKey.SqlDbType,
SteAttributeKey.MultiValued,
SteAttributeKey.MaxLength,
SteAttributeKey.Precision,
SteAttributeKey.Scale,
SteAttributeKey.LocaleId,
SteAttributeKey.CompareOptions,
SteAttributeKey.TypeName,
SteAttributeKey.Type,
SteAttributeKey.Fields,
SteAttributeKey.Value
}).AsReadOnly();
// data value and server consts
private readonly string _connStr;
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))]
public async Task TestPacketNumberWraparound()
{
// This test uses a specifically crafted SQL record enumerator and data to put the
// TdsParserStateObject.WritePacket(byte,bool) into a state where it can't
// differentiate between a packet in the middle of a large packet-set after a byte
// counter wraparound and the first packet of the connection and in doing so trips over
// a check for packet length from the input which has been forced to tell it that there
// is no output buffer space left, this causes an uncancellable infinite loop.
//
// If the enumerator is completely read to the end then the bug is no longer present
// and the packet creation task returns, if the timeout occurs it is probable (but not
// absolute) that the write operation is stuck.
// Arrange
var enumerator = new WraparoundRowEnumerator(1000000);
using var cancellationTokenSource = new CancellationTokenSource();
// Act
Stopwatch stopwatch = new();
stopwatch.Start();
Task actionTask = Task.Factory.StartNew(
async () => await RunPacketNumberWraparound(enumerator, cancellationTokenSource.Token),
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning);
Task timeoutTask = Task.Delay(TimeSpan.FromSeconds(60), cancellationTokenSource.Token);
await Task.WhenAny(actionTask, timeoutTask);
stopwatch.Stop();
cancellationTokenSource.Cancel();
// Assert
Assert.True(
enumerator.MaxCount == enumerator.Count,
$"enumerator.Count={enumerator.Count}, " +
$"enumerator.MaxCount={enumerator.MaxCount}, " +
$"elapsed={stopwatch.Elapsed}");
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))]
public void TestConnectionIsSafeToReuse()
{
using SqlConnection connection = new(DataTestUtility.TCPConnectionString);
// Bad Scenario - exception expected.
try
{
List<Item> list = new()
{
new Item(0),
null,
new Item(2),
new Item(3),
new Item(4),
new Item(5)
};
IEnumerable<int> Ids = list.Select(x => x.id.Value).Distinct();
var sqlParam = new SqlParameter("ids", SqlDbType.Structured)
{
TypeName = "dbo.TableOfIntId",
SqlValue = Ids.Select(x =>
{
SqlDataRecord rec = new(new[] { new SqlMetaData("Id", SqlDbType.Int) });
rec.SetInt32(0, x);
return rec;
})
};
var parameters = new List<SqlParameter>() { sqlParam };
const string SQL = @"SELECT * FROM information_schema.COLUMNS cols INNER JOIN @ids Ids on Ids.id = cols.ORDINAL_POSITION";
using SqlCommand cmd = new(SQL, connection);
cmd.CommandTimeout = 100;
AddCommandParameters(cmd, parameters);
new SqlDataAdapter(cmd).Fill(new("BadFunc"));
Assert.Fail("Expected exception did not occur");
}
catch (Exception e)
{
// Ignore this exception as it's deliberately introduced.
Assert.True(e.Message.Contains("Object reference not set to an instance of an object"), "Expected exception did not occur");
}
// Good Scenario - No failure expected.
try
{
const string SQL = @"SELECT * FROM information_schema.tables WHERE TABLE_NAME = @TableName";
var parameters = new List<SqlParameter>() { new SqlParameter("@TableName", "Temp") };
using SqlCommand cmd = new(SQL, connection);
cmd.CommandTimeout = 100;
AddCommandParameters(cmd, parameters);
new SqlDataAdapter(cmd).Fill(new("GoodFunc"));
}
catch (Exception e)
{
Assert.Fail($"Unexpected error occurred: {e.Message}");
}
}
private class Item
{
public Item(int? v)
{
id = v;
}
public int? id { get; set; }
}
static internal void AddCommandParameters(SqlCommand command, IEnumerable parameters)
{
if (parameters == null)
{
return;
}
foreach (SqlParameter p in parameters)
{
if (p == null)
{
continue;
}
if (p.Value == null)
{
var clone = (SqlParameter)((ICloneable)p).Clone();
clone.Value = DBNull.Value;
command.Parameters.Add(clone);
}
else
{
command.Parameters.Add(p);
}
}
}
public TvpTest()
{
_connStr = DataTestUtility.TCPConnectionString;
}
internal sealed class CarriageReturnLineFeedReplacer : TextWriter
{
private TextWriter _output;
private int _lineFeedCount;
private bool _hasCarriageReturn;
internal CarriageReturnLineFeedReplacer(TextWriter output)
{
_output = output ?? throw new ArgumentNullException(nameof(output));
}
public int LineFeedCount
{
get { return _lineFeedCount; }
}
public override Encoding Encoding
{
get { return _output.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _output.FormatProvider; }
}
public override string NewLine
{
get { return _output.NewLine; }
set { _output.NewLine = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)_output).Dispose();
}
_output = null;
}
public override void Flush()
{
_output.Flush();
}
public override void Write(char value)
{
if ('\n' == value)
{
_lineFeedCount++;
if (!_hasCarriageReturn)
{ // X'\n'Y -> X'\r\n'Y
_output.Write('\r');
}
}
_hasCarriageReturn = '\r' == value;
_output.Write(value);
}
}
#region Main test methods
internal void ColumnBoundariesTest()
{
_ = SteStructuredTypeBoundaries.AllColumnTypesExceptUdts.GetEnumerator(
s_boundariesTestKeys);
TestTVPPermutations(SteStructuredTypeBoundaries.AllColumnTypesExceptUdts, false);
//Console.WriteLine("+++++++++++ UDT TVP tests ++++++++++++++");
//TestTVPPermutations(SteStructuredTypeBoundaries.UdtsOnly, true);
}
private void TestTVPPermutations(SteStructuredTypeBoundaries bounds, bool runOnlyDataRecordTest)
{
IEnumerator<StePermutation> boundsMD = bounds.GetEnumerator(s_boundariesTestKeys);
object[][] baseValues = SteStructuredTypeBoundaries.GetSeparateValues(boundsMD);
IList<DataTable> dtList = GenerateDataTables(baseValues);
TransactionOptions opts = new();
opts.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
// for each unique pattern of metadata
int iter = 0;
while (boundsMD.MoveNext())
{
Console.WriteLine("+++++++ Iteration {0} ++++++++", iter);
StePermutation tvpPerm = boundsMD.Current;
// Set up base command
SqlCommand cmd;
SqlParameter param;
cmd = new SqlCommand(GetProcName(tvpPerm))
{
CommandType = CommandType.StoredProcedure
};
param = cmd.Parameters.Add(TvpName, SqlDbType.Structured);
param.TypeName = GetTypeName(tvpPerm);
// set up the server
try
{
CreateServerObjects(tvpPerm);
}
catch (SqlException se)
{
Console.WriteLine("SqlException creating objects: {0}", se.Number);
DropServerObjects(tvpPerm);
iter++;
continue;
}
// NOTE: The server objects created above (a table type and a stored procedure) must be
// dropped even when the body below throws. Their names are unique per permutation,
// so anything left behind stays in the shared test database forever.
try
{
// Send list of SqlDataRecords as value
Console.WriteLine("------IEnumerable<SqlDataRecord>---------");
try
{
param.Value = CreateListOfRecords(tvpPerm, baseValues);
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
if (!runOnlyDataRecordTest)
{
// send DbDataReader
Console.WriteLine("------DbDataReader---------");
try
{
param.Value = new TvpRestartableReader(CreateListOfRecords(tvpPerm, baseValues));
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
// send datasets
Console.WriteLine("------DataTables---------");
foreach (DataTable d in dtList)
{
param.Value = d;
ExecuteAndVerify(cmd, tvpPerm, null, d);
}
}
}
finally
{
// And clean up
DropServerObjects(tvpPerm);
}
iter++;
}
}
private static async Task RunPacketNumberWraparound(
WraparoundRowEnumerator enumerator,
CancellationToken cancellationToken)
{
using var connection = new SqlConnection(DataTestUtility.TCPConnectionString);
await connection.OpenAsync(cancellationToken);
using var cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "unimportant";
var parameter = new SqlParameter("@rows", SqlDbType.Structured)
{
TypeName = "unimportant",
Value = enumerator
};
cmd.Parameters.Add(parameter);
try
{
await cmd.ExecuteNonQueryAsync(cancellationToken);
}
catch (Exception)
{
// ignore the errors caused by the sproc and table type not existing
}
}
#endregion
#region Utility Methods
private bool AllowableDifference(string source, object result, StePermutation metadata)
{
bool returnValue = false;
// turn result into a string
string resultStr = null;
if (result.GetType() == typeof(string))
{
resultStr = (string)result;
}
else if (result.GetType() == typeof(char[]))
{
resultStr = new string((char[])result);
}
else if (result.GetType() == typeof(SqlChars))
{
resultStr = new string(((SqlChars)result).Value);
}
if (resultStr != null)
{
if (source.Equals(resultStr))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out object value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
if (maxLength < source.Length &&
source.Substring(0, maxLength).Equals(resultStr))
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (maxLength > source.Length &&
resultStr.Length == maxLength &&
metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Char == ((SqlDbType)value) ||
SqlDbType.NChar == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
return returnValue;
}
private bool AllowableDifference(byte[] source, object result, StePermutation metadata)
{
bool returnValue = false;
// turn result into byte array
byte[] resultBytes = null;
if (result.GetType() == typeof(byte[]))
{
resultBytes = (byte[])result;
}
else if (result.GetType() == typeof(SqlBytes))
{
resultBytes = ((SqlBytes)result).Value;
}
if (resultBytes != null)
{
if (source.Equals(resultBytes) || resultBytes.Length == source.Length)
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out object value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
// allowable max-length adjustments
if (maxLength == resultBytes.Length)
{ // a bit optimistic, but what the heck.
// truncation
if (maxLength <= source.Length)
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) && value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Binary == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool AllowableDifference(SqlDecimal source, object result, StePermutation metadata)
{
bool returnValue = false;
// turn result into SqlDecimal
SqlDecimal resultValue = SqlDecimal.Null;
if (result.GetType() == typeof(SqlDecimal))
{
resultValue = (SqlDecimal)result;
}
else if (result.GetType() == typeof(decimal))
{
resultValue = new SqlDecimal((decimal)result);
}
else if (result.GetType() == typeof(SqlMoney))
{
resultValue = new SqlDecimal(((SqlMoney)result).Value);
}
if (!resultValue.IsNull)
{
if (source.Equals(resultValue))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out object value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
(SqlDbType.SmallMoney == (SqlDbType)value ||
SqlDbType.Money == (SqlDbType)value))
{
// Some server conversions seem to lose the decimal places
// TODO: Investigate and validate that this is acceptable!
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, source.Precision, 0);
if (tmp.Equals(resultValue))
{
returnValue = true;
}
else
{
tmp = SqlDecimal.ConvertToPrecScale(resultValue, resultValue.Precision, 0);
returnValue = tmp.Equals(source);
}
}
// check if value was altered by precision/scale conversion
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SqlDbType.Decimal == (SqlDbType)value)
{
if (metadata.TryGetValue(SteAttributeKey.Scale, out value) &&
metadata.TryGetValue(SteAttributeKey.Precision, out object value2) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SteTypeBoundaries.s_doNotUseMarker != value2)
{
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, (byte)value2, (byte)value);
returnValue = tmp.Equals(resultValue);
}
// check if value was changed to 1 by the restartable reader
// due to exceeding size limits of System.Decimal
if (resultValue == (SqlDecimal)1M)
{
try
{
decimal dummy = source.Value;
}
catch (OverflowException)
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool CompareValue(object result, object source, StePermutation metadata)
{
bool isMatch = false;
if (!IsNull(source))
{
if (!IsNull(result))
{
if (source.Equals(result) || result.Equals(source))
{
isMatch = true;
}
else
{
switch (Type.GetTypeCode(source.GetType()))
{
case TypeCode.String:
isMatch = AllowableDifference((string)source, result, metadata);
break;
case TypeCode.Object:
{
if (source is char[] charSource)
{
source = new string(charSource);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is byte[] byteSource)
{
isMatch = AllowableDifference(byteSource, result, metadata);
}
else if (source is SqlBytes sqlBytesSource)
{
isMatch = AllowableDifference(sqlBytesSource.Value, result, metadata);
}
else if (source is SqlChars sqlCharSource)
{
source = new string(sqlCharSource.Value);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is SqlInt64 @int && result is long)
{
isMatch = result.Equals(@int.Value);
}
else if (source is SqlInt32 shortSource && result is int)
{
isMatch = result.Equals(shortSource.Value);
}
else if (source is SqlInt16 intSource && result is short)
{
isMatch = result.Equals(intSource.Value);
}
else if (source is SqlSingle singleSource && result is float)
{
isMatch = result.Equals(singleSource.Value);
}
else if (source is SqlDouble @double && result is double)
{
isMatch = result.Equals(@double.Value);
}
else if (source is SqlDateTime timeSource && result is DateTime)
{
isMatch = result.Equals(timeSource.Value);
}
else if (source is SqlMoney sqlMoneySource)
{
isMatch = AllowableDifference(new SqlDecimal(sqlMoneySource.Value), result, metadata);
}
else if (source is SqlDecimal @decimal)
{
isMatch = AllowableDifference(@decimal, result, metadata);
}
}
break;
case TypeCode.Decimal:
if (result is SqlDecimal || result is decimal || result is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal((decimal)source), result, metadata);
}
break;
default:
break;
}
}
}
}
else
{
if (IsNull(result))
{
isMatch = true;
}
}
if (!isMatch)
{
ReportMismatch(source, result, metadata);
}
return isMatch;
}
private IList<SqlDataRecord> CreateListOfRecords(StePermutation tvpPerm, object[][] baseValues)
{
IList<StePermutation> fields = GetFields(tvpPerm);
SqlMetaData[] fieldMetadata = new SqlMetaData[fields.Count];
int i = 0;
foreach (StePermutation perm in fields)
{
fieldMetadata[i] = PermToSqlMetaData(perm);
i++;
}
List<SqlDataRecord> records = new(baseValues.Length);
for (int rowOrd = 0; rowOrd < baseValues.Length; rowOrd++)
{
object[] row = baseValues[rowOrd];
SqlDataRecord rec = new(fieldMetadata);
records.Add(rec); // Call SetValue *after* Add to ensure record is put in list
for (int colOrd = 0; colOrd < row.Length; colOrd++)
{
// Set value in try-catch to prevent some errors from aborting run.
try
{
rec.SetValue(colOrd, row[colOrd]);
}
catch (OverflowException oe)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, DataTestUtility.GetValueString(row[colOrd]), oe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, DataTestUtility.GetValueString(row[colOrd]), ae.Message);
}
}
}
return records;
}
private DataTable CreateNewTable(object[] row, ref Type[] lastRowTypes)
{
DataTable dt = new();
for (int i = 0; i < row.Length; i++)
{
object value = row[i];
Type t;
if (value == null || DBNull.Value == value)
{
if (lastRowTypes[i] == null)
{
return null;
}
else
{
t = lastRowTypes[i];
}
}
else
{
t = value.GetType();
}
dt.Columns.Add(new DataColumn("Col" + i + "_" + t.Name, t));
lastRowTypes[i] = t;
}
return dt;
}
// create table type and proc that uses that type at the server
private void CreateServerObjects(StePermutation tvpPerm)
{
// Create the table type tsql
StringBuilder tsql = new();
tsql.Append("CREATE TYPE ");
tsql.Append(GetTypeName(tvpPerm));
tsql.Append(" AS TABLE(");
bool addSeparator = false;
int colOrdinal = 1;
foreach (StePermutation perm in GetFields(tvpPerm))
{
if (addSeparator)
{
tsql.Append(", ");
}
else
{
addSeparator = true;
}
// column name
tsql.Append("column");
tsql.Append(colOrdinal);
tsql.Append(" ");
// column type
SqlDbType dbType = (SqlDbType)perm[SteAttributeKey.SqlDbType];
switch (dbType)
{
case SqlDbType.BigInt:
tsql.Append("Bigint");
break;
case SqlDbType.Binary:
tsql.Append("Binary(");
object maxLenObj = perm[SteAttributeKey.MaxLength];
int maxLen;
if (maxLenObj == SteTypeBoundaries.s_doNotUseMarker)
{
maxLen = 8000;
}
else
{
maxLen = (int)maxLenObj;
}
tsql.Append(maxLen);
tsql.Append(")");
break;
case SqlDbType.Bit:
tsql.Append("Bit");
break;
case SqlDbType.Char:
tsql.Append("Char(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.DateTime:
tsql.Append("DateTime");
break;
case SqlDbType.Decimal:
tsql.Append("Decimal(");
tsql.Append(perm[SteAttributeKey.Precision]);
tsql.Append(", ");
tsql.Append(perm[SteAttributeKey.Scale]);
tsql.Append(")");
break;
case SqlDbType.Float:
tsql.Append("Float");
break;
case SqlDbType.Image:
tsql.Append("Image");
break;
case SqlDbType.Int:
tsql.Append("Int");
break;
case SqlDbType.Money:
tsql.Append("Money");
break;
case SqlDbType.NChar:
tsql.Append("NChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.NText:
tsql.Append("NText");
break;
case SqlDbType.NVarChar:
tsql.Append("NVarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Real:
tsql.Append("Real");
break;
case SqlDbType.UniqueIdentifier:
tsql.Append("UniqueIdentifier");
break;
case SqlDbType.SmallDateTime:
tsql.Append("SmallDateTime");
break;
case SqlDbType.SmallInt:
tsql.Append("SmallInt");
break;
case SqlDbType.SmallMoney:
tsql.Append("SmallMoney");
break;
case SqlDbType.Text:
tsql.Append("Text");
break;
case SqlDbType.Timestamp:
tsql.Append("Timestamp");
break;
case SqlDbType.TinyInt:
tsql.Append("TinyInt");
break;
case SqlDbType.VarBinary:
tsql.Append("VarBinary(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.VarChar:
tsql.Append("VarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Variant:
tsql.Append("Variant");
break;
case SqlDbType.Xml:
tsql.Append("Xml");
break;
case SqlDbType.Udt:
string typeName = (string)perm[SteAttributeKey.TypeName];
tsql.Append(typeName);
break;
case SqlDbType.Structured:
throw new NotSupportedException("Not supported");
}
colOrdinal++;
}
tsql.Append(")");
using SqlConnection conn = new(_connStr);
conn.Open();
// execute it to create the type
SqlCommand cmd = new(tsql.ToString(), conn);
cmd.ExecuteNonQuery();
// and create the proc that uses the type
cmd.CommandText = string.Format("CREATE PROC {0}(@tvp {1} READONLY) AS SELECT * FROM @tvp order by {2}",
GetProcName(tvpPerm), GetTypeName(tvpPerm), colOrdinal - 1);
cmd.ExecuteNonQuery();
}
private bool DoesRowMatchMetadata(object[] row, DataTable table)
{
bool result = true;
if (row.Length != table.Columns.Count)
{
result = false;
}
else
{
for (int i = 0; i < row.Length; i++)
{
if (row[i] != null && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType)
{
result = false;
}
}
}
return result;
}
private void DropServerObjects(StePermutation tvpPerm)
{
using SqlConnection conn = new(_connStr);
conn.Open();
// NOTE: The procedure and the type are dropped by separate, individually guarded commands.
// Previously both drops shared a single batch, so when the procedure did not exist (the
// CREATE PROC step failed after CREATE TYPE succeeded) the batch aborted on the first
// statement and the table type was leaked into the shared test database.
DropServerObject(conn, "DROP PROC IF EXISTS " + GetProcName(tvpPerm));
DropServerObject(conn, "DROP TYPE IF EXISTS " + GetTypeName(tvpPerm));
}
private static void DropServerObject(SqlConnection conn, string dropText)
{
using SqlCommand cmd = new(dropText, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine("SqlException dropping objects: {0}", e.Number);
}
}
private void ExecuteAndVerify(SqlCommand cmd, StePermutation tvpPerm, object[][] objValues, DataTable dtValues)
{
using SqlConnection conn = new(_connStr);
conn.Open();
cmd.Connection = conn;
if (DataTestUtility.IsNotAzureServer())
{
// Choose the 2628 error message instead of 8152 in SQL Server 2016 & 2017
using SqlCommand cmdFix = new("DBCC TRACEON(460)", conn);
cmdFix.ExecuteNonQuery();
}
try
{
using SqlDataReader rdr = cmd.ExecuteReader();
VerifyColumnBoundaries(rdr, GetFields(tvpPerm), objValues, dtValues);
}
catch (SqlException se)
{
Console.WriteLine("SqlException. Error Code: {0}", se.Number);
}
catch (InvalidOperationException ioe)
{
Console.WriteLine("InvalidOp: {0}", ioe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("ArgumentException: {0}", ae.Message);
}
}
private IList<DataTable> GenerateDataTables(object[][] values)
{
List<DataTable> dtList = new();
Type[] valueTypes = new Type[values[0].Length];
foreach (object[] row in values)
{
DataTable targetTable = null;
if (0 < dtList.Count)
{
// shortcut for matching last table (most common scenario)
if (DoesRowMatchMetadata(row, dtList[dtList.Count - 1]))
{
targetTable = dtList[dtList.Count - 1];
}
else
{
foreach (DataTable candidate in dtList)
{
if (DoesRowMatchMetadata(row, candidate))
{
targetTable = candidate;
break;
}
}
}
}
if (targetTable == null)
{
targetTable = CreateNewTable(row, ref valueTypes);
if (targetTable != null)
{
dtList.Add(targetTable);
}
}
if (targetTable != null)
{
targetTable.Rows.Add(row);
}
}
return dtList;