forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlCommand.PrepareExecute.cs
More file actions
515 lines (439 loc) · 20.8 KB
/
NpgsqlCommand.PrepareExecute.cs
File metadata and controls
515 lines (439 loc) · 20.8 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
// created on 18/11/2013
// Npgsql.NpgsqlCommand.PrepareExecute.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;
namespace Npgsql
{
/// <summary>
/// Represents a SQL statement or function (stored procedure) to execute
/// against a PostgreSQL database. This class cannot be inherited.
/// </summary>
public sealed partial class NpgsqlCommand : DbCommand, ICloneable
{
/// <summary>
/// Internal query shortcut for use in cases where the number
/// of affected rows is of no interest.
/// </summary>
internal static void ExecuteBlind(NpgsqlConnector connector, byte[] command, int timeout = 20)
{
// Bypass cpmmand parsing overhead and send command verbatim.
ExecuteBlind(connector, NpgsqlQuery.Create(connector.BackendProtocolVersion, command), timeout);
}
/// <summary>
/// Internal query shortcut for use in cases where the number
/// of affected rows is of no interest.
/// </summary>
internal static void ExecuteBlind(NpgsqlConnector connector, string command, int timeout = 20)
{
// Bypass cpmmand parsing overhead and send command verbatim.
ExecuteBlind(connector, NpgsqlQuery.Create(connector.BackendProtocolVersion, command), timeout);
}
private static void ExecuteBlind(NpgsqlConnector connector, NpgsqlQuery query, int timeout)
{
// Block the notification thread before writing anything to the wire.
using (var blocker = connector.BlockNotificationThread())
{
// Set statement timeout as needed.
connector.SetBackendCommandTimeout(timeout);
// Write the Query message to the wire.
connector.Query(query);
// Flush, and wait for and discard all responses.
connector.ProcessAndDiscardBackendResponses();
}
}
/// <summary>
/// Special adaptation of ExecuteBlind() that sets statement_timeout.
/// This exists to prevent Connector.SetBackendCommandTimeout() from calling Command.ExecuteBlind(),
/// which will cause an endless recursive loop.
/// </summary>
/// <param name="connector"></param>
/// <param name="timeout">Timeout in seconds.</param>
internal static void ExecuteSetStatementTimeoutBlind(NpgsqlConnector connector, int timeout)
{
NpgsqlQuery query;
// Bypass cpmmand parsing overhead and send command verbatim.
query = NpgsqlQuery.Create(connector.BackendProtocolVersion, string.Format("SET statement_timeout = {0}", timeout * 1000));
// Write the Query message to the wire.
connector.Query(query);
// Flush, and wait for and discard all responses.
connector.ProcessAndDiscardBackendResponses();
}
/// <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)
{
CheckConnectionState();
// Block the notification thread before writing anything to the wire.
using (m_Connector.BlockNotificationThread())
{
IEnumerable<IServerResponseObject> responseEnum;
ForwardsOnlyDataReader reader;
m_Connector.SetBackendCommandTimeout(CommandTimeout);
if (prepared == PrepareStatus.NeedsPrepare)
{
PrepareInternal();
}
if (prepared == PrepareStatus.NotPrepared || prepared == PrepareStatus.V2Prepared)
{
NpgsqlQuery query;
byte[] commandText = GetCommandText();
query = NpgsqlQuery.Create(m_Connector.BackendProtocolVersion, commandText);
// Write the Query message to the wire.
m_Connector.Query(query);
// Tell to mediator what command is being sent.
if (prepared == PrepareStatus.NotPrepared)
{
m_Connector.Mediator.SetSqlSent(commandText, NpgsqlMediator.SQLSentType.Simple);
}
else
{
m_Connector.Mediator.SetSqlSent(preparedCommandText, NpgsqlMediator.SQLSentType.Execute);
}
// Flush and wait for responses.
responseEnum = m_Connector.ProcessBackendResponsesEnum();
// Construct the return reader.
reader = new ForwardsOnlyDataReader(
responseEnum,
cb,
this,
m_Connector.BlockNotificationThread()
);
if (
commandType == 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.
StringWriter sw = new StringWriter();
string queryText;
while (reader.Read())
{
sw.WriteLine("FETCH ALL FROM \"{0}\";", reader.GetString(0));
}
reader.Dispose();
queryText = sw.ToString();
if (queryText == "")
{
queryText = ";";
}
// Passthrough the commandtimeout to the inner command, so user can also control its timeout.
// TODO: Check if there is a better way to handle that.
query = NpgsqlQuery.Create(m_Connector.BackendProtocolVersion, queryText);
// Write the Query message to the wire.
m_Connector.Query(query);
// Flush and wait for responses.
responseEnum = m_Connector.ProcessBackendResponsesEnum();
// Construct the return reader.
reader = new ForwardsOnlyDataReader(
responseEnum,
cb,
this,
m_Connector.BlockNotificationThread()
);
}
}
else
{
// Update the Bind object with current parameter data as needed.
BindParameters();
// Write the Bind, Execute, and Sync message to the wire.
m_Connector.Bind(bind);
m_Connector.Execute(execute);
m_Connector.Sync();
// Tell to mediator what command is being sent.
m_Connector.Mediator.SetSqlSent(preparedCommandText, NpgsqlMediator.SQLSentType.Execute);
// Flush and wait for responses.
responseEnum = m_Connector.ProcessBackendResponsesEnum();
// Construct the return reader, possibly with a saved row description from Prepare().
reader = new ForwardsOnlyDataReader(
responseEnum,
cb,
this,
m_Connector.BlockNotificationThread(),
true,
currentRowDescription
);
}
return reader;
}
}
///<summary>
/// This method binds the parameters from parameters collection to the bind
/// message.
/// </summary>
private void BindParameters()
{
if (parameters.Count != 0)
{
byte[][] parameterValues = bind.ParameterValues;
Int16[] parameterFormatCodes = bind.ParameterFormatCodes;
bool bindAll = false;
bool bound = false;
if (parameterValues == null || parameterValues.Length != parameters.Count)
{
parameterValues = new byte[parameters.Count][];
bindAll = true;
}
for (Int32 i = 0; i < parameters.Count; i++)
{
if (! bindAll && parameters[i].Bound)
{
continue;
}
parameterValues[i] = parameters[i].TypeInfo.ConvertToBackend(parameters[i].Value, true, Connector.NativeToBackendTypeConverterOptions);
bound = true;
parameters[i].Bound = true;
if (parameterValues[i] == null) {
parameterFormatCodes[i]= (Int16)FormatCode.Binary;
} else {
parameterFormatCodes[i] = parameters[i].TypeInfo.SupportsBinaryBackendData ? (Int16)FormatCode.Binary : (Int16)FormatCode.Text;
}
}
if (bound)
{
bind.ParameterValues = parameterValues;
bind.ParameterFormatCodes = parameterFormatCodes;
}
}
}
/// <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;
}
}
private void UnPrepare()
{
if (prepared == PrepareStatus.V3Prepared)
{
bind = null;
execute = null;
currentRowDescription = null;
prepared = PrepareStatus.NeedsPrepare;
}
else if (prepared == PrepareStatus.V2Prepared)
{
planName = String.Empty;
prepared = PrepareStatus.NeedsPrepare;
}
preparedCommandText = 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();
if (! m_Connector.SupportsPrepare)
{
return; // Do nothing.
}
UnPrepare();
PrepareInternal();
}
private void PrepareInternal()
{
if (m_Connector.BackendProtocolVersion == ProtocolVersion.Version2)
{
planName = Connector.NextPlanName();
preparedCommandText = GetCommandText(true, false);
ExecuteBlind(m_Connector, preparedCommandText);
prepared = PrepareStatus.V2Prepared;
// Tell to mediator what command is being sent.
m_Connector.Mediator.SetSqlSent(preparedCommandText, NpgsqlMediator.SQLSentType.Prepare);
}
else
{
// Use the extended query parsing...
planName = m_Connector.NextPlanName();
String portalName = "";
preparedCommandText = GetCommandText(true, true);
NpgsqlParse parse = new NpgsqlParse(planName, preparedCommandText, new Int32[] { });
NpgsqlDescribe statementDescribe = new NpgsqlDescribeStatement(planName);
IEnumerable<IServerResponseObject> responseEnum;
NpgsqlRowDescription returnRowDesc = null;
// Write Parse, Describe, and Sync messages to the wire.
m_Connector.Parse(parse);
m_Connector.Describe(statementDescribe);
m_Connector.Sync();
// Tell to mediator what command is being sent.
m_Connector.Mediator.SetSqlSent(preparedCommandText, NpgsqlMediator.SQLSentType.Parse);
// Flush and wait for response.
responseEnum = m_Connector.ProcessBackendResponsesEnum();
// Look for a NpgsqlRowDescription in the responses, discarding everything else.
foreach (IServerResponseObject response in responseEnum)
{
if (response is NpgsqlRowDescription)
{
returnRowDesc = (NpgsqlRowDescription)response;
}
else if (response is IDisposable)
{
(response as IDisposable).Dispose();
}
}
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)
{
// Binary format?
// PG always defaults to text encoding. We can fix up the row description
// here based on support for binary encoding. Once this is done,
// there is no need to request another row description after Bind.
returnRowDescData.FormatCode = returnRowDescData.TypeInfo.SupportsBinaryBackendData ? FormatCode.Binary : FormatCode.Text;
resultFormatCodes[i] = (Int16)returnRowDescData.FormatCode;
}
else
{
// Text format (default).
resultFormatCodes[i] = (Int16)FormatCode.Text;
}
}
}
else
{
resultFormatCodes = new Int16[] { 0 };
}
// Save the row description for use with all future Executes.
currentRowDescription = returnRowDesc;
// The Bind and Execute message objects live through multiple Executes.
// Only Bind changes at all between Executes, which is done in BindParameters().
bind = new NpgsqlBind(portalName, planName, new Int16[Parameters.Count], null, resultFormatCodes);
execute = new NpgsqlExecute(portalName, 0);
prepared = PrepareStatus.V3Prepared;
}
}
}
}