-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
OleDbDataReader.cs
2595 lines (2293 loc) · 96.3 KB
/
OleDbDataReader.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.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Data.OleDb
{
public sealed class OleDbDataReader : DbDataReader
{
private readonly CommandBehavior _commandBehavior;
// object model interaction
private OleDbConnection? _connection;
private OleDbCommand? _command;
// DataReader owns the parameter bindings until CloseDataReader
// this allows OleDbCommand.Dispose to not require OleDbDataReader.Dispose
private Bindings? _parameterBindings;
// OLEDB interfaces
private UnsafeNativeMethods.IMultipleResults? _imultipleResults;
private UnsafeNativeMethods.IRowset? _irowset;
private UnsafeNativeMethods.IRow? _irow;
private ChapterHandle _chapterHandle = ChapterHandle.DB_NULL_HCHAPTER;
private readonly int _depth;
private bool _isClosed, _isRead, _hasRows, _hasRowsReadCheck;
private long _sequentialBytesRead;
private int _sequentialOrdinal;
private Bindings?[]? _bindings; // _metadata contains the ColumnBinding
// do we need to jump to the next accessor
private int _nextAccessorForRetrieval;
// must increment the counter before retrieving value so that
// if an exception is thrown, user can continue without erroring again
private int _nextValueForRetrieval;
// record affected for the current dataset
private IntPtr _recordsAffected = ADP.RecordsUnaffected;
private bool _useIColumnsRowset;
private bool _sequentialAccess;
private bool _singleRow;
// cached information for Reading (rowhandles/status)
private nint _rowHandleFetchCount; // (>1 fails against jet)
private RowHandleBuffer? _rowHandleNativeBuffer;
private nint _rowFetchedCount;
private int _currentRow;
private DataTable? _dbSchemaTable;
private int _visibleFieldCount;
private MetaData[]? _metadata;
private FieldNameLookup? _fieldNameLookup;
// ctor for an ICommandText, IMultipleResults, IRowset, IRow
// ctor for an ADODB.Recordset, ADODB.Record or Hierarchial resultset
internal OleDbDataReader(OleDbConnection? connection, OleDbCommand? command, int depth, CommandBehavior commandBehavior)
{
_connection = connection;
_command = command;
_commandBehavior = commandBehavior;
if ((null != command) && (0 == _depth))
{
_parameterBindings = command.TakeBindingOwnerShip();
}
_depth = depth;
}
private void Initialize()
{
CommandBehavior behavior = _commandBehavior;
_useIColumnsRowset = (0 != (CommandBehavior.KeyInfo & behavior));
_sequentialAccess = (0 != (CommandBehavior.SequentialAccess & behavior));
if (0 == _depth)
{
_singleRow = (0 != (CommandBehavior.SingleRow & behavior));
}
}
internal void InitializeIMultipleResults(object? result)
{
Initialize();
_imultipleResults = (UnsafeNativeMethods.IMultipleResults?)result; // maybe null if no results
}
internal void InitializeIRowset(object? result, ChapterHandle chapterHandle, IntPtr recordsAffected)
{
// if from ADODB, connection will be null
if ((null == _connection) || (ChapterHandle.DB_NULL_HCHAPTER != chapterHandle))
{
_rowHandleFetchCount = 1;
}
Initialize();
_recordsAffected = recordsAffected;
_irowset = (UnsafeNativeMethods.IRowset?)result; // maybe null if no results
_chapterHandle = chapterHandle;
}
internal void InitializeIRow(object? result, IntPtr recordsAffected)
{
Initialize();
Debug.Assert(_singleRow, "SingleRow not already set");
_singleRow = true;
_recordsAffected = recordsAffected;
_irow = (UnsafeNativeMethods.IRow?)result; // maybe null if no results
_hasRows = (null != _irow);
}
internal OleDbCommand? Command
{
get
{
return _command;
}
}
public override int Depth
{
get
{
if (IsClosed)
{
throw ADP.DataReaderClosed("Depth");
}
return _depth;
}
}
public override int FieldCount
{
get
{
if (IsClosed)
{
throw ADP.DataReaderClosed("FieldCount");
}
MetaData[]? metadata = MetaData;
return ((null != metadata) ? metadata.Length : 0);
}
}
public override bool HasRows
{
get
{
if (IsClosed)
{
throw ADP.DataReaderClosed("HasRows");
}
return _hasRows;
}
}
public override bool IsClosed
{
get
{ // if we have a rowset or multiplieresults, we may have more to read
Debug.Assert((_singleRow && !_isClosed && !_isRead && (null == _irow) && (null == _irowset)) ||
_isClosed == ((null == _irow) && (null == _irowset) && (null == _imultipleResults)
&& (null == _dbSchemaTable) && (null == _connection) && (null == _command)),
"IsClosed mismatch");
return _isClosed;
}
}
private MetaData[]? MetaData
{
get { return _metadata; }
}
public override int RecordsAffected
{
get
{
return ADP.IntPtrToInt32(_recordsAffected);
}
}
/*
internal long RecordsAffectedLong {
get {
return (long)_recordsAffected;
}
}*/
public override object this[int index]
{
get
{
return GetValue(index);
}
}
public override object this[string name]
{
get
{
int ordinal = GetOrdinal(name);
return GetValue(ordinal);
}
}
// grouping the native OLE DB casts togther by required interfaces and optional interfaces
// want these to be methods, not properties otherwise they appear in VS7 managed debugger which attempts to evaluate them
// required interface, safe cast
private UnsafeNativeMethods.IAccessor IAccessor()
{
return (UnsafeNativeMethods.IAccessor)IRowset();
}
// required interface, safe cast
private UnsafeNativeMethods.IRowsetInfo IRowsetInfo()
{
return (UnsafeNativeMethods.IRowsetInfo)IRowset();
}
private UnsafeNativeMethods.IRowset IRowset()
{
UnsafeNativeMethods.IRowset? irowset = _irowset;
if (null == irowset)
{
Debug.Assert(false, "object is disposed");
throw new ObjectDisposedException(GetType().Name);
}
return irowset;
}
private UnsafeNativeMethods.IRow IRow()
{
UnsafeNativeMethods.IRow? irow = _irow;
if (null == irow)
{
Debug.Assert(false, "object is disposed");
throw new ObjectDisposedException(GetType().Name);
}
return irow;
}
public override DataTable? GetSchemaTable()
{
DataTable? schemaTable = _dbSchemaTable;
if (null == schemaTable)
{
MetaData[]? metadata = MetaData;
if ((null != metadata) && (0 < metadata.Length))
{
if ((0 < metadata.Length) && _useIColumnsRowset && (null != _connection))
{
AppendSchemaInfo();
}
schemaTable = BuildSchemaTable(metadata);
}
else if (IsClosed)
{
throw ADP.DataReaderClosed("GetSchemaTable");
}
//GetSchemaTable() is defined to return null after NextResult returns false
//throw ADP.DataReaderNoData();
}
return schemaTable;
}
internal void BuildMetaInfo()
{
Debug.Assert(null == _metadata, "BuildMetaInfo: already built, by _metadata");
if (null != _irowset)
{
if (_useIColumnsRowset)
{
BuildSchemaTableRowset(_irowset);
}
else
{
BuildSchemaTableInfo(_irowset, false, false);
}
if (null != _metadata && 0 < _metadata.Length)
{
// @devnote: because we want to use the DBACCESSOR_OPTIMIZED bit,
// we are required to create the accessor before fetching any rows
CreateAccessors(true);
Debug.Assert(null != _bindings, "unexpected dbBindings");
}
}
else if (null != _irow)
{
BuildSchemaTableInfo(_irow, false, false);
if (null != _metadata && 0 < _metadata.Length)
{
CreateBindingsFromMetaData(true);
}
}
if (null == _metadata)
{
_hasRows = false;
_visibleFieldCount = 0;
_metadata = Array.Empty<MetaData>();
}
}
private DataTable BuildSchemaTable(MetaData[] metadata)
{
Debug.Assert(null == _dbSchemaTable, "BuildSchemaTable: schema table already exists");
Debug.Assert(null != metadata, "BuildSchemaTable: no _metadata");
DataTable schemaTable = new DataTable("SchemaTable");
schemaTable.Locale = CultureInfo.InvariantCulture;
schemaTable.MinimumCapacity = metadata.Length;
DataColumn name = new DataColumn("ColumnName", typeof(string));
DataColumn ordinal = new DataColumn("ColumnOrdinal", typeof(int));
DataColumn size = new DataColumn("ColumnSize", typeof(int));
DataColumn precision = new DataColumn("NumericPrecision", typeof(short));
DataColumn scale = new DataColumn("NumericScale", typeof(short));
DataColumn dataType = new DataColumn(SchemaTableColumn.DataType, typeof(Type));
DataColumn providerType = new DataColumn("ProviderType", typeof(int));
DataColumn isLong = new DataColumn("IsLong", typeof(bool));
DataColumn allowDBNull = new DataColumn("AllowDBNull", typeof(bool));
DataColumn isReadOnly = new DataColumn("IsReadOnly", typeof(bool));
DataColumn isRowVersion = new DataColumn("IsRowVersion", typeof(bool));
DataColumn isUnique = new DataColumn("IsUnique", typeof(bool));
DataColumn isKey = new DataColumn("IsKey", typeof(bool));
DataColumn isAutoIncrement = new DataColumn("IsAutoIncrement", typeof(bool));
DataColumn isHidden = new DataColumn("IsHidden", typeof(bool));
DataColumn baseSchemaName = new DataColumn("BaseSchemaName", typeof(string));
DataColumn baseCatalogName = new DataColumn("BaseCatalogName", typeof(string));
DataColumn baseTableName = new DataColumn("BaseTableName", typeof(string));
DataColumn baseColumnName = new DataColumn("BaseColumnName", typeof(string));
ordinal.DefaultValue = 0;
isLong.DefaultValue = false;
DataColumnCollection columns = schemaTable.Columns;
columns.Add(name);
columns.Add(ordinal);
columns.Add(size);
columns.Add(precision);
columns.Add(scale);
columns.Add(dataType);
columns.Add(providerType);
columns.Add(isLong);
columns.Add(allowDBNull);
columns.Add(isReadOnly);
columns.Add(isRowVersion);
columns.Add(isUnique);
columns.Add(isKey);
columns.Add(isAutoIncrement);
if (_visibleFieldCount < metadata.Length)
{
columns.Add(isHidden);
}
columns.Add(baseSchemaName);
columns.Add(baseCatalogName);
columns.Add(baseTableName);
columns.Add(baseColumnName);
for (int i = 0; i < metadata.Length; ++i)
{
MetaData info = metadata[i];
DataRow newRow = schemaTable.NewRow();
newRow[name] = info.columnName;
newRow[ordinal] = i;
// @devnote: size is count of characters for WSTR or STR, bytes otherwise
// @devnote: see OLEDB spec under IColumnsInfo::GetColumnInfo
newRow[size] = ((info.type.enumOleDbType != OleDbType.BSTR) ? info.size : -1);
newRow[precision] = info.precision;
newRow[scale] = info.scale;
newRow[dataType] = info.type.dataType;
newRow[providerType] = info.type.enumOleDbType;
newRow[isLong] = OleDbDataReader.IsLong(info.flags);
if (info.isKeyColumn)
{
newRow[allowDBNull] = OleDbDataReader.AllowDBNull(info.flags);
}
else
{
newRow[allowDBNull] = OleDbDataReader.AllowDBNullMaybeNull(info.flags);
}
newRow[isReadOnly] = OleDbDataReader.IsReadOnly(info.flags);
newRow[isRowVersion] = OleDbDataReader.IsRowVersion(info.flags);
newRow[isUnique] = info.isUnique;
newRow[isKey] = info.isKeyColumn;
newRow[isAutoIncrement] = info.isAutoIncrement;
if (_visibleFieldCount < metadata.Length)
{
newRow[isHidden] = info.isHidden;
}
if (null != info.baseSchemaName)
{
newRow[baseSchemaName] = info.baseSchemaName;
}
if (null != info.baseCatalogName)
{
newRow[baseCatalogName] = info.baseCatalogName;
}
if (null != info.baseTableName)
{
newRow[baseTableName] = info.baseTableName;
}
if (null != info.baseColumnName)
{
newRow[baseColumnName] = info.baseColumnName;
}
schemaTable.Rows.Add(newRow);
newRow.AcceptChanges();
}
// mark all columns as readonly
int count = columns.Count;
for (int i = 0; i < count; i++)
{
columns[i].ReadOnly = true;
}
_dbSchemaTable = schemaTable;
return schemaTable;
}
private void BuildSchemaTableInfo(object handle, bool filterITypeInfo, bool filterChapters)
{
Debug.Assert(null == _dbSchemaTable, "non-null SchemaTable");
Debug.Assert(null == _metadata, "non-null metadata");
Debug.Assert(null != handle, "unexpected null rowset");
UnsafeNativeMethods.IColumnsInfo? icolumnsInfo = (handle as UnsafeNativeMethods.IColumnsInfo);
if (null == icolumnsInfo)
{
_dbSchemaTable = null;
#if DEBUG
if (handle is UnsafeNativeMethods.IRow)
{
Debug.Assert(false, "bad IRow - IColumnsInfo not available");
}
else
{
Debug.Assert(handle is UnsafeNativeMethods.IRowset, "bad IRowset - IColumnsInfo not available");
}
#endif
return;
}
OleDbHResult hr;
nint columnCount = 0; // column count
IntPtr columnInfos = IntPtr.Zero; // ptr to byvalue tagDBCOLUMNINFO[]
using (DualCoTaskMem safehandle = new DualCoTaskMem(icolumnsInfo, out columnCount, out columnInfos, out hr))
{
if (hr < 0)
{
ProcessResults(hr);
}
if (0 < checked((int)columnCount))
{
BuildSchemaTableInfoTable((int)columnCount, columnInfos, filterITypeInfo, filterChapters);
}
}
}
// create DataColumns
// add DataColumns to DataTable
// add schema information to DataTable
// generate unique column names
private void BuildSchemaTableInfoTable(int columnCount, IntPtr columnInfos, bool filterITypeInfo, bool filterChapters)
{
Debug.Assert(0 < columnCount, "BuildSchemaTableInfoTable - no column");
int rowCount = 0;
MetaData[] metainfo = new MetaData[columnCount];
// for every column, build an equivalent to tagDBCOLUMNINFO
tagDBCOLUMNINFO dbColumnInfo = new tagDBCOLUMNINFO();
for (int i = 0, offset = 0; i < columnCount; ++i, offset += ODB.SizeOf_tagDBCOLUMNINFO)
{
Marshal.PtrToStructure(ADP.IntPtrOffset(columnInfos, offset), dbColumnInfo);
if (0 >= dbColumnInfo.iOrdinal)
{
continue;
}
if (OleDbDataReader.DoColumnDropFilter(dbColumnInfo.dwFlags))
{
continue;
}
if (null == dbColumnInfo.pwszName)
{
dbColumnInfo.pwszName = "";
}
if (filterITypeInfo && (ODB.DBCOLUMN_TYPEINFO == dbColumnInfo.pwszName))
{
continue;
}
if (filterChapters && (NativeDBType.HCHAPTER == dbColumnInfo.wType))
{
continue; // filter chapters in IRowset from IDBSchemaRowset for DumpToTable
}
bool islong = OleDbDataReader.IsLong(dbColumnInfo.dwFlags);
bool isfixed = OleDbDataReader.IsFixed(dbColumnInfo.dwFlags);
NativeDBType dbType = NativeDBType.FromDBType(dbColumnInfo.wType, islong, isfixed);
MetaData info = new MetaData();
info.columnName = dbColumnInfo.pwszName;
info.type = dbType;
info.ordinal = dbColumnInfo.iOrdinal;
nint maxsize = dbColumnInfo.ulColumnSize;
info.size = (((maxsize < 0) || (int.MaxValue < maxsize)) ? int.MaxValue : (int)maxsize);
info.flags = dbColumnInfo.dwFlags;
info.precision = dbColumnInfo.bPrecision;
info.scale = dbColumnInfo.bScale;
info.kind = dbColumnInfo.columnid.eKind;
switch (dbColumnInfo.columnid.eKind)
{
case ODB.DBKIND_GUID_NAME:
case ODB.DBKIND_GUID_PROPID:
case ODB.DBKIND_GUID:
info.guid = dbColumnInfo.columnid.uGuid;
break;
default:
Debug.Assert(ODB.DBKIND_PGUID_NAME != dbColumnInfo.columnid.eKind, "OLE DB providers never return pGuid-style bindings.");
Debug.Assert(ODB.DBKIND_PGUID_PROPID != dbColumnInfo.columnid.eKind, "OLE DB providers never return pGuid-style bindings.");
info.guid = Guid.Empty;
break;
}
switch (dbColumnInfo.columnid.eKind)
{
case ODB.DBKIND_GUID_PROPID:
case ODB.DBKIND_PROPID:
info.propid = dbColumnInfo.columnid.ulPropid;
break;
case ODB.DBKIND_GUID_NAME:
case ODB.DBKIND_NAME:
if (IntPtr.Zero != dbColumnInfo.columnid.ulPropid)
{
info.idname = Marshal.PtrToStringUni(dbColumnInfo.columnid.ulPropid);
}
else
{
info.idname = null;
}
break;
default:
info.propid = IntPtr.Zero;
break;
}
metainfo[rowCount] = info;
#if DEBUG
if (AdapterSwitches.DataSchema.TraceVerbose)
{
Debug.WriteLine($"OleDbDataReader[{info.ordinal}, {dbColumnInfo.pwszName}]={dbType.enumOleDbType},{dbType.dataSourceType}, {dbType.wType}");
}
#endif
rowCount++;
}
if (rowCount < columnCount)
{ // shorten names array appropriately
MetaData[] tmpinfo = new MetaData[rowCount];
for (int i = 0; i < rowCount; ++i)
{
tmpinfo[i] = metainfo[i];
}
metainfo = tmpinfo;
}
_visibleFieldCount = rowCount;
_metadata = metainfo;
}
private void BuildSchemaTableRowset(object handle)
{
Debug.Assert(null == _dbSchemaTable, "BuildSchemaTableRowset - non-null SchemaTable");
Debug.Assert(null != handle, "BuildSchemaTableRowset(object) - unexpected null handle");
UnsafeNativeMethods.IColumnsRowset? icolumnsRowset = (handle as UnsafeNativeMethods.IColumnsRowset);
if (null != icolumnsRowset)
{
UnsafeNativeMethods.IRowset? rowset = null;
IntPtr cOptColumns;
OleDbHResult hr;
using (DualCoTaskMem prgOptColumns = new DualCoTaskMem(icolumnsRowset, out cOptColumns, out hr))
{
Debug.Assert((0 == hr) || prgOptColumns.IsInvalid, "GetAvailableCOlumns: unexpected return");
hr = icolumnsRowset.GetColumnsRowset(IntPtr.Zero, cOptColumns, prgOptColumns, in ODB.IID_IRowset, 0, IntPtr.Zero, out rowset);
}
Debug.Assert((0 <= hr) || (null == rowset), "if GetColumnsRowset failed, rowset should be null");
if (hr < 0)
{
ProcessResults(hr);
}
DumpToSchemaTable(rowset);
// release the rowset to avoid race condition between the GC and the user code causing
// "Connection is busy with results for another command" exception
if (null != rowset)
{
Marshal.ReleaseComObject(rowset);
}
}
else
{
_useIColumnsRowset = false;
BuildSchemaTableInfo(handle, false, false);
}
}
public override void Close()
{
OleDbConnection? con = _connection;
OleDbCommand? cmd = _command;
Bindings? bindings = _parameterBindings;
_connection = null!;
_command = null!;
_parameterBindings = null;
_isClosed = true;
DisposeOpenResults();
_hasRows = false;
if ((null != cmd) && cmd.canceling)
{
DisposeNativeMultipleResults();
if (null != bindings)
{
bindings.CloseFromConnection();
bindings = null;
}
}
else
{
UnsafeNativeMethods.IMultipleResults? multipleResults = _imultipleResults;
_imultipleResults = null;
if (null != multipleResults)
{
// if we don't have a cmd, same as a cancel (don't call NextResults) which is ADODB behavior
try
{
// tricky code path is an exception is thrown
// causing connection to do a ResetState and connection.Close
// resulting in OleDbCommand.CloseFromConnection
if ((null != cmd) && !cmd.canceling)
{
IntPtr affected = IntPtr.Zero;
OleDbException? nextResultsFailure = NextResults(multipleResults, null, cmd, out affected);
_recordsAffected = AddRecordsAffected(_recordsAffected, affected);
if (null != nextResultsFailure)
{
throw nextResultsFailure;
}
}
}
finally
{
if (null != multipleResults)
{
Marshal.ReleaseComObject(multipleResults);
}
}
}
}
if ((null != cmd) && (0 == _depth))
{
// return bindings back to the cmd after closure of root DataReader
cmd.CloseFromDataReader(bindings);
}
if (null != con)
{
con.RemoveWeakReference(this);
// if the DataReader is Finalized it will not close the connection
if (IsCommandBehavior(CommandBehavior.CloseConnection))
{
con.Close();
}
}
// release unmanaged objects
RowHandleBuffer? rowHandleNativeBuffer = _rowHandleNativeBuffer;
_rowHandleNativeBuffer = null;
rowHandleNativeBuffer?.Dispose();
}
internal void CloseReaderFromConnection(bool canceling)
{
// being called from the connection, we will have a command. that command
// may be Disposed, but it doesn't matter since another command can't execute
// until all DataReader are closed
if (null != _command)
{ // UNDONE: understand why this could be null, it shouldn't be but was
_command.canceling = canceling;
}
// called from the connection which will remove this from its ReferenceCollection
// we want the NextResult behavior, but no errors
_connection = null!;
Close();
}
private void DisposeManagedRowset()
{
//not cleared after last rowset
//_hasRows = false;
_isRead = false;
_hasRowsReadCheck = false;
_nextAccessorForRetrieval = 0;
_nextValueForRetrieval = 0;
Bindings?[]? bindings = _bindings;
_bindings = null;
if (null != bindings)
{
for (int i = 0; i < bindings.Length; ++i)
{
if (bindings[i] is Bindings binding)
{
binding.Dispose();
}
}
}
_currentRow = 0;
_rowFetchedCount = 0;
_dbSchemaTable = null;
_visibleFieldCount = 0;
_metadata = null;
_fieldNameLookup = null;
}
private void DisposeNativeMultipleResults()
{
UnsafeNativeMethods.IMultipleResults? imultipleResults = _imultipleResults;
_imultipleResults = null;
if (null != imultipleResults)
{
Marshal.ReleaseComObject(imultipleResults);
}
}
private void DisposeNativeRowset()
{
UnsafeNativeMethods.IRowset? irowset = _irowset;
_irowset = null;
ChapterHandle chapter = _chapterHandle;
_chapterHandle = ChapterHandle.DB_NULL_HCHAPTER;
if (ChapterHandle.DB_NULL_HCHAPTER != chapter)
{
chapter.Dispose();
}
if (null != irowset)
{
Marshal.ReleaseComObject(irowset);
}
}
private void DisposeNativeRow()
{
UnsafeNativeMethods.IRow? irow = _irow;
_irow = null;
if (null != irow)
{
Marshal.ReleaseComObject(irow);
}
}
private void DisposeOpenResults()
{
DisposeManagedRowset();
DisposeNativeRow();
DisposeNativeRowset();
}
public override bool GetBoolean(int ordinal)
{
ColumnBinding binding = GetColumnBinding(ordinal);
return binding.ValueBoolean();
}
public override byte GetByte(int ordinal)
{
ColumnBinding binding = GetColumnBinding(ordinal);
return binding.ValueByte();
}
private ColumnBinding DoSequentialCheck(int ordinal, long dataIndex, string method)
{
ColumnBinding binding = GetColumnBinding(ordinal);
if (dataIndex > int.MaxValue)
{
throw ADP.InvalidSourceBufferIndex(0, dataIndex, "dataIndex");
}
if (_sequentialOrdinal != ordinal)
{
_sequentialOrdinal = ordinal;
_sequentialBytesRead = 0;
}
else if (_sequentialAccess && (_sequentialBytesRead < dataIndex))
{
throw ADP.NonSeqByteAccess(dataIndex, _sequentialBytesRead, method);
}
// getting the value doesn't really belong, but it's common to both
// callers GetBytes and GetChars so we might as well have the code here
return binding;
}
public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int bufferIndex, int length)
{
ColumnBinding binding = DoSequentialCheck(ordinal, dataIndex, ADP.GetBytes);
byte[] value = binding.ValueByteArray();
if (null == buffer)
{
return value.Length;
}
int srcIndex = (int)dataIndex;
int byteCount = Math.Min(value.Length - srcIndex, length);
if (srcIndex < 0)
{
throw ADP.InvalidSourceBufferIndex(value.Length, srcIndex, "dataIndex");
}
else if ((bufferIndex < 0) || (bufferIndex >= buffer.Length))
{
throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
}
if (0 < byteCount)
{
// @usernote: user may encounter ArgumentException from Buffer.BlockCopy
Buffer.BlockCopy(value, srcIndex, buffer, bufferIndex, byteCount);
_sequentialBytesRead = srcIndex + byteCount;
}
else if (length < 0)
{
throw ADP.InvalidDataLength(length);
}
else
{
byteCount = 0;
}
return byteCount;
}
public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int bufferIndex, int length)
{
ColumnBinding binding = DoSequentialCheck(ordinal, dataIndex, ADP.GetChars);
string value = binding.ValueString();
if (null == buffer)
{
return value.Length;
}
int srcIndex = (int)dataIndex;
int charCount = Math.Min(value.Length - srcIndex, length);
if (srcIndex < 0)
{
throw ADP.InvalidSourceBufferIndex(value.Length, srcIndex, "dataIndex");
}
else if ((bufferIndex < 0) || (bufferIndex >= buffer.Length))
{
throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
}
if (0 < charCount)
{
// @usernote: user may encounter ArgumentException from String.CopyTo
value.CopyTo(srcIndex, buffer, bufferIndex, charCount);
_sequentialBytesRead = srcIndex + charCount;
}
else if (length < 0)
{
throw ADP.InvalidDataLength(length);
}
else
{
charCount = 0;
}
return charCount;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override char GetChar(int ordinal)
{
throw ADP.NotSupported();
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public new OleDbDataReader GetData(int ordinal)
{
ColumnBinding binding = GetColumnBinding(ordinal);
return binding.ValueChapter();
}
protected override DbDataReader GetDbDataReader(int ordinal)
{
return GetData(ordinal);
}
internal OleDbDataReader ResetChapter(int bindingIndex, int index, RowBinding rowbinding, int valueOffset)
{
return GetDataForReader(_metadata![bindingIndex + index].ordinal, rowbinding, valueOffset);
}
private OleDbDataReader GetDataForReader(IntPtr ordinal, RowBinding rowbinding, int valueOffset)
{
UnsafeNativeMethods.IRowsetInfo rowsetInfo = IRowsetInfo();
UnsafeNativeMethods.IRowset? result;
OleDbHResult hr;
hr = rowsetInfo.GetReferencedRowset((IntPtr)ordinal, in ODB.IID_IRowset, out result);
ProcessResults(hr);
// Per docs result can be null only when hr is DB_E_NOTAREFERENCECOLUMN which in most of the cases will cause the exception in ProcessResult
OleDbDataReader? reader = null;
if (result != null)
{
// only when the first datareader is closed will the connection close
ChapterHandle chapterHandle = ChapterHandle.CreateChapterHandle(result, rowbinding, valueOffset);
reader = new OleDbDataReader(_connection, _command, 1 + Depth, _commandBehavior & ~CommandBehavior.CloseConnection);
reader.InitializeIRowset(result, chapterHandle, ADP.RecordsUnaffected);
reader.BuildMetaInfo();
reader.HasRowsRead();
// connection tracks all readers to prevent cmd from executing
// until all readers (including nested) are closed
_connection?.AddWeakReference(reader, OleDbReferenceCollection.DataReaderTag);
}
return reader!;
}
public override string GetDataTypeName(int index)
{
if (null != _metadata)
{
return _metadata[index].type.dataSourceType;
}
throw ADP.DataReaderNoData();
}
public override DateTime GetDateTime(int ordinal)
{
ColumnBinding binding = GetColumnBinding(ordinal);
return binding.ValueDateTime();
}
public override decimal GetDecimal(int ordinal)
{
ColumnBinding binding = GetColumnBinding(ordinal);
return binding.ValueDecimal();
}
public override double GetDouble(int ordinal)