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