1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/dbtable.cpp
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence
12 ///////////////////////////////////////////////////////////////////////////////
14 #include "wx/wxprec.h"
23 #include "wx/object.h"
25 #include "wx/string.h"
31 #ifdef DBDEBUG_CONSOLE
32 #include "wx/ioswrap.h"
35 #include "wx/filefn.h"
41 #include "wx/dbtable.h"
43 // FIXME-UTF8: get rid of this after switching to Unicode-only builds:
45 #define WXSQLCAST(s) ((SQLTCHAR FAR *)(wchar_t*)(s).wchar_str())
47 #define WXSQLCAST(s) ((SQLTCHAR FAR *)(char*)(s).char_str())
50 ULONG lastTableID
= 0;
54 #include "wx/thread.h"
57 wxCriticalSection csTablesInUse
;
61 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
63 while ( (*target
++ = *source
++) != '\0' && --n
!= 0 )
71 /********** wxDbColDef::wxDbColDef() Constructor **********/
72 wxDbColDef::wxDbColDef()
78 bool wxDbColDef::Initialize()
81 DbDataType
= DB_DATA_TYPE_INTEGER
;
82 SqlCtype
= SQL_C_LONG
;
87 InsertAllowed
= false;
94 } // wxDbColDef::Initialize()
97 /********** wxDbTable::wxDbTable() Constructor **********/
98 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
99 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
101 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
103 } // wxDbTable::wxDbTable()
106 /********** wxDbTable::~wxDbTable() **********/
107 wxDbTable::~wxDbTable()
110 } // wxDbTable::~wxDbTable()
113 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
114 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
116 // Initializing member variables
117 pDb
= pwxDb
; // Pointer to the wxDb object
121 m_hstmtGridQuery
= 0;
122 hstmtDefault
= 0; // Initialized below
123 hstmtCount
= 0; // Initialized first time it is needed
130 m_numCols
= numColumns
; // Number of columns in the table
131 where
.Empty(); // Where clause
132 orderBy
.Empty(); // Order By clause
133 from
.Empty(); // From clause
134 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
139 queryTableName
.Empty();
141 wxASSERT(tblName
.length());
147 tableName
= tblName
; // Table Name
148 if ((pDb
->Dbms() == dbmsORACLE
) ||
149 (pDb
->Dbms() == dbmsFIREBIRD
) ||
150 (pDb
->Dbms() == dbmsINTERBASE
))
151 tableName
= tableName
.Upper();
153 if (tblPath
.length())
154 tablePath
= tblPath
; // Table Path - used for dBase files
158 if (qryTblName
.length()) // Name of the table/view to query
159 queryTableName
= qryTblName
;
161 queryTableName
= tblName
;
163 if ((pDb
->Dbms() == dbmsORACLE
) ||
164 (pDb
->Dbms() == dbmsFIREBIRD
) ||
165 (pDb
->Dbms() == dbmsINTERBASE
))
166 queryTableName
= queryTableName
.Upper();
168 pDb
->incrementTableCount();
171 tableID
= ++lastTableID
;
172 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"),
173 tblName
.c_str(), tableID
, wx_static_cast(void*, pDb
));
176 wxTablesInUse
*tableInUse
;
177 tableInUse
= new wxTablesInUse();
178 tableInUse
->tableName
= tblName
;
179 tableInUse
->tableID
= tableID
;
180 tableInUse
->pDb
= pDb
;
182 wxCriticalSectionLocker
lock(csTablesInUse
);
183 TablesInUse
.Append(tableInUse
);
189 // Grab the HENV and HDBC from the wxDb object
190 henv
= pDb
->GetHENV();
191 hdbc
= pDb
->GetHDBC();
193 // Allocate space for column definitions
195 colDefs
= new wxDbColDef
[m_numCols
]; // Points to the first column definition
197 // Allocate statement handles for the table
200 // Allocate a separate statement handle for performing inserts
201 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
202 pDb
->DispAllErrors(henv
, hdbc
);
203 // Allocate a separate statement handle for performing deletes
204 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
205 pDb
->DispAllErrors(henv
, hdbc
);
206 // Allocate a separate statement handle for performing updates
207 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
208 pDb
->DispAllErrors(henv
, hdbc
);
210 // Allocate a separate statement handle for internal use
211 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
212 pDb
->DispAllErrors(henv
, hdbc
);
214 // Set the cursor type for the statement handles
215 cursorType
= SQL_CURSOR_STATIC
;
217 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
219 // Check to see if cursor type is supported
220 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
221 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
223 // Datasource does not support static cursors. Driver
224 // will substitute a cursor type. Call SQLGetStmtOption()
225 // to determine which cursor type was selected.
226 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
227 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
228 #ifdef DBDEBUG_CONSOLE
229 cout
<< wxT("Static cursor changed to: ");
232 case SQL_CURSOR_FORWARD_ONLY
:
233 cout
<< wxT("Forward Only");
235 case SQL_CURSOR_STATIC
:
236 cout
<< wxT("Static");
238 case SQL_CURSOR_KEYSET_DRIVEN
:
239 cout
<< wxT("Keyset Driven");
241 case SQL_CURSOR_DYNAMIC
:
242 cout
<< wxT("Dynamic");
245 cout
<< endl
<< endl
;
248 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
250 // Force the use of a forward only cursor...
251 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
252 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
254 // Should never happen
255 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
262 pDb
->DispNextError();
263 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
266 #ifdef DBDEBUG_CONSOLE
268 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
273 // Set the cursor type for the INSERT statement handle
274 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
275 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
276 // Set the cursor type for the DELETE statement handle
277 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
278 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
279 // Set the cursor type for the UPDATE statement handle
280 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
281 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
284 // Make the default cursor the active cursor
285 hstmtDefault
= GetNewCursor(false,false);
286 wxASSERT(hstmtDefault
);
287 hstmt
= *hstmtDefault
;
291 } // wxDbTable::initialize()
294 void wxDbTable::cleanup()
299 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"),
300 tableName
.c_str(), tableID
, wx_static_cast(void*, pDb
));
309 wxList::compatibility_iterator pNode
;
311 wxCriticalSectionLocker
lock(csTablesInUse
);
312 pNode
= TablesInUse
.GetFirst();
313 while (!found
&& pNode
)
315 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
318 delete (wxTablesInUse
*)pNode
->GetData();
319 TablesInUse
.Erase(pNode
);
322 pNode
= pNode
->GetNext();
328 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
329 wxLogDebug (msg
,wxT("NOTICE..."));
334 // Decrement the wxDb table count
336 pDb
->decrementTableCount();
338 // Delete memory allocated for column definitions
342 // Free statement handles
348 ODBC 3.0 says to use this form
349 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
351 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
352 pDb
->DispAllErrors(henv
, hdbc
);
358 ODBC 3.0 says to use this form
359 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
361 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
362 pDb
->DispAllErrors(henv
, hdbc
);
368 ODBC 3.0 says to use this form
369 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
371 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
372 pDb
->DispAllErrors(henv
, hdbc
);
378 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
379 pDb
->DispAllErrors(henv
, hdbc
);
382 // Delete dynamically allocated cursors
384 DeleteCursor(hstmtDefault
);
387 DeleteCursor(hstmtCount
);
389 if (m_hstmtGridQuery
)
390 DeleteCursor(m_hstmtGridQuery
);
392 } // wxDbTable::cleanup()
395 /***************************** PRIVATE FUNCTIONS *****************************/
398 void wxDbTable::setCbValueForColumn(int columnIndex
)
400 switch(colDefs
[columnIndex
].DbDataType
)
402 case DB_DATA_TYPE_VARCHAR
:
403 case DB_DATA_TYPE_MEMO
:
404 if (colDefs
[columnIndex
].Null
)
405 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
407 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
409 case DB_DATA_TYPE_INTEGER
:
410 if (colDefs
[columnIndex
].Null
)
411 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
413 colDefs
[columnIndex
].CbValue
= 0;
415 case DB_DATA_TYPE_FLOAT
:
416 if (colDefs
[columnIndex
].Null
)
417 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
419 colDefs
[columnIndex
].CbValue
= 0;
421 case DB_DATA_TYPE_DATE
:
422 if (colDefs
[columnIndex
].Null
)
423 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
425 colDefs
[columnIndex
].CbValue
= 0;
427 case DB_DATA_TYPE_BLOB
:
428 if (colDefs
[columnIndex
].Null
)
429 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
431 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
432 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
434 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
439 /********** wxDbTable::bindParams() **********/
440 bool wxDbTable::bindParams(bool forUpdate
)
442 wxASSERT(!queryOnly
);
447 SDWORD precision
= 0;
450 // Bind each column of the table that should be bound
451 // to a parameter marker
455 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
459 if (!colDefs
[i
].Updateable
)
464 if (!colDefs
[i
].InsertAllowed
)
468 switch(colDefs
[i
].DbDataType
)
470 case DB_DATA_TYPE_VARCHAR
:
471 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
472 precision
= colDefs
[i
].SzDataObj
;
475 case DB_DATA_TYPE_MEMO
:
476 fSqlType
= pDb
->GetTypeInfMemo().FsqlType
;
477 precision
= colDefs
[i
].SzDataObj
;
480 case DB_DATA_TYPE_INTEGER
:
481 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
482 precision
= pDb
->GetTypeInfInteger().Precision
;
485 case DB_DATA_TYPE_FLOAT
:
486 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
487 precision
= pDb
->GetTypeInfFloat().Precision
;
488 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
489 // SQL Sybase Anywhere v5.5 returned a negative number for the
490 // MaxScale. This caused ODBC to kick out an error on ibscale.
491 // I check for this here and set the scale = precision.
493 // scale = (short) precision;
495 case DB_DATA_TYPE_DATE
:
496 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
497 precision
= pDb
->GetTypeInfDate().Precision
;
500 case DB_DATA_TYPE_BLOB
:
501 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
502 precision
= colDefs
[i
].SzDataObj
;
507 setCbValueForColumn(i
);
511 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
512 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
513 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
515 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
520 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
521 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
522 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
524 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
529 // Completed successfully
532 } // wxDbTable::bindParams()
535 /********** wxDbTable::bindInsertParams() **********/
536 bool wxDbTable::bindInsertParams(void)
538 return bindParams(false);
539 } // wxDbTable::bindInsertParams()
542 /********** wxDbTable::bindUpdateParams() **********/
543 bool wxDbTable::bindUpdateParams(void)
545 return bindParams(true);
546 } // wxDbTable::bindUpdateParams()
549 /********** wxDbTable::bindCols() **********/
550 bool wxDbTable::bindCols(HSTMT cursor
)
552 // Bind each column of the table to a memory address for fetching data
554 for (i
= 0; i
< m_numCols
; i
++)
556 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
557 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValueCol
) != SQL_SUCCESS
)
558 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
561 // Completed successfully
563 } // wxDbTable::bindCols()
566 /********** wxDbTable::getRec() **********/
567 bool wxDbTable::getRec(UWORD fetchType
)
571 if (!pDb
->FwdOnlyCursors())
573 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
574 SQLULEN cRowsFetched
;
577 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
578 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
580 if (retcode
== SQL_NO_DATA_FOUND
)
583 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
587 // Set the Null member variable to indicate the Null state
588 // of each column just read in.
590 for (i
= 0; i
< m_numCols
; i
++)
591 colDefs
[i
].Null
= (colDefs
[i
].CbValueCol
== SQL_NULL_DATA
);
596 // Fetch the next record from the record set
597 retcode
= SQLFetch(hstmt
);
598 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
600 if (retcode
== SQL_NO_DATA_FOUND
)
603 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
607 // Set the Null member variable to indicate the Null state
608 // of each column just read in.
610 for (i
= 0; i
< m_numCols
; i
++)
611 colDefs
[i
].Null
= (colDefs
[i
].CbValueCol
== SQL_NULL_DATA
);
615 // Completed successfully
618 } // wxDbTable::getRec()
621 /********** wxDbTable::execDelete() **********/
622 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
626 // Execute the DELETE statement
627 retcode
= SQLExecDirect(hstmtDelete
, WXSQLCAST(pSqlStmt
), SQL_NTS
);
629 if (retcode
== SQL_SUCCESS
||
630 retcode
== SQL_NO_DATA_FOUND
||
631 retcode
== SQL_SUCCESS_WITH_INFO
)
633 // Record deleted successfully
637 // Problem deleting record
638 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
640 } // wxDbTable::execDelete()
643 /********** wxDbTable::execUpdate() **********/
644 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
648 // Execute the UPDATE statement
649 retcode
= SQLExecDirect(hstmtUpdate
, WXSQLCAST(pSqlStmt
), SQL_NTS
);
651 if (retcode
== SQL_SUCCESS
||
652 retcode
== SQL_NO_DATA_FOUND
||
653 retcode
== SQL_SUCCESS_WITH_INFO
)
655 // Record updated successfully
658 else if (retcode
== SQL_NEED_DATA
)
661 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
662 while (retcode
== SQL_NEED_DATA
)
664 // Find the parameter
666 for (i
=0; i
< m_numCols
; i
++)
668 if (colDefs
[i
].PtrDataObj
== pParmID
)
670 // We found it. Store the parameter.
671 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
672 if (retcode
!= SQL_SUCCESS
)
674 pDb
->DispNextError();
675 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
680 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
682 if (retcode
== SQL_SUCCESS
||
683 retcode
== SQL_NO_DATA_FOUND
||
684 retcode
== SQL_SUCCESS_WITH_INFO
)
686 // Record updated successfully
691 // Problem updating record
692 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
694 } // wxDbTable::execUpdate()
697 /********** wxDbTable::query() **********/
698 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
703 // The user may wish to select for update, but the DBMS may not be capable
704 selectForUpdate
= CanSelectForUpdate();
706 selectForUpdate
= false;
708 // Set the SQL SELECT string
709 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
710 { // so generate a select statement.
711 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
712 pDb
->WriteSqlLog(sqlStmt
);
715 // Make sure the cursor is closed first
716 if (!CloseCursor(hstmt
))
719 // Execute the SQL SELECT statement
721 retcode
= SQLExecDirect(hstmt
, (queryType
== DB_SELECT_STATEMENT
? WXSQLCAST(pSqlStmt
) : WXSQLCAST(sqlStmt
)), SQL_NTS
);
722 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
723 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
725 // Completed successfully
728 } // wxDbTable::query()
731 /***************************** PUBLIC FUNCTIONS *****************************/
734 /********** wxDbTable::Open() **********/
735 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
744 // Calculate the maximum size of the concatenated
745 // keys for use with wxDbGrid
747 for (i
=0; i
< m_numCols
; i
++)
749 if (colDefs
[i
].KeyField
)
751 m_keysize
+= colDefs
[i
].SzDataObj
;
758 if (checkTableExists
)
760 if (pDb
->Dbms() == dbmsPOSTGRES
)
761 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
763 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
766 // Verify that the table exists in the database
769 s
= wxT("Table/view does not exist in the database");
770 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
771 s
+= wxT(", or you have no permissions.\n");
775 else if (checkPrivileges
)
777 // Verify the user has rights to access the table.
778 bool hasPrivs
wxDUMMY_INITIALIZE(true);
780 if (pDb
->Dbms() == dbmsPOSTGRES
)
781 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
783 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
786 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
793 if (!tablePath
.empty())
794 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
796 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
799 pDb
->LogError(p
.GetData());
804 // Bind the member variables for field exchange between
805 // the wxDbTable object and the ODBC record.
808 if (!bindInsertParams()) // Inserts
811 if (!bindUpdateParams()) // Updates
815 if (!bindCols(*hstmtDefault
)) // Selects
818 if (!bindCols(hstmtInternal
)) // Internal use only
822 * Do NOT bind the hstmtCount cursor!!!
825 // Build an insert statement using parameter markers
826 if (!queryOnly
&& m_numCols
> 0)
828 bool needComma
= false;
829 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
830 pDb
->SQLTableName(tableName
.c_str()).c_str());
831 for (i
= 0; i
< m_numCols
; i
++)
833 if (! colDefs
[i
].InsertAllowed
)
837 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
841 sqlStmt
+= wxT(") VALUES (");
843 int insertableCount
= 0;
845 for (i
= 0; i
< m_numCols
; i
++)
847 if (! colDefs
[i
].InsertAllowed
)
857 // Prepare the insert statement for execution
860 if (SQLPrepare(hstmtInsert
, WXSQLCAST(sqlStmt
), SQL_NTS
) != SQL_SUCCESS
)
861 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
867 // Completed successfully
870 } // wxDbTable::Open()
873 /********** wxDbTable::Query() **********/
874 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
877 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
879 } // wxDbTable::Query()
882 /********** wxDbTable::QueryBySqlStmt() **********/
883 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
885 pDb
->WriteSqlLog(pSqlStmt
);
887 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
889 } // wxDbTable::QueryBySqlStmt()
892 /********** wxDbTable::QueryMatching() **********/
893 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
896 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
898 } // wxDbTable::QueryMatching()
901 /********** wxDbTable::QueryOnKeyFields() **********/
902 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
905 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
907 } // wxDbTable::QueryOnKeyFields()
910 /********** wxDbTable::GetPrev() **********/
911 bool wxDbTable::GetPrev(void)
913 if (pDb
->FwdOnlyCursors())
915 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
919 return(getRec(SQL_FETCH_PRIOR
));
921 } // wxDbTable::GetPrev()
924 /********** wxDbTable::operator-- **********/
925 bool wxDbTable::operator--(int)
927 if (pDb
->FwdOnlyCursors())
929 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
933 return(getRec(SQL_FETCH_PRIOR
));
935 } // wxDbTable::operator--
938 /********** wxDbTable::GetFirst() **********/
939 bool wxDbTable::GetFirst(void)
941 if (pDb
->FwdOnlyCursors())
943 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
947 return(getRec(SQL_FETCH_FIRST
));
949 } // wxDbTable::GetFirst()
952 /********** wxDbTable::GetLast() **********/
953 bool wxDbTable::GetLast(void)
955 if (pDb
->FwdOnlyCursors())
957 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
961 return(getRec(SQL_FETCH_LAST
));
963 } // wxDbTable::GetLast()
966 /********** wxDbTable::BuildDeleteStmt() **********/
967 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
969 wxASSERT(!queryOnly
);
973 wxString whereClause
;
977 // Handle the case of DeleteWhere() and the where clause is blank. It should
978 // delete all records from the database in this case.
979 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.length() == 0))
981 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
982 pDb
->SQLTableName(tableName
.c_str()).c_str());
986 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
987 pDb
->SQLTableName(tableName
.c_str()).c_str());
989 // Append the WHERE clause to the SQL DELETE statement
992 case DB_DEL_KEYFIELDS
:
993 // If the datasource supports the ROWID column, build
994 // the where on ROWID for efficiency purposes.
995 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
996 if (CanUpdateByROWID())
999 wxChar rowid
[wxDB_ROWID_LEN
+1];
1001 // Get the ROWID value. If not successful retreiving the ROWID,
1002 // simply fall down through the code and build the WHERE clause
1003 // based on the key fields.
1004 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1006 pSqlStmt
+= wxT("ROWID = '");
1008 pSqlStmt
+= wxT("'");
1012 // Unable to delete by ROWID, so build a WHERE
1013 // clause based on the keyfields.
1014 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1015 pSqlStmt
+= whereClause
;
1018 pSqlStmt
+= pWhereClause
;
1020 case DB_DEL_MATCHING
:
1021 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1022 pSqlStmt
+= whereClause
;
1026 } // BuildDeleteStmt()
1029 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1030 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1032 wxString tempSqlStmt
;
1033 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1034 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1035 } // wxDbTable::BuildDeleteStmt()
1038 /********** wxDbTable::BuildSelectStmt() **********/
1039 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1041 wxString whereClause
;
1042 whereClause
.Empty();
1044 // Build a select statement to query the database
1045 pSqlStmt
= wxT("SELECT ");
1047 // SELECT DISTINCT values only?
1049 pSqlStmt
+= wxT("DISTINCT ");
1051 // Was a FROM clause specified to join tables to the base table?
1052 // Available for ::Query() only!!!
1053 bool appendFromClause
= false;
1054 #if wxODBC_BACKWARD_COMPATABILITY
1055 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1056 appendFromClause
= true;
1058 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.length())
1059 appendFromClause
= true;
1062 // Add the column list
1065 for (i
= 0; i
< m_numCols
; i
++)
1067 tStr
= colDefs
[i
].ColName
;
1068 // If joining tables, the base table column names must be qualified to avoid ambiguity
1069 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1071 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1072 pSqlStmt
+= wxT(".");
1074 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1075 if (i
+ 1 < m_numCols
)
1076 pSqlStmt
+= wxT(",");
1079 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1080 // the ROWID if querying distinct records. The rowid will always be unique.
1081 if (!distinct
&& CanUpdateByROWID())
1083 // If joining tables, the base table column names must be qualified to avoid ambiguity
1084 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1086 pSqlStmt
+= wxT(",");
1087 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1088 pSqlStmt
+= wxT(".ROWID");
1091 pSqlStmt
+= wxT(",ROWID");
1094 // Append the FROM tablename portion
1095 pSqlStmt
+= wxT(" FROM ");
1096 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1097 // pSqlStmt += queryTableName;
1099 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1100 // The HOLDLOCK keyword follows the table name in the from clause.
1101 // Each table in the from clause must specify HOLDLOCK or
1102 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1103 // is parsed but ignored in SYBASE Transact-SQL.
1104 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1105 pSqlStmt
+= wxT(" HOLDLOCK");
1107 if (appendFromClause
)
1110 // Append the WHERE clause. Either append the where clause for the class
1111 // or build a where clause. The typeOfSelect determines this.
1112 switch(typeOfSelect
)
1114 case DB_SELECT_WHERE
:
1115 #if wxODBC_BACKWARD_COMPATABILITY
1116 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1118 if (where
.length()) // May not want a where clause!!!
1121 pSqlStmt
+= wxT(" WHERE ");
1125 case DB_SELECT_KEYFIELDS
:
1126 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1127 if (whereClause
.length())
1129 pSqlStmt
+= wxT(" WHERE ");
1130 pSqlStmt
+= whereClause
;
1133 case DB_SELECT_MATCHING
:
1134 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1135 if (whereClause
.length())
1137 pSqlStmt
+= wxT(" WHERE ");
1138 pSqlStmt
+= whereClause
;
1143 // Append the ORDER BY clause
1144 #if wxODBC_BACKWARD_COMPATABILITY
1145 if (orderBy
&& wxStrlen(orderBy
))
1147 if (orderBy
.length())
1150 pSqlStmt
+= wxT(" ORDER BY ");
1151 pSqlStmt
+= orderBy
;
1154 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1155 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1156 // HOLDLOCK for Sybase.
1157 if (selectForUpdate
&& CanSelectForUpdate())
1158 pSqlStmt
+= wxT(" FOR UPDATE");
1160 } // wxDbTable::BuildSelectStmt()
1163 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1164 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1166 wxString tempSqlStmt
;
1167 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1168 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1169 } // wxDbTable::BuildSelectStmt()
1172 /********** wxDbTable::BuildUpdateStmt() **********/
1173 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1175 wxASSERT(!queryOnly
);
1179 wxString whereClause
;
1180 whereClause
.Empty();
1182 bool firstColumn
= true;
1184 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1185 pDb
->SQLTableName(tableName
.c_str()).c_str());
1187 // Append a list of columns to be updated
1189 for (i
= 0; i
< m_numCols
; i
++)
1191 // Only append Updateable columns
1192 if (colDefs
[i
].Updateable
)
1195 pSqlStmt
+= wxT(",");
1197 firstColumn
= false;
1199 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1200 // pSqlStmt += colDefs[i].ColName;
1201 pSqlStmt
+= wxT(" = ?");
1205 // Append the WHERE clause to the SQL UPDATE statement
1206 pSqlStmt
+= wxT(" WHERE ");
1207 switch(typeOfUpdate
)
1209 case DB_UPD_KEYFIELDS
:
1210 // If the datasource supports the ROWID column, build
1211 // the where on ROWID for efficiency purposes.
1212 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1213 if (CanUpdateByROWID())
1216 wxChar rowid
[wxDB_ROWID_LEN
+1];
1218 // Get the ROWID value. If not successful retreiving the ROWID,
1219 // simply fall down through the code and build the WHERE clause
1220 // based on the key fields.
1221 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1223 pSqlStmt
+= wxT("ROWID = '");
1225 pSqlStmt
+= wxT("'");
1229 // Unable to delete by ROWID, so build a WHERE
1230 // clause based on the keyfields.
1231 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1232 pSqlStmt
+= whereClause
;
1235 pSqlStmt
+= pWhereClause
;
1238 } // BuildUpdateStmt()
1241 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1242 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1244 wxString tempSqlStmt
;
1245 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1246 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1247 } // BuildUpdateStmt()
1250 /********** wxDbTable::BuildWhereClause() **********/
1251 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1252 const wxString
&qualTableName
, bool useLikeComparison
)
1254 * Note: BuildWhereClause() currently ignores timestamp columns.
1255 * They are not included as part of the where clause.
1258 bool moreThanOneColumn
= false;
1261 // Loop through the columns building a where clause as you go
1263 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1265 // Determine if this column should be included in the WHERE clause
1266 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1267 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1269 // Skip over timestamp columns
1270 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1272 // If there is more than 1 column, join them with the keyword "AND"
1273 if (moreThanOneColumn
)
1274 pWhereClause
+= wxT(" AND ");
1276 moreThanOneColumn
= true;
1278 // Concatenate where phrase for the column
1279 wxString tStr
= colDefs
[colNumber
].ColName
;
1281 if (qualTableName
.length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1283 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1284 pWhereClause
+= wxT(".");
1286 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1288 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1289 pWhereClause
+= wxT(" LIKE ");
1291 pWhereClause
+= wxT(" = ");
1293 switch(colDefs
[colNumber
].SqlCtype
)
1299 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1300 colValue
.Printf(wxT("'%s'"), GetDb()->EscapeSqlChars((wxChar
*)colDefs
[colNumber
].PtrDataObj
).c_str());
1304 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1307 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1311 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1314 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1317 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1320 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1325 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1326 colNumber
,colDefs
[colNumber
].ColName
);
1327 wxFAIL_MSG(strMsg
.c_str());
1331 pWhereClause
+= colValue
;
1334 } // wxDbTable::BuildWhereClause()
1337 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1338 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1339 const wxString
&qualTableName
, bool useLikeComparison
)
1341 wxString tempSqlStmt
;
1342 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1343 wxStrcpy(pWhereClause
, tempSqlStmt
);
1344 } // wxDbTable::BuildWhereClause()
1347 /********** wxDbTable::GetRowNum() **********/
1348 UWORD
wxDbTable::GetRowNum(void)
1352 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1354 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1358 // Completed successfully
1359 return((UWORD
) rowNum
);
1361 } // wxDbTable::GetRowNum()
1364 /********** wxDbTable::CloseCursor() **********/
1365 bool wxDbTable::CloseCursor(HSTMT cursor
)
1367 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1368 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1370 // Completed successfully
1373 } // wxDbTable::CloseCursor()
1376 /********** wxDbTable::CreateTable() **********/
1377 bool wxDbTable::CreateTable(bool attemptDrop
)
1385 #ifdef DBDEBUG_CONSOLE
1386 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1390 if (attemptDrop
&& !DropTable())
1394 #ifdef DBDEBUG_CONSOLE
1395 for (i
= 0; i
< m_numCols
; i
++)
1397 // Exclude derived columns since they are NOT part of the base table
1398 if (colDefs
[i
].DerivedCol
)
1400 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1401 switch(colDefs
[i
].DbDataType
)
1403 case DB_DATA_TYPE_VARCHAR
:
1404 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1406 case DB_DATA_TYPE_MEMO
:
1407 cout
<< pDb
->GetTypeInfMemo().TypeName
;
1409 case DB_DATA_TYPE_INTEGER
:
1410 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1412 case DB_DATA_TYPE_FLOAT
:
1413 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1415 case DB_DATA_TYPE_DATE
:
1416 cout
<< pDb
->GetTypeInfDate().TypeName
;
1418 case DB_DATA_TYPE_BLOB
:
1419 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1426 // Build a CREATE TABLE string from the colDefs structure.
1427 bool needComma
= false;
1429 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1430 pDb
->SQLTableName(tableName
.c_str()).c_str());
1432 for (i
= 0; i
< m_numCols
; i
++)
1434 // Exclude derived columns since they are NOT part of the base table
1435 if (colDefs
[i
].DerivedCol
)
1439 sqlStmt
+= wxT(",");
1441 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1442 // sqlStmt += colDefs[i].ColName;
1443 sqlStmt
+= wxT(" ");
1445 switch(colDefs
[i
].DbDataType
)
1447 case DB_DATA_TYPE_VARCHAR
:
1448 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1450 case DB_DATA_TYPE_MEMO
:
1451 sqlStmt
+= pDb
->GetTypeInfMemo().TypeName
;
1453 case DB_DATA_TYPE_INTEGER
:
1454 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1456 case DB_DATA_TYPE_FLOAT
:
1457 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1459 case DB_DATA_TYPE_DATE
:
1460 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1462 case DB_DATA_TYPE_BLOB
:
1463 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1466 // For varchars, append the size of the string
1467 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1468 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1469 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1472 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1476 if (pDb
->Dbms() == dbmsDB2
||
1477 pDb
->Dbms() == dbmsMY_SQL
||
1478 pDb
->Dbms() == dbmsSYBASE_ASE
||
1479 pDb
->Dbms() == dbmsINTERBASE
||
1480 pDb
->Dbms() == dbmsFIREBIRD
||
1481 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1483 if (colDefs
[i
].KeyField
)
1485 sqlStmt
+= wxT(" NOT NULL");
1491 // If there is a primary key defined, include it in the create statement
1492 for (i
= j
= 0; i
< m_numCols
; i
++)
1494 if (colDefs
[i
].KeyField
)
1500 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1501 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1503 switch (pDb
->Dbms())
1507 case dbmsSYBASE_ASA
:
1508 case dbmsSYBASE_ASE
:
1512 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1513 sqlStmt
+= wxT(",PRIMARY KEY (");
1518 sqlStmt
+= wxT(",CONSTRAINT ");
1519 // DB2 is limited to 18 characters for index names
1520 if (pDb
->Dbms() == dbmsDB2
)
1522 wxASSERT_MSG(!tableName
.empty() && tableName
.length() <= 13, wxT("DB2 table/index names must be no longer than 13 characters in length.\n\nTruncating table name to 13 characters."));
1523 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1524 // sqlStmt += tableName.substr(0, 13);
1527 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1528 // sqlStmt += tableName;
1530 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1535 // List column name(s) of column(s) comprising the primary key
1536 for (i
= j
= 0; i
< m_numCols
; i
++)
1538 if (colDefs
[i
].KeyField
)
1540 if (j
++) // Multi part key, comma separate names
1541 sqlStmt
+= wxT(",");
1542 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1544 if (pDb
->Dbms() == dbmsMY_SQL
&&
1545 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1548 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1553 sqlStmt
+= wxT(")");
1555 if (pDb
->Dbms() == dbmsINFORMIX
||
1556 pDb
->Dbms() == dbmsSYBASE_ASA
||
1557 pDb
->Dbms() == dbmsSYBASE_ASE
)
1559 sqlStmt
+= wxT(" CONSTRAINT ");
1560 sqlStmt
+= pDb
->SQLTableName(tableName
);
1561 // sqlStmt += tableName;
1562 sqlStmt
+= wxT("_PIDX");
1565 // Append the closing parentheses for the create table statement
1566 sqlStmt
+= wxT(")");
1568 pDb
->WriteSqlLog(sqlStmt
);
1570 #ifdef DBDEBUG_CONSOLE
1571 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1574 // Execute the CREATE TABLE statement
1575 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1576 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1578 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1579 pDb
->RollbackTrans();
1584 // Commit the transaction and close the cursor
1585 if (!pDb
->CommitTrans())
1587 if (!CloseCursor(hstmt
))
1590 // Database table created successfully
1593 } // wxDbTable::CreateTable()
1596 /********** wxDbTable::DropTable() **********/
1597 bool wxDbTable::DropTable()
1599 // NOTE: This function returns true if the Table does not exist, but
1600 // only for identified databases. Code will need to be added
1601 // below for any other databases when those databases are defined
1602 // to handle this situation consistently
1606 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1607 pDb
->SQLTableName(tableName
.c_str()).c_str());
1609 pDb
->WriteSqlLog(sqlStmt
);
1611 #ifdef DBDEBUG_CONSOLE
1612 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1615 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1616 if (retcode
!= SQL_SUCCESS
)
1618 // Check for "Base table not found" error and ignore
1619 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1620 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1621 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1623 // Check for product specific error codes
1624 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1625 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1626 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1627 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1629 pDb
->DispNextError();
1630 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1631 pDb
->RollbackTrans();
1632 // CloseCursor(hstmt);
1638 // Commit the transaction and close the cursor
1639 if (! pDb
->CommitTrans())
1641 if (! CloseCursor(hstmt
))
1645 } // wxDbTable::DropTable()
1648 /********** wxDbTable::CreateIndex() **********/
1649 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1650 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1654 // Drop the index first
1655 if (attemptDrop
&& !DropIndex(indexName
))
1658 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1659 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1660 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1661 // table was created, then months later you determine that an additional index while
1662 // give better performance, so you want to add an index).
1664 // The following block of code will modify the column definition to make the column be
1665 // defined with the "NOT NULL" qualifier.
1666 if (pDb
->Dbms() == dbmsMY_SQL
)
1671 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1675 // Find the column definition that has the ColName that matches the
1676 // index column name. We need to do this to get the DB_DATA_TYPE of
1677 // the index column, as MySQL's syntax for the ALTER column requires
1679 while (!found
&& (j
< this->m_numCols
))
1681 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1689 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1690 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1696 // retcode is not used
1697 wxODBC_ERRORS retcode
;
1698 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1699 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1700 // This line is just here for debug checking of the value
1701 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1712 pDb
->RollbackTrans();
1717 // Build a CREATE INDEX statement
1718 sqlStmt
= wxT("CREATE ");
1720 sqlStmt
+= wxT("UNIQUE ");
1722 sqlStmt
+= wxT("INDEX ");
1723 sqlStmt
+= pDb
->SQLTableName(indexName
);
1724 sqlStmt
+= wxT(" ON ");
1726 sqlStmt
+= pDb
->SQLTableName(tableName
);
1727 // sqlStmt += tableName;
1728 sqlStmt
+= wxT(" (");
1730 // Append list of columns making up index
1732 for (i
= 0; i
< numIndexColumns
; i
++)
1734 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1735 // sqlStmt += pIndexDefs[i].ColName;
1737 // MySQL requires a key length on VARCHAR keys
1738 if ( pDb
->Dbms() == dbmsMY_SQL
)
1740 // Find the details on this column
1742 for ( j
= 0; j
< m_numCols
; ++j
)
1744 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1749 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1752 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1757 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1758 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1759 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1760 !(pDb
->Dbms() == dbmsPOSTGRES
))
1762 if (pIndexDefs
[i
].Ascending
)
1763 sqlStmt
+= wxT(" ASC");
1765 sqlStmt
+= wxT(" DESC");
1768 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1770 if ((i
+ 1) < numIndexColumns
)
1771 sqlStmt
+= wxT(",");
1774 // Append closing parentheses
1775 sqlStmt
+= wxT(")");
1777 pDb
->WriteSqlLog(sqlStmt
);
1779 #ifdef DBDEBUG_CONSOLE
1780 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1783 // Execute the CREATE INDEX statement
1784 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1785 if (retcode
!= SQL_SUCCESS
)
1787 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1788 pDb
->RollbackTrans();
1793 // Commit the transaction and close the cursor
1794 if (! pDb
->CommitTrans())
1796 if (! CloseCursor(hstmt
))
1799 // Index Created Successfully
1802 } // wxDbTable::CreateIndex()
1805 /********** wxDbTable::DropIndex() **********/
1806 bool wxDbTable::DropIndex(const wxString
&indexName
)
1808 // NOTE: This function returns true if the Index does not exist, but
1809 // only for identified databases. Code will need to be added
1810 // below for any other databases when those databases are defined
1811 // to handle this situation consistently
1815 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1816 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1817 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1818 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1819 pDb
->SQLTableName(tableName
.c_str()).c_str());
1820 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1821 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1822 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1823 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1824 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1825 pDb
->SQLTableName(indexName
.c_str()).c_str());
1827 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1828 pDb
->SQLTableName(indexName
.c_str()).c_str());
1830 pDb
->WriteSqlLog(sqlStmt
);
1832 #ifdef DBDEBUG_CONSOLE
1833 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1835 RETCODE retcode
= SQLExecDirect(hstmt
, WXSQLCAST(sqlStmt
), SQL_NTS
);
1836 if (retcode
!= SQL_SUCCESS
)
1838 // Check for "Index not found" error and ignore
1839 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1840 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1842 // Check for product specific error codes
1843 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1844 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1845 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1846 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1847 (pDb
->Dbms() == dbmsMAXDB
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1848 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1849 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1850 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1851 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1854 pDb
->DispNextError();
1855 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1856 pDb
->RollbackTrans();
1863 // Commit the transaction and close the cursor
1864 if (! pDb
->CommitTrans())
1866 if (! CloseCursor(hstmt
))
1870 } // wxDbTable::DropIndex()
1873 /********** wxDbTable::SetOrderByColNums() **********/
1874 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1876 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1882 va_start(argptr
, first
); /* Initialize variable arguments. */
1883 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1885 // Make sure the passed in column number
1886 // is within the valid range of columns
1888 // Valid columns are 0 thru m_numCols-1
1889 if (colNumber
>= m_numCols
|| colNumber
< 0)
1895 if (colNumber
!= first
)
1896 tempStr
+= wxT(",");
1898 tempStr
+= colDefs
[colNumber
].ColName
;
1899 colNumber
= va_arg (argptr
, int);
1901 va_end (argptr
); /* Reset variable arguments. */
1903 SetOrderByClause(tempStr
);
1906 } // wxDbTable::SetOrderByColNums()
1909 /********** wxDbTable::Insert() **********/
1910 int wxDbTable::Insert(void)
1912 wxASSERT(!queryOnly
);
1913 if (queryOnly
|| !insertable
)
1918 // Insert the record by executing the already prepared insert statement
1920 retcode
= SQLExecute(hstmtInsert
);
1921 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1922 retcode
!= SQL_NEED_DATA
)
1924 // Check to see if integrity constraint was violated
1925 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1926 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1927 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1930 pDb
->DispNextError();
1931 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1935 if (retcode
== SQL_NEED_DATA
)
1938 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1939 while (retcode
== SQL_NEED_DATA
)
1941 // Find the parameter
1943 for (i
=0; i
< m_numCols
; i
++)
1945 if (colDefs
[i
].PtrDataObj
== pParmID
)
1947 // We found it. Store the parameter.
1948 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1949 if (retcode
!= SQL_SUCCESS
)
1951 pDb
->DispNextError();
1952 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1958 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1959 if (retcode
!= SQL_SUCCESS
&&
1960 retcode
!= SQL_SUCCESS_WITH_INFO
)
1962 // record was not inserted
1963 pDb
->DispNextError();
1964 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1970 // Record inserted into the datasource successfully
1973 } // wxDbTable::Insert()
1976 /********** wxDbTable::Update() **********/
1977 bool wxDbTable::Update(void)
1979 wxASSERT(!queryOnly
);
1985 // Build the SQL UPDATE statement
1986 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1988 pDb
->WriteSqlLog(sqlStmt
);
1990 #ifdef DBDEBUG_CONSOLE
1991 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1994 // Execute the SQL UPDATE statement
1995 return(execUpdate(sqlStmt
));
1997 } // wxDbTable::Update()
2000 /********** wxDbTable::Update(pSqlStmt) **********/
2001 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2003 wxASSERT(!queryOnly
);
2007 pDb
->WriteSqlLog(pSqlStmt
);
2009 return(execUpdate(pSqlStmt
));
2011 } // wxDbTable::Update(pSqlStmt)
2014 /********** wxDbTable::UpdateWhere() **********/
2015 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2017 wxASSERT(!queryOnly
);
2023 // Build the SQL UPDATE statement
2024 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2026 pDb
->WriteSqlLog(sqlStmt
);
2028 #ifdef DBDEBUG_CONSOLE
2029 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2032 // Execute the SQL UPDATE statement
2033 return(execUpdate(sqlStmt
));
2035 } // wxDbTable::UpdateWhere()
2038 /********** wxDbTable::Delete() **********/
2039 bool wxDbTable::Delete(void)
2041 wxASSERT(!queryOnly
);
2048 // Build the SQL DELETE statement
2049 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2051 pDb
->WriteSqlLog(sqlStmt
);
2053 // Execute the SQL DELETE statement
2054 return(execDelete(sqlStmt
));
2056 } // wxDbTable::Delete()
2059 /********** wxDbTable::DeleteWhere() **********/
2060 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2062 wxASSERT(!queryOnly
);
2069 // Build the SQL DELETE statement
2070 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2072 pDb
->WriteSqlLog(sqlStmt
);
2074 // Execute the SQL DELETE statement
2075 return(execDelete(sqlStmt
));
2077 } // wxDbTable::DeleteWhere()
2080 /********** wxDbTable::DeleteMatching() **********/
2081 bool wxDbTable::DeleteMatching(void)
2083 wxASSERT(!queryOnly
);
2090 // Build the SQL DELETE statement
2091 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2093 pDb
->WriteSqlLog(sqlStmt
);
2095 // Execute the SQL DELETE statement
2096 return(execDelete(sqlStmt
));
2098 } // wxDbTable::DeleteMatching()
2101 /********** wxDbTable::IsColNull() **********/
2102 bool wxDbTable::IsColNull(UWORD colNumber
) const
2105 This logic is just not right. It would indicate true
2106 if a numeric field were set to a value of 0.
2108 switch(colDefs[colNumber].SqlCtype)
2112 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2113 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2115 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2117 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2119 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2121 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2123 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2125 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2126 case SQL_C_TIMESTAMP:
2127 TIMESTAMP_STRUCT *pDt;
2128 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2129 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2137 return (colDefs
[colNumber
].Null
);
2138 } // wxDbTable::IsColNull()
2141 /********** wxDbTable::CanSelectForUpdate() **********/
2142 bool wxDbTable::CanSelectForUpdate(void)
2147 if (pDb
->Dbms() == dbmsMY_SQL
)
2150 if ((pDb
->Dbms() == dbmsORACLE
) ||
2151 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2156 } // wxDbTable::CanSelectForUpdate()
2159 /********** wxDbTable::CanUpdateByROWID() **********/
2160 bool wxDbTable::CanUpdateByROWID(void)
2163 * NOTE: Returning false for now until this can be debugged,
2164 * as the ROWID is not getting updated correctly
2168 if (pDb->Dbms() == dbmsORACLE)
2173 } // wxDbTable::CanUpdateByROWID()
2176 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2177 bool wxDbTable::IsCursorClosedOnCommit(void)
2179 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2184 } // wxDbTable::IsCursorClosedOnCommit()
2188 /********** wxDbTable::ClearMemberVar() **********/
2189 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2191 wxASSERT(colNumber
< m_numCols
);
2193 switch(colDefs
[colNumber
].SqlCtype
)
2199 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2200 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2203 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2206 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2210 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2213 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2216 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2219 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2221 case SQL_C_TIMESTAMP
:
2222 TIMESTAMP_STRUCT
*pDt
;
2223 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2234 pDtd
= (DATE_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2241 pDtt
= (TIME_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2249 SetColNull(colNumber
);
2250 } // wxDbTable::ClearMemberVar()
2253 /********** wxDbTable::ClearMemberVars() **********/
2254 void wxDbTable::ClearMemberVars(bool setToNull
)
2258 // Loop through the columns setting each member variable to zero
2259 for (i
=0; i
< m_numCols
; i
++)
2260 ClearMemberVar((UWORD
)i
,setToNull
);
2262 } // wxDbTable::ClearMemberVars()
2265 /********** wxDbTable::SetQueryTimeout() **********/
2266 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2268 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2269 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2270 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2271 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2272 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2273 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2274 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2275 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2277 // Completed Successfully
2280 } // wxDbTable::SetQueryTimeout()
2283 /********** wxDbTable::SetColDefs() **********/
2284 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2285 SWORD cType
, int size
, bool keyField
, bool updateable
,
2286 bool insertAllowed
, bool derivedColumn
)
2290 if (index
>= m_numCols
) // Columns numbers are zero based....
2292 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
);
2298 if (!colDefs
) // May happen if the database connection fails
2301 if (fieldName
.length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2303 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2304 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2306 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2307 fieldName
.c_str(),colDefs
[index
].ColName
);
2312 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2314 colDefs
[index
].DbDataType
= dataType
;
2315 colDefs
[index
].PtrDataObj
= pData
;
2316 colDefs
[index
].SqlCtype
= cType
;
2317 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2318 colDefs
[index
].KeyField
= keyField
;
2319 colDefs
[index
].DerivedCol
= derivedColumn
;
2320 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2323 colDefs
[index
].Updateable
= false;
2324 colDefs
[index
].InsertAllowed
= false;
2328 colDefs
[index
].Updateable
= updateable
;
2329 colDefs
[index
].InsertAllowed
= insertAllowed
;
2332 colDefs
[index
].Null
= false;
2336 } // wxDbTable::SetColDefs()
2339 /********** wxDbTable::SetColDefs() **********/
2340 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2343 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2349 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2351 for (index
= 0; index
< numCols
; index
++)
2353 // Process the fields
2354 switch (pColInfs
[index
].dbDataType
)
2356 case DB_DATA_TYPE_VARCHAR
:
2357 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2358 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2359 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2361 case DB_DATA_TYPE_MEMO
:
2362 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2363 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2364 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2366 case DB_DATA_TYPE_INTEGER
:
2367 // Can be long or short
2368 if (pColInfs
[index
].bufferSize
== sizeof(long))
2370 pColDataPtrs
[index
].PtrDataObj
= new long;
2371 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2372 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2376 pColDataPtrs
[index
].PtrDataObj
= new short;
2377 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2378 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2381 case DB_DATA_TYPE_FLOAT
:
2382 // Can be float or double
2383 if (pColInfs
[index
].bufferSize
== sizeof(float))
2385 pColDataPtrs
[index
].PtrDataObj
= new float;
2386 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2387 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2391 pColDataPtrs
[index
].PtrDataObj
= new double;
2392 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2393 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2396 case DB_DATA_TYPE_DATE
:
2397 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2398 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2399 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2401 case DB_DATA_TYPE_BLOB
:
2402 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2403 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2404 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2405 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2408 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2409 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2412 // Unable to build all the column definitions, as either one of
2413 // the calls to "new" failed above, or there was a BLOB field
2414 // to have a column definition for. If BLOBs are to be used,
2415 // the other form of ::SetColDefs() must be used, as it is impossible
2416 // to know the maximum size to create the PtrDataObj to be.
2417 delete [] pColDataPtrs
;
2423 return (pColDataPtrs
);
2425 } // wxDbTable::SetColDefs()
2428 /********** wxDbTable::SetCursor() **********/
2429 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2431 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2432 hstmt
= *hstmtDefault
;
2434 hstmt
= *hstmtActivate
;
2436 } // wxDbTable::SetCursor()
2439 /********** wxDbTable::Count(const wxString &) **********/
2440 ULONG
wxDbTable::Count(const wxString
&args
)
2446 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2447 sqlStmt
= wxT("SELECT COUNT(");
2449 sqlStmt
+= wxT(") FROM ");
2450 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2451 // sqlStmt += queryTableName;
2452 #if wxODBC_BACKWARD_COMPATABILITY
2453 if (from
&& wxStrlen(from
))
2459 // Add the where clause if one is provided
2460 #if wxODBC_BACKWARD_COMPATABILITY
2461 if (where
&& wxStrlen(where
))
2466 sqlStmt
+= wxT(" WHERE ");
2470 pDb
->WriteSqlLog(sqlStmt
);
2472 // Initialize the Count cursor if it's not already initialized
2475 hstmtCount
= GetNewCursor(false,false);
2476 wxASSERT(hstmtCount
);
2481 // Execute the SQL statement
2482 if (SQLExecDirect(*hstmtCount
, WXSQLCAST(sqlStmt
), SQL_NTS
) != SQL_SUCCESS
)
2484 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2489 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2491 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2495 // Obtain the result
2496 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2498 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2503 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2504 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2506 // Return the record count
2509 } // wxDbTable::Count()
2512 /********** wxDbTable::Refresh() **********/
2513 bool wxDbTable::Refresh(void)
2517 // Switch to the internal cursor so any active cursors are not corrupted
2518 HSTMT currCursor
= GetCursor();
2519 hstmt
= hstmtInternal
;
2520 #if wxODBC_BACKWARD_COMPATABILITY
2521 // Save the where and order by clauses
2522 wxChar
*saveWhere
= where
;
2523 wxChar
*saveOrderBy
= orderBy
;
2525 wxString saveWhere
= where
;
2526 wxString saveOrderBy
= orderBy
;
2528 // Build a where clause to refetch the record with. Try and use the
2529 // ROWID if it's available, ow use the key fields.
2530 wxString whereClause
;
2531 whereClause
.Empty();
2533 if (CanUpdateByROWID())
2536 wxChar rowid
[wxDB_ROWID_LEN
+1];
2538 // Get the ROWID value. If not successful retreiving the ROWID,
2539 // simply fall down through the code and build the WHERE clause
2540 // based on the key fields.
2541 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2543 whereClause
+= pDb
->SQLTableName(queryTableName
);
2544 // whereClause += queryTableName;
2545 whereClause
+= wxT(".ROWID = '");
2546 whereClause
+= rowid
;
2547 whereClause
+= wxT("'");
2551 // If unable to use the ROWID, build a where clause from the keyfields
2552 if (wxStrlen(whereClause
) == 0)
2553 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2555 // Requery the record
2556 where
= whereClause
;
2561 if (result
&& !GetNext())
2564 // Switch back to original cursor
2565 SetCursor(&currCursor
);
2567 // Free the internal cursor
2568 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2569 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2571 // Restore the original where and order by clauses
2573 orderBy
= saveOrderBy
;
2577 } // wxDbTable::Refresh()
2580 /********** wxDbTable::SetColNull() **********/
2581 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2583 if (colNumber
< m_numCols
)
2585 colDefs
[colNumber
].Null
= set
;
2586 if (set
) // Blank out the values in the member variable
2587 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2589 setCbValueForColumn(colNumber
);
2596 } // wxDbTable::SetColNull()
2599 /********** wxDbTable::SetColNull() **********/
2600 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2603 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2605 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2609 if (colNumber
< m_numCols
)
2611 colDefs
[colNumber
].Null
= set
;
2612 if (set
) // Blank out the values in the member variable
2613 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2615 setCbValueForColumn(colNumber
);
2622 } // wxDbTable::SetColNull()
2625 /********** wxDbTable::GetNewCursor() **********/
2626 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2628 HSTMT
*newHSTMT
= new HSTMT
;
2633 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2635 pDb
->DispAllErrors(henv
, hdbc
);
2640 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2642 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2649 if (!bindCols(*newHSTMT
))
2657 SetCursor(newHSTMT
);
2661 } // wxDbTable::GetNewCursor()
2664 /********** wxDbTable::DeleteCursor() **********/
2665 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2669 if (!hstmtDel
) // Cursor already deleted
2673 ODBC 3.0 says to use this form
2674 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2677 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2679 pDb
->DispAllErrors(henv
, hdbc
);
2687 } // wxDbTable::DeleteCursor()
2689 //////////////////////////////////////////////////////////////
2690 // wxDbGrid support functions
2691 //////////////////////////////////////////////////////////////
2693 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2695 if (!m_hstmtGridQuery
)
2697 m_hstmtGridQuery
= GetNewCursor(false,false);
2698 if (!bindCols(*m_hstmtGridQuery
))
2702 m_rowmode
= rowmode
;
2705 case WX_ROW_MODE_QUERY
:
2706 SetCursor(m_hstmtGridQuery
);
2708 case WX_ROW_MODE_INDIVIDUAL
:
2709 SetCursor(hstmtDefault
);
2714 } // wxDbTable::SetRowMode()
2717 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2720 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2722 switch (colDefs
[colNumber
].SqlCtype
)
2725 #if defined(SQL_WCHAR)
2728 #if defined(SQL_WVARCHAR)
2734 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2738 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2742 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2745 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2748 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2750 case SQL_C_UTINYINT
:
2751 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2754 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2757 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2760 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2762 case SQL_C_TIMESTAMP
:
2763 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2766 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2773 } // wxDbTable::GetCol()
2776 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2778 //FIXME: Add proper wxDateTime support to wxVariant..
2781 SetColNull((UWORD
)colNumber
, val
.IsNull());
2785 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2786 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2787 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2789 //Returns null if invalid!
2790 if (!dateval
.ParseDate(val
.GetString()))
2791 SetColNull((UWORD
)colNumber
, true);
2794 switch (colDefs
[colNumber
].SqlCtype
)
2797 #if defined(SQL_WCHAR)
2800 #if defined(SQL_WVARCHAR)
2806 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2807 val
.GetString().c_str(),
2808 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2812 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2816 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2819 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2822 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2824 case SQL_C_UTINYINT
:
2825 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2828 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2830 //FIXME: Add proper wxDateTime support to wxVariant..
2833 DATE_STRUCT
*dataptr
=
2834 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2836 dataptr
->year
= (SWORD
)dateval
.GetYear();
2837 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2838 dataptr
->day
= (UWORD
)dateval
.GetDay();
2843 TIME_STRUCT
*dataptr
=
2844 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2846 dataptr
->hour
= dateval
.GetHour();
2847 dataptr
->minute
= dateval
.GetMinute();
2848 dataptr
->second
= dateval
.GetSecond();
2851 case SQL_C_TIMESTAMP
:
2853 TIMESTAMP_STRUCT
*dataptr
=
2854 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2855 dataptr
->year
= (SWORD
)dateval
.GetYear();
2856 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2857 dataptr
->day
= (UWORD
)dateval
.GetDay();
2859 dataptr
->hour
= dateval
.GetHour();
2860 dataptr
->minute
= dateval
.GetMinute();
2861 dataptr
->second
= dateval
.GetSecond();
2865 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2870 } // if (!val.IsNull())
2871 } // wxDbTable::SetCol()
2874 GenericKey
wxDbTable::GetKey()
2879 blk
= malloc(m_keysize
);
2880 blkptr
= (wxChar
*) blk
;
2883 for (i
=0; i
< m_numCols
; i
++)
2885 if (colDefs
[i
].KeyField
)
2887 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2888 blkptr
+= colDefs
[i
].SzDataObj
;
2892 GenericKey k
= GenericKey(blk
, m_keysize
);
2896 } // wxDbTable::GetKey()
2899 void wxDbTable::SetKey(const GenericKey
& k
)
2905 blkptr
= (wxChar
*)blk
;
2908 for (i
=0; i
< m_numCols
; i
++)
2910 if (colDefs
[i
].KeyField
)
2912 SetColNull((UWORD
)i
, false);
2913 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2914 blkptr
+= colDefs
[i
].SzDataObj
;
2917 } // wxDbTable::SetKey()
2920 #endif // wxUSE_ODBC