1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/dbtable.cpp
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence
12 ///////////////////////////////////////////////////////////////////////////////
14 #include "wx/wxprec.h"
23 #include "wx/object.h"
25 #include "wx/string.h"
30 #ifdef DBDEBUG_CONSOLE
31 #include "wx/ioswrap.h"
34 #include "wx/filefn.h"
40 #include "wx/dbtable.h"
42 // FIXME-UTF8: get rid of this after switching to Unicode-only builds:
44 #define WXSQLCAST(s) ((SQLTCHAR FAR *)(wchar_t*)(s).wchar_str())
46 #define WXSQLCAST(s) ((SQLTCHAR FAR *)(char*)(s).char_str())
49 ULONG lastTableID
= 0;
53 #include "wx/thread.h"
56 wxCriticalSection csTablesInUse
;
60 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
62 while ( (*target
++ = *source
++) != '\0' && --n
!= 0 )
70 /********** wxDbColDef::wxDbColDef() Constructor **********/
71 wxDbColDef::wxDbColDef()
77 bool wxDbColDef::Initialize()
80 DbDataType
= DB_DATA_TYPE_INTEGER
;
81 SqlCtype
= SQL_C_LONG
;
86 InsertAllowed
= false;
93 } // wxDbColDef::Initialize()
96 /********** wxDbTable::wxDbTable() Constructor **********/
97 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
98 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
100 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
102 } // wxDbTable::wxDbTable()
105 /********** wxDbTable::~wxDbTable() **********/
106 wxDbTable::~wxDbTable()
109 } // wxDbTable::~wxDbTable()
112 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
113 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
115 // Initializing member variables
116 pDb
= pwxDb
; // Pointer to the wxDb object
120 m_hstmtGridQuery
= 0;
121 hstmtDefault
= 0; // Initialized below
122 hstmtCount
= 0; // Initialized first time it is needed
129 m_numCols
= numColumns
; // Number of columns in the table
130 where
.Empty(); // Where clause
131 orderBy
.Empty(); // Order By clause
132 from
.Empty(); // From clause
133 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
138 queryTableName
.Empty();
140 wxASSERT(tblName
.length());
146 tableName
= tblName
; // Table Name
147 if ((pDb
->Dbms() == dbmsORACLE
) ||
148 (pDb
->Dbms() == dbmsFIREBIRD
) ||
149 (pDb
->Dbms() == dbmsINTERBASE
))
150 tableName
= tableName
.Upper();
152 if (tblPath
.length())
153 tablePath
= tblPath
; // Table Path - used for dBase files
157 if (qryTblName
.length()) // Name of the table/view to query
158 queryTableName
= qryTblName
;
160 queryTableName
= tblName
;
162 if ((pDb
->Dbms() == dbmsORACLE
) ||
163 (pDb
->Dbms() == dbmsFIREBIRD
) ||
164 (pDb
->Dbms() == dbmsINTERBASE
))
165 queryTableName
= queryTableName
.Upper();
167 pDb
->incrementTableCount();
170 tableID
= ++lastTableID
;
171 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"),
172 tblName
.c_str(), tableID
, wx_static_cast(void*, pDb
));
175 wxTablesInUse
*tableInUse
;
176 tableInUse
= new wxTablesInUse();
177 tableInUse
->tableName
= tblName
;
178 tableInUse
->tableID
= tableID
;
179 tableInUse
->pDb
= pDb
;
181 wxCriticalSectionLocker
lock(csTablesInUse
);
182 TablesInUse
.Append(tableInUse
);
188 // Grab the HENV and HDBC from the wxDb object
189 henv
= pDb
->GetHENV();
190 hdbc
= pDb
->GetHDBC();
192 // Allocate space for column definitions
194 colDefs
= new wxDbColDef
[m_numCols
]; // Points to the first column definition
196 // Allocate statement handles for the table
199 // Allocate a separate statement handle for performing inserts
200 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
201 pDb
->DispAllErrors(henv
, hdbc
);
202 // Allocate a separate statement handle for performing deletes
203 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
204 pDb
->DispAllErrors(henv
, hdbc
);
205 // Allocate a separate statement handle for performing updates
206 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
207 pDb
->DispAllErrors(henv
, hdbc
);
209 // Allocate a separate statement handle for internal use
210 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
211 pDb
->DispAllErrors(henv
, hdbc
);
213 // Set the cursor type for the statement handles
214 cursorType
= SQL_CURSOR_STATIC
;
216 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
218 // Check to see if cursor type is supported
219 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
220 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
222 // Datasource does not support static cursors. Driver
223 // will substitute a cursor type. Call SQLGetStmtOption()
224 // to determine which cursor type was selected.
225 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
226 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
227 #ifdef DBDEBUG_CONSOLE
228 cout
<< wxT("Static cursor changed to: ");
231 case SQL_CURSOR_FORWARD_ONLY
:
232 cout
<< wxT("Forward Only");
234 case SQL_CURSOR_STATIC
:
235 cout
<< wxT("Static");
237 case SQL_CURSOR_KEYSET_DRIVEN
:
238 cout
<< wxT("Keyset Driven");
240 case SQL_CURSOR_DYNAMIC
:
241 cout
<< wxT("Dynamic");
244 cout
<< endl
<< endl
;
247 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
249 // Force the use of a forward only cursor...
250 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
251 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
253 // Should never happen
254 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
261 pDb
->DispNextError();
262 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
265 #ifdef DBDEBUG_CONSOLE
267 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
272 // Set the cursor type for the INSERT statement handle
273 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
274 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
275 // Set the cursor type for the DELETE statement handle
276 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
277 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
278 // Set the cursor type for the UPDATE statement handle
279 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
280 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
283 // Make the default cursor the active cursor
284 hstmtDefault
= GetNewCursor(false,false);
285 wxASSERT(hstmtDefault
);
286 hstmt
= *hstmtDefault
;
290 } // wxDbTable::initialize()
293 void wxDbTable::cleanup()
298 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"),
299 tableName
.c_str(), tableID
, wx_static_cast(void*, pDb
));
308 wxList::compatibility_iterator pNode
;
310 wxCriticalSectionLocker
lock(csTablesInUse
);
311 pNode
= TablesInUse
.GetFirst();
312 while (!found
&& pNode
)
314 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
317 delete (wxTablesInUse
*)pNode
->GetData();
318 TablesInUse
.Erase(pNode
);
321 pNode
= pNode
->GetNext();
327 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
328 wxLogDebug (msg
,wxT("NOTICE..."));
333 // Decrement the wxDb table count
335 pDb
->decrementTableCount();
337 // Delete memory allocated for column definitions
341 // Free statement handles
347 ODBC 3.0 says to use this form
348 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
350 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
351 pDb
->DispAllErrors(henv
, hdbc
);
357 ODBC 3.0 says to use this form
358 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
360 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
361 pDb
->DispAllErrors(henv
, hdbc
);
367 ODBC 3.0 says to use this form
368 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
370 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
371 pDb
->DispAllErrors(henv
, hdbc
);
377 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
378 pDb
->DispAllErrors(henv
, hdbc
);
381 // Delete dynamically allocated cursors
383 DeleteCursor(hstmtDefault
);
386 DeleteCursor(hstmtCount
);
388 if (m_hstmtGridQuery
)
389 DeleteCursor(m_hstmtGridQuery
);
391 } // wxDbTable::cleanup()
394 /***************************** PRIVATE FUNCTIONS *****************************/
397 void wxDbTable::setCbValueForColumn(int columnIndex
)
399 switch(colDefs
[columnIndex
].DbDataType
)
401 case DB_DATA_TYPE_VARCHAR
:
402 case DB_DATA_TYPE_MEMO
:
403 if (colDefs
[columnIndex
].Null
)
404 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
406 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
408 case DB_DATA_TYPE_INTEGER
:
409 if (colDefs
[columnIndex
].Null
)
410 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
412 colDefs
[columnIndex
].CbValue
= 0;
414 case DB_DATA_TYPE_FLOAT
:
415 if (colDefs
[columnIndex
].Null
)
416 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
418 colDefs
[columnIndex
].CbValue
= 0;
420 case DB_DATA_TYPE_DATE
:
421 if (colDefs
[columnIndex
].Null
)
422 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
424 colDefs
[columnIndex
].CbValue
= 0;
426 case DB_DATA_TYPE_BLOB
:
427 if (colDefs
[columnIndex
].Null
)
428 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
430 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
431 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
433 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
438 /********** wxDbTable::bindParams() **********/
439 bool wxDbTable::bindParams(bool forUpdate
)
441 wxASSERT(!queryOnly
);
446 SDWORD precision
= 0;
449 // Bind each column of the table that should be bound
450 // to a parameter marker
454 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
458 if (!colDefs
[i
].Updateable
)
463 if (!colDefs
[i
].InsertAllowed
)
467 switch(colDefs
[i
].DbDataType
)
469 case DB_DATA_TYPE_VARCHAR
:
470 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
471 precision
= colDefs
[i
].SzDataObj
;
474 case DB_DATA_TYPE_MEMO
:
475 fSqlType
= pDb
->GetTypeInfMemo().FsqlType
;
476 precision
= colDefs
[i
].SzDataObj
;
479 case DB_DATA_TYPE_INTEGER
:
480 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
481 precision
= pDb
->GetTypeInfInteger().Precision
;
484 case DB_DATA_TYPE_FLOAT
:
485 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
486 precision
= pDb
->GetTypeInfFloat().Precision
;
487 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
488 // SQL Sybase Anywhere v5.5 returned a negative number for the
489 // MaxScale. This caused ODBC to kick out an error on ibscale.
490 // I check for this here and set the scale = precision.
492 // scale = (short) precision;
494 case DB_DATA_TYPE_DATE
:
495 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
496 precision
= pDb
->GetTypeInfDate().Precision
;
499 case DB_DATA_TYPE_BLOB
:
500 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
501 precision
= colDefs
[i
].SzDataObj
;
506 setCbValueForColumn(i
);
510 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
511 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
512 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
514 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
519 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
520 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
521 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
523 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
528 // Completed successfully
531 } // wxDbTable::bindParams()
534 /********** wxDbTable::bindInsertParams() **********/
535 bool wxDbTable::bindInsertParams(void)
537 return bindParams(false);
538 } // wxDbTable::bindInsertParams()
541 /********** wxDbTable::bindUpdateParams() **********/
542 bool wxDbTable::bindUpdateParams(void)
544 return bindParams(true);
545 } // wxDbTable::bindUpdateParams()
548 /********** wxDbTable::bindCols() **********/
549 bool wxDbTable::bindCols(HSTMT cursor
)
551 // Bind each column of the table to a memory address for fetching data
553 for (i
= 0; i
< m_numCols
; i
++)
555 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
556 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValueCol
) != SQL_SUCCESS
)
557 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
560 // Completed successfully
562 } // wxDbTable::bindCols()
565 /********** wxDbTable::getRec() **********/
566 bool wxDbTable::getRec(UWORD fetchType
)
570 if (!pDb
->FwdOnlyCursors())
572 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
573 SQLULEN cRowsFetched
;
576 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
577 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
579 if (retcode
== SQL_NO_DATA_FOUND
)
582 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
586 // Set the Null member variable to indicate the Null state
587 // of each column just read in.
589 for (i
= 0; i
< m_numCols
; i
++)
590 colDefs
[i
].Null
= (colDefs
[i
].CbValueCol
== SQL_NULL_DATA
);
595 // Fetch the next record from the record set
596 retcode
= SQLFetch(hstmt
);
597 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
599 if (retcode
== SQL_NO_DATA_FOUND
)
602 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
606 // Set the Null member variable to indicate the Null state
607 // of each column just read in.
609 for (i
= 0; i
< m_numCols
; i
++)
610 colDefs
[i
].Null
= (colDefs
[i
].CbValueCol
== SQL_NULL_DATA
);
614 // Completed successfully
617 } // wxDbTable::getRec()
620 /********** wxDbTable::execDelete() **********/
621 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
625 // Execute the DELETE statement
626 retcode
= SQLExecDirect(hstmtDelete
, WXSQLCAST(pSqlStmt
), SQL_NTS
);
628 if (retcode
== SQL_SUCCESS
||
629 retcode
== SQL_NO_DATA_FOUND
||
630 retcode
== SQL_SUCCESS_WITH_INFO
)
632 // Record deleted successfully
636 // Problem deleting record
637 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
639 } // wxDbTable::execDelete()
642 /********** wxDbTable::execUpdate() **********/
643 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
647 // Execute the UPDATE statement
648 retcode
= SQLExecDirect(hstmtUpdate
, WXSQLCAST(pSqlStmt
), SQL_NTS
);
650 if (retcode
== SQL_SUCCESS
||
651 retcode
== SQL_NO_DATA_FOUND
||
652 retcode
== SQL_SUCCESS_WITH_INFO
)
654 // Record updated successfully
657 else if (retcode
== SQL_NEED_DATA
)
660 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
661 while (retcode
== SQL_NEED_DATA
)
663 // Find the parameter
665 for (i
=0; i
< m_numCols
; i
++)
667 if (colDefs
[i
].PtrDataObj
== pParmID
)
669 // We found it. Store the parameter.
670 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
671 if (retcode
!= SQL_SUCCESS
)
673 pDb
->DispNextError();
674 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
679 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
681 if (retcode
== SQL_SUCCESS
||
682 retcode
== SQL_NO_DATA_FOUND
||
683 retcode
== SQL_SUCCESS_WITH_INFO
)
685 // Record updated successfully
690 // Problem updating record
691 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
693 } // wxDbTable::execUpdate()
696 /********** wxDbTable::query() **********/
697 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
702 // The user may wish to select for update, but the DBMS may not be capable
703 selectForUpdate
= CanSelectForUpdate();
705 selectForUpdate
= false;
707 // Set the SQL SELECT string
708 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
709 { // so generate a select statement.
710 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
711 pDb
->WriteSqlLog(sqlStmt
);
714 // Make sure the cursor is closed first
715 if (!CloseCursor(hstmt
))
718 // Execute the SQL SELECT statement
720 retcode
= SQLExecDirect(hstmt
, (queryType
== DB_SELECT_STATEMENT
? WXSQLCAST(pSqlStmt
) : WXSQLCAST(sqlStmt
)), SQL_NTS
);
721 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
722 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
724 // Completed successfully
727 } // wxDbTable::query()
730 /***************************** PUBLIC FUNCTIONS *****************************/
733 /********** wxDbTable::Open() **********/
734 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
743 // Calculate the maximum size of the concatenated
744 // keys for use with wxDbGrid
746 for (i
=0; i
< m_numCols
; i
++)
748 if (colDefs
[i
].KeyField
)
750 m_keysize
+= colDefs
[i
].SzDataObj
;
757 if (checkTableExists
)
759 if (pDb
->Dbms() == dbmsPOSTGRES
)
760 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
762 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
765 // Verify that the table exists in the database
768 s
= wxT("Table/view does not exist in the database");
769 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
770 s
+= wxT(", or you have no permissions.\n");
774 else if (checkPrivileges
)
776 // Verify the user has rights to access the table.
777 bool hasPrivs
wxDUMMY_INITIALIZE(true);
779 if (pDb
->Dbms() == dbmsPOSTGRES
)
780 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
782 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
785 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
792 if (!tablePath
.empty())
793 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
795 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
798 pDb
->LogError(p
.GetData());
803 // Bind the member variables for field exchange between
804 // the wxDbTable object and the ODBC record.
807 if (!bindInsertParams()) // Inserts
810 if (!bindUpdateParams()) // Updates
814 if (!bindCols(*hstmtDefault
)) // Selects
817 if (!bindCols(hstmtInternal
)) // Internal use only
821 * Do NOT bind the hstmtCount cursor!!!
824 // Build an insert statement using parameter markers
825 if (!queryOnly
&& m_numCols
> 0)
827 bool needComma
= false;
828 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
829 pDb
->SQLTableName(tableName
.c_str()).c_str());
830 for (i
= 0; i
< m_numCols
; i
++)
832 if (! colDefs
[i
].InsertAllowed
)
836 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
840 sqlStmt
+= wxT(") VALUES (");
842 int insertableCount
= 0;
844 for (i
= 0; i
< m_numCols
; i
++)
846 if (! colDefs
[i
].InsertAllowed
)
856 // Prepare the insert statement for execution
859 if (SQLPrepare(hstmtInsert
, WXSQLCAST(sqlStmt
), SQL_NTS
) != SQL_SUCCESS
)
860 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
866 // Completed successfully
869 } // wxDbTable::Open()
872 /********** wxDbTable::Query() **********/
873 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
876 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
878 } // wxDbTable::Query()
881 /********** wxDbTable::QueryBySqlStmt() **********/
882 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
884 pDb
->WriteSqlLog(pSqlStmt
);
886 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
888 } // wxDbTable::QueryBySqlStmt()
891 /********** wxDbTable::QueryMatching() **********/
892 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
895 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
897 } // wxDbTable::QueryMatching()
900 /********** wxDbTable::QueryOnKeyFields() **********/
901 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
904 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
906 } // wxDbTable::QueryOnKeyFields()
909 /********** wxDbTable::GetPrev() **********/
910 bool wxDbTable::GetPrev(void)
912 if (pDb
->FwdOnlyCursors())
914 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
918 return(getRec(SQL_FETCH_PRIOR
));
920 } // wxDbTable::GetPrev()
923 /********** wxDbTable::operator-- **********/
924 bool wxDbTable::operator--(int)
926 if (pDb
->FwdOnlyCursors())
928 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
932 return(getRec(SQL_FETCH_PRIOR
));
934 } // wxDbTable::operator--
937 /********** wxDbTable::GetFirst() **********/
938 bool wxDbTable::GetFirst(void)
940 if (pDb
->FwdOnlyCursors())
942 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
946 return(getRec(SQL_FETCH_FIRST
));
948 } // wxDbTable::GetFirst()
951 /********** wxDbTable::GetLast() **********/
952 bool wxDbTable::GetLast(void)
954 if (pDb
->FwdOnlyCursors())
956 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
960 return(getRec(SQL_FETCH_LAST
));
962 } // wxDbTable::GetLast()
965 /********** wxDbTable::BuildDeleteStmt() **********/
966 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
968 wxASSERT(!queryOnly
);
972 wxString whereClause
;
976 // Handle the case of DeleteWhere() and the where clause is blank. It should
977 // delete all records from the database in this case.
978 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.length() == 0))
980 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
981 pDb
->SQLTableName(tableName
.c_str()).c_str());
985 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
986 pDb
->SQLTableName(tableName
.c_str()).c_str());
988 // Append the WHERE clause to the SQL DELETE statement
991 case DB_DEL_KEYFIELDS
:
992 // If the datasource supports the ROWID column, build
993 // the where on ROWID for efficiency purposes.
994 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
995 if (CanUpdateByROWID())
998 wxChar rowid
[wxDB_ROWID_LEN
+1];
1000 // Get the ROWID value. If not successful retreiving the ROWID,
1001 // simply fall down through the code and build the WHERE clause
1002 // based on the key fields.
1003 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1005 pSqlStmt
+= wxT("ROWID = '");
1007 pSqlStmt
+= wxT("'");
1011 // Unable to delete by ROWID, so build a WHERE
1012 // clause based on the keyfields.
1013 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1014 pSqlStmt
+= whereClause
;
1017 pSqlStmt
+= pWhereClause
;
1019 case DB_DEL_MATCHING
:
1020 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1021 pSqlStmt
+= whereClause
;
1025 } // BuildDeleteStmt()
1028 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1029 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1031 wxString tempSqlStmt
;
1032 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1033 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1034 } // wxDbTable::BuildDeleteStmt()
1037 /********** wxDbTable::BuildSelectStmt() **********/
1038 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1040 wxString whereClause
;
1041 whereClause
.Empty();
1043 // Build a select statement to query the database
1044 pSqlStmt
= wxT("SELECT ");
1046 // SELECT DISTINCT values only?
1048 pSqlStmt
+= wxT("DISTINCT ");
1050 // Was a FROM clause specified to join tables to the base table?
1051 // Available for ::Query() only!!!
1052 bool appendFromClause
= false;
1053 #if wxODBC_BACKWARD_COMPATABILITY
1054 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1055 appendFromClause
= true;
1057 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.length())
1058 appendFromClause
= true;
1061 // Add the column list
1064 for (i
= 0; i
< m_numCols
; i
++)
1066 tStr
= colDefs
[i
].ColName
;
1067 // If joining tables, the base table column names must be qualified to avoid ambiguity
1068 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1070 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1071 pSqlStmt
+= wxT(".");
1073 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1074 if (i
+ 1 < m_numCols
)
1075 pSqlStmt
+= wxT(",");
1078 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1079 // the ROWID if querying distinct records. The rowid will always be unique.
1080 if (!distinct
&& CanUpdateByROWID())
1082 // If joining tables, the base table column names must be qualified to avoid ambiguity
1083 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1085 pSqlStmt
+= wxT(",");
1086 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1087 pSqlStmt
+= wxT(".ROWID");
1090 pSqlStmt
+= wxT(",ROWID");
1093 // Append the FROM tablename portion
1094 pSqlStmt
+= wxT(" FROM ");
1095 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1096 // pSqlStmt += queryTableName;
1098 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1099 // The HOLDLOCK keyword follows the table name in the from clause.
1100 // Each table in the from clause must specify HOLDLOCK or
1101 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1102 // is parsed but ignored in SYBASE Transact-SQL.
1103 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1104 pSqlStmt
+= wxT(" HOLDLOCK");
1106 if (appendFromClause
)
1109 // Append the WHERE clause. Either append the where clause for the class
1110 // or build a where clause. The typeOfSelect determines this.
1111 switch(typeOfSelect
)
1113 case DB_SELECT_WHERE
:
1114 #if wxODBC_BACKWARD_COMPATABILITY
1115 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1117 if (where
.length()) // May not want a where clause!!!
1120 pSqlStmt
+= wxT(" WHERE ");
1124 case DB_SELECT_KEYFIELDS
:
1125 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1126 if (whereClause
.length())
1128 pSqlStmt
+= wxT(" WHERE ");
1129 pSqlStmt
+= whereClause
;
1132 case DB_SELECT_MATCHING
:
1133 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1134 if (whereClause
.length())
1136 pSqlStmt
+= wxT(" WHERE ");
1137 pSqlStmt
+= whereClause
;
1142 // Append the ORDER BY clause
1143 #if wxODBC_BACKWARD_COMPATABILITY
1144 if (orderBy
&& wxStrlen(orderBy
))
1146 if (orderBy
.length())
1149 pSqlStmt
+= wxT(" ORDER BY ");
1150 pSqlStmt
+= orderBy
;
1153 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1154 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1155 // HOLDLOCK for Sybase.
1156 if (selectForUpdate
&& CanSelectForUpdate())
1157 pSqlStmt
+= wxT(" FOR UPDATE");
1159 } // wxDbTable::BuildSelectStmt()
1162 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1163 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1165 wxString tempSqlStmt
;
1166 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1167 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1168 } // wxDbTable::BuildSelectStmt()
1171 /********** wxDbTable::BuildUpdateStmt() **********/
1172 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1174 wxASSERT(!queryOnly
);
1178 wxString whereClause
;
1179 whereClause
.Empty();
1181 bool firstColumn
= true;
1183 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1184 pDb
->SQLTableName(tableName
.c_str()).c_str());
1186 // Append a list of columns to be updated
1188 for (i
= 0; i
< m_numCols
; i
++)
1190 // Only append Updateable columns
1191 if (colDefs
[i
].Updateable
)
1194 pSqlStmt
+= wxT(",");
1196 firstColumn
= false;
1198 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1199 // pSqlStmt += colDefs[i].ColName;
1200 pSqlStmt
+= wxT(" = ?");
1204 // Append the WHERE clause to the SQL UPDATE statement
1205 pSqlStmt
+= wxT(" WHERE ");
1206 switch(typeOfUpdate
)
1208 case DB_UPD_KEYFIELDS
:
1209 // If the datasource supports the ROWID column, build
1210 // the where on ROWID for efficiency purposes.
1211 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1212 if (CanUpdateByROWID())
1215 wxChar rowid
[wxDB_ROWID_LEN
+1];
1217 // Get the ROWID value. If not successful retreiving the ROWID,
1218 // simply fall down through the code and build the WHERE clause
1219 // based on the key fields.
1220 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1222 pSqlStmt
+= wxT("ROWID = '");
1224 pSqlStmt
+= wxT("'");
1228 // Unable to delete by ROWID, so build a WHERE
1229 // clause based on the keyfields.
1230 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1231 pSqlStmt
+= whereClause
;
1234 pSqlStmt
+= pWhereClause
;
1237 } // BuildUpdateStmt()
1240 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1241 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1243 wxString tempSqlStmt
;
1244 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1245 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1246 } // BuildUpdateStmt()
1249 /********** wxDbTable::BuildWhereClause() **********/
1250 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1251 const wxString
&qualTableName
, bool useLikeComparison
)
1253 * Note: BuildWhereClause() currently ignores timestamp columns.
1254 * They are not included as part of the where clause.
1257 bool moreThanOneColumn
= false;
1260 // Loop through the columns building a where clause as you go
1262 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1264 // Determine if this column should be included in the WHERE clause
1265 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1266 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1268 // Skip over timestamp columns
1269 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1271 // If there is more than 1 column, join them with the keyword "AND"
1272 if (moreThanOneColumn
)
1273 pWhereClause
+= wxT(" AND ");
1275 moreThanOneColumn
= true;
1277 // Concatenate where phrase for the column
1278 wxString tStr
= colDefs
[colNumber
].ColName
;
1280 if (qualTableName
.length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1282 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1283 pWhereClause
+= wxT(".");
1285 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1287 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1288 pWhereClause
+= wxT(" LIKE ");
1290 pWhereClause
+= wxT(" = ");
1292 switch(colDefs
[colNumber
].SqlCtype
)
1298 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1299 colValue
.Printf(wxT("'%s'"), GetDb()->EscapeSqlChars((wxChar
*)colDefs
[colNumber
].PtrDataObj
).c_str());
1303 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1306 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1310 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1313 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1316 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1319 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1324 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1325 colNumber
,colDefs
[colNumber
].ColName
);
1326 wxFAIL_MSG(strMsg
.c_str());
1330 pWhereClause
+= colValue
;
1333 } // wxDbTable::BuildWhereClause()
1336 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1337 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1338 const wxString
&qualTableName
, bool useLikeComparison
)
1340 wxString tempSqlStmt
;
1341 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1342 wxStrcpy(pWhereClause
, tempSqlStmt
);
1343 } // wxDbTable::BuildWhereClause()
1346 /********** wxDbTable::GetRowNum() **********/
1347 UWORD
wxDbTable::GetRowNum(void)
1351 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1353 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1357 // Completed successfully
1358 return((UWORD
) rowNum
);
1360 } // wxDbTable::GetRowNum()
1363 /********** wxDbTable::CloseCursor() **********/
1364 bool wxDbTable::CloseCursor(HSTMT cursor
)
1366 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1367 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1369 // Completed successfully
1372 } // wxDbTable::CloseCursor()
1375 /********** wxDbTable::CreateTable() **********/
1376 bool wxDbTable::CreateTable(bool attemptDrop
)
1384 #ifdef DBDEBUG_CONSOLE
1385 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1389 if (attemptDrop
&& !DropTable())
1393 #ifdef DBDEBUG_CONSOLE
1394 for (i
= 0; i
< m_numCols
; i
++)
1396 // Exclude derived columns since they are NOT part of the base table
1397 if (colDefs
[i
].DerivedCol
)
1399 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1400 switch(colDefs
[i
].DbDataType
)
1402 case DB_DATA_TYPE_VARCHAR
:
1403 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1405 case DB_DATA_TYPE_MEMO
:
1406 cout
<< pDb
->GetTypeInfMemo().TypeName
;
1408 case DB_DATA_TYPE_INTEGER
:
1409 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1411 case DB_DATA_TYPE_FLOAT
:
1412 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1414 case DB_DATA_TYPE_DATE
:
1415 cout
<< pDb
->GetTypeInfDate().TypeName
;
1417 case DB_DATA_TYPE_BLOB
:
1418 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1425 // Build a CREATE TABLE string from the colDefs structure.
1426 bool needComma
= false;
1428 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1429 pDb
->SQLTableName(tableName
.c_str()).c_str());
1431 for (i
= 0; i
< m_numCols
; i
++)
1433 // Exclude derived columns since they are NOT part of the base table
1434 if (colDefs
[i
].DerivedCol
)
1438 sqlStmt
+= wxT(",");
1440 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1441 // sqlStmt += colDefs[i].ColName;
1442 sqlStmt
+= wxT(" ");
1444 switch(colDefs
[i
].DbDataType
)
1446 case DB_DATA_TYPE_VARCHAR
:
1447 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1449 case DB_DATA_TYPE_MEMO
:
1450 sqlStmt
+= pDb
->GetTypeInfMemo().TypeName
;
1452 case DB_DATA_TYPE_INTEGER
:
1453 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1455 case DB_DATA_TYPE_FLOAT
:
1456 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1458 case DB_DATA_TYPE_DATE
:
1459 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1461 case DB_DATA_TYPE_BLOB
:
1462 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1465 // For varchars, append the size of the string
1466 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1467 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1468 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1471 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1475 if (pDb
->Dbms() == dbmsDB2
||
1476 pDb
->Dbms() == dbmsMY_SQL
||
1477 pDb
->Dbms() == dbmsSYBASE_ASE
||
1478 pDb
->Dbms() == dbmsINTERBASE
||
1479 pDb
->Dbms() == dbmsFIREBIRD
||
1480 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1482 if (colDefs
[i
].KeyField
)
1484 sqlStmt
+= wxT(" NOT NULL");
1490 // If there is a primary key defined, include it in the create statement
1491 for (i
= j
= 0; i
< m_numCols
; i
++)
1493 if (colDefs
[i
].KeyField
)
1499 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1500 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1502 switch (pDb
->Dbms())
1506 case dbmsSYBASE_ASA
:
1507 case dbmsSYBASE_ASE
:
1511 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1512 sqlStmt
+= wxT(",PRIMARY KEY (");
1517 sqlStmt
+= wxT(",CONSTRAINT ");
1518 // DB2 is limited to 18 characters for index names
1519 if (pDb
->Dbms() == dbmsDB2
)
1521 wxASSERT_MSG(!tableName
.empty() && tableName
.length() <= 13, wxT("DB2 table/index names must be no longer than 13 characters in length.\n\nTruncating table name to 13 characters."));
1522 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1523 // sqlStmt += tableName.substr(0, 13);
1526 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1527 // sqlStmt += tableName;
1529 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1534 // List column name(s) of column(s) comprising the primary key
1535 for (i
= j
= 0; i
< m_numCols
; i
++)
1537 if (colDefs
[i
].KeyField
)
1539 if (j
++) // Multi part key, comma separate names
1540 sqlStmt
+= wxT(",");
1541 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1543 if (pDb
->Dbms() == dbmsMY_SQL
&&
1544 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1547 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1552 sqlStmt
+= wxT(")");
1554 if (pDb
->Dbms() == dbmsINFORMIX
||
1555 pDb
->Dbms() == dbmsSYBASE_ASA
||
1556 pDb
->Dbms() == dbmsSYBASE_ASE
)
1558 sqlStmt
+= wxT(" CONSTRAINT ");
1559 sqlStmt
+= pDb
->SQLTableName(tableName
);
1560 // sqlStmt += tableName;
1561 sqlStmt
+= wxT("_PIDX");
1564 // Append the closing parentheses for the create table statement
1565 sqlStmt
+= wxT(")");
1567 pDb
->WriteSqlLog(sqlStmt
);
1569 #ifdef DBDEBUG_CONSOLE
1570 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1573 // Execute the CREATE TABLE statement
1574 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1575 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1577 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1578 pDb
->RollbackTrans();
1583 // Commit the transaction and close the cursor
1584 if (!pDb
->CommitTrans())
1586 if (!CloseCursor(hstmt
))
1589 // Database table created successfully
1592 } // wxDbTable::CreateTable()
1595 /********** wxDbTable::DropTable() **********/
1596 bool wxDbTable::DropTable()
1598 // NOTE: This function returns true if the Table does not exist, but
1599 // only for identified databases. Code will need to be added
1600 // below for any other databases when those databases are defined
1601 // to handle this situation consistently
1605 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1606 pDb
->SQLTableName(tableName
.c_str()).c_str());
1608 pDb
->WriteSqlLog(sqlStmt
);
1610 #ifdef DBDEBUG_CONSOLE
1611 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1614 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1615 if (retcode
!= SQL_SUCCESS
)
1617 // Check for "Base table not found" error and ignore
1618 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1619 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1620 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1622 // Check for product specific error codes
1623 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1624 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1625 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1626 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1628 pDb
->DispNextError();
1629 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1630 pDb
->RollbackTrans();
1631 // CloseCursor(hstmt);
1637 // Commit the transaction and close the cursor
1638 if (! pDb
->CommitTrans())
1640 if (! CloseCursor(hstmt
))
1644 } // wxDbTable::DropTable()
1647 /********** wxDbTable::CreateIndex() **********/
1648 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1649 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1653 // Drop the index first
1654 if (attemptDrop
&& !DropIndex(indexName
))
1657 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1658 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1659 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1660 // table was created, then months later you determine that an additional index while
1661 // give better performance, so you want to add an index).
1663 // The following block of code will modify the column definition to make the column be
1664 // defined with the "NOT NULL" qualifier.
1665 if (pDb
->Dbms() == dbmsMY_SQL
)
1670 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1674 // Find the column definition that has the ColName that matches the
1675 // index column name. We need to do this to get the DB_DATA_TYPE of
1676 // the index column, as MySQL's syntax for the ALTER column requires
1678 while (!found
&& (j
< this->m_numCols
))
1680 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1688 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1689 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1695 // retcode is not used
1696 wxODBC_ERRORS retcode
;
1697 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1698 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1699 // This line is just here for debug checking of the value
1700 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1711 pDb
->RollbackTrans();
1716 // Build a CREATE INDEX statement
1717 sqlStmt
= wxT("CREATE ");
1719 sqlStmt
+= wxT("UNIQUE ");
1721 sqlStmt
+= wxT("INDEX ");
1722 sqlStmt
+= pDb
->SQLTableName(indexName
);
1723 sqlStmt
+= wxT(" ON ");
1725 sqlStmt
+= pDb
->SQLTableName(tableName
);
1726 // sqlStmt += tableName;
1727 sqlStmt
+= wxT(" (");
1729 // Append list of columns making up index
1731 for (i
= 0; i
< numIndexColumns
; i
++)
1733 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1734 // sqlStmt += pIndexDefs[i].ColName;
1736 // MySQL requires a key length on VARCHAR keys
1737 if ( pDb
->Dbms() == dbmsMY_SQL
)
1739 // Find the details on this column
1741 for ( j
= 0; j
< m_numCols
; ++j
)
1743 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1748 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1751 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1756 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1757 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1758 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1759 !(pDb
->Dbms() == dbmsPOSTGRES
))
1761 if (pIndexDefs
[i
].Ascending
)
1762 sqlStmt
+= wxT(" ASC");
1764 sqlStmt
+= wxT(" DESC");
1767 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1769 if ((i
+ 1) < numIndexColumns
)
1770 sqlStmt
+= wxT(",");
1773 // Append closing parentheses
1774 sqlStmt
+= wxT(")");
1776 pDb
->WriteSqlLog(sqlStmt
);
1778 #ifdef DBDEBUG_CONSOLE
1779 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1782 // Execute the CREATE INDEX statement
1783 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1784 if (retcode
!= SQL_SUCCESS
)
1786 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1787 pDb
->RollbackTrans();
1792 // Commit the transaction and close the cursor
1793 if (! pDb
->CommitTrans())
1795 if (! CloseCursor(hstmt
))
1798 // Index Created Successfully
1801 } // wxDbTable::CreateIndex()
1804 /********** wxDbTable::DropIndex() **********/
1805 bool wxDbTable::DropIndex(const wxString
&indexName
)
1807 // NOTE: This function returns true if the Index does not exist, but
1808 // only for identified databases. Code will need to be added
1809 // below for any other databases when those databases are defined
1810 // to handle this situation consistently
1814 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1815 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1816 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1817 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1818 pDb
->SQLTableName(tableName
.c_str()).c_str());
1819 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1820 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1821 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1822 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1823 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1824 pDb
->SQLTableName(indexName
.c_str()).c_str());
1826 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1827 pDb
->SQLTableName(indexName
.c_str()).c_str());
1829 pDb
->WriteSqlLog(sqlStmt
);
1831 #ifdef DBDEBUG_CONSOLE
1832 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1834 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1835 if (retcode
!= SQL_SUCCESS
)
1837 // Check for "Index not found" error and ignore
1838 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1839 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1841 // Check for product specific error codes
1842 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1843 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1844 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1845 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1846 (pDb
->Dbms() == dbmsMAXDB
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1847 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1848 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1849 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1850 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1853 pDb
->DispNextError();
1854 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1855 pDb
->RollbackTrans();
1862 // Commit the transaction and close the cursor
1863 if (! pDb
->CommitTrans())
1865 if (! CloseCursor(hstmt
))
1869 } // wxDbTable::DropIndex()
1872 /********** wxDbTable::SetOrderByColNums() **********/
1873 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1875 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1881 va_start(argptr
, first
); /* Initialize variable arguments. */
1882 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1884 // Make sure the passed in column number
1885 // is within the valid range of columns
1887 // Valid columns are 0 thru m_numCols-1
1888 if (colNumber
>= m_numCols
|| colNumber
< 0)
1894 if (colNumber
!= first
)
1895 tempStr
+= wxT(",");
1897 tempStr
+= colDefs
[colNumber
].ColName
;
1898 colNumber
= va_arg (argptr
, int);
1900 va_end (argptr
); /* Reset variable arguments. */
1902 SetOrderByClause(tempStr
);
1905 } // wxDbTable::SetOrderByColNums()
1908 /********** wxDbTable::Insert() **********/
1909 int wxDbTable::Insert(void)
1911 wxASSERT(!queryOnly
);
1912 if (queryOnly
|| !insertable
)
1917 // Insert the record by executing the already prepared insert statement
1919 retcode
= SQLExecute(hstmtInsert
);
1920 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1921 retcode
!= SQL_NEED_DATA
)
1923 // Check to see if integrity constraint was violated
1924 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1925 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1926 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1929 pDb
->DispNextError();
1930 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1934 if (retcode
== SQL_NEED_DATA
)
1937 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1938 while (retcode
== SQL_NEED_DATA
)
1940 // Find the parameter
1942 for (i
=0; i
< m_numCols
; i
++)
1944 if (colDefs
[i
].PtrDataObj
== pParmID
)
1946 // We found it. Store the parameter.
1947 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1948 if (retcode
!= SQL_SUCCESS
)
1950 pDb
->DispNextError();
1951 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1957 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1958 if (retcode
!= SQL_SUCCESS
&&
1959 retcode
!= SQL_SUCCESS_WITH_INFO
)
1961 // record was not inserted
1962 pDb
->DispNextError();
1963 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1969 // Record inserted into the datasource successfully
1972 } // wxDbTable::Insert()
1975 /********** wxDbTable::Update() **********/
1976 bool wxDbTable::Update(void)
1978 wxASSERT(!queryOnly
);
1984 // Build the SQL UPDATE statement
1985 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1987 pDb
->WriteSqlLog(sqlStmt
);
1989 #ifdef DBDEBUG_CONSOLE
1990 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1993 // Execute the SQL UPDATE statement
1994 return(execUpdate(sqlStmt
));
1996 } // wxDbTable::Update()
1999 /********** wxDbTable::Update(pSqlStmt) **********/
2000 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2002 wxASSERT(!queryOnly
);
2006 pDb
->WriteSqlLog(pSqlStmt
);
2008 return(execUpdate(pSqlStmt
));
2010 } // wxDbTable::Update(pSqlStmt)
2013 /********** wxDbTable::UpdateWhere() **********/
2014 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2016 wxASSERT(!queryOnly
);
2022 // Build the SQL UPDATE statement
2023 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2025 pDb
->WriteSqlLog(sqlStmt
);
2027 #ifdef DBDEBUG_CONSOLE
2028 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2031 // Execute the SQL UPDATE statement
2032 return(execUpdate(sqlStmt
));
2034 } // wxDbTable::UpdateWhere()
2037 /********** wxDbTable::Delete() **********/
2038 bool wxDbTable::Delete(void)
2040 wxASSERT(!queryOnly
);
2047 // Build the SQL DELETE statement
2048 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2050 pDb
->WriteSqlLog(sqlStmt
);
2052 // Execute the SQL DELETE statement
2053 return(execDelete(sqlStmt
));
2055 } // wxDbTable::Delete()
2058 /********** wxDbTable::DeleteWhere() **********/
2059 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2061 wxASSERT(!queryOnly
);
2068 // Build the SQL DELETE statement
2069 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2071 pDb
->WriteSqlLog(sqlStmt
);
2073 // Execute the SQL DELETE statement
2074 return(execDelete(sqlStmt
));
2076 } // wxDbTable::DeleteWhere()
2079 /********** wxDbTable::DeleteMatching() **********/
2080 bool wxDbTable::DeleteMatching(void)
2082 wxASSERT(!queryOnly
);
2089 // Build the SQL DELETE statement
2090 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2092 pDb
->WriteSqlLog(sqlStmt
);
2094 // Execute the SQL DELETE statement
2095 return(execDelete(sqlStmt
));
2097 } // wxDbTable::DeleteMatching()
2100 /********** wxDbTable::IsColNull() **********/
2101 bool wxDbTable::IsColNull(UWORD colNumber
) const
2104 This logic is just not right. It would indicate true
2105 if a numeric field were set to a value of 0.
2107 switch(colDefs[colNumber].SqlCtype)
2111 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2112 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2114 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2116 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2118 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2120 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2122 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2124 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2125 case SQL_C_TIMESTAMP:
2126 TIMESTAMP_STRUCT *pDt;
2127 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2128 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2136 return (colDefs
[colNumber
].Null
);
2137 } // wxDbTable::IsColNull()
2140 /********** wxDbTable::CanSelectForUpdate() **********/
2141 bool wxDbTable::CanSelectForUpdate(void)
2146 if (pDb
->Dbms() == dbmsMY_SQL
)
2149 if ((pDb
->Dbms() == dbmsORACLE
) ||
2150 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2155 } // wxDbTable::CanSelectForUpdate()
2158 /********** wxDbTable::CanUpdateByROWID() **********/
2159 bool wxDbTable::CanUpdateByROWID(void)
2162 * NOTE: Returning false for now until this can be debugged,
2163 * as the ROWID is not getting updated correctly
2167 if (pDb->Dbms() == dbmsORACLE)
2172 } // wxDbTable::CanUpdateByROWID()
2175 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2176 bool wxDbTable::IsCursorClosedOnCommit(void)
2178 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2183 } // wxDbTable::IsCursorClosedOnCommit()
2187 /********** wxDbTable::ClearMemberVar() **********/
2188 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2190 wxASSERT(colNumber
< m_numCols
);
2192 switch(colDefs
[colNumber
].SqlCtype
)
2198 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2199 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2202 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2205 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2209 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2212 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2215 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2218 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2220 case SQL_C_TIMESTAMP
:
2221 TIMESTAMP_STRUCT
*pDt
;
2222 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2233 pDtd
= (DATE_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2240 pDtt
= (TIME_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2248 SetColNull(colNumber
);
2249 } // wxDbTable::ClearMemberVar()
2252 /********** wxDbTable::ClearMemberVars() **********/
2253 void wxDbTable::ClearMemberVars(bool setToNull
)
2257 // Loop through the columns setting each member variable to zero
2258 for (i
=0; i
< m_numCols
; i
++)
2259 ClearMemberVar((UWORD
)i
,setToNull
);
2261 } // wxDbTable::ClearMemberVars()
2264 /********** wxDbTable::SetQueryTimeout() **********/
2265 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2267 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2268 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2269 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2270 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2271 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2272 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2273 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2274 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2276 // Completed Successfully
2279 } // wxDbTable::SetQueryTimeout()
2282 /********** wxDbTable::SetColDefs() **********/
2283 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2284 SWORD cType
, int size
, bool keyField
, bool updateable
,
2285 bool insertAllowed
, bool derivedColumn
)
2289 if (index
>= m_numCols
) // Columns numbers are zero based....
2291 tmpStr
.Printf(wxT("Specified column index (%d) exceeds the maximum number of columns (%d) registered for this table definition. Column definition not added."), index
, m_numCols
);
2297 if (!colDefs
) // May happen if the database connection fails
2300 if (fieldName
.length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2302 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2303 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2305 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2306 fieldName
.c_str(),colDefs
[index
].ColName
);
2311 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2313 colDefs
[index
].DbDataType
= dataType
;
2314 colDefs
[index
].PtrDataObj
= pData
;
2315 colDefs
[index
].SqlCtype
= cType
;
2316 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2317 colDefs
[index
].KeyField
= keyField
;
2318 colDefs
[index
].DerivedCol
= derivedColumn
;
2319 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2322 colDefs
[index
].Updateable
= false;
2323 colDefs
[index
].InsertAllowed
= false;
2327 colDefs
[index
].Updateable
= updateable
;
2328 colDefs
[index
].InsertAllowed
= insertAllowed
;
2331 colDefs
[index
].Null
= false;
2335 } // wxDbTable::SetColDefs()
2338 /********** wxDbTable::SetColDefs() **********/
2339 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2342 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2348 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2350 for (index
= 0; index
< numCols
; index
++)
2352 // Process the fields
2353 switch (pColInfs
[index
].dbDataType
)
2355 case DB_DATA_TYPE_VARCHAR
:
2356 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2357 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2358 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2360 case DB_DATA_TYPE_MEMO
:
2361 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2362 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2363 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2365 case DB_DATA_TYPE_INTEGER
:
2366 // Can be long or short
2367 if (pColInfs
[index
].bufferSize
== sizeof(long))
2369 pColDataPtrs
[index
].PtrDataObj
= new long;
2370 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2371 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2375 pColDataPtrs
[index
].PtrDataObj
= new short;
2376 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2377 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2380 case DB_DATA_TYPE_FLOAT
:
2381 // Can be float or double
2382 if (pColInfs
[index
].bufferSize
== sizeof(float))
2384 pColDataPtrs
[index
].PtrDataObj
= new float;
2385 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2386 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2390 pColDataPtrs
[index
].PtrDataObj
= new double;
2391 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2392 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2395 case DB_DATA_TYPE_DATE
:
2396 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2397 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2398 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2400 case DB_DATA_TYPE_BLOB
:
2401 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2402 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2403 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2404 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2407 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2408 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2411 // Unable to build all the column definitions, as either one of
2412 // the calls to "new" failed above, or there was a BLOB field
2413 // to have a column definition for. If BLOBs are to be used,
2414 // the other form of ::SetColDefs() must be used, as it is impossible
2415 // to know the maximum size to create the PtrDataObj to be.
2416 delete [] pColDataPtrs
;
2422 return (pColDataPtrs
);
2424 } // wxDbTable::SetColDefs()
2427 /********** wxDbTable::SetCursor() **********/
2428 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2430 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2431 hstmt
= *hstmtDefault
;
2433 hstmt
= *hstmtActivate
;
2435 } // wxDbTable::SetCursor()
2438 /********** wxDbTable::Count(const wxString &) **********/
2439 ULONG
wxDbTable::Count(const wxString
&args
)
2445 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2446 sqlStmt
= wxT("SELECT COUNT(");
2448 sqlStmt
+= wxT(") FROM ");
2449 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2450 // sqlStmt += queryTableName;
2451 #if wxODBC_BACKWARD_COMPATABILITY
2452 if (from
&& wxStrlen(from
))
2458 // Add the where clause if one is provided
2459 #if wxODBC_BACKWARD_COMPATABILITY
2460 if (where
&& wxStrlen(where
))
2465 sqlStmt
+= wxT(" WHERE ");
2469 pDb
->WriteSqlLog(sqlStmt
);
2471 // Initialize the Count cursor if it's not already initialized
2474 hstmtCount
= GetNewCursor(false,false);
2475 wxASSERT(hstmtCount
);
2480 // Execute the SQL statement
2481 if (SQLExecDirect(*hstmtCount
, WXSQLCAST(sqlStmt
), SQL_NTS
) != SQL_SUCCESS
)
2483 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2488 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2490 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2494 // Obtain the result
2495 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2497 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2502 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2503 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2505 // Return the record count
2508 } // wxDbTable::Count()
2511 /********** wxDbTable::Refresh() **********/
2512 bool wxDbTable::Refresh(void)
2516 // Switch to the internal cursor so any active cursors are not corrupted
2517 HSTMT currCursor
= GetCursor();
2518 hstmt
= hstmtInternal
;
2519 #if wxODBC_BACKWARD_COMPATABILITY
2520 // Save the where and order by clauses
2521 wxChar
*saveWhere
= where
;
2522 wxChar
*saveOrderBy
= orderBy
;
2524 wxString saveWhere
= where
;
2525 wxString saveOrderBy
= orderBy
;
2527 // Build a where clause to refetch the record with. Try and use the
2528 // ROWID if it's available, ow use the key fields.
2529 wxString whereClause
;
2530 whereClause
.Empty();
2532 if (CanUpdateByROWID())
2535 wxChar rowid
[wxDB_ROWID_LEN
+1];
2537 // Get the ROWID value. If not successful retreiving the ROWID,
2538 // simply fall down through the code and build the WHERE clause
2539 // based on the key fields.
2540 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2542 whereClause
+= pDb
->SQLTableName(queryTableName
);
2543 // whereClause += queryTableName;
2544 whereClause
+= wxT(".ROWID = '");
2545 whereClause
+= rowid
;
2546 whereClause
+= wxT("'");
2550 // If unable to use the ROWID, build a where clause from the keyfields
2551 if (wxStrlen(whereClause
) == 0)
2552 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2554 // Requery the record
2555 where
= whereClause
;
2560 if (result
&& !GetNext())
2563 // Switch back to original cursor
2564 SetCursor(&currCursor
);
2566 // Free the internal cursor
2567 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2568 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2570 // Restore the original where and order by clauses
2572 orderBy
= saveOrderBy
;
2576 } // wxDbTable::Refresh()
2579 /********** wxDbTable::SetColNull() **********/
2580 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2582 if (colNumber
< m_numCols
)
2584 colDefs
[colNumber
].Null
= set
;
2585 if (set
) // Blank out the values in the member variable
2586 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2588 setCbValueForColumn(colNumber
);
2595 } // wxDbTable::SetColNull()
2598 /********** wxDbTable::SetColNull() **********/
2599 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2602 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2604 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2608 if (colNumber
< m_numCols
)
2610 colDefs
[colNumber
].Null
= set
;
2611 if (set
) // Blank out the values in the member variable
2612 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2614 setCbValueForColumn(colNumber
);
2621 } // wxDbTable::SetColNull()
2624 /********** wxDbTable::GetNewCursor() **********/
2625 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2627 HSTMT
*newHSTMT
= new HSTMT
;
2632 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2634 pDb
->DispAllErrors(henv
, hdbc
);
2639 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2641 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2648 if (!bindCols(*newHSTMT
))
2656 SetCursor(newHSTMT
);
2660 } // wxDbTable::GetNewCursor()
2663 /********** wxDbTable::DeleteCursor() **********/
2664 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2668 if (!hstmtDel
) // Cursor already deleted
2672 ODBC 3.0 says to use this form
2673 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2676 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2678 pDb
->DispAllErrors(henv
, hdbc
);
2686 } // wxDbTable::DeleteCursor()
2688 //////////////////////////////////////////////////////////////
2689 // wxDbGrid support functions
2690 //////////////////////////////////////////////////////////////
2692 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2694 if (!m_hstmtGridQuery
)
2696 m_hstmtGridQuery
= GetNewCursor(false,false);
2697 if (!bindCols(*m_hstmtGridQuery
))
2701 m_rowmode
= rowmode
;
2704 case WX_ROW_MODE_QUERY
:
2705 SetCursor(m_hstmtGridQuery
);
2707 case WX_ROW_MODE_INDIVIDUAL
:
2708 SetCursor(hstmtDefault
);
2713 } // wxDbTable::SetRowMode()
2716 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2719 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2721 switch (colDefs
[colNumber
].SqlCtype
)
2724 #if defined(SQL_WCHAR)
2727 #if defined(SQL_WVARCHAR)
2733 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2737 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2741 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2744 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2747 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2749 case SQL_C_UTINYINT
:
2750 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2753 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2756 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2759 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2761 case SQL_C_TIMESTAMP
:
2762 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2765 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2772 } // wxDbTable::GetCol()
2775 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2777 //FIXME: Add proper wxDateTime support to wxVariant..
2780 SetColNull((UWORD
)colNumber
, val
.IsNull());
2784 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2785 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2786 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2788 //Returns null if invalid!
2789 if (!dateval
.ParseDate(val
.GetString()))
2790 SetColNull((UWORD
)colNumber
, true);
2793 switch (colDefs
[colNumber
].SqlCtype
)
2796 #if defined(SQL_WCHAR)
2799 #if defined(SQL_WVARCHAR)
2805 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2806 val
.GetString().c_str(),
2807 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2811 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2815 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2818 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2821 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2823 case SQL_C_UTINYINT
:
2824 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2827 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2829 //FIXME: Add proper wxDateTime support to wxVariant..
2832 DATE_STRUCT
*dataptr
=
2833 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2835 dataptr
->year
= (SWORD
)dateval
.GetYear();
2836 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2837 dataptr
->day
= (UWORD
)dateval
.GetDay();
2842 TIME_STRUCT
*dataptr
=
2843 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2845 dataptr
->hour
= dateval
.GetHour();
2846 dataptr
->minute
= dateval
.GetMinute();
2847 dataptr
->second
= dateval
.GetSecond();
2850 case SQL_C_TIMESTAMP
:
2852 TIMESTAMP_STRUCT
*dataptr
=
2853 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2854 dataptr
->year
= (SWORD
)dateval
.GetYear();
2855 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2856 dataptr
->day
= (UWORD
)dateval
.GetDay();
2858 dataptr
->hour
= dateval
.GetHour();
2859 dataptr
->minute
= dateval
.GetMinute();
2860 dataptr
->second
= dateval
.GetSecond();
2864 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2869 } // if (!val.IsNull())
2870 } // wxDbTable::SetCol()
2873 GenericKey
wxDbTable::GetKey()
2878 blk
= malloc(m_keysize
);
2879 blkptr
= (wxChar
*) blk
;
2882 for (i
=0; i
< m_numCols
; i
++)
2884 if (colDefs
[i
].KeyField
)
2886 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2887 blkptr
+= colDefs
[i
].SzDataObj
;
2891 GenericKey k
= GenericKey(blk
, m_keysize
);
2895 } // wxDbTable::GetKey()
2898 void wxDbTable::SetKey(const GenericKey
& k
)
2904 blkptr
= (wxChar
*)blk
;
2907 for (i
=0; i
< m_numCols
; i
++)
2909 if (colDefs
[i
].KeyField
)
2911 SetColNull((UWORD
)i
, false);
2912 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2913 blkptr
+= colDefs
[i
].SzDataObj
;
2916 } // wxDbTable::SetKey()
2919 #endif // wxUSE_ODBC