1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence, plus:
12 // Notice: This class library and its intellectual design are free of charge for use,
13 // modification, enhancement, debugging under the following conditions:
14 // 1) These classes may only be used as part of the implementation of a
15 // wxWindows-based application
16 // 2) All enhancements and bug fixes are to be submitted back to the wxWindows
17 // user groups free of all charges for use with the wxWindows library.
18 // 3) These classes may not be distributed as part of any other class library,
19 // DLL, text (written or electronic), other than a complete distribution of
20 // the wxWindows GUI development toolkit.
21 ///////////////////////////////////////////////////////////////////////////////
28 #pragma implementation "dbtable.h"
31 #include "wx/wxprec.h"
37 #ifdef DBDEBUG_CONSOLE
39 #include "wx/ioswrap.h"
43 #include "wx/string.h"
44 #include "wx/object.h"
48 #include "wx/msgdlg.h"
52 #include "wx/filefn.h"
61 #include "wx/dbtable.h"
64 // The HPUX preprocessor lines below were commented out on 8/20/97
65 // because macros.h currently redefines DEBUG and is unneeded.
67 // # include <macros.h>
70 # include <sys/minmax.h>
74 ULONG lastTableID
= 0;
82 /********** wxDbColDef::wxDbColDef() Constructor **********/
83 wxDbColDef::wxDbColDef()
89 bool wxDbColDef::Initialize()
92 DbDataType
= DB_DATA_TYPE_INTEGER
;
93 SqlCtype
= SQL_C_LONG
;
98 InsertAllowed
= FALSE
;
104 } // wxDbColDef::Initialize()
107 /********** wxDbTable::wxDbTable() Constructor **********/
108 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
109 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
111 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
113 } // wxDbTable::wxDbTable()
116 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
117 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
118 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
120 wxString tempQryTblName
;
121 tempQryTblName
= qryTblName
;
122 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
124 } // wxDbTable::wxDbTable()
127 /********** wxDbTable::~wxDbTable() **********/
128 wxDbTable::~wxDbTable()
131 } // wxDbTable::~wxDbTable()
134 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
135 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
137 // Initializing member variables
138 pDb
= pwxDb
; // Pointer to the wxDb object
142 m_hstmtGridQuery
= 0;
143 hstmtDefault
= 0; // Initialized below
144 hstmtCount
= 0; // Initialized first time it is needed
151 noCols
= numColumns
; // Number of cols in the table
152 where
.Empty(); // Where clause
153 orderBy
.Empty(); // Order By clause
154 from
.Empty(); // From clause
155 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
160 queryTableName
.Empty();
162 wxASSERT(tblName
.Length());
168 tableName
= tblName
; // Table Name
169 if (tblPath
.Length())
170 tablePath
= tblPath
; // Table Path - used for dBase files
174 if (qryTblName
.Length()) // Name of the table/view to query
175 queryTableName
= qryTblName
;
177 queryTableName
= tblName
;
179 pDb
->incrementTableCount();
182 tableID
= ++lastTableID
;
183 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
186 wxTablesInUse
*tableInUse
;
187 tableInUse
= new wxTablesInUse();
188 tableInUse
->tableName
= tblName
;
189 tableInUse
->tableID
= tableID
;
190 tableInUse
->pDb
= pDb
;
191 TablesInUse
.Append(tableInUse
);
196 // Grab the HENV and HDBC from the wxDb object
197 henv
= pDb
->GetHENV();
198 hdbc
= pDb
->GetHDBC();
200 // Allocate space for column definitions
202 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
204 // Allocate statement handles for the table
207 // Allocate a separate statement handle for performing inserts
208 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
209 pDb
->DispAllErrors(henv
, hdbc
);
210 // Allocate a separate statement handle for performing deletes
211 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
212 pDb
->DispAllErrors(henv
, hdbc
);
213 // Allocate a separate statement handle for performing updates
214 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
215 pDb
->DispAllErrors(henv
, hdbc
);
217 // Allocate a separate statement handle for internal use
218 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
219 pDb
->DispAllErrors(henv
, hdbc
);
221 // Set the cursor type for the statement handles
222 cursorType
= SQL_CURSOR_STATIC
;
224 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
226 // Check to see if cursor type is supported
227 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
228 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
230 // Datasource does not support static cursors. Driver
231 // will substitute a cursor type. Call SQLGetStmtOption()
232 // to determine which cursor type was selected.
233 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
234 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
235 #ifdef DBDEBUG_CONSOLE
236 cout
<< wxT("Static cursor changed to: ");
239 case SQL_CURSOR_FORWARD_ONLY
:
240 cout
<< wxT("Forward Only");
242 case SQL_CURSOR_STATIC
:
243 cout
<< wxT("Static");
245 case SQL_CURSOR_KEYSET_DRIVEN
:
246 cout
<< wxT("Keyset Driven");
248 case SQL_CURSOR_DYNAMIC
:
249 cout
<< wxT("Dynamic");
252 cout
<< endl
<< endl
;
255 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
257 // Force the use of a forward only cursor...
258 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
259 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
261 // Should never happen
262 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
269 pDb
->DispNextError();
270 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
273 #ifdef DBDEBUG_CONSOLE
275 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
280 // Set the cursor type for the INSERT statement handle
281 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
282 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
283 // Set the cursor type for the DELETE statement handle
284 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
285 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
286 // Set the cursor type for the UPDATE statement handle
287 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
288 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
291 // Make the default cursor the active cursor
292 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
293 wxASSERT(hstmtDefault
);
294 hstmt
= *hstmtDefault
;
298 } // wxDbTable::initialize()
301 void wxDbTable::cleanup()
306 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
313 TablesInUse
.DeleteContents(TRUE
);
317 pNode
= TablesInUse
.First();
318 while (pNode
&& !found
)
320 if (((wxTablesInUse
*)pNode
->Data())->tableID
== tableID
)
323 if (!TablesInUse
.DeleteNode(pNode
))
324 wxLogDebug (s
,wxT("Unable to delete node!"));
327 pNode
= pNode
->Next();
332 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
333 wxLogDebug (msg
,wxT("NOTICE..."));
338 // Decrement the wxDb table count
340 pDb
->decrementTableCount();
342 // Delete memory allocated for column definitions
346 // Free statement handles
352 ODBC 3.0 says to use this form
353 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
355 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
356 pDb
->DispAllErrors(henv
, hdbc
);
362 ODBC 3.0 says to use this form
363 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
365 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
366 pDb
->DispAllErrors(henv
, hdbc
);
372 ODBC 3.0 says to use this form
373 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
375 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
376 pDb
->DispAllErrors(henv
, hdbc
);
382 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
383 pDb
->DispAllErrors(henv
, hdbc
);
386 // Delete dynamically allocated cursors
388 DeleteCursor(hstmtDefault
);
391 DeleteCursor(hstmtCount
);
393 if (m_hstmtGridQuery
)
394 DeleteCursor(m_hstmtGridQuery
);
396 } // wxDbTable::cleanup()
399 /***************************** PRIVATE FUNCTIONS *****************************/
402 /********** wxDbTable::bindParams() **********/
403 bool wxDbTable::bindParams(bool forUpdate
)
405 wxASSERT(!queryOnly
);
410 UDWORD precision
= 0;
413 // Bind each column of the table that should be bound
414 // to a parameter marker
418 for (i
=0, colNo
=1; i
< noCols
; i
++)
422 if (!colDefs
[i
].Updateable
)
427 if (!colDefs
[i
].InsertAllowed
)
431 switch(colDefs
[i
].DbDataType
)
433 case DB_DATA_TYPE_VARCHAR
:
434 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
435 precision
= colDefs
[i
].SzDataObj
;
438 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
440 colDefs
[i
].CbValue
= SQL_NTS
;
442 case DB_DATA_TYPE_INTEGER
:
443 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
444 precision
= pDb
->GetTypeInfInteger().Precision
;
447 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
449 colDefs
[i
].CbValue
= 0;
451 case DB_DATA_TYPE_FLOAT
:
452 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
453 precision
= pDb
->GetTypeInfFloat().Precision
;
454 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
455 // SQL Sybase Anywhere v5.5 returned a negative number for the
456 // MaxScale. This caused ODBC to kick out an error on ibscale.
457 // I check for this here and set the scale = precision.
459 // scale = (short) precision;
461 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
463 colDefs
[i
].CbValue
= 0;
465 case DB_DATA_TYPE_DATE
:
466 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
467 precision
= pDb
->GetTypeInfDate().Precision
;
470 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
472 colDefs
[i
].CbValue
= 0;
474 case DB_DATA_TYPE_BLOB
:
475 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
479 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
481 colDefs
[i
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[i
].SzDataObj
);
486 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
487 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
488 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
490 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
495 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
496 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
497 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
499 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
504 // Completed successfully
507 } // wxDbTable::bindParams()
510 /********** wxDbTable::bindInsertParams() **********/
511 bool wxDbTable::bindInsertParams(void)
513 return bindParams(FALSE
);
514 } // wxDbTable::bindInsertParams()
517 /********** wxDbTable::bindUpdateParams() **********/
518 bool wxDbTable::bindUpdateParams(void)
520 return bindParams(TRUE
);
521 } // wxDbTable::bindUpdateParams()
524 /********** wxDbTable::bindCols() **********/
525 bool wxDbTable::bindCols(HSTMT cursor
)
527 // Bind each column of the table to a memory address for fetching data
529 for (i
= 0; i
< noCols
; i
++)
531 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
532 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
534 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
538 // Completed successfully
541 } // wxDbTable::bindCols()
544 /********** wxDbTable::getRec() **********/
545 bool wxDbTable::getRec(UWORD fetchType
)
549 if (!pDb
->FwdOnlyCursors())
551 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
555 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
556 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
558 if (retcode
== SQL_NO_DATA_FOUND
)
561 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
565 // Set the Null member variable to indicate the Null state
566 // of each column just read in.
568 for (i
= 0; i
< noCols
; i
++)
569 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
574 // Fetch the next record from the record set
575 retcode
= SQLFetch(hstmt
);
576 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
578 if (retcode
== SQL_NO_DATA_FOUND
)
581 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
585 // Set the Null member variable to indicate the Null state
586 // of each column just read in.
588 for (i
= 0; i
< noCols
; i
++)
589 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
593 // Completed successfully
596 } // wxDbTable::getRec()
599 /********** wxDbTable::execDelete() **********/
600 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
604 // Execute the DELETE statement
605 retcode
= SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
607 if (retcode
== SQL_SUCCESS
||
608 retcode
== SQL_NO_DATA_FOUND
||
609 retcode
== SQL_SUCCESS_WITH_INFO
)
611 // Record deleted successfully
615 // Problem deleting record
616 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
618 } // wxDbTable::execDelete()
621 /********** wxDbTable::execUpdate() **********/
622 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
626 // Execute the UPDATE statement
627 retcode
= SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
629 if (retcode
== SQL_SUCCESS
||
630 retcode
== SQL_NO_DATA_FOUND
||
631 retcode
== SQL_SUCCESS_WITH_INFO
)
633 // Record updated successfully
637 // Problem updating record
638 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
640 } // wxDbTable::execUpdate()
643 /********** wxDbTable::query() **********/
644 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
649 // The user may wish to select for update, but the DBMS may not be capable
650 selectForUpdate
= CanSelectForUpdate();
652 selectForUpdate
= FALSE
;
654 // Set the SQL SELECT string
655 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
656 { // so generate a select statement.
657 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
658 pDb
->WriteSqlLog(sqlStmt
);
661 // Make sure the cursor is closed first
662 if (!CloseCursor(hstmt
))
665 // Execute the SQL SELECT statement
667 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
668 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
669 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
671 // Completed successfully
674 } // wxDbTable::query()
677 /***************************** PUBLIC FUNCTIONS *****************************/
680 /********** wxDbTable::Open() **********/
681 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
691 // Calculate the maximum size of the concatenated
692 // keys for use with wxDbGrid
694 for (i
=0; i
< noCols
; i
++)
696 if (colDefs
[i
].KeyField
)
699 m_keysize
+= colDefs
[i
].SzDataObj
;
704 // Verify that the table exists in the database
705 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
707 s
= wxT("Table/view does not exist in the database");
708 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
709 s
+= wxT(", or you have no permissions.\n");
713 else if (checkPrivileges
)
715 // Verify the user has rights to access the table.
716 // Shortcut boolean evaluation to optimize out call to
719 // Unfortunately this optimization doesn't seem to be
721 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
722 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
723 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
730 if (!tablePath
.IsEmpty())
731 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
733 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
736 pDb
->LogError(p
.GetData());
741 // Bind the member variables for field exchange between
742 // the wxDbTable object and the ODBC record.
745 if (!bindInsertParams()) // Inserts
748 if (!bindUpdateParams()) // Updates
752 if (!bindCols(*hstmtDefault
)) // Selects
755 if (!bindCols(hstmtInternal
)) // Internal use only
759 * Do NOT bind the hstmtCount cursor!!!
762 // Build an insert statement using parameter markers
763 if (!queryOnly
&& noCols
> 0)
765 bool needComma
= FALSE
;
766 sqlStmt
.Printf(wxT("INSERT INTO %s ("), tableName
.c_str());
767 for (i
= 0; i
< noCols
; i
++)
769 if (! colDefs
[i
].InsertAllowed
)
773 sqlStmt
+= colDefs
[i
].ColName
;
777 sqlStmt
+= wxT(") VALUES (");
779 int insertableCount
= 0;
781 for (i
= 0; i
< noCols
; i
++)
783 if (! colDefs
[i
].InsertAllowed
)
793 // Prepare the insert statement for execution
796 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
797 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
803 // Completed successfully
806 } // wxDbTable::Open()
809 /********** wxDbTable::Query() **********/
810 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
813 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
815 } // wxDbTable::Query()
818 /********** wxDbTable::QueryBySqlStmt() **********/
819 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
821 pDb
->WriteSqlLog(pSqlStmt
);
823 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
825 } // wxDbTable::QueryBySqlStmt()
828 /********** wxDbTable::QueryMatching() **********/
829 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
832 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
834 } // wxDbTable::QueryMatching()
837 /********** wxDbTable::QueryOnKeyFields() **********/
838 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
841 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
843 } // wxDbTable::QueryOnKeyFields()
846 /********** wxDbTable::GetPrev() **********/
847 bool wxDbTable::GetPrev(void)
849 if (pDb
->FwdOnlyCursors())
851 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
855 return(getRec(SQL_FETCH_PRIOR
));
857 } // wxDbTable::GetPrev()
860 /********** wxDbTable::operator-- **********/
861 bool wxDbTable::operator--(int)
863 if (pDb
->FwdOnlyCursors())
865 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
869 return(getRec(SQL_FETCH_PRIOR
));
871 } // wxDbTable::operator--
874 /********** wxDbTable::GetFirst() **********/
875 bool wxDbTable::GetFirst(void)
877 if (pDb
->FwdOnlyCursors())
879 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
883 return(getRec(SQL_FETCH_FIRST
));
885 } // wxDbTable::GetFirst()
888 /********** wxDbTable::GetLast() **********/
889 bool wxDbTable::GetLast(void)
891 if (pDb
->FwdOnlyCursors())
893 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
897 return(getRec(SQL_FETCH_LAST
));
899 } // wxDbTable::GetLast()
902 /********** wxDbTable::BuildDeleteStmt() **********/
903 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
905 wxASSERT(!queryOnly
);
909 wxString whereClause
;
913 // Handle the case of DeleteWhere() and the where clause is blank. It should
914 // delete all records from the database in this case.
915 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
917 pSqlStmt
.Printf(wxT("DELETE FROM %s"), tableName
.c_str());
921 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "), tableName
.c_str());
923 // Append the WHERE clause to the SQL DELETE statement
926 case DB_DEL_KEYFIELDS
:
927 // If the datasource supports the ROWID column, build
928 // the where on ROWID for efficiency purposes.
929 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
933 wxChar rowid
[wxDB_ROWID_LEN
+1];
935 // Get the ROWID value. If not successful retreiving the ROWID,
936 // simply fall down through the code and build the WHERE clause
937 // based on the key fields.
938 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
940 pSqlStmt
+= wxT("ROWID = '");
942 pSqlStmt
+= wxT("'");
946 // Unable to delete by ROWID, so build a WHERE
947 // clause based on the keyfields.
948 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
949 pSqlStmt
+= whereClause
;
952 pSqlStmt
+= pWhereClause
;
954 case DB_DEL_MATCHING
:
955 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
956 pSqlStmt
+= whereClause
;
960 } // BuildDeleteStmt()
963 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
964 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
966 wxString tempSqlStmt
;
967 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
968 wxStrcpy(pSqlStmt
, tempSqlStmt
);
969 } // wxDbTable::BuildDeleteStmt()
972 /********** wxDbTable::BuildSelectStmt() **********/
973 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
975 wxString whereClause
;
978 // Build a select statement to query the database
979 pSqlStmt
= wxT("SELECT ");
981 // SELECT DISTINCT values only?
983 pSqlStmt
+= wxT("DISTINCT ");
985 // Was a FROM clause specified to join tables to the base table?
986 // Available for ::Query() only!!!
987 bool appendFromClause
= FALSE
;
988 #if wxODBC_BACKWARD_COMPATABILITY
989 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
990 appendFromClause
= TRUE
;
992 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
993 appendFromClause
= TRUE
;
996 // Add the column list
998 for (i
= 0; i
< noCols
; i
++)
1000 // If joining tables, the base table column names must be qualified to avoid ambiguity
1001 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1003 pSqlStmt
+= queryTableName
;
1004 pSqlStmt
+= wxT(".");
1006 pSqlStmt
+= colDefs
[i
].ColName
;
1008 pSqlStmt
+= wxT(",");
1011 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1012 // the ROWID if querying distinct records. The rowid will always be unique.
1013 if (!distinct
&& CanUpdByROWID())
1015 // If joining tables, the base table column names must be qualified to avoid ambiguity
1016 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1018 pSqlStmt
+= wxT(",");
1019 pSqlStmt
+= queryTableName
;
1020 pSqlStmt
+= wxT(".ROWID");
1023 pSqlStmt
+= wxT(",ROWID");
1026 // Append the FROM tablename portion
1027 pSqlStmt
+= wxT(" FROM ");
1028 pSqlStmt
+= queryTableName
;
1030 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1031 // The HOLDLOCK keyword follows the table name in the from clause.
1032 // Each table in the from clause must specify HOLDLOCK or
1033 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1034 // is parsed but ignored in SYBASE Transact-SQL.
1035 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1036 pSqlStmt
+= wxT(" HOLDLOCK");
1038 if (appendFromClause
)
1041 // Append the WHERE clause. Either append the where clause for the class
1042 // or build a where clause. The typeOfSelect determines this.
1043 switch(typeOfSelect
)
1045 case DB_SELECT_WHERE
:
1046 #if wxODBC_BACKWARD_COMPATABILITY
1047 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1049 if (where
.Length()) // May not want a where clause!!!
1052 pSqlStmt
+= wxT(" WHERE ");
1056 case DB_SELECT_KEYFIELDS
:
1057 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1058 if (whereClause
.Length())
1060 pSqlStmt
+= wxT(" WHERE ");
1061 pSqlStmt
+= whereClause
;
1064 case DB_SELECT_MATCHING
:
1065 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1066 if (whereClause
.Length())
1068 pSqlStmt
+= wxT(" WHERE ");
1069 pSqlStmt
+= whereClause
;
1074 // Append the ORDER BY clause
1075 #if wxODBC_BACKWARD_COMPATABILITY
1076 if (orderBy
&& wxStrlen(orderBy
))
1078 if (orderBy
.Length())
1081 pSqlStmt
+= wxT(" ORDER BY ");
1082 pSqlStmt
+= orderBy
;
1085 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1086 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1087 // HOLDLOCK for Sybase.
1088 if (selectForUpdate
&& CanSelectForUpdate())
1089 pSqlStmt
+= wxT(" FOR UPDATE");
1091 } // wxDbTable::BuildSelectStmt()
1094 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1095 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1097 wxString tempSqlStmt
;
1098 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1099 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1100 } // wxDbTable::BuildSelectStmt()
1103 /********** wxDbTable::BuildUpdateStmt() **********/
1104 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1106 wxASSERT(!queryOnly
);
1110 wxString whereClause
;
1111 whereClause
.Empty();
1113 bool firstColumn
= TRUE
;
1115 pSqlStmt
.Printf(wxT("UPDATE %s SET "), tableName
.Upper().c_str());
1117 // Append a list of columns to be updated
1119 for (i
= 0; i
< noCols
; i
++)
1121 // Only append Updateable columns
1122 if (colDefs
[i
].Updateable
)
1125 pSqlStmt
+= wxT(",");
1127 firstColumn
= FALSE
;
1128 pSqlStmt
+= colDefs
[i
].ColName
;
1129 pSqlStmt
+= wxT(" = ?");
1133 // Append the WHERE clause to the SQL UPDATE statement
1134 pSqlStmt
+= wxT(" WHERE ");
1137 case DB_UPD_KEYFIELDS
:
1138 // If the datasource supports the ROWID column, build
1139 // the where on ROWID for efficiency purposes.
1140 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1141 if (CanUpdByROWID())
1144 wxChar rowid
[wxDB_ROWID_LEN
+1];
1146 // Get the ROWID value. If not successful retreiving the ROWID,
1147 // simply fall down through the code and build the WHERE clause
1148 // based on the key fields.
1149 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1151 pSqlStmt
+= wxT("ROWID = '");
1153 pSqlStmt
+= wxT("'");
1157 // Unable to delete by ROWID, so build a WHERE
1158 // clause based on the keyfields.
1159 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1160 pSqlStmt
+= whereClause
;
1163 pSqlStmt
+= pWhereClause
;
1166 } // BuildUpdateStmt()
1169 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1170 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1172 wxString tempSqlStmt
;
1173 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1174 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1175 } // BuildUpdateStmt()
1178 /********** wxDbTable::BuildWhereClause() **********/
1179 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1180 const wxString
&qualTableName
, bool useLikeComparison
)
1182 * Note: BuildWhereClause() currently ignores timestamp columns.
1183 * They are not included as part of the where clause.
1186 bool moreThanOneColumn
= FALSE
;
1189 // Loop through the columns building a where clause as you go
1191 for (i
= 0; i
< noCols
; i
++)
1193 // Determine if this column should be included in the WHERE clause
1194 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1195 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(i
))))
1197 // Skip over timestamp columns
1198 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1200 // If there is more than 1 column, join them with the keyword "AND"
1201 if (moreThanOneColumn
)
1202 pWhereClause
+= wxT(" AND ");
1204 moreThanOneColumn
= TRUE
;
1205 // Concatenate where phrase for the column
1206 if (qualTableName
.Length())
1208 pWhereClause
+= qualTableName
;
1209 pWhereClause
+= wxT(".");
1211 pWhereClause
+= colDefs
[i
].ColName
;
1212 if (useLikeComparison
&& (colDefs
[i
].SqlCtype
== SQL_C_CHAR
))
1213 pWhereClause
+= wxT(" LIKE ");
1215 pWhereClause
+= wxT(" = ");
1216 switch(colDefs
[i
].SqlCtype
)
1219 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1222 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[i
].PtrDataObj
));
1225 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[i
].PtrDataObj
));
1228 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1231 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1234 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1237 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1240 pWhereClause
+= colValue
;
1243 } // wxDbTable::BuildWhereClause()
1246 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1247 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1248 const wxString
&qualTableName
, bool useLikeComparison
)
1250 wxString tempSqlStmt
;
1251 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1252 wxStrcpy(pWhereClause
, tempSqlStmt
);
1253 } // wxDbTable::BuildWhereClause()
1256 /********** wxDbTable::GetRowNum() **********/
1257 UWORD
wxDbTable::GetRowNum(void)
1261 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1263 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1267 // Completed successfully
1268 return((UWORD
) rowNum
);
1270 } // wxDbTable::GetRowNum()
1273 /********** wxDbTable::CloseCursor() **********/
1274 bool wxDbTable::CloseCursor(HSTMT cursor
)
1276 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1277 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1279 // Completed successfully
1282 } // wxDbTable::CloseCursor()
1285 /********** wxDbTable::CreateTable() **********/
1286 bool wxDbTable::CreateTable(bool attemptDrop
)
1294 #ifdef DBDEBUG_CONSOLE
1295 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1299 if (attemptDrop
&& !DropTable())
1303 #ifdef DBDEBUG_CONSOLE
1304 for (i
= 0; i
< noCols
; i
++)
1306 // Exclude derived columns since they are NOT part of the base table
1307 if (colDefs
[i
].DerivedCol
)
1309 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1310 switch(colDefs
[i
].DbDataType
)
1312 case DB_DATA_TYPE_VARCHAR
:
1313 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1315 case DB_DATA_TYPE_INTEGER
:
1316 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1318 case DB_DATA_TYPE_FLOAT
:
1319 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1321 case DB_DATA_TYPE_DATE
:
1322 cout
<< pDb
->GetTypeInfDate().TypeName
;
1324 case DB_DATA_TYPE_BLOB
:
1325 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1332 // Build a CREATE TABLE string from the colDefs structure.
1333 bool needComma
= FALSE
;
1334 sqlStmt
.Printf(wxT("CREATE TABLE %s ("), tableName
.c_str());
1336 for (i
= 0; i
< noCols
; i
++)
1338 // Exclude derived columns since they are NOT part of the base table
1339 if (colDefs
[i
].DerivedCol
)
1343 sqlStmt
+= wxT(",");
1345 sqlStmt
+= colDefs
[i
].ColName
;
1346 sqlStmt
+= wxT(" ");
1348 switch(colDefs
[i
].DbDataType
)
1350 case DB_DATA_TYPE_VARCHAR
:
1351 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1353 case DB_DATA_TYPE_INTEGER
:
1354 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1356 case DB_DATA_TYPE_FLOAT
:
1357 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1359 case DB_DATA_TYPE_DATE
:
1360 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1362 case DB_DATA_TYPE_BLOB
:
1363 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1366 // For varchars, append the size of the string
1367 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)// ||
1368 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1371 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1375 if (pDb
->Dbms() == dbmsDB2
||
1376 pDb
->Dbms() == dbmsMY_SQL
||
1377 pDb
->Dbms() == dbmsSYBASE_ASE
||
1378 pDb
->Dbms() == dbmsINTERBASE
||
1379 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1381 if (colDefs
[i
].KeyField
)
1383 sqlStmt
+= wxT(" NOT NULL");
1389 // If there is a primary key defined, include it in the create statement
1390 for (i
= j
= 0; i
< noCols
; i
++)
1392 if (colDefs
[i
].KeyField
)
1398 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
1400 switch (pDb
->Dbms())
1403 case dbmsSYBASE_ASA
:
1404 case dbmsSYBASE_ASE
:
1407 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1408 sqlStmt
+= wxT(",PRIMARY KEY (");
1413 sqlStmt
+= wxT(",CONSTRAINT ");
1414 // DB2 is limited to 18 characters for index names
1415 if (pDb
->Dbms() == dbmsDB2
)
1417 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."));
1418 sqlStmt
+= tableName
.substr(0, 13);
1421 sqlStmt
+= tableName
;
1423 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1428 // List column name(s) of column(s) comprising the primary key
1429 for (i
= j
= 0; i
< noCols
; i
++)
1431 if (colDefs
[i
].KeyField
)
1433 if (j
++) // Multi part key, comma separate names
1434 sqlStmt
+= wxT(",");
1435 sqlStmt
+= colDefs
[i
].ColName
;
1438 sqlStmt
+= wxT(")");
1440 if (pDb
->Dbms() == dbmsINFORMIX
||
1441 pDb
->Dbms() == dbmsSYBASE_ASA
||
1442 pDb
->Dbms() == dbmsSYBASE_ASE
)
1444 sqlStmt
+= wxT(" CONSTRAINT ");
1445 sqlStmt
+= tableName
;
1446 sqlStmt
+= wxT("_PIDX");
1449 // Append the closing parentheses for the create table statement
1450 sqlStmt
+= wxT(")");
1452 pDb
->WriteSqlLog(sqlStmt
);
1454 #ifdef DBDEBUG_CONSOLE
1455 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1458 // Execute the CREATE TABLE statement
1459 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1460 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1462 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1463 pDb
->RollbackTrans();
1468 // Commit the transaction and close the cursor
1469 if (!pDb
->CommitTrans())
1471 if (!CloseCursor(hstmt
))
1474 // Database table created successfully
1477 } // wxDbTable::CreateTable()
1480 /********** wxDbTable::DropTable() **********/
1481 bool wxDbTable::DropTable()
1483 // NOTE: This function returns TRUE if the Table does not exist, but
1484 // only for identified databases. Code will need to be added
1485 // below for any other databases when those databases are defined
1486 // to handle this situation consistently
1490 sqlStmt
.Printf(wxT("DROP TABLE %s"), tableName
.c_str());
1492 pDb
->WriteSqlLog(sqlStmt
);
1494 #ifdef DBDEBUG_CONSOLE
1495 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1501 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1502 if (retcode
!= SQL_SUCCESS
)
1504 // Check for "Base table not found" error and ignore
1505 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1506 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1507 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1509 // Check for product specific error codes
1510 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1511 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1512 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1513 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1515 pDb
->DispNextError();
1516 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1517 pDb
->RollbackTrans();
1518 // CloseCursor(hstmt);
1524 // Commit the transaction and close the cursor
1525 if (! pDb
->CommitTrans())
1527 if (! CloseCursor(hstmt
))
1531 } // wxDbTable::DropTable()
1534 /********** wxDbTable::CreateIndex() **********/
1535 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1536 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1540 // Drop the index first
1541 if (attemptDrop
&& !DropIndex(idxName
))
1544 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1545 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1546 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1547 // table was created, then months later you determine that an additional index while
1548 // give better performance, so you want to add an index).
1550 // The following block of code will modify the column definition to make the column be
1551 // defined with the "NOT NULL" qualifier.
1552 if (pDb
->Dbms() == dbmsMY_SQL
)
1557 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1561 // Find the column definition that has the ColName that matches the
1562 // index column name. We need to do this to get the DB_DATA_TYPE of
1563 // the index column, as MySQL's syntax for the ALTER column requires
1565 while (!found
&& (j
< this->noCols
))
1567 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1575 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1576 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1581 wxODBC_ERRORS retcode
;
1582 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1583 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1584 // This line is just here for debug checking of the value
1585 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1595 pDb
->RollbackTrans();
1600 // Build a CREATE INDEX statement
1601 sqlStmt
= wxT("CREATE ");
1603 sqlStmt
+= wxT("UNIQUE ");
1605 sqlStmt
+= wxT("INDEX ");
1607 sqlStmt
+= wxT(" ON ");
1608 sqlStmt
+= tableName
;
1609 sqlStmt
+= wxT(" (");
1611 // Append list of columns making up index
1613 for (i
= 0; i
< noIdxCols
; i
++)
1615 sqlStmt
+= pIdxDefs
[i
].ColName
;
1617 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1618 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (strncmp(pDb
->dbInf
.dbmsVer
,"07",2)==0)) &&
1619 !(pDb
->Dbms() == dbmsPOSTGRES
))
1621 if (pIdxDefs
[i
].Ascending
)
1622 sqlStmt
+= wxT(" ASC");
1624 sqlStmt
+= wxT(" DESC");
1627 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, "Datasource does not support DESCending index columns");
1629 if ((i
+ 1) < noIdxCols
)
1630 sqlStmt
+= wxT(",");
1633 // Append closing parentheses
1634 sqlStmt
+= wxT(")");
1636 pDb
->WriteSqlLog(sqlStmt
);
1638 #ifdef DBDEBUG_CONSOLE
1639 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1642 // Execute the CREATE INDEX statement
1643 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1645 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1646 pDb
->RollbackTrans();
1651 // Commit the transaction and close the cursor
1652 if (! pDb
->CommitTrans())
1654 if (! CloseCursor(hstmt
))
1657 // Index Created Successfully
1660 } // wxDbTable::CreateIndex()
1663 /********** wxDbTable::DropIndex() **********/
1664 bool wxDbTable::DropIndex(const wxString
&idxName
)
1666 // NOTE: This function returns TRUE if the Index does not exist, but
1667 // only for identified databases. Code will need to be added
1668 // below for any other databases when those databases are defined
1669 // to handle this situation consistently
1673 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1674 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1675 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),idxName
.c_str(), tableName
.c_str());
1676 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1677 (pDb
->Dbms() == dbmsSYBASE_ASE
))
1678 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),tableName
.c_str(), idxName
.c_str());
1680 sqlStmt
.Printf(wxT("DROP INDEX %s"),idxName
.c_str());
1682 pDb
->WriteSqlLog(sqlStmt
);
1684 #ifdef DBDEBUG_CONSOLE
1685 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1688 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1690 // Check for "Index not found" error and ignore
1691 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1692 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1694 // Check for product specific error codes
1695 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1696 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1697 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1698 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1699 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1700 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1701 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1704 pDb
->DispNextError();
1705 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1706 pDb
->RollbackTrans();
1713 // Commit the transaction and close the cursor
1714 if (! pDb
->CommitTrans())
1716 if (! CloseCursor(hstmt
))
1720 } // wxDbTable::DropIndex()
1723 /********** wxDbTable::SetOrderByColNums() **********/
1724 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1726 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1732 va_start(argptr
, first
); /* Initialize variable arguments. */
1733 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1735 // Make sure the passed in column number
1736 // is within the valid range of columns
1738 // Valid columns are 0 thru noCols-1
1739 if (colNo
>= noCols
|| colNo
< 0)
1746 tempStr
+= wxT(",");
1748 tempStr
+= colDefs
[colNo
].ColName
;
1749 colNo
= va_arg (argptr
, int);
1751 va_end (argptr
); /* Reset variable arguments. */
1753 SetOrderByClause(tempStr
);
1756 } // wxDbTable::SetOrderByColNums()
1759 /********** wxDbTable::Insert() **********/
1760 int wxDbTable::Insert(void)
1762 wxASSERT(!queryOnly
);
1763 if (queryOnly
|| !insertable
)
1768 // Insert the record by executing the already prepared insert statement
1770 retcode
=SQLExecute(hstmtInsert
);
1771 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1773 // Check to see if integrity constraint was violated
1774 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1775 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1776 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1779 pDb
->DispNextError();
1780 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1785 // Record inserted into the datasource successfully
1788 } // wxDbTable::Insert()
1791 /********** wxDbTable::Update() **********/
1792 bool wxDbTable::Update(void)
1794 wxASSERT(!queryOnly
);
1800 // Build the SQL UPDATE statement
1801 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1803 pDb
->WriteSqlLog(sqlStmt
);
1805 #ifdef DBDEBUG_CONSOLE
1806 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1809 // Execute the SQL UPDATE statement
1810 return(execUpdate(sqlStmt
));
1812 } // wxDbTable::Update()
1815 /********** wxDbTable::Update(pSqlStmt) **********/
1816 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1818 wxASSERT(!queryOnly
);
1822 pDb
->WriteSqlLog(pSqlStmt
);
1824 return(execUpdate(pSqlStmt
));
1826 } // wxDbTable::Update(pSqlStmt)
1829 /********** wxDbTable::UpdateWhere() **********/
1830 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1832 wxASSERT(!queryOnly
);
1838 // Build the SQL UPDATE statement
1839 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1841 pDb
->WriteSqlLog(sqlStmt
);
1843 #ifdef DBDEBUG_CONSOLE
1844 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1847 // Execute the SQL UPDATE statement
1848 return(execUpdate(sqlStmt
));
1850 } // wxDbTable::UpdateWhere()
1853 /********** wxDbTable::Delete() **********/
1854 bool wxDbTable::Delete(void)
1856 wxASSERT(!queryOnly
);
1863 // Build the SQL DELETE statement
1864 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1866 pDb
->WriteSqlLog(sqlStmt
);
1868 // Execute the SQL DELETE statement
1869 return(execDelete(sqlStmt
));
1871 } // wxDbTable::Delete()
1874 /********** wxDbTable::DeleteWhere() **********/
1875 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
1877 wxASSERT(!queryOnly
);
1884 // Build the SQL DELETE statement
1885 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1887 pDb
->WriteSqlLog(sqlStmt
);
1889 // Execute the SQL DELETE statement
1890 return(execDelete(sqlStmt
));
1892 } // wxDbTable::DeleteWhere()
1895 /********** wxDbTable::DeleteMatching() **********/
1896 bool wxDbTable::DeleteMatching(void)
1898 wxASSERT(!queryOnly
);
1905 // Build the SQL DELETE statement
1906 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1908 pDb
->WriteSqlLog(sqlStmt
);
1910 // Execute the SQL DELETE statement
1911 return(execDelete(sqlStmt
));
1913 } // wxDbTable::DeleteMatching()
1916 /********** wxDbTable::IsColNull() **********/
1917 bool wxDbTable::IsColNull(UWORD colNo
) const
1920 This logic is just not right. It would indicate TRUE
1921 if a numeric field were set to a value of 0.
1923 switch(colDefs[colNo].SqlCtype)
1926 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
1928 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
1930 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
1932 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1934 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1936 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
1938 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
1939 case SQL_C_TIMESTAMP:
1940 TIMESTAMP_STRUCT *pDt;
1941 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
1942 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
1950 return (colDefs
[colNo
].Null
);
1951 } // wxDbTable::IsColNull()
1954 /********** wxDbTable::CanSelectForUpdate() **********/
1955 bool wxDbTable::CanSelectForUpdate(void)
1960 if (pDb
->Dbms() == dbmsMY_SQL
)
1963 if ((pDb
->Dbms() == dbmsORACLE
) ||
1964 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
1969 } // wxDbTable::CanSelectForUpdate()
1972 /********** wxDbTable::CanUpdByROWID() **********/
1973 bool wxDbTable::CanUpdByROWID(void)
1976 * NOTE: Returning FALSE for now until this can be debugged,
1977 * as the ROWID is not getting updated correctly
1981 if (pDb->Dbms() == dbmsORACLE)
1986 } // wxDbTable::CanUpdByROWID()
1989 /********** wxDbTable::IsCursorClosedOnCommit() **********/
1990 bool wxDbTable::IsCursorClosedOnCommit(void)
1992 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
1997 } // wxDbTable::IsCursorClosedOnCommit()
2001 /********** wxDbTable::ClearMemberVar() **********/
2002 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2004 wxASSERT(colNo
< noCols
);
2006 switch(colDefs
[colNo
].SqlCtype
)
2009 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2012 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2015 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2018 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2021 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2024 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2027 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2029 case SQL_C_TIMESTAMP
:
2030 TIMESTAMP_STRUCT
*pDt
;
2031 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2044 } // wxDbTable::ClearMemberVar()
2047 /********** wxDbTable::ClearMemberVars() **********/
2048 void wxDbTable::ClearMemberVars(bool setToNull
)
2052 // Loop through the columns setting each member variable to zero
2053 for (i
=0; i
< noCols
; i
++)
2054 ClearMemberVar(i
,setToNull
);
2056 } // wxDbTable::ClearMemberVars()
2059 /********** wxDbTable::SetQueryTimeout() **********/
2060 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2062 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2063 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2064 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2065 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2066 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2067 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2068 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2069 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2071 // Completed Successfully
2074 } // wxDbTable::SetQueryTimeout()
2077 /********** wxDbTable::SetColDefs() **********/
2078 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2079 SWORD cType
, int size
, bool keyField
, bool upd
,
2080 bool insAllow
, bool derivedCol
)
2082 if (!colDefs
) // May happen if the database connection fails
2085 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2087 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2088 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2092 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2093 fieldName
.c_str(),colDefs
[index
].ColName
);
2095 #endif // __WXDEBUG__
2098 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2100 colDefs
[index
].DbDataType
= dataType
;
2101 colDefs
[index
].PtrDataObj
= pData
;
2102 colDefs
[index
].SqlCtype
= cType
;
2103 colDefs
[index
].SzDataObj
= size
;
2104 colDefs
[index
].KeyField
= keyField
;
2105 colDefs
[index
].DerivedCol
= derivedCol
;
2106 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2109 colDefs
[index
].Updateable
= FALSE
;
2110 colDefs
[index
].InsertAllowed
= FALSE
;
2114 colDefs
[index
].Updateable
= upd
;
2115 colDefs
[index
].InsertAllowed
= insAllow
;
2118 colDefs
[index
].Null
= FALSE
;
2120 } // wxDbTable::SetColDefs()
2123 /********** wxDbTable::SetColDefs() **********/
2124 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2127 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2133 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2135 for (index
= 0; index
< numCols
; index
++)
2137 // Process the fields
2138 switch (pColInfs
[index
].dbDataType
)
2140 case DB_DATA_TYPE_VARCHAR
:
2141 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2142 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2143 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2145 case DB_DATA_TYPE_INTEGER
:
2146 // Can be long or short
2147 if (pColInfs
[index
].bufferLength
== sizeof(long))
2149 pColDataPtrs
[index
].PtrDataObj
= new long;
2150 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2151 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2155 pColDataPtrs
[index
].PtrDataObj
= new short;
2156 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2157 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2160 case DB_DATA_TYPE_FLOAT
:
2161 // Can be float or double
2162 if (pColInfs
[index
].bufferLength
== sizeof(float))
2164 pColDataPtrs
[index
].PtrDataObj
= new float;
2165 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2166 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2170 pColDataPtrs
[index
].PtrDataObj
= new double;
2171 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2172 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2175 case DB_DATA_TYPE_DATE
:
2176 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2177 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2178 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2180 case DB_DATA_TYPE_BLOB
:
2181 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2182 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2183 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2184 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2187 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2188 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2191 // Unable to build all the column definitions, as either one of
2192 // the calls to "new" failed above, or there was a BLOB field
2193 // to have a column definition for. If BLOBs are to be used,
2194 // the other form of ::SetColDefs() must be used, as it is impossible
2195 // to know the maximum size to create the PtrDataObj to be.
2196 delete [] pColDataPtrs
;
2202 return (pColDataPtrs
);
2204 } // wxDbTable::SetColDefs()
2207 /********** wxDbTable::SetCursor() **********/
2208 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2210 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2211 hstmt
= *hstmtDefault
;
2213 hstmt
= *hstmtActivate
;
2215 } // wxDbTable::SetCursor()
2218 /********** wxDbTable::Count(const wxString &) **********/
2219 ULONG
wxDbTable::Count(const wxString
&args
)
2225 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2226 sqlStmt
= wxT("SELECT COUNT(");
2228 sqlStmt
+= wxT(") FROM ");
2229 sqlStmt
+= queryTableName
;
2230 #if wxODBC_BACKWARD_COMPATABILITY
2231 if (from
&& wxStrlen(from
))
2237 // Add the where clause if one is provided
2238 #if wxODBC_BACKWARD_COMPATABILITY
2239 if (where
&& wxStrlen(where
))
2244 sqlStmt
+= wxT(" WHERE ");
2248 pDb
->WriteSqlLog(sqlStmt
);
2250 // Initialize the Count cursor if it's not already initialized
2253 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2254 wxASSERT(hstmtCount
);
2259 // Execute the SQL statement
2260 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2262 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2267 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2269 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2273 // Obtain the result
2274 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2276 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2281 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2282 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2284 // Return the record count
2287 } // wxDbTable::Count()
2290 /********** wxDbTable::Refresh() **********/
2291 bool wxDbTable::Refresh(void)
2295 // Switch to the internal cursor so any active cursors are not corrupted
2296 HSTMT currCursor
= GetCursor();
2297 hstmt
= hstmtInternal
;
2298 #if wxODBC_BACKWARD_COMPATABILITY
2299 // Save the where and order by clauses
2300 char *saveWhere
= where
;
2301 char *saveOrderBy
= orderBy
;
2303 wxString saveWhere
= where
;
2304 wxString saveOrderBy
= orderBy
;
2306 // Build a where clause to refetch the record with. Try and use the
2307 // ROWID if it's available, ow use the key fields.
2308 wxString whereClause
;
2309 whereClause
.Empty();
2311 if (CanUpdByROWID())
2314 wxChar rowid
[wxDB_ROWID_LEN
+1];
2316 // Get the ROWID value. If not successful retreiving the ROWID,
2317 // simply fall down through the code and build the WHERE clause
2318 // based on the key fields.
2319 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2321 whereClause
+= queryTableName
;
2322 whereClause
+= wxT(".ROWID = '");
2323 whereClause
+= rowid
;
2324 whereClause
+= wxT("'");
2328 // If unable to use the ROWID, build a where clause from the keyfields
2329 if (wxStrlen(whereClause
) == 0)
2330 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2332 // Requery the record
2333 where
= whereClause
;
2338 if (result
&& !GetNext())
2341 // Switch back to original cursor
2342 SetCursor(&currCursor
);
2344 // Free the internal cursor
2345 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2346 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2348 // Restore the original where and order by clauses
2350 orderBy
= saveOrderBy
;
2354 } // wxDbTable::Refresh()
2357 /********** wxDbTable::SetColNull() **********/
2358 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2362 colDefs
[colNo
].Null
= set
;
2363 if (set
) // Blank out the values in the member variable
2364 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2370 } // wxDbTable::SetColNull()
2373 /********** wxDbTable::SetColNull() **********/
2374 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2377 for (i
= 0; i
< noCols
; i
++)
2379 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2385 colDefs
[i
].Null
= set
;
2386 if (set
) // Blank out the values in the member variable
2387 ClearMemberVar(i
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2393 } // wxDbTable::SetColNull()
2396 /********** wxDbTable::GetNewCursor() **********/
2397 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2399 HSTMT
*newHSTMT
= new HSTMT
;
2404 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2406 pDb
->DispAllErrors(henv
, hdbc
);
2411 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2413 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2420 if (!bindCols(*newHSTMT
))
2428 SetCursor(newHSTMT
);
2432 } // wxDbTable::GetNewCursor()
2435 /********** wxDbTable::DeleteCursor() **********/
2436 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2440 if (!hstmtDel
) // Cursor already deleted
2444 ODBC 3.0 says to use this form
2445 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2448 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2450 pDb
->DispAllErrors(henv
, hdbc
);
2458 } // wxDbTable::DeleteCursor()
2460 //////////////////////////////////////////////////////////////
2461 // wxDbGrid support functions
2462 //////////////////////////////////////////////////////////////
2464 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2466 if (!m_hstmtGridQuery
)
2468 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2469 if (!bindCols(*m_hstmtGridQuery
))
2473 m_rowmode
= rowmode
;
2476 case WX_ROW_MODE_QUERY
:
2477 SetCursor(m_hstmtGridQuery
);
2479 case WX_ROW_MODE_INDIVIDUAL
:
2480 SetCursor(hstmtDefault
);
2485 } // wxDbTable::SetRowMode()
2488 wxVariant
wxDbTable::GetCol(const int col
) const
2491 if ((col
< noCols
) && (!IsColNull(col
)))
2493 switch (colDefs
[col
].SqlCtype
)
2497 val
= (char *)(colDefs
[col
].PtrDataObj
);
2501 val
= *(long *)(colDefs
[col
].PtrDataObj
);
2505 val
= (long int )(*(short *)(colDefs
[col
].PtrDataObj
));
2508 val
= (long)(*(unsigned long *)(colDefs
[col
].PtrDataObj
));
2511 val
= (long)(*(char *)(colDefs
[col
].PtrDataObj
));
2513 case SQL_C_UTINYINT
:
2514 val
= (long)(*(unsigned char *)(colDefs
[col
].PtrDataObj
));
2517 val
= (long)(*(UWORD
*)(colDefs
[col
].PtrDataObj
));
2520 val
= (DATE_STRUCT
*)(colDefs
[col
].PtrDataObj
);
2523 val
= (TIME_STRUCT
*)(colDefs
[col
].PtrDataObj
);
2525 case SQL_C_TIMESTAMP
:
2526 val
= (TIMESTAMP_STRUCT
*)(colDefs
[col
].PtrDataObj
);
2529 val
= *(double *)(colDefs
[col
].PtrDataObj
);
2536 } // wxDbTable::GetCol()
2539 void csstrncpyt(char *s
, const char *t
, int n
)
2541 while ((*s
++ = *t
++) && --n
)
2547 void wxDbTable::SetCol(const int col
, const wxVariant val
)
2549 //FIXME: Add proper wxDateTime support to wxVariant..
2552 SetColNull(col
, val
.IsNull());
2556 if ((colDefs
[col
].SqlCtype
== SQL_C_DATE
)
2557 || (colDefs
[col
].SqlCtype
== SQL_C_TIME
)
2558 || (colDefs
[col
].SqlCtype
== SQL_C_TIMESTAMP
))
2560 //Returns null if invalid!
2561 if (!dateval
.ParseDate(val
.GetString()))
2562 SetColNull(col
,TRUE
);
2565 switch (colDefs
[col
].SqlCtype
)
2569 csstrncpyt((char *)(colDefs
[col
].PtrDataObj
),
2570 val
.GetString().c_str(),
2571 colDefs
[col
].SzDataObj
-1);
2575 *(long *)(colDefs
[col
].PtrDataObj
) = val
;
2579 *(short *)(colDefs
[col
].PtrDataObj
) = val
.GetLong();
2582 *(unsigned long *)(colDefs
[col
].PtrDataObj
) = val
.GetLong();
2585 *(char *)(colDefs
[col
].PtrDataObj
) = val
.GetChar();
2587 case SQL_C_UTINYINT
:
2588 *(unsigned char *)(colDefs
[col
].PtrDataObj
) = val
.GetChar();
2591 *(unsigned short *)(colDefs
[col
].PtrDataObj
) = val
.GetLong();
2593 //FIXME: Add proper wxDateTime support to wxVariant..
2596 DATE_STRUCT
*dataptr
=
2597 (DATE_STRUCT
*)colDefs
[col
].PtrDataObj
;
2599 dataptr
->year
= dateval
.GetYear();
2600 dataptr
->month
= dateval
.GetMonth()+1;
2601 dataptr
->day
= dateval
.GetDay();
2606 TIME_STRUCT
*dataptr
=
2607 (TIME_STRUCT
*)colDefs
[col
].PtrDataObj
;
2609 dataptr
->hour
= dateval
.GetHour();
2610 dataptr
->minute
= dateval
.GetMinute();
2611 dataptr
->second
= dateval
.GetSecond();
2614 case SQL_C_TIMESTAMP
:
2616 TIMESTAMP_STRUCT
*dataptr
=
2617 (TIMESTAMP_STRUCT
*)colDefs
[col
].PtrDataObj
;
2618 dataptr
->year
= dateval
.GetYear();
2619 dataptr
->month
= dateval
.GetMonth()+1;
2620 dataptr
->day
= dateval
.GetDay();
2622 dataptr
->hour
= dateval
.GetHour();
2623 dataptr
->minute
= dateval
.GetMinute();
2624 dataptr
->second
= dateval
.GetSecond();
2628 *(double *)(colDefs
[col
].PtrDataObj
) = val
;
2633 } // if (!val.IsNull())
2634 } // wxDbTable::SetCol()
2637 GenericKey
wxDbTable::GetKey()
2642 blk
= malloc(m_keysize
);
2643 blkptr
= (char *) blk
;
2646 for (i
=0; i
< noCols
; i
++)
2648 if (colDefs
[i
].KeyField
)
2650 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2651 blkptr
+= colDefs
[i
].SzDataObj
;
2655 GenericKey k
= GenericKey(blk
, m_keysize
);
2659 } // wxDbTable::GetKey()
2662 void wxDbTable::SetKey(const GenericKey
& k
)
2668 blkptr
= (char *)blk
;
2671 for (i
=0; i
< noCols
; i
++)
2673 if (colDefs
[i
].KeyField
)
2675 SetColNull(i
, FALSE
);
2676 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2677 blkptr
+= colDefs
[i
].SzDataObj
;
2680 } // wxDbTable::SetKey()
2683 #endif // wxUSE_ODBC