forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlCommand.cs
6658 lines (5870 loc) · 314 KB
/
SqlCommand.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
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Data.Common;
using Microsoft.Data.Sql;
using Microsoft.Data.SqlClient.Server;
// NOTE: The current Microsoft.VSDesigner editor attributes are implemented for System.Data.SqlClient, and are not publicly available.
// New attributes that are designed to work with Microsoft.Data.SqlClient and are publicly documented should be included in future.
namespace Microsoft.Data.SqlClient
{
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/SqlCommand/*'/>
[DefaultEvent("RecordsAffected")]
[ToolboxItem(true)]
[DesignerCategory("")]
// TODO: Add designer attribute when Microsoft.VSDesigner.Data.VS.SqlCommandDesigner uses Microsoft.Data.SqlClient
public sealed partial class SqlCommand : DbCommand, ICloneable
{
private static int _objectTypeCount; // EventSource Counter
private const int MaxRPCNameLength = 1046;
internal readonly int ObjectID = Interlocked.Increment(ref _objectTypeCount); private string _commandText;
private static readonly Func<AsyncCallback, object, IAsyncResult> s_beginExecuteReaderAsync = BeginExecuteReaderAsyncCallback;
private static readonly Func<IAsyncResult, SqlDataReader> s_endExecuteReaderAsync = EndExecuteReaderAsyncCallback;
private static readonly Action<Task<SqlDataReader>> s_cleanupExecuteReaderAsync = CleanupExecuteReaderAsyncCallback;
private static readonly Func<SqlCommand, IAsyncResult, bool, string, object> s_internalEndExecuteNonQuery = InternalEndExecuteNonQueryCallback;
private static readonly Func<SqlCommand, IAsyncResult, bool, string, object> s_internalEndExecuteReader = InternalEndExecuteReaderCallback;
private static readonly Func<SqlCommand, CommandBehavior, AsyncCallback, object, int, bool, bool, IAsyncResult> s_beginExecuteReaderInternal = BeginExecuteReaderInternalCallback;
private static readonly Func<SqlCommand, CommandBehavior, AsyncCallback, object, int, bool, bool, IAsyncResult> s_beginExecuteXmlReaderInternal = BeginExecuteXmlReaderInternalCallback;
private static readonly Func<SqlCommand, CommandBehavior, AsyncCallback, object, int, bool, bool, IAsyncResult> s_beginExecuteNonQueryInternal = BeginExecuteNonQueryInternalCallback;
internal sealed class ExecuteReaderAsyncCallContext : AAsyncCallContext<SqlCommand, SqlDataReader, CancellationTokenRegistration>
{
public Guid OperationID;
public CommandBehavior CommandBehavior;
public SqlCommand Command => _owner;
public TaskCompletionSource<SqlDataReader> TaskCompletionSource => _source;
public void Set(SqlCommand command, TaskCompletionSource<SqlDataReader> source, CancellationTokenRegistration disposable, CommandBehavior behavior, Guid operationID)
{
base.Set(command, source, disposable);
CommandBehavior = behavior;
OperationID = operationID;
}
protected override void Clear()
{
OperationID = default;
CommandBehavior = default;
}
protected override void AfterCleared(SqlCommand owner)
{
owner?.SetCachedCommandExecuteReaderAsyncContext(this);
}
}
internal sealed class ExecuteNonQueryAsyncCallContext : AAsyncCallContext<SqlCommand, int, CancellationTokenRegistration>
{
public Guid OperationID;
public SqlCommand Command => _owner;
public TaskCompletionSource<int> TaskCompletionSource => _source;
public void Set(SqlCommand command, TaskCompletionSource<int> source, CancellationTokenRegistration disposable, Guid operationID)
{
base.Set(command, source, disposable);
OperationID = operationID;
}
protected override void Clear()
{
OperationID = default;
}
protected override void AfterCleared(SqlCommand owner)
{
}
}
private CommandType _commandType;
private int? _commandTimeout;
private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
private bool _designTimeInvisible;
/// <summary>
/// Indicates if the column encryption setting was set at-least once in the batch rpc mode, when using AddBatchCommand.
/// </summary>
private bool _wasBatchModeColumnEncryptionSettingSetOnce;
/// <summary>
/// Column Encryption Override. Defaults to SqlConnectionSetting, in which case
/// it will be Enabled if SqlConnectionOptions.IsColumnEncryptionSettingEnabled = true, Disabled if false.
/// This may also be used to set other behavior which overrides connection level setting.
/// </summary>
private SqlCommandColumnEncryptionSetting _columnEncryptionSetting = SqlCommandColumnEncryptionSetting.UseConnectionSetting;
internal SqlDependency _sqlDep;
#if DEBUG
/// <summary>
/// Force the client to sleep during sp_describe_parameter_encryption in the function TryFetchInputParameterEncryptionInfo.
/// </summary>
private static bool _sleepDuringTryFetchInputParameterEncryptionInfo = false;
/// <summary>
/// Force the client to sleep during sp_describe_parameter_encryption in the function RunExecuteReaderTds.
/// </summary>
private static bool _sleepDuringRunExecuteReaderTdsForSpDescribeParameterEncryption = false;
/// <summary>
/// Force the client to sleep during sp_describe_parameter_encryption after ReadDescribeEncryptionParameterResults.
/// </summary>
private static bool _sleepAfterReadDescribeEncryptionParameterResults = false;
/// <summary>
/// Internal flag for testing purposes that forces all queries to internally end async calls.
/// </summary>
private static bool _forceInternalEndQuery = false;
#endif
private static readonly SqlDiagnosticListener s_diagnosticListener = new SqlDiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
private bool _parentOperationStarted = false;
internal static readonly Action<object> s_cancelIgnoreFailure = CancelIgnoreFailureCallback;
// Prepare
// Against 7.0 Serve a prepare/unprepare requires an extra roundtrip to the server.
//
// From 8.0 and above the preparation can be done as part of the command execution.
private enum EXECTYPE
{
UNPREPARED, // execute unprepared commands, all server versions (results in sp_execsql call)
PREPAREPENDING, // prepare and execute command, 8.0 and above only (results in sp_prepexec call)
PREPARED, // execute prepared commands, all server versions (results in sp_exec call)
}
// _hiddenPrepare
// On 8.0 and above the Prepared state cannot be left. Once a command is prepared it will always be prepared.
// A change in parameters, commandtext etc (IsDirty) automatically causes a hidden prepare
//
// _inPrepare will be set immediately before the actual prepare is done.
// The OnReturnValue function will test this flag to determine whether the returned value is a _prepareHandle or something else.
//
// _prepareHandle - the handle of a prepared command. Apparently there can be multiple prepared commands at a time - a feature that we do not support yet.
private static readonly object s_cachedInvalidPrepareHandle = (object)-1;
private bool _inPrepare = false;
private object _prepareHandle = s_cachedInvalidPrepareHandle; // this is an int which is used in the object typed SqlParameter.Value field, avoid repeated boxing by storing in a box
private bool _hiddenPrepare = false;
private int _preparedConnectionCloseCount = -1;
private int _preparedConnectionReconnectCount = -1;
private SqlParameterCollection _parameters;
private SqlConnection _activeConnection;
private bool _dirty = false; // true if the user changes the commandtext or number of parameters after the command is already prepared
private EXECTYPE _execType = EXECTYPE.UNPREPARED; // by default, assume the user is not sharing a connection so the command has not been prepared
private _SqlRPC[] _rpcArrayOf1 = null; // Used for RPC executes
private _SqlRPC _rpcForEncryption = null; // Used for sp_describe_parameter_encryption RPC executes
// cut down on object creation and cache all these
// cached metadata
private _SqlMetaDataSet _cachedMetaData;
internal ConcurrentDictionary<int, SqlTceCipherInfoEntry> keysToBeSentToEnclave;
internal bool requiresEnclaveComputations = false;
private bool ShouldCacheEncryptionMetadata
{
get
{
return !requiresEnclaveComputations || _activeConnection.Parser.AreEnclaveRetriesSupported;
}
}
internal EnclavePackage enclavePackage = null;
private SqlEnclaveAttestationParameters enclaveAttestationParameters = null;
private byte[] customData = null;
private int customDataLength = 0;
// Last TaskCompletionSource for reconnect task - use for cancellation only
private TaskCompletionSource<object> _reconnectionCompletionSource = null;
#if DEBUG
internal static int DebugForceAsyncWriteDelay { get; set; }
#endif
internal bool InPrepare
{
get
{
return _inPrepare;
}
}
/// <summary>
/// Return if column encryption setting is enabled.
/// The order in the below if is important since _activeConnection.Parser can throw if the
/// underlying tds connection is closed and we don't want to change the behavior for folks
/// not trying to use transparent parameter encryption i.e. who don't use (SqlCommandColumnEncryptionSetting.Enabled or _activeConnection.IsColumnEncryptionSettingEnabled) here.
/// </summary>
internal bool IsColumnEncryptionEnabled
{
get
{
return (_columnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled
|| (_columnEncryptionSetting == SqlCommandColumnEncryptionSetting.UseConnectionSetting && _activeConnection.IsColumnEncryptionSettingEnabled))
&& _activeConnection.Parser != null
&& _activeConnection.Parser.IsColumnEncryptionSupported;
}
}
internal bool ShouldUseEnclaveBasedWorkflow =>
(!string.IsNullOrWhiteSpace(_activeConnection.EnclaveAttestationUrl) || Connection.AttestationProtocol == SqlConnectionAttestationProtocol.None) &&
IsColumnEncryptionEnabled;
/// <summary>
/// Per-command custom providers. It can be provided by the user and can be set more than once.
/// </summary>
private IReadOnlyDictionary<string, SqlColumnEncryptionKeyStoreProvider> _customColumnEncryptionKeyStoreProviders;
internal bool HasColumnEncryptionKeyStoreProvidersRegistered =>
_customColumnEncryptionKeyStoreProviders is not null && _customColumnEncryptionKeyStoreProviders.Count > 0;
// Cached info for async executions
private sealed class CachedAsyncState
{
private int _cachedAsyncCloseCount = -1; // value of the connection's CloseCount property when the asyncResult was set; tracks when connections are closed after an async operation
private TaskCompletionSource<object> _cachedAsyncResult = null;
private SqlConnection _cachedAsyncConnection = null; // Used to validate that the connection hasn't changed when end the connection;
private SqlDataReader _cachedAsyncReader = null;
private RunBehavior _cachedRunBehavior = RunBehavior.ReturnImmediately;
private string _cachedSetOptions = null;
private string _cachedEndMethod = null;
internal CachedAsyncState()
{
}
internal SqlDataReader CachedAsyncReader
{
get { return _cachedAsyncReader; }
}
internal RunBehavior CachedRunBehavior
{
get { return _cachedRunBehavior; }
}
internal string CachedSetOptions
{
get { return _cachedSetOptions; }
}
internal bool PendingAsyncOperation
{
get { return (null != _cachedAsyncResult); }
}
internal string EndMethodName
{
get { return _cachedEndMethod; }
}
internal bool IsActiveConnectionValid(SqlConnection activeConnection)
{
return (_cachedAsyncConnection == activeConnection && _cachedAsyncCloseCount == activeConnection.CloseCount);
}
internal void ResetAsyncState()
{
SqlClientEventSource.Log.TryTraceEvent("CachedAsyncState.ResetAsyncState | API | ObjectId {0}, Client Connection Id {1}, AsyncCommandInProgress={2}",
_cachedAsyncConnection?.ObjectID, _cachedAsyncConnection?.ClientConnectionId, _cachedAsyncConnection?.AsyncCommandInProgress);
_cachedAsyncCloseCount = -1;
_cachedAsyncResult = null;
if (_cachedAsyncConnection != null)
{
_cachedAsyncConnection.AsyncCommandInProgress = false;
_cachedAsyncConnection = null;
}
_cachedAsyncReader = null;
_cachedRunBehavior = RunBehavior.ReturnImmediately;
_cachedSetOptions = null;
_cachedEndMethod = null;
}
internal void SetActiveConnectionAndResult(TaskCompletionSource<object> completion, string endMethod, SqlConnection activeConnection)
{
Debug.Assert(activeConnection != null, "Unexpected null connection argument on SetActiveConnectionAndResult!");
TdsParser parser = activeConnection?.Parser;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.SetActiveConnectionAndResult | API | ObjectId {0}, Client Connection Id {1}, MARS={2}", activeConnection?.ObjectID, activeConnection?.ClientConnectionId, parser?.MARSOn);
if ((parser == null) || (parser.State == TdsParserState.Closed) || (parser.State == TdsParserState.Broken))
{
throw ADP.ClosedConnectionError();
}
_cachedAsyncCloseCount = activeConnection.CloseCount;
_cachedAsyncResult = completion;
if (!parser.MARSOn)
{
if (activeConnection.AsyncCommandInProgress)
throw SQL.MARSUnsupportedOnConnection();
}
_cachedAsyncConnection = activeConnection;
// Should only be needed for non-MARS, but set anyways.
_cachedAsyncConnection.AsyncCommandInProgress = true;
_cachedEndMethod = endMethod;
}
internal void SetAsyncReaderState(SqlDataReader ds, RunBehavior runBehavior, string optionSettings)
{
_cachedAsyncReader = ds;
_cachedRunBehavior = runBehavior;
_cachedSetOptions = optionSettings;
}
}
private CachedAsyncState _cachedAsyncState = null;
private CachedAsyncState cachedAsyncState
{
get
{
if (_cachedAsyncState == null)
{
_cachedAsyncState = new CachedAsyncState();
}
return _cachedAsyncState;
}
}
// sql reader will pull this value out for each NextResult call. It is not cumulative
// _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
internal int _rowsAffected = -1; // rows affected by the command
// number of rows affected by sp_describe_parameter_encryption.
// The below line is used only for debug asserts and not exposed publicly or impacts functionality otherwise.
private int _rowsAffectedBySpDescribeParameterEncryption = -1;
private SqlNotificationRequest _notification;
// transaction support
private SqlTransaction _transaction;
private StatementCompletedEventHandler _statementCompletedEventHandler;
private TdsParserStateObject _stateObj; // this is the TDS session we're using.
// Volatile bool used to synchronize with cancel thread the state change of an executing
// command going from pre-processing to obtaining a stateObject. The cancel synchronization
// we require in the command is only from entering an Execute* API to obtaining a
// stateObj. Once a stateObj is successfully obtained, cancel synchronization is handled
// by the stateObject.
private volatile bool _pendingCancel;
private bool _batchRPCMode;
private List<_SqlRPC> _RPCList;
private _SqlRPC[] _SqlRPCBatchArray;
private _SqlRPC[] _sqlRPCParameterEncryptionReqArray;
private List<SqlParameterCollection> _parameterCollectionList;
private int _currentlyExecutingBatch;
private SqlRetryLogicBaseProvider _retryLogicProvider;
/// <summary>
/// This variable is used to keep track of which RPC batch's results are being read when reading the results of
/// describe parameter encryption RPC requests in BatchRPCMode.
/// </summary>
private int _currentlyExecutingDescribeParameterEncryptionRPC;
/// <summary>
/// A flag to indicate if we have in-progress describe parameter encryption RPC requests.
/// Reset to false when completed.
/// </summary>
internal bool IsDescribeParameterEncryptionRPCCurrentlyInProgress { get; private set; }
/// <summary>
/// A flag to indicate if EndExecute was already initiated by the Begin call.
/// </summary>
private volatile bool _internalEndExecuteInitiated;
/// <summary>
/// A flag to indicate whether we postponed caching the query metadata for this command.
/// </summary>
internal bool CachingQueryMetadataPostponed { get; set; }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ctor[@name="default"]/*'/>
public SqlCommand() : base()
{
GC.SuppressFinalize(this);
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ctor[@name="cmdTextString"]/*'/>
public SqlCommand(string cmdText) : this()
{
CommandText = cmdText;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ctor[@name="cmdTextStringAndSqlConnection"]/*'/>
public SqlCommand(string cmdText, SqlConnection connection) : this()
{
CommandText = cmdText;
Connection = connection;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ctor[@name="cmdTextStringAndSqlConnectionAndSqlTransaction"]/*'/>
public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction) : this()
{
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ctor[@name="cmdTextStringAndSqlConnectionAndSqlTransactionAndSqlCommandColumnEncryptionSetting"]/*'/>
public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction, SqlCommandColumnEncryptionSetting columnEncryptionSetting) : this()
{
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
_columnEncryptionSetting = columnEncryptionSetting;
}
private SqlCommand(SqlCommand from) : this()
{
CommandText = from.CommandText;
CommandTimeout = from.CommandTimeout;
CommandType = from.CommandType;
Connection = from.Connection;
DesignTimeVisible = from.DesignTimeVisible;
Transaction = from.Transaction;
UpdatedRowSource = from.UpdatedRowSource;
_columnEncryptionSetting = from.ColumnEncryptionSetting;
SqlParameterCollection parameters = Parameters;
foreach (object parameter in from.Parameters)
{
parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/Connection/*'/>
/// [
[DefaultValue(null)]
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_Connection)]
new public SqlConnection Connection
{
get
{
return _activeConnection;
}
set
{
// Don't allow the connection to be changed while in an async operation.
if (_activeConnection != value && _activeConnection != null)
{ // If new value...
if (_cachedAsyncState != null && _cachedAsyncState.PendingAsyncOperation)
{ // If in pending async state, throw.
throw SQL.CannotModifyPropertyAsyncOperationInProgress();
}
}
// Check to see if the currently set transaction has completed. If so,
// null out our local reference.
if (null != _transaction && _transaction.Connection == null)
{
_transaction = null;
}
// Command is no longer prepared on new connection, cleanup prepare status
if (IsPrepared)
{
if (_activeConnection != value && _activeConnection != null)
{
try
{
// cleanup
Unprepare();
}
catch (Exception)
{
// we do not really care about errors in unprepare (may be the old connection went bad)
}
finally
{
// clean prepare status (even successful Unprepare does not do that)
_prepareHandle = s_cachedInvalidPrepareHandle;
_execType = EXECTYPE.UNPREPARED;
}
}
}
_activeConnection = value;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_Connection | API | ObjectId {0}, Client Connection Id {1}", ObjectID, value?.ClientConnectionId);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/DbConnection/*'/>
protected override DbConnection DbConnection
{
get
{
return Connection;
}
set
{
Connection = (SqlConnection)value;
}
}
private SqlInternalConnectionTds InternalTdsConnection
{
get
{
return (SqlInternalConnectionTds)_activeConnection.InnerConnection;
}
}
private bool IsProviderRetriable => SqlConfigurableRetryFactory.IsRetriable(RetryLogicProvider);
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/RetryLogicProvider/*' />
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public SqlRetryLogicBaseProvider RetryLogicProvider
{
get
{
if (_retryLogicProvider == null)
{
_retryLogicProvider = SqlConfigurableRetryLogicManager.CommandProvider;
}
return _retryLogicProvider;
}
set
{
_retryLogicProvider = value;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/Notification/*'/>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] // MDAC 90471
[ResCategory(StringsHelper.ResourceNames.DataCategory_Notification)]
[ResDescription(StringsHelper.ResourceNames.SqlCommand_Notification)]
public SqlNotificationRequest Notification
{
get
{
return _notification;
}
set
{
_sqlDep = null;
_notification = value;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_Notification | API | Object Id {0}", ObjectID);
}
}
internal SqlStatistics Statistics
{
get
{
if (null != _activeConnection)
{
if (_activeConnection.StatisticsEnabled ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand))
{
return _activeConnection.Statistics;
}
}
return null;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/Transaction/*'/>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_Transaction)]
new public SqlTransaction Transaction
{
get
{
// if the transaction object has been zombied, just return null
if ((null != _transaction) && (null == _transaction.Connection))
{
_transaction = null;
}
return _transaction;
}
set
{
// Don't allow the transaction to be changed while in an async operation.
if (_transaction != value && _activeConnection != null)
{ // If new value...
if (cachedAsyncState.PendingAsyncOperation)
{ // If in pending async state, throw
throw SQL.CannotModifyPropertyAsyncOperationInProgress();
}
}
_transaction = value;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_Transaction | API | Object Id {0}, Internal Transaction Id {1}, Client Connection Id {2}", ObjectID, value?.InternalTransaction?.TransactionId, Connection?.ClientConnectionId);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/DbTransaction/*'/>
protected override DbTransaction DbTransaction
{
get
{
return Transaction;
}
set
{
Transaction = (SqlTransaction)value;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_DbTransaction | API | Object Id {0}, Client Connection Id {1}", ObjectID, Connection?.ClientConnectionId);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/CommandText/*'/>
[DefaultValue("")]
[RefreshProperties(RefreshProperties.All)] // MDAC 67707
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_CommandText)]
public override string CommandText
{
get => _commandText ?? "";
set
{
if (_commandText != value)
{
PropertyChanging();
_commandText = value;
}
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_CommandText | API | Object Id {0}, String Value = '{1}', Client Connection Id {2}", ObjectID, value, Connection?.ClientConnectionId);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ColumnEncryptionSetting/*'/>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data)]
[ResDescription(StringsHelper.ResourceNames.TCE_SqlCommand_ColumnEncryptionSetting)]
public SqlCommandColumnEncryptionSetting ColumnEncryptionSetting => _columnEncryptionSetting;
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/CommandTimeout/*'/>
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_CommandTimeout)]
public override int CommandTimeout
{
get
{
return _commandTimeout ?? DefaultCommandTimeout;
}
set
{
if (value < 0)
{
throw ADP.InvalidCommandTimeout(value);
}
if (value != _commandTimeout)
{
PropertyChanging();
_commandTimeout = value;
}
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_CommandTimeout | API | ObjectId {0}, Command Timeout value {1}, Client Connection Id {2}", ObjectID, value, Connection?.ClientConnectionId);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/ResetCommandTimeout/*'/>
public void ResetCommandTimeout()
{
if (ADP.DefaultCommandTimeout != CommandTimeout)
{
PropertyChanging();
_commandTimeout = DefaultCommandTimeout;
}
}
private int DefaultCommandTimeout
{
get
{
return _activeConnection?.CommandTimeout ?? ADP.DefaultCommandTimeout;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/CommandType/*'/>
[DefaultValue(System.Data.CommandType.Text)]
[RefreshProperties(RefreshProperties.All)]
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_CommandType)]
public override CommandType CommandType
{
get
{
CommandType cmdType = _commandType;
return ((0 != cmdType) ? cmdType : CommandType.Text);
}
set
{
if (_commandType != value)
{
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
PropertyChanging();
_commandType = value;
break;
case System.Data.CommandType.TableDirect:
throw SQL.NotSupportedCommandType(value);
default:
throw ADP.InvalidCommandType(value);
}
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.Set_CommandType | API | ObjectId {0}, Command type value {1}, Client Connection Id {2}", ObjectID, (int)value, Connection?.ClientConnectionId);
}
}
}
// @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
// to limit the number of components that clutter the design surface,
// when the DataAdapter design wizard generates the insert/update/delete commands it will
// set the DesignTimeVisible property to false so that cmds won't appear as individual objects
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/DesignTimeVisible/*'/>
[DefaultValue(true)]
[DesignOnly(true)]
[Browsable(false)]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public override bool DesignTimeVisible
{
get
{
return !_designTimeInvisible;
}
set
{
_designTimeInvisible = !value;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/EnableOptimizedParameterBinding/*'/>
public bool EnableOptimizedParameterBinding { get; set; }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/Parameters/*'/>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_Parameters)]
new public SqlParameterCollection Parameters
{
get
{
if (null == _parameters)
{
// delay the creation of the SqlParameterCollection
// until user actually uses the Parameters property
_parameters = new SqlParameterCollection();
}
return _parameters;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/DbParameterCollection/*'/>
protected override DbParameterCollection DbParameterCollection
{
get
{
return Parameters;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/UpdatedRowSource/*'/>
[DefaultValue(System.Data.UpdateRowSource.Both)]
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Update)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_UpdatedRowSource)]
public override UpdateRowSource UpdatedRowSource
{
get
{
return _updatedRowSource;
}
set
{
switch (value)
{
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updatedRowSource = value;
break;
default:
throw ADP.InvalidUpdateRowSource(value);
}
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.UpdatedRowSource | API | ObjectId {0}, Updated row source value {1}, Client Connection Id {2}", ObjectID, (int)value, Connection?.ClientConnectionId);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/StatementCompleted/*'/>
[ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_StatementCompleted)]
[ResDescription(StringsHelper.ResourceNames.DbCommand_StatementCompleted)]
public event StatementCompletedEventHandler StatementCompleted
{
add
{
_statementCompletedEventHandler += value;
}
remove
{
_statementCompletedEventHandler -= value;
}
}
internal void OnStatementCompleted(int recordCount)
{
if (0 <= recordCount)
{
StatementCompletedEventHandler handler = _statementCompletedEventHandler;
if (null != handler)
{
try
{
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.OnStatementCompleted | Info | ObjectId {0}, Record Count {1}, Client Connection Id {2}", ObjectID, recordCount, Connection?.ClientConnectionId);
handler(this, new StatementCompletedEventArgs(recordCount));
}
catch (Exception e)
{
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
}
}
}
}
private void PropertyChanging()
{ // also called from SqlParameterCollection
this.IsDirty = true;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/Prepare/*'/>
public override void Prepare()
{
// Reset _pendingCancel upon entry into any Execute - used to synchronize state
// between entry into Execute* API and the thread obtaining the stateObject.
_pendingCancel = false;
SqlStatistics statistics = null;
using (TryEventScope.Create("SqlCommand.Prepare | API | Object Id {0}", ObjectID))
{
SqlClientEventSource.Log.TryCorrelationTraceEvent("SqlCommand.Prepare | API | Correlation | Object Id {0}, ActivityID {1}, Client Connection Id {2}", ObjectID, ActivityCorrelator.Current, Connection?.ClientConnectionId);
try
{
statistics = SqlStatistics.StartTimer(Statistics);
// only prepare if batch with parameters
if (this.IsPrepared && !this.IsDirty
|| (this.CommandType == CommandType.StoredProcedure)
|| ((System.Data.CommandType.Text == this.CommandType)
&& (0 == GetParameterCount(_parameters))))
{
if (null != Statistics)
{
Statistics.SafeIncrement(ref Statistics._prepares);
}
_hiddenPrepare = false;
}
else
{
// Validate the command outside of the try/catch to avoid putting the _stateObj on error
ValidateCommand(isAsync: false);
bool processFinallyBlock = true;
try
{
// NOTE: The state object isn't actually needed for this, but it is still here for back-compat (since it does a bunch of checks)
GetStateObject();
// Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions
if (null != _parameters)
{
int count = _parameters.Count;
for (int i = 0; i < count; ++i)
{
_parameters[i].Prepare(this);
}
}
InternalPrepare();
}
catch (Exception e)
{
processFinallyBlock = ADP.IsCatchableExceptionType(e);
throw;
}
finally
{
if (processFinallyBlock)
{
_hiddenPrepare = false; // The command is now officially prepared
ReliablePutStateObject();
}
}
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
}
private void InternalPrepare()
{
if (this.IsDirty)
{
Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
//
// someone changed the command text or the parameter schema so we must unprepare the command
//
this.Unprepare();
this.IsDirty = false;
}
Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!");
Debug.Assert(_activeConnection != null, "must have an open connection to Prepare");
Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null");
Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!");
Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser");
Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!");
// remember that the user wants to do a prepare but don't actually do an rpc
_execType = EXECTYPE.PREPAREPENDING;
// Note the current close count of the connection - this will tell us if the connection has been closed between calls to Prepare() and Execute
_preparedConnectionCloseCount = _activeConnection.CloseCount;
_preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
if (null != Statistics)
{
Statistics.SafeIncrement(ref Statistics._prepares);
}
}
// SqlInternalConnectionTds needs to be able to unprepare a statement
internal void Unprepare()
{
Debug.Assert(true == IsPrepared, "Invalid attempt to Unprepare a non-prepared command!");
Debug.Assert(_activeConnection != null, "must have an open connection to UnPrepare");
Debug.Assert(false == _inPrepare, "_inPrepare should be false!");
_execType = EXECTYPE.PREPAREPENDING;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.UnPrepare | Info | Object Id {0}, Current Prepared Handle {1}", ObjectID, _prepareHandle);
// Don't zero out the handle because we'll pass it in to sp_prepexec on the next prepare
// Unless the close count isn't the same as when we last prepared
if ((_activeConnection.CloseCount != _preparedConnectionCloseCount) || (_activeConnection.ReconnectCount != _preparedConnectionReconnectCount))
{
// reset our handle
_prepareHandle = s_cachedInvalidPrepareHandle;
}
_cachedMetaData = null;
SqlClientEventSource.Log.TryTraceEvent("SqlCommand.UnPrepare | Info | Object Id {0}, Command unprepared.", ObjectID);
}
// Cancel is supposed to be multi-thread safe.
// It doesn't make sense to verify the connection exists or that it is open during cancel
// because immediately after checking the connection can be closed or removed via another thread.
//
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml' path='docs/members[@name="SqlCommand"]/Cancel/*'/>
public override void Cancel()
{
using (TryEventScope.Create("SqlCommand.Cancel | API | Object Id {0}", ObjectID))
{
SqlClientEventSource.Log.TryCorrelationTraceEvent("SqlCommand.Cancel | API | Correlation | Object Id {0}, Activity Id {1}, Client Connection Id {2}, Command Text '{3}'", ObjectID, ActivityCorrelator.Current, Connection?.ClientConnectionId, CommandText);
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
// If we are in reconnect phase simply cancel the waiting task
var reconnectCompletionSource = _reconnectionCompletionSource;
if (reconnectCompletionSource != null)