]> git.saurik.com Git - wxWidgets.git/blame - src/common/dbtable.cpp
Applied modified form of the StdButtonSize patch.
[wxWidgets.git] / src / common / dbtable.cpp
CommitLineData
108106cf 1///////////////////////////////////////////////////////////////////////////////
1fc5dd6f 2// Name: dbtable.cpp
f6bcfd97 3// Purpose: Implementation of the wxDbTable class.
108106cf 4// Author: Doug Card
67e9aaa3 5// Modified by: George Tasker
3ca6a5f0
BP
6// Bart Jourquin
7// Mark Johnson
108106cf
JS
8// Created: 9.96
9// RCS-ID: $Id$
10// Copyright: (c) 1996 Remstar International, Inc.
7e559cd8 11// Licence: wxWindows licence
108106cf
JS
12///////////////////////////////////////////////////////////////////////////////
13
14/*
15// SYNOPSIS START
16// SYNOPSIS STOP
17*/
e7c9692f 18
14f355c2 19#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
882fc8a9
GT
20 #pragma implementation "dbtable.h"
21#endif
108106cf 22
a2115c88
GT
23#include "wx/wxprec.h"
24
882fc8a9
GT
25#ifdef __BORLANDC__
26 #pragma hdrstop
108106cf 27#endif
108106cf 28
0b8410f3 29#ifdef DBDEBUG_CONSOLE
4888e623
GT
30#if wxUSE_IOSTREAMH
31 #include <iostream.h>
32#else
33 #include <iostream>
34#endif
0b8410f3
GT
35 #include "wx/ioswrap.h"
36#endif
108106cf 37
882fc8a9
GT
38#ifndef WX_PRECOMP
39 #include "wx/string.h"
40 #include "wx/object.h"
41 #include "wx/list.h"
42 #include "wx/utils.h"
882fc8a9 43 #include "wx/log.h"
a2115c88 44#endif
882fc8a9 45#include "wx/filefn.h"
f6bcfd97 46
a2115c88 47#if wxUSE_ODBC
108106cf
JS
48
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
67e9aaa3 52
882fc8a9 53#include "wx/dbtable.h"
108106cf 54
1fc5dd6f 55#ifdef __UNIX__
108106cf
JS
56// The HPUX preprocessor lines below were commented out on 8/20/97
57// because macros.h currently redefines DEBUG and is unneeded.
58// # ifdef HPUX
59// # include <macros.h>
60// # endif
1fc5dd6f 61# ifdef LINUX
108106cf
JS
62# include <sys/minmax.h>
63# endif
64#endif
65
a2115c88
GT
66ULONG lastTableID = 0;
67
68
e041ce57 69#ifdef __WXDEBUG__
89894079 70 wxList TablesInUse;
a2115c88
GT
71#endif
72
73
8a39593e 74void csstrncpyt(wxChar *target, const wxChar *source, int n)
e7c9692f
GT
75{
76 while ( (*target++ = *source++) != '\0' && --n )
77 ;
78
79 *target = '\0';
80}
81
82
83
da99271d
GT
84/********** wxDbColDef::wxDbColDef() Constructor **********/
85wxDbColDef::wxDbColDef()
86{
87 Initialize();
88} // Constructor
89
90
91bool wxDbColDef::Initialize()
92{
93 ColName[0] = 0;
94 DbDataType = DB_DATA_TYPE_INTEGER;
95 SqlCtype = SQL_C_LONG;
96 PtrDataObj = NULL;
97 SzDataObj = 0;
68379eaf
WS
98 KeyField = false;
99 Updateable = false;
100 InsertAllowed = false;
101 DerivedCol = false;
da99271d 102 CbValue = 0;
68379eaf 103 Null = false;
da99271d 104
68379eaf 105 return true;
da99271d
GT
106} // wxDbColDef::Initialize()
107
108
109/********** wxDbTable::wxDbTable() Constructor **********/
6b3f4fb8 110wxDbTable::wxDbTable(wxDb *pwxDb, const wxString &tblName, const UWORD numColumns,
4fdae997 111 const wxString &qryTblName, bool qryOnly, const wxString &tblPath)
108106cf 112{
6b3f4fb8 113 if (!initialize(pwxDb, tblName, numColumns, qryTblName, qryOnly, tblPath))
4fdae997
GT
114 cleanup();
115} // wxDbTable::wxDbTable()
116
117
118/***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
254a2129 119#if WXWIN_COMPATIBILITY_2_4
6b3f4fb8 120wxDbTable::wxDbTable(wxDb *pwxDb, const wxString &tblName, const UWORD numColumns,
4fdae997
GT
121 const wxChar *qryTblName, bool qryOnly, const wxString &tblPath)
122{
123 wxString tempQryTblName;
124 tempQryTblName = qryTblName;
6b3f4fb8 125 if (!initialize(pwxDb, tblName, numColumns, tempQryTblName, qryOnly, tblPath))
4fdae997
GT
126 cleanup();
127} // wxDbTable::wxDbTable()
254a2129 128#endif // WXWIN_COMPATIBILITY_2_4
4fdae997
GT
129
130
131/********** wxDbTable::~wxDbTable() **********/
132wxDbTable::~wxDbTable()
133{
134 this->cleanup();
135} // wxDbTable::~wxDbTable()
136
137
6b3f4fb8 138bool wxDbTable::initialize(wxDb *pwxDb, const wxString &tblName, const UWORD numColumns,
4fdae997
GT
139 const wxString &qryTblName, bool qryOnly, const wxString &tblPath)
140{
141 // Initializing member variables
f6bcfd97 142 pDb = pwxDb; // Pointer to the wxDb object
89894079
VZ
143 henv = 0;
144 hdbc = 0;
145 hstmt = 0;
882fc8a9 146 m_hstmtGridQuery = 0;
89894079
VZ
147 hstmtDefault = 0; // Initialized below
148 hstmtCount = 0; // Initialized first time it is needed
149 hstmtInsert = 0;
150 hstmtDelete = 0;
151 hstmtUpdate = 0;
152 hstmtInternal = 0;
153 colDefs = 0;
154 tableID = 0;
b8032740 155 m_numCols = numColumns; // Number of columns in the table
4fdae997
GT
156 where.Empty(); // Where clause
157 orderBy.Empty(); // Order By clause
158 from.Empty(); // From clause
68379eaf 159 selectForUpdate = false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
89894079 160 queryOnly = qryOnly;
68379eaf 161 insertable = true;
4fdae997
GT
162 tablePath.Empty();
163 tableName.Empty();
164 queryTableName.Empty();
89894079 165
4fdae997
GT
166 wxASSERT(tblName.Length());
167 wxASSERT(pDb);
89894079 168
4fdae997 169 if (!pDb)
68379eaf 170 return false;
4fdae997
GT
171
172 tableName = tblName; // Table Name
215a0070
GT
173 if ((pDb->Dbms() == dbmsORACLE) ||
174 (pDb->Dbms() == dbmsFIREBIRD) ||
175 (pDb->Dbms() == dbmsINTERBASE))
176 tableName = tableName.Upper();
177
4fdae997
GT
178 if (tblPath.Length())
179 tablePath = tblPath; // Table Path - used for dBase files
f02d4a64 180 else
4fdae997 181 tablePath.Empty();
da38429d 182
4fdae997
GT
183 if (qryTblName.Length()) // Name of the table/view to query
184 queryTableName = qryTblName;
89894079 185 else
4fdae997 186 queryTableName = tblName;
da38429d 187
215a0070
GT
188 if ((pDb->Dbms() == dbmsORACLE) ||
189 (pDb->Dbms() == dbmsFIREBIRD) ||
190 (pDb->Dbms() == dbmsINTERBASE))
191 queryTableName = queryTableName.Upper();
192
f6bcfd97 193 pDb->incrementTableCount();
da38429d 194
1e92909e 195 wxString s;
89894079 196 tableID = ++lastTableID;
7d8c3dba 197 s.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName.c_str(), tableID, pDb);
9082f1a9 198
e041ce57 199#ifdef __WXDEBUG__
8128349e
GT
200 wxTablesInUse *tableInUse;
201 tableInUse = new wxTablesInUse();
89894079 202 tableInUse->tableName = tblName;
1e92909e
GT
203 tableInUse->tableID = tableID;
204 tableInUse->pDb = pDb;
89894079 205 TablesInUse.Append(tableInUse);
a2115c88 206#endif
da38429d 207
4fdae997 208 pDb->WriteSqlLog(s);
da38429d 209
f6bcfd97
BP
210 // Grab the HENV and HDBC from the wxDb object
211 henv = pDb->GetHENV();
212 hdbc = pDb->GetHDBC();
da38429d 213
89894079 214 // Allocate space for column definitions
b8032740
GT
215 if (m_numCols)
216 colDefs = new wxDbColDef[m_numCols]; // Points to the first column definition
da38429d 217
89894079
VZ
218 // Allocate statement handles for the table
219 if (!queryOnly)
220 {
221 // Allocate a separate statement handle for performing inserts
222 if (SQLAllocStmt(hdbc, &hstmtInsert) != SQL_SUCCESS)
223 pDb->DispAllErrors(henv, hdbc);
224 // Allocate a separate statement handle for performing deletes
225 if (SQLAllocStmt(hdbc, &hstmtDelete) != SQL_SUCCESS)
226 pDb->DispAllErrors(henv, hdbc);
227 // Allocate a separate statement handle for performing updates
228 if (SQLAllocStmt(hdbc, &hstmtUpdate) != SQL_SUCCESS)
229 pDb->DispAllErrors(henv, hdbc);
230 }
231 // Allocate a separate statement handle for internal use
232 if (SQLAllocStmt(hdbc, &hstmtInternal) != SQL_SUCCESS)
233 pDb->DispAllErrors(henv, hdbc);
da38429d 234
89894079
VZ
235 // Set the cursor type for the statement handles
236 cursorType = SQL_CURSOR_STATIC;
da38429d 237
89894079 238 if (SQLSetStmtOption(hstmtInternal, SQL_CURSOR_TYPE, cursorType) != SQL_SUCCESS)
da38429d 239 {
89894079
VZ
240 // Check to see if cursor type is supported
241 pDb->GetNextError(henv, hdbc, hstmtInternal);
4fdae997 242 if (! wxStrcmp(pDb->sqlState, wxT("01S02"))) // Option Value Changed
3ca6a5f0 243 {
89894079
VZ
244 // Datasource does not support static cursors. Driver
245 // will substitute a cursor type. Call SQLGetStmtOption()
246 // to determine which cursor type was selected.
247 if (SQLGetStmtOption(hstmtInternal, SQL_CURSOR_TYPE, &cursorType) != SQL_SUCCESS)
3ca6a5f0 248 pDb->DispAllErrors(henv, hdbc, hstmtInternal);
a2115c88 249#ifdef DBDEBUG_CONSOLE
4fdae997 250 cout << wxT("Static cursor changed to: ");
89894079 251 switch(cursorType)
3ca6a5f0
BP
252 {
253 case SQL_CURSOR_FORWARD_ONLY:
4fdae997 254 cout << wxT("Forward Only");
3ca6a5f0
BP
255 break;
256 case SQL_CURSOR_STATIC:
4fdae997 257 cout << wxT("Static");
3ca6a5f0
BP
258 break;
259 case SQL_CURSOR_KEYSET_DRIVEN:
4fdae997 260 cout << wxT("Keyset Driven");
3ca6a5f0
BP
261 break;
262 case SQL_CURSOR_DYNAMIC:
4fdae997 263 cout << wxT("Dynamic");
3ca6a5f0
BP
264 break;
265 }
89894079 266 cout << endl << endl;
108106cf 267#endif
3ca6a5f0
BP
268 // BJO20000425
269 if (pDb->FwdOnlyCursors() && cursorType != SQL_CURSOR_FORWARD_ONLY)
270 {
271 // Force the use of a forward only cursor...
272 cursorType = SQL_CURSOR_FORWARD_ONLY;
273 if (SQLSetStmtOption(hstmtInternal, SQL_CURSOR_TYPE, cursorType) != SQL_SUCCESS)
274 {
275 // Should never happen
276 pDb->GetNextError(henv, hdbc, hstmtInternal);
68379eaf 277 return false;
3ca6a5f0
BP
278 }
279 }
280 }
281 else
282 {
89894079
VZ
283 pDb->DispNextError();
284 pDb->DispAllErrors(henv, hdbc, hstmtInternal);
3ca6a5f0 285 }
89894079 286 }
a2115c88 287#ifdef DBDEBUG_CONSOLE
89894079 288 else
4fdae997 289 cout << wxT("Cursor Type set to STATIC") << endl << endl;
108106cf 290#endif
da38429d 291
89894079
VZ
292 if (!queryOnly)
293 {
294 // Set the cursor type for the INSERT statement handle
295 if (SQLSetStmtOption(hstmtInsert, SQL_CURSOR_TYPE, SQL_CURSOR_FORWARD_ONLY) != SQL_SUCCESS)
296 pDb->DispAllErrors(henv, hdbc, hstmtInsert);
297 // Set the cursor type for the DELETE statement handle
298 if (SQLSetStmtOption(hstmtDelete, SQL_CURSOR_TYPE, SQL_CURSOR_FORWARD_ONLY) != SQL_SUCCESS)
299 pDb->DispAllErrors(henv, hdbc, hstmtDelete);
300 // Set the cursor type for the UPDATE statement handle
301 if (SQLSetStmtOption(hstmtUpdate, SQL_CURSOR_TYPE, SQL_CURSOR_FORWARD_ONLY) != SQL_SUCCESS)
302 pDb->DispAllErrors(henv, hdbc, hstmtUpdate);
303 }
da38429d 304
89894079 305 // Make the default cursor the active cursor
68379eaf 306 hstmtDefault = GetNewCursor(false,false);
4fdae997 307 wxASSERT(hstmtDefault);
89894079 308 hstmt = *hstmtDefault;
108106cf 309
68379eaf 310 return true;
67e9aaa3 311
4fdae997
GT
312} // wxDbTable::initialize()
313
314
315void wxDbTable::cleanup()
108106cf 316{
1e92909e 317 wxString s;
89894079
VZ
318 if (pDb)
319 {
7d8c3dba 320 s.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName.c_str(), tableID, pDb);
4fdae997 321 pDb->WriteSqlLog(s);
89894079 322 }
a2115c88 323
e041ce57 324#ifdef __WXDEBUG__
89894079
VZ
325 if (tableID)
326 {
68379eaf 327 bool found = false;
1e92909e 328
e3f8f04d 329 wxList::compatibility_iterator pNode;
52410d54 330 pNode = TablesInUse.GetFirst();
89894079
VZ
331 while (pNode && !found)
332 {
52410d54 333 if (((wxTablesInUse *)pNode->GetData())->tableID == tableID)
89894079 334 {
68379eaf 335 found = true;
e3f8f04d
MB
336 delete (wxTablesInUse *)pNode->GetData();
337 TablesInUse.Erase(pNode);
89894079
VZ
338 }
339 else
52410d54 340 pNode = pNode->GetNext();
89894079
VZ
341 }
342 if (!found)
343 {
1e92909e 344 wxString msg;
597fadce 345 msg.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s.c_str());
4fdae997 346 wxLogDebug (msg,wxT("NOTICE..."));
89894079
VZ
347 }
348 }
a2115c88 349#endif
e041ce57 350
f6bcfd97 351 // Decrement the wxDb table count
89894079 352 if (pDb)
f6bcfd97 353 pDb->decrementTableCount();
89894079
VZ
354
355 // Delete memory allocated for column definitions
356 if (colDefs)
357 delete [] colDefs;
358
359 // Free statement handles
360 if (!queryOnly)
361 {
362 if (hstmtInsert)
7d8c3dba
GT
363 {
364/*
365ODBC 3.0 says to use this form
366 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
367*/
89894079
VZ
368 if (SQLFreeStmt(hstmtInsert, SQL_DROP) != SQL_SUCCESS)
369 pDb->DispAllErrors(henv, hdbc);
7d8c3dba 370 }
7c5c05ae 371
89894079 372 if (hstmtDelete)
7d8c3dba
GT
373 {
374/*
375ODBC 3.0 says to use this form
376 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
377*/
89894079 378 if (SQLFreeStmt(hstmtDelete, SQL_DROP) != SQL_SUCCESS)
7d8c3dba
GT
379 pDb->DispAllErrors(henv, hdbc);
380 }
7c5c05ae 381
89894079 382 if (hstmtUpdate)
7d8c3dba
GT
383 {
384/*
385ODBC 3.0 says to use this form
386 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
387*/
89894079
VZ
388 if (SQLFreeStmt(hstmtUpdate, SQL_DROP) != SQL_SUCCESS)
389 pDb->DispAllErrors(henv, hdbc);
7d8c3dba 390 }
89894079 391 }
3ca6a5f0 392
89894079 393 if (hstmtInternal)
7d8c3dba 394 {
89894079
VZ
395 if (SQLFreeStmt(hstmtInternal, SQL_DROP) != SQL_SUCCESS)
396 pDb->DispAllErrors(henv, hdbc);
7d8c3dba 397 }
89894079
VZ
398
399 // Delete dynamically allocated cursors
400 if (hstmtDefault)
401 DeleteCursor(hstmtDefault);
7c5c05ae 402
89894079
VZ
403 if (hstmtCount)
404 DeleteCursor(hstmtCount);
882fc8a9
GT
405
406 if (m_hstmtGridQuery)
407 DeleteCursor(m_hstmtGridQuery);
408
4fdae997 409} // wxDbTable::cleanup()
67e9aaa3
GT
410
411
6919c53f
GT
412/***************************** PRIVATE FUNCTIONS *****************************/
413
67e9aaa3 414
0907ea9c 415void wxDbTable::setCbValueForColumn(int columnIndex)
e9ed92a2
GT
416{
417 switch(colDefs[columnIndex].DbDataType)
418 {
419 case DB_DATA_TYPE_VARCHAR:
420 if (colDefs[columnIndex].Null)
421 colDefs[columnIndex].CbValue = SQL_NULL_DATA;
422 else
423 colDefs[columnIndex].CbValue = SQL_NTS;
424 break;
425 case DB_DATA_TYPE_INTEGER:
426 if (colDefs[columnIndex].Null)
427 colDefs[columnIndex].CbValue = SQL_NULL_DATA;
428 else
429 colDefs[columnIndex].CbValue = 0;
430 break;
431 case DB_DATA_TYPE_FLOAT:
432 if (colDefs[columnIndex].Null)
433 colDefs[columnIndex].CbValue = SQL_NULL_DATA;
434 else
435 colDefs[columnIndex].CbValue = 0;
436 break;
437 case DB_DATA_TYPE_DATE:
438 if (colDefs[columnIndex].Null)
439 colDefs[columnIndex].CbValue = SQL_NULL_DATA;
440 else
441 colDefs[columnIndex].CbValue = 0;
442 break;
443 case DB_DATA_TYPE_BLOB:
444 if (colDefs[columnIndex].Null)
445 colDefs[columnIndex].CbValue = SQL_NULL_DATA;
446 else
e4e45573 447 if (colDefs[columnIndex].SqlCtype == SQL_C_WXCHAR)
fd9b9198 448 colDefs[columnIndex].CbValue = SQL_NTS;
e9ed92a2
GT
449 else
450 colDefs[columnIndex].CbValue = SQL_LEN_DATA_AT_EXEC(colDefs[columnIndex].SzDataObj);
451 break;
452 }
453}
454
2beca662 455/********** wxDbTable::bindParams() **********/
4fdae997 456bool wxDbTable::bindParams(bool forUpdate)
6919c53f 457{
4fdae997 458 wxASSERT(!queryOnly);
89894079 459 if (queryOnly)
68379eaf 460 return false;
da38429d 461
89894079 462 SWORD fSqlType = 0;
d171743e 463 SDWORD precision = 0;
89894079 464 SWORD scale = 0;
da38429d 465
4fdae997
GT
466 // Bind each column of the table that should be bound
467 // to a parameter marker
6b3f4fb8 468 int i;
b8032740 469 UWORD colNumber;
2beca662 470
b8032740 471 for (i=0, colNumber=1; i < m_numCols; i++)
89894079 472 {
4fdae997 473 if (forUpdate)
89894079 474 {
2beca662 475 if (!colDefs[i].Updateable)
4fdae997 476 continue;
89894079 477 }
4fdae997 478 else
3ca6a5f0 479 {
2beca662 480 if (!colDefs[i].InsertAllowed)
4fdae997 481 continue;
3ca6a5f0 482 }
6919c53f 483
89894079
VZ
484 switch(colDefs[i].DbDataType)
485 {
3ca6a5f0
BP
486 case DB_DATA_TYPE_VARCHAR:
487 fSqlType = pDb->GetTypeInfVarchar().FsqlType;
488 precision = colDefs[i].SzDataObj;
489 scale = 0;
3ca6a5f0
BP
490 break;
491 case DB_DATA_TYPE_INTEGER:
492 fSqlType = pDb->GetTypeInfInteger().FsqlType;
493 precision = pDb->GetTypeInfInteger().Precision;
494 scale = 0;
3ca6a5f0
BP
495 break;
496 case DB_DATA_TYPE_FLOAT:
497 fSqlType = pDb->GetTypeInfFloat().FsqlType;
498 precision = pDb->GetTypeInfFloat().Precision;
da38429d 499 scale = pDb->GetTypeInfFloat().MaximumScale;
3ca6a5f0
BP
500 // SQL Sybase Anywhere v5.5 returned a negative number for the
501 // MaxScale. This caused ODBC to kick out an error on ibscale.
502 // I check for this here and set the scale = precision.
503 //if (scale < 0)
504 // scale = (short) precision;
3ca6a5f0
BP
505 break;
506 case DB_DATA_TYPE_DATE:
507 fSqlType = pDb->GetTypeInfDate().FsqlType;
508 precision = pDb->GetTypeInfDate().Precision;
509 scale = 0;
3ca6a5f0 510 break;
bf5423ea
GT
511 case DB_DATA_TYPE_BLOB:
512 fSqlType = pDb->GetTypeInfBlob().FsqlType;
c9b6d796 513 precision = colDefs[i].SzDataObj;
bf5423ea 514 scale = 0;
bf5423ea 515 break;
3ca6a5f0 516 }
e9ed92a2
GT
517
518 setCbValueForColumn(i);
519
4fdae997
GT
520 if (forUpdate)
521 {
b8032740 522 if (SQLBindParameter(hstmtUpdate, colNumber++, SQL_PARAM_INPUT, colDefs[i].SqlCtype,
da38429d 523 fSqlType, precision, scale, (UCHAR*) colDefs[i].PtrDataObj,
4fdae997
GT
524 precision+1, &colDefs[i].CbValue) != SQL_SUCCESS)
525 {
526 return(pDb->DispAllErrors(henv, hdbc, hstmtUpdate));
527 }
528 }
529 else
3ca6a5f0 530 {
b8032740 531 if (SQLBindParameter(hstmtInsert, colNumber++, SQL_PARAM_INPUT, colDefs[i].SqlCtype,
da38429d 532 fSqlType, precision, scale, (UCHAR*) colDefs[i].PtrDataObj,
c9b6d796 533 precision+1, &colDefs[i].CbValue) != SQL_SUCCESS)
4fdae997
GT
534 {
535 return(pDb->DispAllErrors(henv, hdbc, hstmtInsert));
536 }
89894079 537 }
89894079 538 }
da38429d 539
89894079 540 // Completed successfully
68379eaf 541 return true;
6919c53f 542
4fdae997
GT
543} // wxDbTable::bindParams()
544
545
546/********** wxDbTable::bindInsertParams() **********/
547bool wxDbTable::bindInsertParams(void)
548{
68379eaf 549 return bindParams(false);
4fdae997
GT
550} // wxDbTable::bindInsertParams()
551
552
553/********** wxDbTable::bindUpdateParams() **********/
554bool wxDbTable::bindUpdateParams(void)
555{
68379eaf 556 return bindParams(true);
f6bcfd97 557} // wxDbTable::bindUpdateParams()
6919c53f 558
67e9aaa3 559
f6bcfd97
BP
560/********** wxDbTable::bindCols() **********/
561bool wxDbTable::bindCols(HSTMT cursor)
6919c53f 562{
9d943681
GT
563 static SDWORD cb;
564
89894079 565 // Bind each column of the table to a memory address for fetching data
6b3f4fb8 566 UWORD i;
b8032740 567 for (i = 0; i < m_numCols; i++)
3ca6a5f0 568 {
9d943681 569 cb = colDefs[i].CbValue;
6b3f4fb8 570 if (SQLBindCol(cursor, (UWORD)(i+1), colDefs[i].SqlCtype, (UCHAR*) colDefs[i].PtrDataObj,
9d943681 571 colDefs[i].SzDataObj, &cb ) != SQL_SUCCESS)
3ca6a5f0 572 return (pDb->DispAllErrors(henv, hdbc, cursor));
3ca6a5f0 573 }
89894079
VZ
574
575 // Completed successfully
68379eaf 576 return true;
6919c53f 577
f6bcfd97 578} // wxDbTable::bindCols()
6919c53f 579
67e9aaa3 580
f6bcfd97
BP
581/********** wxDbTable::getRec() **********/
582bool wxDbTable::getRec(UWORD fetchType)
6919c53f 583{
89894079
VZ
584 RETCODE retcode;
585
586 if (!pDb->FwdOnlyCursors())
587 {
588 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
589 UDWORD cRowsFetched;
590 UWORD rowStatus;
591
592 retcode = SQLExtendedFetch(hstmt, fetchType, 0, &cRowsFetched, &rowStatus);
5a226de0 593 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
3ca6a5f0 594 {
89894079 595 if (retcode == SQL_NO_DATA_FOUND)
68379eaf 596 return false;
89894079
VZ
597 else
598 return(pDb->DispAllErrors(henv, hdbc, hstmt));
3ca6a5f0 599 }
f02d4a64
GT
600 else
601 {
602 // Set the Null member variable to indicate the Null state
603 // of each column just read in.
604 int i;
b8032740 605 for (i = 0; i < m_numCols; i++)
f02d4a64
GT
606 colDefs[i].Null = (colDefs[i].CbValue == SQL_NULL_DATA);
607 }
89894079
VZ
608 }
609 else
610 {
611 // Fetch the next record from the record set
612 retcode = SQLFetch(hstmt);
613 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
614 {
615 if (retcode == SQL_NO_DATA_FOUND)
68379eaf 616 return false;
89894079
VZ
617 else
618 return(pDb->DispAllErrors(henv, hdbc, hstmt));
619 }
f02d4a64
GT
620 else
621 {
622 // Set the Null member variable to indicate the Null state
623 // of each column just read in.
624 int i;
b8032740 625 for (i = 0; i < m_numCols; i++)
f02d4a64
GT
626 colDefs[i].Null = (colDefs[i].CbValue == SQL_NULL_DATA);
627 }
89894079
VZ
628 }
629
630 // Completed successfully
68379eaf 631 return true;
6919c53f 632
f6bcfd97 633} // wxDbTable::getRec()
6919c53f 634
67e9aaa3 635
f6bcfd97 636/********** wxDbTable::execDelete() **********/
4fdae997 637bool wxDbTable::execDelete(const wxString &pSqlStmt)
6919c53f 638{
2beca662
GT
639 RETCODE retcode;
640
89894079 641 // Execute the DELETE statement
8a39593e 642 retcode = SQLExecDirect(hstmtDelete, (SQLTCHAR FAR *) pSqlStmt.c_str(), SQL_NTS);
6919c53f 643
2beca662
GT
644 if (retcode == SQL_SUCCESS ||
645 retcode == SQL_NO_DATA_FOUND ||
646 retcode == SQL_SUCCESS_WITH_INFO)
647 {
648 // Record deleted successfully
68379eaf 649 return true;
2beca662
GT
650 }
651
652 // Problem deleting record
653 return(pDb->DispAllErrors(henv, hdbc, hstmtDelete));
6919c53f 654
f6bcfd97 655} // wxDbTable::execDelete()
6919c53f 656
67e9aaa3 657
f6bcfd97 658/********** wxDbTable::execUpdate() **********/
4fdae997 659bool wxDbTable::execUpdate(const wxString &pSqlStmt)
6919c53f 660{
2beca662
GT
661 RETCODE retcode;
662
89894079 663 // Execute the UPDATE statement
8a39593e 664 retcode = SQLExecDirect(hstmtUpdate, (SQLTCHAR FAR *) pSqlStmt.c_str(), SQL_NTS);
6919c53f 665
2beca662
GT
666 if (retcode == SQL_SUCCESS ||
667 retcode == SQL_NO_DATA_FOUND ||
668 retcode == SQL_SUCCESS_WITH_INFO)
669 {
670 // Record updated successfully
68379eaf 671 return true;
2beca662 672 }
5962bdb8
JS
673 else if (retcode == SQL_NEED_DATA)
674 {
675 PTR pParmID;
8a39593e
JS
676 retcode = SQLParamData(hstmtUpdate, &pParmID);
677 while (retcode == SQL_NEED_DATA)
5962bdb8
JS
678 {
679 // Find the parameter
680 int i;
b8032740 681 for (i=0; i < m_numCols; i++)
5962bdb8
JS
682 {
683 if (colDefs[i].PtrDataObj == pParmID)
684 {
685 // We found it. Store the parameter.
686 retcode = SQLPutData(hstmtUpdate, pParmID, colDefs[i].SzDataObj);
687 if (retcode != SQL_SUCCESS)
688 {
689 pDb->DispNextError();
690 return pDb->DispAllErrors(henv, hdbc, hstmtUpdate);
691 }
692 break;
693 }
694 }
c9b6d796 695 retcode = SQLParamData(hstmtUpdate, &pParmID);
5962bdb8
JS
696 }
697 if (retcode == SQL_SUCCESS ||
698 retcode == SQL_NO_DATA_FOUND ||
699 retcode == SQL_SUCCESS_WITH_INFO)
700 {
701 // Record updated successfully
68379eaf 702 return true;
5962bdb8
JS
703 }
704 }
2beca662
GT
705
706 // Problem updating record
707 return(pDb->DispAllErrors(henv, hdbc, hstmtUpdate));
6919c53f 708
f6bcfd97 709} // wxDbTable::execUpdate()
6919c53f 710
67e9aaa3 711
f6bcfd97 712/********** wxDbTable::query() **********/
4fdae997 713bool wxDbTable::query(int queryType, bool forUpdate, bool distinct, const wxString &pSqlStmt)
6919c53f 714{
4fdae997 715 wxString sqlStmt;
6919c53f 716
89894079
VZ
717 if (forUpdate)
718 // The user may wish to select for update, but the DBMS may not be capable
719 selectForUpdate = CanSelectForUpdate();
720 else
68379eaf 721 selectForUpdate = false;
6919c53f 722
89894079
VZ
723 // Set the SQL SELECT string
724 if (queryType != DB_SELECT_STATEMENT) // A select statement was not passed in,
3ca6a5f0 725 { // so generate a select statement.
f6bcfd97 726 BuildSelectStmt(sqlStmt, queryType, distinct);
89894079 727 pDb->WriteSqlLog(sqlStmt);
3ca6a5f0 728 }
e93a3a18 729
89894079 730 // Make sure the cursor is closed first
e93a3a18 731 if (!CloseCursor(hstmt))
68379eaf 732 return false;
6919c53f 733
89894079 734 // Execute the SQL SELECT statement
da38429d 735 int retcode;
8a39593e 736 retcode = SQLExecDirect(hstmt, (SQLTCHAR FAR *) (queryType == DB_SELECT_STATEMENT ? pSqlStmt.c_str() : sqlStmt.c_str()), SQL_NTS);
89894079 737 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
3ca6a5f0 738 return(pDb->DispAllErrors(henv, hdbc, hstmt));
6919c53f 739
89894079 740 // Completed successfully
68379eaf 741 return true;
6919c53f 742
f6bcfd97 743} // wxDbTable::query()
6919c53f
GT
744
745
67e9aaa3
GT
746/***************************** PUBLIC FUNCTIONS *****************************/
747
6919c53f 748
f6bcfd97 749/********** wxDbTable::Open() **********/
1454d4e6 750bool wxDbTable::Open(bool checkPrivileges, bool checkTableExists)
108106cf 751{
89894079 752 if (!pDb)
68379eaf 753 return false;
3ca6a5f0 754
89894079 755 int i;
1e92909e 756 wxString sqlStmt;
f02d4a64 757 wxString s;
882fc8a9
GT
758// int NumKeyCols=0;
759
760 // Calculate the maximum size of the concatenated
761 // keys for use with wxDbGrid
762 m_keysize = 0;
b8032740 763 for (i=0; i < m_numCols; i++)
882fc8a9
GT
764 {
765 if (colDefs[i].KeyField)
766 {
767// NumKeyCols++;
768 m_keysize += colDefs[i].SzDataObj;
769 }
770 }
89894079 771
4fdae997 772 s.Empty();
38ae3a10
GT
773
774 bool exists = true;
775 if (checkTableExists)
776 {
777 if (pDb->Dbms() == dbmsPOSTGRES)
778 exists = pDb->TableExists(tableName, NULL, tablePath);
779 else
780 exists = pDb->TableExists(tableName, pDb->GetUsername(), tablePath);
781 }
782
89894079 783 // Verify that the table exists in the database
38ae3a10 784 if (!exists)
89894079 785 {
4fdae997
GT
786 s = wxT("Table/view does not exist in the database");
787 if ( *(pDb->dbInf.accessibleTables) == wxT('Y'))
788 s += wxT(", or you have no permissions.\n");
e16143f6 789 else
4fdae997 790 s += wxT(".\n");
f02d4a64
GT
791 }
792 else if (checkPrivileges)
793 {
794 // Verify the user has rights to access the table.
d8d26772
WS
795 bool hasPrivs wxDUMMY_INITIALIZE(true);
796
38ae3a10
GT
797 if (pDb->Dbms() == dbmsPOSTGRES)
798 hasPrivs = pDb->TablePrivileges(tableName, wxT("SELECT"), pDb->GetUsername(), NULL, tablePath);
799 else
800 hasPrivs = pDb->TablePrivileges(tableName, wxT("SELECT"), pDb->GetUsername(), pDb->GetUsername(), tablePath);
801
802 if (!hasPrivs)
e4e45573 803 s = wxT("Connecting user does not have sufficient privileges to access this table.\n");
f02d4a64
GT
804 }
805
d8d26772 806 if (!s.empty())
f02d4a64
GT
807 {
808 wxString p;
809
d8d26772 810 if (!tablePath.empty())
7d8c3dba 811 p.Printf(wxT("Error opening '%s/%s'.\n"),tablePath.c_str(),tableName.c_str());
e16143f6 812 else
7d8c3dba 813 p.Printf(wxT("Error opening '%s'.\n"), tableName.c_str());
f02d4a64
GT
814
815 p += s;
816 pDb->LogError(p.GetData());
817
68379eaf 818 return false;
89894079
VZ
819 }
820
821 // Bind the member variables for field exchange between
f6bcfd97 822 // the wxDbTable object and the ODBC record.
89894079
VZ
823 if (!queryOnly)
824 {
825 if (!bindInsertParams()) // Inserts
68379eaf 826 return false;
da38429d 827
89894079 828 if (!bindUpdateParams()) // Updates
68379eaf 829 return false;
89894079 830 }
3ca6a5f0 831
89894079 832 if (!bindCols(*hstmtDefault)) // Selects
68379eaf 833 return false;
da38429d 834
89894079 835 if (!bindCols(hstmtInternal)) // Internal use only
68379eaf 836 return false;
f02d4a64
GT
837
838 /*
89894079
VZ
839 * Do NOT bind the hstmtCount cursor!!!
840 */
841
842 // Build an insert statement using parameter markers
b8032740 843 if (!queryOnly && m_numCols > 0)
89894079 844 {
68379eaf 845 bool needComma = false;
1d6f2348
VZ
846 sqlStmt.Printf(wxT("INSERT INTO %s ("),
847 pDb->SQLTableName(tableName.c_str()).c_str());
b8032740 848 for (i = 0; i < m_numCols; i++)
89894079
VZ
849 {
850 if (! colDefs[i].InsertAllowed)
851 continue;
852 if (needComma)
4fdae997 853 sqlStmt += wxT(",");
243d4b36
GT
854 sqlStmt += pDb->SQLColumnName(colDefs[i].ColName);
855// sqlStmt += colDefs[i].ColName;
68379eaf 856 needComma = true;
89894079 857 }
68379eaf 858 needComma = false;
4fdae997 859 sqlStmt += wxT(") VALUES (");
f6bcfd97 860
3ca6a5f0 861 int insertableCount = 0;
f6bcfd97 862
b8032740 863 for (i = 0; i < m_numCols; i++)
89894079
VZ
864 {
865 if (! colDefs[i].InsertAllowed)
866 continue;
867 if (needComma)
4fdae997
GT
868 sqlStmt += wxT(",");
869 sqlStmt += wxT("?");
68379eaf 870 needComma = true;
3ca6a5f0 871 insertableCount++;
89894079 872 }
4fdae997 873 sqlStmt += wxT(")");
da38429d 874
89894079 875 // Prepare the insert statement for execution
da38429d 876 if (insertableCount)
3ca6a5f0 877 {
8a39593e 878 if (SQLPrepare(hstmtInsert, (SQLTCHAR FAR *) sqlStmt.c_str(), SQL_NTS) != SQL_SUCCESS)
f6bcfd97
BP
879 return(pDb->DispAllErrors(henv, hdbc, hstmtInsert));
880 }
da38429d 881 else
68379eaf 882 insertable = false;
89894079 883 }
da38429d 884
89894079 885 // Completed successfully
68379eaf 886 return true;
108106cf 887
f6bcfd97 888} // wxDbTable::Open()
108106cf 889
67e9aaa3 890
f6bcfd97
BP
891/********** wxDbTable::Query() **********/
892bool wxDbTable::Query(bool forUpdate, bool distinct)
108106cf
JS
893{
894
89894079 895 return(query(DB_SELECT_WHERE, forUpdate, distinct));
108106cf 896
f6bcfd97 897} // wxDbTable::Query()
108106cf 898
67e9aaa3 899
f6bcfd97 900/********** wxDbTable::QueryBySqlStmt() **********/
4fdae997 901bool wxDbTable::QueryBySqlStmt(const wxString &pSqlStmt)
108106cf 902{
89894079 903 pDb->WriteSqlLog(pSqlStmt);
108106cf 904
68379eaf 905 return(query(DB_SELECT_STATEMENT, false, false, pSqlStmt));
108106cf 906
f6bcfd97 907} // wxDbTable::QueryBySqlStmt()
108106cf 908
67e9aaa3 909
f6bcfd97
BP
910/********** wxDbTable::QueryMatching() **********/
911bool wxDbTable::QueryMatching(bool forUpdate, bool distinct)
108106cf
JS
912{
913
89894079 914 return(query(DB_SELECT_MATCHING, forUpdate, distinct));
108106cf 915
f6bcfd97 916} // wxDbTable::QueryMatching()
108106cf 917
67e9aaa3 918
f6bcfd97
BP
919/********** wxDbTable::QueryOnKeyFields() **********/
920bool wxDbTable::QueryOnKeyFields(bool forUpdate, bool distinct)
108106cf
JS
921{
922
89894079 923 return(query(DB_SELECT_KEYFIELDS, forUpdate, distinct));
108106cf 924
f6bcfd97 925} // wxDbTable::QueryOnKeyFields()
108106cf 926
67e9aaa3 927
f6bcfd97
BP
928/********** wxDbTable::GetPrev() **********/
929bool wxDbTable::GetPrev(void)
a3439c7d 930{
89894079
VZ
931 if (pDb->FwdOnlyCursors())
932 {
f6bcfd97 933 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
68379eaf 934 return false;
89894079
VZ
935 }
936 else
937 return(getRec(SQL_FETCH_PRIOR));
3ca6a5f0 938
f6bcfd97 939} // wxDbTable::GetPrev()
a3439c7d 940
67e9aaa3 941
f6bcfd97
BP
942/********** wxDbTable::operator-- **********/
943bool wxDbTable::operator--(int)
a3439c7d 944{
89894079
VZ
945 if (pDb->FwdOnlyCursors())
946 {
f6bcfd97 947 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
68379eaf 948 return false;
89894079
VZ
949 }
950 else
951 return(getRec(SQL_FETCH_PRIOR));
3ca6a5f0 952
f6bcfd97 953} // wxDbTable::operator--
a3439c7d 954
67e9aaa3 955
f6bcfd97
BP
956/********** wxDbTable::GetFirst() **********/
957bool wxDbTable::GetFirst(void)
a3439c7d 958{
89894079
VZ
959 if (pDb->FwdOnlyCursors())
960 {
f6bcfd97 961 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
68379eaf 962 return false;
89894079
VZ
963 }
964 else
965 return(getRec(SQL_FETCH_FIRST));
3ca6a5f0 966
f6bcfd97 967} // wxDbTable::GetFirst()
a3439c7d 968
67e9aaa3 969
f6bcfd97
BP
970/********** wxDbTable::GetLast() **********/
971bool wxDbTable::GetLast(void)
a3439c7d 972{
89894079
VZ
973 if (pDb->FwdOnlyCursors())
974 {
f6bcfd97 975 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
68379eaf 976 return false;
89894079 977 }
da38429d 978 else
89894079 979 return(getRec(SQL_FETCH_LAST));
3ca6a5f0 980
f6bcfd97 981} // wxDbTable::GetLast()
a3439c7d 982
67e9aaa3 983
4fdae997
GT
984/********** wxDbTable::BuildDeleteStmt() **********/
985void wxDbTable::BuildDeleteStmt(wxString &pSqlStmt, int typeOfDel, const wxString &pWhereClause)
108106cf 986{
4fdae997
GT
987 wxASSERT(!queryOnly);
988 if (queryOnly)
989 return;
990
991 wxString whereClause;
89894079 992
4fdae997
GT
993 whereClause.Empty();
994
995 // Handle the case of DeleteWhere() and the where clause is blank. It should
996 // delete all records from the database in this case.
997 if (typeOfDel == DB_DEL_WHERE && (pWhereClause.Length() == 0))
998 {
1d6f2348
VZ
999 pSqlStmt.Printf(wxT("DELETE FROM %s"),
1000 pDb->SQLTableName(tableName.c_str()).c_str());
4fdae997
GT
1001 return;
1002 }
1003
1d6f2348
VZ
1004 pSqlStmt.Printf(wxT("DELETE FROM %s WHERE "),
1005 pDb->SQLTableName(tableName.c_str()).c_str());
4fdae997
GT
1006
1007 // Append the WHERE clause to the SQL DELETE statement
1008 switch(typeOfDel)
1009 {
1010 case DB_DEL_KEYFIELDS:
1011 // If the datasource supports the ROWID column, build
1012 // the where on ROWID for efficiency purposes.
1013 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
b8032740 1014 if (CanUpdateByROWID())
4fdae997
GT
1015 {
1016 SDWORD cb;
1017 wxChar rowid[wxDB_ROWID_LEN+1];
1018
1019 // Get the ROWID value. If not successful retreiving the ROWID,
1020 // simply fall down through the code and build the WHERE clause
1021 // based on the key fields.
b8032740 1022 if (SQLGetData(hstmt, (UWORD)(m_numCols+1), SQL_C_WXCHAR, (UCHAR*) rowid, sizeof(rowid), &cb) == SQL_SUCCESS)
4fdae997
GT
1023 {
1024 pSqlStmt += wxT("ROWID = '");
1025 pSqlStmt += rowid;
1026 pSqlStmt += wxT("'");
1027 break;
1028 }
1029 }
1030 // Unable to delete by ROWID, so build a WHERE
1031 // clause based on the keyfields.
1032 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS);
1033 pSqlStmt += whereClause;
1034 break;
1035 case DB_DEL_WHERE:
1036 pSqlStmt += pWhereClause;
1037 break;
1038 case DB_DEL_MATCHING:
1039 BuildWhereClause(whereClause, DB_WHERE_MATCHING);
1040 pSqlStmt += whereClause;
1041 break;
1042 }
1043
1044} // BuildDeleteStmt()
1045
1046
1047/***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1048void wxDbTable::BuildDeleteStmt(wxChar *pSqlStmt, int typeOfDel, const wxString &pWhereClause)
1049{
1050 wxString tempSqlStmt;
1051 BuildDeleteStmt(tempSqlStmt, typeOfDel, pWhereClause);
1052 wxStrcpy(pSqlStmt, tempSqlStmt);
1053} // wxDbTable::BuildDeleteStmt()
1054
1055
1056/********** wxDbTable::BuildSelectStmt() **********/
1057void wxDbTable::BuildSelectStmt(wxString &pSqlStmt, int typeOfSelect, bool distinct)
1058{
1059 wxString whereClause;
1060 whereClause.Empty();
89894079
VZ
1061
1062 // Build a select statement to query the database
4fdae997 1063 pSqlStmt = wxT("SELECT ");
89894079
VZ
1064
1065 // SELECT DISTINCT values only?
1066 if (distinct)
4fdae997 1067 pSqlStmt += wxT("DISTINCT ");
89894079
VZ
1068
1069 // Was a FROM clause specified to join tables to the base table?
1070 // Available for ::Query() only!!!
68379eaf 1071 bool appendFromClause = false;
f6bcfd97 1072#if wxODBC_BACKWARD_COMPATABILITY
89894079 1073 if (typeOfSelect == DB_SELECT_WHERE && from && wxStrlen(from))
68379eaf 1074 appendFromClause = true;
f6bcfd97
BP
1075#else
1076 if (typeOfSelect == DB_SELECT_WHERE && from.Length())
68379eaf 1077 appendFromClause = true;
f6bcfd97 1078#endif
89894079
VZ
1079
1080 // Add the column list
1081 int i;
52410d54 1082 wxString tStr;
b8032740 1083 for (i = 0; i < m_numCols; i++)
89894079 1084 {
52410d54 1085 tStr = colDefs[i].ColName;
89894079 1086 // If joining tables, the base table column names must be qualified to avoid ambiguity
d23a4aa7 1087 if ((appendFromClause || pDb->Dbms() == dbmsACCESS) && tStr.Find(wxT('.')) == wxNOT_FOUND)
89894079 1088 {
243d4b36 1089 pSqlStmt += pDb->SQLTableName(queryTableName.c_str());
4fdae997 1090 pSqlStmt += wxT(".");
89894079 1091 }
243d4b36 1092 pSqlStmt += pDb->SQLColumnName(colDefs[i].ColName);
b8032740 1093 if (i + 1 < m_numCols)
4fdae997 1094 pSqlStmt += wxT(",");
89894079
VZ
1095 }
1096
1097 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1098 // the ROWID if querying distinct records. The rowid will always be unique.
b8032740 1099 if (!distinct && CanUpdateByROWID())
89894079
VZ
1100 {
1101 // If joining tables, the base table column names must be qualified to avoid ambiguity
2beca662 1102 if (appendFromClause || pDb->Dbms() == dbmsACCESS)
89894079 1103 {
4fdae997 1104 pSqlStmt += wxT(",");
243d4b36
GT
1105 pSqlStmt += pDb->SQLTableName(queryTableName);
1106// pSqlStmt += queryTableName;
4fdae997 1107 pSqlStmt += wxT(".ROWID");
89894079
VZ
1108 }
1109 else
4fdae997 1110 pSqlStmt += wxT(",ROWID");
89894079
VZ
1111 }
1112
1113 // Append the FROM tablename portion
4fdae997 1114 pSqlStmt += wxT(" FROM ");
243d4b36
GT
1115 pSqlStmt += pDb->SQLTableName(queryTableName);
1116// pSqlStmt += queryTableName;
89894079
VZ
1117
1118 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1119 // The HOLDLOCK keyword follows the table name in the from clause.
1120 // Each table in the from clause must specify HOLDLOCK or
1121 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1122 // is parsed but ignored in SYBASE Transact-SQL.
1123 if (selectForUpdate && (pDb->Dbms() == dbmsSYBASE_ASA || pDb->Dbms() == dbmsSYBASE_ASE))
4fdae997 1124 pSqlStmt += wxT(" HOLDLOCK");
89894079
VZ
1125
1126 if (appendFromClause)
4fdae997 1127 pSqlStmt += from;
89894079
VZ
1128
1129 // Append the WHERE clause. Either append the where clause for the class
1130 // or build a where clause. The typeOfSelect determines this.
1131 switch(typeOfSelect)
1132 {
3ca6a5f0 1133 case DB_SELECT_WHERE:
f6bcfd97 1134#if wxODBC_BACKWARD_COMPATABILITY
3ca6a5f0 1135 if (where && wxStrlen(where)) // May not want a where clause!!!
f6bcfd97 1136#else
3ca6a5f0 1137 if (where.Length()) // May not want a where clause!!!
f6bcfd97 1138#endif
3ca6a5f0 1139 {
4fdae997
GT
1140 pSqlStmt += wxT(" WHERE ");
1141 pSqlStmt += where;
3ca6a5f0
BP
1142 }
1143 break;
1144 case DB_SELECT_KEYFIELDS:
1145 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS);
4fdae997 1146 if (whereClause.Length())
3ca6a5f0 1147 {
4fdae997
GT
1148 pSqlStmt += wxT(" WHERE ");
1149 pSqlStmt += whereClause;
3ca6a5f0
BP
1150 }
1151 break;
1152 case DB_SELECT_MATCHING:
1153 BuildWhereClause(whereClause, DB_WHERE_MATCHING);
4fdae997 1154 if (whereClause.Length())
3ca6a5f0 1155 {
4fdae997
GT
1156 pSqlStmt += wxT(" WHERE ");
1157 pSqlStmt += whereClause;
3ca6a5f0
BP
1158 }
1159 break;
89894079
VZ
1160 }
1161
1162 // Append the ORDER BY clause
f6bcfd97 1163#if wxODBC_BACKWARD_COMPATABILITY
89894079 1164 if (orderBy && wxStrlen(orderBy))
f6bcfd97 1165#else
3ca6a5f0 1166 if (orderBy.Length())
f6bcfd97 1167#endif
89894079 1168 {
4fdae997
GT
1169 pSqlStmt += wxT(" ORDER BY ");
1170 pSqlStmt += orderBy;
89894079
VZ
1171 }
1172
1173 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1174 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1175 // HOLDLOCK for Sybase.
1176 if (selectForUpdate && CanSelectForUpdate())
4fdae997
GT
1177 pSqlStmt += wxT(" FOR UPDATE");
1178
1179} // wxDbTable::BuildSelectStmt()
1180
108106cf 1181
4fdae997
GT
1182/***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1183void wxDbTable::BuildSelectStmt(wxChar *pSqlStmt, int typeOfSelect, bool distinct)
1184{
1185 wxString tempSqlStmt;
1186 BuildSelectStmt(tempSqlStmt, typeOfSelect, distinct);
1187 wxStrcpy(pSqlStmt, tempSqlStmt);
f6bcfd97 1188} // wxDbTable::BuildSelectStmt()
108106cf 1189
67e9aaa3 1190
4fdae997 1191/********** wxDbTable::BuildUpdateStmt() **********/
549c8cc2 1192void wxDbTable::BuildUpdateStmt(wxString &pSqlStmt, int typeOfUpdate, const wxString &pWhereClause)
4fdae997
GT
1193{
1194 wxASSERT(!queryOnly);
1195 if (queryOnly)
1196 return;
1197
1198 wxString whereClause;
1199 whereClause.Empty();
1200
68379eaf 1201 bool firstColumn = true;
4fdae997 1202
1d6f2348 1203 pSqlStmt.Printf(wxT("UPDATE %s SET "),
bb064193 1204 pDb->SQLTableName(tableName.c_str()).c_str());
4fdae997
GT
1205
1206 // Append a list of columns to be updated
1207 int i;
b8032740 1208 for (i = 0; i < m_numCols; i++)
4fdae997
GT
1209 {
1210 // Only append Updateable columns
1211 if (colDefs[i].Updateable)
1212 {
9082f1a9 1213 if (!firstColumn)
4fdae997
GT
1214 pSqlStmt += wxT(",");
1215 else
68379eaf 1216 firstColumn = false;
243d4b36
GT
1217
1218 pSqlStmt += pDb->SQLColumnName(colDefs[i].ColName);
1219// pSqlStmt += colDefs[i].ColName;
4fdae997
GT
1220 pSqlStmt += wxT(" = ?");
1221 }
1222 }
1223
1224 // Append the WHERE clause to the SQL UPDATE statement
1225 pSqlStmt += wxT(" WHERE ");
549c8cc2 1226 switch(typeOfUpdate)
4fdae997
GT
1227 {
1228 case DB_UPD_KEYFIELDS:
1229 // If the datasource supports the ROWID column, build
1230 // the where on ROWID for efficiency purposes.
1231 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
b8032740 1232 if (CanUpdateByROWID())
4fdae997
GT
1233 {
1234 SDWORD cb;
1235 wxChar rowid[wxDB_ROWID_LEN+1];
1236
1237 // Get the ROWID value. If not successful retreiving the ROWID,
1238 // simply fall down through the code and build the WHERE clause
1239 // based on the key fields.
b8032740 1240 if (SQLGetData(hstmt, (UWORD)(m_numCols+1), SQL_C_WXCHAR, (UCHAR*) rowid, sizeof(rowid), &cb) == SQL_SUCCESS)
4fdae997
GT
1241 {
1242 pSqlStmt += wxT("ROWID = '");
1243 pSqlStmt += rowid;
1244 pSqlStmt += wxT("'");
1245 break;
1246 }
1247 }
1248 // Unable to delete by ROWID, so build a WHERE
1249 // clause based on the keyfields.
1250 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS);
1251 pSqlStmt += whereClause;
1252 break;
1253 case DB_UPD_WHERE:
1254 pSqlStmt += pWhereClause;
1255 break;
1256 }
1257} // BuildUpdateStmt()
1258
1259
1260/***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
549c8cc2 1261void wxDbTable::BuildUpdateStmt(wxChar *pSqlStmt, int typeOfUpdate, const wxString &pWhereClause)
4fdae997
GT
1262{
1263 wxString tempSqlStmt;
549c8cc2 1264 BuildUpdateStmt(tempSqlStmt, typeOfUpdate, pWhereClause);
4fdae997
GT
1265 wxStrcpy(pSqlStmt, tempSqlStmt);
1266} // BuildUpdateStmt()
1267
1268
1269/********** wxDbTable::BuildWhereClause() **********/
1270void wxDbTable::BuildWhereClause(wxString &pWhereClause, int typeOfWhere,
1271 const wxString &qualTableName, bool useLikeComparison)
1272/*
1273 * Note: BuildWhereClause() currently ignores timestamp columns.
1274 * They are not included as part of the where clause.
1275 */
1276{
68379eaf 1277 bool moreThanOneColumn = false;
4fdae997
GT
1278 wxString colValue;
1279
1280 // Loop through the columns building a where clause as you go
b8032740
GT
1281 int colNumber;
1282 for (colNumber = 0; colNumber < m_numCols; colNumber++)
4fdae997
GT
1283 {
1284 // Determine if this column should be included in the WHERE clause
b8032740
GT
1285 if ((typeOfWhere == DB_WHERE_KEYFIELDS && colDefs[colNumber].KeyField) ||
1286 (typeOfWhere == DB_WHERE_MATCHING && (!IsColNull((UWORD)colNumber))))
4fdae997
GT
1287 {
1288 // Skip over timestamp columns
b8032740 1289 if (colDefs[colNumber].SqlCtype == SQL_C_TIMESTAMP)
4fdae997
GT
1290 continue;
1291 // If there is more than 1 column, join them with the keyword "AND"
1292 if (moreThanOneColumn)
1293 pWhereClause += wxT(" AND ");
1294 else
68379eaf 1295 moreThanOneColumn = true;
e7c9692f 1296
4fdae997 1297 // Concatenate where phrase for the column
b8032740 1298 wxString tStr = colDefs[colNumber].ColName;
e7c9692f 1299
d23a4aa7 1300 if (qualTableName.Length() && tStr.Find(wxT('.')) == wxNOT_FOUND)
4fdae997 1301 {
243d4b36 1302 pWhereClause += pDb->SQLTableName(qualTableName);
4fdae997
GT
1303 pWhereClause += wxT(".");
1304 }
b8032740 1305 pWhereClause += pDb->SQLColumnName(colDefs[colNumber].ColName);
e7c9692f 1306
b8032740 1307 if (useLikeComparison && (colDefs[colNumber].SqlCtype == SQL_C_WXCHAR))
4fdae997
GT
1308 pWhereClause += wxT(" LIKE ");
1309 else
1310 pWhereClause += wxT(" = ");
e7c9692f 1311
b8032740 1312 switch(colDefs[colNumber].SqlCtype)
4fdae997
GT
1313 {
1314 case SQL_C_CHAR:
5c2cd0f6 1315#ifndef __UNIX__
e4e45573 1316 case SQL_C_WCHAR:
d8d26772 1317#endif
e4e45573 1318 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
b8032740 1319 colValue.Printf(wxT("'%s'"), (UCHAR FAR *) colDefs[colNumber].PtrDataObj);
4fdae997 1320 break;
e9ed92a2 1321 case SQL_C_SHORT:
4fdae997 1322 case SQL_C_SSHORT:
b8032740 1323 colValue.Printf(wxT("%hi"), *((SWORD *) colDefs[colNumber].PtrDataObj));
4fdae997
GT
1324 break;
1325 case SQL_C_USHORT:
b8032740 1326 colValue.Printf(wxT("%hu"), *((UWORD *) colDefs[colNumber].PtrDataObj));
4fdae997 1327 break;
e9ed92a2 1328 case SQL_C_LONG:
4fdae997 1329 case SQL_C_SLONG:
b8032740 1330 colValue.Printf(wxT("%li"), *((SDWORD *) colDefs[colNumber].PtrDataObj));
4fdae997
GT
1331 break;
1332 case SQL_C_ULONG:
b8032740 1333 colValue.Printf(wxT("%lu"), *((UDWORD *) colDefs[colNumber].PtrDataObj));
4fdae997
GT
1334 break;
1335 case SQL_C_FLOAT:
b8032740 1336 colValue.Printf(wxT("%.6f"), *((SFLOAT *) colDefs[colNumber].PtrDataObj));
4fdae997
GT
1337 break;
1338 case SQL_C_DOUBLE:
b8032740 1339 colValue.Printf(wxT("%.6f"), *((SDOUBLE *) colDefs[colNumber].PtrDataObj));
4fdae997 1340 break;
e9ed92a2
GT
1341 default:
1342 {
1343 wxString strMsg;
1344 strMsg.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
b8032740 1345 colNumber,colDefs[colNumber].ColName);
2cb43514 1346 wxFAIL_MSG(strMsg.c_str());
e9ed92a2
GT
1347 }
1348 break;
4fdae997
GT
1349 }
1350 pWhereClause += colValue;
1351 }
1352 }
1353} // wxDbTable::BuildWhereClause()
1354
1355
1356/***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1357void wxDbTable::BuildWhereClause(wxChar *pWhereClause, int typeOfWhere,
1358 const wxString &qualTableName, bool useLikeComparison)
1359{
1360 wxString tempSqlStmt;
1361 BuildWhereClause(tempSqlStmt, typeOfWhere, qualTableName, useLikeComparison);
1362 wxStrcpy(pWhereClause, tempSqlStmt);
1363} // wxDbTable::BuildWhereClause()
1364
1365
f6bcfd97
BP
1366/********** wxDbTable::GetRowNum() **********/
1367UWORD wxDbTable::GetRowNum(void)
108106cf 1368{
89894079 1369 UDWORD rowNum;
108106cf 1370
89894079
VZ
1371 if (SQLGetStmtOption(hstmt, SQL_ROW_NUMBER, (UCHAR*) &rowNum) != SQL_SUCCESS)
1372 {
1373 pDb->DispAllErrors(henv, hdbc, hstmt);
1374 return(0);
1375 }
108106cf 1376
89894079
VZ
1377 // Completed successfully
1378 return((UWORD) rowNum);
108106cf 1379
f6bcfd97 1380} // wxDbTable::GetRowNum()
108106cf 1381
67e9aaa3 1382
f6bcfd97
BP
1383/********** wxDbTable::CloseCursor() **********/
1384bool wxDbTable::CloseCursor(HSTMT cursor)
108106cf 1385{
89894079
VZ
1386 if (SQLFreeStmt(cursor, SQL_CLOSE) != SQL_SUCCESS)
1387 return(pDb->DispAllErrors(henv, hdbc, cursor));
108106cf 1388
89894079 1389 // Completed successfully
68379eaf 1390 return true;
108106cf 1391
f6bcfd97 1392} // wxDbTable::CloseCursor()
108106cf 1393
67e9aaa3 1394
f6bcfd97
BP
1395/********** wxDbTable::CreateTable() **********/
1396bool wxDbTable::CreateTable(bool attemptDrop)
108106cf 1397{
89894079 1398 if (!pDb)
68379eaf 1399 return false;
1fc5dd6f 1400
89894079 1401 int i, j;
1e92909e 1402 wxString sqlStmt;
108106cf 1403
a2115c88 1404#ifdef DBDEBUG_CONSOLE
4fdae997 1405 cout << wxT("Creating Table ") << tableName << wxT("...") << endl;
108106cf
JS
1406#endif
1407
89894079
VZ
1408 // Drop table first
1409 if (attemptDrop && !DropTable())
68379eaf 1410 return false;
108106cf 1411
89894079 1412 // Create the table
a2115c88 1413#ifdef DBDEBUG_CONSOLE
b8032740 1414 for (i = 0; i < m_numCols; i++)
89894079
VZ
1415 {
1416 // Exclude derived columns since they are NOT part of the base table
1417 if (colDefs[i].DerivedCol)
1418 continue;
4fdae997 1419 cout << i + 1 << wxT(": ") << colDefs[i].ColName << wxT("; ");
89894079
VZ
1420 switch(colDefs[i].DbDataType)
1421 {
1422 case DB_DATA_TYPE_VARCHAR:
e4e45573 1423 cout << pDb->GetTypeInfVarchar().TypeName << wxT("(") << (int)(colDefs[i].SzDataObj / sizeof(wxChar)) << wxT(")");
89894079
VZ
1424 break;
1425 case DB_DATA_TYPE_INTEGER:
882fc8a9 1426 cout << pDb->GetTypeInfInteger().TypeName;
89894079
VZ
1427 break;
1428 case DB_DATA_TYPE_FLOAT:
882fc8a9 1429 cout << pDb->GetTypeInfFloat().TypeName;
89894079
VZ
1430 break;
1431 case DB_DATA_TYPE_DATE:
882fc8a9 1432 cout << pDb->GetTypeInfDate().TypeName;
89894079 1433 break;
bf5423ea 1434 case DB_DATA_TYPE_BLOB:
882fc8a9 1435 cout << pDb->GetTypeInfBlob().TypeName;
bf5423ea 1436 break;
89894079
VZ
1437 }
1438 cout << endl;
1439 }
108106cf
JS
1440#endif
1441
89894079 1442 // Build a CREATE TABLE string from the colDefs structure.
68379eaf 1443 bool needComma = false;
243d4b36 1444
1d6f2348
VZ
1445 sqlStmt.Printf(wxT("CREATE TABLE %s ("),
1446 pDb->SQLTableName(tableName.c_str()).c_str());
1e92909e 1447
b8032740 1448 for (i = 0; i < m_numCols; i++)
89894079
VZ
1449 {
1450 // Exclude derived columns since they are NOT part of the base table
1451 if (colDefs[i].DerivedCol)
1452 continue;
1453 // Comma Delimiter
1454 if (needComma)
4fdae997 1455 sqlStmt += wxT(",");
89894079 1456 // Column Name
243d4b36
GT
1457 sqlStmt += pDb->SQLColumnName(colDefs[i].ColName);
1458// sqlStmt += colDefs[i].ColName;
4fdae997 1459 sqlStmt += wxT(" ");
89894079
VZ
1460 // Column Type
1461 switch(colDefs[i].DbDataType)
1462 {
1463 case DB_DATA_TYPE_VARCHAR:
3ca6a5f0
BP
1464 sqlStmt += pDb->GetTypeInfVarchar().TypeName;
1465 break;
89894079 1466 case DB_DATA_TYPE_INTEGER:
3ca6a5f0
BP
1467 sqlStmt += pDb->GetTypeInfInteger().TypeName;
1468 break;
89894079 1469 case DB_DATA_TYPE_FLOAT:
3ca6a5f0
BP
1470 sqlStmt += pDb->GetTypeInfFloat().TypeName;
1471 break;
89894079 1472 case DB_DATA_TYPE_DATE:
3ca6a5f0
BP
1473 sqlStmt += pDb->GetTypeInfDate().TypeName;
1474 break;
bf5423ea
GT
1475 case DB_DATA_TYPE_BLOB:
1476 sqlStmt += pDb->GetTypeInfBlob().TypeName;
1477 break;
89894079
VZ
1478 }
1479 // For varchars, append the size of the string
e25cdb86 1480 if (colDefs[i].DbDataType == DB_DATA_TYPE_VARCHAR &&
8a39593e 1481 (pDb->Dbms() != dbmsMY_SQL || pDb->GetTypeInfVarchar().TypeName != _T("text")))// ||
bf5423ea 1482// colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
89894079 1483 {
1e92909e 1484 wxString s;
e4e45573 1485 s.Printf(wxT("(%d)"), (int)(colDefs[i].SzDataObj / sizeof(wxChar)));
4fdae997 1486 sqlStmt += s;
89894079
VZ
1487 }
1488
e93a3a18
GT
1489 if (pDb->Dbms() == dbmsDB2 ||
1490 pDb->Dbms() == dbmsMY_SQL ||
1491 pDb->Dbms() == dbmsSYBASE_ASE ||
9082f1a9 1492 pDb->Dbms() == dbmsINTERBASE ||
215a0070 1493 pDb->Dbms() == dbmsFIREBIRD ||
e93a3a18 1494 pDb->Dbms() == dbmsMS_SQL_SERVER)
89894079
VZ
1495 {
1496 if (colDefs[i].KeyField)
1497 {
4fdae997 1498 sqlStmt += wxT(" NOT NULL");
89894079
VZ
1499 }
1500 }
da38429d 1501
68379eaf 1502 needComma = true;
89894079
VZ
1503 }
1504 // If there is a primary key defined, include it in the create statement
b8032740 1505 for (i = j = 0; i < m_numCols; i++)
89894079
VZ
1506 {
1507 if (colDefs[i].KeyField)
1508 {
1509 j++;
1510 break;
1511 }
1512 }
52410d54
DS
1513 if ( j && (pDb->Dbms() != dbmsDBASE)
1514 && (pDb->Dbms() != dbmsXBASE_SEQUITER) ) // Found a keyfield
89894079 1515 {
87cc3456 1516 switch (pDb->Dbms())
89894079 1517 {
1dee6b39 1518 case dbmsACCESS:
597fadce 1519 case dbmsINFORMIX:
87cc3456
GT
1520 case dbmsSYBASE_ASA:
1521 case dbmsSYBASE_ASE:
1522 case dbmsMY_SQL:
215a0070 1523 case dbmsFIREBIRD:
87cc3456 1524 {
2beca662 1525 // MySQL goes out on this one. We also declare the relevant key NON NULL above
87cc3456
GT
1526 sqlStmt += wxT(",PRIMARY KEY (");
1527 break;
1528 }
1529 default:
1530 {
1531 sqlStmt += wxT(",CONSTRAINT ");
2beca662
GT
1532 // DB2 is limited to 18 characters for index names
1533 if (pDb->Dbms() == dbmsDB2)
1534 {
1535 wxASSERT_MSG((tableName && wxStrlen(tableName) <= 13), wxT("DB2 table/index names must be no longer than 13 characters in length.\n\nTruncating table name to 13 characters."));
243d4b36
GT
1536 sqlStmt += pDb->SQLTableName(tableName.substr(0, 13).c_str());
1537// sqlStmt += tableName.substr(0, 13);
2beca662
GT
1538 }
1539 else
243d4b36
GT
1540 sqlStmt += pDb->SQLTableName(tableName.c_str());
1541// sqlStmt += tableName;
2beca662 1542
87cc3456
GT
1543 sqlStmt += wxT("_PIDX PRIMARY KEY (");
1544 break;
1545 }
89894079
VZ
1546 }
1547
1548 // List column name(s) of column(s) comprising the primary key
b8032740 1549 for (i = j = 0; i < m_numCols; i++)
89894079
VZ
1550 {
1551 if (colDefs[i].KeyField)
1552 {
1553 if (j++) // Multi part key, comma separate names
4fdae997 1554 sqlStmt += wxT(",");
243d4b36 1555 sqlStmt += pDb->SQLColumnName(colDefs[i].ColName);
e25cdb86
GT
1556
1557 if (pDb->Dbms() == dbmsMY_SQL &&
1558 colDefs[i].DbDataType == DB_DATA_TYPE_VARCHAR)
1559 {
1560 wxString s;
e4e45573 1561 s.Printf(wxT("(%d)"), (int)(colDefs[i].SzDataObj / sizeof(wxChar)));
e25cdb86
GT
1562 sqlStmt += s;
1563 }
89894079
VZ
1564 }
1565 }
2beca662
GT
1566 sqlStmt += wxT(")");
1567
597fadce
GT
1568 if (pDb->Dbms() == dbmsINFORMIX ||
1569 pDb->Dbms() == dbmsSYBASE_ASA ||
2beca662
GT
1570 pDb->Dbms() == dbmsSYBASE_ASE)
1571 {
1572 sqlStmt += wxT(" CONSTRAINT ");
243d4b36
GT
1573 sqlStmt += pDb->SQLTableName(tableName);
1574// sqlStmt += tableName;
2beca662
GT
1575 sqlStmt += wxT("_PIDX");
1576 }
89894079
VZ
1577 }
1578 // Append the closing parentheses for the create table statement
4fdae997 1579 sqlStmt += wxT(")");
a2115c88 1580
4fdae997 1581 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 1582
a2115c88 1583#ifdef DBDEBUG_CONSOLE
f6bcfd97 1584 cout << endl << sqlStmt.c_str() << endl;
108106cf
JS
1585#endif
1586
89894079 1587 // Execute the CREATE TABLE statement
8a39593e 1588 RETCODE retcode = SQLExecDirect(hstmt, (SQLTCHAR FAR *) sqlStmt.c_str(), SQL_NTS);
89894079
VZ
1589 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
1590 {
1591 pDb->DispAllErrors(henv, hdbc, hstmt);
1592 pDb->RollbackTrans();
1593 CloseCursor(hstmt);
68379eaf 1594 return false;
89894079
VZ
1595 }
1596
1597 // Commit the transaction and close the cursor
3ca6a5f0 1598 if (!pDb->CommitTrans())
68379eaf 1599 return false;
3ca6a5f0 1600 if (!CloseCursor(hstmt))
68379eaf 1601 return false;
89894079
VZ
1602
1603 // Database table created successfully
68379eaf 1604 return true;
108106cf 1605
f6bcfd97 1606} // wxDbTable::CreateTable()
108106cf 1607
67e9aaa3 1608
f6bcfd97
BP
1609/********** wxDbTable::DropTable() **********/
1610bool wxDbTable::DropTable()
a2115c88 1611{
68379eaf 1612 // NOTE: This function returns true if the Table does not exist, but
89894079 1613 // only for identified databases. Code will need to be added
0b8410f3 1614 // below for any other databases when those databases are defined
89894079 1615 // to handle this situation consistently
a2115c88 1616
1e92909e 1617 wxString sqlStmt;
a2115c88 1618
1d6f2348
VZ
1619 sqlStmt.Printf(wxT("DROP TABLE %s"),
1620 pDb->SQLTableName(tableName.c_str()).c_str());
a2115c88 1621
4fdae997 1622 pDb->WriteSqlLog(sqlStmt);
a2115c88
GT
1623
1624#ifdef DBDEBUG_CONSOLE
f6bcfd97 1625 cout << endl << sqlStmt.c_str() << endl;
a2115c88
GT
1626#endif
1627
8a39593e 1628 RETCODE retcode = SQLExecDirect(hstmt, (SQLTCHAR FAR *) sqlStmt.c_str(), SQL_NTS);
2beca662 1629 if (retcode != SQL_SUCCESS)
89894079
VZ
1630 {
1631 // Check for "Base table not found" error and ignore
da38429d 1632 pDb->GetNextError(henv, hdbc, hstmt);
2beca662 1633 if (wxStrcmp(pDb->sqlState, wxT("S0002")) /*&&
da38429d 1634 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
2beca662 1635 {
89894079 1636 // Check for product specific error codes
2beca662 1637 if (!((pDb->Dbms() == dbmsSYBASE_ASA && !wxStrcmp(pDb->sqlState,wxT("42000"))) || // 5.x (and lower?)
da38429d 1638 (pDb->Dbms() == dbmsSYBASE_ASE && !wxStrcmp(pDb->sqlState,wxT("37000"))) ||
2beca662 1639 (pDb->Dbms() == dbmsPERVASIVE_SQL && !wxStrcmp(pDb->sqlState,wxT("S1000"))) || // Returns an S1000 then an S0002
da38429d 1640 (pDb->Dbms() == dbmsPOSTGRES && !wxStrcmp(pDb->sqlState,wxT("08S01")))))
89894079
VZ
1641 {
1642 pDb->DispNextError();
1643 pDb->DispAllErrors(henv, hdbc, hstmt);
1644 pDb->RollbackTrans();
5a226de0 1645// CloseCursor(hstmt);
68379eaf 1646 return false;
89894079
VZ
1647 }
1648 }
1649 }
1650
1651 // Commit the transaction and close the cursor
1652 if (! pDb->CommitTrans())
68379eaf 1653 return false;
89894079 1654 if (! CloseCursor(hstmt))
68379eaf 1655 return false;
89894079 1656
68379eaf 1657 return true;
f6bcfd97 1658} // wxDbTable::DropTable()
a2115c88 1659
67e9aaa3 1660
f6bcfd97 1661/********** wxDbTable::CreateIndex() **********/
549c8cc2
GT
1662bool wxDbTable::CreateIndex(const wxString &indexName, bool unique, UWORD numIndexColumns,
1663 wxDbIdxDef *pIndexDefs, bool attemptDrop)
108106cf 1664{
1e92909e 1665 wxString sqlStmt;
89894079
VZ
1666
1667 // Drop the index first
549c8cc2 1668 if (attemptDrop && !DropIndex(indexName))
68379eaf 1669 return false;
89894079 1670
3ca6a5f0
BP
1671 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1672 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1673 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1674 // table was created, then months later you determine that an additional index while
1675 // give better performance, so you want to add an index).
1676 //
1677 // The following block of code will modify the column definition to make the column be
1678 // defined with the "NOT NULL" qualifier.
1679 if (pDb->Dbms() == dbmsMY_SQL)
1680 {
1681 wxString sqlStmt;
1682 int i;
68379eaf 1683 bool ok = true;
549c8cc2 1684 for (i = 0; i < numIndexColumns && ok; i++)
3ca6a5f0
BP
1685 {
1686 int j = 0;
68379eaf 1687 bool found = false;
3ca6a5f0
BP
1688 // Find the column definition that has the ColName that matches the
1689 // index column name. We need to do this to get the DB_DATA_TYPE of
1690 // the index column, as MySQL's syntax for the ALTER column requires
1691 // this information
b8032740 1692 while (!found && (j < this->m_numCols))
3ca6a5f0 1693 {
549c8cc2 1694 if (wxStrcmp(colDefs[j].ColName,pIndexDefs[i].ColName) == 0)
68379eaf 1695 found = true;
3ca6a5f0
BP
1696 if (!found)
1697 j++;
1698 }
da38429d 1699
3ca6a5f0
BP
1700 if (found)
1701 {
549c8cc2 1702 ok = pDb->ModifyColumn(tableName, pIndexDefs[i].ColName,
e4e45573 1703 colDefs[j].DbDataType, (int)(colDefs[j].SzDataObj / sizeof(wxChar)),
4fdae997
GT
1704 wxT("NOT NULL"));
1705
3ca6a5f0
BP
1706 if (!ok)
1707 {
8a39593e
JS
1708 #if 0
1709 // retcode is not used
3ca6a5f0
BP
1710 wxODBC_ERRORS retcode;
1711 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1712 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1713 // This line is just here for debug checking of the value
1714 retcode = (wxODBC_ERRORS)pDb->DB_STATUS;
8a39593e 1715 #endif
3ca6a5f0
BP
1716 }
1717 }
1718 else
68379eaf 1719 ok = false;
3ca6a5f0
BP
1720 }
1721 if (ok)
1722 pDb->CommitTrans();
1723 else
1724 {
1725 pDb->RollbackTrans();
68379eaf 1726 return false;
3ca6a5f0
BP
1727 }
1728 }
da38429d 1729
89894079 1730 // Build a CREATE INDEX statement
4fdae997 1731 sqlStmt = wxT("CREATE ");
89894079 1732 if (unique)
4fdae997 1733 sqlStmt += wxT("UNIQUE ");
da38429d 1734
4fdae997 1735 sqlStmt += wxT("INDEX ");
549c8cc2 1736 sqlStmt += pDb->SQLTableName(indexName);
4fdae997 1737 sqlStmt += wxT(" ON ");
243d4b36
GT
1738
1739 sqlStmt += pDb->SQLTableName(tableName);
1740// sqlStmt += tableName;
4fdae997 1741 sqlStmt += wxT(" (");
da38429d 1742
89894079
VZ
1743 // Append list of columns making up index
1744 int i;
549c8cc2 1745 for (i = 0; i < numIndexColumns; i++)
89894079 1746 {
549c8cc2
GT
1747 sqlStmt += pDb->SQLColumnName(pIndexDefs[i].ColName);
1748// sqlStmt += pIndexDefs[i].ColName;
9082f1a9 1749
9c136858
JS
1750 // MySQL requires a key length on VARCHAR keys
1751 if ( pDb->Dbms() == dbmsMY_SQL )
1752 {
1753 // Find the details on this column
1754 int j;
b8032740 1755 for ( j = 0; j < m_numCols; ++j )
9c136858 1756 {
549c8cc2 1757 if ( wxStrcmp( pIndexDefs[i].ColName, colDefs[j].ColName ) == 0 )
9c136858
JS
1758 {
1759 break;
1760 }
1761 }
1762 if ( colDefs[j].DbDataType == DB_DATA_TYPE_VARCHAR)
1763 {
1764 wxString s;
e4e45573 1765 s.Printf(wxT("(%d)"), (int)(colDefs[i].SzDataObj / sizeof(wxChar)));
9c136858
JS
1766 sqlStmt += s;
1767 }
1768 }
68379eaf 1769
9082f1a9 1770 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
8a39593e 1771 if (!((pDb->Dbms() == dbmsMS_SQL_SERVER) && (wxStrncmp(pDb->dbInf.dbmsVer,_T("07"),2)==0)) &&
215a0070 1772 !(pDb->Dbms() == dbmsFIREBIRD) &&
9082f1a9 1773 !(pDb->Dbms() == dbmsPOSTGRES))
89894079 1774 {
549c8cc2 1775 if (pIndexDefs[i].Ascending)
4fdae997 1776 sqlStmt += wxT(" ASC");
89894079 1777 else
4fdae997 1778 sqlStmt += wxT(" DESC");
89894079 1779 }
9082f1a9 1780 else
549c8cc2 1781 wxASSERT_MSG(pIndexDefs[i].Ascending, _T("Datasource does not support DESCending index columns"));
89894079 1782
549c8cc2 1783 if ((i + 1) < numIndexColumns)
4fdae997 1784 sqlStmt += wxT(",");
89894079 1785 }
da38429d 1786
89894079 1787 // Append closing parentheses
4fdae997 1788 sqlStmt += wxT(")");
89894079 1789
4fdae997 1790 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 1791
a2115c88 1792#ifdef DBDEBUG_CONSOLE
f6bcfd97 1793 cout << endl << sqlStmt.c_str() << endl << endl;
108106cf
JS
1794#endif
1795
89894079 1796 // Execute the CREATE INDEX statement
215a0070
GT
1797 RETCODE retcode = SQLExecDirect(hstmt, (SQLTCHAR FAR *) sqlStmt.c_str(), SQL_NTS);
1798 if (retcode != SQL_SUCCESS)
89894079
VZ
1799 {
1800 pDb->DispAllErrors(henv, hdbc, hstmt);
1801 pDb->RollbackTrans();
1802 CloseCursor(hstmt);
68379eaf 1803 return false;
89894079 1804 }
108106cf 1805
89894079
VZ
1806 // Commit the transaction and close the cursor
1807 if (! pDb->CommitTrans())
68379eaf 1808 return false;
89894079 1809 if (! CloseCursor(hstmt))
68379eaf 1810 return false;
108106cf 1811
89894079 1812 // Index Created Successfully
68379eaf 1813 return true;
108106cf 1814
f6bcfd97 1815} // wxDbTable::CreateIndex()
108106cf 1816
67e9aaa3 1817
f6bcfd97 1818/********** wxDbTable::DropIndex() **********/
549c8cc2 1819bool wxDbTable::DropIndex(const wxString &indexName)
a2115c88 1820{
68379eaf 1821 // NOTE: This function returns true if the Index does not exist, but
89894079 1822 // only for identified databases. Code will need to be added
5a226de0 1823 // below for any other databases when those databases are defined
89894079 1824 // to handle this situation consistently
a2115c88 1825
1e92909e 1826 wxString sqlStmt;
a2115c88 1827
5a226de0
GT
1828 if (pDb->Dbms() == dbmsACCESS || pDb->Dbms() == dbmsMY_SQL ||
1829 pDb->Dbms() == dbmsDBASE /*|| Paradox needs this syntax too when we add support*/)
1d6f2348 1830 sqlStmt.Printf(wxT("DROP INDEX %s ON %s"),
549c8cc2 1831 pDb->SQLTableName(indexName.c_str()).c_str(),
6bbff0aa 1832 pDb->SQLTableName(tableName.c_str()).c_str());
e93a3a18 1833 else if ((pDb->Dbms() == dbmsMS_SQL_SERVER) ||
9f4de2dc 1834 (pDb->Dbms() == dbmsSYBASE_ASE) ||
52410d54 1835 (pDb->Dbms() == dbmsXBASE_SEQUITER))
1d6f2348
VZ
1836 sqlStmt.Printf(wxT("DROP INDEX %s.%s"),
1837 pDb->SQLTableName(tableName.c_str()).c_str(),
549c8cc2 1838 pDb->SQLTableName(indexName.c_str()).c_str());
89894079 1839 else
1d6f2348 1840 sqlStmt.Printf(wxT("DROP INDEX %s"),
549c8cc2 1841 pDb->SQLTableName(indexName.c_str()).c_str());
a2115c88 1842
4fdae997 1843 pDb->WriteSqlLog(sqlStmt);
a2115c88
GT
1844
1845#ifdef DBDEBUG_CONSOLE
f6bcfd97 1846 cout << endl << sqlStmt.c_str() << endl;
a2115c88 1847#endif
215a0070
GT
1848 RETCODE retcode = SQLExecDirect(hstmt, (SQLTCHAR FAR *) sqlStmt.c_str(), SQL_NTS);
1849 if (retcode != SQL_SUCCESS)
89894079
VZ
1850 {
1851 // Check for "Index not found" error and ignore
1852 pDb->GetNextError(henv, hdbc, hstmt);
4fdae997 1853 if (wxStrcmp(pDb->sqlState,wxT("S0012"))) // "Index not found"
89894079
VZ
1854 {
1855 // Check for product specific error codes
4fdae997
GT
1856 if (!((pDb->Dbms() == dbmsSYBASE_ASA && !wxStrcmp(pDb->sqlState,wxT("42000"))) || // v5.x (and lower?)
1857 (pDb->Dbms() == dbmsSYBASE_ASE && !wxStrcmp(pDb->sqlState,wxT("37000"))) ||
1858 (pDb->Dbms() == dbmsMS_SQL_SERVER && !wxStrcmp(pDb->sqlState,wxT("S1000"))) ||
215a0070
GT
1859 (pDb->Dbms() == dbmsINTERBASE && !wxStrcmp(pDb->sqlState,wxT("S1000"))) ||
1860 (pDb->Dbms() == dbmsFIREBIRD && !wxStrcmp(pDb->sqlState,wxT("HY000"))) ||
4fdae997
GT
1861 (pDb->Dbms() == dbmsSYBASE_ASE && !wxStrcmp(pDb->sqlState,wxT("S0002"))) || // Base table not found
1862 (pDb->Dbms() == dbmsMY_SQL && !wxStrcmp(pDb->sqlState,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1863 (pDb->Dbms() == dbmsPOSTGRES && !wxStrcmp(pDb->sqlState,wxT("08S01")))
3ca6a5f0 1864 ))
89894079
VZ
1865 {
1866 pDb->DispNextError();
1867 pDb->DispAllErrors(henv, hdbc, hstmt);
1868 pDb->RollbackTrans();
1869 CloseCursor(hstmt);
68379eaf 1870 return false;
89894079
VZ
1871 }
1872 }
1873 }
1874
1875 // Commit the transaction and close the cursor
1876 if (! pDb->CommitTrans())
68379eaf 1877 return false;
89894079 1878 if (! CloseCursor(hstmt))
68379eaf 1879 return false;
89894079 1880
68379eaf 1881 return true;
f6bcfd97 1882} // wxDbTable::DropIndex()
a2115c88 1883
67e9aaa3 1884
38cfbffa 1885/********** wxDbTable::SetOrderByColNums() **********/
e938ff5e 1886bool wxDbTable::SetOrderByColNums(UWORD first, ... )
38cfbffa 1887{
b8032740 1888 int colNumber = first; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
38cfbffa
GT
1889 va_list argptr;
1890
68379eaf 1891 bool abort = false;
38cfbffa
GT
1892 wxString tempStr;
1893
1894 va_start(argptr, first); /* Initialize variable arguments. */
b8032740 1895 while (!abort && (colNumber != wxDB_NO_MORE_COLUMN_NUMBERS))
38cfbffa
GT
1896 {
1897 // Make sure the passed in column number
1898 // is within the valid range of columns
1899 //
b8032740
GT
1900 // Valid columns are 0 thru m_numCols-1
1901 if (colNumber >= m_numCols || colNumber < 0)
38cfbffa 1902 {
68379eaf 1903 abort = true;
38cfbffa
GT
1904 continue;
1905 }
1906
b8032740 1907 if (colNumber != first)
4fdae997 1908 tempStr += wxT(",");
38cfbffa 1909
b8032740
GT
1910 tempStr += colDefs[colNumber].ColName;
1911 colNumber = va_arg (argptr, int);
38cfbffa
GT
1912 }
1913 va_end (argptr); /* Reset variable arguments. */
1914
4fdae997 1915 SetOrderByClause(tempStr);
38cfbffa
GT
1916
1917 return (!abort);
1918} // wxDbTable::SetOrderByColNums()
1919
1920
f6bcfd97
BP
1921/********** wxDbTable::Insert() **********/
1922int wxDbTable::Insert(void)
108106cf 1923{
4fdae997 1924 wxASSERT(!queryOnly);
f6bcfd97 1925 if (queryOnly || !insertable)
89894079
VZ
1926 return(DB_FAILURE);
1927
1928 bindInsertParams();
1929
1930 // Insert the record by executing the already prepared insert statement
1931 RETCODE retcode;
215a0070 1932 retcode = SQLExecute(hstmtInsert);
5962bdb8
JS
1933 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO &&
1934 retcode != SQL_NEED_DATA)
89894079
VZ
1935 {
1936 // Check to see if integrity constraint was violated
1937 pDb->GetNextError(henv, hdbc, hstmtInsert);
4fdae997 1938 if (! wxStrcmp(pDb->sqlState, wxT("23000"))) // Integrity constraint violated
89894079
VZ
1939 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL);
1940 else
1941 {
1942 pDb->DispNextError();
1943 pDb->DispAllErrors(henv, hdbc, hstmtInsert);
1944 return(DB_FAILURE);
1945 }
1946 }
5962bdb8
JS
1947 if (retcode == SQL_NEED_DATA)
1948 {
1949 PTR pParmID;
8a39593e
JS
1950 retcode = SQLParamData(hstmtInsert, &pParmID);
1951 while (retcode == SQL_NEED_DATA)
5962bdb8
JS
1952 {
1953 // Find the parameter
1954 int i;
b8032740 1955 for (i=0; i < m_numCols; i++)
5962bdb8
JS
1956 {
1957 if (colDefs[i].PtrDataObj == pParmID)
1958 {
1959 // We found it. Store the parameter.
1960 retcode = SQLPutData(hstmtInsert, pParmID, colDefs[i].SzDataObj);
1961 if (retcode != SQL_SUCCESS)
1962 {
1963 pDb->DispNextError();
1964 pDb->DispAllErrors(henv, hdbc, hstmtInsert);
1965 return(DB_FAILURE);
1966 }
1967 break;
1968 }
1969 }
c9b6d796 1970 retcode = SQLParamData(hstmtInsert, &pParmID);
160155e6
GT
1971 if (retcode != SQL_SUCCESS &&
1972 retcode != SQL_SUCCESS_WITH_INFO)
1973 {
1974 // record was not inserted
1975 pDb->DispNextError();
1976 pDb->DispAllErrors(henv, hdbc, hstmtInsert);
1977 return(DB_FAILURE);
1978 }
5962bdb8
JS
1979 }
1980 }
89894079
VZ
1981
1982 // Record inserted into the datasource successfully
1983 return(DB_SUCCESS);
108106cf 1984
f6bcfd97 1985} // wxDbTable::Insert()
108106cf 1986
67e9aaa3 1987
f6bcfd97
BP
1988/********** wxDbTable::Update() **********/
1989bool wxDbTable::Update(void)
108106cf 1990{
4fdae997 1991 wxASSERT(!queryOnly);
89894079 1992 if (queryOnly)
68379eaf 1993 return false;
a2115c88 1994
4fdae997 1995 wxString sqlStmt;
108106cf 1996
89894079 1997 // Build the SQL UPDATE statement
f6bcfd97 1998 BuildUpdateStmt(sqlStmt, DB_UPD_KEYFIELDS);
108106cf 1999
89894079 2000 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 2001
a2115c88 2002#ifdef DBDEBUG_CONSOLE
4fdae997 2003 cout << endl << sqlStmt.c_str() << endl << endl;
108106cf
JS
2004#endif
2005
89894079
VZ
2006 // Execute the SQL UPDATE statement
2007 return(execUpdate(sqlStmt));
108106cf 2008
f6bcfd97 2009} // wxDbTable::Update()
108106cf 2010
67e9aaa3 2011
f6bcfd97 2012/********** wxDbTable::Update(pSqlStmt) **********/
4fdae997 2013bool wxDbTable::Update(const wxString &pSqlStmt)
6919c53f 2014{
4fdae997 2015 wxASSERT(!queryOnly);
89894079 2016 if (queryOnly)
68379eaf 2017 return false;
6919c53f 2018
89894079 2019 pDb->WriteSqlLog(pSqlStmt);
6919c53f 2020
89894079 2021 return(execUpdate(pSqlStmt));
6919c53f 2022
f6bcfd97 2023} // wxDbTable::Update(pSqlStmt)
6919c53f 2024
67e9aaa3 2025
f6bcfd97 2026/********** wxDbTable::UpdateWhere() **********/
4fdae997 2027bool wxDbTable::UpdateWhere(const wxString &pWhereClause)
108106cf 2028{
4fdae997 2029 wxASSERT(!queryOnly);
89894079 2030 if (queryOnly)
68379eaf 2031 return false;
a2115c88 2032
4fdae997 2033 wxString sqlStmt;
108106cf 2034
89894079 2035 // Build the SQL UPDATE statement
f6bcfd97 2036 BuildUpdateStmt(sqlStmt, DB_UPD_WHERE, pWhereClause);
108106cf 2037
89894079 2038 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 2039
a2115c88 2040#ifdef DBDEBUG_CONSOLE
4fdae997 2041 cout << endl << sqlStmt.c_str() << endl << endl;
108106cf
JS
2042#endif
2043
89894079
VZ
2044 // Execute the SQL UPDATE statement
2045 return(execUpdate(sqlStmt));
108106cf 2046
f6bcfd97 2047} // wxDbTable::UpdateWhere()
108106cf 2048
67e9aaa3 2049
f6bcfd97
BP
2050/********** wxDbTable::Delete() **********/
2051bool wxDbTable::Delete(void)
108106cf 2052{
4fdae997 2053 wxASSERT(!queryOnly);
89894079 2054 if (queryOnly)
68379eaf 2055 return false;
a2115c88 2056
4fdae997
GT
2057 wxString sqlStmt;
2058 sqlStmt.Empty();
108106cf 2059
89894079 2060 // Build the SQL DELETE statement
f6bcfd97 2061 BuildDeleteStmt(sqlStmt, DB_DEL_KEYFIELDS);
108106cf 2062
89894079 2063 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 2064
89894079
VZ
2065 // Execute the SQL DELETE statement
2066 return(execDelete(sqlStmt));
108106cf 2067
f6bcfd97 2068} // wxDbTable::Delete()
108106cf 2069
67e9aaa3 2070
f6bcfd97 2071/********** wxDbTable::DeleteWhere() **********/
4fdae997 2072bool wxDbTable::DeleteWhere(const wxString &pWhereClause)
108106cf 2073{
4fdae997 2074 wxASSERT(!queryOnly);
89894079 2075 if (queryOnly)
68379eaf 2076 return false;
a2115c88 2077
4fdae997
GT
2078 wxString sqlStmt;
2079 sqlStmt.Empty();
108106cf 2080
89894079 2081 // Build the SQL DELETE statement
f6bcfd97 2082 BuildDeleteStmt(sqlStmt, DB_DEL_WHERE, pWhereClause);
108106cf 2083
89894079 2084 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 2085
89894079
VZ
2086 // Execute the SQL DELETE statement
2087 return(execDelete(sqlStmt));
108106cf 2088
f6bcfd97 2089} // wxDbTable::DeleteWhere()
108106cf 2090
67e9aaa3 2091
f6bcfd97
BP
2092/********** wxDbTable::DeleteMatching() **********/
2093bool wxDbTable::DeleteMatching(void)
108106cf 2094{
4fdae997 2095 wxASSERT(!queryOnly);
89894079 2096 if (queryOnly)
68379eaf 2097 return false;
a2115c88 2098
4fdae997
GT
2099 wxString sqlStmt;
2100 sqlStmt.Empty();
108106cf 2101
89894079 2102 // Build the SQL DELETE statement
f6bcfd97 2103 BuildDeleteStmt(sqlStmt, DB_DEL_MATCHING);
108106cf 2104
89894079 2105 pDb->WriteSqlLog(sqlStmt);
1fc5dd6f 2106
89894079
VZ
2107 // Execute the SQL DELETE statement
2108 return(execDelete(sqlStmt));
108106cf 2109
f6bcfd97 2110} // wxDbTable::DeleteMatching()
108106cf 2111
67e9aaa3 2112
f6bcfd97 2113/********** wxDbTable::IsColNull() **********/
b8032740 2114bool wxDbTable::IsColNull(UWORD colNumber) const
108106cf 2115{
f02d4a64 2116/*
68379eaf 2117 This logic is just not right. It would indicate true
f02d4a64
GT
2118 if a numeric field were set to a value of 0.
2119
b8032740 2120 switch(colDefs[colNumber].SqlCtype)
89894079 2121 {
3ca6a5f0 2122 case SQL_C_CHAR:
e4e45573
GT
2123 case SQL_C_WCHAR:
2124 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
b8032740 2125 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
3ca6a5f0 2126 case SQL_C_SSHORT:
b8032740 2127 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
3ca6a5f0 2128 case SQL_C_USHORT:
b8032740 2129 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
3ca6a5f0 2130 case SQL_C_SLONG:
b8032740 2131 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
3ca6a5f0 2132 case SQL_C_ULONG:
b8032740 2133 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
3ca6a5f0 2134 case SQL_C_FLOAT:
b8032740 2135 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
3ca6a5f0 2136 case SQL_C_DOUBLE:
b8032740 2137 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
3ca6a5f0
BP
2138 case SQL_C_TIMESTAMP:
2139 TIMESTAMP_STRUCT *pDt;
b8032740 2140 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
3ca6a5f0 2141 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
68379eaf 2142 return true;
3ca6a5f0 2143 else
68379eaf 2144 return false;
3ca6a5f0 2145 default:
68379eaf 2146 return true;
89894079 2147 }
f02d4a64 2148*/
b8032740 2149 return (colDefs[colNumber].Null);
f6bcfd97 2150} // wxDbTable::IsColNull()
108106cf 2151
67e9aaa3 2152
f6bcfd97
BP
2153/********** wxDbTable::CanSelectForUpdate() **********/
2154bool wxDbTable::CanSelectForUpdate(void)
108106cf 2155{
38cfbffa 2156 if (queryOnly)
68379eaf 2157 return false;
38cfbffa 2158
89894079 2159 if (pDb->Dbms() == dbmsMY_SQL)
68379eaf 2160 return false;
a2115c88 2161
e93a3a18
GT
2162 if ((pDb->Dbms() == dbmsORACLE) ||
2163 (pDb->dbInf.posStmts & SQL_PS_SELECT_FOR_UPDATE))
68379eaf 2164 return true;
89894079 2165 else
68379eaf 2166 return false;
108106cf 2167
f6bcfd97 2168} // wxDbTable::CanSelectForUpdate()
108106cf 2169
67e9aaa3 2170
b8032740
GT
2171/********** wxDbTable::CanUpdateByROWID() **********/
2172bool wxDbTable::CanUpdateByROWID(void)
108106cf 2173{
67e9aaa3 2174/*
68379eaf 2175 * NOTE: Returning false for now until this can be debugged,
89894079 2176 * as the ROWID is not getting updated correctly
67e9aaa3 2177 */
68379eaf 2178 return false;
6b3f4fb8 2179/*
89894079 2180 if (pDb->Dbms() == dbmsORACLE)
68379eaf 2181 return true;
89894079 2182 else
68379eaf 2183 return false;
6b3f4fb8 2184*/
b8032740 2185} // wxDbTable::CanUpdateByROWID()
108106cf 2186
67e9aaa3 2187
f6bcfd97
BP
2188/********** wxDbTable::IsCursorClosedOnCommit() **********/
2189bool wxDbTable::IsCursorClosedOnCommit(void)
108106cf 2190{
89894079 2191 if (pDb->dbInf.cursorCommitBehavior == SQL_CB_PRESERVE)
68379eaf 2192 return false;
89894079 2193 else
68379eaf 2194 return true;
108106cf 2195
f6bcfd97 2196} // wxDbTable::IsCursorClosedOnCommit()
108106cf 2197
67e9aaa3 2198
f02d4a64
GT
2199
2200/********** wxDbTable::ClearMemberVar() **********/
b8032740 2201void wxDbTable::ClearMemberVar(UWORD colNumber, bool setToNull)
108106cf 2202{
b8032740 2203 wxASSERT(colNumber < m_numCols);
f02d4a64 2204
b8032740 2205 switch(colDefs[colNumber].SqlCtype)
89894079 2206 {
f02d4a64 2207 case SQL_C_CHAR:
5c2cd0f6 2208#ifndef __UNIX__
e4e45573 2209 case SQL_C_WCHAR:
5c2cd0f6 2210#endif
e4e45573 2211 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
b8032740 2212 ((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] = 0;
f02d4a64
GT
2213 break;
2214 case SQL_C_SSHORT:
b8032740 2215 *((SWORD *) colDefs[colNumber].PtrDataObj) = 0;
f02d4a64
GT
2216 break;
2217 case SQL_C_USHORT:
b8032740 2218 *((UWORD*) colDefs[colNumber].PtrDataObj) = 0;
f02d4a64 2219 break;
f292d0ec 2220 case SQL_C_LONG:
f02d4a64 2221 case SQL_C_SLONG:
b8032740 2222 *((SDWORD *) colDefs[colNumber].PtrDataObj) = 0;
f02d4a64
GT
2223 break;
2224 case SQL_C_ULONG:
b8032740 2225 *((UDWORD *) colDefs[colNumber].PtrDataObj) = 0;
f02d4a64
GT
2226 break;
2227 case SQL_C_FLOAT:
b8032740 2228 *((SFLOAT *) colDefs[colNumber].PtrDataObj) = 0.0f;
f02d4a64
GT
2229 break;
2230 case SQL_C_DOUBLE:
b8032740 2231 *((SDOUBLE *) colDefs[colNumber].PtrDataObj) = 0.0f;
f02d4a64
GT
2232 break;
2233 case SQL_C_TIMESTAMP:
2234 TIMESTAMP_STRUCT *pDt;
b8032740 2235 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
f02d4a64
GT
2236 pDt->year = 0;
2237 pDt->month = 0;
2238 pDt->day = 0;
2239 pDt->hour = 0;
2240 pDt->minute = 0;
2241 pDt->second = 0;
2242 pDt->fraction = 0;
2243 break;
89894079 2244 }
108106cf 2245
f02d4a64 2246 if (setToNull)
b8032740 2247 SetColNull(colNumber);
f02d4a64
GT
2248} // wxDbTable::ClearMemberVar()
2249
2250
2251/********** wxDbTable::ClearMemberVars() **********/
2252void wxDbTable::ClearMemberVars(bool setToNull)
2253{
2254 int i;
2255
2256 // Loop through the columns setting each member variable to zero
b8032740 2257 for (i=0; i < m_numCols; i++)
254a2129 2258 ClearMemberVar((UWORD)i,setToNull);
f02d4a64 2259
f6bcfd97 2260} // wxDbTable::ClearMemberVars()
108106cf 2261
67e9aaa3 2262
f6bcfd97
BP
2263/********** wxDbTable::SetQueryTimeout() **********/
2264bool wxDbTable::SetQueryTimeout(UDWORD nSeconds)
108106cf 2265{
89894079
VZ
2266 if (SQLSetStmtOption(hstmtInsert, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2267 return(pDb->DispAllErrors(henv, hdbc, hstmtInsert));
2268 if (SQLSetStmtOption(hstmtUpdate, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2269 return(pDb->DispAllErrors(henv, hdbc, hstmtUpdate));
2270 if (SQLSetStmtOption(hstmtDelete, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2271 return(pDb->DispAllErrors(henv, hdbc, hstmtDelete));
2272 if (SQLSetStmtOption(hstmtInternal, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2273 return(pDb->DispAllErrors(henv, hdbc, hstmtInternal));
2274
2275 // Completed Successfully
68379eaf 2276 return true;
108106cf 2277
f6bcfd97 2278} // wxDbTable::SetQueryTimeout()
108106cf 2279
67e9aaa3 2280
f6bcfd97 2281/********** wxDbTable::SetColDefs() **********/
b8032740
GT
2282bool wxDbTable::SetColDefs(UWORD index, const wxString &fieldName, int dataType, void *pData,
2283 SWORD cType, int size, bool keyField, bool updateable,
549c8cc2 2284 bool insertAllowed, bool derivedColumn)
108106cf 2285{
b8032740
GT
2286 wxString tmpStr;
2287
2288 if (index >= m_numCols) // Columns numbers are zero based....
2289 {
2290 tmpStr.Printf(wxT("Specified column index (%d) exceeds the maximum number of columns (%d) registered for this table definition. Column definition not added."), index, m_numCols);
2291 wxFAIL_MSG(tmpStr);
2292 wxLogDebug(tmpStr);
2293 return false;
2294 }
ff294e0e 2295
89894079 2296 if (!colDefs) // May happen if the database connection fails
b8032740 2297 return false;
89894079 2298
4fdae997 2299 if (fieldName.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN)
89894079 2300 {
9082f1a9 2301 wxStrncpy(colDefs[index].ColName, fieldName, DB_MAX_COLUMN_NAME_LEN);
b8032740 2302 colDefs[index].ColName[DB_MAX_COLUMN_NAME_LEN] = 0; // Prevent buffer overrun
da38429d 2303
b8032740 2304 tmpStr.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
da38429d 2305 fieldName.c_str(),colDefs[index].ColName);
b8032740
GT
2306 wxFAIL_MSG(tmpStr);
2307 wxLogDebug(tmpStr);
89894079
VZ
2308 }
2309 else
2310 wxStrcpy(colDefs[index].ColName, fieldName);
2311
2312 colDefs[index].DbDataType = dataType;
2313 colDefs[index].PtrDataObj = pData;
2314 colDefs[index].SqlCtype = cType;
e4e45573 2315 colDefs[index].SzDataObj = size; //TODO: glt ??? * sizeof(wxChar) ???
89894079 2316 colDefs[index].KeyField = keyField;
549c8cc2 2317 colDefs[index].DerivedCol = derivedColumn;
89894079 2318 // Derived columns by definition would NOT be "Insertable" or "Updateable"
549c8cc2 2319 if (derivedColumn)
89894079 2320 {
68379eaf
WS
2321 colDefs[index].Updateable = false;
2322 colDefs[index].InsertAllowed = false;
89894079
VZ
2323 }
2324 else
2325 {
b8032740 2326 colDefs[index].Updateable = updateable;
549c8cc2 2327 colDefs[index].InsertAllowed = insertAllowed;
89894079
VZ
2328 }
2329
68379eaf 2330 colDefs[index].Null = false;
da38429d 2331
b8032740
GT
2332 return true;
2333
f6bcfd97 2334} // wxDbTable::SetColDefs()
108106cf 2335
67e9aaa3 2336
e93a3a18 2337/********** wxDbTable::SetColDefs() **********/
87cc3456 2338wxDbColDataPtr* wxDbTable::SetColDefs(wxDbColInf *pColInfs, UWORD numCols)
67e9aaa3 2339{
4fdae997 2340 wxASSERT(pColInfs);
f6bcfd97 2341 wxDbColDataPtr *pColDataPtrs = NULL;
67e9aaa3 2342
89894079
VZ
2343 if (pColInfs)
2344 {
87cc3456 2345 UWORD index;
da38429d 2346
f6bcfd97 2347 pColDataPtrs = new wxDbColDataPtr[numCols+1];
67e9aaa3
GT
2348
2349 for (index = 0; index < numCols; index++)
89894079 2350 {
89894079
VZ
2351 // Process the fields
2352 switch (pColInfs[index].dbDataType)
2353 {
2354 case DB_DATA_TYPE_VARCHAR:
e4e45573
GT
2355 pColDataPtrs[index].PtrDataObj = new wxChar[pColInfs[index].bufferSize+(1*sizeof(wxChar))];
2356 pColDataPtrs[index].SzDataObj = pColInfs[index].bufferSize+(1*sizeof(wxChar));
2357 pColDataPtrs[index].SqlCtype = SQL_C_WXCHAR;
0b8410f3 2358 break;
89894079 2359 case DB_DATA_TYPE_INTEGER:
67e9aaa3 2360 // Can be long or short
e4e45573 2361 if (pColInfs[index].bufferSize == sizeof(long))
89894079
VZ
2362 {
2363 pColDataPtrs[index].PtrDataObj = new long;
2364 pColDataPtrs[index].SzDataObj = sizeof(long);
2365 pColDataPtrs[index].SqlCtype = SQL_C_SLONG;
2366 }
2367 else
2368 {
2369 pColDataPtrs[index].PtrDataObj = new short;
2370 pColDataPtrs[index].SzDataObj = sizeof(short);
2371 pColDataPtrs[index].SqlCtype = SQL_C_SSHORT;
2372 }
2373 break;
89894079 2374 case DB_DATA_TYPE_FLOAT:
89894079 2375 // Can be float or double
e4e45573 2376 if (pColInfs[index].bufferSize == sizeof(float))
89894079
VZ
2377 {
2378 pColDataPtrs[index].PtrDataObj = new float;
2379 pColDataPtrs[index].SzDataObj = sizeof(float);
2380 pColDataPtrs[index].SqlCtype = SQL_C_FLOAT;
2381 }
2382 else
2383 {
2384 pColDataPtrs[index].PtrDataObj = new double;
2385 pColDataPtrs[index].SzDataObj = sizeof(double);
2386 pColDataPtrs[index].SqlCtype = SQL_C_DOUBLE;
da38429d 2387 }
89894079 2388 break;
89894079 2389 case DB_DATA_TYPE_DATE:
89894079
VZ
2390 pColDataPtrs[index].PtrDataObj = new TIMESTAMP_STRUCT;
2391 pColDataPtrs[index].SzDataObj = sizeof(TIMESTAMP_STRUCT);
2392 pColDataPtrs[index].SqlCtype = SQL_C_TIMESTAMP;
2393 break;
bf5423ea 2394 case DB_DATA_TYPE_BLOB:
da38429d 2395 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
bf5423ea
GT
2396 pColDataPtrs[index].PtrDataObj = /*BLOB ADDITION NEEDED*/NULL;
2397 pColDataPtrs[index].SzDataObj = /*BLOB ADDITION NEEDED*/sizeof(void *);
2398 pColDataPtrs[index].SqlCtype = SQL_VARBINARY;
2399 break;
2400 }
2401 if (pColDataPtrs[index].PtrDataObj != NULL)
2402 SetColDefs (index,pColInfs[index].colName,pColInfs[index].dbDataType, pColDataPtrs[index].PtrDataObj, pColDataPtrs[index].SqlCtype, pColDataPtrs[index].SzDataObj);
2403 else
2404 {
da38429d 2405 // Unable to build all the column definitions, as either one of
bf5423ea
GT
2406 // the calls to "new" failed above, or there was a BLOB field
2407 // to have a column definition for. If BLOBs are to be used,
2408 // the other form of ::SetColDefs() must be used, as it is impossible
2409 // to know the maximum size to create the PtrDataObj to be.
2410 delete [] pColDataPtrs;
2411 return NULL;
89894079 2412 }
89894079
VZ
2413 }
2414 }
3ca6a5f0 2415
89894079 2416 return (pColDataPtrs);
3ca6a5f0 2417
e93a3a18 2418} // wxDbTable::SetColDefs()
67e9aaa3
GT
2419
2420
f6bcfd97
BP
2421/********** wxDbTable::SetCursor() **********/
2422void wxDbTable::SetCursor(HSTMT *hstmtActivate)
108106cf 2423{
f6bcfd97 2424 if (hstmtActivate == wxDB_DEFAULT_CURSOR)
89894079
VZ
2425 hstmt = *hstmtDefault;
2426 else
2427 hstmt = *hstmtActivate;
108106cf 2428
f6bcfd97 2429} // wxDbTable::SetCursor()
108106cf 2430
67e9aaa3 2431
4fdae997
GT
2432/********** wxDbTable::Count(const wxString &) **********/
2433ULONG wxDbTable::Count(const wxString &args)
108106cf 2434{
3ca6a5f0 2435 ULONG count;
1e92909e 2436 wxString sqlStmt;
89894079
VZ
2437 SDWORD cb;
2438
2439 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
4fdae997 2440 sqlStmt = wxT("SELECT COUNT(");
1e92909e 2441 sqlStmt += args;
4fdae997 2442 sqlStmt += wxT(") FROM ");
243d4b36
GT
2443 sqlStmt += pDb->SQLTableName(queryTableName);
2444// sqlStmt += queryTableName;
f6bcfd97 2445#if wxODBC_BACKWARD_COMPATABILITY
89894079 2446 if (from && wxStrlen(from))
f6bcfd97
BP
2447#else
2448 if (from.Length())
2449#endif
1e92909e 2450 sqlStmt += from;
89894079
VZ
2451
2452 // Add the where clause if one is provided
f6bcfd97 2453#if wxODBC_BACKWARD_COMPATABILITY
89894079 2454 if (where && wxStrlen(where))
f6bcfd97
BP
2455#else
2456 if (where.Length())
2457#endif
89894079 2458 {
4fdae997 2459 sqlStmt += wxT(" WHERE ");
1e92909e 2460 sqlStmt += where;
89894079
VZ
2461 }
2462
4fdae997 2463 pDb->WriteSqlLog(sqlStmt);
89894079
VZ
2464
2465 // Initialize the Count cursor if it's not already initialized
2466 if (!hstmtCount)
2467 {
68379eaf 2468 hstmtCount = GetNewCursor(false,false);
4fdae997 2469 wxASSERT(hstmtCount);
89894079
VZ
2470 if (!hstmtCount)
2471 return(0);
2472 }
2473
2474 // Execute the SQL statement
8a39593e 2475 if (SQLExecDirect(*hstmtCount, (SQLTCHAR FAR *) sqlStmt.c_str(), SQL_NTS) != SQL_SUCCESS)
89894079
VZ
2476 {
2477 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2478 return(0);
2479 }
2480
2481 // Fetch the record
2482 if (SQLFetch(*hstmtCount) != SQL_SUCCESS)
2483 {
2484 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2485 return(0);
2486 }
2487
2488 // Obtain the result
6b3f4fb8 2489 if (SQLGetData(*hstmtCount, (UWORD)1, SQL_C_ULONG, &count, sizeof(count), &cb) != SQL_SUCCESS)
89894079
VZ
2490 {
2491 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2492 return(0);
2493 }
2494
2495 // Free the cursor
2496 if (SQLFreeStmt(*hstmtCount, SQL_CLOSE) != SQL_SUCCESS)
2497 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2498
2499 // Return the record count
3ca6a5f0 2500 return(count);
108106cf 2501
f6bcfd97 2502} // wxDbTable::Count()
108106cf 2503
67e9aaa3 2504
f6bcfd97
BP
2505/********** wxDbTable::Refresh() **********/
2506bool wxDbTable::Refresh(void)
108106cf 2507{
68379eaf 2508 bool result = true;
89894079
VZ
2509
2510 // Switch to the internal cursor so any active cursors are not corrupted
2511 HSTMT currCursor = GetCursor();
2512 hstmt = hstmtInternal;
f6bcfd97 2513#if wxODBC_BACKWARD_COMPATABILITY
89894079 2514 // Save the where and order by clauses
8a39593e
JS
2515 wxChar *saveWhere = where;
2516 wxChar *saveOrderBy = orderBy;
f6bcfd97
BP
2517#else
2518 wxString saveWhere = where;
2519 wxString saveOrderBy = orderBy;
2520#endif
89894079
VZ
2521 // Build a where clause to refetch the record with. Try and use the
2522 // ROWID if it's available, ow use the key fields.
4fdae997
GT
2523 wxString whereClause;
2524 whereClause.Empty();
2525
b8032740 2526 if (CanUpdateByROWID())
89894079
VZ
2527 {
2528 SDWORD cb;
e4e45573 2529 wxChar rowid[wxDB_ROWID_LEN+1];
89894079
VZ
2530
2531 // Get the ROWID value. If not successful retreiving the ROWID,
2532 // simply fall down through the code and build the WHERE clause
2533 // based on the key fields.
b8032740 2534 if (SQLGetData(hstmt, (UWORD)(m_numCols+1), SQL_C_WXCHAR, (UCHAR*) rowid, sizeof(rowid), &cb) == SQL_SUCCESS)
89894079 2535 {
243d4b36
GT
2536 whereClause += pDb->SQLTableName(queryTableName);
2537// whereClause += queryTableName;
4fdae997
GT
2538 whereClause += wxT(".ROWID = '");
2539 whereClause += rowid;
2540 whereClause += wxT("'");
89894079
VZ
2541 }
2542 }
2543
2544 // If unable to use the ROWID, build a where clause from the keyfields
2545 if (wxStrlen(whereClause) == 0)
f6bcfd97 2546 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS, queryTableName);
89894079
VZ
2547
2548 // Requery the record
2549 where = whereClause;
4fdae997 2550 orderBy.Empty();
89894079 2551 if (!Query())
68379eaf 2552 result = false;
89894079
VZ
2553
2554 if (result && !GetNext())
68379eaf 2555 result = false;
89894079
VZ
2556
2557 // Switch back to original cursor
2558 SetCursor(&currCursor);
2559
2560 // Free the internal cursor
2561 if (SQLFreeStmt(hstmtInternal, SQL_CLOSE) != SQL_SUCCESS)
2562 pDb->DispAllErrors(henv, hdbc, hstmtInternal);
2563
2564 // Restore the original where and order by clauses
1e92909e 2565 where = saveWhere;
89894079
VZ
2566 orderBy = saveOrderBy;
2567
2568 return(result);
108106cf 2569
f6bcfd97 2570} // wxDbTable::Refresh()
108106cf 2571
67e9aaa3 2572
e938ff5e 2573/********** wxDbTable::SetColNull() **********/
b8032740 2574bool wxDbTable::SetColNull(UWORD colNumber, bool set)
a2115c88 2575{
b8032740 2576 if (colNumber < m_numCols)
f02d4a64 2577 {
b8032740 2578 colDefs[colNumber].Null = set;
f02d4a64 2579 if (set) // Blank out the values in the member variable
b8032740 2580 ClearMemberVar(colNumber, false); // Must call with false here, or infinite recursion will happen
e9ed92a2 2581
b8032740 2582 setCbValueForColumn(colNumber);
e9ed92a2 2583
68379eaf 2584 return true;
f02d4a64 2585 }
89894079 2586 else
68379eaf 2587 return false;
a2115c88 2588
4fdae997 2589} // wxDbTable::SetColNull()
67e9aaa3 2590
a2115c88 2591
e938ff5e 2592/********** wxDbTable::SetColNull() **********/
4fdae997 2593bool wxDbTable::SetColNull(const wxString &colName, bool set)
a2115c88 2594{
b8032740
GT
2595 int colNumber;
2596 for (colNumber = 0; colNumber < m_numCols; colNumber++)
89894079 2597 {
b8032740 2598 if (!wxStricmp(colName, colDefs[colNumber].ColName))
89894079
VZ
2599 break;
2600 }
2601
b8032740 2602 if (colNumber < m_numCols)
f02d4a64 2603 {
b8032740 2604 colDefs[colNumber].Null = set;
f02d4a64 2605 if (set) // Blank out the values in the member variable
b8032740 2606 ClearMemberVar((UWORD)colNumber,false); // Must call with false here, or infinite recursion will happen
e9ed92a2 2607
b8032740 2608 setCbValueForColumn(colNumber);
e9ed92a2 2609
68379eaf 2610 return true;
f02d4a64 2611 }
89894079 2612 else
68379eaf 2613 return false;
a2115c88 2614
4fdae997 2615} // wxDbTable::SetColNull()
a2115c88 2616
67e9aaa3 2617
f6bcfd97
BP
2618/********** wxDbTable::GetNewCursor() **********/
2619HSTMT *wxDbTable::GetNewCursor(bool setCursor, bool bindColumns)
a2115c88 2620{
89894079 2621 HSTMT *newHSTMT = new HSTMT;
4fdae997 2622 wxASSERT(newHSTMT);
89894079
VZ
2623 if (!newHSTMT)
2624 return(0);
2625
2626 if (SQLAllocStmt(hdbc, newHSTMT) != SQL_SUCCESS)
2627 {
2628 pDb->DispAllErrors(henv, hdbc);
2629 delete newHSTMT;
2630 return(0);
2631 }
2632
2633 if (SQLSetStmtOption(*newHSTMT, SQL_CURSOR_TYPE, cursorType) != SQL_SUCCESS)
2634 {
2635 pDb->DispAllErrors(henv, hdbc, *newHSTMT);
2636 delete newHSTMT;
2637 return(0);
2638 }
2639
2640 if (bindColumns)
2641 {
882fc8a9 2642 if (!bindCols(*newHSTMT))
89894079
VZ
2643 {
2644 delete newHSTMT;
2645 return(0);
2646 }
2647 }
2648
2649 if (setCursor)
2650 SetCursor(newHSTMT);
2651
2652 return(newHSTMT);
2653
f6bcfd97 2654} // wxDbTable::GetNewCursor()
67e9aaa3 2655
a2115c88 2656
f6bcfd97
BP
2657/********** wxDbTable::DeleteCursor() **********/
2658bool wxDbTable::DeleteCursor(HSTMT *hstmtDel)
a2115c88 2659{
68379eaf 2660 bool result = true;
a2115c88 2661
89894079
VZ
2662 if (!hstmtDel) // Cursor already deleted
2663 return(result);
a2115c88 2664
7d8c3dba
GT
2665/*
2666ODBC 3.0 says to use this form
2667 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
da38429d 2668
7d8c3dba 2669*/
89894079
VZ
2670 if (SQLFreeStmt(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2671 {
2672 pDb->DispAllErrors(henv, hdbc);
68379eaf 2673 result = false;
89894079 2674 }
a2115c88 2675
89894079 2676 delete hstmtDel;
a2115c88 2677
89894079 2678 return(result);
a2115c88 2679
f6bcfd97 2680} // wxDbTable::DeleteCursor()
a2115c88 2681
882fc8a9
GT
2682//////////////////////////////////////////////////////////////
2683// wxDbGrid support functions
2684//////////////////////////////////////////////////////////////
2685
2686void wxDbTable::SetRowMode(const rowmode_t rowmode)
2687{
2688 if (!m_hstmtGridQuery)
2689 {
68379eaf 2690 m_hstmtGridQuery = GetNewCursor(false,false);
882fc8a9
GT
2691 if (!bindCols(*m_hstmtGridQuery))
2692 return;
2693 }
2694
2695 m_rowmode = rowmode;
2696 switch (m_rowmode)
2697 {
2698 case WX_ROW_MODE_QUERY:
2699 SetCursor(m_hstmtGridQuery);
2700 break;
2701 case WX_ROW_MODE_INDIVIDUAL:
2702 SetCursor(hstmtDefault);
2703 break;
2704 default:
e7c9692f 2705 wxASSERT(0);
882fc8a9
GT
2706 }
2707} // wxDbTable::SetRowMode()
2708
2709
b8032740 2710wxVariant wxDbTable::GetColumn(const int colNumber) const
882fc8a9
GT
2711{
2712 wxVariant val;
b8032740 2713 if ((colNumber < m_numCols) && (!IsColNull((UWORD)colNumber)))
882fc8a9 2714 {
b8032740 2715 switch (colDefs[colNumber].SqlCtype)
882fc8a9 2716 {
38ae3a10
GT
2717 case SQL_WCHAR:
2718 case SQL_WVARCHAR:
882fc8a9
GT
2719 case SQL_CHAR:
2720 case SQL_VARCHAR:
b8032740 2721 val = (wxChar *)(colDefs[colNumber].PtrDataObj);
882fc8a9
GT
2722 break;
2723 case SQL_C_LONG:
2724 case SQL_C_SLONG:
b8032740 2725 val = *(long *)(colDefs[colNumber].PtrDataObj);
882fc8a9
GT
2726 break;
2727 case SQL_C_SHORT:
2728 case SQL_C_SSHORT:
b8032740 2729 val = (long int )(*(short *)(colDefs[colNumber].PtrDataObj));
882fc8a9
GT
2730 break;
2731 case SQL_C_ULONG:
b8032740 2732 val = (long)(*(unsigned long *)(colDefs[colNumber].PtrDataObj));
882fc8a9
GT
2733 break;
2734 case SQL_C_TINYINT:
b8032740 2735 val = (long)(*(wxChar *)(colDefs[colNumber].PtrDataObj));
882fc8a9
GT
2736 break;
2737 case SQL_C_UTINYINT:
b8032740 2738 val = (long)(*(wxChar *)(colDefs[colNumber].PtrDataObj));
882fc8a9
GT
2739 break;
2740 case SQL_C_USHORT:
b8032740 2741 val = (long)(*(UWORD *)(colDefs[colNumber].PtrDataObj));
882fc8a9
GT
2742 break;
2743 case SQL_C_DATE:
b8032740 2744 val = (DATE_STRUCT *)(colDefs[colNumber].PtrDataObj);
882fc8a9
GT
2745 break;
2746 case SQL_C_TIME:
b8032740 2747 val = (TIME_STRUCT *)(colDefs[colNumber].PtrDataObj);
882fc8a9
GT
2748 break;
2749 case SQL_C_TIMESTAMP:
b8032740 2750 val = (TIMESTAMP_STRUCT *)(colDefs[colNumber].PtrDataObj);
882fc8a9
GT
2751 break;
2752 case SQL_C_DOUBLE:
b8032740 2753 val = *(double *)(colDefs[colNumber].PtrDataObj);
882fc8a9
GT
2754 break;
2755 default:
2756 assert(0);
2757 }
2758 }
2759 return val;
2760} // wxDbTable::GetCol()
2761
2762
b8032740 2763void wxDbTable::SetColumn(const int colNumber, const wxVariant val)
882fc8a9
GT
2764{
2765 //FIXME: Add proper wxDateTime support to wxVariant..
2766 wxDateTime dateval;
2767
b8032740 2768 SetColNull((UWORD)colNumber, val.IsNull());
882fc8a9
GT
2769
2770 if (!val.IsNull())
2771 {
b8032740
GT
2772 if ((colDefs[colNumber].SqlCtype == SQL_C_DATE)
2773 || (colDefs[colNumber].SqlCtype == SQL_C_TIME)
2774 || (colDefs[colNumber].SqlCtype == SQL_C_TIMESTAMP))
882fc8a9
GT
2775 {
2776 //Returns null if invalid!
2777 if (!dateval.ParseDate(val.GetString()))
b8032740 2778 SetColNull((UWORD)colNumber, true);
da38429d 2779 }
882fc8a9 2780
b8032740 2781 switch (colDefs[colNumber].SqlCtype)
882fc8a9 2782 {
38ae3a10
GT
2783 case SQL_WCHAR:
2784 case SQL_WVARCHAR:
882fc8a9
GT
2785 case SQL_CHAR:
2786 case SQL_VARCHAR:
b8032740 2787 csstrncpyt((wxChar *)(colDefs[colNumber].PtrDataObj),
da38429d 2788 val.GetString().c_str(),
b8032740 2789 colDefs[colNumber].SzDataObj-1); //TODO: glt ??? * sizeof(wxChar) ???
882fc8a9
GT
2790 break;
2791 case SQL_C_LONG:
2792 case SQL_C_SLONG:
b8032740 2793 *(long *)(colDefs[colNumber].PtrDataObj) = val;
882fc8a9
GT
2794 break;
2795 case SQL_C_SHORT:
2796 case SQL_C_SSHORT:
b8032740 2797 *(short *)(colDefs[colNumber].PtrDataObj) = (short)val.GetLong();
882fc8a9
GT
2798 break;
2799 case SQL_C_ULONG:
b8032740 2800 *(unsigned long *)(colDefs[colNumber].PtrDataObj) = val.GetLong();
882fc8a9
GT
2801 break;
2802 case SQL_C_TINYINT:
b8032740 2803 *(wxChar *)(colDefs[colNumber].PtrDataObj) = val.GetChar();
882fc8a9
GT
2804 break;
2805 case SQL_C_UTINYINT:
b8032740 2806 *(wxChar *)(colDefs[colNumber].PtrDataObj) = val.GetChar();
882fc8a9
GT
2807 break;
2808 case SQL_C_USHORT:
b8032740 2809 *(unsigned short *)(colDefs[colNumber].PtrDataObj) = (unsigned short)val.GetLong();
882fc8a9
GT
2810 break;
2811 //FIXME: Add proper wxDateTime support to wxVariant..
2812 case SQL_C_DATE:
2813 {
2814 DATE_STRUCT *dataptr =
b8032740 2815 (DATE_STRUCT *)colDefs[colNumber].PtrDataObj;
da38429d 2816
39d350d6
WS
2817 dataptr->year = (SWORD)dateval.GetYear();
2818 dataptr->month = (UWORD)(dateval.GetMonth()+1);
2819 dataptr->day = (UWORD)dateval.GetDay();
882fc8a9
GT
2820 }
2821 break;
2822 case SQL_C_TIME:
2823 {
2824 TIME_STRUCT *dataptr =
b8032740 2825 (TIME_STRUCT *)colDefs[colNumber].PtrDataObj;
da38429d 2826
882fc8a9
GT
2827 dataptr->hour = dateval.GetHour();
2828 dataptr->minute = dateval.GetMinute();
2829 dataptr->second = dateval.GetSecond();
2830 }
2831 break;
2832 case SQL_C_TIMESTAMP:
2833 {
2834 TIMESTAMP_STRUCT *dataptr =
b8032740 2835 (TIMESTAMP_STRUCT *)colDefs[colNumber].PtrDataObj;
39d350d6
WS
2836 dataptr->year = (SWORD)dateval.GetYear();
2837 dataptr->month = (UWORD)(dateval.GetMonth()+1);
2838 dataptr->day = (UWORD)dateval.GetDay();
da38429d 2839
882fc8a9
GT
2840 dataptr->hour = dateval.GetHour();
2841 dataptr->minute = dateval.GetMinute();
2842 dataptr->second = dateval.GetSecond();
2843 }
2844 break;
2845 case SQL_C_DOUBLE:
b8032740 2846 *(double *)(colDefs[colNumber].PtrDataObj) = val;
882fc8a9
GT
2847 break;
2848 default:
2849 assert(0);
2850 } // switch
2851 } // if (!val.IsNull())
2852} // wxDbTable::SetCol()
2853
2854
2855GenericKey wxDbTable::GetKey()
2856{
2857 void *blk;
1dee6b39 2858 wxChar *blkptr;
da38429d 2859
882fc8a9 2860 blk = malloc(m_keysize);
1dee6b39 2861 blkptr = (wxChar *) blk;
da38429d 2862
882fc8a9 2863 int i;
b8032740 2864 for (i=0; i < m_numCols; i++)
882fc8a9
GT
2865 {
2866 if (colDefs[i].KeyField)
2867 {
2868 memcpy(blkptr,colDefs[i].PtrDataObj, colDefs[i].SzDataObj);
2869 blkptr += colDefs[i].SzDataObj;
2870 }
2871 }
2872
2873 GenericKey k = GenericKey(blk, m_keysize);
2874 free(blk);
2875
2876 return k;
2877} // wxDbTable::GetKey()
2878
2879
2880void wxDbTable::SetKey(const GenericKey& k)
2881{
1dee6b39
GT
2882 void *blk;
2883 wxChar *blkptr;
da38429d 2884
882fc8a9 2885 blk = k.GetBlk();
1dee6b39 2886 blkptr = (wxChar *)blk;
882fc8a9
GT
2887
2888 int i;
b8032740 2889 for (i=0; i < m_numCols; i++)
882fc8a9
GT
2890 {
2891 if (colDefs[i].KeyField)
2892 {
254a2129 2893 SetColNull((UWORD)i, false);
882fc8a9
GT
2894 memcpy(colDefs[i].PtrDataObj, blkptr, colDefs[i].SzDataObj);
2895 blkptr += colDefs[i].SzDataObj;
2896 }
2897 }
2898} // wxDbTable::SetKey()
2899
2900
a2115c88 2901#endif // wxUSE_ODBC
1fc5dd6f 2902