-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlCommand.cs
More file actions
1898 lines (1598 loc) · 77.4 KB
/
NpgsqlCommand.cs
File metadata and controls
1898 lines (1598 loc) · 77.4 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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.BackendMessages;
using Npgsql.Util;
using NpgsqlTypes;
using static Npgsql.Util.Statics;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using Npgsql.Internal;
using Npgsql.Properties;
namespace Npgsql;
/// <summary>
/// Represents a SQL statement or function (stored procedure) to execute
/// against a PostgreSQL database. This class cannot be inherited.
/// </summary>
// ReSharper disable once RedundantNameQualifier
[System.ComponentModel.DesignerCategory("")]
public class NpgsqlCommand : DbCommand, ICloneable, IComponent
{
#region Fields
NpgsqlTransaction? _transaction;
readonly NpgsqlConnector? _connector;
/// <summary>
/// If this command is (explicitly) prepared, references the connector on which the preparation happened.
/// Used to detect when the connector was changed (i.e. connection open/close), meaning that the command
/// is no longer prepared.
/// </summary>
NpgsqlConnector? _connectorPreparedOn;
string _commandText;
CommandBehavior _behavior;
int? _timeout;
internal NpgsqlParameterCollection? _parameters;
/// <summary>
/// Whether this <see cref="NpgsqlCommand" /> is wrapped by an <see cref="NpgsqlBatch" />.
/// </summary>
internal bool IsWrappedByBatch { get; }
internal List<NpgsqlBatchCommand> InternalBatchCommands { get; }
Activity? CurrentActivity;
/// <summary>
/// Returns details about each statement that this command has executed.
/// Is only populated when an Execute* method is called.
/// </summary>
[Obsolete("Use the new DbBatch API")]
public IReadOnlyList<NpgsqlBatchCommand> Statements => InternalBatchCommands.AsReadOnly();
UpdateRowSource _updateRowSource = UpdateRowSource.Both;
bool IsExplicitlyPrepared => _connectorPreparedOn != null;
/// <summary>
/// Whether this command is cached by <see cref="NpgsqlConnection" /> and returned by <see cref="NpgsqlConnection.CreateCommand" />.
/// </summary>
internal bool IsCacheable { get; set; }
#if DEBUG
internal static bool EnableSqlRewriting;
internal static bool EnableStoredProcedureCompatMode;
#else
internal static readonly bool EnableSqlRewriting;
internal static readonly bool EnableStoredProcedureCompatMode;
#endif
internal bool EnableErrorBarriers { get; set; }
static readonly TaskScheduler ConstrainedConcurrencyScheduler =
new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, Math.Max(1, Environment.ProcessorCount / 2)).ConcurrentScheduler;
#endregion Fields
#region Constants
internal const int DefaultTimeout = 30;
#endregion
#region Constructors
static NpgsqlCommand()
{
EnableSqlRewriting = !AppContext.TryGetSwitch("Npgsql.EnableSqlRewriting", out var enabled) || enabled;
EnableStoredProcedureCompatMode = AppContext.TryGetSwitch("Npgsql.EnableStoredProcedureCompatMode", out enabled) && enabled;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlCommand"/> class.
/// </summary>
public NpgsqlCommand() : this(null, null, null) {}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlCommand"/> class with the text of the query.
/// </summary>
/// <param name="cmdText">The text of the query.</param>
// ReSharper disable once IntroduceOptionalParameters.Global
public NpgsqlCommand(string? cmdText) : this(cmdText, null, null) {}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlCommand"/> class with the text of the query and a
/// <see cref="NpgsqlConnection"/>.
/// </summary>
/// <param name="cmdText">The text of the query.</param>
/// <param name="connection">A <see cref="NpgsqlConnection"/> that represents the connection to a PostgreSQL server.</param>
// ReSharper disable once IntroduceOptionalParameters.Global
public NpgsqlCommand(string? cmdText, NpgsqlConnection? connection)
{
GC.SuppressFinalize(this);
InternalBatchCommands = new List<NpgsqlBatchCommand>(1);
_commandText = cmdText ?? string.Empty;
InternalConnection = connection;
CommandType = CommandType.Text;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlCommand"/> class with the text of the query, a
/// <see cref="NpgsqlConnection"/>, and the <see cref="NpgsqlTransaction"/>.
/// </summary>
/// <param name="cmdText">The text of the query.</param>
/// <param name="connection">A <see cref="NpgsqlConnection"/> that represents the connection to a PostgreSQL server.</param>
/// <param name="transaction">The <see cref="NpgsqlTransaction"/> in which the <see cref="NpgsqlCommand"/> executes.</param>
public NpgsqlCommand(string? cmdText, NpgsqlConnection? connection, NpgsqlTransaction? transaction)
: this(cmdText, connection)
=> Transaction = transaction;
/// <summary>
/// Used when this <see cref="NpgsqlCommand"/> instance is wrapped inside an <see cref="NpgsqlBatch"/>.
/// </summary>
internal NpgsqlCommand(int batchCommandCapacity, NpgsqlConnection? connection = null)
{
GC.SuppressFinalize(this);
InternalBatchCommands = new List<NpgsqlBatchCommand>(batchCommandCapacity);
InternalConnection = connection;
CommandType = CommandType.Text;
IsWrappedByBatch = true;
// These can/should never be used in this mode
_commandText = null!;
_parameters = null!;
}
internal NpgsqlCommand(string? cmdText, NpgsqlConnector connector) : this(cmdText)
=> _connector = connector;
/// <summary>
/// Used when this <see cref="NpgsqlCommand"/> instance is wrapped inside an <see cref="NpgsqlBatch"/>.
/// </summary>
internal NpgsqlCommand(NpgsqlConnector connector, int batchCommandCapacity)
: this(batchCommandCapacity)
=> _connector = connector;
internal static NpgsqlCommand CreateCachedCommand(NpgsqlConnection connection)
=> new(null, connection) { IsCacheable = true };
#endregion Constructors
#region Public properties
/// <summary>
/// Gets or sets the SQL statement or function (stored procedure) to execute at the data source.
/// </summary>
/// <value>The SQL statement or function (stored procedure) to execute. The default is an empty string.</value>
[AllowNull, DefaultValue("")]
[Category("Data")]
public override string CommandText
{
get => _commandText;
set
{
Debug.Assert(!IsWrappedByBatch);
if (State != CommandState.Idle)
ThrowHelper.ThrowInvalidOperationException("An open data reader exists for this command.");
_commandText = value ?? string.Empty;
ResetPreparation();
// TODO: Technically should do this also if the parameter list (or type) changes
}
}
/// <summary>
/// Gets or sets the wait time (in seconds) before terminating the attempt to execute a command and generating an error.
/// </summary>
/// <value>The time (in seconds) to wait for the command to execute. The default value is 30 seconds.</value>
[DefaultValue(DefaultTimeout)]
public override int CommandTimeout
{
get => _timeout ?? (InternalConnection?.CommandTimeout ?? DefaultTimeout);
set
{
if (value < 0) {
throw new ArgumentOutOfRangeException(nameof(value), value, "CommandTimeout can't be less than zero.");
}
_timeout = value;
}
}
/// <summary>
/// Gets or sets a value indicating how the <see cref="NpgsqlCommand.CommandText"/> property is to be interpreted.
/// </summary>
/// <value>
/// One of the <see cref="System.Data.CommandType"/> values. The default is <see cref="System.Data.CommandType.Text"/>.
/// </value>
[DefaultValue(CommandType.Text)]
[Category("Data")]
public override CommandType CommandType { get; set; }
internal NpgsqlConnection? InternalConnection { get; private set; }
/// <summary>
/// DB connection.
/// </summary>
protected override DbConnection? DbConnection
{
get => InternalConnection;
set
{
if (InternalConnection == value)
return;
InternalConnection = State == CommandState.Idle
? (NpgsqlConnection?)value
: throw new InvalidOperationException("An open data reader exists for this command.");
Transaction = null;
}
}
/// <summary>
/// Gets or sets the <see cref="NpgsqlConnection"/> used by this instance of the <see cref="NpgsqlCommand"/>.
/// </summary>
/// <value>The connection to a data source. The default value is <see langword="null"/>.</value>
[DefaultValue(null)]
[Category("Behavior")]
public new NpgsqlConnection? Connection
{
get => (NpgsqlConnection?)DbConnection;
set => DbConnection = value;
}
/// <summary>
/// Design time visible.
/// </summary>
public override bool DesignTimeVisible { get; set; }
/// <summary>
/// Gets or sets how command results are applied to the DataRow when used by the
/// DbDataAdapter.Update(DataSet) method.
/// </summary>
/// <value>One of the <see cref="System.Data.UpdateRowSource"/> values.</value>
[Category("Behavior"), DefaultValue(UpdateRowSource.Both)]
public override UpdateRowSource UpdatedRowSource
{
get => _updateRowSource;
set
{
switch (value)
{
// validate value (required based on base type contract)
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updateRowSource = value;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Returns whether this query will execute as a prepared (compiled) query.
/// </summary>
public bool IsPrepared
{
get
{
return _connectorPreparedOn == (InternalConnection?.Connector ?? _connector) && AllPrepared();
bool AllPrepared()
{
if (InternalBatchCommands.Count is 0)
return false;
foreach (var s in InternalBatchCommands)
if (s.PreparedStatement is null || !s.PreparedStatement.IsPrepared)
return false;
return true;
}
}
}
#endregion Public properties
#region Known/unknown Result Types Management
/// <summary>
/// Marks all of the query's result columns as either known or unknown.
/// Unknown result columns are requested from PostgreSQL in text format, and Npgsql makes no
/// attempt to parse them. They will be accessible as strings only.
/// </summary>
public bool AllResultTypesAreUnknown
{
get => _allResultTypesAreUnknown;
set
{
// TODO: Check that this isn't modified after calling prepare
_unknownResultTypeList = null;
_allResultTypesAreUnknown = value;
}
}
bool _allResultTypesAreUnknown;
/// <summary>
/// Marks the query's result columns as known or unknown, on a column-by-column basis.
/// Unknown result columns are requested from PostgreSQL in text format, and Npgsql makes no
/// attempt to parse them. They will be accessible as strings only.
/// </summary>
/// <remarks>
/// If the query includes several queries (e.g. SELECT 1; SELECT 2), this will only apply to the first
/// one. The rest of the queries will be fetched and parsed as usual.
///
/// The array size must correspond exactly to the number of result columns the query returns, or an
/// error will be raised.
/// </remarks>
public bool[]? UnknownResultTypeList
{
get => _unknownResultTypeList;
set
{
// TODO: Check that this isn't modified after calling prepare
_allResultTypesAreUnknown = false;
_unknownResultTypeList = value;
}
}
bool[]? _unknownResultTypeList;
#endregion
#region State management
volatile int _state;
/// <summary>
/// The current state of the command
/// </summary>
internal CommandState State
{
get => (CommandState)_state;
set
{
var newState = (int)value;
if (newState == _state)
return;
_state = newState;
}
}
internal void ResetPreparation() => _connectorPreparedOn = null;
#endregion State management
#region Parameters
/// <summary>
/// Creates a new instance of an <see cref="System.Data.Common.DbParameter"/> object.
/// </summary>
/// <returns>A <see cref="System.Data.Common.DbParameter"/> object.</returns>
protected override DbParameter CreateDbParameter() => CreateParameter();
/// <summary>
/// Creates a new instance of a <see cref="NpgsqlParameter"/> object.
/// </summary>
/// <returns>An <see cref="NpgsqlParameter"/> object.</returns>
public new NpgsqlParameter CreateParameter() => new();
/// <summary>
/// DB parameter collection.
/// </summary>
protected override DbParameterCollection DbParameterCollection => Parameters;
/// <summary>
/// Gets the <see cref="NpgsqlParameterCollection"/>.
/// </summary>
/// <value>The parameters of the SQL statement or function (stored procedure). The default is an empty collection.</value>
public new NpgsqlParameterCollection Parameters => _parameters ??= new();
#endregion
#region DeriveParameters
const string DeriveParametersForFunctionQuery = @"
SELECT
CASE
WHEN pg_proc.proargnames IS NULL THEN array_cat(array_fill(''::name,ARRAY[pg_proc.pronargs]),array_agg(pg_attribute.attname ORDER BY pg_attribute.attnum))
ELSE pg_proc.proargnames
END AS proargnames,
pg_proc.proargtypes,
CASE
WHEN pg_proc.proallargtypes IS NULL AND (array_agg(pg_attribute.atttypid))[1] IS NOT NULL THEN array_cat(string_to_array(pg_proc.proargtypes::text,' ')::oid[],array_agg(pg_attribute.atttypid ORDER BY pg_attribute.attnum))
ELSE pg_proc.proallargtypes
END AS proallargtypes,
CASE
WHEN pg_proc.proargmodes IS NULL AND (array_agg(pg_attribute.atttypid))[1] IS NOT NULL THEN array_cat(array_fill('i'::""char"",ARRAY[pg_proc.pronargs]),array_fill('o'::""char"",ARRAY[array_length(array_agg(pg_attribute.atttypid), 1)]))
ELSE pg_proc.proargmodes
END AS proargmodes
FROM pg_proc
LEFT JOIN pg_type ON pg_proc.prorettype = pg_type.oid
LEFT JOIN pg_attribute ON pg_type.typrelid = pg_attribute.attrelid AND pg_attribute.attnum >= 1 AND NOT pg_attribute.attisdropped
WHERE pg_proc.oid = :proname::regproc
GROUP BY pg_proc.proargnames, pg_proc.proargtypes, pg_proc.proallargtypes, pg_proc.proargmodes, pg_proc.pronargs;
";
internal void DeriveParameters()
{
var conn = CheckAndGetConnection();
Debug.Assert(conn is not null);
if (string.IsNullOrEmpty(CommandText))
throw new InvalidOperationException("CommandText property has not been initialized");
using var _ = conn.StartTemporaryBindingScope(out var connector);
foreach (var s in InternalBatchCommands)
if (s.PreparedStatement?.IsExplicit == true)
throw new NpgsqlException("Deriving parameters isn't supported for commands that are already prepared.");
// Here we unprepare statements that possibly are auto-prepared
Unprepare();
Parameters.Clear();
switch (CommandType)
{
case CommandType.Text:
DeriveParametersForQuery(connector);
break;
case CommandType.StoredProcedure:
DeriveParametersForFunction();
break;
default:
throw new NotSupportedException("Cannot derive parameters for CommandType " + CommandType);
}
}
void DeriveParametersForFunction()
{
using var c = new NpgsqlCommand(DeriveParametersForFunctionQuery, InternalConnection);
c.Parameters.Add(new NpgsqlParameter("proname", NpgsqlDbType.Text));
c.Parameters[0].Value = CommandText;
string[]? names = null;
uint[]? types = null;
char[]? modes = null;
using (var rdr = c.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
if (rdr.Read())
{
if (!rdr.IsDBNull(0))
names = rdr.GetFieldValue<string[]>(0);
if (!rdr.IsDBNull(2))
types = rdr.GetFieldValue<uint[]>(2);
if (!rdr.IsDBNull(3))
modes = rdr.GetFieldValue<char[]>(3);
if (types == null)
{
if (rdr.IsDBNull(1) || rdr.GetFieldValue<uint[]>(1).Length == 0)
return; // Parameter-less function
types = rdr.GetFieldValue<uint[]>(1);
}
}
else
throw new InvalidOperationException($"{CommandText} does not exist in pg_proc");
}
var serializerOptions = c.InternalConnection!.Connector!.SerializerOptions;
for (var i = 0; i < types.Length; i++)
{
var param = new NpgsqlParameter();
var postgresType = serializerOptions.DatabaseInfo.GetPostgresType(types[i]);
var npgsqlDbType = postgresType.DataTypeName.ToNpgsqlDbType();
param.DataTypeName = postgresType.DisplayName;
param.PostgresType = postgresType;
if (npgsqlDbType.HasValue)
param.NpgsqlDbType = npgsqlDbType.Value;
if (names != null && i < names.Length)
param.ParameterName = names[i];
else
param.ParameterName = "parameter" + (i + 1);
if (modes == null) // All params are IN, or server < 8.1.0 (and only IN is supported)
param.Direction = ParameterDirection.Input;
else
{
param.Direction = modes[i] switch
{
'i' => ParameterDirection.Input,
'o' => ParameterDirection.Output,
't' => ParameterDirection.Output,
'b' => ParameterDirection.InputOutput,
'v' => throw new NotSupportedException("Cannot derive function parameter of type VARIADIC"),
_ => throw new ArgumentOutOfRangeException("Unknown code in proargmodes while deriving: " + modes[i])
};
}
Parameters.Add(param);
}
}
void DeriveParametersForQuery(NpgsqlConnector connector)
{
using (connector.StartUserAction())
{
LogMessages.DerivingParameters(connector.CommandLogger, CommandText, connector.Id);
if (IsWrappedByBatch)
foreach (var batchCommand in InternalBatchCommands)
connector.SqlQueryParser.ParseRawQuery(batchCommand, connector.UseConformingStrings, deriveParameters: true);
else
connector.SqlQueryParser.ParseRawQuery(this, connector.UseConformingStrings, deriveParameters: true);
var sendTask = SendDeriveParameters(connector, false);
if (sendTask.IsFaulted)
sendTask.GetAwaiter().GetResult();
try
{
foreach (var batchCommand in InternalBatchCommands)
{
Expect<ParseCompleteMessage>(
connector.ReadMessage(async: false).GetAwaiter().GetResult(), connector);
var paramTypeOIDs = Expect<ParameterDescriptionMessage>(
connector.ReadMessage(async: false).GetAwaiter().GetResult(), connector).TypeOIDs;
if (batchCommand.PositionalParameters.Count != paramTypeOIDs.Count)
{
connector.SkipUntil(BackendMessageCode.ReadyForQuery);
Parameters.Clear();
throw new NpgsqlException(
"There was a mismatch in the number of derived parameters between the Npgsql SQL parser and the PostgreSQL parser. Please report this as bug to the Npgsql developers (https://github.com/npgsql/npgsql/issues).");
}
for (var i = 0; i < paramTypeOIDs.Count; i++)
{
try
{
var param = batchCommand.PositionalParameters[i];
var paramOid = paramTypeOIDs[i];
var postgresType = connector.SerializerOptions.DatabaseInfo.GetPostgresType(paramOid);
// We want to keep any domain types visible on the parameter, it will internally do a representational lookup again if necessary.
var npgsqlDbType = postgresType.GetRepresentationalType().DataTypeName.ToNpgsqlDbType();
if (param.NpgsqlDbType != NpgsqlDbType.Unknown && param.NpgsqlDbType != npgsqlDbType)
throw new NpgsqlException(
"The backend parser inferred different types for parameters with the same name. Please try explicit casting within your SQL statement or batch or use different placeholder names.");
param.DataTypeName = postgresType.DisplayName;
param.PostgresType = postgresType;
if (npgsqlDbType.HasValue)
param.NpgsqlDbType = npgsqlDbType.Value;
}
catch
{
connector.SkipUntil(BackendMessageCode.ReadyForQuery);
Parameters.Clear();
throw;
}
}
var msg = connector.ReadMessage(async: false).GetAwaiter().GetResult();
switch (msg.Code)
{
case BackendMessageCode.RowDescription:
case BackendMessageCode.NoData:
break;
default:
throw connector.UnexpectedMessageReceived(msg.Code);
}
}
Expect<ReadyForQueryMessage>(connector.ReadMessage(async: false).GetAwaiter().GetResult(), connector);
}
finally
{
try
{
// Make sure sendTask is complete so we don't race against asynchronous flush
sendTask.GetAwaiter().GetResult();
}
catch
{
// ignored
}
}
}
}
#endregion
#region Prepare
/// <summary>
/// Creates a server-side prepared statement on the PostgreSQL server.
/// This will make repeated future executions of this command much faster.
/// </summary>
public override void Prepare() => Prepare(false).GetAwaiter().GetResult();
/// <summary>
/// Creates a server-side prepared statement on the PostgreSQL server.
/// This will make repeated future executions of this command much faster.
/// </summary>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
public override Task PrepareAsync(CancellationToken cancellationToken = default)
=> Prepare(async: true, cancellationToken);
Task Prepare(bool async, CancellationToken cancellationToken = default)
{
var connection = CheckAndGetConnection();
Debug.Assert(connection is not null);
if (connection.Settings.Multiplexing)
throw new NotSupportedException("Explicit preparation not supported with multiplexing");
var connector = connection.Connector!;
var logger = connector.CommandLogger;
var needToPrepare = false;
if (IsWrappedByBatch)
{
foreach (var batchCommand in InternalBatchCommands)
{
batchCommand._parameters?.ProcessParameters(connector.SerializerOptions, validateValues: false, CommandType);
ProcessRawQuery(connector.SqlQueryParser, connector.UseConformingStrings, batchCommand);
needToPrepare = batchCommand.ExplicitPrepare(connector) || needToPrepare;
}
if (logger.IsEnabled(LogLevel.Debug) && needToPrepare)
LogMessages.PreparingCommandExplicitly(logger, string.Join("; ", CommandTexts()), connector.Id);
IEnumerable<string> CommandTexts()
{
foreach (var c in InternalBatchCommands)
yield return c.CommandText;
}
}
else
{
_parameters?.ProcessParameters(connector.SerializerOptions, validateValues: false, CommandType);
ProcessRawQuery(connector.SqlQueryParser, connector.UseConformingStrings, batchCommand: null);
foreach (var batchCommand in InternalBatchCommands)
needToPrepare = batchCommand.ExplicitPrepare(connector) || needToPrepare;
if (logger.IsEnabled(LogLevel.Debug) && needToPrepare)
LogMessages.PreparingCommandExplicitly(logger, CommandText, connector.Id);
}
_connectorPreparedOn = connector;
// It's possible the command was already prepared, or that persistent prepared statements were found for
// all statements. Nothing to do here, move along.
return needToPrepare
? PrepareLong(this, async, connector, cancellationToken)
: Task.CompletedTask;
static async Task PrepareLong(NpgsqlCommand command, bool async, NpgsqlConnector connector, CancellationToken cancellationToken)
{
try
{
using (connector.StartUserAction(cancellationToken))
{
var sendTask = command.SendPrepare(connector, async, CancellationToken.None);
if (sendTask.IsFaulted)
sendTask.GetAwaiter().GetResult();
try
{
// Loop over statements, skipping those that are already prepared (because they were persisted)
var isFirst = true;
foreach (var batchCommand in command.InternalBatchCommands)
{
if (!batchCommand.IsPreparing)
continue;
var pStatement = batchCommand.PreparedStatement!;
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);
Expect<ParameterDescriptionMessage>(await connector.ReadMessage(async).ConfigureAwait(false), connector);
var msg = await connector.ReadMessage(async).ConfigureAwait(false);
switch (msg.Code)
{
case BackendMessageCode.RowDescription:
// Clone the RowDescription for use with the prepared statement (the one we have is reused
// by the connection)
var description = ((RowDescriptionMessage)msg).Clone();
command.FixupRowDescription(description, isFirst);
batchCommand.Description = description;
break;
case BackendMessageCode.NoData:
batchCommand.Description = null;
break;
default:
throw connector.UnexpectedMessageReceived(msg.Code);
}
pStatement.State = PreparedState.Prepared;
connector.PreparedStatementManager.NumPrepared++;
batchCommand.IsPreparing = false;
isFirst = false;
}
Expect<ReadyForQueryMessage>(await connector.ReadMessage(async).ConfigureAwait(false), connector);
}
finally
{
try
{
// Make sure sendTask is complete so we don't race against asynchronous flush
if (async)
await sendTask.ConfigureAwait(false);
else
sendTask.GetAwaiter().GetResult();
}
catch
{
// ignored
}
}
}
LogMessages.CommandPreparedExplicitly(connector.CommandLogger, connector.Id);
}
catch
{
// The statements weren't prepared successfully, update the bookkeeping for them
foreach (var batchCommand in command.InternalBatchCommands)
{
if (batchCommand.IsPreparing)
{
batchCommand.IsPreparing = false;
batchCommand.PreparedStatement!.AbortPrepare();
}
}
throw;
}
}
}
/// <summary>
/// Unprepares a command, closing server-side statements associated with it.
/// Note that this only affects commands explicitly prepared with <see cref="Prepare()"/>, not
/// automatically prepared statements.
/// </summary>
public void Unprepare()
=> Unprepare(false).GetAwaiter().GetResult();
/// <summary>
/// Unprepares a command, closing server-side statements associated with it.
/// Note that this only affects commands explicitly prepared with <see cref="Prepare()"/>, not
/// automatically prepared statements.
/// </summary>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
public Task UnprepareAsync(CancellationToken cancellationToken = default)
=> Unprepare(async: true, cancellationToken);
async Task Unprepare(bool async, CancellationToken cancellationToken = default)
{
var connection = CheckAndGetConnection();
Debug.Assert(connection is not null);
if (connection.Settings.Multiplexing)
throw new NotSupportedException("Explicit preparation not supported with multiplexing");
var forall = true;
foreach (var statement in InternalBatchCommands)
if (statement.IsPrepared)
{
forall = false;
break;
}
if (forall)
return;
var connector = connection.Connector!;
LogMessages.UnpreparingCommand(connector.CommandLogger, connector.Id);
using (connector.StartUserAction(cancellationToken))
{
// Just wait for SendClose to complete since each statement takes no more than 20 bytes
await SendClose(connector, async, cancellationToken).ConfigureAwait(false);
foreach (var batchCommand in InternalBatchCommands)
{
if (batchCommand.PreparedStatement?.State == PreparedState.BeingUnprepared)
{
Expect<CloseCompletedMessage>(await connector.ReadMessage(async).ConfigureAwait(false), connector);
var pStatement = batchCommand.PreparedStatement;
pStatement.CompleteUnprepare();
if (!pStatement.IsExplicit)
connector.PreparedStatementManager.AutoPrepared[pStatement.AutoPreparedSlotIndex] = null;
batchCommand.PreparedStatement = null;
}
}
Expect<ReadyForQueryMessage>(await connector.ReadMessage(async).ConfigureAwait(false), connector);
}
}
#endregion Prepare
#region Query analysis
internal void ProcessRawQuery(SqlQueryParser? parser, bool standardConformingStrings, NpgsqlBatchCommand? batchCommand)
{
var (commandText, commandType, parameters) = batchCommand is null
? (CommandText, CommandType, _parameters)
: (batchCommand.CommandText, batchCommand.CommandType, batchCommand._parameters);
if (string.IsNullOrEmpty(commandText))
ThrowHelper.ThrowInvalidOperationException("CommandText property has not been initialized");
switch (commandType)
{
case CommandType.Text:
switch (parameters?.PlaceholderType ?? PlaceholderType.NoParameters)
{
case PlaceholderType.Positional:
// In positional parameter mode, we don't need to parse/rewrite the CommandText or reorder the parameters - just use
// them as is. If the SQL contains a semicolon (legacy batching) when positional parameters are in use, we just send
// that and PostgreSQL will error (this behavior is by-design - use the new batching API).
if (batchCommand is null)
{
batchCommand = TruncateStatementsToOne();
batchCommand.FinalCommandText = CommandText;
if (parameters is not null)
batchCommand.PositionalParameters = parameters.InternalList;
}
else
{
batchCommand.FinalCommandText = batchCommand.CommandText;
if (parameters is not null)
batchCommand.PositionalParameters = parameters.InternalList;
}
ValidateParameterCount(batchCommand);
break;
case PlaceholderType.NoParameters:
// Unless the EnableSqlRewriting AppContext switch is explicitly disabled, queries with no parameters are parsed just
// like queries with named parameters, since they may contain a semicolon (legacy batching).
if (EnableSqlRewriting)
goto case PlaceholderType.Named;
goto case PlaceholderType.Positional;
case PlaceholderType.Named:
if (!EnableSqlRewriting)
ThrowHelper.ThrowNotSupportedException($"Named parameters are not supported when Npgsql.{nameof(EnableSqlRewriting)} is disabled");
// The parser is cached on NpgsqlConnector - unless we're in multiplexing mode.
parser ??= new SqlQueryParser();
if (batchCommand is null)
{
parser.ParseRawQuery(this, standardConformingStrings);
if (InternalBatchCommands.Count > 1 && _parameters?.HasOutputParameters == true)
ThrowHelper.ThrowNotSupportedException("Commands with multiple queries cannot have out parameters");
for (var i = 0; i < InternalBatchCommands.Count; i++)
ValidateParameterCount(InternalBatchCommands[i]);
}
else
{
parser.ParseRawQuery(batchCommand, standardConformingStrings);
if (batchCommand._parameters?.HasOutputParameters == true)
ThrowHelper.ThrowNotSupportedException("Batches cannot cannot have out parameters");
ValidateParameterCount(batchCommand);
}
break;
case PlaceholderType.Mixed:
ThrowHelper.ThrowNotSupportedException("Mixing named and positional parameters isn't supported");
break;
default:
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(PlaceholderType), $"Unknown {nameof(PlaceholderType)} value: {{0}}", _parameters?.PlaceholderType ?? PlaceholderType.NoParameters);
break;
}
break;
case CommandType.TableDirect:
batchCommand ??= TruncateStatementsToOne();
batchCommand.FinalCommandText = "SELECT * FROM " + CommandText;
break;
case CommandType.StoredProcedure:
var sqlBuilder = new StringBuilder()
.Append(EnableStoredProcedureCompatMode ? "SELECT * FROM " : "CALL ")
.Append(commandText)
.Append('(');
var isFirstParam = true;
var seenNamedParam = false;
var inputParameters = NpgsqlBatchCommand.EmptyParameters;
if (parameters is not null)
{
inputParameters = new List<NpgsqlParameter>(parameters.Count);
for (var i = 0; i < parameters.Count; i++)
{
var parameter = parameters[i];
// With functions, output parameters are never present when calling the function (they only define the schema of the
// returned table). With stored procedures they must be specified in the CALL argument list (see below).
if (EnableStoredProcedureCompatMode && parameter.Direction == ParameterDirection.Output)
continue;
if (isFirstParam)
isFirstParam = false;
else
sqlBuilder.Append(", ");
if (parameter.IsPositional)
{
if (seenNamedParam)
ThrowHelper.ThrowArgumentException(NpgsqlStrings.PositionalParameterAfterNamed);
}
else
{
seenNamedParam = true;
sqlBuilder
.Append('"')
.Append(parameter.TrimmedName.Replace("\"", "\"\""))
.Append("\" := ");
}
if (parameter.Direction == ParameterDirection.Output)
sqlBuilder.Append("NULL");
else
{
inputParameters!.Add(parameter);
sqlBuilder.Append('$').Append(inputParameters.Count);
}
}
}
sqlBuilder.Append(')');
batchCommand ??= TruncateStatementsToOne();
batchCommand.FinalCommandText = sqlBuilder.ToString();
batchCommand.PositionalParameters.AddRange(inputParameters);
ValidateParameterCount(batchCommand);
break;
default:
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(CommandType), $"Internal Npgsql bug: unexpected value {{0}} of enum {nameof(CommandType)}. Please file a bug.", commandType);
break;
}