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
598 lines (510 loc) · 21.2 KB
/
NpgsqlCommand.cs
File metadata and controls
598 lines (510 loc) · 21.2 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
// 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 partial class NpgsqlCommand : DbCommand, ICloneable
{
private enum PrepareStatus
{
NotPrepared,
NeedsPrepare,
Prepared
}
// Logging related values
private static readonly String CLASSNAME = MethodBase.GetCurrentMethod().DeclaringType.Name;
private static readonly ResourceManager resman = new ResourceManager(MethodBase.GetCurrentMethod().DeclaringType);
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 commandText;
private Int32 timeout;
private CommandType commandType;
private readonly NpgsqlParameterCollection parameters = new NpgsqlParameterCollection();
private String planName;
private Boolean designTimeVisible;
private PrepareStatus prepared = PrepareStatus.NotPrepared;
private byte[] preparedCommandText = null;
private NpgsqlBind bind = null;
private NpgsqlExecute execute = null;
private NpgsqlRowDescription currentRowDescription = null;
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 functionNeedsColumnListDefinition = false; // Functions don't return record by default.
private Boolean commandTimeoutSet = false;
private UpdateRowSource updateRowSource = UpdateRowSource.Both;
private static readonly Array ParamNameCharTable;
// Constructors
static NpgsqlCommand()
{
ParamNameCharTable = BuildParameterNameCharacterTable();
}
private static Array BuildParameterNameCharacterTable()
{
Array paramNameCharTable;
// Table has lower bound of (int)'.';
paramNameCharTable = Array.CreateInstance(typeof(byte), new int[] {'z' - '.' + 1}, new int[] {'.'});
paramNameCharTable.SetValue((byte)'.', (int)'.');
for (int i = '0' ; i <= '9' ; i++)
{
paramNameCharTable.SetValue((byte)i, i);
}
for (int i = 'A' ; i <= 'Z' ; i++)
{
paramNameCharTable.SetValue((byte)i, i);
}
paramNameCharTable.SetValue((byte)'_', (int)'_');
for (int i = 'a' ; i <= 'z' ; i++)
{
paramNameCharTable.SetValue((byte)i, i);
}
return paramNameCharTable;
}
/// <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;
commandText = cmdText;
this.connection = connection;
if (this.connection != null)
{
this.m_Connector = connection.Connector;
if (m_Connector != null && m_Connector.AlwaysPrepare)
{
CommandTimeout = m_Connector.DefaultCommandTimeout;
prepared = PrepareStatus.NeedsPrepare;
}
}
commandType = CommandType.Text;
this.Transaction = transaction;
SetCommandTimeout();
}
/// <summary>
/// Used to execute internal commands.
/// </summary>
internal NpgsqlCommand(String cmdText, NpgsqlConnector connector, int CommandTimeout = 20)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME);
planName = String.Empty;
commandText = cmdText;
this.m_Connector = connector;
this.CommandTimeout = CommandTimeout;
commandType = 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 commandText; }
set
{
// [TODO] Validate commandtext.
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "CommandText", value);
commandText = value;
UnPrepare();
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("value", 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 commandType; }
set
{
commandType = value;
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "CommandType", value);
}
}
/// <summary>
/// DB connection.
/// </summary>
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;
if (m_Connector != null && m_Connector.AlwaysPrepare)
{
prepared = PrepareStatus.NeedsPrepare;
}
}
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; }
/// <summary>
/// DB parameter collection.
/// </summary>
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;
}
}
/// <summary>
/// DB transaction.
/// </summary>
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>
/// 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);
}
}*/
private void SetCommandTimeout()
{
if (commandTimeoutSet)
return;
if (Connection != null)
{
timeout = Connection.CommandTimeout;
}
else
{
timeout = (int)NpgsqlConnectionStringBuilder.GetDefaultValue(Keywords.CommandTimeout);
}
}
internal NpgsqlException ClearPoolAndCreateException(Exception e)
{
Connection.ClearPool();
return new NpgsqlException(resman.GetString("Exception_ConnectionBroken"), e);
}
/// <summary>
/// Design time visible.
/// </summary>
public override bool DesignTimeVisible
{
get { return designTimeVisible; }
set { designTimeVisible = value; }
}
}
}