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