-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlDataReader.cs
More file actions
2192 lines (1893 loc) · 90 KB
/
NpgsqlDataReader.cs
File metadata and controls
2192 lines (1893 loc) · 90 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
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Npgsql.BackendMessages;
using Npgsql.Internal;
using Npgsql.Internal.Converters;
using Npgsql.PostgresTypes;
using Npgsql.Schema;
using NpgsqlTypes;
using static Npgsql.Util.Statics;
namespace Npgsql;
/// <summary>
/// Reads a forward-only stream of rows from a data source.
/// </summary>
#pragma warning disable CA1010
public sealed class NpgsqlDataReader : DbDataReader, IDbColumnSchemaGenerator
#pragma warning restore CA1010
{
static readonly Task<bool> TrueTask = Task.FromResult(true);
static readonly Task<bool> FalseTask = Task.FromResult(false);
internal NpgsqlCommand Command { get; private set; } = default!;
internal NpgsqlConnector Connector { get; }
NpgsqlConnection? _connection;
/// <summary>
/// The behavior of the command with which this reader was executed.
/// </summary>
CommandBehavior _behavior;
/// <summary>
/// The task for writing this command's messages. Awaited on reader cleanup.
/// </summary>
Task? _sendTask;
internal ReaderState State = ReaderState.Disposed;
internal NpgsqlReadBuffer Buffer = default!;
PgReader PgReader => Buffer.PgReader;
/// <summary>
/// Holds the list of statements being executed by this reader.
/// </summary>
List<NpgsqlBatchCommand> _statements = default!;
/// <summary>
/// The index of the current query resultset we're processing (within a multiquery)
/// </summary>
internal int StatementIndex { get; private set; }
/// <summary>
/// Records, for each column, its starting offset and length in the current row.
/// Used only in non-sequential mode.
/// </summary>
readonly List<(int Offset, int Length)> _columns = [];
int _columnsStartPos;
/// <summary>
/// The index of the column that we're on, i.e. that has already been parsed,
/// is memory and can be retrieved. Initialized to -1, which means we're on the column
/// count (which comes before the first column).
/// </summary>
int _column;
/// <summary>
/// The position in the buffer at which the current data row message ends.
/// Used only when the row is consumed non-sequentially.
/// </summary>
int _dataMsgEnd;
/// <summary>
/// Determines, if we can consume the row non-sequentially.
/// Mostly useful for a sequential mode, when the row is already in the buffer.
/// Should always be true for the non-sequential mode.
/// </summary>
bool _isRowBuffered;
/// <summary>
/// Gets or sets whether the current row is fully buffered in memory.
/// When <see langword="false"/>, async reads will go through the real async converter path rather than the sync shortcut.
/// </summary>
/// <remarks>Settable for testing purposes.</remarks>
internal bool IsRowBuffered
{
get => _isRowBuffered;
set => _isRowBuffered = value;
}
/// <summary>
/// The RowDescription message for the current resultset being processed
/// </summary>
internal RowDescriptionMessage? RowDescription;
int ColumnCount => RowDescription!.Count;
/// <summary>
/// Stores the last converter info resolved by column, to speed up repeated reading.
/// </summary>
ColumnInfo[]? ColumnInfoCache { get; set; }
ulong? _recordsAffected;
/// <summary>
/// Whether the current result set has rows
/// </summary>
bool _hasRows;
/// <summary>
/// Is raised whenever Close() is called.
/// </summary>
public event EventHandler? ReaderClosed;
bool _isSchemaOnly;
bool _isSequential;
internal NpgsqlNestedDataReader? CachedFreeNestedDataReader;
long _startTimestamp;
readonly ILogger _commandLogger;
internal NpgsqlDataReader(NpgsqlConnector connector)
{
Connector = connector;
_commandLogger = connector.CommandLogger;
}
internal void Init(
NpgsqlCommand command,
CommandBehavior behavior,
List<NpgsqlBatchCommand> statements,
long startTimestamp = 0,
Task? sendTask = null)
{
Debug.Assert(ColumnInfoCache is null);
Command = command;
_connection = command.InternalConnection;
_behavior = behavior;
_isSchemaOnly = _behavior.HasFlag(CommandBehavior.SchemaOnly);
_isSequential = _behavior.HasFlag(CommandBehavior.SequentialAccess);
_statements = statements;
StatementIndex = -1;
_sendTask = sendTask;
State = ReaderState.BetweenResults;
_recordsAffected = null;
_startTimestamp = startTimestamp;
}
#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()
{
ThrowIfClosedOrDisposed();
return TryRead()?.Result ?? Read(false).GetAwaiter().GetResult();
}
/// <summary>
/// This is the asynchronous version of <see cref="Read()"/>
/// </summary>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>A task representing the asynchronous operation.</returns>
public override Task<bool> ReadAsync(CancellationToken cancellationToken)
{
ThrowIfClosedOrDisposed();
return TryRead() ?? Read(async: true, cancellationToken);
}
// This is an optimized execution path that avoids calling any async methods for the (usual)
// case where the next row (or CommandComplete) is already in memory.
Task<bool>? TryRead()
{
switch (State)
{
case ReaderState.BeforeResult:
// First Read() after NextResult. Data row has already been processed.
State = ReaderState.InResult;
return TrueTask;
case ReaderState.InResult:
break;
default:
return FalseTask;
}
// We have a special case path for SingleRow.
if (_behavior.HasFlag(CommandBehavior.SingleRow) || !_isRowBuffered)
return null;
ConsumeBufferedRow();
const int headerSize = sizeof(byte) + sizeof(int);
var buffer = Buffer;
var readPosition = buffer.ReadPosition;
var bytesLeft = buffer.FilledBytes - readPosition;
if (bytesLeft < headerSize)
return null;
var messageCode = (BackendMessageCode)buffer.ReadByte();
var len = buffer.ReadInt32() - sizeof(int); // Transmitted length includes itself
var isDataRow = messageCode is BackendMessageCode.DataRow;
// sizeof(short) is for the number of columns
var sufficientBytes = isDataRow && _isSequential ? headerSize + sizeof(short) : headerSize + len;
if (bytesLeft < sufficientBytes
|| !isDataRow && (_statements[StatementIndex].AppendErrorBarrier ?? Command.EnableErrorBarriers)
// Could be an error, let main read handle it.
|| Connector.ParseResultSetMessage(buffer, messageCode, len) is not { } msg)
{
buffer.ReadPosition = readPosition;
return null;
}
ProcessMessage(msg);
return isDataRow ? TrueTask : FalseTask;
}
async Task<bool> Read(bool async, CancellationToken cancellationToken = default)
{
using var registration = Connector.StartNestedCancellableOperation(cancellationToken);
try
{
switch (State)
{
case ReaderState.BeforeResult:
// First Read() after NextResult. Data row has already been processed.
State = ReaderState.InResult;
return true;
case ReaderState.InResult:
await ConsumeRow(async).ConfigureAwait(false);
if (_behavior.HasFlag(CommandBehavior.SingleRow))
{
// TODO: See optimization proposal in #410
await Consume(async).ConfigureAwait(false);
return false;
}
break;
case ReaderState.BetweenResults:
case ReaderState.Consumed:
case ReaderState.Closed:
case ReaderState.Disposed:
return false;
default:
ThrowHelper.ThrowArgumentOutOfRangeException();
return false;
}
var msg = await ReadMessage(async).ConfigureAwait(false);
switch (msg.Code)
{
case BackendMessageCode.DataRow:
ProcessMessage(msg);
return true;
case BackendMessageCode.CommandComplete:
case BackendMessageCode.EmptyQueryResponse:
ProcessMessage(msg);
if (_statements[StatementIndex].AppendErrorBarrier ?? Command.EnableErrorBarriers)
Expect<ReadyForQueryMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
return false;
default:
throw Connector.UnexpectedMessageReceived(msg.Code);
}
}
catch
{
// Break may have progressed the reader already.
if (State is not ReaderState.Closed)
State = ReaderState.Consumed;
throw;
}
}
ValueTask<IBackendMessage> ReadMessage(bool async)
{
return _isSequential ? ReadMessageSequential(Connector, async) : Connector.ReadMessage(async);
static async ValueTask<IBackendMessage> ReadMessageSequential(NpgsqlConnector connector, bool async)
{
var msg = await connector.ReadMessage(async, DataRowLoadingMode.Sequential).ConfigureAwait(false);
if (msg.Code == BackendMessageCode.DataRow)
{
// Make sure that the datarow's column count is already buffered
await connector.ReadBuffer.Ensure(2, async).ConfigureAwait(false);
return msg;
}
return msg;
}
}
#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 bool NextResult()
{
ThrowIfClosedOrDisposed();
return (_isSchemaOnly ? NextResultSchemaOnly(false) : NextResult(false))
.GetAwaiter().GetResult();
}
/// <summary>
/// This is the asynchronous version of NextResult.
/// </summary>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>A task representing the asynchronous operation.</returns>
public override Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
ThrowIfClosedOrDisposed();
return _isSchemaOnly
? NextResultSchemaOnly(async: true, cancellationToken: cancellationToken)
: NextResult(async: true, cancellationToken: cancellationToken);
}
/// <summary>
/// Internal implementation of NextResult
/// </summary>
async Task<bool> NextResult(bool async, bool isConsuming = false, CancellationToken cancellationToken = default)
{
Debug.Assert(!_isSchemaOnly);
if (State is ReaderState.Consumed)
return false;
try
{
using var registration = isConsuming ? default : Connector.StartNestedCancellableOperation(cancellationToken);
// If we're in the middle of a resultset, consume it
if (State is ReaderState.BeforeResult or ReaderState.InResult)
await ConsumeResultSet(async).ConfigureAwait(false);
Debug.Assert(State is ReaderState.BetweenResults);
_hasRows = false;
var statements = _statements;
var statementIndex = StatementIndex;
if (statementIndex >= 0)
{
if (RowDescription is { } description && statements[statementIndex].IsPrepared && ColumnInfoCache is { } cache)
description.SetColumnInfoCache(new(cache, 0, ColumnCount));
if (statementIndex is 0 && _behavior.HasFlag(CommandBehavior.SingleResult) && !isConsuming)
{
await Consume(async).ConfigureAwait(false);
return false;
}
}
// We are now at the end of the previous result set. Read up to the next result set, if any.
// Non-prepared statements receive ParseComplete, BindComplete, DescriptionRow/NoData,
// prepared statements receive only BindComplete
for (statementIndex = ++StatementIndex; statementIndex < statements.Count; statementIndex = ++StatementIndex)
{
var statement = statements[statementIndex];
IBackendMessage msg;
if (statement.TryGetPrepared(out var preparedStatement))
{
Expect<BindCompleteMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
RowDescription = preparedStatement.Description;
}
else // Non-prepared/preparing flow
{
preparedStatement = statement.PreparedStatement;
if (preparedStatement != null)
{
Debug.Assert(!preparedStatement.IsPrepared);
if (preparedStatement.StatementBeingReplaced != null)
{
Expect<CloseCompletedMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
preparedStatement.StatementBeingReplaced.CompleteUnprepare();
preparedStatement.StatementBeingReplaced = null;
}
}
Expect<ParseCompleteMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
if (statement.IsPreparing)
{
preparedStatement!.State = PreparedState.Prepared;
Connector.PreparedStatementManager.NumPrepared++;
statement.IsPreparing = false;
}
Expect<BindCompleteMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
msg = await Connector.ReadMessage(async).ConfigureAwait(false);
RowDescription = statement.Description = msg.Code switch
{
BackendMessageCode.NoData => null,
// RowDescription messages are cached on the connector, but if we're auto-preparing, we need to
// clone our own copy which will last beyond the lifetime of this invocation.
BackendMessageCode.RowDescription => preparedStatement == null
? (RowDescriptionMessage)msg
: ((RowDescriptionMessage)msg).Clone(),
_ => throw Connector.UnexpectedMessageReceived(msg.Code)
};
}
if (RowDescription is not null)
{
if (ColumnInfoCache?.Length >= ColumnCount)
Array.Clear(ColumnInfoCache, 0, ColumnCount);
else
{
if (ColumnInfoCache is { } cache)
ArrayPool<ColumnInfo>.Shared.Return(cache, clearArray: true);
ColumnInfoCache = ArrayPool<ColumnInfo>.Shared.Rent(ColumnCount);
}
if (statement.IsPrepared)
RowDescription.LoadColumnInfoCache(Connector.SerializerOptions, ColumnInfoCache);
}
else
{
// Statement did not generate a resultset (e.g. INSERT)
// Read and process its completion message and move on to the next statement
// No need to read sequentially as it's not a DataRow
msg = await Connector.ReadMessage(async).ConfigureAwait(false);
switch (msg.Code)
{
case BackendMessageCode.CommandComplete:
case BackendMessageCode.EmptyQueryResponse:
break;
case BackendMessageCode.CopyInResponse:
throw Connector.Break(new NotSupportedException(
"COPY isn't supported in regular command execution - see https://www.npgsql.org/doc/copy.html for documentation on COPY with Npgsql. " +
"If you are trying to execute a SQL script created by pg_dump, pass the '--inserts' switch to disable generating COPY statements."));
case BackendMessageCode.CopyOutResponse:
throw Connector.Break(new NotSupportedException(
"COPY isn't supported in regular command execution - see https://www.npgsql.org/doc/copy.html for documentation on COPY with Npgsql."));
default:
throw Connector.UnexpectedMessageReceived(msg.Code);
}
ProcessMessage(msg);
if (statement.AppendErrorBarrier ?? Command.EnableErrorBarriers)
Expect<ReadyForQueryMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
continue;
}
if ((Command.WrappingBatch is not null || StatementIndex is 0) && Command.InternalBatchCommands[StatementIndex] is { HasOutputParameters: true } command)
{
// If output parameters are present and this is the first row of the resultset,
// we must always read it in non-sequential mode because it will be traversed twice (once
// here for the parameters, then as a regular row).
msg = await Connector.ReadMessage(async, dataRowLoadingMode: DataRowLoadingMode.NonSequential).ConfigureAwait(false);
ProcessMessage(msg);
if (msg.Code == BackendMessageCode.DataRow)
{
Debug.Assert(RowDescription != null);
Debug.Assert(State == ReaderState.BeforeResult);
try
{
// Temporarily set our state to InResult and non-sequential to allow us to read the values, and in any order.
var isSequential = _isSequential;
var currentPosition = Buffer.ReadPosition;
State = ReaderState.InResult;
_isSequential = false;
try
{
command.PopulateOutputParameters(this, _commandLogger);
// On success we want to revert any row and column state for the user to be able to read the same row again.
if (async)
await PgReader.CommitAsync().ConfigureAwait(false);
else
PgReader.Commit();
State = ReaderState.BeforeResult; // Set the state back
Buffer.ReadPosition = currentPosition; // Restore position
_column = -1;
}
finally
{
// To be on the safe side we always revert this CommandBehavior state change, including on failure.
_isSequential = isSequential;
}
}
catch (Exception e)
{
// TODO: ideally we should flow down to global exception filter and consume there
await Consume(async, firstException: e).ConfigureAwait(false);
throw;
}
}
}
else
{
msg = await ReadMessage(async).ConfigureAwait(false);
ProcessMessage(msg);
}
switch (msg.Code)
{
case BackendMessageCode.DataRow:
Connector.State = ConnectorState.Fetching;
return true;
case BackendMessageCode.CommandComplete:
if (statement.AppendErrorBarrier ?? Command.EnableErrorBarriers)
Expect<ReadyForQueryMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
return true;
default:
Connector.UnexpectedMessageReceived(msg.Code);
break;
}
}
// There are no more queries, we're done. Read the RFQ.
if (_statements.Count is 0 || !(_statements[^1].AppendErrorBarrier ?? Command.EnableErrorBarriers))
Expect<ReadyForQueryMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
State = ReaderState.Consumed;
RowDescription = null;
return false;
}
catch (Exception e)
{
if (e is PostgresException postgresException && StatementIndex >= 0 && StatementIndex < _statements.Count)
{
var statement = _statements[StatementIndex];
// Reference the triggering statement from the exception
if (Connector.Settings.IncludeFailedBatchedCommand)
postgresException.BatchCommand = statement;
// Prevent the command or batch from being recycled (by the connection) when it's disposed. This is important since
// the exception is very likely to escape the using statement of the command, and by that time some other user may
// already be using the recycled instance.
// TODO: we probably should do than even if it's not PostgresException (error from PopulateOutputParameters)
Command.IsCacheable = false;
// If the schema of a table changes after a statement is prepared on that table, PostgreSQL errors with
// 0A000: cached plan must not change result type. 0A000 seems like a non-specific code, but it's very unlikely the
// statement would successfully execute anyway, so invalidate the prepared statement.
if (postgresException.SqlState == PostgresErrorCodes.FeatureNotSupported &&
statement.PreparedStatement is { } preparedStatement)
{
preparedStatement.State = PreparedState.Invalidated;
Command.ResetPreparation();
}
}
// For the statement that errored, if it was being prepared we need to update our bookkeeping to put them back in unprepared
// state.
for (; StatementIndex < _statements.Count; StatementIndex++)
{
var statement = _statements[StatementIndex];
if (statement.IsPreparing)
{
statement.IsPreparing = false;
statement.PreparedStatement!.AbortPrepare();
}
// In normal, non-isolated batching, we've consumed the result set and are done.
// However, if the command has error barrier, we now have to consume results from the commands after it (unless it's the
// last one).
// Note that Consume calls NextResult (this method) recursively, the isConsuming flag tells us we're in this mode.
// TODO: We might as well call Consume on every command (even the last one) to make sure we do read every single message until RFQ
// in case we get an exception in the middle of NextResult
if ((statement.AppendErrorBarrier ?? Command.EnableErrorBarriers) && StatementIndex < _statements.Count - 1)
{
if (isConsuming)
throw;
switch (State)
{
case ReaderState.Consumed:
case ReaderState.Closed:
case ReaderState.Disposed:
// The exception may have caused the connector to break (e.g. I/O), and so the reader is already closed.
break;
default:
// We provide Consume with the first exception which we've just caught.
// If it encounters other exceptions while consuming the rest of the result set, it will raise an AggregateException,
// otherwise it will rethrow this first exception.
await Consume(async, firstException: e).ConfigureAwait(false);
break; // Never reached, Consume always throws above
}
}
}
// Break may have progressed the reader already.
if (State is not ReaderState.Closed)
State = ReaderState.Consumed;
throw;
}
async ValueTask ConsumeResultSet(bool async)
{
await ConsumeRow(async).ConfigureAwait(false);
while (true)
{
var completedMsg = await Connector.ReadMessage(async, DataRowLoadingMode.Skip).ConfigureAwait(false);
switch (completedMsg.Code)
{
case BackendMessageCode.CommandComplete:
case BackendMessageCode.EmptyQueryResponse:
ProcessMessage(completedMsg);
var statement = _statements[StatementIndex];
if (statement.IsPrepared && ColumnInfoCache is not null)
RowDescription!.SetColumnInfoCache(new(ColumnInfoCache, 0, ColumnCount));
if (statement.AppendErrorBarrier ?? Command.EnableErrorBarriers)
Expect<ReadyForQueryMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
break;
default:
// TODO if we hit an ErrorResponse here (PG doesn't do this *today*) we should probably throw.
continue;
}
break;
}
}
}
/// <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>
async Task<bool> NextResultSchemaOnly(bool async, bool isConsuming = false, CancellationToken cancellationToken = default)
{
Debug.Assert(_isSchemaOnly);
if (State is ReaderState.Consumed)
return false;
using var registration = isConsuming ? default : Connector.StartNestedCancellableOperation(cancellationToken);
try
{
for (StatementIndex++; StatementIndex < _statements.Count; StatementIndex++)
{
var statement = _statements[StatementIndex];
if (statement.TryGetPrepared(out var preparedStatement))
{
// Row descriptions have already been populated in the statement objects at the
// Prepare phase
RowDescription = preparedStatement.Description;
}
else
{
var pStatement = statement.PreparedStatement;
if (pStatement != null)
{
Debug.Assert(!pStatement.IsPrepared);
if (pStatement.StatementBeingReplaced != null)
{
Expect<CloseCompletedMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
pStatement.StatementBeingReplaced.CompleteUnprepare();
pStatement.StatementBeingReplaced = null;
}
}
Expect<ParseCompleteMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
if (statement.IsPreparing)
{
pStatement!.State = PreparedState.Prepared;
Connector.PreparedStatementManager.NumPrepared++;
statement.IsPreparing = false;
}
Expect<ParameterDescriptionMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
var msg = await Connector.ReadMessage(async).ConfigureAwait(false);
switch (msg.Code)
{
case BackendMessageCode.NoData:
RowDescription = _statements[StatementIndex].Description = null;
break;
case BackendMessageCode.RowDescription:
// We have a resultset
// RowDescription messages are cached on the connector, but if we're auto-preparing, we need to
// clone our own copy which will last beyond the lifetime of this invocation.
RowDescription = _statements[StatementIndex].Description = preparedStatement == null
? (RowDescriptionMessage)msg
: ((RowDescriptionMessage)msg).Clone();
Command.FixupRowDescription(RowDescription, StatementIndex == 0);
break;
default:
throw Connector.UnexpectedMessageReceived(msg.Code);
}
var forall = true;
for (var i = StatementIndex + 1; i < _statements.Count; i++)
if (!_statements[i].IsPrepared)
{
forall = false;
break;
}
// There are no more queries, we're done. Read to the RFQ.
if (forall)
Expect<ReadyForQueryMessage>(await Connector.ReadMessage(async).ConfigureAwait(false), Connector);
}
// Found a resultset
if (RowDescription is not null)
return true;
}
State = ReaderState.Consumed;
RowDescription = null;
return false;
}
catch (Exception e)
{
// Break may have progressed the reader already.
if (State is not ReaderState.Closed)
State = ReaderState.Consumed;
// Reference the triggering statement from the exception
if (e is PostgresException postgresException && StatementIndex >= 0 && StatementIndex < _statements.Count)
{
// Reference the triggering statement from the exception
if (Connector.Settings.IncludeFailedBatchedCommand)
postgresException.BatchCommand = _statements[StatementIndex];
// Prevent the command or batch from being recycled (by the connection) when it's disposed. This is important since
// the exception is very likely to escape the using statement of the command, and by that time some other user may
// already be using the recycled instance.
Command.IsCacheable = false;
}
// An error means all subsequent statements were skipped by PostgreSQL.
// If any of them were being prepared, we need to update our bookkeeping to put
// them back in unprepared state.
for (; StatementIndex < _statements.Count; StatementIndex++)
{
var statement = _statements[StatementIndex];
if (statement.IsPreparing)
{
statement.IsPreparing = false;
statement.PreparedStatement!.AbortPrepare();
}
}
throw;
}
}
#endregion
#region ProcessMessage
internal void ProcessMessage(IBackendMessage msg)
{
if (msg.Code is not BackendMessageCode.DataRow)
{
HandleUncommon(msg);
return;
}
var dataRow = (DataRowMessage)msg;
// The connector's buffer can actually change between DataRows:
// If a large DataRow exceeding the connector's current read buffer arrives, and we're
// reading in non-sequential mode, a new oversize buffer is allocated. We thus have to
// recapture the connector's buffer on each new DataRow.
// Note that this can happen even in sequential mode, if the row description message is big
// (see #2003)
if (!ReferenceEquals(Buffer, Connector.ReadBuffer))
Buffer = Connector.ReadBuffer;
// We assume that the row's number of columns is identical to the description's
var numColumns = Buffer.ReadInt16();
if (ColumnCount != numColumns)
ThrowHelper.ThrowArgumentException($"Row's number of columns ({numColumns}) differs from the row description's ({ColumnCount})");
var readPosition = Buffer.ReadPosition;
var msgRemainder = dataRow.Length - sizeof(short);
_dataMsgEnd = readPosition + msgRemainder;
_columnsStartPos = readPosition;
_isRowBuffered = msgRemainder <= Buffer.FilledBytes - readPosition;
Debug.Assert(_isRowBuffered || _isSequential);
_column = -1;
if (_columns.Count > 0)
_columns.Clear();
switch (State)
{
case ReaderState.BetweenResults:
_hasRows = true;
State = ReaderState.BeforeResult;
break;
case ReaderState.BeforeResult:
State = ReaderState.InResult;
break;
case ReaderState.InResult:
break;
default:
Connector.UnexpectedMessageReceived(BackendMessageCode.DataRow);
break;
}
[MethodImpl(MethodImplOptions.NoInlining)]
void HandleUncommon(IBackendMessage msg)
{
switch (msg.Code)
{
case BackendMessageCode.CommandComplete:
var completed = (CommandCompleteMessage)msg;
switch (completed.StatementType)
{
case StatementType.Update:
case StatementType.Insert:
case StatementType.Delete:
case StatementType.Copy:
case StatementType.Move:
case StatementType.Merge:
_recordsAffected ??= 0;
_recordsAffected += completed.Rows;
break;
}
_statements[StatementIndex].ApplyCommandComplete(completed);
State = ReaderState.BetweenResults;
break;
case BackendMessageCode.EmptyQueryResponse:
State = ReaderState.BetweenResults;
break;
default:
Connector.UnexpectedMessageReceived(msg.Code);
break;
}
}
}
#endregion
/// <summary>
/// Gets a value indicating the depth of nesting for the current row. Always returns zero.
/// </summary>
public override int Depth => 0;
/// <summary>
/// Gets a value indicating whether the data reader is closed.
/// </summary>
public override bool IsClosed => State is ReaderState.Closed or ReaderState.Disposed;
/// <summary>
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
/// </summary>
/// <value>
/// The number of rows changed, inserted, or deleted. -1 for SELECT statements; 0 if no rows were affected or the statement failed.
/// </value>
public override int RecordsAffected
=> !_recordsAffected.HasValue
? -1
: _recordsAffected > int.MaxValue
? throw new OverflowException(
$"The number of records affected exceeds int.MaxValue. Use {nameof(Rows)}.")
: (int)_recordsAffected;
/// <summary>
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
/// </summary>
/// <value>
/// The number of rows changed, inserted, or deleted. 0 for SELECT statements, if no rows were affected or the statement failed.
/// </value>
public ulong Rows => _recordsAffected ?? 0;
/// <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>
[Obsolete("Use the new DbBatch API")]
public IReadOnlyList<NpgsqlBatchCommand> Statements
{
get
{
ThrowIfClosedOrDisposed();
return _statements.AsReadOnly();
}
}
/// <summary>
/// Gets a value that indicates whether this DbDataReader contains one or more rows.
/// </summary>
public override bool HasRows
{
get
{
ThrowIfClosedOrDisposed();
return _hasRows;
}
}
/// <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
{
ThrowIfClosedOrDisposed();
return State is ReaderState.InResult;
}
}
/// <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) => GetField(ordinal).Name;
/// <summary>
/// Gets the number of columns in the current row.
/// </summary>
public override int FieldCount
{
get
{
ThrowIfClosedOrDisposed();
return RowDescription?.Count ?? 0;
}
}
#region Cleanup / Dispose
/// <summary>
/// Consumes all result sets for this reader, leaving the connector ready for sending and processing further
/// queries
/// </summary>
async Task Consume(bool async, Exception? firstException = null)
{
var exceptions = firstException is null ? null : new List<Exception> { firstException };
// Skip over the other result sets. Note that this does tally records affected from CommandComplete messages, and properly sets
// state for auto-prepared statements
//
// The only exception is when the connector is broken (which can happen in the middle of consuming)
// As then there is no point in going forward.
// An exception to the exception above is when connector is concurrently closed while
// the reader is still going over the result set.
// While this is undefined behavior and user error, we should try to at least do our best to not loop indefinitely.
//
// While we can also check our local state (State == Closed)
// It's probably better to rely on connector since it's private and its state can't be changed
while (Connector.IsConnected)
{
try
{
if (!(_isSchemaOnly
? await NextResultSchemaOnly(async, isConsuming: true).ConfigureAwait(false)
: await NextResult(async, isConsuming: true).ConfigureAwait(false)))
{
break;
}
}
catch (Exception e)
{
exceptions ??= [];
exceptions.Add(e);
}
}
Debug.Assert(exceptions?.Count != 0);