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