1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence
12 ///////////////////////////////////////////////////////////////////////////////
19 #include "wx/wxprec.h"
25 #ifdef DBDEBUG_CONSOLE
31 #include "wx/ioswrap.h"
35 #include "wx/string.h"
36 #include "wx/object.h"
41 #include "wx/filefn.h"
49 #include "wx/dbtable.h"
52 // The HPUX preprocessor lines below were commented out on 8/20/97
53 // because macros.h currently redefines DEBUG and is unneeded.
55 // # include <macros.h>
58 # include <sys/minmax.h>
62 ULONG lastTableID
= 0;
70 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
72 while ( (*target
++ = *source
++) != '\0' && --n
)
80 /********** wxDbColDef::wxDbColDef() Constructor **********/
81 wxDbColDef::wxDbColDef()
87 bool wxDbColDef::Initialize()
90 DbDataType
= DB_DATA_TYPE_INTEGER
;
91 SqlCtype
= SQL_C_LONG
;
96 InsertAllowed
= false;
102 } // wxDbColDef::Initialize()
105 /********** wxDbTable::wxDbTable() Constructor **********/
106 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
107 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
109 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
111 } // wxDbTable::wxDbTable()
114 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
115 #if WXWIN_COMPATIBILITY_2_4
116 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
117 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
119 wxString tempQryTblName
;
120 tempQryTblName
= qryTblName
;
121 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
123 } // wxDbTable::wxDbTable()
124 #endif // WXWIN_COMPATIBILITY_2_4
127 /********** wxDbTable::~wxDbTable() **********/
128 wxDbTable::~wxDbTable()
131 } // wxDbTable::~wxDbTable()
134 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
135 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
137 // Initializing member variables
138 pDb
= pwxDb
; // Pointer to the wxDb object
142 m_hstmtGridQuery
= 0;
143 hstmtDefault
= 0; // Initialized below
144 hstmtCount
= 0; // Initialized first time it is needed
151 m_numCols
= numColumns
; // Number of columns in the table
152 where
.Empty(); // Where clause
153 orderBy
.Empty(); // Order By clause
154 from
.Empty(); // From clause
155 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
160 queryTableName
.Empty();
162 wxASSERT(tblName
.Length());
168 tableName
= tblName
; // Table Name
169 if ((pDb
->Dbms() == dbmsORACLE
) ||
170 (pDb
->Dbms() == dbmsFIREBIRD
) ||
171 (pDb
->Dbms() == dbmsINTERBASE
))
172 tableName
= tableName
.Upper();
174 if (tblPath
.Length())
175 tablePath
= tblPath
; // Table Path - used for dBase files
179 if (qryTblName
.Length()) // Name of the table/view to query
180 queryTableName
= qryTblName
;
182 queryTableName
= tblName
;
184 if ((pDb
->Dbms() == dbmsORACLE
) ||
185 (pDb
->Dbms() == dbmsFIREBIRD
) ||
186 (pDb
->Dbms() == dbmsINTERBASE
))
187 queryTableName
= queryTableName
.Upper();
189 pDb
->incrementTableCount();
192 tableID
= ++lastTableID
;
193 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
196 wxTablesInUse
*tableInUse
;
197 tableInUse
= new wxTablesInUse();
198 tableInUse
->tableName
= tblName
;
199 tableInUse
->tableID
= tableID
;
200 tableInUse
->pDb
= pDb
;
201 TablesInUse
.Append(tableInUse
);
206 // Grab the HENV and HDBC from the wxDb object
207 henv
= pDb
->GetHENV();
208 hdbc
= pDb
->GetHDBC();
210 // Allocate space for column definitions
212 colDefs
= new wxDbColDef
[m_numCols
]; // Points to the first column definition
214 // Allocate statement handles for the table
217 // Allocate a separate statement handle for performing inserts
218 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
219 pDb
->DispAllErrors(henv
, hdbc
);
220 // Allocate a separate statement handle for performing deletes
221 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
222 pDb
->DispAllErrors(henv
, hdbc
);
223 // Allocate a separate statement handle for performing updates
224 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
225 pDb
->DispAllErrors(henv
, hdbc
);
227 // Allocate a separate statement handle for internal use
228 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
229 pDb
->DispAllErrors(henv
, hdbc
);
231 // Set the cursor type for the statement handles
232 cursorType
= SQL_CURSOR_STATIC
;
234 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
236 // Check to see if cursor type is supported
237 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
238 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
240 // Datasource does not support static cursors. Driver
241 // will substitute a cursor type. Call SQLGetStmtOption()
242 // to determine which cursor type was selected.
243 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
244 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
245 #ifdef DBDEBUG_CONSOLE
246 cout
<< wxT("Static cursor changed to: ");
249 case SQL_CURSOR_FORWARD_ONLY
:
250 cout
<< wxT("Forward Only");
252 case SQL_CURSOR_STATIC
:
253 cout
<< wxT("Static");
255 case SQL_CURSOR_KEYSET_DRIVEN
:
256 cout
<< wxT("Keyset Driven");
258 case SQL_CURSOR_DYNAMIC
:
259 cout
<< wxT("Dynamic");
262 cout
<< endl
<< endl
;
265 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
267 // Force the use of a forward only cursor...
268 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
269 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
271 // Should never happen
272 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
279 pDb
->DispNextError();
280 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
283 #ifdef DBDEBUG_CONSOLE
285 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
290 // Set the cursor type for the INSERT statement handle
291 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
292 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
293 // Set the cursor type for the DELETE statement handle
294 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
295 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
296 // Set the cursor type for the UPDATE statement handle
297 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
298 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
301 // Make the default cursor the active cursor
302 hstmtDefault
= GetNewCursor(false,false);
303 wxASSERT(hstmtDefault
);
304 hstmt
= *hstmtDefault
;
308 } // wxDbTable::initialize()
311 void wxDbTable::cleanup()
316 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
325 wxList::compatibility_iterator pNode
;
326 pNode
= TablesInUse
.GetFirst();
327 while (pNode
&& !found
)
329 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
332 delete (wxTablesInUse
*)pNode
->GetData();
333 TablesInUse
.Erase(pNode
);
336 pNode
= pNode
->GetNext();
341 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
342 wxLogDebug (msg
,wxT("NOTICE..."));
347 // Decrement the wxDb table count
349 pDb
->decrementTableCount();
351 // Delete memory allocated for column definitions
355 // Free statement handles
361 ODBC 3.0 says to use this form
362 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
364 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
365 pDb
->DispAllErrors(henv
, hdbc
);
371 ODBC 3.0 says to use this form
372 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
374 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
375 pDb
->DispAllErrors(henv
, hdbc
);
381 ODBC 3.0 says to use this form
382 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
384 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
385 pDb
->DispAllErrors(henv
, hdbc
);
391 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
392 pDb
->DispAllErrors(henv
, hdbc
);
395 // Delete dynamically allocated cursors
397 DeleteCursor(hstmtDefault
);
400 DeleteCursor(hstmtCount
);
402 if (m_hstmtGridQuery
)
403 DeleteCursor(m_hstmtGridQuery
);
405 } // wxDbTable::cleanup()
408 /***************************** PRIVATE FUNCTIONS *****************************/
411 void wxDbTable::setCbValueForColumn(int columnIndex
)
413 switch(colDefs
[columnIndex
].DbDataType
)
415 case DB_DATA_TYPE_VARCHAR
:
416 if (colDefs
[columnIndex
].Null
)
417 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
419 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
421 case DB_DATA_TYPE_INTEGER
:
422 if (colDefs
[columnIndex
].Null
)
423 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
425 colDefs
[columnIndex
].CbValue
= 0;
427 case DB_DATA_TYPE_FLOAT
:
428 if (colDefs
[columnIndex
].Null
)
429 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
431 colDefs
[columnIndex
].CbValue
= 0;
433 case DB_DATA_TYPE_DATE
:
434 if (colDefs
[columnIndex
].Null
)
435 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
437 colDefs
[columnIndex
].CbValue
= 0;
439 case DB_DATA_TYPE_BLOB
:
440 if (colDefs
[columnIndex
].Null
)
441 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
443 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
444 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
446 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
451 /********** wxDbTable::bindParams() **********/
452 bool wxDbTable::bindParams(bool forUpdate
)
454 wxASSERT(!queryOnly
);
459 SDWORD precision
= 0;
462 // Bind each column of the table that should be bound
463 // to a parameter marker
467 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
471 if (!colDefs
[i
].Updateable
)
476 if (!colDefs
[i
].InsertAllowed
)
480 switch(colDefs
[i
].DbDataType
)
482 case DB_DATA_TYPE_VARCHAR
:
483 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
484 precision
= colDefs
[i
].SzDataObj
;
487 case DB_DATA_TYPE_INTEGER
:
488 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
489 precision
= pDb
->GetTypeInfInteger().Precision
;
492 case DB_DATA_TYPE_FLOAT
:
493 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
494 precision
= pDb
->GetTypeInfFloat().Precision
;
495 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
496 // SQL Sybase Anywhere v5.5 returned a negative number for the
497 // MaxScale. This caused ODBC to kick out an error on ibscale.
498 // I check for this here and set the scale = precision.
500 // scale = (short) precision;
502 case DB_DATA_TYPE_DATE
:
503 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
504 precision
= pDb
->GetTypeInfDate().Precision
;
507 case DB_DATA_TYPE_BLOB
:
508 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
509 precision
= colDefs
[i
].SzDataObj
;
514 setCbValueForColumn(i
);
518 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
519 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
520 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
522 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
527 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
528 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
529 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
531 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
536 // Completed successfully
539 } // wxDbTable::bindParams()
542 /********** wxDbTable::bindInsertParams() **********/
543 bool wxDbTable::bindInsertParams(void)
545 return bindParams(false);
546 } // wxDbTable::bindInsertParams()
549 /********** wxDbTable::bindUpdateParams() **********/
550 bool wxDbTable::bindUpdateParams(void)
552 return bindParams(true);
553 } // wxDbTable::bindUpdateParams()
556 /********** wxDbTable::bindCols() **********/
557 bool wxDbTable::bindCols(HSTMT cursor
)
561 // Bind each column of the table to a memory address for fetching data
563 for (i
= 0; i
< m_numCols
; i
++)
565 cb
= colDefs
[i
].CbValue
;
566 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
567 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
568 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
571 // Completed successfully
574 } // wxDbTable::bindCols()
577 /********** wxDbTable::getRec() **********/
578 bool wxDbTable::getRec(UWORD fetchType
)
582 if (!pDb
->FwdOnlyCursors())
584 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
585 SQLULEN cRowsFetched
;
588 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
589 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
591 if (retcode
== SQL_NO_DATA_FOUND
)
594 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
598 // Set the Null member variable to indicate the Null state
599 // of each column just read in.
601 for (i
= 0; i
< m_numCols
; i
++)
602 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
607 // Fetch the next record from the record set
608 retcode
= SQLFetch(hstmt
);
609 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
611 if (retcode
== SQL_NO_DATA_FOUND
)
614 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
618 // Set the Null member variable to indicate the Null state
619 // of each column just read in.
621 for (i
= 0; i
< m_numCols
; i
++)
622 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
626 // Completed successfully
629 } // wxDbTable::getRec()
632 /********** wxDbTable::execDelete() **********/
633 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
637 // Execute the DELETE statement
638 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
640 if (retcode
== SQL_SUCCESS
||
641 retcode
== SQL_NO_DATA_FOUND
||
642 retcode
== SQL_SUCCESS_WITH_INFO
)
644 // Record deleted successfully
648 // Problem deleting record
649 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
651 } // wxDbTable::execDelete()
654 /********** wxDbTable::execUpdate() **********/
655 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
659 // Execute the UPDATE statement
660 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
662 if (retcode
== SQL_SUCCESS
||
663 retcode
== SQL_NO_DATA_FOUND
||
664 retcode
== SQL_SUCCESS_WITH_INFO
)
666 // Record updated successfully
669 else if (retcode
== SQL_NEED_DATA
)
672 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
673 while (retcode
== SQL_NEED_DATA
)
675 // Find the parameter
677 for (i
=0; i
< m_numCols
; i
++)
679 if (colDefs
[i
].PtrDataObj
== pParmID
)
681 // We found it. Store the parameter.
682 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
683 if (retcode
!= SQL_SUCCESS
)
685 pDb
->DispNextError();
686 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
691 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
693 if (retcode
== SQL_SUCCESS
||
694 retcode
== SQL_NO_DATA_FOUND
||
695 retcode
== SQL_SUCCESS_WITH_INFO
)
697 // Record updated successfully
702 // Problem updating record
703 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
705 } // wxDbTable::execUpdate()
708 /********** wxDbTable::query() **********/
709 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
714 // The user may wish to select for update, but the DBMS may not be capable
715 selectForUpdate
= CanSelectForUpdate();
717 selectForUpdate
= false;
719 // Set the SQL SELECT string
720 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
721 { // so generate a select statement.
722 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
723 pDb
->WriteSqlLog(sqlStmt
);
726 // Make sure the cursor is closed first
727 if (!CloseCursor(hstmt
))
730 // Execute the SQL SELECT statement
732 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
733 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
734 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
736 // Completed successfully
739 } // wxDbTable::query()
742 /***************************** PUBLIC FUNCTIONS *****************************/
745 /********** wxDbTable::Open() **********/
746 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
755 // Calculate the maximum size of the concatenated
756 // keys for use with wxDbGrid
758 for (i
=0; i
< m_numCols
; i
++)
760 if (colDefs
[i
].KeyField
)
762 m_keysize
+= colDefs
[i
].SzDataObj
;
769 if (checkTableExists
)
771 if (pDb
->Dbms() == dbmsPOSTGRES
)
772 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
774 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
777 // Verify that the table exists in the database
780 s
= wxT("Table/view does not exist in the database");
781 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
782 s
+= wxT(", or you have no permissions.\n");
786 else if (checkPrivileges
)
788 // Verify the user has rights to access the table.
789 bool hasPrivs
wxDUMMY_INITIALIZE(true);
791 if (pDb
->Dbms() == dbmsPOSTGRES
)
792 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
794 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
797 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
804 if (!tablePath
.empty())
805 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
807 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
810 pDb
->LogError(p
.GetData());
815 // Bind the member variables for field exchange between
816 // the wxDbTable object and the ODBC record.
819 if (!bindInsertParams()) // Inserts
822 if (!bindUpdateParams()) // Updates
826 if (!bindCols(*hstmtDefault
)) // Selects
829 if (!bindCols(hstmtInternal
)) // Internal use only
833 * Do NOT bind the hstmtCount cursor!!!
836 // Build an insert statement using parameter markers
837 if (!queryOnly
&& m_numCols
> 0)
839 bool needComma
= false;
840 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
841 pDb
->SQLTableName(tableName
.c_str()).c_str());
842 for (i
= 0; i
< m_numCols
; i
++)
844 if (! colDefs
[i
].InsertAllowed
)
848 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
852 sqlStmt
+= wxT(") VALUES (");
854 int insertableCount
= 0;
856 for (i
= 0; i
< m_numCols
; i
++)
858 if (! colDefs
[i
].InsertAllowed
)
868 // Prepare the insert statement for execution
871 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
872 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
878 // Completed successfully
881 } // wxDbTable::Open()
884 /********** wxDbTable::Query() **********/
885 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
888 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
890 } // wxDbTable::Query()
893 /********** wxDbTable::QueryBySqlStmt() **********/
894 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
896 pDb
->WriteSqlLog(pSqlStmt
);
898 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
900 } // wxDbTable::QueryBySqlStmt()
903 /********** wxDbTable::QueryMatching() **********/
904 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
907 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
909 } // wxDbTable::QueryMatching()
912 /********** wxDbTable::QueryOnKeyFields() **********/
913 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
916 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
918 } // wxDbTable::QueryOnKeyFields()
921 /********** wxDbTable::GetPrev() **********/
922 bool wxDbTable::GetPrev(void)
924 if (pDb
->FwdOnlyCursors())
926 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
930 return(getRec(SQL_FETCH_PRIOR
));
932 } // wxDbTable::GetPrev()
935 /********** wxDbTable::operator-- **********/
936 bool wxDbTable::operator--(int)
938 if (pDb
->FwdOnlyCursors())
940 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
944 return(getRec(SQL_FETCH_PRIOR
));
946 } // wxDbTable::operator--
949 /********** wxDbTable::GetFirst() **********/
950 bool wxDbTable::GetFirst(void)
952 if (pDb
->FwdOnlyCursors())
954 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
958 return(getRec(SQL_FETCH_FIRST
));
960 } // wxDbTable::GetFirst()
963 /********** wxDbTable::GetLast() **********/
964 bool wxDbTable::GetLast(void)
966 if (pDb
->FwdOnlyCursors())
968 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
972 return(getRec(SQL_FETCH_LAST
));
974 } // wxDbTable::GetLast()
977 /********** wxDbTable::BuildDeleteStmt() **********/
978 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
980 wxASSERT(!queryOnly
);
984 wxString whereClause
;
988 // Handle the case of DeleteWhere() and the where clause is blank. It should
989 // delete all records from the database in this case.
990 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
992 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
993 pDb
->SQLTableName(tableName
.c_str()).c_str());
997 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
998 pDb
->SQLTableName(tableName
.c_str()).c_str());
1000 // Append the WHERE clause to the SQL DELETE statement
1003 case DB_DEL_KEYFIELDS
:
1004 // If the datasource supports the ROWID column, build
1005 // the where on ROWID for efficiency purposes.
1006 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1007 if (CanUpdateByROWID())
1010 wxChar rowid
[wxDB_ROWID_LEN
+1];
1012 // Get the ROWID value. If not successful retreiving the ROWID,
1013 // simply fall down through the code and build the WHERE clause
1014 // based on the key fields.
1015 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1017 pSqlStmt
+= wxT("ROWID = '");
1019 pSqlStmt
+= wxT("'");
1023 // Unable to delete by ROWID, so build a WHERE
1024 // clause based on the keyfields.
1025 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1026 pSqlStmt
+= whereClause
;
1029 pSqlStmt
+= pWhereClause
;
1031 case DB_DEL_MATCHING
:
1032 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1033 pSqlStmt
+= whereClause
;
1037 } // BuildDeleteStmt()
1040 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1041 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1043 wxString tempSqlStmt
;
1044 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1045 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1046 } // wxDbTable::BuildDeleteStmt()
1049 /********** wxDbTable::BuildSelectStmt() **********/
1050 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1052 wxString whereClause
;
1053 whereClause
.Empty();
1055 // Build a select statement to query the database
1056 pSqlStmt
= wxT("SELECT ");
1058 // SELECT DISTINCT values only?
1060 pSqlStmt
+= wxT("DISTINCT ");
1062 // Was a FROM clause specified to join tables to the base table?
1063 // Available for ::Query() only!!!
1064 bool appendFromClause
= false;
1065 #if wxODBC_BACKWARD_COMPATABILITY
1066 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1067 appendFromClause
= true;
1069 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1070 appendFromClause
= true;
1073 // Add the column list
1076 for (i
= 0; i
< m_numCols
; i
++)
1078 tStr
= colDefs
[i
].ColName
;
1079 // If joining tables, the base table column names must be qualified to avoid ambiguity
1080 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1082 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1083 pSqlStmt
+= wxT(".");
1085 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1086 if (i
+ 1 < m_numCols
)
1087 pSqlStmt
+= wxT(",");
1090 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1091 // the ROWID if querying distinct records. The rowid will always be unique.
1092 if (!distinct
&& CanUpdateByROWID())
1094 // If joining tables, the base table column names must be qualified to avoid ambiguity
1095 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1097 pSqlStmt
+= wxT(",");
1098 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1099 pSqlStmt
+= wxT(".ROWID");
1102 pSqlStmt
+= wxT(",ROWID");
1105 // Append the FROM tablename portion
1106 pSqlStmt
+= wxT(" FROM ");
1107 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1108 // pSqlStmt += queryTableName;
1110 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1111 // The HOLDLOCK keyword follows the table name in the from clause.
1112 // Each table in the from clause must specify HOLDLOCK or
1113 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1114 // is parsed but ignored in SYBASE Transact-SQL.
1115 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1116 pSqlStmt
+= wxT(" HOLDLOCK");
1118 if (appendFromClause
)
1121 // Append the WHERE clause. Either append the where clause for the class
1122 // or build a where clause. The typeOfSelect determines this.
1123 switch(typeOfSelect
)
1125 case DB_SELECT_WHERE
:
1126 #if wxODBC_BACKWARD_COMPATABILITY
1127 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1129 if (where
.Length()) // May not want a where clause!!!
1132 pSqlStmt
+= wxT(" WHERE ");
1136 case DB_SELECT_KEYFIELDS
:
1137 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1138 if (whereClause
.Length())
1140 pSqlStmt
+= wxT(" WHERE ");
1141 pSqlStmt
+= whereClause
;
1144 case DB_SELECT_MATCHING
:
1145 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1146 if (whereClause
.Length())
1148 pSqlStmt
+= wxT(" WHERE ");
1149 pSqlStmt
+= whereClause
;
1154 // Append the ORDER BY clause
1155 #if wxODBC_BACKWARD_COMPATABILITY
1156 if (orderBy
&& wxStrlen(orderBy
))
1158 if (orderBy
.Length())
1161 pSqlStmt
+= wxT(" ORDER BY ");
1162 pSqlStmt
+= orderBy
;
1165 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1166 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1167 // HOLDLOCK for Sybase.
1168 if (selectForUpdate
&& CanSelectForUpdate())
1169 pSqlStmt
+= wxT(" FOR UPDATE");
1171 } // wxDbTable::BuildSelectStmt()
1174 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1175 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1177 wxString tempSqlStmt
;
1178 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1179 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1180 } // wxDbTable::BuildSelectStmt()
1183 /********** wxDbTable::BuildUpdateStmt() **********/
1184 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1186 wxASSERT(!queryOnly
);
1190 wxString whereClause
;
1191 whereClause
.Empty();
1193 bool firstColumn
= true;
1195 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1196 pDb
->SQLTableName(tableName
.c_str()).c_str());
1198 // Append a list of columns to be updated
1200 for (i
= 0; i
< m_numCols
; i
++)
1202 // Only append Updateable columns
1203 if (colDefs
[i
].Updateable
)
1206 pSqlStmt
+= wxT(",");
1208 firstColumn
= false;
1210 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1211 // pSqlStmt += colDefs[i].ColName;
1212 pSqlStmt
+= wxT(" = ?");
1216 // Append the WHERE clause to the SQL UPDATE statement
1217 pSqlStmt
+= wxT(" WHERE ");
1218 switch(typeOfUpdate
)
1220 case DB_UPD_KEYFIELDS
:
1221 // If the datasource supports the ROWID column, build
1222 // the where on ROWID for efficiency purposes.
1223 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1224 if (CanUpdateByROWID())
1227 wxChar rowid
[wxDB_ROWID_LEN
+1];
1229 // Get the ROWID value. If not successful retreiving the ROWID,
1230 // simply fall down through the code and build the WHERE clause
1231 // based on the key fields.
1232 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1234 pSqlStmt
+= wxT("ROWID = '");
1236 pSqlStmt
+= wxT("'");
1240 // Unable to delete by ROWID, so build a WHERE
1241 // clause based on the keyfields.
1242 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1243 pSqlStmt
+= whereClause
;
1246 pSqlStmt
+= pWhereClause
;
1249 } // BuildUpdateStmt()
1252 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1253 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1255 wxString tempSqlStmt
;
1256 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1257 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1258 } // BuildUpdateStmt()
1261 /********** wxDbTable::BuildWhereClause() **********/
1262 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1263 const wxString
&qualTableName
, bool useLikeComparison
)
1265 * Note: BuildWhereClause() currently ignores timestamp columns.
1266 * They are not included as part of the where clause.
1269 bool moreThanOneColumn
= false;
1272 // Loop through the columns building a where clause as you go
1274 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1276 // Determine if this column should be included in the WHERE clause
1277 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1278 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1280 // Skip over timestamp columns
1281 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1283 // If there is more than 1 column, join them with the keyword "AND"
1284 if (moreThanOneColumn
)
1285 pWhereClause
+= wxT(" AND ");
1287 moreThanOneColumn
= true;
1289 // Concatenate where phrase for the column
1290 wxString tStr
= colDefs
[colNumber
].ColName
;
1292 if (qualTableName
.Length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1294 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1295 pWhereClause
+= wxT(".");
1297 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1299 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1300 pWhereClause
+= wxT(" LIKE ");
1302 pWhereClause
+= wxT(" = ");
1304 switch(colDefs
[colNumber
].SqlCtype
)
1310 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1311 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
);
1315 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1318 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1322 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1325 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1328 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1331 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1336 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1337 colNumber
,colDefs
[colNumber
].ColName
);
1338 wxFAIL_MSG(strMsg
.c_str());
1342 pWhereClause
+= colValue
;
1345 } // wxDbTable::BuildWhereClause()
1348 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1349 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1350 const wxString
&qualTableName
, bool useLikeComparison
)
1352 wxString tempSqlStmt
;
1353 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1354 wxStrcpy(pWhereClause
, tempSqlStmt
);
1355 } // wxDbTable::BuildWhereClause()
1358 /********** wxDbTable::GetRowNum() **********/
1359 UWORD
wxDbTable::GetRowNum(void)
1363 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1365 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1369 // Completed successfully
1370 return((UWORD
) rowNum
);
1372 } // wxDbTable::GetRowNum()
1375 /********** wxDbTable::CloseCursor() **********/
1376 bool wxDbTable::CloseCursor(HSTMT cursor
)
1378 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1379 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1381 // Completed successfully
1384 } // wxDbTable::CloseCursor()
1387 /********** wxDbTable::CreateTable() **********/
1388 bool wxDbTable::CreateTable(bool attemptDrop
)
1396 #ifdef DBDEBUG_CONSOLE
1397 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1401 if (attemptDrop
&& !DropTable())
1405 #ifdef DBDEBUG_CONSOLE
1406 for (i
= 0; i
< m_numCols
; i
++)
1408 // Exclude derived columns since they are NOT part of the base table
1409 if (colDefs
[i
].DerivedCol
)
1411 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1412 switch(colDefs
[i
].DbDataType
)
1414 case DB_DATA_TYPE_VARCHAR
:
1415 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1417 case DB_DATA_TYPE_INTEGER
:
1418 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1420 case DB_DATA_TYPE_FLOAT
:
1421 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1423 case DB_DATA_TYPE_DATE
:
1424 cout
<< pDb
->GetTypeInfDate().TypeName
;
1426 case DB_DATA_TYPE_BLOB
:
1427 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1434 // Build a CREATE TABLE string from the colDefs structure.
1435 bool needComma
= false;
1437 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1438 pDb
->SQLTableName(tableName
.c_str()).c_str());
1440 for (i
= 0; i
< m_numCols
; i
++)
1442 // Exclude derived columns since they are NOT part of the base table
1443 if (colDefs
[i
].DerivedCol
)
1447 sqlStmt
+= wxT(",");
1449 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1450 // sqlStmt += colDefs[i].ColName;
1451 sqlStmt
+= wxT(" ");
1453 switch(colDefs
[i
].DbDataType
)
1455 case DB_DATA_TYPE_VARCHAR
:
1456 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1458 case DB_DATA_TYPE_INTEGER
:
1459 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1461 case DB_DATA_TYPE_FLOAT
:
1462 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1464 case DB_DATA_TYPE_DATE
:
1465 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1467 case DB_DATA_TYPE_BLOB
:
1468 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1471 // For varchars, append the size of the string
1472 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1473 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1474 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1477 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1481 if (pDb
->Dbms() == dbmsDB2
||
1482 pDb
->Dbms() == dbmsMY_SQL
||
1483 pDb
->Dbms() == dbmsSYBASE_ASE
||
1484 pDb
->Dbms() == dbmsINTERBASE
||
1485 pDb
->Dbms() == dbmsFIREBIRD
||
1486 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1488 if (colDefs
[i
].KeyField
)
1490 sqlStmt
+= wxT(" NOT NULL");
1496 // If there is a primary key defined, include it in the create statement
1497 for (i
= j
= 0; i
< m_numCols
; i
++)
1499 if (colDefs
[i
].KeyField
)
1505 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1506 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1508 switch (pDb
->Dbms())
1512 case dbmsSYBASE_ASA
:
1513 case dbmsSYBASE_ASE
:
1517 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1518 sqlStmt
+= wxT(",PRIMARY KEY (");
1523 sqlStmt
+= wxT(",CONSTRAINT ");
1524 // DB2 is limited to 18 characters for index names
1525 if (pDb
->Dbms() == dbmsDB2
)
1527 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."));
1528 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1529 // sqlStmt += tableName.substr(0, 13);
1532 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1533 // sqlStmt += tableName;
1535 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1540 // List column name(s) of column(s) comprising the primary key
1541 for (i
= j
= 0; i
< m_numCols
; i
++)
1543 if (colDefs
[i
].KeyField
)
1545 if (j
++) // Multi part key, comma separate names
1546 sqlStmt
+= wxT(",");
1547 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1549 if (pDb
->Dbms() == dbmsMY_SQL
&&
1550 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1553 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1558 sqlStmt
+= wxT(")");
1560 if (pDb
->Dbms() == dbmsINFORMIX
||
1561 pDb
->Dbms() == dbmsSYBASE_ASA
||
1562 pDb
->Dbms() == dbmsSYBASE_ASE
)
1564 sqlStmt
+= wxT(" CONSTRAINT ");
1565 sqlStmt
+= pDb
->SQLTableName(tableName
);
1566 // sqlStmt += tableName;
1567 sqlStmt
+= wxT("_PIDX");
1570 // Append the closing parentheses for the create table statement
1571 sqlStmt
+= wxT(")");
1573 pDb
->WriteSqlLog(sqlStmt
);
1575 #ifdef DBDEBUG_CONSOLE
1576 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1579 // Execute the CREATE TABLE statement
1580 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1581 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1583 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1584 pDb
->RollbackTrans();
1589 // Commit the transaction and close the cursor
1590 if (!pDb
->CommitTrans())
1592 if (!CloseCursor(hstmt
))
1595 // Database table created successfully
1598 } // wxDbTable::CreateTable()
1601 /********** wxDbTable::DropTable() **********/
1602 bool wxDbTable::DropTable()
1604 // NOTE: This function returns true if the Table does not exist, but
1605 // only for identified databases. Code will need to be added
1606 // below for any other databases when those databases are defined
1607 // to handle this situation consistently
1611 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1612 pDb
->SQLTableName(tableName
.c_str()).c_str());
1614 pDb
->WriteSqlLog(sqlStmt
);
1616 #ifdef DBDEBUG_CONSOLE
1617 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1620 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1621 if (retcode
!= SQL_SUCCESS
)
1623 // Check for "Base table not found" error and ignore
1624 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1625 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1626 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1628 // Check for product specific error codes
1629 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1630 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1631 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1632 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1634 pDb
->DispNextError();
1635 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1636 pDb
->RollbackTrans();
1637 // CloseCursor(hstmt);
1643 // Commit the transaction and close the cursor
1644 if (! pDb
->CommitTrans())
1646 if (! CloseCursor(hstmt
))
1650 } // wxDbTable::DropTable()
1653 /********** wxDbTable::CreateIndex() **********/
1654 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1655 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1659 // Drop the index first
1660 if (attemptDrop
&& !DropIndex(indexName
))
1663 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1664 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1665 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1666 // table was created, then months later you determine that an additional index while
1667 // give better performance, so you want to add an index).
1669 // The following block of code will modify the column definition to make the column be
1670 // defined with the "NOT NULL" qualifier.
1671 if (pDb
->Dbms() == dbmsMY_SQL
)
1676 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1680 // Find the column definition that has the ColName that matches the
1681 // index column name. We need to do this to get the DB_DATA_TYPE of
1682 // the index column, as MySQL's syntax for the ALTER column requires
1684 while (!found
&& (j
< this->m_numCols
))
1686 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1694 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1695 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1701 // retcode is not used
1702 wxODBC_ERRORS retcode
;
1703 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1704 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1705 // This line is just here for debug checking of the value
1706 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1717 pDb
->RollbackTrans();
1722 // Build a CREATE INDEX statement
1723 sqlStmt
= wxT("CREATE ");
1725 sqlStmt
+= wxT("UNIQUE ");
1727 sqlStmt
+= wxT("INDEX ");
1728 sqlStmt
+= pDb
->SQLTableName(indexName
);
1729 sqlStmt
+= wxT(" ON ");
1731 sqlStmt
+= pDb
->SQLTableName(tableName
);
1732 // sqlStmt += tableName;
1733 sqlStmt
+= wxT(" (");
1735 // Append list of columns making up index
1737 for (i
= 0; i
< numIndexColumns
; i
++)
1739 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1740 // sqlStmt += pIndexDefs[i].ColName;
1742 // MySQL requires a key length on VARCHAR keys
1743 if ( pDb
->Dbms() == dbmsMY_SQL
)
1745 // Find the details on this column
1747 for ( j
= 0; j
< m_numCols
; ++j
)
1749 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1754 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1757 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1762 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1763 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1764 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1765 !(pDb
->Dbms() == dbmsPOSTGRES
))
1767 if (pIndexDefs
[i
].Ascending
)
1768 sqlStmt
+= wxT(" ASC");
1770 sqlStmt
+= wxT(" DESC");
1773 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1775 if ((i
+ 1) < numIndexColumns
)
1776 sqlStmt
+= wxT(",");
1779 // Append closing parentheses
1780 sqlStmt
+= wxT(")");
1782 pDb
->WriteSqlLog(sqlStmt
);
1784 #ifdef DBDEBUG_CONSOLE
1785 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1788 // Execute the CREATE INDEX statement
1789 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1790 if (retcode
!= SQL_SUCCESS
)
1792 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1793 pDb
->RollbackTrans();
1798 // Commit the transaction and close the cursor
1799 if (! pDb
->CommitTrans())
1801 if (! CloseCursor(hstmt
))
1804 // Index Created Successfully
1807 } // wxDbTable::CreateIndex()
1810 /********** wxDbTable::DropIndex() **********/
1811 bool wxDbTable::DropIndex(const wxString
&indexName
)
1813 // NOTE: This function returns true if the Index does not exist, but
1814 // only for identified databases. Code will need to be added
1815 // below for any other databases when those databases are defined
1816 // to handle this situation consistently
1820 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1821 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1822 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1823 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1824 pDb
->SQLTableName(tableName
.c_str()).c_str());
1825 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1826 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1827 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1828 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1829 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1830 pDb
->SQLTableName(indexName
.c_str()).c_str());
1832 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1833 pDb
->SQLTableName(indexName
.c_str()).c_str());
1835 pDb
->WriteSqlLog(sqlStmt
);
1837 #ifdef DBDEBUG_CONSOLE
1838 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1840 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1841 if (retcode
!= SQL_SUCCESS
)
1843 // Check for "Index not found" error and ignore
1844 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1845 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1847 // Check for product specific error codes
1848 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1849 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1850 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1851 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1852 (pDb
->Dbms() == dbmsMAXDB
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1853 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1854 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1855 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1856 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1859 pDb
->DispNextError();
1860 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1861 pDb
->RollbackTrans();
1868 // Commit the transaction and close the cursor
1869 if (! pDb
->CommitTrans())
1871 if (! CloseCursor(hstmt
))
1875 } // wxDbTable::DropIndex()
1878 /********** wxDbTable::SetOrderByColNums() **********/
1879 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1881 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1887 va_start(argptr
, first
); /* Initialize variable arguments. */
1888 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1890 // Make sure the passed in column number
1891 // is within the valid range of columns
1893 // Valid columns are 0 thru m_numCols-1
1894 if (colNumber
>= m_numCols
|| colNumber
< 0)
1900 if (colNumber
!= first
)
1901 tempStr
+= wxT(",");
1903 tempStr
+= colDefs
[colNumber
].ColName
;
1904 colNumber
= va_arg (argptr
, int);
1906 va_end (argptr
); /* Reset variable arguments. */
1908 SetOrderByClause(tempStr
);
1911 } // wxDbTable::SetOrderByColNums()
1914 /********** wxDbTable::Insert() **********/
1915 int wxDbTable::Insert(void)
1917 wxASSERT(!queryOnly
);
1918 if (queryOnly
|| !insertable
)
1923 // Insert the record by executing the already prepared insert statement
1925 retcode
= SQLExecute(hstmtInsert
);
1926 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1927 retcode
!= SQL_NEED_DATA
)
1929 // Check to see if integrity constraint was violated
1930 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1931 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1932 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1935 pDb
->DispNextError();
1936 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1940 if (retcode
== SQL_NEED_DATA
)
1943 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1944 while (retcode
== SQL_NEED_DATA
)
1946 // Find the parameter
1948 for (i
=0; i
< m_numCols
; i
++)
1950 if (colDefs
[i
].PtrDataObj
== pParmID
)
1952 // We found it. Store the parameter.
1953 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1954 if (retcode
!= SQL_SUCCESS
)
1956 pDb
->DispNextError();
1957 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1963 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1964 if (retcode
!= SQL_SUCCESS
&&
1965 retcode
!= SQL_SUCCESS_WITH_INFO
)
1967 // record was not inserted
1968 pDb
->DispNextError();
1969 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1975 // Record inserted into the datasource successfully
1978 } // wxDbTable::Insert()
1981 /********** wxDbTable::Update() **********/
1982 bool wxDbTable::Update(void)
1984 wxASSERT(!queryOnly
);
1990 // Build the SQL UPDATE statement
1991 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1993 pDb
->WriteSqlLog(sqlStmt
);
1995 #ifdef DBDEBUG_CONSOLE
1996 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1999 // Execute the SQL UPDATE statement
2000 return(execUpdate(sqlStmt
));
2002 } // wxDbTable::Update()
2005 /********** wxDbTable::Update(pSqlStmt) **********/
2006 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2008 wxASSERT(!queryOnly
);
2012 pDb
->WriteSqlLog(pSqlStmt
);
2014 return(execUpdate(pSqlStmt
));
2016 } // wxDbTable::Update(pSqlStmt)
2019 /********** wxDbTable::UpdateWhere() **********/
2020 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2022 wxASSERT(!queryOnly
);
2028 // Build the SQL UPDATE statement
2029 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2031 pDb
->WriteSqlLog(sqlStmt
);
2033 #ifdef DBDEBUG_CONSOLE
2034 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2037 // Execute the SQL UPDATE statement
2038 return(execUpdate(sqlStmt
));
2040 } // wxDbTable::UpdateWhere()
2043 /********** wxDbTable::Delete() **********/
2044 bool wxDbTable::Delete(void)
2046 wxASSERT(!queryOnly
);
2053 // Build the SQL DELETE statement
2054 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2056 pDb
->WriteSqlLog(sqlStmt
);
2058 // Execute the SQL DELETE statement
2059 return(execDelete(sqlStmt
));
2061 } // wxDbTable::Delete()
2064 /********** wxDbTable::DeleteWhere() **********/
2065 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2067 wxASSERT(!queryOnly
);
2074 // Build the SQL DELETE statement
2075 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2077 pDb
->WriteSqlLog(sqlStmt
);
2079 // Execute the SQL DELETE statement
2080 return(execDelete(sqlStmt
));
2082 } // wxDbTable::DeleteWhere()
2085 /********** wxDbTable::DeleteMatching() **********/
2086 bool wxDbTable::DeleteMatching(void)
2088 wxASSERT(!queryOnly
);
2095 // Build the SQL DELETE statement
2096 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2098 pDb
->WriteSqlLog(sqlStmt
);
2100 // Execute the SQL DELETE statement
2101 return(execDelete(sqlStmt
));
2103 } // wxDbTable::DeleteMatching()
2106 /********** wxDbTable::IsColNull() **********/
2107 bool wxDbTable::IsColNull(UWORD colNumber
) const
2110 This logic is just not right. It would indicate true
2111 if a numeric field were set to a value of 0.
2113 switch(colDefs[colNumber].SqlCtype)
2117 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2118 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2120 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2122 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2124 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2126 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2128 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2130 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2131 case SQL_C_TIMESTAMP:
2132 TIMESTAMP_STRUCT *pDt;
2133 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2134 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2142 return (colDefs
[colNumber
].Null
);
2143 } // wxDbTable::IsColNull()
2146 /********** wxDbTable::CanSelectForUpdate() **********/
2147 bool wxDbTable::CanSelectForUpdate(void)
2152 if (pDb
->Dbms() == dbmsMY_SQL
)
2155 if ((pDb
->Dbms() == dbmsORACLE
) ||
2156 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2161 } // wxDbTable::CanSelectForUpdate()
2164 /********** wxDbTable::CanUpdateByROWID() **********/
2165 bool wxDbTable::CanUpdateByROWID(void)
2168 * NOTE: Returning false for now until this can be debugged,
2169 * as the ROWID is not getting updated correctly
2173 if (pDb->Dbms() == dbmsORACLE)
2178 } // wxDbTable::CanUpdateByROWID()
2181 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2182 bool wxDbTable::IsCursorClosedOnCommit(void)
2184 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2189 } // wxDbTable::IsCursorClosedOnCommit()
2193 /********** wxDbTable::ClearMemberVar() **********/
2194 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2196 wxASSERT(colNumber
< m_numCols
);
2198 switch(colDefs
[colNumber
].SqlCtype
)
2204 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2205 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2208 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2211 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2215 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2218 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2221 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2224 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2226 case SQL_C_TIMESTAMP
:
2227 TIMESTAMP_STRUCT
*pDt
;
2228 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2240 SetColNull(colNumber
);
2241 } // wxDbTable::ClearMemberVar()
2244 /********** wxDbTable::ClearMemberVars() **********/
2245 void wxDbTable::ClearMemberVars(bool setToNull
)
2249 // Loop through the columns setting each member variable to zero
2250 for (i
=0; i
< m_numCols
; i
++)
2251 ClearMemberVar((UWORD
)i
,setToNull
);
2253 } // wxDbTable::ClearMemberVars()
2256 /********** wxDbTable::SetQueryTimeout() **********/
2257 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2259 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2260 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2261 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2262 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2263 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2264 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2265 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2266 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2268 // Completed Successfully
2271 } // wxDbTable::SetQueryTimeout()
2274 /********** wxDbTable::SetColDefs() **********/
2275 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2276 SWORD cType
, int size
, bool keyField
, bool updateable
,
2277 bool insertAllowed
, bool derivedColumn
)
2281 if (index
>= m_numCols
) // Columns numbers are zero based....
2283 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
);
2289 if (!colDefs
) // May happen if the database connection fails
2292 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2294 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2295 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2297 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2298 fieldName
.c_str(),colDefs
[index
].ColName
);
2303 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2305 colDefs
[index
].DbDataType
= dataType
;
2306 colDefs
[index
].PtrDataObj
= pData
;
2307 colDefs
[index
].SqlCtype
= cType
;
2308 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2309 colDefs
[index
].KeyField
= keyField
;
2310 colDefs
[index
].DerivedCol
= derivedColumn
;
2311 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2314 colDefs
[index
].Updateable
= false;
2315 colDefs
[index
].InsertAllowed
= false;
2319 colDefs
[index
].Updateable
= updateable
;
2320 colDefs
[index
].InsertAllowed
= insertAllowed
;
2323 colDefs
[index
].Null
= false;
2327 } // wxDbTable::SetColDefs()
2330 /********** wxDbTable::SetColDefs() **********/
2331 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2334 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2340 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2342 for (index
= 0; index
< numCols
; index
++)
2344 // Process the fields
2345 switch (pColInfs
[index
].dbDataType
)
2347 case DB_DATA_TYPE_VARCHAR
:
2348 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2349 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2350 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2352 case DB_DATA_TYPE_INTEGER
:
2353 // Can be long or short
2354 if (pColInfs
[index
].bufferSize
== sizeof(long))
2356 pColDataPtrs
[index
].PtrDataObj
= new long;
2357 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2358 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2362 pColDataPtrs
[index
].PtrDataObj
= new short;
2363 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2364 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2367 case DB_DATA_TYPE_FLOAT
:
2368 // Can be float or double
2369 if (pColInfs
[index
].bufferSize
== sizeof(float))
2371 pColDataPtrs
[index
].PtrDataObj
= new float;
2372 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2373 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2377 pColDataPtrs
[index
].PtrDataObj
= new double;
2378 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2379 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2382 case DB_DATA_TYPE_DATE
:
2383 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2384 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2385 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2387 case DB_DATA_TYPE_BLOB
:
2388 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2389 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2390 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2391 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2394 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2395 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2398 // Unable to build all the column definitions, as either one of
2399 // the calls to "new" failed above, or there was a BLOB field
2400 // to have a column definition for. If BLOBs are to be used,
2401 // the other form of ::SetColDefs() must be used, as it is impossible
2402 // to know the maximum size to create the PtrDataObj to be.
2403 delete [] pColDataPtrs
;
2409 return (pColDataPtrs
);
2411 } // wxDbTable::SetColDefs()
2414 /********** wxDbTable::SetCursor() **********/
2415 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2417 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2418 hstmt
= *hstmtDefault
;
2420 hstmt
= *hstmtActivate
;
2422 } // wxDbTable::SetCursor()
2425 /********** wxDbTable::Count(const wxString &) **********/
2426 ULONG
wxDbTable::Count(const wxString
&args
)
2432 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2433 sqlStmt
= wxT("SELECT COUNT(");
2435 sqlStmt
+= wxT(") FROM ");
2436 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2437 // sqlStmt += queryTableName;
2438 #if wxODBC_BACKWARD_COMPATABILITY
2439 if (from
&& wxStrlen(from
))
2445 // Add the where clause if one is provided
2446 #if wxODBC_BACKWARD_COMPATABILITY
2447 if (where
&& wxStrlen(where
))
2452 sqlStmt
+= wxT(" WHERE ");
2456 pDb
->WriteSqlLog(sqlStmt
);
2458 // Initialize the Count cursor if it's not already initialized
2461 hstmtCount
= GetNewCursor(false,false);
2462 wxASSERT(hstmtCount
);
2467 // Execute the SQL statement
2468 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2470 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2475 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2477 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2481 // Obtain the result
2482 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2484 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2489 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2490 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2492 // Return the record count
2495 } // wxDbTable::Count()
2498 /********** wxDbTable::Refresh() **********/
2499 bool wxDbTable::Refresh(void)
2503 // Switch to the internal cursor so any active cursors are not corrupted
2504 HSTMT currCursor
= GetCursor();
2505 hstmt
= hstmtInternal
;
2506 #if wxODBC_BACKWARD_COMPATABILITY
2507 // Save the where and order by clauses
2508 wxChar
*saveWhere
= where
;
2509 wxChar
*saveOrderBy
= orderBy
;
2511 wxString saveWhere
= where
;
2512 wxString saveOrderBy
= orderBy
;
2514 // Build a where clause to refetch the record with. Try and use the
2515 // ROWID if it's available, ow use the key fields.
2516 wxString whereClause
;
2517 whereClause
.Empty();
2519 if (CanUpdateByROWID())
2522 wxChar rowid
[wxDB_ROWID_LEN
+1];
2524 // Get the ROWID value. If not successful retreiving the ROWID,
2525 // simply fall down through the code and build the WHERE clause
2526 // based on the key fields.
2527 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2529 whereClause
+= pDb
->SQLTableName(queryTableName
);
2530 // whereClause += queryTableName;
2531 whereClause
+= wxT(".ROWID = '");
2532 whereClause
+= rowid
;
2533 whereClause
+= wxT("'");
2537 // If unable to use the ROWID, build a where clause from the keyfields
2538 if (wxStrlen(whereClause
) == 0)
2539 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2541 // Requery the record
2542 where
= whereClause
;
2547 if (result
&& !GetNext())
2550 // Switch back to original cursor
2551 SetCursor(&currCursor
);
2553 // Free the internal cursor
2554 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2555 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2557 // Restore the original where and order by clauses
2559 orderBy
= saveOrderBy
;
2563 } // wxDbTable::Refresh()
2566 /********** wxDbTable::SetColNull() **********/
2567 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2569 if (colNumber
< m_numCols
)
2571 colDefs
[colNumber
].Null
= set
;
2572 if (set
) // Blank out the values in the member variable
2573 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2575 setCbValueForColumn(colNumber
);
2582 } // wxDbTable::SetColNull()
2585 /********** wxDbTable::SetColNull() **********/
2586 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2589 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2591 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2595 if (colNumber
< m_numCols
)
2597 colDefs
[colNumber
].Null
= set
;
2598 if (set
) // Blank out the values in the member variable
2599 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2601 setCbValueForColumn(colNumber
);
2608 } // wxDbTable::SetColNull()
2611 /********** wxDbTable::GetNewCursor() **********/
2612 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2614 HSTMT
*newHSTMT
= new HSTMT
;
2619 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2621 pDb
->DispAllErrors(henv
, hdbc
);
2626 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2628 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2635 if (!bindCols(*newHSTMT
))
2643 SetCursor(newHSTMT
);
2647 } // wxDbTable::GetNewCursor()
2650 /********** wxDbTable::DeleteCursor() **********/
2651 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2655 if (!hstmtDel
) // Cursor already deleted
2659 ODBC 3.0 says to use this form
2660 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2663 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2665 pDb
->DispAllErrors(henv
, hdbc
);
2673 } // wxDbTable::DeleteCursor()
2675 //////////////////////////////////////////////////////////////
2676 // wxDbGrid support functions
2677 //////////////////////////////////////////////////////////////
2679 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2681 if (!m_hstmtGridQuery
)
2683 m_hstmtGridQuery
= GetNewCursor(false,false);
2684 if (!bindCols(*m_hstmtGridQuery
))
2688 m_rowmode
= rowmode
;
2691 case WX_ROW_MODE_QUERY
:
2692 SetCursor(m_hstmtGridQuery
);
2694 case WX_ROW_MODE_INDIVIDUAL
:
2695 SetCursor(hstmtDefault
);
2700 } // wxDbTable::SetRowMode()
2703 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2706 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2708 switch (colDefs
[colNumber
].SqlCtype
)
2711 #if defined(SQL_WCHAR)
2714 #if defined(SQL_WVARCHAR)
2720 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2724 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2728 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2731 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2734 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2736 case SQL_C_UTINYINT
:
2737 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2740 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2743 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2746 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2748 case SQL_C_TIMESTAMP
:
2749 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2752 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2759 } // wxDbTable::GetCol()
2762 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2764 //FIXME: Add proper wxDateTime support to wxVariant..
2767 SetColNull((UWORD
)colNumber
, val
.IsNull());
2771 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2772 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2773 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2775 //Returns null if invalid!
2776 if (!dateval
.ParseDate(val
.GetString()))
2777 SetColNull((UWORD
)colNumber
, true);
2780 switch (colDefs
[colNumber
].SqlCtype
)
2783 #if defined(SQL_WCHAR)
2786 #if defined(SQL_WVARCHAR)
2792 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2793 val
.GetString().c_str(),
2794 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2798 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2802 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2805 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2808 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2810 case SQL_C_UTINYINT
:
2811 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2814 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2816 //FIXME: Add proper wxDateTime support to wxVariant..
2819 DATE_STRUCT
*dataptr
=
2820 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2822 dataptr
->year
= (SWORD
)dateval
.GetYear();
2823 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2824 dataptr
->day
= (UWORD
)dateval
.GetDay();
2829 TIME_STRUCT
*dataptr
=
2830 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2832 dataptr
->hour
= dateval
.GetHour();
2833 dataptr
->minute
= dateval
.GetMinute();
2834 dataptr
->second
= dateval
.GetSecond();
2837 case SQL_C_TIMESTAMP
:
2839 TIMESTAMP_STRUCT
*dataptr
=
2840 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2841 dataptr
->year
= (SWORD
)dateval
.GetYear();
2842 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2843 dataptr
->day
= (UWORD
)dateval
.GetDay();
2845 dataptr
->hour
= dateval
.GetHour();
2846 dataptr
->minute
= dateval
.GetMinute();
2847 dataptr
->second
= dateval
.GetSecond();
2851 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2856 } // if (!val.IsNull())
2857 } // wxDbTable::SetCol()
2860 GenericKey
wxDbTable::GetKey()
2865 blk
= malloc(m_keysize
);
2866 blkptr
= (wxChar
*) blk
;
2869 for (i
=0; i
< m_numCols
; i
++)
2871 if (colDefs
[i
].KeyField
)
2873 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2874 blkptr
+= colDefs
[i
].SzDataObj
;
2878 GenericKey k
= GenericKey(blk
, m_keysize
);
2882 } // wxDbTable::GetKey()
2885 void wxDbTable::SetKey(const GenericKey
& k
)
2891 blkptr
= (wxChar
*)blk
;
2894 for (i
=0; i
< m_numCols
; i
++)
2896 if (colDefs
[i
].KeyField
)
2898 SetColNull((UWORD
)i
, false);
2899 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2900 blkptr
+= colDefs
[i
].SzDataObj
;
2903 } // wxDbTable::SetKey()
2906 #endif // wxUSE_ODBC