/
OleDbCommand.cs
1388 lines (1233 loc) · 49.6 KB
/
OleDbCommand.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.
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System.Data.OleDb
{
[Designer("Microsoft.VSDesigner.Data.VS.OleDbCommandDesigner, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[ToolboxItem(true)]
public sealed class OleDbCommand : DbCommand, ICloneable, IDbCommand
{
// command data
private string? _commandText;
private CommandType _commandType;
private int _commandTimeout = ADP.DefaultCommandTimeout;
private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
private bool _designTimeInvisible;
private OleDbConnection? _connection;
private OleDbTransaction? _transaction;
private OleDbParameterCollection? _parameters;
// native information
private UnsafeNativeMethods.ICommandText? _icommandText;
// if executing with a different CommandBehavior.KeyInfo behavior
// original ICommandText must be released and a new ICommandText generated
private CommandBehavior commandBehavior;
private Bindings? _dbBindings;
internal bool canceling;
private bool _isPrepared;
private bool _executeQuery;
private bool _trackingForClose;
private bool _hasDataReader;
private IntPtr _recordsAffected;
private int _changeID;
private int _lastChangeID;
public OleDbCommand() : base()
{
GC.SuppressFinalize(this);
}
public OleDbCommand(string? cmdText) : this()
{
CommandText = cmdText;
}
public OleDbCommand(string? cmdText, OleDbConnection? connection) : this()
{
CommandText = cmdText;
Connection = connection;
}
public OleDbCommand(string? cmdText, OleDbConnection? connection, OleDbTransaction? transaction) : this()
{
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
}
private OleDbCommand(OleDbCommand from) : this()
{ // Clone
CommandText = from.CommandText;
CommandTimeout = from.CommandTimeout;
CommandType = from.CommandType;
Connection = from.Connection;
DesignTimeVisible = from.DesignTimeVisible;
UpdatedRowSource = from.UpdatedRowSource;
Transaction = from.Transaction;
OleDbParameterCollection parameters = Parameters;
foreach (object parameter in from.Parameters)
{
parameters.Add(parameter is ICloneable cloneableParameter ? cloneableParameter.Clone() : parameter);
}
}
private Bindings? ParameterBindings
{
get
{
return _dbBindings;
}
set
{
Bindings? bindings = _dbBindings;
_dbBindings = value;
if ((null != bindings) && (value != bindings))
{
bindings.Dispose();
}
}
}
[DefaultValue("")]
[Editor("Microsoft.VSDesigner.Data.ADO.Design.OleDbCommandTextEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[RefreshProperties(RefreshProperties.All)]
[AllowNull]
public override string CommandText
{
get
{
return _commandText ?? string.Empty;
}
set
{
if (0 != ADP.SrcCompare(_commandText, value))
{
PropertyChanging();
_commandText = value;
}
}
}
public override int CommandTimeout
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _commandTimeout;
}
set
{
if (value < 0)
{
throw ADP.InvalidCommandTimeout(value);
}
if (value != _commandTimeout)
{
PropertyChanging();
_commandTimeout = value;
}
}
}
public void ResetCommandTimeout()
{ // V1.2.3300
if (ADP.DefaultCommandTimeout != _commandTimeout)
{
PropertyChanging();
_commandTimeout = ADP.DefaultCommandTimeout;
}
}
[DefaultValue(System.Data.CommandType.Text)]
[RefreshProperties(RefreshProperties.All)]
public override CommandType CommandType
{
get
{
CommandType cmdType = _commandType;
return ((0 != cmdType) ? cmdType : CommandType.Text);
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
PropertyChanging();
_commandType = value;
break;
default:
throw ADP.InvalidCommandType(value);
}
}
}
[DefaultValue(null)]
[Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public new OleDbConnection? Connection
{
get
{
return _connection;
}
set
{
OleDbConnection? connection = _connection;
if (value != connection)
{
PropertyChanging();
ResetConnection();
_connection = value;
if (null != value)
{
_transaction = OleDbTransaction.TransactionUpdate(_transaction);
}
}
}
}
private void ResetConnection()
{
OleDbConnection? connection = _connection;
if (null != connection)
{
PropertyChanging();
CloseInternal();
if (_trackingForClose)
{
connection.RemoveWeakReference(this);
_trackingForClose = false;
}
}
_connection = null;
}
protected override DbConnection? DbConnection
{ // V1.2.3300
get
{
return Connection;
}
set
{
Connection = (OleDbConnection?)value;
}
}
protected override DbParameterCollection DbParameterCollection
{ // V1.2.3300
get
{
return Parameters;
}
}
protected override DbTransaction? DbTransaction
{ // V1.2.3300
get
{
return Transaction;
}
set
{
Transaction = (OleDbTransaction?)value;
}
}
// @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
[
DefaultValue(true),
DesignOnly(true),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
]
public override bool DesignTimeVisible
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return !_designTimeInvisible;
}
set
{
_designTimeInvisible = !value;
TypeDescriptor.Refresh(this);
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content)
]
public new OleDbParameterCollection Parameters
{
get
{
OleDbParameterCollection? value = _parameters;
if (null == value)
{
// delay the creation of the OleDbParameterCollection
// until user actually uses the Parameters property
value = new OleDbParameterCollection();
_parameters = value;
}
return value;
}
}
private bool HasParameters()
{
OleDbParameterCollection? value = _parameters;
return (null != value) && (0 < value.Count);
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public new OleDbTransaction? Transaction
{
get
{
// find the last non-zombied local transaction object, but not transactions
// that may have been started after the current local transaction
OleDbTransaction? transaction = _transaction;
while ((null != transaction) && (null == transaction.Connection))
{
transaction = transaction.Parent;
_transaction = transaction;
}
return transaction;
}
set
{
_transaction = value;
}
}
[
DefaultValue(System.Data.UpdateRowSource.Both)
]
public override UpdateRowSource UpdatedRowSource
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _updatedRowSource;
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updatedRowSource = value;
break;
default:
throw ADP.InvalidUpdateRowSource(value);
}
}
}
// required interface, safe cast
private UnsafeNativeMethods.IAccessor IAccessor()
{
Debug.Assert(null != _icommandText, "IAccessor: null ICommandText");
return (UnsafeNativeMethods.IAccessor)_icommandText;
}
// required interface, safe cast
internal UnsafeNativeMethods.ICommandProperties ICommandProperties()
{
Debug.Assert(null != _icommandText, "ICommandProperties: null ICommandText");
return (UnsafeNativeMethods.ICommandProperties)_icommandText;
}
// optional interface, unsafe cast
private UnsafeNativeMethods.ICommandPrepare? ICommandPrepare()
{
Debug.Assert(null != _icommandText, "ICommandPrepare: null ICommandText");
return _icommandText as UnsafeNativeMethods.ICommandPrepare;
}
// optional interface, unsafe cast
private UnsafeNativeMethods.ICommandWithParameters ICommandWithParameters()
{
Debug.Assert(null != _icommandText, "ICommandWithParameters: null ICommandText");
UnsafeNativeMethods.ICommandWithParameters? value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters);
if (null == value)
{
throw ODB.NoProviderSupportForParameters(_connection!.Provider, null);
}
return value;
}
private void CreateAccessor()
{
Debug.Assert(System.Data.CommandType.Text == CommandType || System.Data.CommandType.StoredProcedure == CommandType, "CreateAccessor: incorrect CommandType");
Debug.Assert(null == _dbBindings, "CreateAccessor: already has dbBindings");
Debug.Assert(HasParameters(), "CreateAccessor: unexpected, no parameter collection");
// do this first in-case the command doesn't support parameters
UnsafeNativeMethods.ICommandWithParameters commandWithParameters = ICommandWithParameters();
OleDbParameterCollection collection = _parameters!;
OleDbParameter[] parameters = new OleDbParameter[collection.Count];
collection.CopyTo(parameters, 0);
// _dbBindings is used as a switch during ExecuteCommand, so don't set it until everything okay
Bindings bindings = new Bindings(parameters, collection.ChangeID);
for (int i = 0; i < parameters.Length; ++i)
{
bindings.ForceRebind |= parameters[i].BindParameter(i, bindings);
}
bindings.AllocateForAccessor(null, 0, 0);
ApplyParameterBindings(commandWithParameters, bindings.BindInfo!);
UnsafeNativeMethods.IAccessor iaccessor = IAccessor();
OleDbHResult hr = bindings.CreateAccessor(iaccessor, ODB.DBACCESSOR_PARAMETERDATA);
if (hr < 0)
{
ProcessResults(hr);
}
_dbBindings = bindings;
}
private unsafe void ApplyParameterBindings(UnsafeNativeMethods.ICommandWithParameters commandWithParameters, tagDBPARAMBINDINFO[] bindInfo)
{
IntPtr[] ordinals = new IntPtr[bindInfo.Length];
for (int i = 0; i < ordinals.Length; ++i)
{
ordinals[i] = (IntPtr)(i + 1);
}
OleDbHResult hr;
if (ODB.IsRunningOnX86)
{
tagDBPARAMBINDINFO_x86[] bindInfo_x86 = new tagDBPARAMBINDINFO_x86[bindInfo.Length];
for (int i = 0; i < bindInfo.Length; i++)
{
fixed (tagDBPARAMBINDINFO* p = &bindInfo[i])
{
bindInfo_x86[i] = *(tagDBPARAMBINDINFO_x86*)p;
}
}
fixed (tagDBPARAMBINDINFO_x86* p = &bindInfo_x86[0])
{
hr = commandWithParameters.SetParameterInfo((IntPtr)bindInfo.Length, ordinals, (IntPtr)p);
}
}
else
{
fixed (tagDBPARAMBINDINFO* p = &bindInfo[0])
{
hr = commandWithParameters.SetParameterInfo((IntPtr)bindInfo.Length, ordinals, (IntPtr)p);
}
}
if (hr < 0)
{
ProcessResults(hr);
}
}
public override void Cancel()
{
unchecked
{ _changeID++; }
UnsafeNativeMethods.ICommandText? icmdtxt = _icommandText;
if (null != icmdtxt)
{
OleDbHResult hr = OleDbHResult.S_OK;
lock (icmdtxt)
{
// lock the object to avoid race conditions between using the object and releasing the object
// after we acquire the lock, if the class has moved on don't actually call Cancel
if (icmdtxt == _icommandText)
{
hr = icmdtxt.Cancel();
}
}
if (OleDbHResult.DB_E_CANTCANCEL != hr)
{
// if the provider can't cancel the command - don't cancel the DataReader
this.canceling = true;
}
// since cancel is allowed to occur at anytime we can't check the connection status
// since if it returns as closed then the connection will close causing the reader to close
// and that would introduce the possilbility of one thread reading and one thread closing at the same time
ProcessResultsNoReset(hr);
}
else
{
this.canceling = true;
}
}
public OleDbCommand Clone()
{
OleDbCommand clone = new OleDbCommand(this);
return clone;
}
object ICloneable.Clone()
{
return Clone();
}
// Connection.Close & Connection.Dispose(true) notification
internal void CloseCommandFromConnection(bool canceling)
{
this.canceling = canceling;
CloseInternal();
_trackingForClose = false;
_transaction = null;
//GC.SuppressFinalize(this);
}
internal void CloseInternal()
{
Debug.Assert(null != _connection, "no connection, CloseInternal");
CloseInternalParameters();
CloseInternalCommand();
}
// may be called from either
// OleDbDataReader.Close/Dispose
// via OleDbCommand.Dispose or OleDbConnection.Close
internal void CloseFromDataReader(Bindings? bindings)
{
if (null != bindings)
{
if (canceling)
{
bindings.Dispose();
Debug.Assert(_dbBindings == bindings, "bindings with two owners");
}
else
{
bindings.ApplyOutputParameters();
ParameterBindings = bindings;
}
}
_hasDataReader = false;
}
private void CloseInternalCommand()
{
unchecked
{ _changeID++; }
this.commandBehavior = CommandBehavior.Default;
_isPrepared = false;
UnsafeNativeMethods.ICommandText? ict = Interlocked.Exchange(ref _icommandText, null);
if (null != ict)
{
lock (ict)
{
// lock the object to avoid race conditions between using the object and releasing the object
Marshal.ReleaseComObject(ict);
}
}
}
private void CloseInternalParameters()
{
Debug.Assert(null != _connection, "no connection, CloseInternalParameters");
Bindings? bindings = _dbBindings;
_dbBindings = null;
bindings?.Dispose();
}
public new OleDbParameter CreateParameter()
{
return new OleDbParameter();
}
protected override DbParameter CreateDbParameter()
{
return CreateParameter();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{ // release mananged objects
// the DataReader takes ownership of the parameter Bindings
// this way they don't get destroyed when user calls OleDbCommand.Dispose
// when there is an open DataReader
unchecked
{ _changeID++; }
// in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset
ResetConnection();
_transaction = null;
_parameters = null;
CommandText = null;
}
// release unmanaged objects
base.Dispose(disposing); // notify base classes
}
public new OleDbDataReader ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
IDataReader IDbCommand.ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
public new OleDbDataReader ExecuteReader(CommandBehavior behavior)
{
_executeQuery = true;
return ExecuteReaderInternal(behavior, ADP.ExecuteReader)!;
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
private OleDbDataReader? ExecuteReaderInternal(CommandBehavior behavior, string method)
{
OleDbDataReader? dataReader = null;
OleDbException? nextResultsFailure = null;
int state = ODB.InternalStateClosed;
try
{
ValidateConnectionAndTransaction(method);
if (0 != (CommandBehavior.SingleRow & behavior))
{
// CommandBehavior.SingleRow implies CommandBehavior.SingleResult
behavior |= CommandBehavior.SingleResult;
}
object? executeResult;
int resultType;
switch (CommandType)
{
case 0: // uninitialized CommandType.Text
case CommandType.Text:
case CommandType.StoredProcedure:
resultType = ExecuteCommand(behavior, out executeResult);
break;
case CommandType.TableDirect:
resultType = ExecuteTableDirect(behavior, out executeResult);
break;
default:
throw ADP.InvalidCommandType(CommandType);
}
if (_executeQuery)
{
try
{
dataReader = new OleDbDataReader(_connection!, this, 0, this.commandBehavior);
switch (resultType)
{
case ODB.ExecutedIMultipleResults:
dataReader.InitializeIMultipleResults(executeResult);
dataReader.NextResult();
break;
case ODB.ExecutedIRowset:
dataReader.InitializeIRowset(executeResult, ChapterHandle.DB_NULL_HCHAPTER, _recordsAffected);
dataReader.BuildMetaInfo();
dataReader.HasRowsRead();
break;
case ODB.ExecutedIRow:
dataReader.InitializeIRow(executeResult, _recordsAffected);
dataReader.BuildMetaInfo();
break;
case ODB.PrepareICommandText:
if (!_isPrepared)
{
PrepareCommandText(2);
}
OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText!, behavior);
break;
default:
Debug.Assert(false, "ExecuteReaderInternal: unknown result type");
break;
}
executeResult = null;
_hasDataReader = true;
_connection!.AddWeakReference(dataReader, OleDbReferenceCollection.DataReaderTag);
// command stays in the executing state until the connection
// has a datareader to track for it being closed
state = ODB.InternalStateOpen;
}
finally
{
if (ODB.InternalStateOpen != state)
{
this.canceling = true;
if (null != dataReader)
{
((IDisposable)dataReader).Dispose();
dataReader = null;
}
}
}
Debug.Assert(null != dataReader, "ExecuteReader should never return a null DataReader");
}
else
{ // optimized code path for ExecuteNonQuery to not create a OleDbDataReader object
try
{
if (ODB.ExecutedIMultipleResults == resultType)
{
UnsafeNativeMethods.IMultipleResults? multipleResults = (UnsafeNativeMethods.IMultipleResults?)executeResult;
// may cause a Connection.ResetState which closes connection
nextResultsFailure = OleDbDataReader.NextResults(multipleResults, _connection!, this, out _recordsAffected);
}
}
finally
{
try
{
if (null != executeResult)
{
Marshal.ReleaseComObject(executeResult);
executeResult = null;
}
CloseFromDataReader(ParameterBindings);
}
catch (Exception e)
{
// UNDONE - should not be catching all exceptions!!!
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
if (null != nextResultsFailure)
{
nextResultsFailure = new OleDbException(nextResultsFailure, e);
}
else
{
throw;
}
}
}
}
}
finally
{ // finally clear executing state
try
{
if ((null == dataReader) && (ODB.InternalStateOpen != state))
{
ParameterCleanup();
}
}
catch (Exception e)
{
// UNDONE - should not be catching all exceptions!!!
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
if (null != nextResultsFailure)
{
nextResultsFailure = new OleDbException(nextResultsFailure, e);
}
else
{
throw;
}
}
if (null != nextResultsFailure)
{
throw nextResultsFailure;
}
}
return dataReader;
}
private int ExecuteCommand(CommandBehavior behavior, out object? executeResult)
{
if (InitializeCommand(behavior))
{
if (0 != (CommandBehavior.SchemaOnly & this.commandBehavior))
{
executeResult = null;
return ODB.PrepareICommandText;
}
return ExecuteCommandText(out executeResult);
}
return ExecuteTableDirect(behavior, out executeResult);
}
// dbindings handle can't be freed until the output parameters
// have been filled in which occurs after the last rowset is released
// dbbindings.FreeDataHandle occurs in Cloe
private int ExecuteCommandText(out object executeResult)
{
int retcode;
tagDBPARAMS? dbParams = null;
RowBinding? rowbinding = null;
Bindings? bindings = ParameterBindings;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (null != bindings)
{ // parameters may be suppressed
rowbinding = bindings.RowBinding();
rowbinding!.DangerousAddRef(ref mustRelease);
// bindings can't be released until after last rowset is released
// that is when output parameters are populated
// initialize the input parameters to the input databuffer
bindings.ApplyInputParameters();
dbParams = new tagDBPARAMS();
dbParams.pData = rowbinding.DangerousGetDataPtr();
dbParams.cParamSets = 1;
dbParams.hAccessor = rowbinding.DangerousGetAccessorHandle();
}
if ((0 == (CommandBehavior.SingleResult & this.commandBehavior)) && _connection!.SupportMultipleResults())
{
retcode = ExecuteCommandTextForMultpleResults(dbParams!, out executeResult);
}
else if (0 == (CommandBehavior.SingleRow & this.commandBehavior) || !_executeQuery)
{
retcode = ExecuteCommandTextForSingleResult(dbParams!, out executeResult);
}
else
{
retcode = ExecuteCommandTextForSingleRow(dbParams!, out executeResult);
}
}
finally
{
if (mustRelease)
{
rowbinding!.DangerousRelease();
}
}
return retcode;
}
private int ExecuteCommandTextForMultpleResults(tagDBPARAMS dbParams, out object executeResult)
{
Debug.Assert(0 == (CommandBehavior.SingleRow & this.commandBehavior), "SingleRow implies SingleResult");
OleDbHResult hr;
hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult);
if (OleDbHResult.E_NOINTERFACE != hr)
{
ExecuteCommandTextErrorHandling(hr);
return ODB.ExecutedIMultipleResults;
}
SafeNativeMethods.Wrapper.ClearErrorInfo();
return ExecuteCommandTextForSingleResult(dbParams, out executeResult);
}
private int ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, out object executeResult)
{
OleDbHResult hr;
// (Microsoft.Jet.OLEDB.4.0 returns 0 for recordsAffected instead of -1)
if (_executeQuery)
{
hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult);
}
else
{
hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult);
}
ExecuteCommandTextErrorHandling(hr);
return ODB.ExecutedIRowset;
}
private int ExecuteCommandTextForSingleRow(tagDBPARAMS dbParams, out object executeResult)
{
Debug.Assert(_executeQuery, "ExecuteNonQuery should always use ExecuteCommandTextForSingleResult");
if (_connection!.SupportIRow(this))
{
OleDbHResult hr;
hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult);
if (OleDbHResult.DB_E_NOTFOUND == hr)
{
SafeNativeMethods.Wrapper.ClearErrorInfo();
return ODB.ExecutedIRow;
}
else if (OleDbHResult.E_NOINTERFACE != hr)
{
ExecuteCommandTextErrorHandling(hr);
return ODB.ExecutedIRow;
}
}
SafeNativeMethods.Wrapper.ClearErrorInfo();
return ExecuteCommandTextForSingleResult(dbParams, out executeResult);
}
private void ExecuteCommandTextErrorHandling(OleDbHResult hr)
{
Exception? e = OleDbConnection.ProcessResults(hr, _connection);
if (null != e)
{
e = ExecuteCommandTextSpecialErrorHandling(hr, e);
throw e;
}
}
private Exception ExecuteCommandTextSpecialErrorHandling(OleDbHResult hr, Exception e)
{
if (((OleDbHResult.DB_E_ERRORSOCCURRED == hr) || (OleDbHResult.DB_E_BADBINDINFO == hr)) && (null != _dbBindings))
{
//
// this code exist to try for a better user error message by post-morten detection
// of invalid parameter types being passed to a provider that doesn't understand
// the user specified parameter OleDbType
Debug.Assert(null != e, "missing inner exception");
StringBuilder builder = new StringBuilder();
ParameterBindings!.ParameterStatus(builder);
e = ODB.CommandParameterStatus(builder.ToString(), e);
}
return e;
}
public override int ExecuteNonQuery()
{
_executeQuery = false;
ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteNonQuery);
return ADP.IntPtrToInt32(_recordsAffected);
}
public override object? ExecuteScalar()
{
object? value = null;
_executeQuery = true;
using (OleDbDataReader reader = ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteScalar)!)
{
if (reader.Read() && (0 < reader.FieldCount))
{
value = reader.GetValue(0);
}
}
return value;
}
private int ExecuteTableDirect(CommandBehavior behavior, out object? executeResult)
{
this.commandBehavior = behavior;
executeResult = null;
OleDbHResult hr = OleDbHResult.S_OK;
StringMemHandle? sptr = null;
bool mustReleaseStringHandle = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
sptr = new StringMemHandle(ExpandCommandText());
sptr.DangerousAddRef(ref mustReleaseStringHandle);
if (mustReleaseStringHandle)
{
tagDBID tableID = new tagDBID();
tableID.uGuid = Guid.Empty;
tableID.eKind = ODB.DBKIND_NAME;
tableID.ulPropid = sptr.DangerousGetHandle();
using (IOpenRowsetWrapper iopenRowset = _connection!.IOpenRowset())
{
using (DBPropSet? propSet = CommandPropertySets())
{
if (null != propSet)
{
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
propSet.DangerousAddRef(ref mustRelease);
hr = iopenRowset.Value.OpenRowset(IntPtr.Zero, tableID, IntPtr.Zero, ref ODB.IID_IRowset, propSet.PropertySetCount, propSet.DangerousGetHandle(), out executeResult);
}
finally
{
if (mustRelease)