forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNDataReader.cs
685 lines (593 loc) · 16 KB
/
NDataReader.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using NHibernate.Util;
namespace NHibernate.Driver
{
/// <summary>
/// Some Data Providers (ie - SqlClient) do not support Multiple Active Result Sets (MARS).
/// NHibernate relies on being able to create MARS to read Components and entities inside
/// of Collections.
/// </summary>
/// <remarks>
/// This is a completely off-line DataReader - the underlying DbDataReader that was used to create
/// this has been closed and no connections to the Db exists.
/// </remarks>
public partial class NDataReader : DbDataReader
{
private NResult[] results;
private bool isClosed;
// a DataReader is positioned before the first valid record
private int currentRowIndex = -1;
// a DataReader is positioned on the first Result
private int currentResultIndex = 0;
private byte[] cachedByteArray;
private char[] cachedCharArray;
private int cachedColIndex = -1;
protected NDataReader() { }
/// <summary>
/// Creates a NDataReader from a <see cref="DbDataReader" />
/// </summary>
/// <param name="reader">The <see cref="DbDataReader" /> to get the records from the Database.</param>
/// <param name="isMidstream"><see langword="true" /> if we are loading the <see cref="DbDataReader" /> in the middle of reading it.</param>
/// <remarks>
/// NHibernate attempts to not have to read the contents of an <see cref="DbDataReader"/> into memory until it absolutely
/// has to. What that means is that it might have processed some records from the <see cref="DbDataReader"/> and will
/// pick up the <see cref="DbDataReader"/> midstream so that the underlying <see cref="DbDataReader"/> can be closed
/// so a new one can be opened.
/// </remarks>
public static NDataReader Create(DbDataReader reader, bool isMidstream)
{
var dataReader = new NDataReader();
var resultList = new List<NResult>(2);
try
{
// if we are in midstream of processing a DataReader then we are already
// positioned on the first row (index=0)
if (isMidstream)
{
dataReader.currentRowIndex = 0;
}
// there will be atleast one result
resultList.Add(NResult.Create(reader, isMidstream));
while (reader.NextResult())
{
// the second, third, nth result is not processed midstream
resultList.Add(NResult.Create(reader, false));
}
dataReader.results = resultList.ToArray();
}
catch (Exception e)
{
throw new ADOException("There was a problem converting an DbDataReader to NDataReader", e);
}
finally
{
reader.Close();
}
return dataReader;
}
/// <summary>
/// Sets the values that can be cached back to null and sets the
/// index of the cached column to -1
/// </summary>
private void ClearCache()
{
// clear out the caches because we have a new result with diff values.
cachedByteArray = null;
cachedCharArray = null;
cachedColIndex = -1;
}
private NResult GetCurrentResult()
{
return results[currentResultIndex];
}
private object GetValue(string name)
{
return GetCurrentResult().GetValue(currentRowIndex, name);
}
/// <summary></summary>
public override int RecordsAffected
{
get { throw new NotImplementedException("NDataReader should only be used for SELECT statements!"); }
}
public override bool HasRows
{
get { return results.LongLength > 0; }
}
/// <summary></summary>
public override bool IsClosed
{
get { return isClosed; }
}
/// <summary></summary>
public override bool NextResult()
{
currentResultIndex++;
currentRowIndex = -1;
if (currentResultIndex >= results.Length)
{
// move it back to the last result
currentResultIndex--;
return false;
}
ClearCache();
return true;
}
/// <summary></summary>
public override void Close()
{
isClosed = true;
}
/// <summary></summary>
public override bool Read()
{
currentRowIndex++;
if (currentRowIndex >= results[currentResultIndex].RowCount)
{
// reset it back to the last row
currentRowIndex--;
return false;
}
ClearCache();
return true;
}
public override Task<bool> ReadAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Read());
}
public override Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
return Task.FromResult(NextResult());
}
public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken)
{
return Task.FromResult(IsDBNull(ordinal));
}
/// <summary></summary>
public override int Depth
{
get { return currentResultIndex; }
}
/// <summary></summary>
public override DataTable GetSchemaTable()
{
return GetCurrentResult().GetSchemaTable();
}
protected override void Dispose(bool disposing)
{
isClosed = true;
ClearCache();
results = null;
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override int GetInt32(int i)
{
return Convert.ToInt32(GetValue(i));
}
/// <summary></summary>
public override object this[string name]
{
get { return GetValue(name); }
}
/// <summary></summary>
public override object this[int i]
{
get { return GetValue(i); }
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override object GetValue(int i)
{
return GetCurrentResult().GetValue(currentRowIndex, i);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override bool IsDBNull(int i)
{
return GetValue(i).Equals(DBNull.Value);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <param name="fieldOffset"></param>
/// <param name="buffer"></param>
/// <param name="bufferOffset"></param>
/// <param name="length"></param>
/// <returns></returns>
public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferOffset, int length)
{
if (cachedByteArray == null || cachedColIndex != i)
{
cachedColIndex = i;
cachedByteArray = (byte[]) GetValue(i);
}
long remainingLength = cachedByteArray.Length - fieldOffset;
if (buffer == null)
{
return remainingLength;
}
if (remainingLength < length)
{
length = (int) remainingLength;
}
Array.Copy(cachedByteArray, fieldOffset, buffer, bufferOffset, length);
return length;
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override byte GetByte(int i)
{
return Convert.ToByte(GetValue(i));
}
public override IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override System.Type GetFieldType(int i)
{
return GetCurrentResult().GetFieldType(i);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override decimal GetDecimal(int i)
{
return Convert.ToDecimal(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public override int GetValues(object[] values)
{
return GetCurrentResult().GetValues(currentRowIndex, values);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override string GetName(int i)
{
return GetCurrentResult().GetName(i);
}
/// <summary></summary>
public override int FieldCount
{
get { return GetCurrentResult().GetFieldCount(); }
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override long GetInt64(int i)
{
return Convert.ToInt64(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override double GetDouble(int i)
{
return Convert.ToDouble(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override bool GetBoolean(int i)
{
return Convert.ToBoolean(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override Guid GetGuid(int i)
{
return (Guid) GetValue(i);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override DateTime GetDateTime(int i)
{
return Convert.ToDateTime(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public override int GetOrdinal(string name)
{
return GetCurrentResult().GetOrdinal(name);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override string GetDataTypeName(int i)
{
return GetCurrentResult().GetDataTypeName(i);
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override float GetFloat(int i)
{
return Convert.ToSingle(GetValue(i));
}
protected override DbDataReader GetDbDataReader(int ordinal)
{
throw new NotImplementedException("GetDbDataReader(int) has not been implemented.");
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <param name="fieldOffset"></param>
/// <param name="buffer"></param>
/// <param name="bufferOffset"></param>
/// <param name="length"></param>
/// <returns></returns>
public override long GetChars(int i, long fieldOffset, char[] buffer, int bufferOffset, int length)
{
if (cachedCharArray == null || cachedColIndex != i)
{
cachedColIndex = i;
cachedCharArray = (char[]) GetValue(i);
}
long remainingLength = cachedCharArray.Length - fieldOffset;
if (remainingLength < length)
{
length = (int) remainingLength;
}
Array.Copy(cachedCharArray, fieldOffset, buffer, bufferOffset, length);
return length;
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override string GetString(int i)
{
return Convert.ToString(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override char GetChar(int i)
{
return Convert.ToChar(GetValue(i));
}
/// <summary>
///
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public override short GetInt16(int i)
{
return Convert.ToInt16(GetValue(i));
}
/// <summary>
/// Stores a Result from a DataReader in memory.
/// </summary>
private partial class NResult
{
// [row][column]
private object[][] records;
private int colCount = 0;
private DataTable schemaTable;
private NotSupportedException schemaTableNotSupportedException;
// key = field name
// index = field index
private readonly Dictionary<string, int> fieldNameToIndex = new Dictionary<string, int>();
private readonly List<string> fieldIndexToName = new List<string>();
private readonly List<System.Type> fieldTypes = new List<System.Type>();
private readonly List<string> fieldDataTypeNames = new List<string>();
private NResult() { }
/// <summary>
/// Initializes a new instance of the NResult class.
/// </summary>
/// <param name="reader">The DbDataReader to populate the Result with.</param>
/// <param name="isMidstream">
/// <see langword="true" /> if the <see cref="DbDataReader"/> is already positioned on the record
/// to start reading from.
/// </param>
internal static NResult Create(DbDataReader reader, bool isMidstream)
{
var schemaTable = SafeGetSchemaTable(reader, out var exception);
var result = new NResult
{
schemaTable = schemaTable,
schemaTableNotSupportedException = exception
};
List<object[]> recordsList = new List<object[]>();
int rowIndex = 0;
// if we are in the middle of processing the reader then don't bother
// to move to the next record - just use the current one.
while (isMidstream || reader.Read())
{
if (rowIndex == 0)
{
for (int i = 0; i < reader.FieldCount; i++)
{
string fieldName = reader.GetName(i);
result.fieldNameToIndex[fieldName] = i;
result.fieldIndexToName.Add(fieldName);
result.fieldTypes.Add(reader.GetFieldType(i));
result.fieldDataTypeNames.Add(reader.GetDataTypeName(i));
}
result.colCount = reader.FieldCount;
}
rowIndex++;
object[] colValues = new object[reader.FieldCount];
reader.GetValues(colValues);
recordsList.Add(colValues);
// we can go back to reading a reader like normal and don't need
// to consider where we started from.
isMidstream = false;
}
result.records = recordsList.ToArray();
return result;
}
private static DataTable SafeGetSchemaTable(IDataReader reader, out NotSupportedException exception)
{
exception = null;
try
{
return reader.GetSchemaTable();
}
catch (NotSupportedException e)
{
ReflectHelper.PreserveStackTrace(e);
exception = e;
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="colIndex"></param>
/// <returns></returns>
public string GetDataTypeName(int colIndex)
{
return fieldDataTypeNames[colIndex];
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public int GetFieldCount()
{
return fieldIndexToName.Count;
}
/// <summary>
///
/// </summary>
/// <param name="colIndex"></param>
/// <returns></returns>
public System.Type GetFieldType(int colIndex)
{
return fieldTypes[colIndex];
}
/// <summary>
///
/// </summary>
/// <param name="colIndex"></param>
/// <returns></returns>
public string GetName(int colIndex)
{
return fieldIndexToName[colIndex];
}
/// <summary></summary>
public DataTable GetSchemaTable()
{
if (schemaTableNotSupportedException != null)
throw schemaTableNotSupportedException;
return schemaTable;
}
/// <summary>
///
/// </summary>
/// <param name="colName"></param>
/// <returns></returns>
public int GetOrdinal(string colName)
{
// Martijn Boland, 20041106: perform a case-sensitive search first and if that returns
// null, perform a case-insensitive search (as being described in the IDataRecord
// interface, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataIDataRecordClassItemTopic1.asp.
// This is necessary for databases that don't preserve the case of field names when
// they are created without quotes (e.g. DB2, PostgreSQL).
int value;
if (fieldNameToIndex.TryGetValue(colName, out value))
return value;
foreach (KeyValuePair<string, int> pair in fieldNameToIndex)
{
if (string.Equals(pair.Key, colName, StringComparison.InvariantCultureIgnoreCase))
{
return pair.Value;
}
}
throw new IndexOutOfRangeException(String.Format("No column with the specified name was found: {0}.", colName));
}
/// <summary>
///
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="colIndex"></param>
/// <returns></returns>
public object GetValue(int rowIndex, int colIndex)
{
return records[rowIndex][colIndex];
}
/// <summary>
///
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="colName"></param>
/// <returns></returns>
public object GetValue(int rowIndex, string colName)
{
return GetValue(rowIndex, GetOrdinal(colName));
}
/// <summary>
///
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="values"></param>
/// <returns></returns>
public int GetValues(int rowIndex, object[] values)
{
Array.Copy(records[rowIndex], 0, values, 0, colCount);
return colCount;
}
/// <summary></summary>
public int RowCount
{
get { return records.Length; }
}
}
}
}