forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlDataReader.cs
More file actions
2005 lines (1764 loc) · 76.6 KB
/
NpgsqlDataReader.cs
File metadata and controls
2005 lines (1764 loc) · 76.6 KB
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
#region License
// The PostgreSQL License
//
// Copyright (C) 2015 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AsyncRewriter;
using Npgsql.BackendMessages;
using Npgsql.TypeHandlers;
using Npgsql.TypeHandlers.NumericHandlers;
using Npgsql.Logging;
using NpgsqlTypes;
namespace Npgsql
{
/// <summary>
/// Reads a forward-only stream of rows from a data source.
/// </summary>
public partial class NpgsqlDataReader : DbDataReader
{
internal NpgsqlCommand Command { get; private set; }
readonly NpgsqlConnector _connector;
readonly NpgsqlConnection _connection;
readonly CommandBehavior _behavior;
ReaderState State { get; set; }
/// <summary>
/// Holds the list of statements being executed by this reader.
/// </summary>
readonly List<NpgsqlStatement> _statements;
/// <summary>
/// The index of the current query resultset we're processing (within a multiquery)
/// </summary>
int _statementIndex;
/// <summary>
/// The RowDescription message for the current resultset being processed
/// </summary>
RowDescriptionMessage _rowDescription;
DataRowMessage _row;
uint? _recordsAffected;
/// <summary>
/// Indicates that at least one row has been read across all result sets
/// </summary>
bool _readOneRow;
/// <summary>
/// Whether the current result set has rows
/// </summary>
bool? _hasRows;
/// <summary>
/// If HasRows was called before any rows were read, it was forced to read messages. A pending
/// message may be stored here for processing in the next Read() or NextResult().
/// </summary>
IBackendMessage _pendingMessage;
#if !DNXCORE50
/// <summary>
/// If <see cref="GetSchemaTable"/> has been called, its results are cached here.
/// </summary>
DataTable _cachedSchemaTable;
#endif
/// <summary>
/// Is raised whenever Close() is called.
/// </summary>
public event EventHandler ReaderClosed;
/// <summary>
/// In non-sequential mode, contains the cached values already read from the current row
/// </summary>
readonly RowCache _rowCache;
// static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
internal bool IsSequential { get { return (_behavior & CommandBehavior.SequentialAccess) != 0; } }
internal bool IsCaching { get { return !IsSequential; } }
internal bool IsSchemaOnly { get { return (_behavior & CommandBehavior.SchemaOnly) != 0; } }
internal NpgsqlDataReader(NpgsqlCommand command, CommandBehavior behavior, List<NpgsqlStatement> statements)
{
Command = command;
_connection = command.Connection;
_connector = _connection.Connector;
_behavior = behavior;
State = IsSchemaOnly ? ReaderState.BetweenResults : ReaderState.InResult;
if (IsCaching) {
_rowCache = new RowCache();
}
_statements = statements;
}
[RewriteAsync]
internal void Init()
{
_rowDescription = _statements[0].Description;
if (_rowDescription == null)
{
// The first query has not result set, seek forward to the first query that does (if any)
if (!NextResult())
{
// No resultsets at all
return;
}
}
if (Command.Parameters.Any(p => p.IsOutputDirection))
{
PopulateOutputParameters();
}
}
#region Read
/// <summary>
/// Advances the reader to the next record in a result set.
/// </summary>
/// <returns><b>true</b> if there are more rows; otherwise <b>false</b>.</returns>
/// <remarks>
/// The default position of a data reader is before the first record. Therefore, you must call Read to begin accessing data.
/// </remarks>
public override bool Read()
{
return ReadInternal();
}
/// <summary>
/// This is the asynchronous version of <see cref="Read"/> The cancellation token is currently ignored.
/// </summary>
/// <param name="cancellationToken">Ignored for now.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public override async Task<bool> ReadAsync(CancellationToken cancellationToken)
{
return await ReadInternalAsync(cancellationToken).ConfigureAwait(false);
}
[RewriteAsync]
bool ReadInternal()
{
if (_row != null) {
_row.Consume();
_row = null;
}
switch (State)
{
case ReaderState.InResult:
break;
case ReaderState.BetweenResults:
case ReaderState.Consumed:
case ReaderState.Closed:
return false;
default:
throw new ArgumentOutOfRangeException();
}
try
{
if ((_behavior & CommandBehavior.SingleRow) != 0 && _readOneRow)
{
// TODO: See optimization proposal in #410
Consume();
return false;
}
while (true)
{
var msg = ReadMessage();
switch (ProcessMessage(msg))
{
case ReadResult.RowRead:
return true;
case ReadResult.RowNotRead:
return false;
case ReadResult.ReadAgain:
continue;
default:
throw new ArgumentOutOfRangeException();
}
}
}
catch (NpgsqlException)
{
State = ReaderState.Consumed;
throw;
}
}
ReadResult ProcessMessage(IBackendMessage msg)
{
Contract.Requires(msg != null);
switch (msg.Code)
{
case BackendMessageCode.DataRow:
Contract.Assert(_rowDescription != null);
_connector.State = ConnectorState.Fetching;
_row = (DataRowMessage)msg;
Contract.Assume(_rowDescription.NumFields == _row.NumColumns);
if (IsCaching) { _rowCache.Clear(); }
_readOneRow = true;
_hasRows = true;
return ReadResult.RowRead;
case BackendMessageCode.CompletedResponse:
var completed = (CommandCompleteMessage) msg;
switch (completed.StatementType)
{
case StatementType.Update:
case StatementType.Insert:
case StatementType.Delete:
case StatementType.Copy:
if (!_recordsAffected.HasValue) {
_recordsAffected = 0;
}
_recordsAffected += completed.Rows;
break;
}
_statements[_statementIndex].StatementType = completed.StatementType;
_statements[_statementIndex].Rows = completed.Rows;
_statements[_statementIndex].OID = completed.OID;
goto case BackendMessageCode.EmptyQueryResponse;
case BackendMessageCode.EmptyQueryResponse:
State = ReaderState.BetweenResults;
return ReadResult.RowNotRead;
case BackendMessageCode.ReadyForQuery:
State = ReaderState.Consumed;
return ReadResult.RowNotRead;
case BackendMessageCode.BindComplete:
case BackendMessageCode.CloseComplete:
return ReadResult.ReadAgain;
default:
throw new Exception("Received unexpected backend message of type " + msg.Code);
}
}
#endregion
#region NextResult
/// <summary>
/// Advances the reader to the next result when reading the results of a batch of statements.
/// </summary>
/// <returns></returns>
public override sealed bool NextResult()
{
return IsSchemaOnly ? NextResultSchemaOnly() : NextResultInternal();
}
/// <summary>
/// This is the asynchronous version of NextResult.
/// The <paramref name="cancellationToken"/> parameter is currently ignored.
/// </summary>
/// <param name="cancellationToken">Currently ignored.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public override async sealed Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
return IsSchemaOnly ? NextResultSchemaOnly() : await NextResultInternalAsync(cancellationToken).ConfigureAwait(false);
}
[RewriteAsync]
bool NextResultInternal()
{
Contract.Requires(!IsSchemaOnly);
// Contract.Ensures(Command.CommandType != CommandType.StoredProcedure || Contract.Result<bool>() == false);
try
{
// If we're in the middle of a resultset, consume it
switch (State)
{
case ReaderState.InResult:
if (_row != null) {
_row.Consume();
_row = null;
}
// TODO: Duplication with SingleResult handling above
var completedMsg = SkipUntil(BackendMessageCode.CompletedResponse, BackendMessageCode.EmptyQueryResponse);
ProcessMessage(completedMsg);
break;
case ReaderState.BetweenResults:
break;
case ReaderState.Consumed:
case ReaderState.Closed:
return false;
default:
throw new ArgumentOutOfRangeException();
}
Contract.Assert(State == ReaderState.BetweenResults);
_hasRows = null;
#if !DNXCORE50
_cachedSchemaTable = null;
#endif
if ((_behavior & CommandBehavior.SingleResult) != 0)
{
if (State == ReaderState.BetweenResults) {
Consume();
}
return false;
}
// We are now at the end of the previous result set. Read up to the next result set, if any.
for (_statementIndex++; _statementIndex < _statements.Count; _statementIndex++)
{
_rowDescription = _statements[_statementIndex].Description;
if (_rowDescription != null)
{
State = ReaderState.InResult;
// Found a resultset
return true;
}
// Next query has no resultset, read and process its completion message and move on to the next
var completedMsg = SkipUntil(BackendMessageCode.CompletedResponse, BackendMessageCode.EmptyQueryResponse);
ProcessMessage(completedMsg);
}
// There are no more queries, we're done. Read to the RFQ.
ProcessMessage(SkipUntil(BackendMessageCode.ReadyForQuery));
_rowDescription = null;
return false;
}
catch (NpgsqlException)
{
State = ReaderState.Consumed;
throw;
}
}
/// <summary>
/// Note that in SchemaOnly mode there are no resultsets, and we read nothing from the backend (all
/// RowDescriptions have already been processed and are available)
/// </summary>
bool NextResultSchemaOnly()
{
Contract.Requires(IsSchemaOnly);
for (_statementIndex++; _statementIndex < _statements.Count; _statementIndex++)
{
_rowDescription = _statements[_statementIndex].Description;
if (_rowDescription != null)
{
// Found a resultset
return true;
}
}
return false;
}
#endregion
[RewriteAsync]
IBackendMessage ReadMessage()
{
if (_pendingMessage != null) {
var msg = _pendingMessage;
_pendingMessage = null;
return msg;
}
return _connector.ReadSingleMessage(IsSequential ? DataRowLoadingMode.Sequential : DataRowLoadingMode.NonSequential);
}
[RewriteAsync]
IBackendMessage SkipUntil(BackendMessageCode stopAt)
{
if (_pendingMessage != null)
{
if (_pendingMessage.Code == stopAt)
{
var msg = _pendingMessage;
_pendingMessage = null;
return msg;
}
_pendingMessage = null;
}
return _connector.SkipUntil(stopAt);
}
[RewriteAsync]
IBackendMessage SkipUntil(BackendMessageCode stopAt1, BackendMessageCode stopAt2)
{
if (_pendingMessage != null) {
if (_pendingMessage.Code == stopAt1 || _pendingMessage.Code == stopAt2) {
var msg = _pendingMessage;
_pendingMessage = null;
return msg;
}
_pendingMessage = null;
}
return _connector.SkipUntil(stopAt1, stopAt2);
}
/// <summary>
/// Gets a value indicating the depth of nesting for the current row. Always returns zero.
/// </summary>
public override Int32 Depth
{
get { return 0; }
}
/// <summary>
/// Gets a value indicating whether the data reader is closed.
/// </summary>
public override bool IsClosed
{
get { return State == ReaderState.Closed; }
}
/// <summary>
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
/// </summary>
public override int RecordsAffected
{
get { return _recordsAffected.HasValue ? (int)_recordsAffected.Value : -1; }
}
/// <summary>
/// Returns details about each statement that this reader will or has executed.
/// </summary>
/// <remarks>
/// Note that some fields (i.e. rows and oid) are only populated as the reader
/// traverses the result.
///
/// For commands with multiple queries, this exposes the number of rows affected on
/// a statement-by-statement basis, unlike <see cref="NpgsqlDataReader.RecordsAffected"/>
/// which exposes an aggregation across all statements.
/// </remarks>
public IReadOnlyList<NpgsqlStatement> Statements { get { return _statements.AsReadOnly(); } }
/// <summary>
/// Gets a value that indicates whether this DbDataReader contains one or more rows.
/// </summary>
public override bool HasRows
{
get
{
if (_hasRows.HasValue) {
return _hasRows.Value;
}
if (_statementIndex >= _statements.Count) {
return false;
}
while (true)
{
var msg = _connector.ReadSingleMessage(IsSequential ? DataRowLoadingMode.Sequential : DataRowLoadingMode.NonSequential);
switch (msg.Code)
{
case BackendMessageCode.BindComplete:
case BackendMessageCode.RowDescription:
ProcessMessage(msg);
continue;
case BackendMessageCode.DataRow:
_pendingMessage = msg;
_hasRows = true;
return true;
case BackendMessageCode.CompletedResponse:
case BackendMessageCode.EmptyQueryResponse:
_pendingMessage = msg;
_hasRows = false;
return false;
case BackendMessageCode.CloseComplete:
_hasRows = false;
return false;
default:
throw new ArgumentOutOfRangeException("Got unexpected message type: " + msg.Code);
}
}
}
}
/// <summary>
/// Indicates whether the reader is currently positioned on a row, i.e. whether reading a
/// column is possible.
/// This property is different from <see cref="HasRows"/> in that <see cref="HasRows"/> will
/// return true even if attempting to read a column will fail, e.g. before <see cref="Read"/>
/// has been called
/// </summary>
public bool IsOnRow { get { return _row != null; } }
/// <summary>
/// Gets the name of the column, given the zero-based column ordinal.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The name of the specified column.</returns>
public override string GetName(int ordinal)
{
CheckResultSet();
CheckOrdinal(ordinal);
Contract.EndContractBlock();
return _rowDescription[ordinal].Name;
}
/// <summary>
/// Gets the number of columns in the current row.
/// </summary>
public override int FieldCount
{
get
{
// Note MSDN docs that seem to say we should case -1 in this case:
// http://msdn.microsoft.com/en-us/library/system.data.idatarecord.fieldcount(v=vs.110).aspx
// But SqlClient returns 0
return _rowDescription == null ? 0 : _rowDescription.NumFields;
}
}
#region Cleanup / Dispose
/// <summary>
/// Consumes all result sets for this reader, leaving the connector ready for sending and processing further
/// queries
/// </summary>
[RewriteAsync]
void Consume()
{
if (IsSchemaOnly)
{
State = ReaderState.Consumed;
return;
}
if (_row != null)
{
_row.Consume();
_row = null;
}
// Skip over the other result sets, processing only CommandCompleted for RecordsAffected
while (true)
{
var msg = SkipUntil(BackendMessageCode.CompletedResponse, BackendMessageCode.ReadyForQuery);
switch (msg.Code)
{
case BackendMessageCode.CompletedResponse:
ProcessMessage(msg);
continue;
case BackendMessageCode.ReadyForQuery:
ProcessMessage(msg);
return;
default:
throw new Exception("Unexpected message of type " + msg.Code);
}
}
}
/// <summary>
/// Releases the resources used by the <see cref="NpgsqlDataReader">NpgsqlDataReader</see>.
/// </summary>
protected override void Dispose(bool disposing)
{
Close();
}
/// <summary>
/// Closes the <see cref="NpgsqlDataReader"/> object.
/// </summary>
#if DNXCORE50
public void Close()
#else
public override void Close()
#endif
{
if (State == ReaderState.Closed) { return; }
switch (_connector.State)
{
case ConnectorState.Broken:
case ConnectorState.Closed:
// This may have happen because an I/O error while reading a value, or some non-safe
// exception thrown from a type handler. Or if the connection was closed while the reader
// was still open
State = ReaderState.Closed;
Command.State = CommandState.Idle;
if (ReaderClosed != null) {
ReaderClosed(this, EventArgs.Empty);
}
return;
}
if (State != ReaderState.Consumed) {
Consume();
}
Cleanup();
}
internal void Cleanup()
{
State = ReaderState.Closed;
Command.State = CommandState.Idle;
_connector.CurrentReader = null;
_connector.EndUserAction();
if ((_behavior & CommandBehavior.CloseConnection) != 0)
{
_connection.Close();
}
if (ReaderClosed != null)
{
ReaderClosed(this, EventArgs.Empty);
ReaderClosed = null;
}
}
#endregion
/// <summary>
/// Returns the current row, or throws an exception if a row isn't available
/// </summary>
private DataRowMessage Row
{
get
{
if (_row == null) {
throw new InvalidOperationException("Invalid attempt to read when no data is present.");
}
return _row;
}
}
#region Simple value getters
/// <summary>
/// Gets the value of the specified column as a Boolean.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override bool GetBoolean(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumnWithoutCache<bool>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a byte.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override byte GetByte(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumnWithoutCache<byte>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a single character.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override char GetChar(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumnWithoutCache<char>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a 16-bit signed integer.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override short GetInt16(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<short>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a 32-bit signed integer.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override int GetInt32(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<int>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a 64-bit signed integer.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override long GetInt64(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<long>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a <see cref="DateTime"/> object.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override DateTime GetDateTime(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<DateTime>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as an instance of <see cref="string"/>.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override string GetString(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<string>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a <see cref="decimal"/> object.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override decimal GetDecimal(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<decimal>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a double-precision floating point number.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override double GetDouble(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<double>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a single-precision floating point number.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override float GetFloat(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<float>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a globally-unique identifier (GUID).
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override Guid GetGuid(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<Guid>(ordinal);
}
/// <summary>
/// Populates an array of objects with the column values of the current row.
/// </summary>
/// <param name="values">An array of Object into which to copy the attribute columns.</param>
/// <returns>The number of instances of <see cref="object"/> in the array.</returns>
public override int GetValues(object[] values)
{
#region Contracts
if (values == null)
throw new ArgumentNullException("values");
CheckRow();
Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= values.Length);
#endregion
var count = Math.Min(FieldCount, values.Length);
for (var i = 0; i < count; i++) {
values[i] = GetValue(i);
}
return count;
}
/// <summary>
/// Gets the value of the specified column as an instance of <see cref="object"/>.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public override object this[int ordinal]
{
get
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return GetValue(ordinal);
}
}
#endregion
#region Provider-specific type getters
/// <summary>
/// Gets the value of the specified column as an <see cref="NpgsqlDate"/>,
/// Npgsql's provider-specific type for dates.
/// </summary>
/// <remarks>
/// PostgreSQL's date type represents dates from 4713 BC to 5874897 AD, while .NET's DateTime
/// only supports years from 1 to 1999. If you require years outside this range use this accessor.
/// The standard <see cref="GetProviderSpecificValue"/> method will also return this type, but has
/// the disadvantage of boxing the value.
/// See http://www.postgresql.org/docs/current/static/datatype-datetime.html
/// </remarks>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public NpgsqlDate GetDate(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<NpgsqlDate>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as a TimeSpan,
/// </summary>
/// <remarks>
/// PostgreSQL's interval type has has a resolution of 1 microsecond and ranges from
/// -178000000 to 178000000 years, while .NET's TimeSpan has a resolution of 100 nanoseconds
/// and ranges from roughly -29247 to 29247 years.
/// See http://www.postgresql.org/docs/current/static/datatype-datetime.html
/// </remarks>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public TimeSpan GetTimeSpan(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<TimeSpan>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as an <see cref="NpgsqlTimeSpan"/>,
/// Npgsql's provider-specific type for time spans.
/// </summary>
/// <remarks>
/// PostgreSQL's interval type has has a resolution of 1 microsecond and ranges from
/// -178000000 to 178000000 years, while .NET's TimeSpan has a resolution of 100 nanoseconds
/// and ranges from roughly -29247 to 29247 years. If you require values from outside TimeSpan's
/// range use this accessor.
/// The standard ADO.NET <see cref="GetProviderSpecificValue"/> method will also return this
/// type, but has the disadvantage of boxing the value.
/// See http://www.postgresql.org/docs/current/static/datatype-datetime.html
/// </remarks>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public NpgsqlTimeSpan GetInterval(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<NpgsqlTimeSpan>(ordinal);
}
/// <summary>
/// Gets the value of the specified column as an <see cref="NpgsqlDateTime"/>,
/// Npgsql's provider-specific type for date/time timestamps. Note that this type covers
/// both PostgreSQL's "timestamp with time zone" and "timestamp without time zone" types,
/// which differ only in how they are converted upon input/output.
/// </summary>
/// <remarks>
/// PostgreSQL's timestamp type represents dates from 4713 BC to 5874897 AD, while .NET's DateTime
/// only supports years from 1 to 1999. If you require years outside this range use this accessor.
/// The standard <see cref="GetProviderSpecificValue"/> method will also return this type, but has
/// the disadvantage of boxing the value.
/// See http://www.postgresql.org/docs/current/static/datatype-datetime.html
/// </remarks>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The value of the specified column.</returns>
public NpgsqlDateTime GetTimeStamp(int ordinal)
{
CheckRowAndOrdinal(ordinal);
Contract.EndContractBlock();
return ReadColumn<NpgsqlDateTime>(ordinal);
}
#endregion
#region Special binary getters
/// <summary>
/// Reads a stream of bytes from the specified column, starting at location indicated by dataOffset, into the buffer, starting at the location indicated by bufferOffset.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <param name="dataOffset">The index within the row from which to begin the read operation.</param>
/// <param name="buffer">The buffer into which to copy the data.</param>
/// <param name="bufferOffset">The index with the buffer to which the data will be copied.</param>
/// <param name="length">The maximum number of characters to read.</param>
/// <returns>The actual number of bytes read.</returns>
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
#region Contracts
CheckRowAndOrdinal(ordinal);
if (dataOffset < 0 || dataOffset > int.MaxValue)
throw new ArgumentOutOfRangeException("dataOffset", dataOffset, String.Format("dataOffset must be between {0} and {1}", 0, int.MaxValue));
if (buffer != null && (bufferOffset < 0 || bufferOffset >= buffer.Length))
throw new IndexOutOfRangeException(String.Format("bufferOffset must be between {0} and {1}", 0, (buffer.Length - 1)));
if (buffer != null && (length < 0 || length > buffer.Length - bufferOffset))
throw new IndexOutOfRangeException(String.Format("length must be between {0} and {1}", 0, buffer.Length - bufferOffset));
Contract.Ensures(Contract.Result<long>() >= 0);
#endregion
var fieldDescription = _rowDescription[ordinal];
var handler = fieldDescription.Handler as ByteaHandler;
if (handler == null) {
throw new InvalidCastException("GetBytes() not supported for type " + fieldDescription.Name);
}
var row = Row;
row.SeekToColumn(ordinal);
row.CheckNotNull();
return handler.GetBytes(row, (int)dataOffset, buffer, bufferOffset, length, fieldDescription);
}
/// <summary>
/// Retrieves data as a <see cref="Stream"/>.
/// </summary>
/// <param name="ordinal">The zero-based column ordinal.</param>
/// <returns>The returned object.</returns>
#if NET40