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
|
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Data;
using System.Runtime.InteropServices;
namespace IBM.Data.DB2
{
public class DB2Command : System.ComponentModel.Component, IDbCommand, ICloneable
{
#region Private data members
private WeakReference refDataReader;
private string commandText;
private CommandType commandType = CommandType.Text;
private DB2Connection db2Conn;
private DB2Transaction db2Trans;
private int commandTimeout = 30;
private bool prepared = false;
private bool binded = false;
private IntPtr hwndStmt = IntPtr.Zero; //Our statement handle
private DB2ParameterCollection parameters = new DB2ParameterCollection();
private bool disposed = false;
private bool statementOpen;
private CommandBehavior previousBehavior;
private UpdateRowSource updatedRowSource = UpdateRowSource.Both;
private IntPtr statementParametersMemory;
private int statementParametersMemorySize;
#endregion
#region Constructors
public DB2Command()
{
hwndStmt = IntPtr.Zero;
}
public DB2Command(string commandStr):this()
{
commandText = commandStr;
}
public DB2Command(string commandStr, DB2Connection con) : this()
{
db2Conn = con;
commandText = commandStr;
if(con != null)
{
con.AddCommand(this);
}
}
public DB2Command (string commandStr, DB2Connection con, DB2Transaction trans)
{
commandText = commandStr;
db2Conn = con;
db2Trans = trans;
if(con != null)
{
con.AddCommand(this);
}
}
#endregion
#region Dispose
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
ConnectionClosed();
if(db2Conn != null)
{
db2Conn.RemoveCommand(this);
db2Conn = null;
}
}
if(statementParametersMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(statementParametersMemory);
statementParametersMemory = IntPtr.Zero;
}
}
base.Dispose(disposing);
disposed = true;
}
~DB2Command()
{
Dispose(false);
}
internal void DataReaderClosed()
{
CloseStatementHandle(false);
if((previousBehavior & CommandBehavior.CloseConnection) != 0)
Connection.Close();
refDataReader = null;
}
private void CloseStatementHandle(bool dispose)
{
if(hwndStmt != IntPtr.Zero)
{
if(statementOpen)
{
short sqlRet = DB2CLIWrapper.SQLFreeStmt(hwndStmt, DB2Constants.SQL_CLOSE);
}
if((!prepared && statementOpen) ||
dispose)
{
short sqlRet = DB2CLIWrapper.SQLFreeHandle(DB2Constants.SQL_HANDLE_STMT, hwndStmt);
hwndStmt = IntPtr.Zero;
prepared = false;
}
statementOpen = false;
}
}
internal void ConnectionClosed()
{
DB2DataReader reader = null;
if((refDataReader != null) && refDataReader.IsAlive)
{
reader = (DB2DataReader)refDataReader.Target;
}
if((reader != null) && refDataReader.IsAlive)
{
reader.Dispose();
refDataReader = null;
}
CloseStatementHandle(true);
db2Trans = null;
}
#endregion
#region SelfDescribe property
///
/// Property dictates whether or not any paramter markers will get their describe info
/// from the database, or if the user will supply the information
///
bool selfDescribe = false;
public bool SelfDescribe
{
get
{
return selfDescribe;
}
set
{
selfDescribe = value;
}
}
#endregion
#region CommandText property
///
///The query; If it gets set, reset the prepared property
///
public string CommandText
{
get
{
return commandText;
}
set
{
prepared = false;
commandText = value;
}
}
#endregion
#region CommandTimeout property
///
/// The Timeout property states how long we wait for results to return
///
public int CommandTimeout
{
get
{
return commandTimeout;
}
set
{
commandTimeout = value;
if(hwndStmt != IntPtr.Zero)
SetStatementTimeout();
}
}
#endregion
#region CommandType property
public CommandType CommandType
{
get
{
return commandType;
}
set
{
commandType = value;
}
}
#endregion
#region Connection property
///
/// The connection we'll be executing on.
///
IDbConnection IDbCommand.Connection
{
get
{
return db2Conn;
}
set
{
db2Conn = (DB2Connection)value;
}
}
public DB2Connection Connection
{
get
{
return db2Conn;
}
set
{
if(db2Conn != null)
{
db2Conn.RemoveCommand(this);
}
db2Conn = value;
if(db2Conn != null)
{
db2Conn.AddCommand(this);
}
}
}
#endregion
#region Parameters property
///
/// Parameter list, Not yet implemented
///
public DB2ParameterCollection Parameters
{
get
{
return parameters;
}
}
IDataParameterCollection IDbCommand.Parameters
{
get
{
return parameters;
}
}
#endregion
#region Transaction property
///
/// The transaction this command is associated with
///
IDbTransaction IDbCommand.Transaction
{
get
{
return db2Trans;
}
set
{
db2Trans = (DB2Transaction)value;
}
}
public DB2Transaction Transaction
{
get
{
return db2Trans;
}
set
{
db2Trans = value;
}
}
#endregion
#region UpdatedRowSource property
public UpdateRowSource UpdatedRowSource
{
get { return updatedRowSource; }
set { updatedRowSource = value; }
}
#endregion
#region Statement Handle
///
/// returns the DB2Client statement handle
///
public IntPtr statementHandle
{
get
{
return hwndStmt;
}
}
#endregion
#region AllocateStatement function
internal void AllocateStatement(string location)
{
if (db2Conn.DBHandle.ToInt32() == 0) return;
short sqlRet;
sqlRet = DB2CLIWrapper.SQLAllocHandle(DB2Constants.SQL_HANDLE_STMT, db2Conn.DBHandle, out hwndStmt);
if ((sqlRet != DB2Constants.SQL_SUCCESS) && (sqlRet != DB2Constants.SQL_SUCCESS_WITH_INFO))
throw new DB2Exception(DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, location +": Unable to allocate statement handle.");
parameters.HwndStmt = hwndStmt;
SetStatementTimeout();
}
private void SetStatementTimeout()
{
short sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_QUERY_TIMEOUT, new IntPtr(commandTimeout), 0);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set statement timeout.", db2Conn);
}
#endregion
#region Cancel
/// <summary>
/// Attempt to cancel an executing command
/// </summary>
public void Cancel()
{
if(hwndStmt == IntPtr.Zero)
{
throw new InvalidOperationException("Nothing to Cancel.");
}
DB2CLIWrapper.SQLCancel(hwndStmt);
}
#endregion
#region CreateParameter
///
///Returns a parameter
///
public IDbDataParameter CreateParameter()
{
return new DB2Parameter();
}
#endregion
#region ExecuteNonQuery
public int ExecuteNonQuery()
{
ExecuteNonQueryInternal(CommandBehavior.Default);
int numRows;
//How many rows affected. numRows will be -1 if we aren't dealing with an Insert, Delete or Update, or if the statement did not execute successfully
short sqlRet = DB2CLIWrapper.SQLRowCount(hwndStmt, out numRows);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecDirect error.", db2Conn);
do
{
sqlRet = DB2CLIWrapper.SQLMoreResults(this.hwndStmt);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "DB2ClientDataReader - SQLMoreResults", db2Conn);
} while(sqlRet != DB2Constants.SQL_NO_DATA_FOUND);
CloseStatementHandle(false);
return numRows;
}
public void ExecuteNonQueryInternal(CommandBehavior behavior)
{
short sqlRet;
if(prepared && binded)
{
sqlRet = DB2CLIWrapper.SQLExecute(hwndStmt);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecute error.", db2Conn);
return;
}
if((db2Conn == null) || (db2Conn.State != ConnectionState.Open))
throw new InvalidOperationException("Prepare needs an open connection");
if((refDataReader != null) &&
(refDataReader.IsAlive))
throw new InvalidOperationException("There is already an open DataReader associated with this Connection which must be closed first.");
DB2Transaction connectionTransaction = null;
if(db2Conn.WeakRefTransaction != null)
connectionTransaction = (DB2Transaction)db2Conn.WeakRefTransaction.Target;
if(!Object.ReferenceEquals(connectionTransaction, Transaction))
{
if(Transaction == null)
throw new InvalidOperationException("A transaction was started in the connection, but the command doesn't specify a transaction");
throw new InvalidOperationException("The transaction specified at the connection doesn't belong to the connection");
}
if (hwndStmt == IntPtr.Zero)
{
AllocateStatement("InternalExecuteNonQuery");
previousBehavior = 0;
}
if(previousBehavior != behavior)
{
if(((previousBehavior ^ behavior) & CommandBehavior.SchemaOnly) != 0)
{
sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_DEFERRED_PREPARE,
new IntPtr((behavior & CommandBehavior.SchemaOnly) != 0 ? 0 : 1), 0);
// TODO: don't check. what if it is not supported???
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Defered prepare.", db2Conn);
previousBehavior = (previousBehavior & ~CommandBehavior.SchemaOnly) | (behavior & CommandBehavior.SchemaOnly);
}
if(((previousBehavior ^ behavior) & CommandBehavior.SingleRow) != 0)
{
sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_MAX_ROWS,
new IntPtr((behavior & CommandBehavior.SingleRow) == 0 ? 0 : 1), 0);
// TODO: don't check. what if it is not supported???
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set max rows", db2Conn);
previousBehavior = (previousBehavior & ~CommandBehavior.SingleRow) | (behavior & CommandBehavior.SingleRow);
}
previousBehavior = behavior;
}
if((Transaction == null) &&
!db2Conn.openConnection.autoCommit)
{
sqlRet = DB2CLIWrapper.SQLSetConnectAttr(db2Conn.DBHandle, DB2Constants.SQL_ATTR_AUTOCOMMIT, new IntPtr(DB2Constants.SQL_AUTOCOMMIT_ON), 0);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, "Error setting AUTOCOMMIT ON in transaction CTOR.", db2Conn);
db2Conn.openConnection.autoCommit = true;
sqlRet = DB2CLIWrapper.SQLSetConnectAttr(db2Conn.DBHandle, DB2Constants.SQL_ATTR_TXN_ISOLATION, new IntPtr(DB2Constants.SQL_TXN_READ_COMMITTED), 0);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, "Error setting isolation level.", db2Conn);
}
if ((commandText == null) ||(commandText.Length == 0))
throw new InvalidOperationException("Command string is empty");
if(CommandType.StoredProcedure == commandType && !commandText.StartsWith("CALL "))
commandText = "CALL " + commandText + " ()";
if((behavior & CommandBehavior.SchemaOnly) != 0)
{
if(!prepared)
{
Prepare();
}
}
else
{
if(statementParametersMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(statementParametersMemory);
statementParametersMemory = IntPtr.Zero;
}
BindParams();
if (prepared)
{
sqlRet = DB2CLIWrapper.SQLExecute(hwndStmt);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecute error.", db2Conn);
}
else
{
sqlRet = DB2CLIWrapper.SQLExecDirect(hwndStmt, commandText, commandText.Length);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecDirect error.", db2Conn);
}
statementOpen = true;
parameters.GetOutValues();
if(statementParametersMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(statementParametersMemory);
statementParametersMemory = IntPtr.Zero;
}
}
}
#endregion
#region ExecuteReader calls
///
///ExecuteReader
///
IDataReader IDbCommand.ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
public DB2DataReader ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
public DB2DataReader ExecuteReader(CommandBehavior behavior)
{
if((db2Conn == null) || (db2Conn.State != ConnectionState.Open))
throw new InvalidOperationException("Prepare needs an open connection");
DB2DataReader reader;
ExecuteNonQueryInternal(behavior);
reader = new DB2DataReader(db2Conn, this, behavior);
refDataReader = new WeakReference(reader);
return reader;
}
#endregion
#region ExecuteScalar
///
/// ExecuteScalar
///
public object ExecuteScalar()
{
if((db2Conn == null) || (db2Conn.State != ConnectionState.Open))
throw new InvalidOperationException("Prepare needs an open connection");
using(DB2DataReader reader = ExecuteReader(CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
if(reader.Read() && (reader.FieldCount > 0))
{
return reader[0];
}
}
return null;
}
#endregion
#region Prepare ()
public void Prepare ()
{
if((db2Conn == null) || (db2Conn.State != ConnectionState.Open))
throw new InvalidOperationException("Prepare needs an open connection");
CloseStatementHandle(false);
if (hwndStmt == IntPtr.Zero)
{
AllocateStatement("InternalExecuteNonQuery");
}
short sqlRet = 0;
IntPtr numParams = IntPtr.Zero;
sqlRet = DB2CLIWrapper.SQLPrepare(hwndStmt, commandText, commandText.Length);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLPrepare error.", db2Conn);
statementOpen = true;
prepared=true;
}
#endregion
private string AddCallParam( string _cmString)
{
if(_cmString.IndexOf("()") != -1)
{
return _cmString.Replace("()","(?)");
}
return _cmString.Replace(")", ",?)");
}
private void BindParams()
{
if(parameters.Count > 0)
{
statementParametersMemorySize = 0;
int offset = 0;
short sqlRet;
for(int i = 0; i < parameters.Count; i++)
{
if(commandType == CommandType.StoredProcedure)
{
commandText = AddCallParam(commandText);
}
DB2Parameter param = parameters[i];
param.CalculateRequiredmemory();
statementParametersMemorySize += param.requiredMemory + 8;
param.internalBuffer = Marshal.AllocHGlobal(param.requiredMemory);
offset += param.requiredMemory;
param.internalLengthBuffer = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(param.internalLengthBuffer, param.requiredMemory);
sqlRet = param.Bind(this.hwndStmt, (short)(i + 1));
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Error binding parameter in DB2Command: ", db2Conn);
}
binded = true;
}
}
#region ICloneable Members
object ICloneable.Clone()
{
DB2Command clone = new DB2Command();
clone.Connection = Connection;
clone.commandText = commandText;
clone.commandType = commandType;
clone.Transaction = db2Trans;
clone.commandTimeout = commandTimeout;
clone.updatedRowSource = updatedRowSource;
clone.parameters = new DB2ParameterCollection();
for(int i = 0; i < parameters.Count; i++)
clone.Parameters.Add(((ICloneable)parameters[i]).Clone());
return clone;
}
#endregion
}
}
|