forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlCommand.cs
More file actions
1505 lines (1259 loc) · 59.9 KB
/
NpgsqlCommand.cs
File metadata and controls
1505 lines (1259 loc) · 59.9 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
// created on 21/5/2002 at 20:03
// Npgsql.NpgsqlCommand.cs
//
// Author:
// Francisco Jr. (fxjrlists@yahoo.com.br)
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Text.RegularExpressions;
using NpgsqlTypes;
#if WITHDESIGN
#endif
namespace Npgsql
{
/// <summary>
/// Represents a SQL statement or function (stored procedure) to execute
/// against a PostgreSQL database. This class cannot be inherited.
/// </summary>
#if WITHDESIGN
[System.Drawing.ToolboxBitmapAttribute(typeof(NpgsqlCommand)), ToolboxItem(true)]
#endif
public sealed class NpgsqlCommand : DbCommand, ICloneable
{
// Logging related values
private static readonly String CLASSNAME = MethodBase.GetCurrentMethod().DeclaringType.Name;
private static readonly ResourceManager resman = new ResourceManager(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Regex parameterReplace = new Regex(@"([:@][\w\.]*)", RegexOptions.Singleline|RegexOptions.Compiled);
private static readonly Regex POSTGRES_TEXT_ARRAY = new Regex(@"^array\[+'", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private NpgsqlConnection connection;
private NpgsqlConnector m_Connector; //renamed to account for hiding it in a local function
//if all locals were named with this prefix, it would solve LOTS of issues.
private NpgsqlTransaction transaction;
private String text;
private Int32 timeout;
private CommandType type;
private readonly NpgsqlParameterCollection parameters = new NpgsqlParameterCollection();
private String planName;
private Boolean designTimeVisible;
private NpgsqlParse parse;
private NpgsqlBind bind;
private Int64 lastInsertedOID = 0;
// locals about function support so we don`t need to check it everytime a function is called.
private Boolean functionChecksDone = false;
private Boolean addProcedureParenthesis = false; // Do not add procedure parenthesis by default.
private Boolean functionNeedsColumnListDefinition = false; // Functions don't return record by default.
private Boolean commandTimeoutSet = false;
private UpdateRowSource updateRowSource = UpdateRowSource.Both;
// Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> class.
/// </summary>
public NpgsqlCommand()
: this(String.Empty, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> class with the text of the query.
/// </summary>
/// <param name="cmdText">The text of the query.</param>
public NpgsqlCommand(String cmdText)
: this(cmdText, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> class with the text of the query and a <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see>.
/// </summary>
/// <param name="cmdText">The text of the query.</param>
/// <param name="connection">A <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> that represents the connection to a PostgreSQL server.</param>
public NpgsqlCommand(String cmdText, NpgsqlConnection connection)
: this(cmdText, connection, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> class with the text of the query, a <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see>, and the <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see>.
/// </summary>
/// <param name="cmdText">The text of the query.</param>
/// <param name="connection">A <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> that represents the connection to a PostgreSQL server.</param>
/// <param name="transaction">The <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see> in which the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> executes.</param>
public NpgsqlCommand(String cmdText, NpgsqlConnection connection, NpgsqlTransaction transaction)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME);
planName = String.Empty;
text = cmdText;
this.connection = connection;
if (this.connection != null)
{
this.m_Connector = connection.Connector;
}
type = CommandType.Text;
this.Transaction = transaction;
SetCommandTimeout();
}
/// <summary>
/// Used to execute internal commands.
/// </summary>
internal NpgsqlCommand(String cmdText, NpgsqlConnector connector)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME);
planName = String.Empty;
text = cmdText;
this.m_Connector = connector;
type = CommandType.Text;
// Removed this setting. It was causing too much problem.
// Do internal commands really need different timeout setting?
// Internal commands aren't affected by command timeout value provided by user.
// timeout = 20;
}
// Public properties.
/// <summary>
/// Gets or sets the SQL statement or function (stored procedure) to execute at the data source.
/// </summary>
/// <value>The Transact-SQL statement or stored procedure to execute. The default is an empty string.</value>
[Category("Data"), DefaultValue("")]
public override String CommandText
{
get { return text; }
set
{
// [TODO] Validate commandtext.
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "CommandText", value);
text = value;
planName = String.Empty;
parse = null;
bind = null;
functionChecksDone = false;
}
}
/// <summary>
/// Gets or sets the wait time 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 is 20 seconds.</value>
[DefaultValue(20)]
public override Int32 CommandTimeout
{
get { return timeout; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(resman.GetString("Exception_CommandTimeoutLessZero"));
}
timeout = value;
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "CommandTimeout", value);
commandTimeoutSet = true;
}
}
/// <summary>
/// Gets or sets a value indicating how the
/// <see cref="Npgsql.NpgsqlCommand.CommandText">CommandText</see> property is to be interpreted.
/// </summary>
/// <value>One of the <see cref="System.Data.CommandType">CommandType</see> values. The default is <see cref="System.Data.CommandType">CommandType.Text</see>.</value>
[Category("Data"), DefaultValue(CommandType.Text)]
public override CommandType CommandType
{
get { return type; }
set
{
type = value;
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "CommandType", value);
}
}
protected override DbConnection DbConnection
{
get { return Connection; }
set
{
Connection = (NpgsqlConnection)value;
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "DbConnection", value);
}
}
/// <summary>
/// Gets or sets the <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see>
/// used by this instance of the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see>.
/// </summary>
/// <value>The connection to a data source. The default value is a null reference.</value>
[Category("Behavior"), DefaultValue(null)]
public new NpgsqlConnection Connection
{
get
{
NpgsqlEventLog.LogPropertyGet(LogLevel.Debug, CLASSNAME, "Connection");
return connection;
}
set
{
if (this.Connection == value)
{
return;
}
//if (this.transaction != null && this.transaction.Connection == null)
// this.transaction = null;
// All this checking needs revising. It should be simpler.
// This this.Connector != null check was added to remove the nullreferenceexception in case
// of the previous connection has been closed which makes Connector null and so the last check would fail.
// See bug 1000581 for more details.
if (this.transaction != null && this.connection != null && this.Connector != null && this.Connector.Transaction != null)
{
throw new InvalidOperationException(resman.GetString("Exception_SetConnectionInTransaction"));
}
this.connection = value;
Transaction = null;
if (this.connection != null)
{
m_Connector = this.connection.Connector;
}
SetCommandTimeout();
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "Connection", value);
}
}
internal NpgsqlConnector Connector
{
get
{
if (this.connection != null)
{
m_Connector = this.connection.Connector;
}
return m_Connector;
}
}
internal Type[] ExpectedTypes { get; set; }
protected override DbParameterCollection DbParameterCollection
{
get { return Parameters; }
}
/// <summary>
/// Gets the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see>.
/// </summary>
/// <value>The parameters of the SQL statement or function (stored procedure). The default is an empty collection.</value>
#if WITHDESIGN
[Category("Data"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
#endif
public new NpgsqlParameterCollection Parameters
{
get
{
NpgsqlEventLog.LogPropertyGet(LogLevel.Debug, CLASSNAME, "Parameters");
return parameters;
}
}
protected override DbTransaction DbTransaction
{
get { return Transaction; }
set
{
Transaction = (NpgsqlTransaction)value;
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "IDbCommand.Transaction", value);
}
}
/// <summary>
/// Gets or sets the <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see>
/// within which the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> executes.
/// </summary>
/// <value>The <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see>.
/// The default value is a null reference.</value>
#if WITHDESIGN
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#endif
public new NpgsqlTransaction Transaction
{
get
{
NpgsqlEventLog.LogPropertyGet(LogLevel.Debug, CLASSNAME, "Transaction");
if (this.transaction != null && this.transaction.Connection == null)
{
this.transaction = null;
}
return this.transaction;
}
set
{
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "Transaction", value);
this.transaction = value;
}
}
/// <summary>
/// Gets or sets how command results are applied to the <see cref="System.Data.DataRow">DataRow</see>
/// when used by the <see cref="System.Data.Common.DbDataAdapter.Update(DataSet)">Update</see>
/// method of the <see cref="System.Data.Common.DbDataAdapter">DbDataAdapter</see>.
/// </summary>
/// <value>One of the <see cref="System.Data.UpdateRowSource">UpdateRowSource</see> values.</value>
#if WITHDESIGN
[Category("Behavior"), DefaultValue(UpdateRowSource.Both)]
#endif
public override UpdateRowSource UpdatedRowSource
{
get
{
NpgsqlEventLog.LogPropertyGet(LogLevel.Debug, CLASSNAME, "UpdatedRowSource");
return 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 oid of inserted row. This is only updated when using executenonQuery and when command inserts just a single row. If table is created without oids, this will always be 0.
/// </summary>
public Int64 LastInsertedOID
{
get { return lastInsertedOID; }
}
/// <summary>
/// Attempts to cancel the execution of a <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see>.
/// </summary>
/// <remarks>This Method isn't implemented yet.</remarks>
public override void Cancel()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Cancel");
try
{
// get copy for thread safety of null test
NpgsqlConnector connector = Connector;
if (connector != null)
{
connector.CancelRequest();
}
}
catch (IOException)
{
Connection.ClearPool();
}
catch (NpgsqlException)
{
// Cancel documentation says the Cancel doesn't throw on failure
}
}
/// <summary>
/// Create a new command based on this one.
/// </summary>
/// <returns>A new NpgsqlCommand object.</returns>
Object ICloneable.Clone()
{
return Clone();
}
/// <summary>
/// Create a new command based on this one.
/// </summary>
/// <returns>A new NpgsqlCommand object.</returns>
public NpgsqlCommand Clone()
{
// TODO: Add consistency checks.
NpgsqlCommand clone = new NpgsqlCommand(CommandText, Connection, Transaction);
clone.CommandTimeout = CommandTimeout;
clone.CommandType = CommandType;
clone.DesignTimeVisible = DesignTimeVisible;
if (ExpectedTypes != null)
{
clone.ExpectedTypes = (Type[])ExpectedTypes.Clone();
}
foreach (NpgsqlParameter parameter in Parameters)
{
clone.Parameters.Add(parameter.Clone());
}
return clone;
}
/// <summary>
/// Creates a new instance of an <see cref="System.Data.Common.DbParameter">DbParameter</see> object.
/// </summary>
/// <returns>An <see cref="System.Data.Common.DbParameter">DbParameter</see> object.</returns>
protected override DbParameter CreateDbParameter()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "CreateDbParameter");
return CreateParameter();
}
/// <summary>
/// Creates a new instance of a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.
/// </summary>
/// <returns>A <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.</returns>
public new NpgsqlParameter CreateParameter()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "CreateParameter");
return new NpgsqlParameter();
}
/// <summary>
/// Slightly optimised version of ExecuteNonQuery() for internal ues in cases where the number
/// of affected rows is of no interest.
/// </summary>
internal void ExecuteBlind()
{
GetReader(CommandBehavior.SequentialAccess).Dispose();
}
/// <summary>
/// Executes a SQL statement against the connection and returns the number of rows affected.
/// </summary>
/// <returns>The number of rows affected if known; -1 otherwise.</returns>
public override Int32 ExecuteNonQuery()
{
//We treat this as a simple wrapper for calling ExecuteReader() and then
//update the records affected count at every call to NextResult();
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ExecuteNonQuery");
int? ret = null;
using (NpgsqlDataReader rdr = GetReader(CommandBehavior.SequentialAccess))
{
do
{
int thisRecord = rdr.RecordsAffected;
if (thisRecord != -1)
{
ret = (ret ?? 0) + thisRecord;
}
lastInsertedOID = rdr.LastInsertedOID ?? lastInsertedOID;
}
while (rdr.NextResult());
}
return ret ?? -1;
}
/// <summary>
/// Sends the <see cref="Npgsql.NpgsqlCommand.CommandText">CommandText</see> to
/// the <see cref="Npgsql.NpgsqlConnection">Connection</see> and builds a
/// <see cref="Npgsql.NpgsqlDataReader">NpgsqlDataReader</see>
/// using one of the <see cref="System.Data.CommandBehavior">CommandBehavior</see> values.
/// </summary>
/// <param name="behavior">One of the <see cref="System.Data.CommandBehavior">CommandBehavior</see> values.</param>
/// <returns>A <see cref="Npgsql.NpgsqlDataReader">NpgsqlDataReader</see> object.</returns>
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
/// <summary>
/// Sends the <see cref="Npgsql.NpgsqlCommand.CommandText">CommandText</see> to
/// the <see cref="Npgsql.NpgsqlConnection">Connection</see> and builds a
/// <see cref="Npgsql.NpgsqlDataReader">NpgsqlDataReader</see>.
/// </summary>
/// <returns>A <see cref="Npgsql.NpgsqlDataReader">NpgsqlDataReader</see> object.</returns>
public new NpgsqlDataReader ExecuteReader()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ExecuteReader");
return ExecuteReader(CommandBehavior.Default);
}
/// <summary>
/// Sends the <see cref="Npgsql.NpgsqlCommand.CommandText">CommandText</see> to
/// the <see cref="Npgsql.NpgsqlConnection">Connection</see> and builds a
/// <see cref="Npgsql.NpgsqlDataReader">NpgsqlDataReader</see>
/// using one of the <see cref="System.Data.CommandBehavior">CommandBehavior</see> values.
/// </summary>
/// <param name="cb">One of the <see cref="System.Data.CommandBehavior">CommandBehavior</see> values.</param>
/// <returns>A <see cref="Npgsql.NpgsqlDataReader">NpgsqlDataReader</see> object.</returns>
/// <remarks>Currently the CommandBehavior parameter is ignored.</remarks>
public new NpgsqlDataReader ExecuteReader(CommandBehavior cb)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ExecuteReader", cb);
// Close connection if requested even when there is an error.
try
{
if (connection != null)
{
if (connection.PreloadReader)
{
//Adjust behaviour so source reader is sequential access - for speed - and doesn't close the connection - or it'll do so at the wrong time.
CommandBehavior adjusted = (cb | CommandBehavior.SequentialAccess) & ~CommandBehavior.CloseConnection;
return new CachingDataReader(GetReader(adjusted), cb);
}
}
return GetReader(cb);
}
catch (Exception)
{
if ((cb & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection)
{
connection.Close();
}
throw;
}
}
internal ForwardsOnlyDataReader GetReader(CommandBehavior cb)
{
try
{
CheckConnectionState();
// reset any responses just before getting new ones
Connector.Mediator.ResetResponses();
// Set command timeout.
m_Connector.Mediator.CommandTimeout = CommandTimeout;
using (m_Connector.BlockNotificationThread())
{
ForwardsOnlyDataReader reader;
if (parse == null)
{
reader = new ForwardsOnlyDataReader(m_Connector.QueryEnum(this), cb, this,
m_Connector.BlockNotificationThread(), false);
if (type == CommandType.StoredProcedure
&& reader.FieldCount == 1
&& reader.GetDataTypeName(0) == "refcursor")
{
// When a function returns a sole column of refcursor, transparently
// FETCH ALL from every such cursor and return those results.
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.Append("fetch all from \"").Append(reader.GetString(0)).Append("\";");
}
sb.Append(";"); // Just in case the list of cursors is empty.
reader = new NpgsqlCommand(sb.ToString(), Connection).GetReader(reader._behavior);
}
}
else
{
BindParameters();
reader = new ForwardsOnlyDataReader(m_Connector.ExecuteEnum(new NpgsqlExecute(bind.PortalName, 0)), cb, this,
m_Connector.BlockNotificationThread(), true);
}
return reader;
}
}
catch (IOException ex)
{
throw ClearPoolAndCreateException(ex);
}
}
///<summary>
/// This method binds the parameters from parameters collection to the bind
/// message.
/// </summary>
private void BindParameters()
{
if (parameters.Count != 0)
{
Object[] parameterValues = new Object[parameters.Count];
Int16[] parameterFormatCodes = bind.ParameterFormatCodes;
for (Int32 i = 0; i < parameters.Count; i++)
{
// Do not quote strings, or escape existing quotes - this will be handled by the backend.
// DBNull or null values are returned as null.
// TODO: Would it be better to remove this null special handling out of ConvertToBackend??
// Do special handling of bytea values. They will be send in binary form.
// TODO: Add binary format support for all supported types. Not only bytea.
if (parameters[i].TypeInfo.NpgsqlDbType != NpgsqlDbType.Bytea)
{
parameterValues[i] = parameters[i].TypeInfo.ConvertToBackend(parameters[i].Value, true);
}
else
{
if (parameters[i].Value != DBNull.Value)
{
parameterFormatCodes[i] = (Int16)FormatCode.Binary;
parameterValues[i] = (byte[])parameters[i].Value;
}
else
{
parameterValues[i] = parameters[i].TypeInfo.ConvertToBackend(parameters[i].Value, true);
}
}
}
bind.ParameterValues = parameterValues;
bind.ParameterFormatCodes = parameterFormatCodes;
}
try
{
// In case of error when binding parameters, the ReadyForQuery isn't returned.
// According to docs: "[...] The response is either BindComplete or ErrorResponse."
Connector.RequireReadyForQuery = false;
Connector.Bind(bind);
Connector.Flush();
}
catch
{
// Check catch{} of Preapre method for discussion about that.
Connector.Sync();
throw;
}
}
/// <summary>
/// Executes the query, and returns the first column of the first row
/// in the result set returned by the query. Extra columns or rows are ignored.
/// </summary>
/// <returns>The first column of the first row in the result set,
/// or a null reference if the result set is empty.</returns>
public override Object ExecuteScalar()
{
using (
NpgsqlDataReader reader =
GetReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
return reader.Read() && reader.FieldCount != 0 ? reader.GetValue(0) : null;
}
}
/// <summary>
/// Creates a prepared version of the command on a PostgreSQL server.
/// </summary>
public override void Prepare()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Prepare");
// Check the connection state.
CheckConnectionState();
// reset any responses just before getting new ones
Connector.Mediator.ResetResponses();
// Set command timeout.
m_Connector.Mediator.CommandTimeout = CommandTimeout;
if (!m_Connector.SupportsPrepare)
{
return; // Do nothing.
}
if (m_Connector.BackendProtocolVersion == ProtocolVersion.Version2)
{
using (NpgsqlCommand command = new NpgsqlCommand(GetPrepareCommandText(), m_Connector))
{
command.ExecuteBlind();
}
}
else
{
using (m_Connector.BlockNotificationThread())
{
try
{
// Use the extended query parsing...
planName = m_Connector.NextPlanName();
String portalName = m_Connector.NextPortalName();
parse = new NpgsqlParse(planName, GetParseCommandText(), new Int32[] { });
m_Connector.Parse(parse);
// We need that because Flush() doesn't cause backend to send
// ReadyForQuery on error. Without ReadyForQuery, we don't return
// from query extended processing.
// We could have used Connector.Flush() which sends us back a
// ReadyForQuery, but on postgresql server below 8.1 there is an error
// with extended query processing which hinders us from using it.
m_Connector.RequireReadyForQuery = false;
m_Connector.Flush();
// Description...
NpgsqlDescribe describe = new NpgsqlDescribe('S', planName);
m_Connector.Describe(describe);
NpgsqlRowDescription returnRowDesc = m_Connector.Sync();
Int16[] resultFormatCodes;
if (returnRowDesc != null)
{
resultFormatCodes = new Int16[returnRowDesc.NumFields];
for (int i = 0; i < returnRowDesc.NumFields; i++)
{
NpgsqlRowDescription.FieldData returnRowDescData = returnRowDesc[i];
if (returnRowDescData.TypeInfo != null && returnRowDescData.TypeInfo.NpgsqlDbType == NpgsqlDbType.Bytea)
{
// Binary format
resultFormatCodes[i] = (Int16)FormatCode.Binary;
}
else
{
// Text Format
resultFormatCodes[i] = (Int16)FormatCode.Text;
}
}
}
else
{
resultFormatCodes = new Int16[] { 0 };
}
bind = new NpgsqlBind("", planName, new Int16[Parameters.Count], null, resultFormatCodes);
}
catch (IOException e)
{
throw ClearPoolAndCreateException(e);
}
catch
{
// As per documentation:
// "[...] When an error is detected while processing any extended-query message,
// the backend issues ErrorResponse, then reads and discards messages until a
// Sync is reached, then issues ReadyForQuery and returns to normal message processing.[...]"
// So, send a sync command if we get any problems.
m_Connector.Sync();
throw;
}
}
}
}
/*
/// <summary>
/// Releases the resources used by the <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see>.
/// </summary>
protected override void Dispose (bool disposing)
{
if (disposing)
{
// Only if explicitly calling Close or dispose we still have access to
// managed resources.
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Dispose");
if (connection != null)
{
connection.Dispose();
}
base.Dispose(disposing);
}
}*/
///<summary>
/// This method checks the connection state to see if the connection
/// is set or it is open. If one of this conditions is not met, throws
/// an InvalidOperationException
///</summary>
private void CheckConnectionState()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "CheckConnectionState");
// Check the connection state.
if (Connector == null || Connector.State == ConnectionState.Closed)
{
throw new InvalidOperationException(resman.GetString("Exception_ConnectionNotOpen"));
}
if (Connector.State != ConnectionState.Open)
{
throw new InvalidOperationException(
"There is already an open DataReader associated with this Command which must be closed first.");
}
}
/// <summary>
/// This method substitutes the <see cref="Npgsql.NpgsqlCommand.Parameters">Parameters</see>, if exist, in the command
/// to their actual values.
/// The parameter name format is <b>:ParameterName</b>.
/// </summary>
/// <returns>A version of <see cref="Npgsql.NpgsqlCommand.CommandText">CommandText</see> with the <see cref="Npgsql.NpgsqlCommand.Parameters">Parameters</see> inserted.</returns>
internal StringBuilder GetCommandText()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetCommandText");
StringBuilder ret = string.IsNullOrEmpty(planName) ? GetClearCommandText() : GetPreparedCommandText();
// In constructing the command text, we potentially called internal
// queries. Reset command timeout and SQL sent.
m_Connector.Mediator.ResetResponses();
m_Connector.Mediator.CommandTimeout = CommandTimeout;
return ret;
}
private static void PassEscapedArray(StringBuilder query, string array)
{
bool inTextLiteral = false;
int endAt = array.Length - 1;//leave last char for separate append as we don't have to continually check we're safe to add the next char too.
for(int i = 0; i != endAt; ++i)
{
if(array[i] == '\'')
{
if(!inTextLiteral)
{
query.Append("E'");
inTextLiteral = true;
}
else if(array[i + 1] == '\'')//SQL-escaped '
{
query.Append("''");
++i;
}
else
{
query.Append('\'');
inTextLiteral = false;
}
}
else
query.Append(array[i]);
}
query.Append(array[endAt]);
}
private void PassParam(StringBuilder query, NpgsqlParameter p)
{
string serialised = p.TypeInfo.ConvertToBackend(p.Value, false);
// Add parentheses wrapping parameter value before the type cast to avoid problems with Int16.MinValue, Int32.MinValue and Int64.MinValue
// See bug #1010543
// Check if this parenthesis can be collapsed with the previous one about the array support. This way, we could use
// only one pair of parentheses for the two purposes instead of two pairs.
query.Append('(');
if(Connector.UseConformantStrings)
switch(serialised[0])
{
case '\''://type passed as string or string with type.
//We could test to see if \ is used anywhere, but then we could be doing quite an expensive check (if the value is large) for little gain.
query.Append("E").Append(serialised);
break;
case 'a':
if(POSTGRES_TEXT_ARRAY.IsMatch(serialised))
PassEscapedArray(query, serialised);
else
query.Append(serialised);
break;
default:
query.Append(serialised);
break;
}
else
query.Append(serialised);
query.Append(')');
if (p.UseCast)
{
query.Append("::").Append(p.TypeInfo.CastName);
if (p.TypeInfo.UseSize && (p.Size > 0))
query.Append('(').Append(p.Size).Append(')');
}
}
private StringBuilder GetClearCommandText()
{
if (NpgsqlEventLog.Level == LogLevel.Debug)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetClearCommandText");
}
StringBuilder result = PGUtil.TrimStringBuilder(new StringBuilder(text));
switch(type)
{
case CommandType.TableDirect:
return result.Insert(0, "select * from "); // There is no parameter support on table direct.
case CommandType.StoredProcedure:
if (!functionChecksDone)
{
functionNeedsColumnListDefinition = Parameters.Count != 0 && CheckFunctionNeedsColumnDefinitionList();
// Check if just procedure name was passed. If so, does not replace parameter names and just pass parameter values in order they were added in parameters collection. Also check if command text finishes in a ";" which would make Npgsql incorrectly append a "()" when executing this command text.
switch(result[result.Length - 1])
{
case ')' : case ';':
addProcedureParenthesis = false;
break;
default:
addProcedureParenthesis = true;
break;
}
functionChecksDone = true;