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