]> git.saurik.com Git - wxWidgets.git/blob - src/common/dbtable.cpp
really fixed wxConfig bug
[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 UWORD numColumns,
132 const wxString &qryTblName, bool qryOnly, const wxString &tblPath)
133 {
134 if (!initialize(pwxDb, tblName, numColumns, 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 UWORD numColumns,
141 const wxChar *qryTblName, bool qryOnly, const wxString &tblPath)
142 {
143 wxString tempQryTblName;
144 tempQryTblName = qryTblName;
145 if (!initialize(pwxDb, tblName, numColumns, 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 UWORD numColumns,
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 = numColumns; // Number 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::bindParams() **********/
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;
434 UWORD colNo;
435
436 for (i=0, colNo=1; i < noCols; i++)
437 {
438 if (forUpdate)
439 {
440 if (!colDefs[i].Updateable)
441 continue;
442 }
443 else
444 {
445 if (!colDefs[i].InsertAllowed)
446 continue;
447 }
448
449 switch(colDefs[i].DbDataType)
450 {
451 case DB_DATA_TYPE_VARCHAR:
452 fSqlType = pDb->GetTypeInfVarchar().FsqlType;
453 precision = colDefs[i].SzDataObj;
454 scale = 0;
455 if (colDefs[i].Null)
456 colDefs[i].CbValue = SQL_NULL_DATA;
457 else
458 colDefs[i].CbValue = SQL_NTS;
459 break;
460 case DB_DATA_TYPE_INTEGER:
461 fSqlType = pDb->GetTypeInfInteger().FsqlType;
462 precision = pDb->GetTypeInfInteger().Precision;
463 scale = 0;
464 if (colDefs[i].Null)
465 colDefs[i].CbValue = SQL_NULL_DATA;
466 else
467 colDefs[i].CbValue = 0;
468 break;
469 case DB_DATA_TYPE_FLOAT:
470 fSqlType = pDb->GetTypeInfFloat().FsqlType;
471 precision = pDb->GetTypeInfFloat().Precision;
472 scale = pDb->GetTypeInfFloat().MaximumScale;
473 // SQL Sybase Anywhere v5.5 returned a negative number for the
474 // MaxScale. This caused ODBC to kick out an error on ibscale.
475 // I check for this here and set the scale = precision.
476 //if (scale < 0)
477 // scale = (short) precision;
478 if (colDefs[i].Null)
479 colDefs[i].CbValue = SQL_NULL_DATA;
480 else
481 colDefs[i].CbValue = 0;
482 break;
483 case DB_DATA_TYPE_DATE:
484 fSqlType = pDb->GetTypeInfDate().FsqlType;
485 precision = pDb->GetTypeInfDate().Precision;
486 scale = 0;
487 if (colDefs[i].Null)
488 colDefs[i].CbValue = SQL_NULL_DATA;
489 else
490 colDefs[i].CbValue = 0;
491 break;
492 case DB_DATA_TYPE_BLOB:
493 fSqlType = pDb->GetTypeInfBlob().FsqlType;
494 precision = 50000;
495 scale = 0;
496 if (colDefs[i].Null)
497 colDefs[i].CbValue = SQL_NULL_DATA;
498 else
499 colDefs[i].CbValue = SQL_LEN_DATA_AT_EXEC(colDefs[i].SzDataObj);
500 break;
501 }
502 if (forUpdate)
503 {
504 if (SQLBindParameter(hstmtUpdate, colNo++, SQL_PARAM_INPUT, colDefs[i].SqlCtype,
505 fSqlType, precision, scale, (UCHAR*) colDefs[i].PtrDataObj,
506 precision+1, &colDefs[i].CbValue) != SQL_SUCCESS)
507 {
508 return(pDb->DispAllErrors(henv, hdbc, hstmtUpdate));
509 }
510 }
511 else
512 {
513 if (SQLBindParameter(hstmtInsert, colNo++, SQL_PARAM_INPUT, colDefs[i].SqlCtype,
514 fSqlType, precision, scale, (UCHAR*) colDefs[i].PtrDataObj,
515 precision+1,&colDefs[i].CbValue) != SQL_SUCCESS)
516 {
517 return(pDb->DispAllErrors(henv, hdbc, hstmtInsert));
518 }
519 }
520 }
521
522 // Completed successfully
523 return(TRUE);
524
525 } // wxDbTable::bindParams()
526
527
528 /********** wxDbTable::bindInsertParams() **********/
529 bool wxDbTable::bindInsertParams(void)
530 {
531 return bindParams(FALSE);
532 } // wxDbTable::bindInsertParams()
533
534
535 /********** wxDbTable::bindUpdateParams() **********/
536 bool wxDbTable::bindUpdateParams(void)
537 {
538 return bindParams(TRUE);
539 } // wxDbTable::bindUpdateParams()
540
541
542 /********** wxDbTable::bindCols() **********/
543 bool wxDbTable::bindCols(HSTMT cursor)
544 {
545 // Bind each column of the table to a memory address for fetching data
546 UWORD i;
547 for (i = 0; i < noCols; i++)
548 {
549 if (SQLBindCol(cursor, (UWORD)(i+1), colDefs[i].SqlCtype, (UCHAR*) colDefs[i].PtrDataObj,
550 colDefs[i].SzDataObj, &colDefs[i].CbValue ) != SQL_SUCCESS)
551 {
552 return (pDb->DispAllErrors(henv, hdbc, cursor));
553 }
554 }
555
556 // Completed successfully
557 return(TRUE);
558
559 } // wxDbTable::bindCols()
560
561
562 /********** wxDbTable::getRec() **********/
563 bool wxDbTable::getRec(UWORD fetchType)
564 {
565 RETCODE retcode;
566
567 if (!pDb->FwdOnlyCursors())
568 {
569 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
570 UDWORD cRowsFetched;
571 UWORD rowStatus;
572
573 retcode = SQLExtendedFetch(hstmt, fetchType, 0, &cRowsFetched, &rowStatus);
574 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
575 {
576 if (retcode == SQL_NO_DATA_FOUND)
577 return(FALSE);
578 else
579 return(pDb->DispAllErrors(henv, hdbc, hstmt));
580 }
581 else
582 {
583 // Set the Null member variable to indicate the Null state
584 // of each column just read in.
585 int i;
586 for (i = 0; i < noCols; i++)
587 colDefs[i].Null = (colDefs[i].CbValue == SQL_NULL_DATA);
588 }
589 }
590 else
591 {
592 // Fetch the next record from the record set
593 retcode = SQLFetch(hstmt);
594 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
595 {
596 if (retcode == SQL_NO_DATA_FOUND)
597 return(FALSE);
598 else
599 return(pDb->DispAllErrors(henv, hdbc, hstmt));
600 }
601 else
602 {
603 // Set the Null member variable to indicate the Null state
604 // of each column just read in.
605 int i;
606 for (i = 0; i < noCols; i++)
607 colDefs[i].Null = (colDefs[i].CbValue == SQL_NULL_DATA);
608 }
609 }
610
611 // Completed successfully
612 return(TRUE);
613
614 } // wxDbTable::getRec()
615
616
617 /********** wxDbTable::execDelete() **********/
618 bool wxDbTable::execDelete(const wxString &pSqlStmt)
619 {
620 RETCODE retcode;
621
622 // Execute the DELETE statement
623 retcode = SQLExecDirect(hstmtDelete, (UCHAR FAR *) pSqlStmt.c_str(), SQL_NTS);
624
625 if (retcode == SQL_SUCCESS ||
626 retcode == SQL_NO_DATA_FOUND ||
627 retcode == SQL_SUCCESS_WITH_INFO)
628 {
629 // Record deleted successfully
630 return(TRUE);
631 }
632
633 // Problem deleting record
634 return(pDb->DispAllErrors(henv, hdbc, hstmtDelete));
635
636 } // wxDbTable::execDelete()
637
638
639 /********** wxDbTable::execUpdate() **********/
640 bool wxDbTable::execUpdate(const wxString &pSqlStmt)
641 {
642 RETCODE retcode;
643
644 // Execute the UPDATE statement
645 retcode = SQLExecDirect(hstmtUpdate, (UCHAR FAR *) pSqlStmt.c_str(), SQL_NTS);
646
647 if (retcode == SQL_SUCCESS ||
648 retcode == SQL_NO_DATA_FOUND ||
649 retcode == SQL_SUCCESS_WITH_INFO)
650 {
651 // Record updated successfully
652 return(TRUE);
653 }
654
655 // Problem updating record
656 return(pDb->DispAllErrors(henv, hdbc, hstmtUpdate));
657
658 } // wxDbTable::execUpdate()
659
660
661 /********** wxDbTable::query() **********/
662 bool wxDbTable::query(int queryType, bool forUpdate, bool distinct, const wxString &pSqlStmt)
663 {
664 wxString sqlStmt;
665
666 if (forUpdate)
667 // The user may wish to select for update, but the DBMS may not be capable
668 selectForUpdate = CanSelectForUpdate();
669 else
670 selectForUpdate = FALSE;
671
672 // Set the SQL SELECT string
673 if (queryType != DB_SELECT_STATEMENT) // A select statement was not passed in,
674 { // so generate a select statement.
675 BuildSelectStmt(sqlStmt, queryType, distinct);
676 pDb->WriteSqlLog(sqlStmt);
677 }
678
679 // Make sure the cursor is closed first
680 if (!CloseCursor(hstmt))
681 return(FALSE);
682
683 // Execute the SQL SELECT statement
684 int retcode;
685 retcode = SQLExecDirect(hstmt, (UCHAR FAR *) (queryType == DB_SELECT_STATEMENT ? pSqlStmt.c_str() : sqlStmt.c_str()), SQL_NTS);
686 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
687 return(pDb->DispAllErrors(henv, hdbc, hstmt));
688
689 // Completed successfully
690 return(TRUE);
691
692 } // wxDbTable::query()
693
694
695 /***************************** PUBLIC FUNCTIONS *****************************/
696
697
698 /********** wxDbTable::Open() **********/
699 bool wxDbTable::Open(bool checkPrivileges, bool checkTableExists)
700 {
701 if (!pDb)
702 return FALSE;
703
704 int i;
705 wxString sqlStmt;
706 wxString s;
707
708 s.Empty();
709 // Verify that the table exists in the database
710 if (checkTableExists && !pDb->TableExists(tableName, pDb->GetUsername(), tablePath))
711 {
712 s = wxT("Table/view does not exist in the database");
713 if ( *(pDb->dbInf.accessibleTables) == wxT('Y'))
714 s += wxT(", or you have no permissions.\n");
715 else
716 s += wxT(".\n");
717 }
718 else if (checkPrivileges)
719 {
720 // Verify the user has rights to access the table.
721 // Shortcut boolean evaluation to optimize out call to
722 // TablePrivileges
723 //
724 // Unfortunately this optimization doesn't seem to be
725 // reliable!
726 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
727 !pDb->TablePrivileges(tableName,wxT("SELECT"), pDb->GetUsername(), pDb->GetUsername(), tablePath))
728 s = wxT("Current logged in user does not have sufficient privileges to access this table.\n");
729 }
730
731 if (!s.IsEmpty())
732 {
733 wxString p;
734
735 if (!tablePath.IsEmpty())
736 p.Printf(wxT("Error opening '%s/%s'.\n"),tablePath.c_str(),tableName.c_str());
737 else
738 p.Printf(wxT("Error opening '%s'.\n"), tableName.c_str());
739
740 p += s;
741 pDb->LogError(p.GetData());
742
743 return(FALSE);
744 }
745
746 // Bind the member variables for field exchange between
747 // the wxDbTable object and the ODBC record.
748 if (!queryOnly)
749 {
750 if (!bindInsertParams()) // Inserts
751 return(FALSE);
752
753 if (!bindUpdateParams()) // Updates
754 return(FALSE);
755 }
756
757 if (!bindCols(*hstmtDefault)) // Selects
758 return(FALSE);
759
760 if (!bindCols(hstmtInternal)) // Internal use only
761 return(FALSE);
762
763 /*
764 * Do NOT bind the hstmtCount cursor!!!
765 */
766
767 // Build an insert statement using parameter markers
768 if (!queryOnly && noCols > 0)
769 {
770 bool needComma = FALSE;
771 sqlStmt.Printf(wxT("INSERT INTO %s ("), tableName.c_str());
772 for (i = 0; i < noCols; i++)
773 {
774 if (! colDefs[i].InsertAllowed)
775 continue;
776 if (needComma)
777 sqlStmt += wxT(",");
778 sqlStmt += colDefs[i].ColName;
779 needComma = TRUE;
780 }
781 needComma = FALSE;
782 sqlStmt += wxT(") VALUES (");
783
784 int insertableCount = 0;
785
786 for (i = 0; i < noCols; i++)
787 {
788 if (! colDefs[i].InsertAllowed)
789 continue;
790 if (needComma)
791 sqlStmt += wxT(",");
792 sqlStmt += wxT("?");
793 needComma = TRUE;
794 insertableCount++;
795 }
796 sqlStmt += wxT(")");
797
798 // Prepare the insert statement for execution
799 if (insertableCount)
800 {
801 if (SQLPrepare(hstmtInsert, (UCHAR FAR *) sqlStmt.c_str(), SQL_NTS) != SQL_SUCCESS)
802 return(pDb->DispAllErrors(henv, hdbc, hstmtInsert));
803 }
804 else
805 insertable= FALSE;
806 }
807
808 // Completed successfully
809 return(TRUE);
810
811 } // wxDbTable::Open()
812
813
814 /********** wxDbTable::Query() **********/
815 bool wxDbTable::Query(bool forUpdate, bool distinct)
816 {
817
818 return(query(DB_SELECT_WHERE, forUpdate, distinct));
819
820 } // wxDbTable::Query()
821
822
823 /********** wxDbTable::QueryBySqlStmt() **********/
824 bool wxDbTable::QueryBySqlStmt(const wxString &pSqlStmt)
825 {
826 pDb->WriteSqlLog(pSqlStmt);
827
828 return(query(DB_SELECT_STATEMENT, FALSE, FALSE, pSqlStmt));
829
830 } // wxDbTable::QueryBySqlStmt()
831
832
833 /********** wxDbTable::QueryMatching() **********/
834 bool wxDbTable::QueryMatching(bool forUpdate, bool distinct)
835 {
836
837 return(query(DB_SELECT_MATCHING, forUpdate, distinct));
838
839 } // wxDbTable::QueryMatching()
840
841
842 /********** wxDbTable::QueryOnKeyFields() **********/
843 bool wxDbTable::QueryOnKeyFields(bool forUpdate, bool distinct)
844 {
845
846 return(query(DB_SELECT_KEYFIELDS, forUpdate, distinct));
847
848 } // wxDbTable::QueryOnKeyFields()
849
850
851 /********** wxDbTable::GetPrev() **********/
852 bool wxDbTable::GetPrev(void)
853 {
854 if (pDb->FwdOnlyCursors())
855 {
856 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
857 return FALSE;
858 }
859 else
860 return(getRec(SQL_FETCH_PRIOR));
861
862 } // wxDbTable::GetPrev()
863
864
865 /********** wxDbTable::operator-- **********/
866 bool wxDbTable::operator--(int)
867 {
868 if (pDb->FwdOnlyCursors())
869 {
870 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
871 return FALSE;
872 }
873 else
874 return(getRec(SQL_FETCH_PRIOR));
875
876 } // wxDbTable::operator--
877
878
879 /********** wxDbTable::GetFirst() **********/
880 bool wxDbTable::GetFirst(void)
881 {
882 if (pDb->FwdOnlyCursors())
883 {
884 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
885 return FALSE;
886 }
887 else
888 return(getRec(SQL_FETCH_FIRST));
889
890 } // wxDbTable::GetFirst()
891
892
893 /********** wxDbTable::GetLast() **********/
894 bool wxDbTable::GetLast(void)
895 {
896 if (pDb->FwdOnlyCursors())
897 {
898 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
899 return FALSE;
900 }
901 else
902 return(getRec(SQL_FETCH_LAST));
903
904 } // wxDbTable::GetLast()
905
906
907 /********** wxDbTable::BuildDeleteStmt() **********/
908 void wxDbTable::BuildDeleteStmt(wxString &pSqlStmt, int typeOfDel, const wxString &pWhereClause)
909 {
910 wxASSERT(!queryOnly);
911 if (queryOnly)
912 return;
913
914 wxString whereClause;
915
916 whereClause.Empty();
917
918 // Handle the case of DeleteWhere() and the where clause is blank. It should
919 // delete all records from the database in this case.
920 if (typeOfDel == DB_DEL_WHERE && (pWhereClause.Length() == 0))
921 {
922 pSqlStmt.Printf(wxT("DELETE FROM %s"), tableName.c_str());
923 return;
924 }
925
926 pSqlStmt.Printf(wxT("DELETE FROM %s WHERE "), tableName.c_str());
927
928 // Append the WHERE clause to the SQL DELETE statement
929 switch(typeOfDel)
930 {
931 case DB_DEL_KEYFIELDS:
932 // If the datasource supports the ROWID column, build
933 // the where on ROWID for efficiency purposes.
934 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
935 if (CanUpdByROWID())
936 {
937 SDWORD cb;
938 wxChar rowid[wxDB_ROWID_LEN+1];
939
940 // Get the ROWID value. If not successful retreiving the ROWID,
941 // simply fall down through the code and build the WHERE clause
942 // based on the key fields.
943 if (SQLGetData(hstmt, (UWORD)(noCols+1), SQL_C_CHAR, (UCHAR*) rowid, wxDB_ROWID_LEN, &cb) == SQL_SUCCESS)
944 {
945 pSqlStmt += wxT("ROWID = '");
946 pSqlStmt += rowid;
947 pSqlStmt += wxT("'");
948 break;
949 }
950 }
951 // Unable to delete by ROWID, so build a WHERE
952 // clause based on the keyfields.
953 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS);
954 pSqlStmt += whereClause;
955 break;
956 case DB_DEL_WHERE:
957 pSqlStmt += pWhereClause;
958 break;
959 case DB_DEL_MATCHING:
960 BuildWhereClause(whereClause, DB_WHERE_MATCHING);
961 pSqlStmt += whereClause;
962 break;
963 }
964
965 } // BuildDeleteStmt()
966
967
968 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
969 void wxDbTable::BuildDeleteStmt(wxChar *pSqlStmt, int typeOfDel, const wxString &pWhereClause)
970 {
971 wxString tempSqlStmt;
972 BuildDeleteStmt(tempSqlStmt, typeOfDel, pWhereClause);
973 wxStrcpy(pSqlStmt, tempSqlStmt);
974 } // wxDbTable::BuildDeleteStmt()
975
976
977 /********** wxDbTable::BuildSelectStmt() **********/
978 void wxDbTable::BuildSelectStmt(wxString &pSqlStmt, int typeOfSelect, bool distinct)
979 {
980 wxString whereClause;
981 whereClause.Empty();
982
983 // Build a select statement to query the database
984 pSqlStmt = wxT("SELECT ");
985
986 // SELECT DISTINCT values only?
987 if (distinct)
988 pSqlStmt += wxT("DISTINCT ");
989
990 // Was a FROM clause specified to join tables to the base table?
991 // Available for ::Query() only!!!
992 bool appendFromClause = FALSE;
993 #if wxODBC_BACKWARD_COMPATABILITY
994 if (typeOfSelect == DB_SELECT_WHERE && from && wxStrlen(from))
995 appendFromClause = TRUE;
996 #else
997 if (typeOfSelect == DB_SELECT_WHERE && from.Length())
998 appendFromClause = TRUE;
999 #endif
1000
1001 // Add the column list
1002 int i;
1003 for (i = 0; i < noCols; i++)
1004 {
1005 // If joining tables, the base table column names must be qualified to avoid ambiguity
1006 if (appendFromClause || pDb->Dbms() == dbmsACCESS)
1007 {
1008 pSqlStmt += queryTableName;
1009 pSqlStmt += wxT(".");
1010 }
1011 pSqlStmt += colDefs[i].ColName;
1012 if (i + 1 < noCols)
1013 pSqlStmt += wxT(",");
1014 }
1015
1016 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1017 // the ROWID if querying distinct records. The rowid will always be unique.
1018 if (!distinct && CanUpdByROWID())
1019 {
1020 // If joining tables, the base table column names must be qualified to avoid ambiguity
1021 if (appendFromClause || pDb->Dbms() == dbmsACCESS)
1022 {
1023 pSqlStmt += wxT(",");
1024 pSqlStmt += queryTableName;
1025 pSqlStmt += wxT(".ROWID");
1026 }
1027 else
1028 pSqlStmt += wxT(",ROWID");
1029 }
1030
1031 // Append the FROM tablename portion
1032 pSqlStmt += wxT(" FROM ");
1033 pSqlStmt += queryTableName;
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))
1041 pSqlStmt += wxT(" HOLDLOCK");
1042
1043 if (appendFromClause)
1044 pSqlStmt += from;
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 {
1050 case DB_SELECT_WHERE:
1051 #if wxODBC_BACKWARD_COMPATABILITY
1052 if (where && wxStrlen(where)) // May not want a where clause!!!
1053 #else
1054 if (where.Length()) // May not want a where clause!!!
1055 #endif
1056 {
1057 pSqlStmt += wxT(" WHERE ");
1058 pSqlStmt += where;
1059 }
1060 break;
1061 case DB_SELECT_KEYFIELDS:
1062 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS);
1063 if (whereClause.Length())
1064 {
1065 pSqlStmt += wxT(" WHERE ");
1066 pSqlStmt += whereClause;
1067 }
1068 break;
1069 case DB_SELECT_MATCHING:
1070 BuildWhereClause(whereClause, DB_WHERE_MATCHING);
1071 if (whereClause.Length())
1072 {
1073 pSqlStmt += wxT(" WHERE ");
1074 pSqlStmt += whereClause;
1075 }
1076 break;
1077 }
1078
1079 // Append the ORDER BY clause
1080 #if wxODBC_BACKWARD_COMPATABILITY
1081 if (orderBy && wxStrlen(orderBy))
1082 #else
1083 if (orderBy.Length())
1084 #endif
1085 {
1086 pSqlStmt += wxT(" ORDER BY ");
1087 pSqlStmt += orderBy;
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())
1094 pSqlStmt += wxT(" FOR UPDATE");
1095
1096 } // wxDbTable::BuildSelectStmt()
1097
1098
1099 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1100 void wxDbTable::BuildSelectStmt(wxChar *pSqlStmt, int typeOfSelect, bool distinct)
1101 {
1102 wxString tempSqlStmt;
1103 BuildSelectStmt(tempSqlStmt, typeOfSelect, distinct);
1104 wxStrcpy(pSqlStmt, tempSqlStmt);
1105 } // wxDbTable::BuildSelectStmt()
1106
1107
1108 /********** wxDbTable::BuildUpdateStmt() **********/
1109 void 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
1118 bool firstColumn = TRUE;
1119
1120 pSqlStmt.Printf(wxT("UPDATE %s SET "), tableName.Upper().c_str());
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 {
1129 if (!firstColumn)
1130 pSqlStmt += wxT(",");
1131 else
1132 firstColumn = FALSE;
1133 pSqlStmt += colDefs[i].ColName;
1134 pSqlStmt += wxT(" = ?");
1135 }
1136 }
1137
1138 // Append the WHERE clause to the SQL UPDATE statement
1139 pSqlStmt += wxT(" WHERE ");
1140 switch(typeOfUpd)
1141 {
1142 case DB_UPD_KEYFIELDS:
1143 // If the datasource supports the ROWID column, build
1144 // the where on ROWID for efficiency purposes.
1145 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1146 if (CanUpdByROWID())
1147 {
1148 SDWORD cb;
1149 wxChar rowid[wxDB_ROWID_LEN+1];
1150
1151 // Get the ROWID value. If not successful retreiving the ROWID,
1152 // simply fall down through the code and build the WHERE clause
1153 // based on the key fields.
1154 if (SQLGetData(hstmt, (UWORD)(noCols+1), SQL_C_CHAR, (UCHAR*) rowid, wxDB_ROWID_LEN, &cb) == SQL_SUCCESS)
1155 {
1156 pSqlStmt += wxT("ROWID = '");
1157 pSqlStmt += rowid;
1158 pSqlStmt += wxT("'");
1159 break;
1160 }
1161 }
1162 // Unable to delete by ROWID, so build a WHERE
1163 // clause based on the keyfields.
1164 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS);
1165 pSqlStmt += whereClause;
1166 break;
1167 case DB_UPD_WHERE:
1168 pSqlStmt += pWhereClause;
1169 break;
1170 }
1171 } // BuildUpdateStmt()
1172
1173
1174 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1175 void wxDbTable::BuildUpdateStmt(wxChar *pSqlStmt, int typeOfUpd, const wxString &pWhereClause)
1176 {
1177 wxString tempSqlStmt;
1178 BuildUpdateStmt(tempSqlStmt, typeOfUpd, pWhereClause);
1179 wxStrcpy(pSqlStmt, tempSqlStmt);
1180 } // BuildUpdateStmt()
1181
1182
1183 /********** wxDbTable::BuildWhereClause() **********/
1184 void wxDbTable::BuildWhereClause(wxString &pWhereClause, int typeOfWhere,
1185 const wxString &qualTableName, bool useLikeComparison)
1186 /*
1187 * Note: BuildWhereClause() currently ignores timestamp columns.
1188 * They are not included as part of the where clause.
1189 */
1190 {
1191 bool moreThanOneColumn = FALSE;
1192 wxString colValue;
1193
1194 // Loop through the columns building a where clause as you go
1195 int i;
1196 for (i = 0; i < noCols; i++)
1197 {
1198 // Determine if this column should be included in the WHERE clause
1199 if ((typeOfWhere == DB_WHERE_KEYFIELDS && colDefs[i].KeyField) ||
1200 (typeOfWhere == DB_WHERE_MATCHING && (!IsColNull(i))))
1201 {
1202 // Skip over timestamp columns
1203 if (colDefs[i].SqlCtype == SQL_C_TIMESTAMP)
1204 continue;
1205 // If there is more than 1 column, join them with the keyword "AND"
1206 if (moreThanOneColumn)
1207 pWhereClause += wxT(" AND ");
1208 else
1209 moreThanOneColumn = TRUE;
1210 // Concatenate where phrase for the column
1211 if (qualTableName.Length())
1212 {
1213 pWhereClause += qualTableName;
1214 pWhereClause += wxT(".");
1215 }
1216 pWhereClause += colDefs[i].ColName;
1217 if (useLikeComparison && (colDefs[i].SqlCtype == SQL_C_CHAR))
1218 pWhereClause += wxT(" LIKE ");
1219 else
1220 pWhereClause += wxT(" = ");
1221 switch(colDefs[i].SqlCtype)
1222 {
1223 case SQL_C_CHAR:
1224 colValue.Printf(wxT("'%s'"), (UCHAR FAR *) colDefs[i].PtrDataObj);
1225 break;
1226 case SQL_C_SSHORT:
1227 colValue.Printf(wxT("%hi"), *((SWORD *) colDefs[i].PtrDataObj));
1228 break;
1229 case SQL_C_USHORT:
1230 colValue.Printf(wxT("%hu"), *((UWORD *) colDefs[i].PtrDataObj));
1231 break;
1232 case SQL_C_SLONG:
1233 colValue.Printf(wxT("%li"), *((SDWORD *) colDefs[i].PtrDataObj));
1234 break;
1235 case SQL_C_ULONG:
1236 colValue.Printf(wxT("%lu"), *((UDWORD *) colDefs[i].PtrDataObj));
1237 break;
1238 case SQL_C_FLOAT:
1239 colValue.Printf(wxT("%.6f"), *((SFLOAT *) colDefs[i].PtrDataObj));
1240 break;
1241 case SQL_C_DOUBLE:
1242 colValue.Printf(wxT("%.6f"), *((SDOUBLE *) colDefs[i].PtrDataObj));
1243 break;
1244 }
1245 pWhereClause += colValue;
1246 }
1247 }
1248 } // wxDbTable::BuildWhereClause()
1249
1250
1251 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1252 void wxDbTable::BuildWhereClause(wxChar *pWhereClause, int typeOfWhere,
1253 const wxString &qualTableName, bool useLikeComparison)
1254 {
1255 wxString tempSqlStmt;
1256 BuildWhereClause(tempSqlStmt, typeOfWhere, qualTableName, useLikeComparison);
1257 wxStrcpy(pWhereClause, tempSqlStmt);
1258 } // wxDbTable::BuildWhereClause()
1259
1260
1261 /********** wxDbTable::GetRowNum() **********/
1262 UWORD wxDbTable::GetRowNum(void)
1263 {
1264 UDWORD rowNum;
1265
1266 if (SQLGetStmtOption(hstmt, SQL_ROW_NUMBER, (UCHAR*) &rowNum) != SQL_SUCCESS)
1267 {
1268 pDb->DispAllErrors(henv, hdbc, hstmt);
1269 return(0);
1270 }
1271
1272 // Completed successfully
1273 return((UWORD) rowNum);
1274
1275 } // wxDbTable::GetRowNum()
1276
1277
1278 /********** wxDbTable::CloseCursor() **********/
1279 bool wxDbTable::CloseCursor(HSTMT cursor)
1280 {
1281 if (SQLFreeStmt(cursor, SQL_CLOSE) != SQL_SUCCESS)
1282 return(pDb->DispAllErrors(henv, hdbc, cursor));
1283
1284 // Completed successfully
1285 return(TRUE);
1286
1287 } // wxDbTable::CloseCursor()
1288
1289
1290 /********** wxDbTable::CreateTable() **********/
1291 bool wxDbTable::CreateTable(bool attemptDrop)
1292 {
1293 if (!pDb)
1294 return FALSE;
1295
1296 int i, j;
1297 wxString sqlStmt;
1298
1299 #ifdef DBDEBUG_CONSOLE
1300 cout << wxT("Creating Table ") << tableName << wxT("...") << endl;
1301 #endif
1302
1303 // Drop table first
1304 if (attemptDrop && !DropTable())
1305 return FALSE;
1306
1307 // Create the table
1308 #ifdef DBDEBUG_CONSOLE
1309 for (i = 0; i < noCols; i++)
1310 {
1311 // Exclude derived columns since they are NOT part of the base table
1312 if (colDefs[i].DerivedCol)
1313 continue;
1314 cout << i + 1 << wxT(": ") << colDefs[i].ColName << wxT("; ");
1315 switch(colDefs[i].DbDataType)
1316 {
1317 case DB_DATA_TYPE_VARCHAR:
1318 cout << pDb->typeInfVarchar.TypeName << wxT("(") << colDefs[i].SzDataObj << wxT(")");
1319 break;
1320 case DB_DATA_TYPE_INTEGER:
1321 cout << pDb->typeInfInteger.TypeName;
1322 break;
1323 case DB_DATA_TYPE_FLOAT:
1324 cout << pDb->typeInfFloat.TypeName;
1325 break;
1326 case DB_DATA_TYPE_DATE:
1327 cout << pDb->typeInfDate.TypeName;
1328 break;
1329 case DB_DATA_TYPE_BLOB:
1330 cout << pDb->typeInfBlob.TypeName;
1331 break;
1332 }
1333 cout << endl;
1334 }
1335 #endif
1336
1337 // Build a CREATE TABLE string from the colDefs structure.
1338 bool needComma = FALSE;
1339 sqlStmt.Printf(wxT("CREATE TABLE %s ("), tableName.c_str());
1340
1341 for (i = 0; i < noCols; i++)
1342 {
1343 // Exclude derived columns since they are NOT part of the base table
1344 if (colDefs[i].DerivedCol)
1345 continue;
1346 // Comma Delimiter
1347 if (needComma)
1348 sqlStmt += wxT(",");
1349 // Column Name
1350 sqlStmt += colDefs[i].ColName;
1351 sqlStmt += wxT(" ");
1352 // Column Type
1353 switch(colDefs[i].DbDataType)
1354 {
1355 case DB_DATA_TYPE_VARCHAR:
1356 sqlStmt += pDb->GetTypeInfVarchar().TypeName;
1357 break;
1358 case DB_DATA_TYPE_INTEGER:
1359 sqlStmt += pDb->GetTypeInfInteger().TypeName;
1360 break;
1361 case DB_DATA_TYPE_FLOAT:
1362 sqlStmt += pDb->GetTypeInfFloat().TypeName;
1363 break;
1364 case DB_DATA_TYPE_DATE:
1365 sqlStmt += pDb->GetTypeInfDate().TypeName;
1366 break;
1367 case DB_DATA_TYPE_BLOB:
1368 sqlStmt += pDb->GetTypeInfBlob().TypeName;
1369 break;
1370 }
1371 // For varchars, append the size of the string
1372 if (colDefs[i].DbDataType == DB_DATA_TYPE_VARCHAR)// ||
1373 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1374 {
1375 wxString s;
1376 s.Printf(wxT("(%d)"), colDefs[i].SzDataObj);
1377 sqlStmt += s;
1378 }
1379
1380 if (pDb->Dbms() == dbmsDB2 ||
1381 pDb->Dbms() == dbmsMY_SQL ||
1382 pDb->Dbms() == dbmsSYBASE_ASE ||
1383 pDb->Dbms() == dbmsINTERBASE ||
1384 pDb->Dbms() == dbmsMS_SQL_SERVER)
1385 {
1386 if (colDefs[i].KeyField)
1387 {
1388 sqlStmt += wxT(" NOT NULL");
1389 }
1390 }
1391
1392 needComma = TRUE;
1393 }
1394 // If there is a primary key defined, include it in the create statement
1395 for (i = j = 0; i < noCols; i++)
1396 {
1397 if (colDefs[i].KeyField)
1398 {
1399 j++;
1400 break;
1401 }
1402 }
1403 if (j && pDb->Dbms() != dbmsDBASE) // Found a keyfield
1404 {
1405 switch (pDb->Dbms())
1406 {
1407 case dbmsSYBASE_ASA:
1408 case dbmsSYBASE_ASE:
1409 case dbmsMY_SQL:
1410 {
1411 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1412 sqlStmt += wxT(",PRIMARY KEY (");
1413 break;
1414 }
1415 default:
1416 {
1417 sqlStmt += wxT(",CONSTRAINT ");
1418 // DB2 is limited to 18 characters for index names
1419 if (pDb->Dbms() == dbmsDB2)
1420 {
1421 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."));
1422 sqlStmt += tableName.substr(0, 13);
1423 }
1424 else
1425 sqlStmt += tableName;
1426
1427 sqlStmt += wxT("_PIDX PRIMARY KEY (");
1428 break;
1429 }
1430 }
1431
1432 // List column name(s) of column(s) comprising the primary key
1433 for (i = j = 0; i < noCols; i++)
1434 {
1435 if (colDefs[i].KeyField)
1436 {
1437 if (j++) // Multi part key, comma separate names
1438 sqlStmt += wxT(",");
1439 sqlStmt += colDefs[i].ColName;
1440 }
1441 }
1442 sqlStmt += wxT(")");
1443
1444 if (pDb->Dbms() == dbmsSYBASE_ASA ||
1445 pDb->Dbms() == dbmsSYBASE_ASE)
1446 {
1447 sqlStmt += wxT(" CONSTRAINT ");
1448 sqlStmt += tableName;
1449 sqlStmt += wxT("_PIDX");
1450 }
1451 }
1452 // Append the closing parentheses for the create table statement
1453 sqlStmt += wxT(")");
1454
1455 pDb->WriteSqlLog(sqlStmt);
1456
1457 #ifdef DBDEBUG_CONSOLE
1458 cout << endl << sqlStmt.c_str() << endl;
1459 #endif
1460
1461 // Execute the CREATE TABLE statement
1462 RETCODE retcode = SQLExecDirect(hstmt, (UCHAR FAR *) sqlStmt.c_str(), SQL_NTS);
1463 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
1464 {
1465 pDb->DispAllErrors(henv, hdbc, hstmt);
1466 pDb->RollbackTrans();
1467 CloseCursor(hstmt);
1468 return(FALSE);
1469 }
1470
1471 // Commit the transaction and close the cursor
1472 if (!pDb->CommitTrans())
1473 return(FALSE);
1474 if (!CloseCursor(hstmt))
1475 return(FALSE);
1476
1477 // Database table created successfully
1478 return(TRUE);
1479
1480 } // wxDbTable::CreateTable()
1481
1482
1483 /********** wxDbTable::DropTable() **********/
1484 bool wxDbTable::DropTable()
1485 {
1486 // NOTE: This function returns TRUE if the Table does not exist, but
1487 // only for identified databases. Code will need to be added
1488 // below for any other databases when those databases are defined
1489 // to handle this situation consistently
1490
1491 wxString sqlStmt;
1492
1493 sqlStmt.Printf(wxT("DROP TABLE %s"), tableName.c_str());
1494
1495 pDb->WriteSqlLog(sqlStmt);
1496
1497 #ifdef DBDEBUG_CONSOLE
1498 cout << endl << sqlStmt.c_str() << endl;
1499 #endif
1500
1501
1502
1503
1504 RETCODE retcode = SQLExecDirect(hstmt, (UCHAR FAR *) sqlStmt.c_str(), SQL_NTS);
1505 if (retcode != SQL_SUCCESS)
1506 {
1507 // Check for "Base table not found" error and ignore
1508 pDb->GetNextError(henv, hdbc, hstmt);
1509 if (wxStrcmp(pDb->sqlState, wxT("S0002")) /*&&
1510 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1511 {
1512 // Check for product specific error codes
1513 if (!((pDb->Dbms() == dbmsSYBASE_ASA && !wxStrcmp(pDb->sqlState,wxT("42000"))) || // 5.x (and lower?)
1514 (pDb->Dbms() == dbmsSYBASE_ASE && !wxStrcmp(pDb->sqlState,wxT("37000"))) ||
1515 (pDb->Dbms() == dbmsPERVASIVE_SQL && !wxStrcmp(pDb->sqlState,wxT("S1000"))) || // Returns an S1000 then an S0002
1516 (pDb->Dbms() == dbmsPOSTGRES && !wxStrcmp(pDb->sqlState,wxT("08S01")))))
1517 {
1518 pDb->DispNextError();
1519 pDb->DispAllErrors(henv, hdbc, hstmt);
1520 pDb->RollbackTrans();
1521 // CloseCursor(hstmt);
1522 return(FALSE);
1523 }
1524 }
1525 }
1526
1527 // Commit the transaction and close the cursor
1528 if (! pDb->CommitTrans())
1529 return(FALSE);
1530 if (! CloseCursor(hstmt))
1531 return(FALSE);
1532
1533 return(TRUE);
1534 } // wxDbTable::DropTable()
1535
1536
1537 /********** wxDbTable::CreateIndex() **********/
1538 bool wxDbTable::CreateIndex(const wxString &idxName, bool unique, UWORD noIdxCols,
1539 wxDbIdxDef *pIdxDefs, bool attemptDrop)
1540 {
1541 wxString sqlStmt;
1542
1543 // Drop the index first
1544 if (attemptDrop && !DropIndex(idxName))
1545 return (FALSE);
1546
1547 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1548 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1549 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1550 // table was created, then months later you determine that an additional index while
1551 // give better performance, so you want to add an index).
1552 //
1553 // The following block of code will modify the column definition to make the column be
1554 // defined with the "NOT NULL" qualifier.
1555 if (pDb->Dbms() == dbmsMY_SQL)
1556 {
1557 wxString sqlStmt;
1558 int i;
1559 bool ok = TRUE;
1560 for (i = 0; i < noIdxCols && ok; i++)
1561 {
1562 int j = 0;
1563 bool found = FALSE;
1564 // Find the column definition that has the ColName that matches the
1565 // index column name. We need to do this to get the DB_DATA_TYPE of
1566 // the index column, as MySQL's syntax for the ALTER column requires
1567 // this information
1568 while (!found && (j < this->noCols))
1569 {
1570 if (wxStrcmp(colDefs[j].ColName,pIdxDefs[i].ColName) == 0)
1571 found = TRUE;
1572 if (!found)
1573 j++;
1574 }
1575
1576 if (found)
1577 {
1578 ok = pDb->ModifyColumn(tableName, pIdxDefs[i].ColName,
1579 colDefs[j].DbDataType, colDefs[j].SzDataObj,
1580 wxT("NOT NULL"));
1581
1582 if (!ok)
1583 {
1584 wxODBC_ERRORS retcode;
1585 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1586 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1587 // This line is just here for debug checking of the value
1588 retcode = (wxODBC_ERRORS)pDb->DB_STATUS;
1589 }
1590 }
1591 else
1592 ok = FALSE;
1593 }
1594 if (ok)
1595 pDb->CommitTrans();
1596 else
1597 {
1598 pDb->RollbackTrans();
1599 return(FALSE);
1600 }
1601 }
1602
1603 // Build a CREATE INDEX statement
1604 sqlStmt = wxT("CREATE ");
1605 if (unique)
1606 sqlStmt += wxT("UNIQUE ");
1607
1608 sqlStmt += wxT("INDEX ");
1609 sqlStmt += idxName;
1610 sqlStmt += wxT(" ON ");
1611 sqlStmt += tableName;
1612 sqlStmt += wxT(" (");
1613
1614 // Append list of columns making up index
1615 int i;
1616 for (i = 0; i < noIdxCols; i++)
1617 {
1618 sqlStmt += pIdxDefs[i].ColName;
1619
1620 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1621 if (!((pDb->Dbms() == dbmsMS_SQL_SERVER) && (strncmp(pDb->dbInf.dbmsVer,"07",2)==0)) &&
1622 !(pDb->Dbms() == dbmsPOSTGRES))
1623 {
1624 if (pIdxDefs[i].Ascending)
1625 sqlStmt += wxT(" ASC");
1626 else
1627 sqlStmt += wxT(" DESC");
1628 }
1629 else
1630 wxASSERT_MSG(!pIdxDefs[i].Ascending, "Datasource does not support DESCending index columns");
1631
1632 if ((i + 1) < noIdxCols)
1633 sqlStmt += wxT(",");
1634 }
1635
1636 // Append closing parentheses
1637 sqlStmt += wxT(")");
1638
1639 pDb->WriteSqlLog(sqlStmt);
1640
1641 #ifdef DBDEBUG_CONSOLE
1642 cout << endl << sqlStmt.c_str() << endl << endl;
1643 #endif
1644
1645 // Execute the CREATE INDEX statement
1646 if (SQLExecDirect(hstmt, (UCHAR FAR *) sqlStmt.c_str(), SQL_NTS) != SQL_SUCCESS)
1647 {
1648 pDb->DispAllErrors(henv, hdbc, hstmt);
1649 pDb->RollbackTrans();
1650 CloseCursor(hstmt);
1651 return(FALSE);
1652 }
1653
1654 // Commit the transaction and close the cursor
1655 if (! pDb->CommitTrans())
1656 return(FALSE);
1657 if (! CloseCursor(hstmt))
1658 return(FALSE);
1659
1660 // Index Created Successfully
1661 return(TRUE);
1662
1663 } // wxDbTable::CreateIndex()
1664
1665
1666 /********** wxDbTable::DropIndex() **********/
1667 bool wxDbTable::DropIndex(const wxString &idxName)
1668 {
1669 // NOTE: This function returns TRUE if the Index does not exist, but
1670 // only for identified databases. Code will need to be added
1671 // below for any other databases when those databases are defined
1672 // to handle this situation consistently
1673
1674 wxString sqlStmt;
1675
1676 if (pDb->Dbms() == dbmsACCESS || pDb->Dbms() == dbmsMY_SQL ||
1677 pDb->Dbms() == dbmsDBASE /*|| Paradox needs this syntax too when we add support*/)
1678 sqlStmt.Printf(wxT("DROP INDEX %s ON %s"),idxName.c_str(), tableName.c_str());
1679 else if ((pDb->Dbms() == dbmsMS_SQL_SERVER) ||
1680 (pDb->Dbms() == dbmsSYBASE_ASE))
1681 sqlStmt.Printf(wxT("DROP INDEX %s.%s"),tableName.c_str(), idxName.c_str());
1682 else
1683 sqlStmt.Printf(wxT("DROP INDEX %s"),idxName.c_str());
1684
1685 pDb->WriteSqlLog(sqlStmt);
1686
1687 #ifdef DBDEBUG_CONSOLE
1688 cout << endl << sqlStmt.c_str() << endl;
1689 #endif
1690
1691 if (SQLExecDirect(hstmt, (UCHAR FAR *) sqlStmt.c_str(), SQL_NTS) != SQL_SUCCESS)
1692 {
1693 // Check for "Index not found" error and ignore
1694 pDb->GetNextError(henv, hdbc, hstmt);
1695 if (wxStrcmp(pDb->sqlState,wxT("S0012"))) // "Index not found"
1696 {
1697 // Check for product specific error codes
1698 if (!((pDb->Dbms() == dbmsSYBASE_ASA && !wxStrcmp(pDb->sqlState,wxT("42000"))) || // v5.x (and lower?)
1699 (pDb->Dbms() == dbmsSYBASE_ASE && !wxStrcmp(pDb->sqlState,wxT("37000"))) ||
1700 (pDb->Dbms() == dbmsMS_SQL_SERVER && !wxStrcmp(pDb->sqlState,wxT("S1000"))) ||
1701 (pDb->Dbms() == dbmsINTERBASE && !wxStrcmp(pDb->sqlState,wxT("S1000"))) ||
1702 (pDb->Dbms() == dbmsSYBASE_ASE && !wxStrcmp(pDb->sqlState,wxT("S0002"))) || // Base table not found
1703 (pDb->Dbms() == dbmsMY_SQL && !wxStrcmp(pDb->sqlState,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1704 (pDb->Dbms() == dbmsPOSTGRES && !wxStrcmp(pDb->sqlState,wxT("08S01")))
1705 ))
1706 {
1707 pDb->DispNextError();
1708 pDb->DispAllErrors(henv, hdbc, hstmt);
1709 pDb->RollbackTrans();
1710 CloseCursor(hstmt);
1711 return(FALSE);
1712 }
1713 }
1714 }
1715
1716 // Commit the transaction and close the cursor
1717 if (! pDb->CommitTrans())
1718 return(FALSE);
1719 if (! CloseCursor(hstmt))
1720 return(FALSE);
1721
1722 return(TRUE);
1723 } // wxDbTable::DropIndex()
1724
1725
1726 /********** wxDbTable::SetOrderByColNums() **********/
1727 bool wxDbTable::SetOrderByColNums(UWORD first, ... )
1728 {
1729 int colNo = first; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1730 va_list argptr;
1731
1732 bool abort = FALSE;
1733 wxString tempStr;
1734
1735 va_start(argptr, first); /* Initialize variable arguments. */
1736 while (!abort && (colNo != wxDB_NO_MORE_COLUMN_NUMBERS))
1737 {
1738 // Make sure the passed in column number
1739 // is within the valid range of columns
1740 //
1741 // Valid columns are 0 thru noCols-1
1742 if (colNo >= noCols || colNo < 0)
1743 {
1744 abort = TRUE;
1745 continue;
1746 }
1747
1748 if (colNo != first)
1749 tempStr += wxT(",");
1750
1751 tempStr += colDefs[colNo].ColName;
1752 colNo = va_arg (argptr, int);
1753 }
1754 va_end (argptr); /* Reset variable arguments. */
1755
1756 SetOrderByClause(tempStr);
1757
1758 return (!abort);
1759 } // wxDbTable::SetOrderByColNums()
1760
1761
1762 /********** wxDbTable::Insert() **********/
1763 int wxDbTable::Insert(void)
1764 {
1765 wxASSERT(!queryOnly);
1766 if (queryOnly || !insertable)
1767 return(DB_FAILURE);
1768
1769 bindInsertParams();
1770
1771 // Insert the record by executing the already prepared insert statement
1772 RETCODE retcode;
1773 retcode=SQLExecute(hstmtInsert);
1774 if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
1775 {
1776 // Check to see if integrity constraint was violated
1777 pDb->GetNextError(henv, hdbc, hstmtInsert);
1778 if (! wxStrcmp(pDb->sqlState, wxT("23000"))) // Integrity constraint violated
1779 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL);
1780 else
1781 {
1782 pDb->DispNextError();
1783 pDb->DispAllErrors(henv, hdbc, hstmtInsert);
1784 return(DB_FAILURE);
1785 }
1786 }
1787
1788 // Record inserted into the datasource successfully
1789 return(DB_SUCCESS);
1790
1791 } // wxDbTable::Insert()
1792
1793
1794 /********** wxDbTable::Update() **********/
1795 bool wxDbTable::Update(void)
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_KEYFIELDS);
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::Update()
1816
1817
1818 /********** wxDbTable::Update(pSqlStmt) **********/
1819 bool wxDbTable::Update(const wxString &pSqlStmt)
1820 {
1821 wxASSERT(!queryOnly);
1822 if (queryOnly)
1823 return(FALSE);
1824
1825 pDb->WriteSqlLog(pSqlStmt);
1826
1827 return(execUpdate(pSqlStmt));
1828
1829 } // wxDbTable::Update(pSqlStmt)
1830
1831
1832 /********** wxDbTable::UpdateWhere() **********/
1833 bool wxDbTable::UpdateWhere(const wxString &pWhereClause)
1834 {
1835 wxASSERT(!queryOnly);
1836 if (queryOnly)
1837 return(FALSE);
1838
1839 wxString sqlStmt;
1840
1841 // Build the SQL UPDATE statement
1842 BuildUpdateStmt(sqlStmt, DB_UPD_WHERE, pWhereClause);
1843
1844 pDb->WriteSqlLog(sqlStmt);
1845
1846 #ifdef DBDEBUG_CONSOLE
1847 cout << endl << sqlStmt.c_str() << endl << endl;
1848 #endif
1849
1850 // Execute the SQL UPDATE statement
1851 return(execUpdate(sqlStmt));
1852
1853 } // wxDbTable::UpdateWhere()
1854
1855
1856 /********** wxDbTable::Delete() **********/
1857 bool wxDbTable::Delete(void)
1858 {
1859 wxASSERT(!queryOnly);
1860 if (queryOnly)
1861 return(FALSE);
1862
1863 wxString sqlStmt;
1864 sqlStmt.Empty();
1865
1866 // Build the SQL DELETE statement
1867 BuildDeleteStmt(sqlStmt, DB_DEL_KEYFIELDS);
1868
1869 pDb->WriteSqlLog(sqlStmt);
1870
1871 // Execute the SQL DELETE statement
1872 return(execDelete(sqlStmt));
1873
1874 } // wxDbTable::Delete()
1875
1876
1877 /********** wxDbTable::DeleteWhere() **********/
1878 bool wxDbTable::DeleteWhere(const wxString &pWhereClause)
1879 {
1880 wxASSERT(!queryOnly);
1881 if (queryOnly)
1882 return(FALSE);
1883
1884 wxString sqlStmt;
1885 sqlStmt.Empty();
1886
1887 // Build the SQL DELETE statement
1888 BuildDeleteStmt(sqlStmt, DB_DEL_WHERE, pWhereClause);
1889
1890 pDb->WriteSqlLog(sqlStmt);
1891
1892 // Execute the SQL DELETE statement
1893 return(execDelete(sqlStmt));
1894
1895 } // wxDbTable::DeleteWhere()
1896
1897
1898 /********** wxDbTable::DeleteMatching() **********/
1899 bool wxDbTable::DeleteMatching(void)
1900 {
1901 wxASSERT(!queryOnly);
1902 if (queryOnly)
1903 return(FALSE);
1904
1905 wxString sqlStmt;
1906 sqlStmt.Empty();
1907
1908 // Build the SQL DELETE statement
1909 BuildDeleteStmt(sqlStmt, DB_DEL_MATCHING);
1910
1911 pDb->WriteSqlLog(sqlStmt);
1912
1913 // Execute the SQL DELETE statement
1914 return(execDelete(sqlStmt));
1915
1916 } // wxDbTable::DeleteMatching()
1917
1918
1919 /********** wxDbTable::IsColNull() **********/
1920 bool wxDbTable::IsColNull(UWORD colNo)
1921 {
1922 /*
1923 This logic is just not right. It would indicate TRUE
1924 if a numeric field were set to a value of 0.
1925
1926 switch(colDefs[colNo].SqlCtype)
1927 {
1928 case SQL_C_CHAR:
1929 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
1930 case SQL_C_SSHORT:
1931 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
1932 case SQL_C_USHORT:
1933 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
1934 case SQL_C_SLONG:
1935 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1936 case SQL_C_ULONG:
1937 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1938 case SQL_C_FLOAT:
1939 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
1940 case SQL_C_DOUBLE:
1941 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
1942 case SQL_C_TIMESTAMP:
1943 TIMESTAMP_STRUCT *pDt;
1944 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
1945 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
1946 return(TRUE);
1947 else
1948 return(FALSE);
1949 default:
1950 return(TRUE);
1951 }
1952 */
1953 return (colDefs[colNo].Null);
1954 } // wxDbTable::IsColNull()
1955
1956
1957 /********** wxDbTable::CanSelectForUpdate() **********/
1958 bool wxDbTable::CanSelectForUpdate(void)
1959 {
1960 if (queryOnly)
1961 return FALSE;
1962
1963 if (pDb->Dbms() == dbmsMY_SQL)
1964 return FALSE;
1965
1966 if ((pDb->Dbms() == dbmsORACLE) ||
1967 (pDb->dbInf.posStmts & SQL_PS_SELECT_FOR_UPDATE))
1968 return(TRUE);
1969 else
1970 return(FALSE);
1971
1972 } // wxDbTable::CanSelectForUpdate()
1973
1974
1975 /********** wxDbTable::CanUpdByROWID() **********/
1976 bool wxDbTable::CanUpdByROWID(void)
1977 {
1978 /*
1979 * NOTE: Returning FALSE for now until this can be debugged,
1980 * as the ROWID is not getting updated correctly
1981 */
1982 return FALSE;
1983 /*
1984 if (pDb->Dbms() == dbmsORACLE)
1985 return(TRUE);
1986 else
1987 return(FALSE);
1988 */
1989 } // wxDbTable::CanUpdByROWID()
1990
1991
1992 /********** wxDbTable::IsCursorClosedOnCommit() **********/
1993 bool wxDbTable::IsCursorClosedOnCommit(void)
1994 {
1995 if (pDb->dbInf.cursorCommitBehavior == SQL_CB_PRESERVE)
1996 return(FALSE);
1997 else
1998 return(TRUE);
1999
2000 } // wxDbTable::IsCursorClosedOnCommit()
2001
2002
2003
2004 /********** wxDbTable::ClearMemberVar() **********/
2005 void wxDbTable::ClearMemberVar(UWORD colNo, bool setToNull)
2006 {
2007 wxASSERT(colNo < noCols);
2008
2009 switch(colDefs[colNo].SqlCtype)
2010 {
2011 case SQL_C_CHAR:
2012 ((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] = 0;
2013 break;
2014 case SQL_C_SSHORT:
2015 *((SWORD *) colDefs[colNo].PtrDataObj) = 0;
2016 break;
2017 case SQL_C_USHORT:
2018 *((UWORD*) colDefs[colNo].PtrDataObj) = 0;
2019 break;
2020 case SQL_C_SLONG:
2021 *((SDWORD *) colDefs[colNo].PtrDataObj) = 0;
2022 break;
2023 case SQL_C_ULONG:
2024 *((UDWORD *) colDefs[colNo].PtrDataObj) = 0;
2025 break;
2026 case SQL_C_FLOAT:
2027 *((SFLOAT *) colDefs[colNo].PtrDataObj) = 0.0f;
2028 break;
2029 case SQL_C_DOUBLE:
2030 *((SDOUBLE *) colDefs[colNo].PtrDataObj) = 0.0f;
2031 break;
2032 case SQL_C_TIMESTAMP:
2033 TIMESTAMP_STRUCT *pDt;
2034 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
2035 pDt->year = 0;
2036 pDt->month = 0;
2037 pDt->day = 0;
2038 pDt->hour = 0;
2039 pDt->minute = 0;
2040 pDt->second = 0;
2041 pDt->fraction = 0;
2042 break;
2043 }
2044
2045 if (setToNull)
2046 SetColNull(colNo);
2047 } // wxDbTable::ClearMemberVar()
2048
2049
2050 /********** wxDbTable::ClearMemberVars() **********/
2051 void wxDbTable::ClearMemberVars(bool setToNull)
2052 {
2053 int i;
2054
2055 // Loop through the columns setting each member variable to zero
2056 for (i=0; i < noCols; i++)
2057 ClearMemberVar(i,setToNull);
2058
2059 } // wxDbTable::ClearMemberVars()
2060
2061
2062 /********** wxDbTable::SetQueryTimeout() **********/
2063 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds)
2064 {
2065 if (SQLSetStmtOption(hstmtInsert, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2066 return(pDb->DispAllErrors(henv, hdbc, hstmtInsert));
2067 if (SQLSetStmtOption(hstmtUpdate, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2068 return(pDb->DispAllErrors(henv, hdbc, hstmtUpdate));
2069 if (SQLSetStmtOption(hstmtDelete, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2070 return(pDb->DispAllErrors(henv, hdbc, hstmtDelete));
2071 if (SQLSetStmtOption(hstmtInternal, SQL_QUERY_TIMEOUT, nSeconds) != SQL_SUCCESS)
2072 return(pDb->DispAllErrors(henv, hdbc, hstmtInternal));
2073
2074 // Completed Successfully
2075 return(TRUE);
2076
2077 } // wxDbTable::SetQueryTimeout()
2078
2079
2080 /********** wxDbTable::SetColDefs() **********/
2081 void wxDbTable::SetColDefs(UWORD index, const wxString &fieldName, int dataType, void *pData,
2082 SWORD cType, int size, bool keyField, bool upd,
2083 bool insAllow, bool derivedCol)
2084 {
2085 if (!colDefs) // May happen if the database connection fails
2086 return;
2087
2088 if (fieldName.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN)
2089 {
2090 int assertColumnNameTooLong = 0;
2091 wxStrncpy(colDefs[index].ColName, fieldName, DB_MAX_COLUMN_NAME_LEN);
2092 colDefs[index].ColName[DB_MAX_COLUMN_NAME_LEN] = 0;
2093 wxString tmpMsg;
2094 tmpMsg.sprintf("Column name '%s' is too long. Truncated to '%s'.",fieldName,colDefs[index].ColName);
2095 wxASSERT_MSG(assertColumnNameTooLong,tmpMsg.c_str());
2096 }
2097 else
2098 wxStrcpy(colDefs[index].ColName, fieldName);
2099
2100 colDefs[index].DbDataType = dataType;
2101 colDefs[index].PtrDataObj = pData;
2102 colDefs[index].SqlCtype = cType;
2103 colDefs[index].SzDataObj = size;
2104 colDefs[index].KeyField = keyField;
2105 colDefs[index].DerivedCol = derivedCol;
2106 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2107 if (derivedCol)
2108 {
2109 colDefs[index].Updateable = FALSE;
2110 colDefs[index].InsertAllowed = FALSE;
2111 }
2112 else
2113 {
2114 colDefs[index].Updateable = upd;
2115 colDefs[index].InsertAllowed = insAllow;
2116 }
2117
2118 colDefs[index].Null = FALSE;
2119
2120 } // wxDbTable::SetColDefs()
2121
2122
2123 /********** wxDbTable::SetColDefs() **********/
2124 wxDbColDataPtr* wxDbTable::SetColDefs(wxDbColInf *pColInfs, UWORD numCols)
2125 {
2126 wxASSERT(pColInfs);
2127 wxDbColDataPtr *pColDataPtrs = NULL;
2128
2129 if (pColInfs)
2130 {
2131 UWORD index;
2132
2133 pColDataPtrs = new wxDbColDataPtr[numCols+1];
2134
2135 for (index = 0; index < numCols; index++)
2136 {
2137 // Process the fields
2138 switch (pColInfs[index].dbDataType)
2139 {
2140 case DB_DATA_TYPE_VARCHAR:
2141 pColDataPtrs[index].PtrDataObj = new wxChar[pColInfs[index].bufferLength+1];
2142 pColDataPtrs[index].SzDataObj = pColInfs[index].columnSize;
2143 pColDataPtrs[index].SqlCtype = SQL_C_CHAR;
2144 break;
2145 case DB_DATA_TYPE_INTEGER:
2146 // Can be long or short
2147 if (pColInfs[index].bufferLength == sizeof(long))
2148 {
2149 pColDataPtrs[index].PtrDataObj = new long;
2150 pColDataPtrs[index].SzDataObj = sizeof(long);
2151 pColDataPtrs[index].SqlCtype = SQL_C_SLONG;
2152 }
2153 else
2154 {
2155 pColDataPtrs[index].PtrDataObj = new short;
2156 pColDataPtrs[index].SzDataObj = sizeof(short);
2157 pColDataPtrs[index].SqlCtype = SQL_C_SSHORT;
2158 }
2159 break;
2160 case DB_DATA_TYPE_FLOAT:
2161 // Can be float or double
2162 if (pColInfs[index].bufferLength == sizeof(float))
2163 {
2164 pColDataPtrs[index].PtrDataObj = new float;
2165 pColDataPtrs[index].SzDataObj = sizeof(float);
2166 pColDataPtrs[index].SqlCtype = SQL_C_FLOAT;
2167 }
2168 else
2169 {
2170 pColDataPtrs[index].PtrDataObj = new double;
2171 pColDataPtrs[index].SzDataObj = sizeof(double);
2172 pColDataPtrs[index].SqlCtype = SQL_C_DOUBLE;
2173 }
2174 break;
2175 case DB_DATA_TYPE_DATE:
2176 pColDataPtrs[index].PtrDataObj = new TIMESTAMP_STRUCT;
2177 pColDataPtrs[index].SzDataObj = sizeof(TIMESTAMP_STRUCT);
2178 pColDataPtrs[index].SqlCtype = SQL_C_TIMESTAMP;
2179 break;
2180 case DB_DATA_TYPE_BLOB:
2181 int notSupportedYet = 0;
2182 wxASSERT_MSG(notSupportedYet, wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2183 pColDataPtrs[index].PtrDataObj = /*BLOB ADDITION NEEDED*/NULL;
2184 pColDataPtrs[index].SzDataObj = /*BLOB ADDITION NEEDED*/sizeof(void *);
2185 pColDataPtrs[index].SqlCtype = SQL_VARBINARY;
2186 break;
2187 }
2188 if (pColDataPtrs[index].PtrDataObj != NULL)
2189 SetColDefs (index,pColInfs[index].colName,pColInfs[index].dbDataType, pColDataPtrs[index].PtrDataObj, pColDataPtrs[index].SqlCtype, pColDataPtrs[index].SzDataObj);
2190 else
2191 {
2192 // Unable to build all the column definitions, as either one of
2193 // the calls to "new" failed above, or there was a BLOB field
2194 // to have a column definition for. If BLOBs are to be used,
2195 // the other form of ::SetColDefs() must be used, as it is impossible
2196 // to know the maximum size to create the PtrDataObj to be.
2197 delete [] pColDataPtrs;
2198 return NULL;
2199 }
2200 }
2201 }
2202
2203 return (pColDataPtrs);
2204
2205 } // wxDbTable::SetColDefs()
2206
2207
2208 /********** wxDbTable::SetCursor() **********/
2209 void wxDbTable::SetCursor(HSTMT *hstmtActivate)
2210 {
2211 if (hstmtActivate == wxDB_DEFAULT_CURSOR)
2212 hstmt = *hstmtDefault;
2213 else
2214 hstmt = *hstmtActivate;
2215
2216 } // wxDbTable::SetCursor()
2217
2218
2219 /********** wxDbTable::Count(const wxString &) **********/
2220 ULONG wxDbTable::Count(const wxString &args)
2221 {
2222 ULONG count;
2223 wxString sqlStmt;
2224 SDWORD cb;
2225
2226 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2227 sqlStmt = wxT("SELECT COUNT(");
2228 sqlStmt += args;
2229 sqlStmt += wxT(") FROM ");
2230 sqlStmt += queryTableName;
2231 #if wxODBC_BACKWARD_COMPATABILITY
2232 if (from && wxStrlen(from))
2233 #else
2234 if (from.Length())
2235 #endif
2236 sqlStmt += from;
2237
2238 // Add the where clause if one is provided
2239 #if wxODBC_BACKWARD_COMPATABILITY
2240 if (where && wxStrlen(where))
2241 #else
2242 if (where.Length())
2243 #endif
2244 {
2245 sqlStmt += wxT(" WHERE ");
2246 sqlStmt += where;
2247 }
2248
2249 pDb->WriteSqlLog(sqlStmt);
2250
2251 // Initialize the Count cursor if it's not already initialized
2252 if (!hstmtCount)
2253 {
2254 hstmtCount = GetNewCursor(FALSE,FALSE);
2255 wxASSERT(hstmtCount);
2256 if (!hstmtCount)
2257 return(0);
2258 }
2259
2260 // Execute the SQL statement
2261 if (SQLExecDirect(*hstmtCount, (UCHAR FAR *) sqlStmt.c_str(), SQL_NTS) != SQL_SUCCESS)
2262 {
2263 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2264 return(0);
2265 }
2266
2267 // Fetch the record
2268 if (SQLFetch(*hstmtCount) != SQL_SUCCESS)
2269 {
2270 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2271 return(0);
2272 }
2273
2274 // Obtain the result
2275 if (SQLGetData(*hstmtCount, (UWORD)1, SQL_C_ULONG, &count, sizeof(count), &cb) != SQL_SUCCESS)
2276 {
2277 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2278 return(0);
2279 }
2280
2281 // Free the cursor
2282 if (SQLFreeStmt(*hstmtCount, SQL_CLOSE) != SQL_SUCCESS)
2283 pDb->DispAllErrors(henv, hdbc, *hstmtCount);
2284
2285 // Return the record count
2286 return(count);
2287
2288 } // wxDbTable::Count()
2289
2290
2291 /********** wxDbTable::Refresh() **********/
2292 bool wxDbTable::Refresh(void)
2293 {
2294 bool result = TRUE;
2295
2296 // Switch to the internal cursor so any active cursors are not corrupted
2297 HSTMT currCursor = GetCursor();
2298 hstmt = hstmtInternal;
2299 #if wxODBC_BACKWARD_COMPATABILITY
2300 // Save the where and order by clauses
2301 char *saveWhere = where;
2302 char *saveOrderBy = orderBy;
2303 #else
2304 wxString saveWhere = where;
2305 wxString saveOrderBy = orderBy;
2306 #endif
2307 // Build a where clause to refetch the record with. Try and use the
2308 // ROWID if it's available, ow use the key fields.
2309 wxString whereClause;
2310 whereClause.Empty();
2311
2312 if (CanUpdByROWID())
2313 {
2314 SDWORD cb;
2315 wxChar rowid[wxDB_ROWID_LEN+1];
2316
2317 // Get the ROWID value. If not successful retreiving the ROWID,
2318 // simply fall down through the code and build the WHERE clause
2319 // based on the key fields.
2320 if (SQLGetData(hstmt, (UWORD)(noCols+1), SQL_C_CHAR, (UCHAR*) rowid, wxDB_ROWID_LEN, &cb) == SQL_SUCCESS)
2321 {
2322 whereClause += queryTableName;
2323 whereClause += wxT(".ROWID = '");
2324 whereClause += rowid;
2325 whereClause += wxT("'");
2326 }
2327 }
2328
2329 // If unable to use the ROWID, build a where clause from the keyfields
2330 if (wxStrlen(whereClause) == 0)
2331 BuildWhereClause(whereClause, DB_WHERE_KEYFIELDS, queryTableName);
2332
2333 // Requery the record
2334 where = whereClause;
2335 orderBy.Empty();
2336 if (!Query())
2337 result = FALSE;
2338
2339 if (result && !GetNext())
2340 result = FALSE;
2341
2342 // Switch back to original cursor
2343 SetCursor(&currCursor);
2344
2345 // Free the internal cursor
2346 if (SQLFreeStmt(hstmtInternal, SQL_CLOSE) != SQL_SUCCESS)
2347 pDb->DispAllErrors(henv, hdbc, hstmtInternal);
2348
2349 // Restore the original where and order by clauses
2350 where = saveWhere;
2351 orderBy = saveOrderBy;
2352
2353 return(result);
2354
2355 } // wxDbTable::Refresh()
2356
2357
2358 /********** wxDbTable::SetColNull() **********/
2359 bool wxDbTable::SetColNull(UWORD colNo, bool set)
2360 {
2361 if (colNo < noCols)
2362 {
2363 colDefs[colNo].Null = set;
2364 if (set) // Blank out the values in the member variable
2365 ClearMemberVar(colNo,FALSE); // Must call with FALSE, or infinite recursion will happen
2366 return(TRUE);
2367 }
2368 else
2369 return(FALSE);
2370
2371 } // wxDbTable::SetColNull()
2372
2373
2374 /********** wxDbTable::SetColNull() **********/
2375 bool wxDbTable::SetColNull(const wxString &colName, bool set)
2376 {
2377 int i;
2378 for (i = 0; i < noCols; i++)
2379 {
2380 if (!wxStricmp(colName, colDefs[i].ColName))
2381 break;
2382 }
2383
2384 if (i < noCols)
2385 {
2386 colDefs[i].Null = set;
2387 if (set) // Blank out the values in the member variable
2388 ClearMemberVar(i,FALSE); // Must call with FALSE, or infinite recursion will happen
2389 return(TRUE);
2390 }
2391 else
2392 return(FALSE);
2393
2394 } // wxDbTable::SetColNull()
2395
2396
2397 /********** wxDbTable::GetNewCursor() **********/
2398 HSTMT *wxDbTable::GetNewCursor(bool setCursor, bool bindColumns)
2399 {
2400 HSTMT *newHSTMT = new HSTMT;
2401 wxASSERT(newHSTMT);
2402 if (!newHSTMT)
2403 return(0);
2404
2405 if (SQLAllocStmt(hdbc, newHSTMT) != SQL_SUCCESS)
2406 {
2407 pDb->DispAllErrors(henv, hdbc);
2408 delete newHSTMT;
2409 return(0);
2410 }
2411
2412 if (SQLSetStmtOption(*newHSTMT, SQL_CURSOR_TYPE, cursorType) != SQL_SUCCESS)
2413 {
2414 pDb->DispAllErrors(henv, hdbc, *newHSTMT);
2415 delete newHSTMT;
2416 return(0);
2417 }
2418
2419 if (bindColumns)
2420 {
2421 if(!bindCols(*newHSTMT))
2422 {
2423 delete newHSTMT;
2424 return(0);
2425 }
2426 }
2427
2428 if (setCursor)
2429 SetCursor(newHSTMT);
2430
2431 return(newHSTMT);
2432
2433 } // wxDbTable::GetNewCursor()
2434
2435
2436 /********** wxDbTable::DeleteCursor() **********/
2437 bool wxDbTable::DeleteCursor(HSTMT *hstmtDel)
2438 {
2439 bool result = TRUE;
2440
2441 if (!hstmtDel) // Cursor already deleted
2442 return(result);
2443
2444 /*
2445 ODBC 3.0 says to use this form
2446 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2447
2448 */
2449 if (SQLFreeStmt(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2450 {
2451 pDb->DispAllErrors(henv, hdbc);
2452 result = FALSE;
2453 }
2454
2455 delete hstmtDel;
2456
2457 return(result);
2458
2459 } // wxDbTable::DeleteCursor()
2460
2461 #endif // wxUSE_ODBC
2462