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 case DB_DATA_TYPE_MEMO
:
417 if (colDefs
[columnIndex
].Null
)
418 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
420 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
423 case DB_DATA_TYPE_INTEGER
:
424 if (colDefs
[columnIndex
].Null
)
425 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
427 colDefs
[columnIndex
].CbValue
= 0;
429 case DB_DATA_TYPE_FLOAT
:
430 if (colDefs
[columnIndex
].Null
)
431 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
433 colDefs
[columnIndex
].CbValue
= 0;
435 case DB_DATA_TYPE_DATE
:
436 if (colDefs
[columnIndex
].Null
)
437 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
439 colDefs
[columnIndex
].CbValue
= 0;
441 case DB_DATA_TYPE_BLOB
:
442 if (colDefs
[columnIndex
].Null
)
443 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
445 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
446 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
448 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
453 /********** wxDbTable::bindParams() **********/
454 bool wxDbTable::bindParams(bool forUpdate
)
456 wxASSERT(!queryOnly
);
461 SDWORD precision
= 0;
464 // Bind each column of the table that should be bound
465 // to a parameter marker
469 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
473 if (!colDefs
[i
].Updateable
)
478 if (!colDefs
[i
].InsertAllowed
)
482 switch(colDefs
[i
].DbDataType
)
484 case DB_DATA_TYPE_VARCHAR
:
485 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
486 precision
= colDefs
[i
].SzDataObj
;
489 case DB_DATA_TYPE_MEMO
:
490 fSqlType
= pDb
->GetTypeInfMemo().FsqlType
;
491 precision
= colDefs
[i
].SzDataObj
;
494 case DB_DATA_TYPE_INTEGER
:
495 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
496 precision
= pDb
->GetTypeInfInteger().Precision
;
499 case DB_DATA_TYPE_FLOAT
:
500 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
501 precision
= pDb
->GetTypeInfFloat().Precision
;
502 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
503 // SQL Sybase Anywhere v5.5 returned a negative number for the
504 // MaxScale. This caused ODBC to kick out an error on ibscale.
505 // I check for this here and set the scale = precision.
507 // scale = (short) precision;
509 case DB_DATA_TYPE_DATE
:
510 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
511 precision
= pDb
->GetTypeInfDate().Precision
;
514 case DB_DATA_TYPE_BLOB
:
515 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
516 precision
= colDefs
[i
].SzDataObj
;
521 setCbValueForColumn(i
);
525 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
526 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
527 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
529 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
534 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
535 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
536 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
538 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
543 // Completed successfully
546 } // wxDbTable::bindParams()
549 /********** wxDbTable::bindInsertParams() **********/
550 bool wxDbTable::bindInsertParams(void)
552 return bindParams(false);
553 } // wxDbTable::bindInsertParams()
556 /********** wxDbTable::bindUpdateParams() **********/
557 bool wxDbTable::bindUpdateParams(void)
559 return bindParams(true);
560 } // wxDbTable::bindUpdateParams()
563 /********** wxDbTable::bindCols() **********/
564 bool wxDbTable::bindCols(HSTMT cursor
)
568 // Bind each column of the table to a memory address for fetching data
570 for (i
= 0; i
< m_numCols
; i
++)
572 cb
= colDefs
[i
].CbValue
;
573 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
574 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
575 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
578 // Completed successfully
581 } // wxDbTable::bindCols()
584 /********** wxDbTable::getRec() **********/
585 bool wxDbTable::getRec(UWORD fetchType
)
589 if (!pDb
->FwdOnlyCursors())
591 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
592 SQLULEN cRowsFetched
;
595 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
596 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
598 if (retcode
== SQL_NO_DATA_FOUND
)
601 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
605 // Set the Null member variable to indicate the Null state
606 // of each column just read in.
608 for (i
= 0; i
< m_numCols
; i
++)
609 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
614 // Fetch the next record from the record set
615 retcode
= SQLFetch(hstmt
);
616 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
618 if (retcode
== SQL_NO_DATA_FOUND
)
621 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
625 // Set the Null member variable to indicate the Null state
626 // of each column just read in.
628 for (i
= 0; i
< m_numCols
; i
++)
629 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
633 // Completed successfully
636 } // wxDbTable::getRec()
639 /********** wxDbTable::execDelete() **********/
640 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
644 // Execute the DELETE statement
645 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
647 if (retcode
== SQL_SUCCESS
||
648 retcode
== SQL_NO_DATA_FOUND
||
649 retcode
== SQL_SUCCESS_WITH_INFO
)
651 // Record deleted successfully
655 // Problem deleting record
656 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
658 } // wxDbTable::execDelete()
661 /********** wxDbTable::execUpdate() **********/
662 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
666 // Execute the UPDATE statement
667 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
669 if (retcode
== SQL_SUCCESS
||
670 retcode
== SQL_NO_DATA_FOUND
||
671 retcode
== SQL_SUCCESS_WITH_INFO
)
673 // Record updated successfully
676 else if (retcode
== SQL_NEED_DATA
)
679 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
680 while (retcode
== SQL_NEED_DATA
)
682 // Find the parameter
684 for (i
=0; i
< m_numCols
; i
++)
686 if (colDefs
[i
].PtrDataObj
== pParmID
)
688 // We found it. Store the parameter.
689 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
690 if (retcode
!= SQL_SUCCESS
)
692 pDb
->DispNextError();
693 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
698 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
700 if (retcode
== SQL_SUCCESS
||
701 retcode
== SQL_NO_DATA_FOUND
||
702 retcode
== SQL_SUCCESS_WITH_INFO
)
704 // Record updated successfully
709 // Problem updating record
710 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
712 } // wxDbTable::execUpdate()
715 /********** wxDbTable::query() **********/
716 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
721 // The user may wish to select for update, but the DBMS may not be capable
722 selectForUpdate
= CanSelectForUpdate();
724 selectForUpdate
= false;
726 // Set the SQL SELECT string
727 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
728 { // so generate a select statement.
729 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
730 pDb
->WriteSqlLog(sqlStmt
);
733 // Make sure the cursor is closed first
734 if (!CloseCursor(hstmt
))
737 // Execute the SQL SELECT statement
739 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
740 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
741 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
743 // Completed successfully
746 } // wxDbTable::query()
749 /***************************** PUBLIC FUNCTIONS *****************************/
752 /********** wxDbTable::Open() **********/
753 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
762 // Calculate the maximum size of the concatenated
763 // keys for use with wxDbGrid
765 for (i
=0; i
< m_numCols
; i
++)
767 if (colDefs
[i
].KeyField
)
769 m_keysize
+= colDefs
[i
].SzDataObj
;
776 if (checkTableExists
)
778 if (pDb
->Dbms() == dbmsPOSTGRES
)
779 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
781 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
784 // Verify that the table exists in the database
787 s
= wxT("Table/view does not exist in the database");
788 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
789 s
+= wxT(", or you have no permissions.\n");
793 else if (checkPrivileges
)
795 // Verify the user has rights to access the table.
796 bool hasPrivs
wxDUMMY_INITIALIZE(true);
798 if (pDb
->Dbms() == dbmsPOSTGRES
)
799 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
801 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
804 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
811 if (!tablePath
.empty())
812 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
814 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
817 pDb
->LogError(p
.GetData());
822 // Bind the member variables for field exchange between
823 // the wxDbTable object and the ODBC record.
826 if (!bindInsertParams()) // Inserts
829 if (!bindUpdateParams()) // Updates
833 if (!bindCols(*hstmtDefault
)) // Selects
836 if (!bindCols(hstmtInternal
)) // Internal use only
840 * Do NOT bind the hstmtCount cursor!!!
843 // Build an insert statement using parameter markers
844 if (!queryOnly
&& m_numCols
> 0)
846 bool needComma
= false;
847 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
848 pDb
->SQLTableName(tableName
.c_str()).c_str());
849 for (i
= 0; i
< m_numCols
; i
++)
851 if (! colDefs
[i
].InsertAllowed
)
855 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
859 sqlStmt
+= wxT(") VALUES (");
861 int insertableCount
= 0;
863 for (i
= 0; i
< m_numCols
; i
++)
865 if (! colDefs
[i
].InsertAllowed
)
875 // Prepare the insert statement for execution
878 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
879 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
885 // Completed successfully
888 } // wxDbTable::Open()
891 /********** wxDbTable::Query() **********/
892 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
895 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
897 } // wxDbTable::Query()
900 /********** wxDbTable::QueryBySqlStmt() **********/
901 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
903 pDb
->WriteSqlLog(pSqlStmt
);
905 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
907 } // wxDbTable::QueryBySqlStmt()
910 /********** wxDbTable::QueryMatching() **********/
911 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
914 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
916 } // wxDbTable::QueryMatching()
919 /********** wxDbTable::QueryOnKeyFields() **********/
920 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
923 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
925 } // wxDbTable::QueryOnKeyFields()
928 /********** wxDbTable::GetPrev() **********/
929 bool wxDbTable::GetPrev(void)
931 if (pDb
->FwdOnlyCursors())
933 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
937 return(getRec(SQL_FETCH_PRIOR
));
939 } // wxDbTable::GetPrev()
942 /********** wxDbTable::operator-- **********/
943 bool wxDbTable::operator--(int)
945 if (pDb
->FwdOnlyCursors())
947 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
951 return(getRec(SQL_FETCH_PRIOR
));
953 } // wxDbTable::operator--
956 /********** wxDbTable::GetFirst() **********/
957 bool wxDbTable::GetFirst(void)
959 if (pDb
->FwdOnlyCursors())
961 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
965 return(getRec(SQL_FETCH_FIRST
));
967 } // wxDbTable::GetFirst()
970 /********** wxDbTable::GetLast() **********/
971 bool wxDbTable::GetLast(void)
973 if (pDb
->FwdOnlyCursors())
975 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
979 return(getRec(SQL_FETCH_LAST
));
981 } // wxDbTable::GetLast()
984 /********** wxDbTable::BuildDeleteStmt() **********/
985 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
987 wxASSERT(!queryOnly
);
991 wxString whereClause
;
995 // Handle the case of DeleteWhere() and the where clause is blank. It should
996 // delete all records from the database in this case.
997 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
999 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
1000 pDb
->SQLTableName(tableName
.c_str()).c_str());
1004 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
1005 pDb
->SQLTableName(tableName
.c_str()).c_str());
1007 // Append the WHERE clause to the SQL DELETE statement
1010 case DB_DEL_KEYFIELDS
:
1011 // If the datasource supports the ROWID column, build
1012 // the where on ROWID for efficiency purposes.
1013 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1014 if (CanUpdateByROWID())
1017 wxChar rowid
[wxDB_ROWID_LEN
+1];
1019 // Get the ROWID value. If not successful retreiving the ROWID,
1020 // simply fall down through the code and build the WHERE clause
1021 // based on the key fields.
1022 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1024 pSqlStmt
+= wxT("ROWID = '");
1026 pSqlStmt
+= wxT("'");
1030 // Unable to delete by ROWID, so build a WHERE
1031 // clause based on the keyfields.
1032 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1033 pSqlStmt
+= whereClause
;
1036 pSqlStmt
+= pWhereClause
;
1038 case DB_DEL_MATCHING
:
1039 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1040 pSqlStmt
+= whereClause
;
1044 } // BuildDeleteStmt()
1047 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1048 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1050 wxString tempSqlStmt
;
1051 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1052 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1053 } // wxDbTable::BuildDeleteStmt()
1056 /********** wxDbTable::BuildSelectStmt() **********/
1057 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1059 wxString whereClause
;
1060 whereClause
.Empty();
1062 // Build a select statement to query the database
1063 pSqlStmt
= wxT("SELECT ");
1065 // SELECT DISTINCT values only?
1067 pSqlStmt
+= wxT("DISTINCT ");
1069 // Was a FROM clause specified to join tables to the base table?
1070 // Available for ::Query() only!!!
1071 bool appendFromClause
= false;
1072 #if wxODBC_BACKWARD_COMPATABILITY
1073 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1074 appendFromClause
= true;
1076 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1077 appendFromClause
= true;
1080 // Add the column list
1083 for (i
= 0; i
< m_numCols
; i
++)
1085 tStr
= colDefs
[i
].ColName
;
1086 // If joining tables, the base table column names must be qualified to avoid ambiguity
1087 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1089 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1090 pSqlStmt
+= wxT(".");
1092 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1093 if (i
+ 1 < m_numCols
)
1094 pSqlStmt
+= wxT(",");
1097 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1098 // the ROWID if querying distinct records. The rowid will always be unique.
1099 if (!distinct
&& CanUpdateByROWID())
1101 // If joining tables, the base table column names must be qualified to avoid ambiguity
1102 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1104 pSqlStmt
+= wxT(",");
1105 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1106 pSqlStmt
+= wxT(".ROWID");
1109 pSqlStmt
+= wxT(",ROWID");
1112 // Append the FROM tablename portion
1113 pSqlStmt
+= wxT(" FROM ");
1114 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1115 // pSqlStmt += queryTableName;
1117 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1118 // The HOLDLOCK keyword follows the table name in the from clause.
1119 // Each table in the from clause must specify HOLDLOCK or
1120 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1121 // is parsed but ignored in SYBASE Transact-SQL.
1122 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1123 pSqlStmt
+= wxT(" HOLDLOCK");
1125 if (appendFromClause
)
1128 // Append the WHERE clause. Either append the where clause for the class
1129 // or build a where clause. The typeOfSelect determines this.
1130 switch(typeOfSelect
)
1132 case DB_SELECT_WHERE
:
1133 #if wxODBC_BACKWARD_COMPATABILITY
1134 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1136 if (where
.Length()) // May not want a where clause!!!
1139 pSqlStmt
+= wxT(" WHERE ");
1143 case DB_SELECT_KEYFIELDS
:
1144 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1145 if (whereClause
.Length())
1147 pSqlStmt
+= wxT(" WHERE ");
1148 pSqlStmt
+= whereClause
;
1151 case DB_SELECT_MATCHING
:
1152 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1153 if (whereClause
.Length())
1155 pSqlStmt
+= wxT(" WHERE ");
1156 pSqlStmt
+= whereClause
;
1161 // Append the ORDER BY clause
1162 #if wxODBC_BACKWARD_COMPATABILITY
1163 if (orderBy
&& wxStrlen(orderBy
))
1165 if (orderBy
.Length())
1168 pSqlStmt
+= wxT(" ORDER BY ");
1169 pSqlStmt
+= orderBy
;
1172 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1173 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1174 // HOLDLOCK for Sybase.
1175 if (selectForUpdate
&& CanSelectForUpdate())
1176 pSqlStmt
+= wxT(" FOR UPDATE");
1178 } // wxDbTable::BuildSelectStmt()
1181 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1182 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1184 wxString tempSqlStmt
;
1185 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1186 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1187 } // wxDbTable::BuildSelectStmt()
1190 /********** wxDbTable::BuildUpdateStmt() **********/
1191 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1193 wxASSERT(!queryOnly
);
1197 wxString whereClause
;
1198 whereClause
.Empty();
1200 bool firstColumn
= true;
1202 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1203 pDb
->SQLTableName(tableName
.c_str()).c_str());
1205 // Append a list of columns to be updated
1207 for (i
= 0; i
< m_numCols
; i
++)
1209 // Only append Updateable columns
1210 if (colDefs
[i
].Updateable
)
1213 pSqlStmt
+= wxT(",");
1215 firstColumn
= false;
1217 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1218 // pSqlStmt += colDefs[i].ColName;
1219 pSqlStmt
+= wxT(" = ?");
1223 // Append the WHERE clause to the SQL UPDATE statement
1224 pSqlStmt
+= wxT(" WHERE ");
1225 switch(typeOfUpdate
)
1227 case DB_UPD_KEYFIELDS
:
1228 // If the datasource supports the ROWID column, build
1229 // the where on ROWID for efficiency purposes.
1230 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1231 if (CanUpdateByROWID())
1234 wxChar rowid
[wxDB_ROWID_LEN
+1];
1236 // Get the ROWID value. If not successful retreiving the ROWID,
1237 // simply fall down through the code and build the WHERE clause
1238 // based on the key fields.
1239 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1241 pSqlStmt
+= wxT("ROWID = '");
1243 pSqlStmt
+= wxT("'");
1247 // Unable to delete by ROWID, so build a WHERE
1248 // clause based on the keyfields.
1249 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1250 pSqlStmt
+= whereClause
;
1253 pSqlStmt
+= pWhereClause
;
1256 } // BuildUpdateStmt()
1259 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1260 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1262 wxString tempSqlStmt
;
1263 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1264 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1265 } // BuildUpdateStmt()
1268 /********** wxDbTable::BuildWhereClause() **********/
1269 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1270 const wxString
&qualTableName
, bool useLikeComparison
)
1272 * Note: BuildWhereClause() currently ignores timestamp columns.
1273 * They are not included as part of the where clause.
1276 bool moreThanOneColumn
= false;
1279 // Loop through the columns building a where clause as you go
1281 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1283 // Determine if this column should be included in the WHERE clause
1284 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1285 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1287 // Skip over timestamp columns
1288 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1290 // If there is more than 1 column, join them with the keyword "AND"
1291 if (moreThanOneColumn
)
1292 pWhereClause
+= wxT(" AND ");
1294 moreThanOneColumn
= true;
1296 // Concatenate where phrase for the column
1297 wxString tStr
= colDefs
[colNumber
].ColName
;
1299 if (qualTableName
.Length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1301 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1302 pWhereClause
+= wxT(".");
1304 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1306 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1307 pWhereClause
+= wxT(" LIKE ");
1309 pWhereClause
+= wxT(" = ");
1311 switch(colDefs
[colNumber
].SqlCtype
)
1317 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1318 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
);
1322 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1325 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1329 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1332 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1335 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1338 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1343 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1344 colNumber
,colDefs
[colNumber
].ColName
);
1345 wxFAIL_MSG(strMsg
.c_str());
1349 pWhereClause
+= colValue
;
1352 } // wxDbTable::BuildWhereClause()
1355 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1356 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1357 const wxString
&qualTableName
, bool useLikeComparison
)
1359 wxString tempSqlStmt
;
1360 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1361 wxStrcpy(pWhereClause
, tempSqlStmt
);
1362 } // wxDbTable::BuildWhereClause()
1365 /********** wxDbTable::GetRowNum() **********/
1366 UWORD
wxDbTable::GetRowNum(void)
1370 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1372 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1376 // Completed successfully
1377 return((UWORD
) rowNum
);
1379 } // wxDbTable::GetRowNum()
1382 /********** wxDbTable::CloseCursor() **********/
1383 bool wxDbTable::CloseCursor(HSTMT cursor
)
1385 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1386 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1388 // Completed successfully
1391 } // wxDbTable::CloseCursor()
1394 /********** wxDbTable::CreateTable() **********/
1395 bool wxDbTable::CreateTable(bool attemptDrop
)
1403 #ifdef DBDEBUG_CONSOLE
1404 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1408 if (attemptDrop
&& !DropTable())
1412 #ifdef DBDEBUG_CONSOLE
1413 for (i
= 0; i
< m_numCols
; i
++)
1415 // Exclude derived columns since they are NOT part of the base table
1416 if (colDefs
[i
].DerivedCol
)
1418 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1419 switch(colDefs
[i
].DbDataType
)
1421 case DB_DATA_TYPE_VARCHAR
:
1422 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1424 case DB_DATA_TYPE_MEMO
:
1425 cout
<< pDb
->GetTypeInfMemo().TypeName
;
1427 case DB_DATA_TYPE_INTEGER
:
1428 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1430 case DB_DATA_TYPE_FLOAT
:
1431 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1433 case DB_DATA_TYPE_DATE
:
1434 cout
<< pDb
->GetTypeInfDate().TypeName
;
1436 case DB_DATA_TYPE_BLOB
:
1437 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1444 // Build a CREATE TABLE string from the colDefs structure.
1445 bool needComma
= false;
1447 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1448 pDb
->SQLTableName(tableName
.c_str()).c_str());
1450 for (i
= 0; i
< m_numCols
; i
++)
1452 // Exclude derived columns since they are NOT part of the base table
1453 if (colDefs
[i
].DerivedCol
)
1457 sqlStmt
+= wxT(",");
1459 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1460 // sqlStmt += colDefs[i].ColName;
1461 sqlStmt
+= wxT(" ");
1463 switch(colDefs
[i
].DbDataType
)
1465 case DB_DATA_TYPE_VARCHAR
:
1466 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1468 case DB_DATA_TYPE_MEMO
:
1469 sqlStmt
+= pDb
->GetTypeInfMemo().TypeName
;
1471 case DB_DATA_TYPE_INTEGER
:
1472 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1474 case DB_DATA_TYPE_FLOAT
:
1475 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1477 case DB_DATA_TYPE_DATE
:
1478 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1480 case DB_DATA_TYPE_BLOB
:
1481 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1484 // For varchars, append the size of the string
1485 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1486 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1487 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1490 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1494 if (pDb
->Dbms() == dbmsDB2
||
1495 pDb
->Dbms() == dbmsMY_SQL
||
1496 pDb
->Dbms() == dbmsSYBASE_ASE
||
1497 pDb
->Dbms() == dbmsINTERBASE
||
1498 pDb
->Dbms() == dbmsFIREBIRD
||
1499 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1501 if (colDefs
[i
].KeyField
)
1503 sqlStmt
+= wxT(" NOT NULL");
1509 // If there is a primary key defined, include it in the create statement
1510 for (i
= j
= 0; i
< m_numCols
; i
++)
1512 if (colDefs
[i
].KeyField
)
1518 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1519 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1521 switch (pDb
->Dbms())
1525 case dbmsSYBASE_ASA
:
1526 case dbmsSYBASE_ASE
:
1530 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1531 sqlStmt
+= wxT(",PRIMARY KEY (");
1536 sqlStmt
+= wxT(",CONSTRAINT ");
1537 // DB2 is limited to 18 characters for index names
1538 if (pDb
->Dbms() == dbmsDB2
)
1540 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."));
1541 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1542 // sqlStmt += tableName.substr(0, 13);
1545 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1546 // sqlStmt += tableName;
1548 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1553 // List column name(s) of column(s) comprising the primary key
1554 for (i
= j
= 0; i
< m_numCols
; i
++)
1556 if (colDefs
[i
].KeyField
)
1558 if (j
++) // Multi part key, comma separate names
1559 sqlStmt
+= wxT(",");
1560 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1562 if (pDb
->Dbms() == dbmsMY_SQL
&&
1563 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1566 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1571 sqlStmt
+= wxT(")");
1573 if (pDb
->Dbms() == dbmsINFORMIX
||
1574 pDb
->Dbms() == dbmsSYBASE_ASA
||
1575 pDb
->Dbms() == dbmsSYBASE_ASE
)
1577 sqlStmt
+= wxT(" CONSTRAINT ");
1578 sqlStmt
+= pDb
->SQLTableName(tableName
);
1579 // sqlStmt += tableName;
1580 sqlStmt
+= wxT("_PIDX");
1583 // Append the closing parentheses for the create table statement
1584 sqlStmt
+= wxT(")");
1586 pDb
->WriteSqlLog(sqlStmt
);
1588 #ifdef DBDEBUG_CONSOLE
1589 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1592 // Execute the CREATE TABLE statement
1593 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1594 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1596 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1597 pDb
->RollbackTrans();
1602 // Commit the transaction and close the cursor
1603 if (!pDb
->CommitTrans())
1605 if (!CloseCursor(hstmt
))
1608 // Database table created successfully
1611 } // wxDbTable::CreateTable()
1614 /********** wxDbTable::DropTable() **********/
1615 bool wxDbTable::DropTable()
1617 // NOTE: This function returns true if the Table does not exist, but
1618 // only for identified databases. Code will need to be added
1619 // below for any other databases when those databases are defined
1620 // to handle this situation consistently
1624 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1625 pDb
->SQLTableName(tableName
.c_str()).c_str());
1627 pDb
->WriteSqlLog(sqlStmt
);
1629 #ifdef DBDEBUG_CONSOLE
1630 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1633 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1634 if (retcode
!= SQL_SUCCESS
)
1636 // Check for "Base table not found" error and ignore
1637 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1638 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1639 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1641 // Check for product specific error codes
1642 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1643 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1644 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1645 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1647 pDb
->DispNextError();
1648 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1649 pDb
->RollbackTrans();
1650 // CloseCursor(hstmt);
1656 // Commit the transaction and close the cursor
1657 if (! pDb
->CommitTrans())
1659 if (! CloseCursor(hstmt
))
1663 } // wxDbTable::DropTable()
1666 /********** wxDbTable::CreateIndex() **********/
1667 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1668 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1672 // Drop the index first
1673 if (attemptDrop
&& !DropIndex(indexName
))
1676 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1677 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1678 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1679 // table was created, then months later you determine that an additional index while
1680 // give better performance, so you want to add an index).
1682 // The following block of code will modify the column definition to make the column be
1683 // defined with the "NOT NULL" qualifier.
1684 if (pDb
->Dbms() == dbmsMY_SQL
)
1689 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1693 // Find the column definition that has the ColName that matches the
1694 // index column name. We need to do this to get the DB_DATA_TYPE of
1695 // the index column, as MySQL's syntax for the ALTER column requires
1697 while (!found
&& (j
< this->m_numCols
))
1699 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1707 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1708 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1714 // retcode is not used
1715 wxODBC_ERRORS retcode
;
1716 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1717 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1718 // This line is just here for debug checking of the value
1719 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1730 pDb
->RollbackTrans();
1735 // Build a CREATE INDEX statement
1736 sqlStmt
= wxT("CREATE ");
1738 sqlStmt
+= wxT("UNIQUE ");
1740 sqlStmt
+= wxT("INDEX ");
1741 sqlStmt
+= pDb
->SQLTableName(indexName
);
1742 sqlStmt
+= wxT(" ON ");
1744 sqlStmt
+= pDb
->SQLTableName(tableName
);
1745 // sqlStmt += tableName;
1746 sqlStmt
+= wxT(" (");
1748 // Append list of columns making up index
1750 for (i
= 0; i
< numIndexColumns
; i
++)
1752 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1753 // sqlStmt += pIndexDefs[i].ColName;
1755 // MySQL requires a key length on VARCHAR keys
1756 if ( pDb
->Dbms() == dbmsMY_SQL
)
1758 // Find the details on this column
1760 for ( j
= 0; j
< m_numCols
; ++j
)
1762 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1767 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1770 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1775 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1776 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1777 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1778 !(pDb
->Dbms() == dbmsPOSTGRES
))
1780 if (pIndexDefs
[i
].Ascending
)
1781 sqlStmt
+= wxT(" ASC");
1783 sqlStmt
+= wxT(" DESC");
1786 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1788 if ((i
+ 1) < numIndexColumns
)
1789 sqlStmt
+= wxT(",");
1792 // Append closing parentheses
1793 sqlStmt
+= wxT(")");
1795 pDb
->WriteSqlLog(sqlStmt
);
1797 #ifdef DBDEBUG_CONSOLE
1798 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1801 // Execute the CREATE INDEX statement
1802 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1803 if (retcode
!= SQL_SUCCESS
)
1805 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1806 pDb
->RollbackTrans();
1811 // Commit the transaction and close the cursor
1812 if (! pDb
->CommitTrans())
1814 if (! CloseCursor(hstmt
))
1817 // Index Created Successfully
1820 } // wxDbTable::CreateIndex()
1823 /********** wxDbTable::DropIndex() **********/
1824 bool wxDbTable::DropIndex(const wxString
&indexName
)
1826 // NOTE: This function returns true if the Index does not exist, but
1827 // only for identified databases. Code will need to be added
1828 // below for any other databases when those databases are defined
1829 // to handle this situation consistently
1833 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1834 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1835 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1836 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1837 pDb
->SQLTableName(tableName
.c_str()).c_str());
1838 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1839 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1840 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1841 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1842 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1843 pDb
->SQLTableName(indexName
.c_str()).c_str());
1845 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1846 pDb
->SQLTableName(indexName
.c_str()).c_str());
1848 pDb
->WriteSqlLog(sqlStmt
);
1850 #ifdef DBDEBUG_CONSOLE
1851 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1853 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1854 if (retcode
!= SQL_SUCCESS
)
1856 // Check for "Index not found" error and ignore
1857 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1858 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1860 // Check for product specific error codes
1861 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1862 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1863 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1864 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1865 (pDb
->Dbms() == dbmsMAXDB
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1866 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1867 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1868 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1869 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1872 pDb
->DispNextError();
1873 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1874 pDb
->RollbackTrans();
1881 // Commit the transaction and close the cursor
1882 if (! pDb
->CommitTrans())
1884 if (! CloseCursor(hstmt
))
1888 } // wxDbTable::DropIndex()
1891 /********** wxDbTable::SetOrderByColNums() **********/
1892 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1894 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1900 va_start(argptr
, first
); /* Initialize variable arguments. */
1901 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1903 // Make sure the passed in column number
1904 // is within the valid range of columns
1906 // Valid columns are 0 thru m_numCols-1
1907 if (colNumber
>= m_numCols
|| colNumber
< 0)
1913 if (colNumber
!= first
)
1914 tempStr
+= wxT(",");
1916 tempStr
+= colDefs
[colNumber
].ColName
;
1917 colNumber
= va_arg (argptr
, int);
1919 va_end (argptr
); /* Reset variable arguments. */
1921 SetOrderByClause(tempStr
);
1924 } // wxDbTable::SetOrderByColNums()
1927 /********** wxDbTable::Insert() **********/
1928 int wxDbTable::Insert(void)
1930 wxASSERT(!queryOnly
);
1931 if (queryOnly
|| !insertable
)
1936 // Insert the record by executing the already prepared insert statement
1938 retcode
= SQLExecute(hstmtInsert
);
1939 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1940 retcode
!= SQL_NEED_DATA
)
1942 // Check to see if integrity constraint was violated
1943 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1944 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1945 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1948 pDb
->DispNextError();
1949 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1953 if (retcode
== SQL_NEED_DATA
)
1956 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1957 while (retcode
== SQL_NEED_DATA
)
1959 // Find the parameter
1961 for (i
=0; i
< m_numCols
; i
++)
1963 if (colDefs
[i
].PtrDataObj
== pParmID
)
1965 // We found it. Store the parameter.
1966 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1967 if (retcode
!= SQL_SUCCESS
)
1969 pDb
->DispNextError();
1970 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1976 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1977 if (retcode
!= SQL_SUCCESS
&&
1978 retcode
!= SQL_SUCCESS_WITH_INFO
)
1980 // record was not inserted
1981 pDb
->DispNextError();
1982 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1988 // Record inserted into the datasource successfully
1991 } // wxDbTable::Insert()
1994 /********** wxDbTable::Update() **********/
1995 bool wxDbTable::Update(void)
1997 wxASSERT(!queryOnly
);
2003 // Build the SQL UPDATE statement
2004 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
2006 pDb
->WriteSqlLog(sqlStmt
);
2008 #ifdef DBDEBUG_CONSOLE
2009 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2012 // Execute the SQL UPDATE statement
2013 return(execUpdate(sqlStmt
));
2015 } // wxDbTable::Update()
2018 /********** wxDbTable::Update(pSqlStmt) **********/
2019 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2021 wxASSERT(!queryOnly
);
2025 pDb
->WriteSqlLog(pSqlStmt
);
2027 return(execUpdate(pSqlStmt
));
2029 } // wxDbTable::Update(pSqlStmt)
2032 /********** wxDbTable::UpdateWhere() **********/
2033 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2035 wxASSERT(!queryOnly
);
2041 // Build the SQL UPDATE statement
2042 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2044 pDb
->WriteSqlLog(sqlStmt
);
2046 #ifdef DBDEBUG_CONSOLE
2047 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2050 // Execute the SQL UPDATE statement
2051 return(execUpdate(sqlStmt
));
2053 } // wxDbTable::UpdateWhere()
2056 /********** wxDbTable::Delete() **********/
2057 bool wxDbTable::Delete(void)
2059 wxASSERT(!queryOnly
);
2066 // Build the SQL DELETE statement
2067 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2069 pDb
->WriteSqlLog(sqlStmt
);
2071 // Execute the SQL DELETE statement
2072 return(execDelete(sqlStmt
));
2074 } // wxDbTable::Delete()
2077 /********** wxDbTable::DeleteWhere() **********/
2078 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2080 wxASSERT(!queryOnly
);
2087 // Build the SQL DELETE statement
2088 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2090 pDb
->WriteSqlLog(sqlStmt
);
2092 // Execute the SQL DELETE statement
2093 return(execDelete(sqlStmt
));
2095 } // wxDbTable::DeleteWhere()
2098 /********** wxDbTable::DeleteMatching() **********/
2099 bool wxDbTable::DeleteMatching(void)
2101 wxASSERT(!queryOnly
);
2108 // Build the SQL DELETE statement
2109 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2111 pDb
->WriteSqlLog(sqlStmt
);
2113 // Execute the SQL DELETE statement
2114 return(execDelete(sqlStmt
));
2116 } // wxDbTable::DeleteMatching()
2119 /********** wxDbTable::IsColNull() **********/
2120 bool wxDbTable::IsColNull(UWORD colNumber
) const
2123 This logic is just not right. It would indicate true
2124 if a numeric field were set to a value of 0.
2126 switch(colDefs[colNumber].SqlCtype)
2130 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2131 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2133 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2135 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2137 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2139 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2141 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2143 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2144 case SQL_C_TIMESTAMP:
2145 TIMESTAMP_STRUCT *pDt;
2146 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2147 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2155 return (colDefs
[colNumber
].Null
);
2156 } // wxDbTable::IsColNull()
2159 /********** wxDbTable::CanSelectForUpdate() **********/
2160 bool wxDbTable::CanSelectForUpdate(void)
2165 if (pDb
->Dbms() == dbmsMY_SQL
)
2168 if ((pDb
->Dbms() == dbmsORACLE
) ||
2169 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2174 } // wxDbTable::CanSelectForUpdate()
2177 /********** wxDbTable::CanUpdateByROWID() **********/
2178 bool wxDbTable::CanUpdateByROWID(void)
2181 * NOTE: Returning false for now until this can be debugged,
2182 * as the ROWID is not getting updated correctly
2186 if (pDb->Dbms() == dbmsORACLE)
2191 } // wxDbTable::CanUpdateByROWID()
2194 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2195 bool wxDbTable::IsCursorClosedOnCommit(void)
2197 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2202 } // wxDbTable::IsCursorClosedOnCommit()
2206 /********** wxDbTable::ClearMemberVar() **********/
2207 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2209 wxASSERT(colNumber
< m_numCols
);
2211 switch(colDefs
[colNumber
].SqlCtype
)
2217 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2218 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2221 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2224 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2228 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2231 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2234 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2237 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2239 case SQL_C_TIMESTAMP
:
2240 TIMESTAMP_STRUCT
*pDt
;
2241 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2253 SetColNull(colNumber
);
2254 } // wxDbTable::ClearMemberVar()
2257 /********** wxDbTable::ClearMemberVars() **********/
2258 void wxDbTable::ClearMemberVars(bool setToNull
)
2262 // Loop through the columns setting each member variable to zero
2263 for (i
=0; i
< m_numCols
; i
++)
2264 ClearMemberVar((UWORD
)i
,setToNull
);
2266 } // wxDbTable::ClearMemberVars()
2269 /********** wxDbTable::SetQueryTimeout() **********/
2270 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2272 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2273 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2274 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2275 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2276 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2277 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2278 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2279 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2281 // Completed Successfully
2284 } // wxDbTable::SetQueryTimeout()
2287 /********** wxDbTable::SetColDefs() **********/
2288 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2289 SWORD cType
, int size
, bool keyField
, bool updateable
,
2290 bool insertAllowed
, bool derivedColumn
)
2294 if (index
>= m_numCols
) // Columns numbers are zero based....
2296 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
);
2302 if (!colDefs
) // May happen if the database connection fails
2305 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2307 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2308 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2310 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2311 fieldName
.c_str(),colDefs
[index
].ColName
);
2316 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2318 colDefs
[index
].DbDataType
= dataType
;
2319 colDefs
[index
].PtrDataObj
= pData
;
2320 colDefs
[index
].SqlCtype
= cType
;
2321 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2322 colDefs
[index
].KeyField
= keyField
;
2323 colDefs
[index
].DerivedCol
= derivedColumn
;
2324 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2327 colDefs
[index
].Updateable
= false;
2328 colDefs
[index
].InsertAllowed
= false;
2332 colDefs
[index
].Updateable
= updateable
;
2333 colDefs
[index
].InsertAllowed
= insertAllowed
;
2336 colDefs
[index
].Null
= false;
2340 } // wxDbTable::SetColDefs()
2343 /********** wxDbTable::SetColDefs() **********/
2344 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2347 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2353 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2355 for (index
= 0; index
< numCols
; index
++)
2357 // Process the fields
2358 switch (pColInfs
[index
].dbDataType
)
2360 case DB_DATA_TYPE_VARCHAR
:
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_MEMO
:
2366 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2367 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2368 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2370 case DB_DATA_TYPE_INTEGER
:
2371 // Can be long or short
2372 if (pColInfs
[index
].bufferSize
== sizeof(long))
2374 pColDataPtrs
[index
].PtrDataObj
= new long;
2375 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2376 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2380 pColDataPtrs
[index
].PtrDataObj
= new short;
2381 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2382 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2385 case DB_DATA_TYPE_FLOAT
:
2386 // Can be float or double
2387 if (pColInfs
[index
].bufferSize
== sizeof(float))
2389 pColDataPtrs
[index
].PtrDataObj
= new float;
2390 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2391 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2395 pColDataPtrs
[index
].PtrDataObj
= new double;
2396 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2397 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2400 case DB_DATA_TYPE_DATE
:
2401 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2402 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2403 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2405 case DB_DATA_TYPE_BLOB
:
2406 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2407 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2408 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2409 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2412 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2413 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2416 // Unable to build all the column definitions, as either one of
2417 // the calls to "new" failed above, or there was a BLOB field
2418 // to have a column definition for. If BLOBs are to be used,
2419 // the other form of ::SetColDefs() must be used, as it is impossible
2420 // to know the maximum size to create the PtrDataObj to be.
2421 delete [] pColDataPtrs
;
2427 return (pColDataPtrs
);
2429 } // wxDbTable::SetColDefs()
2432 /********** wxDbTable::SetCursor() **********/
2433 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2435 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2436 hstmt
= *hstmtDefault
;
2438 hstmt
= *hstmtActivate
;
2440 } // wxDbTable::SetCursor()
2443 /********** wxDbTable::Count(const wxString &) **********/
2444 ULONG
wxDbTable::Count(const wxString
&args
)
2450 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2451 sqlStmt
= wxT("SELECT COUNT(");
2453 sqlStmt
+= wxT(") FROM ");
2454 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2455 // sqlStmt += queryTableName;
2456 #if wxODBC_BACKWARD_COMPATABILITY
2457 if (from
&& wxStrlen(from
))
2463 // Add the where clause if one is provided
2464 #if wxODBC_BACKWARD_COMPATABILITY
2465 if (where
&& wxStrlen(where
))
2470 sqlStmt
+= wxT(" WHERE ");
2474 pDb
->WriteSqlLog(sqlStmt
);
2476 // Initialize the Count cursor if it's not already initialized
2479 hstmtCount
= GetNewCursor(false,false);
2480 wxASSERT(hstmtCount
);
2485 // Execute the SQL statement
2486 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2488 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2493 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2495 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2499 // Obtain the result
2500 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2502 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2507 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2508 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2510 // Return the record count
2513 } // wxDbTable::Count()
2516 /********** wxDbTable::Refresh() **********/
2517 bool wxDbTable::Refresh(void)
2521 // Switch to the internal cursor so any active cursors are not corrupted
2522 HSTMT currCursor
= GetCursor();
2523 hstmt
= hstmtInternal
;
2524 #if wxODBC_BACKWARD_COMPATABILITY
2525 // Save the where and order by clauses
2526 wxChar
*saveWhere
= where
;
2527 wxChar
*saveOrderBy
= orderBy
;
2529 wxString saveWhere
= where
;
2530 wxString saveOrderBy
= orderBy
;
2532 // Build a where clause to refetch the record with. Try and use the
2533 // ROWID if it's available, ow use the key fields.
2534 wxString whereClause
;
2535 whereClause
.Empty();
2537 if (CanUpdateByROWID())
2540 wxChar rowid
[wxDB_ROWID_LEN
+1];
2542 // Get the ROWID value. If not successful retreiving the ROWID,
2543 // simply fall down through the code and build the WHERE clause
2544 // based on the key fields.
2545 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2547 whereClause
+= pDb
->SQLTableName(queryTableName
);
2548 // whereClause += queryTableName;
2549 whereClause
+= wxT(".ROWID = '");
2550 whereClause
+= rowid
;
2551 whereClause
+= wxT("'");
2555 // If unable to use the ROWID, build a where clause from the keyfields
2556 if (wxStrlen(whereClause
) == 0)
2557 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2559 // Requery the record
2560 where
= whereClause
;
2565 if (result
&& !GetNext())
2568 // Switch back to original cursor
2569 SetCursor(&currCursor
);
2571 // Free the internal cursor
2572 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2573 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2575 // Restore the original where and order by clauses
2577 orderBy
= saveOrderBy
;
2581 } // wxDbTable::Refresh()
2584 /********** wxDbTable::SetColNull() **********/
2585 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2587 if (colNumber
< m_numCols
)
2589 colDefs
[colNumber
].Null
= set
;
2590 if (set
) // Blank out the values in the member variable
2591 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2593 setCbValueForColumn(colNumber
);
2600 } // wxDbTable::SetColNull()
2603 /********** wxDbTable::SetColNull() **********/
2604 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2607 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2609 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2613 if (colNumber
< m_numCols
)
2615 colDefs
[colNumber
].Null
= set
;
2616 if (set
) // Blank out the values in the member variable
2617 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2619 setCbValueForColumn(colNumber
);
2626 } // wxDbTable::SetColNull()
2629 /********** wxDbTable::GetNewCursor() **********/
2630 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2632 HSTMT
*newHSTMT
= new HSTMT
;
2637 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2639 pDb
->DispAllErrors(henv
, hdbc
);
2644 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2646 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2653 if (!bindCols(*newHSTMT
))
2661 SetCursor(newHSTMT
);
2665 } // wxDbTable::GetNewCursor()
2668 /********** wxDbTable::DeleteCursor() **********/
2669 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2673 if (!hstmtDel
) // Cursor already deleted
2677 ODBC 3.0 says to use this form
2678 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2681 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2683 pDb
->DispAllErrors(henv
, hdbc
);
2691 } // wxDbTable::DeleteCursor()
2693 //////////////////////////////////////////////////////////////
2694 // wxDbGrid support functions
2695 //////////////////////////////////////////////////////////////
2697 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2699 if (!m_hstmtGridQuery
)
2701 m_hstmtGridQuery
= GetNewCursor(false,false);
2702 if (!bindCols(*m_hstmtGridQuery
))
2706 m_rowmode
= rowmode
;
2709 case WX_ROW_MODE_QUERY
:
2710 SetCursor(m_hstmtGridQuery
);
2712 case WX_ROW_MODE_INDIVIDUAL
:
2713 SetCursor(hstmtDefault
);
2718 } // wxDbTable::SetRowMode()
2721 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2724 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2726 switch (colDefs
[colNumber
].SqlCtype
)
2729 #if defined(SQL_WCHAR)
2732 #if defined(SQL_WVARCHAR)
2738 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2742 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2746 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2749 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2752 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2754 case SQL_C_UTINYINT
:
2755 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2758 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2761 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2764 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2766 case SQL_C_TIMESTAMP
:
2767 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2770 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2777 } // wxDbTable::GetCol()
2780 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2782 //FIXME: Add proper wxDateTime support to wxVariant..
2785 SetColNull((UWORD
)colNumber
, val
.IsNull());
2789 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2790 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2791 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2793 //Returns null if invalid!
2794 if (!dateval
.ParseDate(val
.GetString()))
2795 SetColNull((UWORD
)colNumber
, true);
2798 switch (colDefs
[colNumber
].SqlCtype
)
2801 #if defined(SQL_WCHAR)
2804 #if defined(SQL_WVARCHAR)
2810 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2811 val
.GetString().c_str(),
2812 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2816 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2820 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2823 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2826 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2828 case SQL_C_UTINYINT
:
2829 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2832 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2834 //FIXME: Add proper wxDateTime support to wxVariant..
2837 DATE_STRUCT
*dataptr
=
2838 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2840 dataptr
->year
= (SWORD
)dateval
.GetYear();
2841 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2842 dataptr
->day
= (UWORD
)dateval
.GetDay();
2847 TIME_STRUCT
*dataptr
=
2848 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2850 dataptr
->hour
= dateval
.GetHour();
2851 dataptr
->minute
= dateval
.GetMinute();
2852 dataptr
->second
= dateval
.GetSecond();
2855 case SQL_C_TIMESTAMP
:
2857 TIMESTAMP_STRUCT
*dataptr
=
2858 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2859 dataptr
->year
= (SWORD
)dateval
.GetYear();
2860 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2861 dataptr
->day
= (UWORD
)dateval
.GetDay();
2863 dataptr
->hour
= dateval
.GetHour();
2864 dataptr
->minute
= dateval
.GetMinute();
2865 dataptr
->second
= dateval
.GetSecond();
2869 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2874 } // if (!val.IsNull())
2875 } // wxDbTable::SetCol()
2878 GenericKey
wxDbTable::GetKey()
2883 blk
= malloc(m_keysize
);
2884 blkptr
= (wxChar
*) blk
;
2887 for (i
=0; i
< m_numCols
; i
++)
2889 if (colDefs
[i
].KeyField
)
2891 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2892 blkptr
+= colDefs
[i
].SzDataObj
;
2896 GenericKey k
= GenericKey(blk
, m_keysize
);
2900 } // wxDbTable::GetKey()
2903 void wxDbTable::SetKey(const GenericKey
& k
)
2909 blkptr
= (wxChar
*)blk
;
2912 for (i
=0; i
< m_numCols
; i
++)
2914 if (colDefs
[i
].KeyField
)
2916 SetColNull((UWORD
)i
, false);
2917 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2918 blkptr
+= colDefs
[i
].SzDataObj
;
2921 } // wxDbTable::SetKey()
2924 #endif // wxUSE_ODBC