-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SqlBulkCopy.cs
2721 lines (2438 loc) · 124 KB
/
SqlBulkCopy.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
//------------------------------------------------------------------------------
// <copyright file="SqlBulkCopy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------
// todo list:
// * An ID column need to be ignored - even if there is an association
// * Spec: ID columns will be ignored - even if there is an association
// * Spec: How do we publish CommandTimeout on the bcpoperation?
//
namespace System.Data.SqlClient {
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using System.Xml;
using MSS = Microsoft.SqlServer.Server;
// -------------------------------------------------------------------------------------------------
// this internal class helps us to associate the metadata (from the target)
// with columnordinals (from the source)
//
sealed internal class _ColumnMapping {
internal int _sourceColumnOrdinal;
internal _SqlMetaData _metadata;
internal _ColumnMapping(int columnId, _SqlMetaData metadata) {
_sourceColumnOrdinal = columnId;
_metadata = metadata;
}
}
sealed internal class Row {
private object[] _dataFields;
internal Row(int rowCount) {
_dataFields = new object[rowCount];
}
internal object[] DataFields {
get {
return _dataFields;
}
}
internal object this[int index] {
get {
return _dataFields[index];
}
}
}
// the controlling class for one result (metadata + rows)
//
sealed internal class Result {
private _SqlMetaDataSet _metadata;
private ArrayList _rowset;
internal Result(_SqlMetaDataSet metadata) {
this._metadata = metadata;
this._rowset = new ArrayList();
}
internal int Count {
get {
return _rowset.Count;
}
}
internal _SqlMetaDataSet MetaData {
get {
return _metadata;
}
}
internal Row this[int index] {
get {
return (Row)_rowset[index];
}
}
internal void AddRow(Row row) {
_rowset.Add(row);
}
}
// A wrapper object for metadata and rowsets returned by our initial queries
//
sealed internal class BulkCopySimpleResultSet {
private ArrayList _results; // the list of results
private Result resultSet; // the current result
private int[] indexmap; // associates columnids with indexes in the rowarray
// c-tor
//
internal BulkCopySimpleResultSet() {
_results = new ArrayList();
}
// indexer
//
internal Result this[int idx] {
get {
return (Result)_results[idx];
}
}
// callback function for the tdsparser
// note that setting the metadata adds a resultset
//
internal void SetMetaData(_SqlMetaDataSet metadata) {
resultSet = new Result(metadata);
_results.Add(resultSet);
indexmap = new int[resultSet.MetaData.Length];
for(int i = 0; i < indexmap.Length; i++) {
indexmap[i] = i;
}
}
// callback function for the tdsparser
// this will create an indexmap for the active resultset
//
internal int[] CreateIndexMap() {
return indexmap;
}
// callback function for the tdsparser
// this will return an array of rows to store the rowdata
//
internal object[] CreateRowBuffer() {
Row row = new Row(resultSet.MetaData.Length);
resultSet.AddRow(row);
return row.DataFields;
}
}
// -------------------------------------------------------------------------------------------------
//
//
public sealed class SqlBulkCopy : IDisposable {
private enum TableNameComponents {
Server = 0,
Catalog,
Owner,
TableName,
}
private enum ValueSourceType {
Unspecified = 0,
IDataReader,
DataTable,
RowArray,
DbDataReader
}
// Enum for specifying SqlDataReader.Get method used
private enum ValueMethod : byte {
GetValue,
SqlTypeSqlDecimal,
SqlTypeSqlDouble,
SqlTypeSqlSingle,
DataFeedStream,
DataFeedText,
DataFeedXml
}
// Used to hold column metadata for SqlDataReader case
private struct SourceColumnMetadata {
public SourceColumnMetadata(ValueMethod method, bool isSqlType, bool isDataFeed) {
Method = method;
IsSqlType = isSqlType;
IsDataFeed = isDataFeed;
}
public readonly ValueMethod Method;
public readonly bool IsSqlType;
public readonly bool IsDataFeed;
}
// The initial query will return three tables.
// Transaction count has only one value in one column and one row
// MetaData has n columns but no rows
// Collation has 4 columns and n rows
private const int TranCountResultId = 0;
private const int TranCountRowId = 0;
private const int TranCountValueId = 0;
private const int MetaDataResultId = 1;
private const int CollationResultId = 2;
private const int ColIdId = 0;
private const int NameId = 1;
private const int Tds_CollationId = 2;
private const int CollationId = 3;
private const int MAX_LENGTH = 0x7FFFFFFF;
private const int DefaultCommandTimeout = 30;
private bool _enableStreaming = false;
private int _batchSize;
private bool _ownConnection;
private SqlBulkCopyOptions _copyOptions;
private int _timeout = DefaultCommandTimeout;
private string _destinationTableName;
private int _rowsCopied;
private int _notifyAfter;
private int _rowsUntilNotification;
private bool _insideRowsCopiedEvent;
private object _rowSource;
private SqlDataReader _SqlDataReaderRowSource;
private bool _rowSourceIsSqlDataReaderSmi;
private DbDataReader _DbDataReaderRowSource;
private DataTable _dataTableSource;
private SqlBulkCopyColumnMappingCollection _columnMappings;
private SqlBulkCopyColumnMappingCollection _localColumnMappings;
private SqlConnection _connection;
private SqlTransaction _internalTransaction;
private SqlTransaction _externalTransaction;
private ValueSourceType _rowSourceType = ValueSourceType.Unspecified;
private DataRow _currentRow;
private int _currentRowLength;
private DataRowState _rowStateToSkip;
private IEnumerator _rowEnumerator;
private TdsParser _parser;
private TdsParserStateObject _stateObj;
private List<_ColumnMapping> _sortedColumnMappings;
private SqlRowsCopiedEventHandler _rowsCopiedEventHandler;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
//newly added member variables for Async modification, m = member variable to bcp
private int _savedBatchSize = 0; //save the batchsize so that changes are not affected unexpectedly
private bool _hasMoreRowToCopy = false;
private bool _isAsyncBulkCopy = false;
private bool _isBulkCopyingInProgress = false;
private SqlInternalConnectionTds.SyncAsyncLock _parserLock = null;
private SourceColumnMetadata[] _currentRowMetadata;
// for debug purpose only.
//
#if DEBUG
internal static bool _setAlwaysTaskOnWrite = false; //when set and in DEBUG mode, TdsParser::WriteBulkCopyValue will always return a task
internal static bool SetAlwaysTaskOnWrite {
set {
_setAlwaysTaskOnWrite = value;
}
get{
return _setAlwaysTaskOnWrite;
}
}
#endif
// ctor
//
public SqlBulkCopy(SqlConnection connection) {
if(connection == null) {
throw ADP.ArgumentNull("connection");
}
_connection = connection;
_columnMappings = new SqlBulkCopyColumnMappingCollection();
}
public SqlBulkCopy(SqlConnection connection, SqlBulkCopyOptions copyOptions, SqlTransaction externalTransaction)
: this (connection) {
_copyOptions = copyOptions;
if(externalTransaction != null && IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction)) {
throw SQL.BulkLoadConflictingTransactionOption();
}
if(!IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction)) {
_externalTransaction = externalTransaction;
}
}
public SqlBulkCopy(string connectionString) : this (new SqlConnection(connectionString)) {
if(connectionString == null) {
throw ADP.ArgumentNull("connectionString");
}
_connection = new SqlConnection(connectionString);
_columnMappings = new SqlBulkCopyColumnMappingCollection();
_ownConnection = true;
}
public SqlBulkCopy(string connectionString, SqlBulkCopyOptions copyOptions)
: this (connectionString) {
_copyOptions = copyOptions;
}
public int BatchSize {
get {
return _batchSize;
}
set {
if(value >= 0) {
_batchSize = value;
}
else {
throw ADP.ArgumentOutOfRange("BatchSize");
}
}
}
public int BulkCopyTimeout {
get {
return _timeout;
}
set {
if(value < 0) {
throw SQL.BulkLoadInvalidTimeout(value);
}
_timeout = value;
}
}
public bool EnableStreaming {
get {
return _enableStreaming;
}
set {
_enableStreaming = value;
}
}
public SqlBulkCopyColumnMappingCollection ColumnMappings {
get {
return _columnMappings;
}
}
public string DestinationTableName {
get {
return _destinationTableName;
}
set {
if(value == null) {
throw ADP.ArgumentNull("DestinationTableName");
}
else if(value.Length == 0) {
throw ADP.ArgumentOutOfRange("DestinationTableName");
}
_destinationTableName = value;
}
}
public int NotifyAfter {
get {
return _notifyAfter;
}
set {
if(value >= 0) {
_notifyAfter = value;
}
else {
throw ADP.ArgumentOutOfRange("NotifyAfter");
}
}
}
internal int ObjectID {
get {
return _objectID;
}
}
public event SqlRowsCopiedEventHandler SqlRowsCopied {
add {
_rowsCopiedEventHandler += value;
}
remove {
_rowsCopiedEventHandler -= value;
}
}
internal SqlStatistics Statistics {
get {
if(null != _connection) {
if(_connection.StatisticsEnabled) {
return _connection.Statistics;
}
}
return null;
}
}
//================================================================
// IDisposable
//================================================================
void IDisposable.Dispose() {
this.Dispose(true);
GC.SuppressFinalize(this);
}
private bool IsCopyOption(SqlBulkCopyOptions copyOption) {
return (_copyOptions & copyOption) == copyOption;
}
//Creates the initial query string, but does not execute it.
//
private string CreateInitialQuery() {
string[] parts;
try {
parts = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", Res.SQL_BulkCopyDestinationTableName, true);
}
catch (Exception e) {
throw SQL.BulkLoadInvalidDestinationTable(this.DestinationTableName, e);
}
if (ADP.IsEmpty(parts[MultipartIdentifier.TableIndex])) {
throw SQL.BulkLoadInvalidDestinationTable(this.DestinationTableName, null);
}
string TDSCommand;
TDSCommand = "select @@trancount; SET FMTONLY ON select * from " + this.DestinationTableName + " SET FMTONLY OFF ";
if (_connection.IsShiloh) {
// If its a temp DB then try to connect
string TableCollationsStoredProc;
if (_connection.IsKatmaiOrNewer) {
TableCollationsStoredProc = "sp_tablecollations_100";
}
else if (_connection.IsYukonOrNewer) {
TableCollationsStoredProc = "sp_tablecollations_90";
}
else {
TableCollationsStoredProc = "sp_tablecollations";
}
string TableName = parts[MultipartIdentifier.TableIndex];
bool isTempTable = TableName.Length > 0 && '#' == TableName[0];
if (!ADP.IsEmpty(TableName)) {
// Escape table name to be put inside TSQL literal block (within N'').
TableName = SqlServerEscapeHelper.EscapeStringAsLiteral(TableName);
// VSDD 581951 - escape the table name
TableName = SqlServerEscapeHelper.EscapeIdentifier(TableName);
}
string SchemaName = parts[MultipartIdentifier.SchemaIndex];
if (!ADP.IsEmpty(SchemaName)) {
// Escape schema name to be put inside TSQL literal block (within N'').
SchemaName = SqlServerEscapeHelper.EscapeStringAsLiteral(SchemaName);
// VSDD 581951 - escape the schema name
SchemaName = SqlServerEscapeHelper.EscapeIdentifier(SchemaName);
}
string CatalogName = parts[MultipartIdentifier.CatalogIndex];
if (isTempTable && ADP.IsEmpty(CatalogName)) {
TDSCommand += String.Format((IFormatProvider)null, "exec tempdb..{0} N'{1}.{2}'",
TableCollationsStoredProc,
SchemaName,
TableName
);
}
else {
// VSDD 581951 - escape the catalog name
if (!ADP.IsEmpty(CatalogName)) {
CatalogName = SqlServerEscapeHelper.EscapeIdentifier(CatalogName);
}
TDSCommand += String.Format((IFormatProvider)null, "exec {0}..{1} N'{2}.{3}'",
CatalogName,
TableCollationsStoredProc,
SchemaName,
TableName
);
}
}
return TDSCommand;
}
// Creates and then executes initial query to get information about the targettable
// When __isAsyncBulkCopy == false (i.e. it is Sync copy): out result contains the resulset. Returns null.
// When __isAsyncBulkCopy == true (i.e. it is Async copy): This still uses the _parser.Run method synchronously and return Task<BulkCopySimpleResultSet>.
// We need to have a _parser.RunAsync to make it real async.
private Task<BulkCopySimpleResultSet> CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) {
string TDSCommand = CreateInitialQuery();
Bid.Trace("<sc.SqlBulkCopy.CreateAndExecuteInitialQueryAsync|INFO> Initial Query: '%ls' \n", TDSCommand);
Bid.CorrelationTrace("<sc.SqlBulkCopy.CreateAndExecuteInitialQueryAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true);
if (executeTask == null) {
result = new BulkCopySimpleResultSet();
RunParser(result);
return null;
}
else {
Debug.Assert(_isAsyncBulkCopy, "Execution pended when not doing async bulk copy");
result = null;
return executeTask.ContinueWith<BulkCopySimpleResultSet>(t => {
Debug.Assert(!t.IsCanceled, "Execution task was canceled");
if (t.IsFaulted) {
throw t.Exception.InnerException;
}
else {
var internalResult = new BulkCopySimpleResultSet();
RunParserReliably(internalResult);
return internalResult;
}
}, TaskScheduler.Default);
}
}
// Matches associated columns with metadata from initial query
// builds and executes the update bulk command
//
private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet internalResults) {
StringBuilder updateBulkCommandText = new StringBuilder();
if (_connection.IsShiloh && 0 == internalResults[CollationResultId].Count) {
throw SQL.BulkLoadNoCollation();
}
Debug.Assert((internalResults != null), "Where are the results from the initial query?");
updateBulkCommandText.AppendFormat("insert bulk {0} (", this.DestinationTableName);
int nmatched = 0; // number of columns that match and are accepted
int nrejected = 0; // number of columns that match but were rejected
bool rejectColumn; // true if a column is rejected because of an excluded type
bool isInTransaction;
if(_parser.IsYukonOrNewer) {
isInTransaction = _connection.HasLocalTransaction;
}
else {
isInTransaction = (bool)(0 < (SqlInt32)(internalResults[TranCountResultId][TranCountRowId][TranCountValueId]));
}
// Throw if there is a transaction but no flag is set
if(isInTransaction && null == _externalTransaction && null == _internalTransaction && (_connection.Parser != null && _connection.Parser.CurrentTransaction != null && _connection.Parser.CurrentTransaction.IsLocal)) {
throw SQL.BulkLoadExistingTransaction();
}
// loop over the metadata for each column
//
_SqlMetaDataSet metaDataSet = internalResults[MetaDataResultId].MetaData;
_sortedColumnMappings = new List<_ColumnMapping>(metaDataSet.Length);
for(int i = 0; i < metaDataSet.Length; i++) {
_SqlMetaData metadata = metaDataSet[i];
rejectColumn = false;
// Check for excluded types
//
if((metadata.type == SqlDbType.Timestamp)
|| ((metadata.isIdentity) && !IsCopyOption(SqlBulkCopyOptions.KeepIdentity))) {
// remove metadata for excluded columns
metaDataSet[i] = null;
rejectColumn = true;
// we still need to find a matching column association
}
// find out if this column is associated
int assocId;
for(assocId = 0; assocId < _localColumnMappings.Count; assocId++) {
if((_localColumnMappings[assocId]._destinationColumnOrdinal == metadata.ordinal) ||
(UnquotedName(_localColumnMappings[assocId]._destinationColumnName) == metadata.column)) {
if(rejectColumn) {
nrejected++; // count matched columns only
break;
}
_sortedColumnMappings.Add(new _ColumnMapping(_localColumnMappings[assocId]._internalSourceColumnOrdinal, metadata));
nmatched++;
if(nmatched > 1) {
updateBulkCommandText.Append(", "); // a leading comma for all but the first one
}
// some datatypes need special handling ...
//
if(metadata.type == SqlDbType.Variant) {
AppendColumnNameAndTypeName(updateBulkCommandText, metadata.column, "sql_variant");
}
else if(metadata.type == SqlDbType.Udt) {
// UDTs are sent as varbinary
AppendColumnNameAndTypeName(updateBulkCommandText, metadata.column, "varbinary");
}
else {
AppendColumnNameAndTypeName(updateBulkCommandText, metadata.column, typeof(SqlDbType).GetEnumName(metadata.type));
}
switch(metadata.metaType.NullableType) {
case TdsEnums.SQLNUMERICN:
case TdsEnums.SQLDECIMALN:
// decimal and numeric need to include precision and scale
//
updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0},{1})", metadata.precision, metadata.scale);
break;
case TdsEnums.SQLUDT: {
if (metadata.IsLargeUdt) {
updateBulkCommandText.Append("(max)");
} else {
int size = metadata.length;
updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0})", size);
}
break;
}
case TdsEnums.SQLTIME:
case TdsEnums.SQLDATETIME2:
case TdsEnums.SQLDATETIMEOFFSET:
// date, dateime2, and datetimeoffset need to include scale
//
updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0})", metadata.scale);
break;
default: {
// for non-long non-fixed types we need to add the Size
//
if(!metadata.metaType.IsFixed && !metadata.metaType.IsLong) {
int size = metadata.length;
switch(metadata.metaType.NullableType) {
case TdsEnums.SQLNCHAR:
case TdsEnums.SQLNVARCHAR:
case TdsEnums.SQLNTEXT:
size /= 2;
break;
default:
break;
}
updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0})", size);
}
else if(metadata.metaType.IsPlp && metadata.metaType.SqlDbType != SqlDbType.Xml) {
// Partial length column prefix (max)
updateBulkCommandText.Append("(max)");
}
break;
}
}
if(_connection.IsShiloh) {
// Shiloh or above!
// get collation for column i
Result rowset = internalResults[CollationResultId];
object rowvalue = rowset[i][CollationId];
bool shouldSendCollation;
switch (metadata.type) {
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.VarChar:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.NText:
shouldSendCollation = true;
break;
default:
shouldSendCollation = false;
break;
}
if (rowvalue != null && shouldSendCollation) {
Debug.Assert(rowvalue is SqlString);
SqlString collation_name = (SqlString)rowvalue;
if(!collation_name.IsNull) {
updateBulkCommandText.Append(" COLLATE " + collation_name.Value);
// VSTFDEVDIV 461426: compare collations only if the collation value was set on the metadata
if (null != _SqlDataReaderRowSource && metadata.collation != null) {
// On SqlDataReader we can verify the sourcecolumn collation!
int sourceColumnId = _localColumnMappings[assocId]._internalSourceColumnOrdinal;
int destinationLcid = metadata.collation.LCID;
int sourceLcid = _SqlDataReaderRowSource.GetLocaleId(sourceColumnId);
if(sourceLcid != destinationLcid) {
throw SQL.BulkLoadLcidMismatch(sourceLcid, _SqlDataReaderRowSource.GetName(sourceColumnId), destinationLcid, metadata.column);
}
}
}
}
}
break;
} // end if found
} // end of (inner) for loop
if(assocId == _localColumnMappings.Count) {
// remove metadata for unmatched columns
metaDataSet[i] = null;
}
} // end of (outer) for loop
// all columnmappings should have matched up
if(nmatched + nrejected != _localColumnMappings.Count) {
throw (SQL.BulkLoadNonMatchingColumnMapping());
}
updateBulkCommandText.Append(")");
if((_copyOptions & (
SqlBulkCopyOptions.KeepNulls
| SqlBulkCopyOptions.TableLock
| SqlBulkCopyOptions.CheckConstraints
| SqlBulkCopyOptions.FireTriggers
| SqlBulkCopyOptions.AllowEncryptedValueModifications)) != SqlBulkCopyOptions.Default) {
bool addSeparator = false; // insert a comma character if multiple options in list ...
updateBulkCommandText.Append(" with (");
if(IsCopyOption(SqlBulkCopyOptions.KeepNulls)) {
updateBulkCommandText.Append("KEEP_NULLS");
addSeparator = true;
}
if(IsCopyOption(SqlBulkCopyOptions.TableLock)) {
updateBulkCommandText.Append((addSeparator ? ", " : "") + "TABLOCK");
addSeparator = true;
}
if(IsCopyOption(SqlBulkCopyOptions.CheckConstraints)) {
updateBulkCommandText.Append((addSeparator ? ", " : "") + "CHECK_CONSTRAINTS");
addSeparator = true;
}
if(IsCopyOption(SqlBulkCopyOptions.FireTriggers)) {
updateBulkCommandText.Append((addSeparator ? ", " : "") + "FIRE_TRIGGERS");
addSeparator = true;
}
if(IsCopyOption(SqlBulkCopyOptions.AllowEncryptedValueModifications)) {
updateBulkCommandText.Append((addSeparator ? ", " : "") + "ALLOW_ENCRYPTED_VALUE_MODIFICATIONS");
addSeparator = true;
}
updateBulkCommandText.Append(")");
}
return (updateBulkCommandText.ToString());
}
// submitts the updatebulk command
//
private Task SubmitUpdateBulkCommand(string TDSCommand) {
Bid.CorrelationTrace("<sc.SqlBulkCopy.SubmitUpdateBulkCommand|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true);
if (executeTask == null) {
RunParser();
return null;
}
else {
Debug.Assert(_isAsyncBulkCopy, "Execution pended when not doing async bulk copy");
return executeTask.ContinueWith(t => {
Debug.Assert(!t.IsCanceled, "Execution task was canceled");
if (t.IsFaulted) {
throw t.Exception.InnerException;
}
else {
RunParserReliably();
}
}, TaskScheduler.Default);
}
}
// Starts writing the Bulkcopy data stream
//
private void WriteMetaData(BulkCopySimpleResultSet internalResults) {
_stateObj.SetTimeoutSeconds(this.BulkCopyTimeout);
_SqlMetaDataSet metadataCollection = internalResults[MetaDataResultId].MetaData;
_stateObj._outputMessageType = TdsEnums.MT_BULK;
_parser.WriteBulkCopyMetaData(metadataCollection, _sortedColumnMappings.Count, _stateObj);
}
//================================================================
// Close()
//
// Terminates the bulk copy operation.
// Must be called at the end of the bulk copy session.
//================================================================
public void Close() {
if(_insideRowsCopiedEvent) {
throw SQL.InvalidOperationInsideEvent();
}
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
if(disposing) {
// dispose dependend objects
_columnMappings = null;
_parser = null;
try {
// Just in case there is a lingering transaction (which there shouldn't be)
try {
Debug.Assert(_internalTransaction == null, "Internal transaction exists during dispose");
if (null != _internalTransaction) {
_internalTransaction.Rollback();
_internalTransaction.Dispose();
_internalTransaction = null;
}
}
catch(Exception e) {
//
if(!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
finally {
if(_connection != null) {
if(_ownConnection) {
_connection.Dispose();
}
_connection = null;
}
}
}
// free unmanaged objects
}
// unified method to read a value from the current row
//
private object GetValueFromSourceRow(int destRowIndex, out bool isSqlType, out bool isDataFeed, out bool isNull) {
_SqlMetaData metadata = _sortedColumnMappings[destRowIndex]._metadata;
int sourceOrdinal = _sortedColumnMappings[destRowIndex]._sourceColumnOrdinal;
switch(_rowSourceType) {
case ValueSourceType.IDataReader:
case ValueSourceType.DbDataReader:
// Handle data feeds (common for both DbDataReader and SqlDataReader)
if (_currentRowMetadata[destRowIndex].IsDataFeed) {
if (_DbDataReaderRowSource.IsDBNull(sourceOrdinal)) {
isSqlType = false;
isDataFeed = false;
isNull = true;
return DBNull.Value;
}
else {
isSqlType = false;
isDataFeed = true;
isNull = false;
switch (_currentRowMetadata[destRowIndex].Method) {
case ValueMethod.DataFeedStream:
return new StreamDataFeed(_DbDataReaderRowSource.GetStream(sourceOrdinal));
case ValueMethod.DataFeedText:
return new TextDataFeed(_DbDataReaderRowSource.GetTextReader(sourceOrdinal));
case ValueMethod.DataFeedXml:
// Only SqlDataReader supports an XmlReader
// There is no GetXmlReader on DbDataReader, however if GetValue returns XmlReader we will read it as stream if it is assigned to XML field
Debug.Assert(_SqlDataReaderRowSource != null, "Should not be reading row as an XmlReader if bulk copy source is not a SqlDataReader");
return new XmlDataFeed(_SqlDataReaderRowSource.GetXmlReader(sourceOrdinal));
default:
Debug.Assert(false, string.Format("Current column is marked as being a DataFeed, but no DataFeed compatible method was provided. Method: {0}", _currentRowMetadata[destRowIndex].Method));
isDataFeed = false;
object columnValue = _DbDataReaderRowSource.GetValue(sourceOrdinal);
ADP.IsNullOrSqlType(columnValue, out isNull, out isSqlType);
return columnValue;
}
}
}
// SqlDataReader-specific logic
else if (null != _SqlDataReaderRowSource) {
if (_currentRowMetadata[destRowIndex].IsSqlType) {
INullable value;
isSqlType = true;
isDataFeed = false;
switch (_currentRowMetadata[destRowIndex].Method) {
case ValueMethod.SqlTypeSqlDecimal:
value = _SqlDataReaderRowSource.GetSqlDecimal(sourceOrdinal);
break;
case ValueMethod.SqlTypeSqlDouble:
value = new SqlDecimal(_SqlDataReaderRowSource.GetSqlDouble(sourceOrdinal).Value);
break;
case ValueMethod.SqlTypeSqlSingle:
value = new SqlDecimal(_SqlDataReaderRowSource.GetSqlSingle(sourceOrdinal).Value);
break;
default:
Debug.Assert(false, string.Format("Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {0}", _currentRowMetadata[destRowIndex].Method));
value = (INullable)_SqlDataReaderRowSource.GetSqlValue(sourceOrdinal);
break;
}
isNull = value.IsNull;
return value;
}
else {
isSqlType = false;
isDataFeed = false;
object value = _SqlDataReaderRowSource.GetValue(sourceOrdinal);
isNull = ((value == null) || (value == DBNull.Value));
if ((!isNull) && (metadata.type == SqlDbType.Udt)) {
var columnAsINullable = value as INullable;
isNull = (columnAsINullable != null) && columnAsINullable.IsNull;
}
#if DEBUG
else if (!isNull) {
Debug.Assert(!(value is INullable) || !((INullable)value).IsNull, "IsDBNull returned false, but GetValue returned a null INullable");
}
#endif
return value;
}
}
else {
isDataFeed = false;
IDataReader rowSourceAsIDataReader = (IDataReader)_rowSource;
// Back-compat with 4.0 and 4.5 - only use IsDbNull when streaming is enabled and only for non-SqlDataReader
if ((_enableStreaming) && (_SqlDataReaderRowSource == null) && (rowSourceAsIDataReader.IsDBNull(sourceOrdinal))) {
isSqlType = false;
isNull = true;
return DBNull.Value;
}
else {
object columnValue = rowSourceAsIDataReader.GetValue(sourceOrdinal);
ADP.IsNullOrSqlType(columnValue, out isNull, out isSqlType);
return columnValue;
}
}
case ValueSourceType.DataTable:
case ValueSourceType.RowArray: {
Debug.Assert(_currentRow != null, "uninitialized _currentRow");
Debug.Assert(sourceOrdinal < _currentRowLength, "inconsistency of length of rows from rowsource!");
isDataFeed = false;
object currentRowValue = _currentRow[sourceOrdinal];
ADP.IsNullOrSqlType(currentRowValue, out isNull, out isSqlType);
// If this row is not null, and there are special storage types for this row, then handle the special storage types
if ((!isNull) && (_currentRowMetadata[destRowIndex].IsSqlType)) {
switch (_currentRowMetadata[destRowIndex].Method) {
case ValueMethod.SqlTypeSqlSingle: {
if (isSqlType) {
return new SqlDecimal(((SqlSingle)currentRowValue).Value);
}
else {
float f = (float)currentRowValue;
if (!float.IsNaN(f)) {
isSqlType = true;
return new SqlDecimal(f);
}
break;
}
}
case ValueMethod.SqlTypeSqlDouble: {
if (isSqlType) {
return new SqlDecimal(((SqlDouble)currentRowValue).Value);
}
else {
double d = (double)currentRowValue;
if (!double.IsNaN(d)) {
isSqlType = true;
return new SqlDecimal(d);
}
break;
}
}
case ValueMethod.SqlTypeSqlDecimal: {
if (isSqlType) {
return (SqlDecimal)currentRowValue;
}
else {
isSqlType = true;
return new SqlDecimal((Decimal)currentRowValue);
}
}
default: {
Debug.Assert(false, string.Format("Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {0}", _currentRowMetadata[destRowIndex].Method));
break;
}
}
}
// If we are here then either the value is null, there was no special storage type for this column or the special storage type wasn't handled (e.g. if the currentRowValue is NaN)
return currentRowValue;
}
default: {
Debug.Assert(false, "ValueSourcType unspecified");
throw ADP.NotSupported();
}
}
}
// unified method to read a row from the current rowsource
// When _isAsyncBulkCopy == true (i.e. async copy): returns Task<bool> when IDataReader is a DbDataReader, Null for others.
// When _isAsyncBulkCopy == false (i.e. sync copy): returns null. Uses ReadFromRowSource to get the boolean value.
// "more" -- should be used by the caller only when the return value is null.