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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
20 #pragma implementation "dbtable.h"
23 #include "wx/wxprec.h"
29 #ifdef DBDEBUG_CONSOLE
35 #include "wx/ioswrap.h"
39 #include "wx/string.h"
40 #include "wx/object.h"
45 #include "wx/filefn.h"
53 #include "wx/dbtable.h"
56 // The HPUX preprocessor lines below were commented out on 8/20/97
57 // because macros.h currently redefines DEBUG and is unneeded.
59 // # include <macros.h>
62 # include <sys/minmax.h>
66 ULONG lastTableID
= 0;
74 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
76 while ( (*target
++ = *source
++) != '\0' && --n
)
84 /********** wxDbColDef::wxDbColDef() Constructor **********/
85 wxDbColDef::wxDbColDef()
91 bool wxDbColDef::Initialize()
94 DbDataType
= DB_DATA_TYPE_INTEGER
;
95 SqlCtype
= SQL_C_LONG
;
100 InsertAllowed
= false;
106 } // wxDbColDef::Initialize()
109 /********** wxDbTable::wxDbTable() Constructor **********/
110 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
111 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
113 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
115 } // wxDbTable::wxDbTable()
118 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
119 #if WXWIN_COMPATIBILITY_2_4
120 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
121 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
123 wxString tempQryTblName
;
124 tempQryTblName
= qryTblName
;
125 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
127 } // wxDbTable::wxDbTable()
128 #endif // WXWIN_COMPATIBILITY_2_4
131 /********** wxDbTable::~wxDbTable() **********/
132 wxDbTable::~wxDbTable()
135 } // wxDbTable::~wxDbTable()
138 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
139 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
141 // Initializing member variables
142 pDb
= pwxDb
; // Pointer to the wxDb object
146 m_hstmtGridQuery
= 0;
147 hstmtDefault
= 0; // Initialized below
148 hstmtCount
= 0; // Initialized first time it is needed
155 noCols
= numColumns
; // Number of cols in the table
156 where
.Empty(); // Where clause
157 orderBy
.Empty(); // Order By clause
158 from
.Empty(); // From clause
159 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
164 queryTableName
.Empty();
166 wxASSERT(tblName
.Length());
172 tableName
= tblName
; // Table Name
173 if (tblPath
.Length())
174 tablePath
= tblPath
; // Table Path - used for dBase files
178 if (qryTblName
.Length()) // Name of the table/view to query
179 queryTableName
= qryTblName
;
181 queryTableName
= tblName
;
183 pDb
->incrementTableCount();
186 tableID
= ++lastTableID
;
187 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
190 wxTablesInUse
*tableInUse
;
191 tableInUse
= new wxTablesInUse();
192 tableInUse
->tableName
= tblName
;
193 tableInUse
->tableID
= tableID
;
194 tableInUse
->pDb
= pDb
;
195 TablesInUse
.Append(tableInUse
);
200 // Grab the HENV and HDBC from the wxDb object
201 henv
= pDb
->GetHENV();
202 hdbc
= pDb
->GetHDBC();
204 // Allocate space for column definitions
206 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
208 // Allocate statement handles for the table
211 // Allocate a separate statement handle for performing inserts
212 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
213 pDb
->DispAllErrors(henv
, hdbc
);
214 // Allocate a separate statement handle for performing deletes
215 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
216 pDb
->DispAllErrors(henv
, hdbc
);
217 // Allocate a separate statement handle for performing updates
218 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
219 pDb
->DispAllErrors(henv
, hdbc
);
221 // Allocate a separate statement handle for internal use
222 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
223 pDb
->DispAllErrors(henv
, hdbc
);
225 // Set the cursor type for the statement handles
226 cursorType
= SQL_CURSOR_STATIC
;
228 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
230 // Check to see if cursor type is supported
231 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
232 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
234 // Datasource does not support static cursors. Driver
235 // will substitute a cursor type. Call SQLGetStmtOption()
236 // to determine which cursor type was selected.
237 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
238 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
239 #ifdef DBDEBUG_CONSOLE
240 cout
<< wxT("Static cursor changed to: ");
243 case SQL_CURSOR_FORWARD_ONLY
:
244 cout
<< wxT("Forward Only");
246 case SQL_CURSOR_STATIC
:
247 cout
<< wxT("Static");
249 case SQL_CURSOR_KEYSET_DRIVEN
:
250 cout
<< wxT("Keyset Driven");
252 case SQL_CURSOR_DYNAMIC
:
253 cout
<< wxT("Dynamic");
256 cout
<< endl
<< endl
;
259 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
261 // Force the use of a forward only cursor...
262 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
263 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
265 // Should never happen
266 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
273 pDb
->DispNextError();
274 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
277 #ifdef DBDEBUG_CONSOLE
279 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
284 // Set the cursor type for the INSERT statement handle
285 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
286 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
287 // Set the cursor type for the DELETE statement handle
288 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
289 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
290 // Set the cursor type for the UPDATE statement handle
291 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
292 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
295 // Make the default cursor the active cursor
296 hstmtDefault
= GetNewCursor(false,false);
297 wxASSERT(hstmtDefault
);
298 hstmt
= *hstmtDefault
;
302 } // wxDbTable::initialize()
305 void wxDbTable::cleanup()
310 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
319 wxList::compatibility_iterator pNode
;
320 pNode
= TablesInUse
.GetFirst();
321 while (pNode
&& !found
)
323 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
326 delete (wxTablesInUse
*)pNode
->GetData();
327 TablesInUse
.Erase(pNode
);
330 pNode
= pNode
->GetNext();
335 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
336 wxLogDebug (msg
,wxT("NOTICE..."));
341 // Decrement the wxDb table count
343 pDb
->decrementTableCount();
345 // Delete memory allocated for column definitions
349 // Free statement handles
355 ODBC 3.0 says to use this form
356 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
358 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
359 pDb
->DispAllErrors(henv
, hdbc
);
365 ODBC 3.0 says to use this form
366 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
368 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
369 pDb
->DispAllErrors(henv
, hdbc
);
375 ODBC 3.0 says to use this form
376 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
378 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
379 pDb
->DispAllErrors(henv
, hdbc
);
385 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
386 pDb
->DispAllErrors(henv
, hdbc
);
389 // Delete dynamically allocated cursors
391 DeleteCursor(hstmtDefault
);
394 DeleteCursor(hstmtCount
);
396 if (m_hstmtGridQuery
)
397 DeleteCursor(m_hstmtGridQuery
);
399 } // wxDbTable::cleanup()
402 /***************************** PRIVATE FUNCTIONS *****************************/
405 void wxDbTable::setCbValueForColumn(int columnIndex
)
407 switch(colDefs
[columnIndex
].DbDataType
)
409 case DB_DATA_TYPE_VARCHAR
:
410 if (colDefs
[columnIndex
].Null
)
411 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
413 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
415 case DB_DATA_TYPE_INTEGER
:
416 if (colDefs
[columnIndex
].Null
)
417 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
419 colDefs
[columnIndex
].CbValue
= 0;
421 case DB_DATA_TYPE_FLOAT
:
422 if (colDefs
[columnIndex
].Null
)
423 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
425 colDefs
[columnIndex
].CbValue
= 0;
427 case DB_DATA_TYPE_DATE
:
428 if (colDefs
[columnIndex
].Null
)
429 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
431 colDefs
[columnIndex
].CbValue
= 0;
433 case DB_DATA_TYPE_BLOB
:
434 if (colDefs
[columnIndex
].Null
)
435 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
437 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_CHAR
)
438 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
440 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
445 /********** wxDbTable::bindParams() **********/
446 bool wxDbTable::bindParams(bool forUpdate
)
448 wxASSERT(!queryOnly
);
453 SDWORD precision
= 0;
456 // Bind each column of the table that should be bound
457 // to a parameter marker
461 for (i
=0, colNo
=1; i
< noCols
; i
++)
465 if (!colDefs
[i
].Updateable
)
470 if (!colDefs
[i
].InsertAllowed
)
474 switch(colDefs
[i
].DbDataType
)
476 case DB_DATA_TYPE_VARCHAR
:
477 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
478 precision
= colDefs
[i
].SzDataObj
;
481 case DB_DATA_TYPE_INTEGER
:
482 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
483 precision
= pDb
->GetTypeInfInteger().Precision
;
486 case DB_DATA_TYPE_FLOAT
:
487 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
488 precision
= pDb
->GetTypeInfFloat().Precision
;
489 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
490 // SQL Sybase Anywhere v5.5 returned a negative number for the
491 // MaxScale. This caused ODBC to kick out an error on ibscale.
492 // I check for this here and set the scale = precision.
494 // scale = (short) precision;
496 case DB_DATA_TYPE_DATE
:
497 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
498 precision
= pDb
->GetTypeInfDate().Precision
;
501 case DB_DATA_TYPE_BLOB
:
502 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
503 precision
= colDefs
[i
].SzDataObj
;
508 setCbValueForColumn(i
);
512 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
513 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
514 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
516 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
521 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
522 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
523 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
525 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
530 // Completed successfully
533 } // wxDbTable::bindParams()
536 /********** wxDbTable::bindInsertParams() **********/
537 bool wxDbTable::bindInsertParams(void)
539 return bindParams(false);
540 } // wxDbTable::bindInsertParams()
543 /********** wxDbTable::bindUpdateParams() **********/
544 bool wxDbTable::bindUpdateParams(void)
546 return bindParams(true);
547 } // wxDbTable::bindUpdateParams()
550 /********** wxDbTable::bindCols() **********/
551 bool wxDbTable::bindCols(HSTMT cursor
)
555 // Bind each column of the table to a memory address for fetching data
557 for (i
= 0; i
< noCols
; i
++)
559 cb
= colDefs
[i
].CbValue
;
560 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
561 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
562 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
565 // Completed successfully
568 } // wxDbTable::bindCols()
571 /********** wxDbTable::getRec() **********/
572 bool wxDbTable::getRec(UWORD fetchType
)
576 if (!pDb
->FwdOnlyCursors())
578 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
582 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
583 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
585 if (retcode
== SQL_NO_DATA_FOUND
)
588 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
592 // Set the Null member variable to indicate the Null state
593 // of each column just read in.
595 for (i
= 0; i
< noCols
; i
++)
596 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
601 // Fetch the next record from the record set
602 retcode
= SQLFetch(hstmt
);
603 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
605 if (retcode
== SQL_NO_DATA_FOUND
)
608 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
612 // Set the Null member variable to indicate the Null state
613 // of each column just read in.
615 for (i
= 0; i
< noCols
; i
++)
616 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
620 // Completed successfully
623 } // wxDbTable::getRec()
626 /********** wxDbTable::execDelete() **********/
627 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
631 // Execute the DELETE statement
632 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
634 if (retcode
== SQL_SUCCESS
||
635 retcode
== SQL_NO_DATA_FOUND
||
636 retcode
== SQL_SUCCESS_WITH_INFO
)
638 // Record deleted successfully
642 // Problem deleting record
643 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
645 } // wxDbTable::execDelete()
648 /********** wxDbTable::execUpdate() **********/
649 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
653 // Execute the UPDATE statement
654 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
656 if (retcode
== SQL_SUCCESS
||
657 retcode
== SQL_NO_DATA_FOUND
||
658 retcode
== SQL_SUCCESS_WITH_INFO
)
660 // Record updated successfully
663 else if (retcode
== SQL_NEED_DATA
)
666 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
667 while (retcode
== SQL_NEED_DATA
)
669 // Find the parameter
671 for (i
=0; i
< noCols
; i
++)
673 if (colDefs
[i
].PtrDataObj
== pParmID
)
675 // We found it. Store the parameter.
676 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
677 if (retcode
!= SQL_SUCCESS
)
679 pDb
->DispNextError();
680 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
685 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
687 if (retcode
== SQL_SUCCESS
||
688 retcode
== SQL_NO_DATA_FOUND
||
689 retcode
== SQL_SUCCESS_WITH_INFO
)
691 // Record updated successfully
696 // Problem updating record
697 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
699 } // wxDbTable::execUpdate()
702 /********** wxDbTable::query() **********/
703 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
708 // The user may wish to select for update, but the DBMS may not be capable
709 selectForUpdate
= CanSelectForUpdate();
711 selectForUpdate
= false;
713 // Set the SQL SELECT string
714 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
715 { // so generate a select statement.
716 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
717 pDb
->WriteSqlLog(sqlStmt
);
720 // Make sure the cursor is closed first
721 if (!CloseCursor(hstmt
))
724 // Execute the SQL SELECT statement
726 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
727 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
728 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
730 // Completed successfully
733 } // wxDbTable::query()
736 /***************************** PUBLIC FUNCTIONS *****************************/
739 /********** wxDbTable::Open() **********/
740 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
750 // Calculate the maximum size of the concatenated
751 // keys for use with wxDbGrid
753 for (i
=0; i
< noCols
; i
++)
755 if (colDefs
[i
].KeyField
)
758 m_keysize
+= colDefs
[i
].SzDataObj
;
763 // Verify that the table exists in the database
764 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
766 s
= wxT("Table/view does not exist in the database");
767 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
768 s
+= wxT(", or you have no permissions.\n");
772 else if (checkPrivileges
)
774 // Verify the user has rights to access the table.
775 // Shortcut boolean evaluation to optimize out call to
778 // Unfortunately this optimization doesn't seem to be
780 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
781 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
782 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
789 if (!tablePath
.IsEmpty())
790 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
792 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
795 pDb
->LogError(p
.GetData());
800 // Bind the member variables for field exchange between
801 // the wxDbTable object and the ODBC record.
804 if (!bindInsertParams()) // Inserts
807 if (!bindUpdateParams()) // Updates
811 if (!bindCols(*hstmtDefault
)) // Selects
814 if (!bindCols(hstmtInternal
)) // Internal use only
818 * Do NOT bind the hstmtCount cursor!!!
821 // Build an insert statement using parameter markers
822 if (!queryOnly
&& noCols
> 0)
824 bool needComma
= false;
825 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
826 pDb
->SQLTableName(tableName
.c_str()).c_str());
827 for (i
= 0; i
< noCols
; i
++)
829 if (! colDefs
[i
].InsertAllowed
)
833 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
834 // sqlStmt += colDefs[i].ColName;
838 sqlStmt
+= wxT(") VALUES (");
840 int insertableCount
= 0;
842 for (i
= 0; i
< noCols
; i
++)
844 if (! colDefs
[i
].InsertAllowed
)
854 // Prepare the insert statement for execution
857 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
858 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
864 // Completed successfully
867 } // wxDbTable::Open()
870 /********** wxDbTable::Query() **********/
871 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
874 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
876 } // wxDbTable::Query()
879 /********** wxDbTable::QueryBySqlStmt() **********/
880 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
882 pDb
->WriteSqlLog(pSqlStmt
);
884 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
886 } // wxDbTable::QueryBySqlStmt()
889 /********** wxDbTable::QueryMatching() **********/
890 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
893 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
895 } // wxDbTable::QueryMatching()
898 /********** wxDbTable::QueryOnKeyFields() **********/
899 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
902 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
904 } // wxDbTable::QueryOnKeyFields()
907 /********** wxDbTable::GetPrev() **********/
908 bool wxDbTable::GetPrev(void)
910 if (pDb
->FwdOnlyCursors())
912 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
916 return(getRec(SQL_FETCH_PRIOR
));
918 } // wxDbTable::GetPrev()
921 /********** wxDbTable::operator-- **********/
922 bool wxDbTable::operator--(int)
924 if (pDb
->FwdOnlyCursors())
926 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
930 return(getRec(SQL_FETCH_PRIOR
));
932 } // wxDbTable::operator--
935 /********** wxDbTable::GetFirst() **********/
936 bool wxDbTable::GetFirst(void)
938 if (pDb
->FwdOnlyCursors())
940 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
944 return(getRec(SQL_FETCH_FIRST
));
946 } // wxDbTable::GetFirst()
949 /********** wxDbTable::GetLast() **********/
950 bool wxDbTable::GetLast(void)
952 if (pDb
->FwdOnlyCursors())
954 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
958 return(getRec(SQL_FETCH_LAST
));
960 } // wxDbTable::GetLast()
963 /********** wxDbTable::BuildDeleteStmt() **********/
964 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
966 wxASSERT(!queryOnly
);
970 wxString whereClause
;
974 // Handle the case of DeleteWhere() and the where clause is blank. It should
975 // delete all records from the database in this case.
976 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
978 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
979 pDb
->SQLTableName(tableName
.c_str()).c_str());
983 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
984 pDb
->SQLTableName(tableName
.c_str()).c_str());
986 // Append the WHERE clause to the SQL DELETE statement
989 case DB_DEL_KEYFIELDS
:
990 // If the datasource supports the ROWID column, build
991 // the where on ROWID for efficiency purposes.
992 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
996 wxChar rowid
[wxDB_ROWID_LEN
+1];
998 // Get the ROWID value. If not successful retreiving the ROWID,
999 // simply fall down through the code and build the WHERE clause
1000 // based on the key fields.
1001 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1003 pSqlStmt
+= wxT("ROWID = '");
1005 pSqlStmt
+= wxT("'");
1009 // Unable to delete by ROWID, so build a WHERE
1010 // clause based on the keyfields.
1011 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1012 pSqlStmt
+= whereClause
;
1015 pSqlStmt
+= pWhereClause
;
1017 case DB_DEL_MATCHING
:
1018 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1019 pSqlStmt
+= whereClause
;
1023 } // BuildDeleteStmt()
1026 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1027 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1029 wxString tempSqlStmt
;
1030 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1031 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1032 } // wxDbTable::BuildDeleteStmt()
1035 /********** wxDbTable::BuildSelectStmt() **********/
1036 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1038 wxString whereClause
;
1039 whereClause
.Empty();
1041 // Build a select statement to query the database
1042 pSqlStmt
= wxT("SELECT ");
1044 // SELECT DISTINCT values only?
1046 pSqlStmt
+= wxT("DISTINCT ");
1048 // Was a FROM clause specified to join tables to the base table?
1049 // Available for ::Query() only!!!
1050 bool appendFromClause
= false;
1051 #if wxODBC_BACKWARD_COMPATABILITY
1052 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1053 appendFromClause
= true;
1055 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1056 appendFromClause
= true;
1059 // Add the column list
1062 for (i
= 0; i
< noCols
; i
++)
1064 tStr
= colDefs
[i
].ColName
;
1065 // If joining tables, the base table column names must be qualified to avoid ambiguity
1066 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1068 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1069 pSqlStmt
+= wxT(".");
1071 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1073 pSqlStmt
+= wxT(",");
1076 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1077 // the ROWID if querying distinct records. The rowid will always be unique.
1078 if (!distinct
&& CanUpdByROWID())
1080 // If joining tables, the base table column names must be qualified to avoid ambiguity
1081 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1083 pSqlStmt
+= wxT(",");
1084 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1085 // pSqlStmt += queryTableName;
1086 pSqlStmt
+= wxT(".ROWID");
1089 pSqlStmt
+= wxT(",ROWID");
1092 // Append the FROM tablename portion
1093 pSqlStmt
+= wxT(" FROM ");
1094 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1095 // pSqlStmt += queryTableName;
1097 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1098 // The HOLDLOCK keyword follows the table name in the from clause.
1099 // Each table in the from clause must specify HOLDLOCK or
1100 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1101 // is parsed but ignored in SYBASE Transact-SQL.
1102 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1103 pSqlStmt
+= wxT(" HOLDLOCK");
1105 if (appendFromClause
)
1108 // Append the WHERE clause. Either append the where clause for the class
1109 // or build a where clause. The typeOfSelect determines this.
1110 switch(typeOfSelect
)
1112 case DB_SELECT_WHERE
:
1113 #if wxODBC_BACKWARD_COMPATABILITY
1114 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1116 if (where
.Length()) // May not want a where clause!!!
1119 pSqlStmt
+= wxT(" WHERE ");
1123 case DB_SELECT_KEYFIELDS
:
1124 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1125 if (whereClause
.Length())
1127 pSqlStmt
+= wxT(" WHERE ");
1128 pSqlStmt
+= whereClause
;
1131 case DB_SELECT_MATCHING
:
1132 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1133 if (whereClause
.Length())
1135 pSqlStmt
+= wxT(" WHERE ");
1136 pSqlStmt
+= whereClause
;
1141 // Append the ORDER BY clause
1142 #if wxODBC_BACKWARD_COMPATABILITY
1143 if (orderBy
&& wxStrlen(orderBy
))
1145 if (orderBy
.Length())
1148 pSqlStmt
+= wxT(" ORDER BY ");
1149 pSqlStmt
+= orderBy
;
1152 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1153 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1154 // HOLDLOCK for Sybase.
1155 if (selectForUpdate
&& CanSelectForUpdate())
1156 pSqlStmt
+= wxT(" FOR UPDATE");
1158 } // wxDbTable::BuildSelectStmt()
1161 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1162 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1164 wxString tempSqlStmt
;
1165 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1166 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1167 } // wxDbTable::BuildSelectStmt()
1170 /********** wxDbTable::BuildUpdateStmt() **********/
1171 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1173 wxASSERT(!queryOnly
);
1177 wxString whereClause
;
1178 whereClause
.Empty();
1180 bool firstColumn
= true;
1182 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1183 pDb
->SQLTableName(tableName
.c_str()).c_str());
1185 // Append a list of columns to be updated
1187 for (i
= 0; i
< noCols
; i
++)
1189 // Only append Updateable columns
1190 if (colDefs
[i
].Updateable
)
1193 pSqlStmt
+= wxT(",");
1195 firstColumn
= false;
1197 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1198 // pSqlStmt += colDefs[i].ColName;
1199 pSqlStmt
+= wxT(" = ?");
1203 // Append the WHERE clause to the SQL UPDATE statement
1204 pSqlStmt
+= wxT(" WHERE ");
1207 case DB_UPD_KEYFIELDS
:
1208 // If the datasource supports the ROWID column, build
1209 // the where on ROWID for efficiency purposes.
1210 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1211 if (CanUpdByROWID())
1214 wxChar rowid
[wxDB_ROWID_LEN
+1];
1216 // Get the ROWID value. If not successful retreiving the ROWID,
1217 // simply fall down through the code and build the WHERE clause
1218 // based on the key fields.
1219 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1221 pSqlStmt
+= wxT("ROWID = '");
1223 pSqlStmt
+= wxT("'");
1227 // Unable to delete by ROWID, so build a WHERE
1228 // clause based on the keyfields.
1229 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1230 pSqlStmt
+= whereClause
;
1233 pSqlStmt
+= pWhereClause
;
1236 } // BuildUpdateStmt()
1239 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1240 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1242 wxString tempSqlStmt
;
1243 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1244 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1245 } // BuildUpdateStmt()
1248 /********** wxDbTable::BuildWhereClause() **********/
1249 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1250 const wxString
&qualTableName
, bool useLikeComparison
)
1252 * Note: BuildWhereClause() currently ignores timestamp columns.
1253 * They are not included as part of the where clause.
1256 bool moreThanOneColumn
= false;
1259 // Loop through the columns building a where clause as you go
1261 for (colNo
= 0; colNo
< noCols
; colNo
++)
1263 // Determine if this column should be included in the WHERE clause
1264 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNo
].KeyField
) ||
1265 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNo
))))
1267 // Skip over timestamp columns
1268 if (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
)
1270 // If there is more than 1 column, join them with the keyword "AND"
1271 if (moreThanOneColumn
)
1272 pWhereClause
+= wxT(" AND ");
1274 moreThanOneColumn
= true;
1276 // Concatenate where phrase for the column
1277 wxString tStr
= colDefs
[colNo
].ColName
;
1279 if (qualTableName
.Length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1281 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1282 pWhereClause
+= wxT(".");
1284 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNo
].ColName
);
1286 if (useLikeComparison
&& (colDefs
[colNo
].SqlCtype
== SQL_C_CHAR
))
1287 pWhereClause
+= wxT(" LIKE ");
1289 pWhereClause
+= wxT(" = ");
1291 switch(colDefs
[colNo
].SqlCtype
)
1294 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
);
1298 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNo
].PtrDataObj
));
1301 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNo
].PtrDataObj
));
1305 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNo
].PtrDataObj
));
1308 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNo
].PtrDataObj
));
1311 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
));
1314 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
));
1319 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1320 colNo
,colDefs
[colNo
].ColName
);
1321 wxFAIL_MSG(strMsg
.c_str());
1325 pWhereClause
+= colValue
;
1328 } // wxDbTable::BuildWhereClause()
1331 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1332 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1333 const wxString
&qualTableName
, bool useLikeComparison
)
1335 wxString tempSqlStmt
;
1336 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1337 wxStrcpy(pWhereClause
, tempSqlStmt
);
1338 } // wxDbTable::BuildWhereClause()
1341 /********** wxDbTable::GetRowNum() **********/
1342 UWORD
wxDbTable::GetRowNum(void)
1346 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1348 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1352 // Completed successfully
1353 return((UWORD
) rowNum
);
1355 } // wxDbTable::GetRowNum()
1358 /********** wxDbTable::CloseCursor() **********/
1359 bool wxDbTable::CloseCursor(HSTMT cursor
)
1361 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1362 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1364 // Completed successfully
1367 } // wxDbTable::CloseCursor()
1370 /********** wxDbTable::CreateTable() **********/
1371 bool wxDbTable::CreateTable(bool attemptDrop
)
1379 #ifdef DBDEBUG_CONSOLE
1380 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1384 if (attemptDrop
&& !DropTable())
1388 #ifdef DBDEBUG_CONSOLE
1389 for (i
= 0; i
< noCols
; i
++)
1391 // Exclude derived columns since they are NOT part of the base table
1392 if (colDefs
[i
].DerivedCol
)
1394 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1395 switch(colDefs
[i
].DbDataType
)
1397 case DB_DATA_TYPE_VARCHAR
:
1398 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1400 case DB_DATA_TYPE_INTEGER
:
1401 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1403 case DB_DATA_TYPE_FLOAT
:
1404 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1406 case DB_DATA_TYPE_DATE
:
1407 cout
<< pDb
->GetTypeInfDate().TypeName
;
1409 case DB_DATA_TYPE_BLOB
:
1410 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1417 // Build a CREATE TABLE string from the colDefs structure.
1418 bool needComma
= false;
1420 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1421 pDb
->SQLTableName(tableName
.c_str()).c_str());
1423 for (i
= 0; i
< noCols
; i
++)
1425 // Exclude derived columns since they are NOT part of the base table
1426 if (colDefs
[i
].DerivedCol
)
1430 sqlStmt
+= wxT(",");
1432 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1433 // sqlStmt += colDefs[i].ColName;
1434 sqlStmt
+= wxT(" ");
1436 switch(colDefs
[i
].DbDataType
)
1438 case DB_DATA_TYPE_VARCHAR
:
1439 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1441 case DB_DATA_TYPE_INTEGER
:
1442 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1444 case DB_DATA_TYPE_FLOAT
:
1445 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1447 case DB_DATA_TYPE_DATE
:
1448 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1450 case DB_DATA_TYPE_BLOB
:
1451 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1454 // For varchars, append the size of the string
1455 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1456 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1457 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1460 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1464 if (pDb
->Dbms() == dbmsDB2
||
1465 pDb
->Dbms() == dbmsMY_SQL
||
1466 pDb
->Dbms() == dbmsSYBASE_ASE
||
1467 pDb
->Dbms() == dbmsINTERBASE
||
1468 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1470 if (colDefs
[i
].KeyField
)
1472 sqlStmt
+= wxT(" NOT NULL");
1478 // If there is a primary key defined, include it in the create statement
1479 for (i
= j
= 0; i
< noCols
; i
++)
1481 if (colDefs
[i
].KeyField
)
1487 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1488 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1490 switch (pDb
->Dbms())
1494 case dbmsSYBASE_ASA
:
1495 case dbmsSYBASE_ASE
:
1498 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1499 sqlStmt
+= wxT(",PRIMARY KEY (");
1504 sqlStmt
+= wxT(",CONSTRAINT ");
1505 // DB2 is limited to 18 characters for index names
1506 if (pDb
->Dbms() == dbmsDB2
)
1508 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."));
1509 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1510 // sqlStmt += tableName.substr(0, 13);
1513 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1514 // sqlStmt += tableName;
1516 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1521 // List column name(s) of column(s) comprising the primary key
1522 for (i
= j
= 0; i
< noCols
; i
++)
1524 if (colDefs
[i
].KeyField
)
1526 if (j
++) // Multi part key, comma separate names
1527 sqlStmt
+= wxT(",");
1528 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1530 if (pDb
->Dbms() == dbmsMY_SQL
&&
1531 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1534 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1539 sqlStmt
+= wxT(")");
1541 if (pDb
->Dbms() == dbmsINFORMIX
||
1542 pDb
->Dbms() == dbmsSYBASE_ASA
||
1543 pDb
->Dbms() == dbmsSYBASE_ASE
)
1545 sqlStmt
+= wxT(" CONSTRAINT ");
1546 sqlStmt
+= pDb
->SQLTableName(tableName
);
1547 // sqlStmt += tableName;
1548 sqlStmt
+= wxT("_PIDX");
1551 // Append the closing parentheses for the create table statement
1552 sqlStmt
+= wxT(")");
1554 pDb
->WriteSqlLog(sqlStmt
);
1556 #ifdef DBDEBUG_CONSOLE
1557 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1560 // Execute the CREATE TABLE statement
1561 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1562 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1564 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1565 pDb
->RollbackTrans();
1570 // Commit the transaction and close the cursor
1571 if (!pDb
->CommitTrans())
1573 if (!CloseCursor(hstmt
))
1576 // Database table created successfully
1579 } // wxDbTable::CreateTable()
1582 /********** wxDbTable::DropTable() **********/
1583 bool wxDbTable::DropTable()
1585 // NOTE: This function returns true if the Table does not exist, but
1586 // only for identified databases. Code will need to be added
1587 // below for any other databases when those databases are defined
1588 // to handle this situation consistently
1592 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1593 pDb
->SQLTableName(tableName
.c_str()).c_str());
1595 pDb
->WriteSqlLog(sqlStmt
);
1597 #ifdef DBDEBUG_CONSOLE
1598 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1601 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1602 if (retcode
!= SQL_SUCCESS
)
1604 // Check for "Base table not found" error and ignore
1605 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1606 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1607 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1609 // Check for product specific error codes
1610 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1611 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1612 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1613 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1615 pDb
->DispNextError();
1616 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1617 pDb
->RollbackTrans();
1618 // CloseCursor(hstmt);
1624 // Commit the transaction and close the cursor
1625 if (! pDb
->CommitTrans())
1627 if (! CloseCursor(hstmt
))
1631 } // wxDbTable::DropTable()
1634 /********** wxDbTable::CreateIndex() **********/
1635 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1636 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1640 // Drop the index first
1641 if (attemptDrop
&& !DropIndex(idxName
))
1644 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1645 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1646 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1647 // table was created, then months later you determine that an additional index while
1648 // give better performance, so you want to add an index).
1650 // The following block of code will modify the column definition to make the column be
1651 // defined with the "NOT NULL" qualifier.
1652 if (pDb
->Dbms() == dbmsMY_SQL
)
1657 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1661 // Find the column definition that has the ColName that matches the
1662 // index column name. We need to do this to get the DB_DATA_TYPE of
1663 // the index column, as MySQL's syntax for the ALTER column requires
1665 while (!found
&& (j
< this->noCols
))
1667 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1675 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1676 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1682 // retcode is not used
1683 wxODBC_ERRORS retcode
;
1684 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1685 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1686 // This line is just here for debug checking of the value
1687 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1698 pDb
->RollbackTrans();
1703 // Build a CREATE INDEX statement
1704 sqlStmt
= wxT("CREATE ");
1706 sqlStmt
+= wxT("UNIQUE ");
1708 sqlStmt
+= wxT("INDEX ");
1709 sqlStmt
+= pDb
->SQLTableName(idxName
);
1710 sqlStmt
+= wxT(" ON ");
1712 sqlStmt
+= pDb
->SQLTableName(tableName
);
1713 // sqlStmt += tableName;
1714 sqlStmt
+= wxT(" (");
1716 // Append list of columns making up index
1718 for (i
= 0; i
< noIdxCols
; i
++)
1720 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1721 // sqlStmt += pIdxDefs[i].ColName;
1723 // MySQL requires a key length on VARCHAR keys
1724 if ( pDb
->Dbms() == dbmsMY_SQL
)
1726 // Find the details on this column
1728 for ( j
= 0; j
< noCols
; ++j
)
1730 if ( wxStrcmp( pIdxDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1735 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1738 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1743 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1744 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1745 !(pDb
->Dbms() == dbmsPOSTGRES
))
1747 if (pIdxDefs
[i
].Ascending
)
1748 sqlStmt
+= wxT(" ASC");
1750 sqlStmt
+= wxT(" DESC");
1753 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1755 if ((i
+ 1) < noIdxCols
)
1756 sqlStmt
+= wxT(",");
1759 // Append closing parentheses
1760 sqlStmt
+= wxT(")");
1762 pDb
->WriteSqlLog(sqlStmt
);
1764 #ifdef DBDEBUG_CONSOLE
1765 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1768 // Execute the CREATE INDEX statement
1769 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1771 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1772 pDb
->RollbackTrans();
1777 // Commit the transaction and close the cursor
1778 if (! pDb
->CommitTrans())
1780 if (! CloseCursor(hstmt
))
1783 // Index Created Successfully
1786 } // wxDbTable::CreateIndex()
1789 /********** wxDbTable::DropIndex() **********/
1790 bool wxDbTable::DropIndex(const wxString
&idxName
)
1792 // NOTE: This function returns true if the Index does not exist, but
1793 // only for identified databases. Code will need to be added
1794 // below for any other databases when those databases are defined
1795 // to handle this situation consistently
1799 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1800 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1801 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1802 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1803 pDb
->SQLTableName(tableName
.c_str()).c_str());
1804 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1805 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1806 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1807 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1808 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1809 pDb
->SQLTableName(idxName
.c_str()).c_str());
1811 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1812 pDb
->SQLTableName(idxName
.c_str()).c_str());
1814 pDb
->WriteSqlLog(sqlStmt
);
1816 #ifdef DBDEBUG_CONSOLE
1817 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1820 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1822 // Check for "Index not found" error and ignore
1823 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1824 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1826 // Check for product specific error codes
1827 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1828 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1829 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1830 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1831 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1832 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1833 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1836 pDb
->DispNextError();
1837 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1838 pDb
->RollbackTrans();
1845 // Commit the transaction and close the cursor
1846 if (! pDb
->CommitTrans())
1848 if (! CloseCursor(hstmt
))
1852 } // wxDbTable::DropIndex()
1855 /********** wxDbTable::SetOrderByColNums() **********/
1856 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1858 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1864 va_start(argptr
, first
); /* Initialize variable arguments. */
1865 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1867 // Make sure the passed in column number
1868 // is within the valid range of columns
1870 // Valid columns are 0 thru noCols-1
1871 if (colNo
>= noCols
|| colNo
< 0)
1878 tempStr
+= wxT(",");
1880 tempStr
+= colDefs
[colNo
].ColName
;
1881 colNo
= va_arg (argptr
, int);
1883 va_end (argptr
); /* Reset variable arguments. */
1885 SetOrderByClause(tempStr
);
1888 } // wxDbTable::SetOrderByColNums()
1891 /********** wxDbTable::Insert() **********/
1892 int wxDbTable::Insert(void)
1894 wxASSERT(!queryOnly
);
1895 if (queryOnly
|| !insertable
)
1900 // Insert the record by executing the already prepared insert statement
1902 retcode
=SQLExecute(hstmtInsert
);
1903 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1904 retcode
!= SQL_NEED_DATA
)
1906 // Check to see if integrity constraint was violated
1907 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1908 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1909 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1912 pDb
->DispNextError();
1913 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1917 if (retcode
== SQL_NEED_DATA
)
1920 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1921 while (retcode
== SQL_NEED_DATA
)
1923 // Find the parameter
1925 for (i
=0; i
< noCols
; i
++)
1927 if (colDefs
[i
].PtrDataObj
== pParmID
)
1929 // We found it. Store the parameter.
1930 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1931 if (retcode
!= SQL_SUCCESS
)
1933 pDb
->DispNextError();
1934 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1940 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1941 if (retcode
!= SQL_SUCCESS
&&
1942 retcode
!= SQL_SUCCESS_WITH_INFO
)
1944 // record was not inserted
1945 pDb
->DispNextError();
1946 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1952 // Record inserted into the datasource successfully
1955 } // wxDbTable::Insert()
1958 /********** wxDbTable::Update() **********/
1959 bool wxDbTable::Update(void)
1961 wxASSERT(!queryOnly
);
1967 // Build the SQL UPDATE statement
1968 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1970 pDb
->WriteSqlLog(sqlStmt
);
1972 #ifdef DBDEBUG_CONSOLE
1973 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1976 // Execute the SQL UPDATE statement
1977 return(execUpdate(sqlStmt
));
1979 } // wxDbTable::Update()
1982 /********** wxDbTable::Update(pSqlStmt) **********/
1983 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1985 wxASSERT(!queryOnly
);
1989 pDb
->WriteSqlLog(pSqlStmt
);
1991 return(execUpdate(pSqlStmt
));
1993 } // wxDbTable::Update(pSqlStmt)
1996 /********** wxDbTable::UpdateWhere() **********/
1997 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1999 wxASSERT(!queryOnly
);
2005 // Build the SQL UPDATE statement
2006 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2008 pDb
->WriteSqlLog(sqlStmt
);
2010 #ifdef DBDEBUG_CONSOLE
2011 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2014 // Execute the SQL UPDATE statement
2015 return(execUpdate(sqlStmt
));
2017 } // wxDbTable::UpdateWhere()
2020 /********** wxDbTable::Delete() **********/
2021 bool wxDbTable::Delete(void)
2023 wxASSERT(!queryOnly
);
2030 // Build the SQL DELETE statement
2031 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2033 pDb
->WriteSqlLog(sqlStmt
);
2035 // Execute the SQL DELETE statement
2036 return(execDelete(sqlStmt
));
2038 } // wxDbTable::Delete()
2041 /********** wxDbTable::DeleteWhere() **********/
2042 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2044 wxASSERT(!queryOnly
);
2051 // Build the SQL DELETE statement
2052 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2054 pDb
->WriteSqlLog(sqlStmt
);
2056 // Execute the SQL DELETE statement
2057 return(execDelete(sqlStmt
));
2059 } // wxDbTable::DeleteWhere()
2062 /********** wxDbTable::DeleteMatching() **********/
2063 bool wxDbTable::DeleteMatching(void)
2065 wxASSERT(!queryOnly
);
2072 // Build the SQL DELETE statement
2073 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2075 pDb
->WriteSqlLog(sqlStmt
);
2077 // Execute the SQL DELETE statement
2078 return(execDelete(sqlStmt
));
2080 } // wxDbTable::DeleteMatching()
2083 /********** wxDbTable::IsColNull() **********/
2084 bool wxDbTable::IsColNull(UWORD colNo
) const
2087 This logic is just not right. It would indicate true
2088 if a numeric field were set to a value of 0.
2090 switch(colDefs[colNo].SqlCtype)
2093 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
2095 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
2097 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
2099 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2101 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2103 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
2105 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
2106 case SQL_C_TIMESTAMP:
2107 TIMESTAMP_STRUCT *pDt;
2108 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
2109 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2117 return (colDefs
[colNo
].Null
);
2118 } // wxDbTable::IsColNull()
2121 /********** wxDbTable::CanSelectForUpdate() **********/
2122 bool wxDbTable::CanSelectForUpdate(void)
2127 if (pDb
->Dbms() == dbmsMY_SQL
)
2130 if ((pDb
->Dbms() == dbmsORACLE
) ||
2131 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2136 } // wxDbTable::CanSelectForUpdate()
2139 /********** wxDbTable::CanUpdByROWID() **********/
2140 bool wxDbTable::CanUpdByROWID(void)
2143 * NOTE: Returning false for now until this can be debugged,
2144 * as the ROWID is not getting updated correctly
2148 if (pDb->Dbms() == dbmsORACLE)
2153 } // wxDbTable::CanUpdByROWID()
2156 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2157 bool wxDbTable::IsCursorClosedOnCommit(void)
2159 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2164 } // wxDbTable::IsCursorClosedOnCommit()
2168 /********** wxDbTable::ClearMemberVar() **********/
2169 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2171 wxASSERT(colNo
< noCols
);
2173 switch(colDefs
[colNo
].SqlCtype
)
2176 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2179 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2182 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2186 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2189 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2192 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2195 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2197 case SQL_C_TIMESTAMP
:
2198 TIMESTAMP_STRUCT
*pDt
;
2199 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2212 } // wxDbTable::ClearMemberVar()
2215 /********** wxDbTable::ClearMemberVars() **********/
2216 void wxDbTable::ClearMemberVars(bool setToNull
)
2220 // Loop through the columns setting each member variable to zero
2221 for (i
=0; i
< noCols
; i
++)
2222 ClearMemberVar((UWORD
)i
,setToNull
);
2224 } // wxDbTable::ClearMemberVars()
2227 /********** wxDbTable::SetQueryTimeout() **********/
2228 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2230 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2231 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2232 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2233 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2234 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2235 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2236 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2237 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2239 // Completed Successfully
2242 } // wxDbTable::SetQueryTimeout()
2245 /********** wxDbTable::SetColDefs() **********/
2246 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2247 SWORD cType
, int size
, bool keyField
, bool upd
,
2248 bool insAllow
, bool derivedCol
)
2250 wxASSERT_MSG( index
< noCols
,
2251 _T("Specified column index exceeds the maximum number of columns for this table.") );
2253 if (!colDefs
) // May happen if the database connection fails
2256 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2258 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2259 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2263 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2264 fieldName
.c_str(),colDefs
[index
].ColName
);
2266 #endif // __WXDEBUG__
2269 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2271 colDefs
[index
].DbDataType
= dataType
;
2272 colDefs
[index
].PtrDataObj
= pData
;
2273 colDefs
[index
].SqlCtype
= cType
;
2274 colDefs
[index
].SzDataObj
= size
;
2275 colDefs
[index
].KeyField
= keyField
;
2276 colDefs
[index
].DerivedCol
= derivedCol
;
2277 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2280 colDefs
[index
].Updateable
= false;
2281 colDefs
[index
].InsertAllowed
= false;
2285 colDefs
[index
].Updateable
= upd
;
2286 colDefs
[index
].InsertAllowed
= insAllow
;
2289 colDefs
[index
].Null
= false;
2291 } // wxDbTable::SetColDefs()
2294 /********** wxDbTable::SetColDefs() **********/
2295 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2298 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2304 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2306 for (index
= 0; index
< numCols
; index
++)
2308 // Process the fields
2309 switch (pColInfs
[index
].dbDataType
)
2311 case DB_DATA_TYPE_VARCHAR
:
2312 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2313 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2314 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2316 case DB_DATA_TYPE_INTEGER
:
2317 // Can be long or short
2318 if (pColInfs
[index
].bufferLength
== sizeof(long))
2320 pColDataPtrs
[index
].PtrDataObj
= new long;
2321 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2322 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2326 pColDataPtrs
[index
].PtrDataObj
= new short;
2327 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2328 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2331 case DB_DATA_TYPE_FLOAT
:
2332 // Can be float or double
2333 if (pColInfs
[index
].bufferLength
== sizeof(float))
2335 pColDataPtrs
[index
].PtrDataObj
= new float;
2336 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2337 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2341 pColDataPtrs
[index
].PtrDataObj
= new double;
2342 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2343 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2346 case DB_DATA_TYPE_DATE
:
2347 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2348 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2349 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2351 case DB_DATA_TYPE_BLOB
:
2352 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2353 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2354 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2355 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2358 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2359 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2362 // Unable to build all the column definitions, as either one of
2363 // the calls to "new" failed above, or there was a BLOB field
2364 // to have a column definition for. If BLOBs are to be used,
2365 // the other form of ::SetColDefs() must be used, as it is impossible
2366 // to know the maximum size to create the PtrDataObj to be.
2367 delete [] pColDataPtrs
;
2373 return (pColDataPtrs
);
2375 } // wxDbTable::SetColDefs()
2378 /********** wxDbTable::SetCursor() **********/
2379 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2381 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2382 hstmt
= *hstmtDefault
;
2384 hstmt
= *hstmtActivate
;
2386 } // wxDbTable::SetCursor()
2389 /********** wxDbTable::Count(const wxString &) **********/
2390 ULONG
wxDbTable::Count(const wxString
&args
)
2396 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2397 sqlStmt
= wxT("SELECT COUNT(");
2399 sqlStmt
+= wxT(") FROM ");
2400 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2401 // sqlStmt += queryTableName;
2402 #if wxODBC_BACKWARD_COMPATABILITY
2403 if (from
&& wxStrlen(from
))
2409 // Add the where clause if one is provided
2410 #if wxODBC_BACKWARD_COMPATABILITY
2411 if (where
&& wxStrlen(where
))
2416 sqlStmt
+= wxT(" WHERE ");
2420 pDb
->WriteSqlLog(sqlStmt
);
2422 // Initialize the Count cursor if it's not already initialized
2425 hstmtCount
= GetNewCursor(false,false);
2426 wxASSERT(hstmtCount
);
2431 // Execute the SQL statement
2432 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2434 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2439 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2441 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2445 // Obtain the result
2446 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2448 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2453 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2454 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2456 // Return the record count
2459 } // wxDbTable::Count()
2462 /********** wxDbTable::Refresh() **********/
2463 bool wxDbTable::Refresh(void)
2467 // Switch to the internal cursor so any active cursors are not corrupted
2468 HSTMT currCursor
= GetCursor();
2469 hstmt
= hstmtInternal
;
2470 #if wxODBC_BACKWARD_COMPATABILITY
2471 // Save the where and order by clauses
2472 wxChar
*saveWhere
= where
;
2473 wxChar
*saveOrderBy
= orderBy
;
2475 wxString saveWhere
= where
;
2476 wxString saveOrderBy
= orderBy
;
2478 // Build a where clause to refetch the record with. Try and use the
2479 // ROWID if it's available, ow use the key fields.
2480 wxString whereClause
;
2481 whereClause
.Empty();
2483 if (CanUpdByROWID())
2486 wxChar rowid
[wxDB_ROWID_LEN
+1];
2488 // Get the ROWID value. If not successful retreiving the ROWID,
2489 // simply fall down through the code and build the WHERE clause
2490 // based on the key fields.
2491 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2493 whereClause
+= pDb
->SQLTableName(queryTableName
);
2494 // whereClause += queryTableName;
2495 whereClause
+= wxT(".ROWID = '");
2496 whereClause
+= rowid
;
2497 whereClause
+= wxT("'");
2501 // If unable to use the ROWID, build a where clause from the keyfields
2502 if (wxStrlen(whereClause
) == 0)
2503 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2505 // Requery the record
2506 where
= whereClause
;
2511 if (result
&& !GetNext())
2514 // Switch back to original cursor
2515 SetCursor(&currCursor
);
2517 // Free the internal cursor
2518 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2519 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2521 // Restore the original where and order by clauses
2523 orderBy
= saveOrderBy
;
2527 } // wxDbTable::Refresh()
2530 /********** wxDbTable::SetColNull() **********/
2531 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2535 colDefs
[colNo
].Null
= set
;
2536 if (set
) // Blank out the values in the member variable
2537 ClearMemberVar(colNo
, false); // Must call with false here, or infinite recursion will happen
2539 setCbValueForColumn(colNo
);
2546 } // wxDbTable::SetColNull()
2549 /********** wxDbTable::SetColNull() **********/
2550 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2553 for (colNo
= 0; colNo
< noCols
; colNo
++)
2555 if (!wxStricmp(colName
, colDefs
[colNo
].ColName
))
2561 colDefs
[colNo
].Null
= set
;
2562 if (set
) // Blank out the values in the member variable
2563 ClearMemberVar((UWORD
)colNo
,false); // Must call with false here, or infinite recursion will happen
2565 setCbValueForColumn(colNo
);
2572 } // wxDbTable::SetColNull()
2575 /********** wxDbTable::GetNewCursor() **********/
2576 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2578 HSTMT
*newHSTMT
= new HSTMT
;
2583 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2585 pDb
->DispAllErrors(henv
, hdbc
);
2590 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2592 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2599 if (!bindCols(*newHSTMT
))
2607 SetCursor(newHSTMT
);
2611 } // wxDbTable::GetNewCursor()
2614 /********** wxDbTable::DeleteCursor() **********/
2615 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2619 if (!hstmtDel
) // Cursor already deleted
2623 ODBC 3.0 says to use this form
2624 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2627 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2629 pDb
->DispAllErrors(henv
, hdbc
);
2637 } // wxDbTable::DeleteCursor()
2639 //////////////////////////////////////////////////////////////
2640 // wxDbGrid support functions
2641 //////////////////////////////////////////////////////////////
2643 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2645 if (!m_hstmtGridQuery
)
2647 m_hstmtGridQuery
= GetNewCursor(false,false);
2648 if (!bindCols(*m_hstmtGridQuery
))
2652 m_rowmode
= rowmode
;
2655 case WX_ROW_MODE_QUERY
:
2656 SetCursor(m_hstmtGridQuery
);
2658 case WX_ROW_MODE_INDIVIDUAL
:
2659 SetCursor(hstmtDefault
);
2664 } // wxDbTable::SetRowMode()
2667 wxVariant
wxDbTable::GetCol(const int colNo
) const
2670 if ((colNo
< noCols
) && (!IsColNull((UWORD
)colNo
)))
2672 switch (colDefs
[colNo
].SqlCtype
)
2676 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2680 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2684 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2687 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2690 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2692 case SQL_C_UTINYINT
:
2693 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2696 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2699 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2702 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2704 case SQL_C_TIMESTAMP
:
2705 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2708 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2715 } // wxDbTable::GetCol()
2718 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2720 //FIXME: Add proper wxDateTime support to wxVariant..
2723 SetColNull((UWORD
)colNo
, val
.IsNull());
2727 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2728 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2729 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2731 //Returns null if invalid!
2732 if (!dateval
.ParseDate(val
.GetString()))
2733 SetColNull((UWORD
)colNo
, true);
2736 switch (colDefs
[colNo
].SqlCtype
)
2740 csstrncpyt((wxChar
*)(colDefs
[colNo
].PtrDataObj
),
2741 val
.GetString().c_str(),
2742 colDefs
[colNo
].SzDataObj
-1);
2746 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2750 *(short *)(colDefs
[colNo
].PtrDataObj
) = (short)val
.GetLong();
2753 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2756 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2758 case SQL_C_UTINYINT
:
2759 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2762 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = (unsigned short)val
.GetLong();
2764 //FIXME: Add proper wxDateTime support to wxVariant..
2767 DATE_STRUCT
*dataptr
=
2768 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2770 dataptr
->year
= (SWORD
)dateval
.GetYear();
2771 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2772 dataptr
->day
= (UWORD
)dateval
.GetDay();
2777 TIME_STRUCT
*dataptr
=
2778 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2780 dataptr
->hour
= dateval
.GetHour();
2781 dataptr
->minute
= dateval
.GetMinute();
2782 dataptr
->second
= dateval
.GetSecond();
2785 case SQL_C_TIMESTAMP
:
2787 TIMESTAMP_STRUCT
*dataptr
=
2788 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2789 dataptr
->year
= (SWORD
)dateval
.GetYear();
2790 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2791 dataptr
->day
= (UWORD
)dateval
.GetDay();
2793 dataptr
->hour
= dateval
.GetHour();
2794 dataptr
->minute
= dateval
.GetMinute();
2795 dataptr
->second
= dateval
.GetSecond();
2799 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2804 } // if (!val.IsNull())
2805 } // wxDbTable::SetCol()
2808 GenericKey
wxDbTable::GetKey()
2813 blk
= malloc(m_keysize
);
2814 blkptr
= (wxChar
*) blk
;
2817 for (i
=0; i
< noCols
; i
++)
2819 if (colDefs
[i
].KeyField
)
2821 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2822 blkptr
+= colDefs
[i
].SzDataObj
;
2826 GenericKey k
= GenericKey(blk
, m_keysize
);
2830 } // wxDbTable::GetKey()
2833 void wxDbTable::SetKey(const GenericKey
& k
)
2839 blkptr
= (wxChar
*)blk
;
2842 for (i
=0; i
< noCols
; i
++)
2844 if (colDefs
[i
].KeyField
)
2846 SetColNull((UWORD
)i
, false);
2847 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2848 blkptr
+= colDefs
[i
].SzDataObj
;
2851 } // wxDbTable::SetKey()
2854 #endif // wxUSE_ODBC