1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
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 ///////////////////////////////////////////////////////////////////////////////
28 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
29 #pragma implementation "dbtable.h"
32 #include "wx/wxprec.h"
38 #ifdef DBDEBUG_CONSOLE
44 #include "wx/ioswrap.h"
48 #include "wx/string.h"
49 #include "wx/object.h"
54 #include "wx/filefn.h"
62 #include "wx/dbtable.h"
65 // The HPUX preprocessor lines below were commented out on 8/20/97
66 // because macros.h currently redefines DEBUG and is unneeded.
68 // # include <macros.h>
71 # include <sys/minmax.h>
75 ULONG lastTableID
= 0;
83 void csstrncpyt(char *target
, const char *source
, int n
)
85 while ( (*target
++ = *source
++) != '\0' && --n
)
93 /********** wxDbColDef::wxDbColDef() Constructor **********/
94 wxDbColDef::wxDbColDef()
100 bool wxDbColDef::Initialize()
103 DbDataType
= DB_DATA_TYPE_INTEGER
;
104 SqlCtype
= SQL_C_LONG
;
109 InsertAllowed
= FALSE
;
115 } // wxDbColDef::Initialize()
118 /********** wxDbTable::wxDbTable() Constructor **********/
119 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
120 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
122 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
124 } // wxDbTable::wxDbTable()
127 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
128 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
129 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
131 wxString tempQryTblName
;
132 tempQryTblName
= qryTblName
;
133 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
135 } // wxDbTable::wxDbTable()
138 /********** wxDbTable::~wxDbTable() **********/
139 wxDbTable::~wxDbTable()
142 } // wxDbTable::~wxDbTable()
145 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
146 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
148 // Initializing member variables
149 pDb
= pwxDb
; // Pointer to the wxDb object
153 m_hstmtGridQuery
= 0;
154 hstmtDefault
= 0; // Initialized below
155 hstmtCount
= 0; // Initialized first time it is needed
162 noCols
= numColumns
; // Number of cols in the table
163 where
.Empty(); // Where clause
164 orderBy
.Empty(); // Order By clause
165 from
.Empty(); // From clause
166 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
171 queryTableName
.Empty();
173 wxASSERT(tblName
.Length());
179 tableName
= tblName
; // Table Name
180 if (tblPath
.Length())
181 tablePath
= tblPath
; // Table Path - used for dBase files
185 if (qryTblName
.Length()) // Name of the table/view to query
186 queryTableName
= qryTblName
;
188 queryTableName
= tblName
;
190 pDb
->incrementTableCount();
193 tableID
= ++lastTableID
;
194 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
197 wxTablesInUse
*tableInUse
;
198 tableInUse
= new wxTablesInUse();
199 tableInUse
->tableName
= tblName
;
200 tableInUse
->tableID
= tableID
;
201 tableInUse
->pDb
= pDb
;
202 TablesInUse
.Append(tableInUse
);
207 // Grab the HENV and HDBC from the wxDb object
208 henv
= pDb
->GetHENV();
209 hdbc
= pDb
->GetHDBC();
211 // Allocate space for column definitions
213 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
215 // Allocate statement handles for the table
218 // Allocate a separate statement handle for performing inserts
219 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
220 pDb
->DispAllErrors(henv
, hdbc
);
221 // Allocate a separate statement handle for performing deletes
222 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
223 pDb
->DispAllErrors(henv
, hdbc
);
224 // Allocate a separate statement handle for performing updates
225 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
226 pDb
->DispAllErrors(henv
, hdbc
);
228 // Allocate a separate statement handle for internal use
229 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
230 pDb
->DispAllErrors(henv
, hdbc
);
232 // Set the cursor type for the statement handles
233 cursorType
= SQL_CURSOR_STATIC
;
235 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
237 // Check to see if cursor type is supported
238 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
239 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
241 // Datasource does not support static cursors. Driver
242 // will substitute a cursor type. Call SQLGetStmtOption()
243 // to determine which cursor type was selected.
244 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
245 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
246 #ifdef DBDEBUG_CONSOLE
247 cout
<< wxT("Static cursor changed to: ");
250 case SQL_CURSOR_FORWARD_ONLY
:
251 cout
<< wxT("Forward Only");
253 case SQL_CURSOR_STATIC
:
254 cout
<< wxT("Static");
256 case SQL_CURSOR_KEYSET_DRIVEN
:
257 cout
<< wxT("Keyset Driven");
259 case SQL_CURSOR_DYNAMIC
:
260 cout
<< wxT("Dynamic");
263 cout
<< endl
<< endl
;
266 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
268 // Force the use of a forward only cursor...
269 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
270 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
272 // Should never happen
273 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
280 pDb
->DispNextError();
281 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
284 #ifdef DBDEBUG_CONSOLE
286 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
291 // Set the cursor type for the INSERT statement handle
292 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
293 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
294 // Set the cursor type for the DELETE statement handle
295 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
296 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
297 // Set the cursor type for the UPDATE statement handle
298 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
299 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
302 // Make the default cursor the active cursor
303 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
304 wxASSERT(hstmtDefault
);
305 hstmt
= *hstmtDefault
;
309 } // wxDbTable::initialize()
312 void wxDbTable::cleanup()
317 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
324 TablesInUse
.DeleteContents(TRUE
);
328 pNode
= TablesInUse
.First();
329 while (pNode
&& !found
)
331 if (((wxTablesInUse
*)pNode
->Data())->tableID
== tableID
)
334 if (!TablesInUse
.DeleteNode(pNode
))
335 wxLogDebug (s
,wxT("Unable to delete node!"));
338 pNode
= pNode
->Next();
343 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
344 wxLogDebug (msg
,wxT("NOTICE..."));
349 // Decrement the wxDb table count
351 pDb
->decrementTableCount();
353 // Delete memory allocated for column definitions
357 // Free statement handles
363 ODBC 3.0 says to use this form
364 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
366 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
367 pDb
->DispAllErrors(henv
, hdbc
);
373 ODBC 3.0 says to use this form
374 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
376 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
377 pDb
->DispAllErrors(henv
, hdbc
);
383 ODBC 3.0 says to use this form
384 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
386 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
387 pDb
->DispAllErrors(henv
, hdbc
);
393 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
394 pDb
->DispAllErrors(henv
, hdbc
);
397 // Delete dynamically allocated cursors
399 DeleteCursor(hstmtDefault
);
402 DeleteCursor(hstmtCount
);
404 if (m_hstmtGridQuery
)
405 DeleteCursor(m_hstmtGridQuery
);
407 } // wxDbTable::cleanup()
410 /***************************** PRIVATE FUNCTIONS *****************************/
413 /********** wxDbTable::bindParams() **********/
414 bool wxDbTable::bindParams(bool forUpdate
)
416 wxASSERT(!queryOnly
);
421 SDWORD precision
= 0;
424 // Bind each column of the table that should be bound
425 // to a parameter marker
429 for (i
=0, colNo
=1; i
< noCols
; i
++)
433 if (!colDefs
[i
].Updateable
)
438 if (!colDefs
[i
].InsertAllowed
)
442 switch(colDefs
[i
].DbDataType
)
444 case DB_DATA_TYPE_VARCHAR
:
445 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
446 precision
= colDefs
[i
].SzDataObj
;
449 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
451 colDefs
[i
].CbValue
= SQL_NTS
;
453 case DB_DATA_TYPE_INTEGER
:
454 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
455 precision
= pDb
->GetTypeInfInteger().Precision
;
458 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
460 colDefs
[i
].CbValue
= 0;
462 case DB_DATA_TYPE_FLOAT
:
463 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
464 precision
= pDb
->GetTypeInfFloat().Precision
;
465 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
466 // SQL Sybase Anywhere v5.5 returned a negative number for the
467 // MaxScale. This caused ODBC to kick out an error on ibscale.
468 // I check for this here and set the scale = precision.
470 // scale = (short) precision;
472 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
474 colDefs
[i
].CbValue
= 0;
476 case DB_DATA_TYPE_DATE
:
477 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
478 precision
= pDb
->GetTypeInfDate().Precision
;
481 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
483 colDefs
[i
].CbValue
= 0;
485 case DB_DATA_TYPE_BLOB
:
486 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
490 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
492 colDefs
[i
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[i
].SzDataObj
);
497 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
498 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
499 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
501 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
506 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
507 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
508 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
510 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
515 // Completed successfully
518 } // wxDbTable::bindParams()
521 /********** wxDbTable::bindInsertParams() **********/
522 bool wxDbTable::bindInsertParams(void)
524 return bindParams(FALSE
);
525 } // wxDbTable::bindInsertParams()
528 /********** wxDbTable::bindUpdateParams() **********/
529 bool wxDbTable::bindUpdateParams(void)
531 return bindParams(TRUE
);
532 } // wxDbTable::bindUpdateParams()
535 /********** wxDbTable::bindCols() **********/
536 bool wxDbTable::bindCols(HSTMT cursor
)
540 // Bind each column of the table to a memory address for fetching data
542 for (i
= 0; i
< noCols
; i
++)
544 cb
= colDefs
[i
].CbValue
;
545 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
546 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
547 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
550 // Completed successfully
553 } // wxDbTable::bindCols()
556 /********** wxDbTable::getRec() **********/
557 bool wxDbTable::getRec(UWORD fetchType
)
561 if (!pDb
->FwdOnlyCursors())
563 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
567 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
568 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
570 if (retcode
== SQL_NO_DATA_FOUND
)
573 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
577 // Set the Null member variable to indicate the Null state
578 // of each column just read in.
580 for (i
= 0; i
< noCols
; i
++)
581 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
586 // Fetch the next record from the record set
587 retcode
= SQLFetch(hstmt
);
588 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
590 if (retcode
== SQL_NO_DATA_FOUND
)
593 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
597 // Set the Null member variable to indicate the Null state
598 // of each column just read in.
600 for (i
= 0; i
< noCols
; i
++)
601 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
605 // Completed successfully
608 } // wxDbTable::getRec()
611 /********** wxDbTable::execDelete() **********/
612 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
616 // Execute the DELETE statement
617 retcode
= SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
619 if (retcode
== SQL_SUCCESS
||
620 retcode
== SQL_NO_DATA_FOUND
||
621 retcode
== SQL_SUCCESS_WITH_INFO
)
623 // Record deleted successfully
627 // Problem deleting record
628 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
630 } // wxDbTable::execDelete()
633 /********** wxDbTable::execUpdate() **********/
634 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
638 // Execute the UPDATE statement
639 retcode
= SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
641 if (retcode
== SQL_SUCCESS
||
642 retcode
== SQL_NO_DATA_FOUND
||
643 retcode
== SQL_SUCCESS_WITH_INFO
)
645 // Record updated successfully
648 else if (retcode
== SQL_NEED_DATA
)
651 while ((retcode
= SQLParamData(hstmtUpdate
, &pParmID
) == SQL_NEED_DATA
))
653 // Find the parameter
655 for (i
=0; i
< noCols
; i
++)
657 if (colDefs
[i
].PtrDataObj
== pParmID
)
659 // We found it. Store the parameter.
660 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
661 if (retcode
!= SQL_SUCCESS
)
663 pDb
->DispNextError();
664 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
670 if (retcode
== SQL_SUCCESS
||
671 retcode
== SQL_NO_DATA_FOUND
||
672 retcode
== SQL_SUCCESS_WITH_INFO
)
674 // Record updated successfully
679 // Problem updating record
680 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
682 } // wxDbTable::execUpdate()
685 /********** wxDbTable::query() **********/
686 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
691 // The user may wish to select for update, but the DBMS may not be capable
692 selectForUpdate
= CanSelectForUpdate();
694 selectForUpdate
= FALSE
;
696 // Set the SQL SELECT string
697 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
698 { // so generate a select statement.
699 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
700 pDb
->WriteSqlLog(sqlStmt
);
703 // Make sure the cursor is closed first
704 if (!CloseCursor(hstmt
))
707 // Execute the SQL SELECT statement
709 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
710 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
711 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
713 // Completed successfully
716 } // wxDbTable::query()
719 /***************************** PUBLIC FUNCTIONS *****************************/
722 /********** wxDbTable::Open() **********/
723 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
733 // Calculate the maximum size of the concatenated
734 // keys for use with wxDbGrid
736 for (i
=0; i
< noCols
; i
++)
738 if (colDefs
[i
].KeyField
)
741 m_keysize
+= colDefs
[i
].SzDataObj
;
746 // Verify that the table exists in the database
747 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
749 s
= wxT("Table/view does not exist in the database");
750 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
751 s
+= wxT(", or you have no permissions.\n");
755 else if (checkPrivileges
)
757 // Verify the user has rights to access the table.
758 // Shortcut boolean evaluation to optimize out call to
761 // Unfortunately this optimization doesn't seem to be
763 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
764 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
765 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
772 if (!tablePath
.IsEmpty())
773 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
775 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
778 pDb
->LogError(p
.GetData());
783 // Bind the member variables for field exchange between
784 // the wxDbTable object and the ODBC record.
787 if (!bindInsertParams()) // Inserts
790 if (!bindUpdateParams()) // Updates
794 if (!bindCols(*hstmtDefault
)) // Selects
797 if (!bindCols(hstmtInternal
)) // Internal use only
801 * Do NOT bind the hstmtCount cursor!!!
804 // Build an insert statement using parameter markers
805 if (!queryOnly
&& noCols
> 0)
807 bool needComma
= FALSE
;
808 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
809 pDb
->SQLTableName(tableName
.c_str()).c_str());
810 for (i
= 0; i
< noCols
; i
++)
812 if (! colDefs
[i
].InsertAllowed
)
816 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
817 // sqlStmt += colDefs[i].ColName;
821 sqlStmt
+= wxT(") VALUES (");
823 int insertableCount
= 0;
825 for (i
= 0; i
< noCols
; i
++)
827 if (! colDefs
[i
].InsertAllowed
)
837 // Prepare the insert statement for execution
840 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
841 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
847 // Completed successfully
850 } // wxDbTable::Open()
853 /********** wxDbTable::Query() **********/
854 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
857 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
859 } // wxDbTable::Query()
862 /********** wxDbTable::QueryBySqlStmt() **********/
863 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
865 pDb
->WriteSqlLog(pSqlStmt
);
867 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
869 } // wxDbTable::QueryBySqlStmt()
872 /********** wxDbTable::QueryMatching() **********/
873 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
876 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
878 } // wxDbTable::QueryMatching()
881 /********** wxDbTable::QueryOnKeyFields() **********/
882 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
885 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
887 } // wxDbTable::QueryOnKeyFields()
890 /********** wxDbTable::GetPrev() **********/
891 bool wxDbTable::GetPrev(void)
893 if (pDb
->FwdOnlyCursors())
895 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
899 return(getRec(SQL_FETCH_PRIOR
));
901 } // wxDbTable::GetPrev()
904 /********** wxDbTable::operator-- **********/
905 bool wxDbTable::operator--(int)
907 if (pDb
->FwdOnlyCursors())
909 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
913 return(getRec(SQL_FETCH_PRIOR
));
915 } // wxDbTable::operator--
918 /********** wxDbTable::GetFirst() **********/
919 bool wxDbTable::GetFirst(void)
921 if (pDb
->FwdOnlyCursors())
923 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
927 return(getRec(SQL_FETCH_FIRST
));
929 } // wxDbTable::GetFirst()
932 /********** wxDbTable::GetLast() **********/
933 bool wxDbTable::GetLast(void)
935 if (pDb
->FwdOnlyCursors())
937 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
941 return(getRec(SQL_FETCH_LAST
));
943 } // wxDbTable::GetLast()
946 /********** wxDbTable::BuildDeleteStmt() **********/
947 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
949 wxASSERT(!queryOnly
);
953 wxString whereClause
;
957 // Handle the case of DeleteWhere() and the where clause is blank. It should
958 // delete all records from the database in this case.
959 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
961 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
962 pDb
->SQLTableName(tableName
.c_str()).c_str());
966 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
967 pDb
->SQLTableName(tableName
.c_str()).c_str());
969 // Append the WHERE clause to the SQL DELETE statement
972 case DB_DEL_KEYFIELDS
:
973 // If the datasource supports the ROWID column, build
974 // the where on ROWID for efficiency purposes.
975 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
979 wxChar rowid
[wxDB_ROWID_LEN
+1];
981 // Get the ROWID value. If not successful retreiving the ROWID,
982 // simply fall down through the code and build the WHERE clause
983 // based on the key fields.
984 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
986 pSqlStmt
+= wxT("ROWID = '");
988 pSqlStmt
+= wxT("'");
992 // Unable to delete by ROWID, so build a WHERE
993 // clause based on the keyfields.
994 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
995 pSqlStmt
+= whereClause
;
998 pSqlStmt
+= pWhereClause
;
1000 case DB_DEL_MATCHING
:
1001 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1002 pSqlStmt
+= whereClause
;
1006 } // BuildDeleteStmt()
1009 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1010 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1012 wxString tempSqlStmt
;
1013 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1014 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1015 } // wxDbTable::BuildDeleteStmt()
1018 /********** wxDbTable::BuildSelectStmt() **********/
1019 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1021 wxString whereClause
;
1022 whereClause
.Empty();
1024 // Build a select statement to query the database
1025 pSqlStmt
= wxT("SELECT ");
1027 // SELECT DISTINCT values only?
1029 pSqlStmt
+= wxT("DISTINCT ");
1031 // Was a FROM clause specified to join tables to the base table?
1032 // Available for ::Query() only!!!
1033 bool appendFromClause
= FALSE
;
1034 #if wxODBC_BACKWARD_COMPATABILITY
1035 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1036 appendFromClause
= TRUE
;
1038 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1039 appendFromClause
= TRUE
;
1042 // Add the column list
1045 for (i
= 0; i
< noCols
; i
++)
1047 tStr
= colDefs
[i
].ColName
;
1048 // If joining tables, the base table column names must be qualified to avoid ambiguity
1049 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && !tStr
.Find(wxT('.')))
1051 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1052 pSqlStmt
+= wxT(".");
1054 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1056 pSqlStmt
+= wxT(",");
1059 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1060 // the ROWID if querying distinct records. The rowid will always be unique.
1061 if (!distinct
&& CanUpdByROWID())
1063 // If joining tables, the base table column names must be qualified to avoid ambiguity
1064 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1066 pSqlStmt
+= wxT(",");
1067 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1068 // pSqlStmt += queryTableName;
1069 pSqlStmt
+= wxT(".ROWID");
1072 pSqlStmt
+= wxT(",ROWID");
1075 // Append the FROM tablename portion
1076 pSqlStmt
+= wxT(" FROM ");
1077 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1078 // pSqlStmt += queryTableName;
1080 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1081 // The HOLDLOCK keyword follows the table name in the from clause.
1082 // Each table in the from clause must specify HOLDLOCK or
1083 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1084 // is parsed but ignored in SYBASE Transact-SQL.
1085 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1086 pSqlStmt
+= wxT(" HOLDLOCK");
1088 if (appendFromClause
)
1091 // Append the WHERE clause. Either append the where clause for the class
1092 // or build a where clause. The typeOfSelect determines this.
1093 switch(typeOfSelect
)
1095 case DB_SELECT_WHERE
:
1096 #if wxODBC_BACKWARD_COMPATABILITY
1097 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1099 if (where
.Length()) // May not want a where clause!!!
1102 pSqlStmt
+= wxT(" WHERE ");
1106 case DB_SELECT_KEYFIELDS
:
1107 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1108 if (whereClause
.Length())
1110 pSqlStmt
+= wxT(" WHERE ");
1111 pSqlStmt
+= whereClause
;
1114 case DB_SELECT_MATCHING
:
1115 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1116 if (whereClause
.Length())
1118 pSqlStmt
+= wxT(" WHERE ");
1119 pSqlStmt
+= whereClause
;
1124 // Append the ORDER BY clause
1125 #if wxODBC_BACKWARD_COMPATABILITY
1126 if (orderBy
&& wxStrlen(orderBy
))
1128 if (orderBy
.Length())
1131 pSqlStmt
+= wxT(" ORDER BY ");
1132 pSqlStmt
+= orderBy
;
1135 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1136 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1137 // HOLDLOCK for Sybase.
1138 if (selectForUpdate
&& CanSelectForUpdate())
1139 pSqlStmt
+= wxT(" FOR UPDATE");
1141 } // wxDbTable::BuildSelectStmt()
1144 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1145 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1147 wxString tempSqlStmt
;
1148 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1149 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1150 } // wxDbTable::BuildSelectStmt()
1153 /********** wxDbTable::BuildUpdateStmt() **********/
1154 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1156 wxASSERT(!queryOnly
);
1160 wxString whereClause
;
1161 whereClause
.Empty();
1163 bool firstColumn
= TRUE
;
1165 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1166 pDb
->SQLTableName(tableName
.c_str()).c_str());
1168 // Append a list of columns to be updated
1170 for (i
= 0; i
< noCols
; i
++)
1172 // Only append Updateable columns
1173 if (colDefs
[i
].Updateable
)
1176 pSqlStmt
+= wxT(",");
1178 firstColumn
= FALSE
;
1180 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1181 // pSqlStmt += colDefs[i].ColName;
1182 pSqlStmt
+= wxT(" = ?");
1186 // Append the WHERE clause to the SQL UPDATE statement
1187 pSqlStmt
+= wxT(" WHERE ");
1190 case DB_UPD_KEYFIELDS
:
1191 // If the datasource supports the ROWID column, build
1192 // the where on ROWID for efficiency purposes.
1193 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1194 if (CanUpdByROWID())
1197 wxChar rowid
[wxDB_ROWID_LEN
+1];
1199 // Get the ROWID value. If not successful retreiving the ROWID,
1200 // simply fall down through the code and build the WHERE clause
1201 // based on the key fields.
1202 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1204 pSqlStmt
+= wxT("ROWID = '");
1206 pSqlStmt
+= wxT("'");
1210 // Unable to delete by ROWID, so build a WHERE
1211 // clause based on the keyfields.
1212 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1213 pSqlStmt
+= whereClause
;
1216 pSqlStmt
+= pWhereClause
;
1219 } // BuildUpdateStmt()
1222 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1223 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1225 wxString tempSqlStmt
;
1226 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1227 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1228 } // BuildUpdateStmt()
1231 /********** wxDbTable::BuildWhereClause() **********/
1232 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1233 const wxString
&qualTableName
, bool useLikeComparison
)
1235 * Note: BuildWhereClause() currently ignores timestamp columns.
1236 * They are not included as part of the where clause.
1239 bool moreThanOneColumn
= FALSE
;
1242 // Loop through the columns building a where clause as you go
1244 for (colNo
= 0; colNo
< noCols
; colNo
++)
1246 // Determine if this column should be included in the WHERE clause
1247 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNo
].KeyField
) ||
1248 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(colNo
))))
1250 // Skip over timestamp columns
1251 if (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
)
1253 // If there is more than 1 column, join them with the keyword "AND"
1254 if (moreThanOneColumn
)
1255 pWhereClause
+= wxT(" AND ");
1257 moreThanOneColumn
= TRUE
;
1259 // Concatenate where phrase for the column
1260 wxString tStr
= colDefs
[colNo
].ColName
;
1262 if (qualTableName
.Length() && !tStr
.Find(wxT('.')))
1264 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1265 pWhereClause
+= wxT(".");
1267 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNo
].ColName
);
1269 if (useLikeComparison
&& (colDefs
[colNo
].SqlCtype
== SQL_C_CHAR
))
1270 pWhereClause
+= wxT(" LIKE ");
1272 pWhereClause
+= wxT(" = ");
1274 switch(colDefs
[colNo
].SqlCtype
)
1277 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
);
1280 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNo
].PtrDataObj
));
1283 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNo
].PtrDataObj
));
1286 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNo
].PtrDataObj
));
1289 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNo
].PtrDataObj
));
1292 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
));
1295 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
));
1298 pWhereClause
+= colValue
;
1301 } // wxDbTable::BuildWhereClause()
1304 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1305 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1306 const wxString
&qualTableName
, bool useLikeComparison
)
1308 wxString tempSqlStmt
;
1309 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1310 wxStrcpy(pWhereClause
, tempSqlStmt
);
1311 } // wxDbTable::BuildWhereClause()
1314 /********** wxDbTable::GetRowNum() **********/
1315 UWORD
wxDbTable::GetRowNum(void)
1319 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1321 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1325 // Completed successfully
1326 return((UWORD
) rowNum
);
1328 } // wxDbTable::GetRowNum()
1331 /********** wxDbTable::CloseCursor() **********/
1332 bool wxDbTable::CloseCursor(HSTMT cursor
)
1334 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1335 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1337 // Completed successfully
1340 } // wxDbTable::CloseCursor()
1343 /********** wxDbTable::CreateTable() **********/
1344 bool wxDbTable::CreateTable(bool attemptDrop
)
1352 #ifdef DBDEBUG_CONSOLE
1353 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1357 if (attemptDrop
&& !DropTable())
1361 #ifdef DBDEBUG_CONSOLE
1362 for (i
= 0; i
< noCols
; i
++)
1364 // Exclude derived columns since they are NOT part of the base table
1365 if (colDefs
[i
].DerivedCol
)
1367 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1368 switch(colDefs
[i
].DbDataType
)
1370 case DB_DATA_TYPE_VARCHAR
:
1371 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1373 case DB_DATA_TYPE_INTEGER
:
1374 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1376 case DB_DATA_TYPE_FLOAT
:
1377 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1379 case DB_DATA_TYPE_DATE
:
1380 cout
<< pDb
->GetTypeInfDate().TypeName
;
1382 case DB_DATA_TYPE_BLOB
:
1383 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1390 // Build a CREATE TABLE string from the colDefs structure.
1391 bool needComma
= FALSE
;
1393 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1394 pDb
->SQLTableName(tableName
.c_str()).c_str());
1396 for (i
= 0; i
< noCols
; i
++)
1398 // Exclude derived columns since they are NOT part of the base table
1399 if (colDefs
[i
].DerivedCol
)
1403 sqlStmt
+= wxT(",");
1405 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1406 // sqlStmt += colDefs[i].ColName;
1407 sqlStmt
+= wxT(" ");
1409 switch(colDefs
[i
].DbDataType
)
1411 case DB_DATA_TYPE_VARCHAR
:
1412 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1414 case DB_DATA_TYPE_INTEGER
:
1415 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1417 case DB_DATA_TYPE_FLOAT
:
1418 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1420 case DB_DATA_TYPE_DATE
:
1421 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1423 case DB_DATA_TYPE_BLOB
:
1424 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1427 // For varchars, append the size of the string
1428 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1429 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= "text"))// ||
1430 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1433 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1437 if (pDb
->Dbms() == dbmsDB2
||
1438 pDb
->Dbms() == dbmsMY_SQL
||
1439 pDb
->Dbms() == dbmsSYBASE_ASE
||
1440 pDb
->Dbms() == dbmsINTERBASE
||
1441 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1443 if (colDefs
[i
].KeyField
)
1445 sqlStmt
+= wxT(" NOT NULL");
1451 // If there is a primary key defined, include it in the create statement
1452 for (i
= j
= 0; i
< noCols
; i
++)
1454 if (colDefs
[i
].KeyField
)
1460 if (j
&& (pDb
->Dbms() != dbmsDBASE
)
1461 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
)
1462 ) // Found a keyfield
1464 switch (pDb
->Dbms())
1468 case dbmsSYBASE_ASA
:
1469 case dbmsSYBASE_ASE
:
1472 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1473 sqlStmt
+= wxT(",PRIMARY KEY (");
1478 sqlStmt
+= wxT(",CONSTRAINT ");
1479 // DB2 is limited to 18 characters for index names
1480 if (pDb
->Dbms() == dbmsDB2
)
1482 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."));
1483 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1484 // sqlStmt += tableName.substr(0, 13);
1487 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1488 // sqlStmt += tableName;
1490 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1495 // List column name(s) of column(s) comprising the primary key
1496 for (i
= j
= 0; i
< noCols
; i
++)
1498 if (colDefs
[i
].KeyField
)
1500 if (j
++) // Multi part key, comma separate names
1501 sqlStmt
+= wxT(",");
1502 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1504 if (pDb
->Dbms() == dbmsMY_SQL
&&
1505 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1508 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1513 sqlStmt
+= wxT(")");
1515 if (pDb
->Dbms() == dbmsINFORMIX
||
1516 pDb
->Dbms() == dbmsSYBASE_ASA
||
1517 pDb
->Dbms() == dbmsSYBASE_ASE
)
1519 sqlStmt
+= wxT(" CONSTRAINT ");
1520 sqlStmt
+= pDb
->SQLTableName(tableName
);
1521 // sqlStmt += tableName;
1522 sqlStmt
+= wxT("_PIDX");
1525 // Append the closing parentheses for the create table statement
1526 sqlStmt
+= wxT(")");
1528 pDb
->WriteSqlLog(sqlStmt
);
1530 #ifdef DBDEBUG_CONSOLE
1531 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1534 // Execute the CREATE TABLE statement
1535 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1536 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1538 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1539 pDb
->RollbackTrans();
1544 // Commit the transaction and close the cursor
1545 if (!pDb
->CommitTrans())
1547 if (!CloseCursor(hstmt
))
1550 // Database table created successfully
1553 } // wxDbTable::CreateTable()
1556 /********** wxDbTable::DropTable() **********/
1557 bool wxDbTable::DropTable()
1559 // NOTE: This function returns TRUE if the Table does not exist, but
1560 // only for identified databases. Code will need to be added
1561 // below for any other databases when those databases are defined
1562 // to handle this situation consistently
1566 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1567 pDb
->SQLTableName(tableName
.c_str()).c_str());
1569 pDb
->WriteSqlLog(sqlStmt
);
1571 #ifdef DBDEBUG_CONSOLE
1572 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1575 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1576 if (retcode
!= SQL_SUCCESS
)
1578 // Check for "Base table not found" error and ignore
1579 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1580 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1581 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1583 // Check for product specific error codes
1584 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1585 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1586 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1587 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1589 pDb
->DispNextError();
1590 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1591 pDb
->RollbackTrans();
1592 // CloseCursor(hstmt);
1598 // Commit the transaction and close the cursor
1599 if (! pDb
->CommitTrans())
1601 if (! CloseCursor(hstmt
))
1605 } // wxDbTable::DropTable()
1608 /********** wxDbTable::CreateIndex() **********/
1609 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1610 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1614 // Drop the index first
1615 if (attemptDrop
&& !DropIndex(idxName
))
1618 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1619 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1620 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1621 // table was created, then months later you determine that an additional index while
1622 // give better performance, so you want to add an index).
1624 // The following block of code will modify the column definition to make the column be
1625 // defined with the "NOT NULL" qualifier.
1626 if (pDb
->Dbms() == dbmsMY_SQL
)
1631 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1635 // Find the column definition that has the ColName that matches the
1636 // index column name. We need to do this to get the DB_DATA_TYPE of
1637 // the index column, as MySQL's syntax for the ALTER column requires
1639 while (!found
&& (j
< this->noCols
))
1641 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1649 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1650 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1655 wxODBC_ERRORS retcode
;
1656 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1657 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1658 // This line is just here for debug checking of the value
1659 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1669 pDb
->RollbackTrans();
1674 // Build a CREATE INDEX statement
1675 sqlStmt
= wxT("CREATE ");
1677 sqlStmt
+= wxT("UNIQUE ");
1679 sqlStmt
+= wxT("INDEX ");
1680 sqlStmt
+= pDb
->SQLTableName(idxName
);
1681 sqlStmt
+= wxT(" ON ");
1683 sqlStmt
+= pDb
->SQLTableName(tableName
);
1684 // sqlStmt += tableName;
1685 sqlStmt
+= wxT(" (");
1687 // Append list of columns making up index
1689 for (i
= 0; i
< noIdxCols
; i
++)
1691 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1692 // sqlStmt += pIdxDefs[i].ColName;
1694 // MySQL requires a key length on VARCHAR keys
1695 if ( pDb
->Dbms() == dbmsMY_SQL
)
1697 // Find the details on this column
1699 for ( j
= 0; j
< noCols
; ++j
)
1701 if ( wxStrcmp( pIdxDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1706 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1709 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1714 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1715 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (strncmp(pDb
->dbInf
.dbmsVer
,"07",2)==0)) &&
1716 !(pDb
->Dbms() == dbmsPOSTGRES
))
1718 if (pIdxDefs
[i
].Ascending
)
1719 sqlStmt
+= wxT(" ASC");
1721 sqlStmt
+= wxT(" DESC");
1724 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, "Datasource does not support DESCending index columns");
1726 if ((i
+ 1) < noIdxCols
)
1727 sqlStmt
+= wxT(",");
1730 // Append closing parentheses
1731 sqlStmt
+= wxT(")");
1733 pDb
->WriteSqlLog(sqlStmt
);
1735 #ifdef DBDEBUG_CONSOLE
1736 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1739 // Execute the CREATE INDEX statement
1740 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1742 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1743 pDb
->RollbackTrans();
1748 // Commit the transaction and close the cursor
1749 if (! pDb
->CommitTrans())
1751 if (! CloseCursor(hstmt
))
1754 // Index Created Successfully
1757 } // wxDbTable::CreateIndex()
1760 /********** wxDbTable::DropIndex() **********/
1761 bool wxDbTable::DropIndex(const wxString
&idxName
)
1763 // NOTE: This function returns TRUE if the Index does not exist, but
1764 // only for identified databases. Code will need to be added
1765 // below for any other databases when those databases are defined
1766 // to handle this situation consistently
1770 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1771 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1772 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1773 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1774 pDb
->SQLTableName(tableName
.c_str()).c_str());
1775 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1776 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1777 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1778 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1779 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1780 pDb
->SQLTableName(idxName
.c_str()).c_str());
1782 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1783 pDb
->SQLTableName(idxName
.c_str()).c_str());
1785 pDb
->WriteSqlLog(sqlStmt
);
1787 #ifdef DBDEBUG_CONSOLE
1788 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1791 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1793 // Check for "Index not found" error and ignore
1794 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1795 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1797 // Check for product specific error codes
1798 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1799 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1800 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1801 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1802 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1803 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1804 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1807 pDb
->DispNextError();
1808 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1809 pDb
->RollbackTrans();
1816 // Commit the transaction and close the cursor
1817 if (! pDb
->CommitTrans())
1819 if (! CloseCursor(hstmt
))
1823 } // wxDbTable::DropIndex()
1826 /********** wxDbTable::SetOrderByColNums() **********/
1827 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1829 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1835 va_start(argptr
, first
); /* Initialize variable arguments. */
1836 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1838 // Make sure the passed in column number
1839 // is within the valid range of columns
1841 // Valid columns are 0 thru noCols-1
1842 if (colNo
>= noCols
|| colNo
< 0)
1849 tempStr
+= wxT(",");
1851 tempStr
+= colDefs
[colNo
].ColName
;
1852 colNo
= va_arg (argptr
, int);
1854 va_end (argptr
); /* Reset variable arguments. */
1856 SetOrderByClause(tempStr
);
1859 } // wxDbTable::SetOrderByColNums()
1862 /********** wxDbTable::Insert() **********/
1863 int wxDbTable::Insert(void)
1865 wxASSERT(!queryOnly
);
1866 if (queryOnly
|| !insertable
)
1871 // Insert the record by executing the already prepared insert statement
1873 retcode
=SQLExecute(hstmtInsert
);
1874 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1875 retcode
!= SQL_NEED_DATA
)
1877 // Check to see if integrity constraint was violated
1878 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1879 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1880 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1883 pDb
->DispNextError();
1884 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1888 if (retcode
== SQL_NEED_DATA
)
1891 while ((retcode
= SQLParamData(hstmtInsert
, &pParmID
) == SQL_NEED_DATA
))
1893 // Find the parameter
1895 for (i
=0; i
< noCols
; i
++)
1897 if (colDefs
[i
].PtrDataObj
== pParmID
)
1899 // We found it. Store the parameter.
1900 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1901 if (retcode
!= SQL_SUCCESS
)
1903 pDb
->DispNextError();
1904 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1913 // Record inserted into the datasource successfully
1916 } // wxDbTable::Insert()
1919 /********** wxDbTable::Update() **********/
1920 bool wxDbTable::Update(void)
1922 wxASSERT(!queryOnly
);
1928 // Build the SQL UPDATE statement
1929 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1931 pDb
->WriteSqlLog(sqlStmt
);
1933 #ifdef DBDEBUG_CONSOLE
1934 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1937 // Execute the SQL UPDATE statement
1938 return(execUpdate(sqlStmt
));
1940 } // wxDbTable::Update()
1943 /********** wxDbTable::Update(pSqlStmt) **********/
1944 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1946 wxASSERT(!queryOnly
);
1950 pDb
->WriteSqlLog(pSqlStmt
);
1952 return(execUpdate(pSqlStmt
));
1954 } // wxDbTable::Update(pSqlStmt)
1957 /********** wxDbTable::UpdateWhere() **********/
1958 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1960 wxASSERT(!queryOnly
);
1966 // Build the SQL UPDATE statement
1967 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1969 pDb
->WriteSqlLog(sqlStmt
);
1971 #ifdef DBDEBUG_CONSOLE
1972 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1975 // Execute the SQL UPDATE statement
1976 return(execUpdate(sqlStmt
));
1978 } // wxDbTable::UpdateWhere()
1981 /********** wxDbTable::Delete() **********/
1982 bool wxDbTable::Delete(void)
1984 wxASSERT(!queryOnly
);
1991 // Build the SQL DELETE statement
1992 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1994 pDb
->WriteSqlLog(sqlStmt
);
1996 // Execute the SQL DELETE statement
1997 return(execDelete(sqlStmt
));
1999 } // wxDbTable::Delete()
2002 /********** wxDbTable::DeleteWhere() **********/
2003 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2005 wxASSERT(!queryOnly
);
2012 // Build the SQL DELETE statement
2013 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2015 pDb
->WriteSqlLog(sqlStmt
);
2017 // Execute the SQL DELETE statement
2018 return(execDelete(sqlStmt
));
2020 } // wxDbTable::DeleteWhere()
2023 /********** wxDbTable::DeleteMatching() **********/
2024 bool wxDbTable::DeleteMatching(void)
2026 wxASSERT(!queryOnly
);
2033 // Build the SQL DELETE statement
2034 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2036 pDb
->WriteSqlLog(sqlStmt
);
2038 // Execute the SQL DELETE statement
2039 return(execDelete(sqlStmt
));
2041 } // wxDbTable::DeleteMatching()
2044 /********** wxDbTable::IsColNull() **********/
2045 bool wxDbTable::IsColNull(UWORD colNo
) const
2048 This logic is just not right. It would indicate TRUE
2049 if a numeric field were set to a value of 0.
2051 switch(colDefs[colNo].SqlCtype)
2054 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
2056 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
2058 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
2060 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2062 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2064 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
2066 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
2067 case SQL_C_TIMESTAMP:
2068 TIMESTAMP_STRUCT *pDt;
2069 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
2070 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2078 return (colDefs
[colNo
].Null
);
2079 } // wxDbTable::IsColNull()
2082 /********** wxDbTable::CanSelectForUpdate() **********/
2083 bool wxDbTable::CanSelectForUpdate(void)
2088 if (pDb
->Dbms() == dbmsMY_SQL
)
2091 if ((pDb
->Dbms() == dbmsORACLE
) ||
2092 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2097 } // wxDbTable::CanSelectForUpdate()
2100 /********** wxDbTable::CanUpdByROWID() **********/
2101 bool wxDbTable::CanUpdByROWID(void)
2104 * NOTE: Returning FALSE for now until this can be debugged,
2105 * as the ROWID is not getting updated correctly
2109 if (pDb->Dbms() == dbmsORACLE)
2114 } // wxDbTable::CanUpdByROWID()
2117 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2118 bool wxDbTable::IsCursorClosedOnCommit(void)
2120 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2125 } // wxDbTable::IsCursorClosedOnCommit()
2129 /********** wxDbTable::ClearMemberVar() **********/
2130 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2132 wxASSERT(colNo
< noCols
);
2134 switch(colDefs
[colNo
].SqlCtype
)
2137 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2140 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2143 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2146 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2149 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2152 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2155 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2157 case SQL_C_TIMESTAMP
:
2158 TIMESTAMP_STRUCT
*pDt
;
2159 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2172 } // wxDbTable::ClearMemberVar()
2175 /********** wxDbTable::ClearMemberVars() **********/
2176 void wxDbTable::ClearMemberVars(bool setToNull
)
2180 // Loop through the columns setting each member variable to zero
2181 for (i
=0; i
< noCols
; i
++)
2182 ClearMemberVar(i
,setToNull
);
2184 } // wxDbTable::ClearMemberVars()
2187 /********** wxDbTable::SetQueryTimeout() **********/
2188 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2190 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2191 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2192 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2193 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2194 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2195 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2196 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2197 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2199 // Completed Successfully
2202 } // wxDbTable::SetQueryTimeout()
2205 /********** wxDbTable::SetColDefs() **********/
2206 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2207 SWORD cType
, int size
, bool keyField
, bool upd
,
2208 bool insAllow
, bool derivedCol
)
2210 wxASSERT_MSG( index
< noCols
,
2211 _T("Specified column index exceeds the maximum number of columns for this table.") );
2213 if (!colDefs
) // May happen if the database connection fails
2216 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2218 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2219 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2223 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2224 fieldName
.c_str(),colDefs
[index
].ColName
);
2226 #endif // __WXDEBUG__
2229 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2231 colDefs
[index
].DbDataType
= dataType
;
2232 colDefs
[index
].PtrDataObj
= pData
;
2233 colDefs
[index
].SqlCtype
= cType
;
2234 colDefs
[index
].SzDataObj
= size
;
2235 colDefs
[index
].KeyField
= keyField
;
2236 colDefs
[index
].DerivedCol
= derivedCol
;
2237 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2240 colDefs
[index
].Updateable
= FALSE
;
2241 colDefs
[index
].InsertAllowed
= FALSE
;
2245 colDefs
[index
].Updateable
= upd
;
2246 colDefs
[index
].InsertAllowed
= insAllow
;
2249 colDefs
[index
].Null
= FALSE
;
2251 } // wxDbTable::SetColDefs()
2254 /********** wxDbTable::SetColDefs() **********/
2255 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2258 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2264 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2266 for (index
= 0; index
< numCols
; index
++)
2268 // Process the fields
2269 switch (pColInfs
[index
].dbDataType
)
2271 case DB_DATA_TYPE_VARCHAR
:
2272 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2273 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2274 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2276 case DB_DATA_TYPE_INTEGER
:
2277 // Can be long or short
2278 if (pColInfs
[index
].bufferLength
== sizeof(long))
2280 pColDataPtrs
[index
].PtrDataObj
= new long;
2281 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2282 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2286 pColDataPtrs
[index
].PtrDataObj
= new short;
2287 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2288 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2291 case DB_DATA_TYPE_FLOAT
:
2292 // Can be float or double
2293 if (pColInfs
[index
].bufferLength
== sizeof(float))
2295 pColDataPtrs
[index
].PtrDataObj
= new float;
2296 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2297 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2301 pColDataPtrs
[index
].PtrDataObj
= new double;
2302 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2303 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2306 case DB_DATA_TYPE_DATE
:
2307 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2308 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2309 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2311 case DB_DATA_TYPE_BLOB
:
2312 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2313 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2314 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2315 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2318 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2319 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2322 // Unable to build all the column definitions, as either one of
2323 // the calls to "new" failed above, or there was a BLOB field
2324 // to have a column definition for. If BLOBs are to be used,
2325 // the other form of ::SetColDefs() must be used, as it is impossible
2326 // to know the maximum size to create the PtrDataObj to be.
2327 delete [] pColDataPtrs
;
2333 return (pColDataPtrs
);
2335 } // wxDbTable::SetColDefs()
2338 /********** wxDbTable::SetCursor() **********/
2339 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2341 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2342 hstmt
= *hstmtDefault
;
2344 hstmt
= *hstmtActivate
;
2346 } // wxDbTable::SetCursor()
2349 /********** wxDbTable::Count(const wxString &) **********/
2350 ULONG
wxDbTable::Count(const wxString
&args
)
2356 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2357 sqlStmt
= wxT("SELECT COUNT(");
2359 sqlStmt
+= wxT(") FROM ");
2360 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2361 // sqlStmt += queryTableName;
2362 #if wxODBC_BACKWARD_COMPATABILITY
2363 if (from
&& wxStrlen(from
))
2369 // Add the where clause if one is provided
2370 #if wxODBC_BACKWARD_COMPATABILITY
2371 if (where
&& wxStrlen(where
))
2376 sqlStmt
+= wxT(" WHERE ");
2380 pDb
->WriteSqlLog(sqlStmt
);
2382 // Initialize the Count cursor if it's not already initialized
2385 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2386 wxASSERT(hstmtCount
);
2391 // Execute the SQL statement
2392 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2394 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2399 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2401 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2405 // Obtain the result
2406 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2408 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2413 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2414 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2416 // Return the record count
2419 } // wxDbTable::Count()
2422 /********** wxDbTable::Refresh() **********/
2423 bool wxDbTable::Refresh(void)
2427 // Switch to the internal cursor so any active cursors are not corrupted
2428 HSTMT currCursor
= GetCursor();
2429 hstmt
= hstmtInternal
;
2430 #if wxODBC_BACKWARD_COMPATABILITY
2431 // Save the where and order by clauses
2432 char *saveWhere
= where
;
2433 char *saveOrderBy
= orderBy
;
2435 wxString saveWhere
= where
;
2436 wxString saveOrderBy
= orderBy
;
2438 // Build a where clause to refetch the record with. Try and use the
2439 // ROWID if it's available, ow use the key fields.
2440 wxString whereClause
;
2441 whereClause
.Empty();
2443 if (CanUpdByROWID())
2446 wxChar rowid
[wxDB_ROWID_LEN
+1];
2448 // Get the ROWID value. If not successful retreiving the ROWID,
2449 // simply fall down through the code and build the WHERE clause
2450 // based on the key fields.
2451 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2453 whereClause
+= pDb
->SQLTableName(queryTableName
);
2454 // whereClause += queryTableName;
2455 whereClause
+= wxT(".ROWID = '");
2456 whereClause
+= rowid
;
2457 whereClause
+= wxT("'");
2461 // If unable to use the ROWID, build a where clause from the keyfields
2462 if (wxStrlen(whereClause
) == 0)
2463 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2465 // Requery the record
2466 where
= whereClause
;
2471 if (result
&& !GetNext())
2474 // Switch back to original cursor
2475 SetCursor(&currCursor
);
2477 // Free the internal cursor
2478 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2479 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2481 // Restore the original where and order by clauses
2483 orderBy
= saveOrderBy
;
2487 } // wxDbTable::Refresh()
2490 /********** wxDbTable::SetColNull() **********/
2491 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2495 colDefs
[colNo
].Null
= set
;
2496 if (set
) // Blank out the values in the member variable
2498 colDefs
[colNo
].CbValue
= SQL_NULL_DATA
; // SF PATCH#766404
2499 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2506 } // wxDbTable::SetColNull()
2509 /********** wxDbTable::SetColNull() **********/
2510 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2513 for (colNo
= 0; colNo
< noCols
; colNo
++)
2515 if (!wxStricmp(colName
, colDefs
[colNo
].ColName
))
2521 colDefs
[colNo
].Null
= set
;
2522 if (set
) // Blank out the values in the member variable
2524 colDefs
[colNo
].CbValue
= SQL_NULL_DATA
; // SF PATCH#766404
2525 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2532 } // wxDbTable::SetColNull()
2535 /********** wxDbTable::GetNewCursor() **********/
2536 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2538 HSTMT
*newHSTMT
= new HSTMT
;
2543 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2545 pDb
->DispAllErrors(henv
, hdbc
);
2550 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2552 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2559 if (!bindCols(*newHSTMT
))
2567 SetCursor(newHSTMT
);
2571 } // wxDbTable::GetNewCursor()
2574 /********** wxDbTable::DeleteCursor() **********/
2575 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2579 if (!hstmtDel
) // Cursor already deleted
2583 ODBC 3.0 says to use this form
2584 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2587 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2589 pDb
->DispAllErrors(henv
, hdbc
);
2597 } // wxDbTable::DeleteCursor()
2599 //////////////////////////////////////////////////////////////
2600 // wxDbGrid support functions
2601 //////////////////////////////////////////////////////////////
2603 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2605 if (!m_hstmtGridQuery
)
2607 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2608 if (!bindCols(*m_hstmtGridQuery
))
2612 m_rowmode
= rowmode
;
2615 case WX_ROW_MODE_QUERY
:
2616 SetCursor(m_hstmtGridQuery
);
2618 case WX_ROW_MODE_INDIVIDUAL
:
2619 SetCursor(hstmtDefault
);
2624 } // wxDbTable::SetRowMode()
2627 wxVariant
wxDbTable::GetCol(const int colNo
) const
2630 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2632 switch (colDefs
[colNo
].SqlCtype
)
2636 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2640 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2644 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2647 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2650 val
= (long)(*(char *)(colDefs
[colNo
].PtrDataObj
));
2652 case SQL_C_UTINYINT
:
2653 val
= (long)(*(unsigned char *)(colDefs
[colNo
].PtrDataObj
));
2656 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2659 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2662 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2664 case SQL_C_TIMESTAMP
:
2665 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2668 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2675 } // wxDbTable::GetCol()
2678 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2680 //FIXME: Add proper wxDateTime support to wxVariant..
2683 SetColNull(colNo
, val
.IsNull());
2687 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2688 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2689 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2691 //Returns null if invalid!
2692 if (!dateval
.ParseDate(val
.GetString()))
2693 SetColNull(colNo
, TRUE
);
2696 switch (colDefs
[colNo
].SqlCtype
)
2700 csstrncpyt((char *)(colDefs
[colNo
].PtrDataObj
),
2701 val
.GetString().c_str(),
2702 colDefs
[colNo
].SzDataObj
-1);
2706 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2710 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2713 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2716 *(char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2718 case SQL_C_UTINYINT
:
2719 *(unsigned char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2722 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2724 //FIXME: Add proper wxDateTime support to wxVariant..
2727 DATE_STRUCT
*dataptr
=
2728 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2730 dataptr
->year
= dateval
.GetYear();
2731 dataptr
->month
= dateval
.GetMonth()+1;
2732 dataptr
->day
= dateval
.GetDay();
2737 TIME_STRUCT
*dataptr
=
2738 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2740 dataptr
->hour
= dateval
.GetHour();
2741 dataptr
->minute
= dateval
.GetMinute();
2742 dataptr
->second
= dateval
.GetSecond();
2745 case SQL_C_TIMESTAMP
:
2747 TIMESTAMP_STRUCT
*dataptr
=
2748 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2749 dataptr
->year
= dateval
.GetYear();
2750 dataptr
->month
= dateval
.GetMonth()+1;
2751 dataptr
->day
= dateval
.GetDay();
2753 dataptr
->hour
= dateval
.GetHour();
2754 dataptr
->minute
= dateval
.GetMinute();
2755 dataptr
->second
= dateval
.GetSecond();
2759 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2764 } // if (!val.IsNull())
2765 } // wxDbTable::SetCol()
2768 GenericKey
wxDbTable::GetKey()
2773 blk
= malloc(m_keysize
);
2774 blkptr
= (wxChar
*) blk
;
2777 for (i
=0; i
< noCols
; i
++)
2779 if (colDefs
[i
].KeyField
)
2781 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2782 blkptr
+= colDefs
[i
].SzDataObj
;
2786 GenericKey k
= GenericKey(blk
, m_keysize
);
2790 } // wxDbTable::GetKey()
2793 void wxDbTable::SetKey(const GenericKey
& k
)
2799 blkptr
= (wxChar
*)blk
;
2802 for (i
=0; i
< noCols
; i
++)
2804 if (colDefs
[i
].KeyField
)
2806 SetColNull(i
, FALSE
);
2807 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2808 blkptr
+= colDefs
[i
].SzDataObj
;
2811 } // wxDbTable::SetKey()
2814 #endif // wxUSE_ODBC