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"
47 #include "wx/msgdlg.h"
50 #include "wx/filefn.h"
59 #include "wx/dbtable.h"
62 // The HPUX preprocessor lines below were commented out on 8/20/97
63 // because macros.h currently redefines DEBUG and is unneeded.
65 // # include <macros.h>
68 # include <sys/minmax.h>
72 ULONG lastTableID
= 0;
80 /********** wxDbColDef::wxDbColDef() Constructor **********/
81 wxDbColDef::wxDbColDef()
87 bool wxDbColDef::Initialize()
90 DbDataType
= DB_DATA_TYPE_INTEGER
;
91 SqlCtype
= SQL_C_LONG
;
96 InsertAllowed
= FALSE
;
102 } // wxDbColDef::Initialize()
105 /********** wxDbTable::wxDbTable() Constructor **********/
106 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
107 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
109 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
111 } // wxDbTable::wxDbTable()
114 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
115 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
116 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
118 wxString tempQryTblName
;
119 tempQryTblName
= qryTblName
;
120 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
122 } // wxDbTable::wxDbTable()
125 /********** wxDbTable::~wxDbTable() **********/
126 wxDbTable::~wxDbTable()
129 } // wxDbTable::~wxDbTable()
132 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
133 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
135 // Initializing member variables
136 pDb
= pwxDb
; // Pointer to the wxDb object
140 m_hstmtGridQuery
= 0;
141 hstmtDefault
= 0; // Initialized below
142 hstmtCount
= 0; // Initialized first time it is needed
149 noCols
= numColumns
; // Number of cols in the table
150 where
.Empty(); // Where clause
151 orderBy
.Empty(); // Order By clause
152 from
.Empty(); // From clause
153 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
158 queryTableName
.Empty();
160 wxASSERT(tblName
.Length());
166 tableName
= tblName
; // Table Name
167 if (tblPath
.Length())
168 tablePath
= tblPath
; // Table Path - used for dBase files
172 if (qryTblName
.Length()) // Name of the table/view to query
173 queryTableName
= qryTblName
;
175 queryTableName
= tblName
;
177 pDb
->incrementTableCount();
180 tableID
= ++lastTableID
;
181 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
184 wxTablesInUse
*tableInUse
;
185 tableInUse
= new wxTablesInUse();
186 tableInUse
->tableName
= tblName
;
187 tableInUse
->tableID
= tableID
;
188 tableInUse
->pDb
= pDb
;
189 TablesInUse
.Append(tableInUse
);
194 // Grab the HENV and HDBC from the wxDb object
195 henv
= pDb
->GetHENV();
196 hdbc
= pDb
->GetHDBC();
198 // Allocate space for column definitions
200 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
202 // Allocate statement handles for the table
205 // Allocate a separate statement handle for performing inserts
206 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
207 pDb
->DispAllErrors(henv
, hdbc
);
208 // Allocate a separate statement handle for performing deletes
209 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
210 pDb
->DispAllErrors(henv
, hdbc
);
211 // Allocate a separate statement handle for performing updates
212 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
213 pDb
->DispAllErrors(henv
, hdbc
);
215 // Allocate a separate statement handle for internal use
216 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
217 pDb
->DispAllErrors(henv
, hdbc
);
219 // Set the cursor type for the statement handles
220 cursorType
= SQL_CURSOR_STATIC
;
222 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
224 // Check to see if cursor type is supported
225 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
226 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
228 // Datasource does not support static cursors. Driver
229 // will substitute a cursor type. Call SQLGetStmtOption()
230 // to determine which cursor type was selected.
231 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
232 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
233 #ifdef DBDEBUG_CONSOLE
234 cout
<< wxT("Static cursor changed to: ");
237 case SQL_CURSOR_FORWARD_ONLY
:
238 cout
<< wxT("Forward Only");
240 case SQL_CURSOR_STATIC
:
241 cout
<< wxT("Static");
243 case SQL_CURSOR_KEYSET_DRIVEN
:
244 cout
<< wxT("Keyset Driven");
246 case SQL_CURSOR_DYNAMIC
:
247 cout
<< wxT("Dynamic");
250 cout
<< endl
<< endl
;
253 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
255 // Force the use of a forward only cursor...
256 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
257 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
259 // Should never happen
260 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
267 pDb
->DispNextError();
268 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
271 #ifdef DBDEBUG_CONSOLE
273 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
278 // Set the cursor type for the INSERT statement handle
279 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
280 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
281 // Set the cursor type for the DELETE statement handle
282 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
283 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
284 // Set the cursor type for the UPDATE statement handle
285 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
286 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
289 // Make the default cursor the active cursor
290 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
291 wxASSERT(hstmtDefault
);
292 hstmt
= *hstmtDefault
;
296 } // wxDbTable::initialize()
299 void wxDbTable::cleanup()
304 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
311 TablesInUse
.DeleteContents(TRUE
);
315 pNode
= TablesInUse
.First();
316 while (pNode
&& !found
)
318 if (((wxTablesInUse
*)pNode
->Data())->tableID
== tableID
)
321 if (!TablesInUse
.DeleteNode(pNode
))
322 wxLogDebug (s
,wxT("Unable to delete node!"));
325 pNode
= pNode
->Next();
330 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
331 wxLogDebug (msg
,wxT("NOTICE..."));
336 // Decrement the wxDb table count
338 pDb
->decrementTableCount();
340 // Delete memory allocated for column definitions
344 // Free statement handles
350 ODBC 3.0 says to use this form
351 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
353 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
354 pDb
->DispAllErrors(henv
, hdbc
);
360 ODBC 3.0 says to use this form
361 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
363 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
364 pDb
->DispAllErrors(henv
, hdbc
);
370 ODBC 3.0 says to use this form
371 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
373 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
374 pDb
->DispAllErrors(henv
, hdbc
);
380 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
381 pDb
->DispAllErrors(henv
, hdbc
);
384 // Delete dynamically allocated cursors
386 DeleteCursor(hstmtDefault
);
389 DeleteCursor(hstmtCount
);
391 if (m_hstmtGridQuery
)
392 DeleteCursor(m_hstmtGridQuery
);
394 } // wxDbTable::cleanup()
397 /***************************** PRIVATE FUNCTIONS *****************************/
400 /********** wxDbTable::bindParams() **********/
401 bool wxDbTable::bindParams(bool forUpdate
)
403 wxASSERT(!queryOnly
);
408 UDWORD precision
= 0;
411 // Bind each column of the table that should be bound
412 // to a parameter marker
416 for (i
=0, colNo
=1; i
< noCols
; i
++)
420 if (!colDefs
[i
].Updateable
)
425 if (!colDefs
[i
].InsertAllowed
)
429 switch(colDefs
[i
].DbDataType
)
431 case DB_DATA_TYPE_VARCHAR
:
432 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
433 precision
= colDefs
[i
].SzDataObj
;
436 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
438 colDefs
[i
].CbValue
= SQL_NTS
;
440 case DB_DATA_TYPE_INTEGER
:
441 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
442 precision
= pDb
->GetTypeInfInteger().Precision
;
445 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
447 colDefs
[i
].CbValue
= 0;
449 case DB_DATA_TYPE_FLOAT
:
450 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
451 precision
= pDb
->GetTypeInfFloat().Precision
;
452 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
453 // SQL Sybase Anywhere v5.5 returned a negative number for the
454 // MaxScale. This caused ODBC to kick out an error on ibscale.
455 // I check for this here and set the scale = precision.
457 // scale = (short) precision;
459 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
461 colDefs
[i
].CbValue
= 0;
463 case DB_DATA_TYPE_DATE
:
464 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
465 precision
= pDb
->GetTypeInfDate().Precision
;
468 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
470 colDefs
[i
].CbValue
= 0;
472 case DB_DATA_TYPE_BLOB
:
473 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
477 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
479 colDefs
[i
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[i
].SzDataObj
);
484 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
485 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
486 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
488 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
493 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
494 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
495 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
497 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
502 // Completed successfully
505 } // wxDbTable::bindParams()
508 /********** wxDbTable::bindInsertParams() **********/
509 bool wxDbTable::bindInsertParams(void)
511 return bindParams(FALSE
);
512 } // wxDbTable::bindInsertParams()
515 /********** wxDbTable::bindUpdateParams() **********/
516 bool wxDbTable::bindUpdateParams(void)
518 return bindParams(TRUE
);
519 } // wxDbTable::bindUpdateParams()
522 /********** wxDbTable::bindCols() **********/
523 bool wxDbTable::bindCols(HSTMT cursor
)
525 // Bind each column of the table to a memory address for fetching data
527 for (i
= 0; i
< noCols
; i
++)
529 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
530 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
532 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
536 // Completed successfully
539 } // wxDbTable::bindCols()
542 /********** wxDbTable::getRec() **********/
543 bool wxDbTable::getRec(UWORD fetchType
)
547 if (!pDb
->FwdOnlyCursors())
549 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
553 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
554 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
556 if (retcode
== SQL_NO_DATA_FOUND
)
559 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
563 // Set the Null member variable to indicate the Null state
564 // of each column just read in.
566 for (i
= 0; i
< noCols
; i
++)
567 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
572 // Fetch the next record from the record set
573 retcode
= SQLFetch(hstmt
);
574 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
576 if (retcode
== SQL_NO_DATA_FOUND
)
579 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
583 // Set the Null member variable to indicate the Null state
584 // of each column just read in.
586 for (i
= 0; i
< noCols
; i
++)
587 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
591 // Completed successfully
594 } // wxDbTable::getRec()
597 /********** wxDbTable::execDelete() **********/
598 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
602 // Execute the DELETE statement
603 retcode
= SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
605 if (retcode
== SQL_SUCCESS
||
606 retcode
== SQL_NO_DATA_FOUND
||
607 retcode
== SQL_SUCCESS_WITH_INFO
)
609 // Record deleted successfully
613 // Problem deleting record
614 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
616 } // wxDbTable::execDelete()
619 /********** wxDbTable::execUpdate() **********/
620 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
624 // Execute the UPDATE statement
625 retcode
= SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
627 if (retcode
== SQL_SUCCESS
||
628 retcode
== SQL_NO_DATA_FOUND
||
629 retcode
== SQL_SUCCESS_WITH_INFO
)
631 // Record updated successfully
635 // Problem updating record
636 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
638 } // wxDbTable::execUpdate()
641 /********** wxDbTable::query() **********/
642 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
647 // The user may wish to select for update, but the DBMS may not be capable
648 selectForUpdate
= CanSelectForUpdate();
650 selectForUpdate
= FALSE
;
652 // Set the SQL SELECT string
653 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
654 { // so generate a select statement.
655 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
656 pDb
->WriteSqlLog(sqlStmt
);
659 // Make sure the cursor is closed first
660 if (!CloseCursor(hstmt
))
663 // Execute the SQL SELECT statement
665 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
666 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
667 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
669 // Completed successfully
672 } // wxDbTable::query()
675 /***************************** PUBLIC FUNCTIONS *****************************/
678 /********** wxDbTable::Open() **********/
679 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
689 // Calculate the maximum size of the concatenated
690 // keys for use with wxDbGrid
692 for (i
=0; i
< noCols
; i
++)
694 if (colDefs
[i
].KeyField
)
697 m_keysize
+= colDefs
[i
].SzDataObj
;
702 // Verify that the table exists in the database
703 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
705 s
= wxT("Table/view does not exist in the database");
706 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
707 s
+= wxT(", or you have no permissions.\n");
711 else if (checkPrivileges
)
713 // Verify the user has rights to access the table.
714 // Shortcut boolean evaluation to optimize out call to
717 // Unfortunately this optimization doesn't seem to be
719 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
720 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
721 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
728 if (!tablePath
.IsEmpty())
729 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
731 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
734 pDb
->LogError(p
.GetData());
739 // Bind the member variables for field exchange between
740 // the wxDbTable object and the ODBC record.
743 if (!bindInsertParams()) // Inserts
746 if (!bindUpdateParams()) // Updates
750 if (!bindCols(*hstmtDefault
)) // Selects
753 if (!bindCols(hstmtInternal
)) // Internal use only
757 * Do NOT bind the hstmtCount cursor!!!
760 // Build an insert statement using parameter markers
761 if (!queryOnly
&& noCols
> 0)
763 bool needComma
= FALSE
;
764 sqlStmt
.Printf(wxT("INSERT INTO %s ("), tableName
.c_str());
765 for (i
= 0; i
< noCols
; i
++)
767 if (! colDefs
[i
].InsertAllowed
)
771 sqlStmt
+= colDefs
[i
].ColName
;
775 sqlStmt
+= wxT(") VALUES (");
777 int insertableCount
= 0;
779 for (i
= 0; i
< noCols
; i
++)
781 if (! colDefs
[i
].InsertAllowed
)
791 // Prepare the insert statement for execution
794 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
795 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
801 // Completed successfully
804 } // wxDbTable::Open()
807 /********** wxDbTable::Query() **********/
808 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
811 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
813 } // wxDbTable::Query()
816 /********** wxDbTable::QueryBySqlStmt() **********/
817 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
819 pDb
->WriteSqlLog(pSqlStmt
);
821 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
823 } // wxDbTable::QueryBySqlStmt()
826 /********** wxDbTable::QueryMatching() **********/
827 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
830 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
832 } // wxDbTable::QueryMatching()
835 /********** wxDbTable::QueryOnKeyFields() **********/
836 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
839 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
841 } // wxDbTable::QueryOnKeyFields()
844 /********** wxDbTable::GetPrev() **********/
845 bool wxDbTable::GetPrev(void)
847 if (pDb
->FwdOnlyCursors())
849 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
853 return(getRec(SQL_FETCH_PRIOR
));
855 } // wxDbTable::GetPrev()
858 /********** wxDbTable::operator-- **********/
859 bool wxDbTable::operator--(int)
861 if (pDb
->FwdOnlyCursors())
863 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
867 return(getRec(SQL_FETCH_PRIOR
));
869 } // wxDbTable::operator--
872 /********** wxDbTable::GetFirst() **********/
873 bool wxDbTable::GetFirst(void)
875 if (pDb
->FwdOnlyCursors())
877 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
881 return(getRec(SQL_FETCH_FIRST
));
883 } // wxDbTable::GetFirst()
886 /********** wxDbTable::GetLast() **********/
887 bool wxDbTable::GetLast(void)
889 if (pDb
->FwdOnlyCursors())
891 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
895 return(getRec(SQL_FETCH_LAST
));
897 } // wxDbTable::GetLast()
900 /********** wxDbTable::BuildDeleteStmt() **********/
901 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
903 wxASSERT(!queryOnly
);
907 wxString whereClause
;
911 // Handle the case of DeleteWhere() and the where clause is blank. It should
912 // delete all records from the database in this case.
913 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
915 pSqlStmt
.Printf(wxT("DELETE FROM %s"), tableName
.c_str());
919 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "), tableName
.c_str());
921 // Append the WHERE clause to the SQL DELETE statement
924 case DB_DEL_KEYFIELDS
:
925 // If the datasource supports the ROWID column, build
926 // the where on ROWID for efficiency purposes.
927 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
931 wxChar rowid
[wxDB_ROWID_LEN
+1];
933 // Get the ROWID value. If not successful retreiving the ROWID,
934 // simply fall down through the code and build the WHERE clause
935 // based on the key fields.
936 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
938 pSqlStmt
+= wxT("ROWID = '");
940 pSqlStmt
+= wxT("'");
944 // Unable to delete by ROWID, so build a WHERE
945 // clause based on the keyfields.
946 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
947 pSqlStmt
+= whereClause
;
950 pSqlStmt
+= pWhereClause
;
952 case DB_DEL_MATCHING
:
953 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
954 pSqlStmt
+= whereClause
;
958 } // BuildDeleteStmt()
961 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
962 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
964 wxString tempSqlStmt
;
965 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
966 wxStrcpy(pSqlStmt
, tempSqlStmt
);
967 } // wxDbTable::BuildDeleteStmt()
970 /********** wxDbTable::BuildSelectStmt() **********/
971 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
973 wxString whereClause
;
976 // Build a select statement to query the database
977 pSqlStmt
= wxT("SELECT ");
979 // SELECT DISTINCT values only?
981 pSqlStmt
+= wxT("DISTINCT ");
983 // Was a FROM clause specified to join tables to the base table?
984 // Available for ::Query() only!!!
985 bool appendFromClause
= FALSE
;
986 #if wxODBC_BACKWARD_COMPATABILITY
987 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
988 appendFromClause
= TRUE
;
990 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
991 appendFromClause
= TRUE
;
994 // Add the column list
996 for (i
= 0; i
< noCols
; i
++)
998 // If joining tables, the base table column names must be qualified to avoid ambiguity
999 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1001 pSqlStmt
+= queryTableName
;
1002 pSqlStmt
+= wxT(".");
1004 pSqlStmt
+= colDefs
[i
].ColName
;
1006 pSqlStmt
+= wxT(",");
1009 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1010 // the ROWID if querying distinct records. The rowid will always be unique.
1011 if (!distinct
&& CanUpdByROWID())
1013 // If joining tables, the base table column names must be qualified to avoid ambiguity
1014 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1016 pSqlStmt
+= wxT(",");
1017 pSqlStmt
+= queryTableName
;
1018 pSqlStmt
+= wxT(".ROWID");
1021 pSqlStmt
+= wxT(",ROWID");
1024 // Append the FROM tablename portion
1025 pSqlStmt
+= wxT(" FROM ");
1026 pSqlStmt
+= queryTableName
;
1028 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1029 // The HOLDLOCK keyword follows the table name in the from clause.
1030 // Each table in the from clause must specify HOLDLOCK or
1031 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1032 // is parsed but ignored in SYBASE Transact-SQL.
1033 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1034 pSqlStmt
+= wxT(" HOLDLOCK");
1036 if (appendFromClause
)
1039 // Append the WHERE clause. Either append the where clause for the class
1040 // or build a where clause. The typeOfSelect determines this.
1041 switch(typeOfSelect
)
1043 case DB_SELECT_WHERE
:
1044 #if wxODBC_BACKWARD_COMPATABILITY
1045 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1047 if (where
.Length()) // May not want a where clause!!!
1050 pSqlStmt
+= wxT(" WHERE ");
1054 case DB_SELECT_KEYFIELDS
:
1055 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1056 if (whereClause
.Length())
1058 pSqlStmt
+= wxT(" WHERE ");
1059 pSqlStmt
+= whereClause
;
1062 case DB_SELECT_MATCHING
:
1063 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1064 if (whereClause
.Length())
1066 pSqlStmt
+= wxT(" WHERE ");
1067 pSqlStmt
+= whereClause
;
1072 // Append the ORDER BY clause
1073 #if wxODBC_BACKWARD_COMPATABILITY
1074 if (orderBy
&& wxStrlen(orderBy
))
1076 if (orderBy
.Length())
1079 pSqlStmt
+= wxT(" ORDER BY ");
1080 pSqlStmt
+= orderBy
;
1083 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1084 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1085 // HOLDLOCK for Sybase.
1086 if (selectForUpdate
&& CanSelectForUpdate())
1087 pSqlStmt
+= wxT(" FOR UPDATE");
1089 } // wxDbTable::BuildSelectStmt()
1092 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1093 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1095 wxString tempSqlStmt
;
1096 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1097 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1098 } // wxDbTable::BuildSelectStmt()
1101 /********** wxDbTable::BuildUpdateStmt() **********/
1102 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1104 wxASSERT(!queryOnly
);
1108 wxString whereClause
;
1109 whereClause
.Empty();
1111 bool firstColumn
= TRUE
;
1113 pSqlStmt
.Printf(wxT("UPDATE %s SET "), tableName
.Upper().c_str());
1115 // Append a list of columns to be updated
1117 for (i
= 0; i
< noCols
; i
++)
1119 // Only append Updateable columns
1120 if (colDefs
[i
].Updateable
)
1123 pSqlStmt
+= wxT(",");
1125 firstColumn
= FALSE
;
1126 pSqlStmt
+= colDefs
[i
].ColName
;
1127 pSqlStmt
+= wxT(" = ?");
1131 // Append the WHERE clause to the SQL UPDATE statement
1132 pSqlStmt
+= wxT(" WHERE ");
1135 case DB_UPD_KEYFIELDS
:
1136 // If the datasource supports the ROWID column, build
1137 // the where on ROWID for efficiency purposes.
1138 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1139 if (CanUpdByROWID())
1142 wxChar rowid
[wxDB_ROWID_LEN
+1];
1144 // Get the ROWID value. If not successful retreiving the ROWID,
1145 // simply fall down through the code and build the WHERE clause
1146 // based on the key fields.
1147 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1149 pSqlStmt
+= wxT("ROWID = '");
1151 pSqlStmt
+= wxT("'");
1155 // Unable to delete by ROWID, so build a WHERE
1156 // clause based on the keyfields.
1157 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1158 pSqlStmt
+= whereClause
;
1161 pSqlStmt
+= pWhereClause
;
1164 } // BuildUpdateStmt()
1167 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1168 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1170 wxString tempSqlStmt
;
1171 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1172 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1173 } // BuildUpdateStmt()
1176 /********** wxDbTable::BuildWhereClause() **********/
1177 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1178 const wxString
&qualTableName
, bool useLikeComparison
)
1180 * Note: BuildWhereClause() currently ignores timestamp columns.
1181 * They are not included as part of the where clause.
1184 bool moreThanOneColumn
= FALSE
;
1187 // Loop through the columns building a where clause as you go
1189 for (i
= 0; i
< noCols
; i
++)
1191 // Determine if this column should be included in the WHERE clause
1192 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1193 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(i
))))
1195 // Skip over timestamp columns
1196 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1198 // If there is more than 1 column, join them with the keyword "AND"
1199 if (moreThanOneColumn
)
1200 pWhereClause
+= wxT(" AND ");
1202 moreThanOneColumn
= TRUE
;
1203 // Concatenate where phrase for the column
1204 if (qualTableName
.Length())
1206 pWhereClause
+= qualTableName
;
1207 pWhereClause
+= wxT(".");
1209 pWhereClause
+= colDefs
[i
].ColName
;
1210 if (useLikeComparison
&& (colDefs
[i
].SqlCtype
== SQL_C_CHAR
))
1211 pWhereClause
+= wxT(" LIKE ");
1213 pWhereClause
+= wxT(" = ");
1214 switch(colDefs
[i
].SqlCtype
)
1217 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1220 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[i
].PtrDataObj
));
1223 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[i
].PtrDataObj
));
1226 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1229 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1232 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1235 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1238 pWhereClause
+= colValue
;
1241 } // wxDbTable::BuildWhereClause()
1244 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1245 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1246 const wxString
&qualTableName
, bool useLikeComparison
)
1248 wxString tempSqlStmt
;
1249 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1250 wxStrcpy(pWhereClause
, tempSqlStmt
);
1251 } // wxDbTable::BuildWhereClause()
1254 /********** wxDbTable::GetRowNum() **********/
1255 UWORD
wxDbTable::GetRowNum(void)
1259 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1261 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1265 // Completed successfully
1266 return((UWORD
) rowNum
);
1268 } // wxDbTable::GetRowNum()
1271 /********** wxDbTable::CloseCursor() **********/
1272 bool wxDbTable::CloseCursor(HSTMT cursor
)
1274 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1275 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1277 // Completed successfully
1280 } // wxDbTable::CloseCursor()
1283 /********** wxDbTable::CreateTable() **********/
1284 bool wxDbTable::CreateTable(bool attemptDrop
)
1292 #ifdef DBDEBUG_CONSOLE
1293 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1297 if (attemptDrop
&& !DropTable())
1301 #ifdef DBDEBUG_CONSOLE
1302 for (i
= 0; i
< noCols
; i
++)
1304 // Exclude derived columns since they are NOT part of the base table
1305 if (colDefs
[i
].DerivedCol
)
1307 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1308 switch(colDefs
[i
].DbDataType
)
1310 case DB_DATA_TYPE_VARCHAR
:
1311 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1313 case DB_DATA_TYPE_INTEGER
:
1314 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1316 case DB_DATA_TYPE_FLOAT
:
1317 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1319 case DB_DATA_TYPE_DATE
:
1320 cout
<< pDb
->GetTypeInfDate().TypeName
;
1322 case DB_DATA_TYPE_BLOB
:
1323 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1330 // Build a CREATE TABLE string from the colDefs structure.
1331 bool needComma
= FALSE
;
1332 sqlStmt
.Printf(wxT("CREATE TABLE %s ("), tableName
.c_str());
1334 for (i
= 0; i
< noCols
; i
++)
1336 // Exclude derived columns since they are NOT part of the base table
1337 if (colDefs
[i
].DerivedCol
)
1341 sqlStmt
+= wxT(",");
1343 sqlStmt
+= colDefs
[i
].ColName
;
1344 sqlStmt
+= wxT(" ");
1346 switch(colDefs
[i
].DbDataType
)
1348 case DB_DATA_TYPE_VARCHAR
:
1349 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1351 case DB_DATA_TYPE_INTEGER
:
1352 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1354 case DB_DATA_TYPE_FLOAT
:
1355 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1357 case DB_DATA_TYPE_DATE
:
1358 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1360 case DB_DATA_TYPE_BLOB
:
1361 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1364 // For varchars, append the size of the string
1365 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)// ||
1366 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1369 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1373 if (pDb
->Dbms() == dbmsDB2
||
1374 pDb
->Dbms() == dbmsMY_SQL
||
1375 pDb
->Dbms() == dbmsSYBASE_ASE
||
1376 pDb
->Dbms() == dbmsINTERBASE
||
1377 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1379 if (colDefs
[i
].KeyField
)
1381 sqlStmt
+= wxT(" NOT NULL");
1387 // If there is a primary key defined, include it in the create statement
1388 for (i
= j
= 0; i
< noCols
; i
++)
1390 if (colDefs
[i
].KeyField
)
1396 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
1398 switch (pDb
->Dbms())
1401 case dbmsSYBASE_ASA
:
1402 case dbmsSYBASE_ASE
:
1405 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1406 sqlStmt
+= wxT(",PRIMARY KEY (");
1411 sqlStmt
+= wxT(",CONSTRAINT ");
1412 // DB2 is limited to 18 characters for index names
1413 if (pDb
->Dbms() == dbmsDB2
)
1415 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."));
1416 sqlStmt
+= tableName
.substr(0, 13);
1419 sqlStmt
+= tableName
;
1421 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1426 // List column name(s) of column(s) comprising the primary key
1427 for (i
= j
= 0; i
< noCols
; i
++)
1429 if (colDefs
[i
].KeyField
)
1431 if (j
++) // Multi part key, comma separate names
1432 sqlStmt
+= wxT(",");
1433 sqlStmt
+= colDefs
[i
].ColName
;
1436 sqlStmt
+= wxT(")");
1438 if (pDb
->Dbms() == dbmsINFORMIX
||
1439 pDb
->Dbms() == dbmsSYBASE_ASA
||
1440 pDb
->Dbms() == dbmsSYBASE_ASE
)
1442 sqlStmt
+= wxT(" CONSTRAINT ");
1443 sqlStmt
+= tableName
;
1444 sqlStmt
+= wxT("_PIDX");
1447 // Append the closing parentheses for the create table statement
1448 sqlStmt
+= wxT(")");
1450 pDb
->WriteSqlLog(sqlStmt
);
1452 #ifdef DBDEBUG_CONSOLE
1453 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1456 // Execute the CREATE TABLE statement
1457 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1458 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1460 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1461 pDb
->RollbackTrans();
1466 // Commit the transaction and close the cursor
1467 if (!pDb
->CommitTrans())
1469 if (!CloseCursor(hstmt
))
1472 // Database table created successfully
1475 } // wxDbTable::CreateTable()
1478 /********** wxDbTable::DropTable() **********/
1479 bool wxDbTable::DropTable()
1481 // NOTE: This function returns TRUE if the Table does not exist, but
1482 // only for identified databases. Code will need to be added
1483 // below for any other databases when those databases are defined
1484 // to handle this situation consistently
1488 sqlStmt
.Printf(wxT("DROP TABLE %s"), tableName
.c_str());
1490 pDb
->WriteSqlLog(sqlStmt
);
1492 #ifdef DBDEBUG_CONSOLE
1493 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1499 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1500 if (retcode
!= SQL_SUCCESS
)
1502 // Check for "Base table not found" error and ignore
1503 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1504 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1505 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1507 // Check for product specific error codes
1508 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1509 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1510 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1511 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1513 pDb
->DispNextError();
1514 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1515 pDb
->RollbackTrans();
1516 // CloseCursor(hstmt);
1522 // Commit the transaction and close the cursor
1523 if (! pDb
->CommitTrans())
1525 if (! CloseCursor(hstmt
))
1529 } // wxDbTable::DropTable()
1532 /********** wxDbTable::CreateIndex() **********/
1533 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1534 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1538 // Drop the index first
1539 if (attemptDrop
&& !DropIndex(idxName
))
1542 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1543 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1544 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1545 // table was created, then months later you determine that an additional index while
1546 // give better performance, so you want to add an index).
1548 // The following block of code will modify the column definition to make the column be
1549 // defined with the "NOT NULL" qualifier.
1550 if (pDb
->Dbms() == dbmsMY_SQL
)
1555 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1559 // Find the column definition that has the ColName that matches the
1560 // index column name. We need to do this to get the DB_DATA_TYPE of
1561 // the index column, as MySQL's syntax for the ALTER column requires
1563 while (!found
&& (j
< this->noCols
))
1565 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1573 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1574 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1579 wxODBC_ERRORS retcode
;
1580 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1581 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1582 // This line is just here for debug checking of the value
1583 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1593 pDb
->RollbackTrans();
1598 // Build a CREATE INDEX statement
1599 sqlStmt
= wxT("CREATE ");
1601 sqlStmt
+= wxT("UNIQUE ");
1603 sqlStmt
+= wxT("INDEX ");
1605 sqlStmt
+= wxT(" ON ");
1606 sqlStmt
+= tableName
;
1607 sqlStmt
+= wxT(" (");
1609 // Append list of columns making up index
1611 for (i
= 0; i
< noIdxCols
; i
++)
1613 sqlStmt
+= pIdxDefs
[i
].ColName
;
1615 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1616 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (strncmp(pDb
->dbInf
.dbmsVer
,"07",2)==0)) &&
1617 !(pDb
->Dbms() == dbmsPOSTGRES
))
1619 if (pIdxDefs
[i
].Ascending
)
1620 sqlStmt
+= wxT(" ASC");
1622 sqlStmt
+= wxT(" DESC");
1625 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, "Datasource does not support DESCending index columns");
1627 if ((i
+ 1) < noIdxCols
)
1628 sqlStmt
+= wxT(",");
1631 // Append closing parentheses
1632 sqlStmt
+= wxT(")");
1634 pDb
->WriteSqlLog(sqlStmt
);
1636 #ifdef DBDEBUG_CONSOLE
1637 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1640 // Execute the CREATE INDEX statement
1641 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1643 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1644 pDb
->RollbackTrans();
1649 // Commit the transaction and close the cursor
1650 if (! pDb
->CommitTrans())
1652 if (! CloseCursor(hstmt
))
1655 // Index Created Successfully
1658 } // wxDbTable::CreateIndex()
1661 /********** wxDbTable::DropIndex() **********/
1662 bool wxDbTable::DropIndex(const wxString
&idxName
)
1664 // NOTE: This function returns TRUE if the Index does not exist, but
1665 // only for identified databases. Code will need to be added
1666 // below for any other databases when those databases are defined
1667 // to handle this situation consistently
1671 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1672 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1673 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),idxName
.c_str(), tableName
.c_str());
1674 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1675 (pDb
->Dbms() == dbmsSYBASE_ASE
))
1676 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),tableName
.c_str(), idxName
.c_str());
1678 sqlStmt
.Printf(wxT("DROP INDEX %s"),idxName
.c_str());
1680 pDb
->WriteSqlLog(sqlStmt
);
1682 #ifdef DBDEBUG_CONSOLE
1683 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1686 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1688 // Check for "Index not found" error and ignore
1689 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1690 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1692 // Check for product specific error codes
1693 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1694 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1695 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1696 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1697 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1698 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1699 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1702 pDb
->DispNextError();
1703 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1704 pDb
->RollbackTrans();
1711 // Commit the transaction and close the cursor
1712 if (! pDb
->CommitTrans())
1714 if (! CloseCursor(hstmt
))
1718 } // wxDbTable::DropIndex()
1721 /********** wxDbTable::SetOrderByColNums() **********/
1722 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1724 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1730 va_start(argptr
, first
); /* Initialize variable arguments. */
1731 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1733 // Make sure the passed in column number
1734 // is within the valid range of columns
1736 // Valid columns are 0 thru noCols-1
1737 if (colNo
>= noCols
|| colNo
< 0)
1744 tempStr
+= wxT(",");
1746 tempStr
+= colDefs
[colNo
].ColName
;
1747 colNo
= va_arg (argptr
, int);
1749 va_end (argptr
); /* Reset variable arguments. */
1751 SetOrderByClause(tempStr
);
1754 } // wxDbTable::SetOrderByColNums()
1757 /********** wxDbTable::Insert() **********/
1758 int wxDbTable::Insert(void)
1760 wxASSERT(!queryOnly
);
1761 if (queryOnly
|| !insertable
)
1766 // Insert the record by executing the already prepared insert statement
1768 retcode
=SQLExecute(hstmtInsert
);
1769 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1771 // Check to see if integrity constraint was violated
1772 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1773 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1774 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1777 pDb
->DispNextError();
1778 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1783 // Record inserted into the datasource successfully
1786 } // wxDbTable::Insert()
1789 /********** wxDbTable::Update() **********/
1790 bool wxDbTable::Update(void)
1792 wxASSERT(!queryOnly
);
1798 // Build the SQL UPDATE statement
1799 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1801 pDb
->WriteSqlLog(sqlStmt
);
1803 #ifdef DBDEBUG_CONSOLE
1804 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1807 // Execute the SQL UPDATE statement
1808 return(execUpdate(sqlStmt
));
1810 } // wxDbTable::Update()
1813 /********** wxDbTable::Update(pSqlStmt) **********/
1814 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1816 wxASSERT(!queryOnly
);
1820 pDb
->WriteSqlLog(pSqlStmt
);
1822 return(execUpdate(pSqlStmt
));
1824 } // wxDbTable::Update(pSqlStmt)
1827 /********** wxDbTable::UpdateWhere() **********/
1828 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1830 wxASSERT(!queryOnly
);
1836 // Build the SQL UPDATE statement
1837 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1839 pDb
->WriteSqlLog(sqlStmt
);
1841 #ifdef DBDEBUG_CONSOLE
1842 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1845 // Execute the SQL UPDATE statement
1846 return(execUpdate(sqlStmt
));
1848 } // wxDbTable::UpdateWhere()
1851 /********** wxDbTable::Delete() **********/
1852 bool wxDbTable::Delete(void)
1854 wxASSERT(!queryOnly
);
1861 // Build the SQL DELETE statement
1862 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1864 pDb
->WriteSqlLog(sqlStmt
);
1866 // Execute the SQL DELETE statement
1867 return(execDelete(sqlStmt
));
1869 } // wxDbTable::Delete()
1872 /********** wxDbTable::DeleteWhere() **********/
1873 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
1875 wxASSERT(!queryOnly
);
1882 // Build the SQL DELETE statement
1883 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1885 pDb
->WriteSqlLog(sqlStmt
);
1887 // Execute the SQL DELETE statement
1888 return(execDelete(sqlStmt
));
1890 } // wxDbTable::DeleteWhere()
1893 /********** wxDbTable::DeleteMatching() **********/
1894 bool wxDbTable::DeleteMatching(void)
1896 wxASSERT(!queryOnly
);
1903 // Build the SQL DELETE statement
1904 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1906 pDb
->WriteSqlLog(sqlStmt
);
1908 // Execute the SQL DELETE statement
1909 return(execDelete(sqlStmt
));
1911 } // wxDbTable::DeleteMatching()
1914 /********** wxDbTable::IsColNull() **********/
1915 bool wxDbTable::IsColNull(UWORD colNo
) const
1918 This logic is just not right. It would indicate TRUE
1919 if a numeric field were set to a value of 0.
1921 switch(colDefs[colNo].SqlCtype)
1924 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
1926 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
1928 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
1930 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1932 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1934 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
1936 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
1937 case SQL_C_TIMESTAMP:
1938 TIMESTAMP_STRUCT *pDt;
1939 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
1940 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
1948 return (colDefs
[colNo
].Null
);
1949 } // wxDbTable::IsColNull()
1952 /********** wxDbTable::CanSelectForUpdate() **********/
1953 bool wxDbTable::CanSelectForUpdate(void)
1958 if (pDb
->Dbms() == dbmsMY_SQL
)
1961 if ((pDb
->Dbms() == dbmsORACLE
) ||
1962 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
1967 } // wxDbTable::CanSelectForUpdate()
1970 /********** wxDbTable::CanUpdByROWID() **********/
1971 bool wxDbTable::CanUpdByROWID(void)
1974 * NOTE: Returning FALSE for now until this can be debugged,
1975 * as the ROWID is not getting updated correctly
1979 if (pDb->Dbms() == dbmsORACLE)
1984 } // wxDbTable::CanUpdByROWID()
1987 /********** wxDbTable::IsCursorClosedOnCommit() **********/
1988 bool wxDbTable::IsCursorClosedOnCommit(void)
1990 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
1995 } // wxDbTable::IsCursorClosedOnCommit()
1999 /********** wxDbTable::ClearMemberVar() **********/
2000 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2002 wxASSERT(colNo
< noCols
);
2004 switch(colDefs
[colNo
].SqlCtype
)
2007 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2010 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2013 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2016 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2019 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2022 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2025 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2027 case SQL_C_TIMESTAMP
:
2028 TIMESTAMP_STRUCT
*pDt
;
2029 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2042 } // wxDbTable::ClearMemberVar()
2045 /********** wxDbTable::ClearMemberVars() **********/
2046 void wxDbTable::ClearMemberVars(bool setToNull
)
2050 // Loop through the columns setting each member variable to zero
2051 for (i
=0; i
< noCols
; i
++)
2052 ClearMemberVar(i
,setToNull
);
2054 } // wxDbTable::ClearMemberVars()
2057 /********** wxDbTable::SetQueryTimeout() **********/
2058 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2060 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2061 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2062 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2063 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2064 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2065 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2066 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2067 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2069 // Completed Successfully
2072 } // wxDbTable::SetQueryTimeout()
2075 /********** wxDbTable::SetColDefs() **********/
2076 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2077 SWORD cType
, int size
, bool keyField
, bool upd
,
2078 bool insAllow
, bool derivedCol
)
2080 if (!colDefs
) // May happen if the database connection fails
2083 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2085 int assertColumnNameTooLong
= 0;
2086 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2087 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2089 tmpMsg
.Printf("Column name '%s' is too long. Truncated to '%s'.",fieldName
.c_str(),colDefs
[index
].ColName
);
2090 wxASSERT_MSG(assertColumnNameTooLong
,tmpMsg
.c_str());
2093 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2095 colDefs
[index
].DbDataType
= dataType
;
2096 colDefs
[index
].PtrDataObj
= pData
;
2097 colDefs
[index
].SqlCtype
= cType
;
2098 colDefs
[index
].SzDataObj
= size
;
2099 colDefs
[index
].KeyField
= keyField
;
2100 colDefs
[index
].DerivedCol
= derivedCol
;
2101 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2104 colDefs
[index
].Updateable
= FALSE
;
2105 colDefs
[index
].InsertAllowed
= FALSE
;
2109 colDefs
[index
].Updateable
= upd
;
2110 colDefs
[index
].InsertAllowed
= insAllow
;
2113 colDefs
[index
].Null
= FALSE
;
2115 } // wxDbTable::SetColDefs()
2118 /********** wxDbTable::SetColDefs() **********/
2119 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2122 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2128 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2130 for (index
= 0; index
< numCols
; index
++)
2132 // Process the fields
2133 switch (pColInfs
[index
].dbDataType
)
2135 case DB_DATA_TYPE_VARCHAR
:
2136 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2137 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2138 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2140 case DB_DATA_TYPE_INTEGER
:
2141 // Can be long or short
2142 if (pColInfs
[index
].bufferLength
== sizeof(long))
2144 pColDataPtrs
[index
].PtrDataObj
= new long;
2145 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2146 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2150 pColDataPtrs
[index
].PtrDataObj
= new short;
2151 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2152 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2155 case DB_DATA_TYPE_FLOAT
:
2156 // Can be float or double
2157 if (pColInfs
[index
].bufferLength
== sizeof(float))
2159 pColDataPtrs
[index
].PtrDataObj
= new float;
2160 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2161 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2165 pColDataPtrs
[index
].PtrDataObj
= new double;
2166 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2167 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2170 case DB_DATA_TYPE_DATE
:
2171 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2172 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2173 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2175 case DB_DATA_TYPE_BLOB
:
2176 int notSupportedYet
= 0;
2177 wxASSERT_MSG(notSupportedYet
, wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2178 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2179 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2180 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2183 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2184 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2187 // Unable to build all the column definitions, as either one of
2188 // the calls to "new" failed above, or there was a BLOB field
2189 // to have a column definition for. If BLOBs are to be used,
2190 // the other form of ::SetColDefs() must be used, as it is impossible
2191 // to know the maximum size to create the PtrDataObj to be.
2192 delete [] pColDataPtrs
;
2198 return (pColDataPtrs
);
2200 } // wxDbTable::SetColDefs()
2203 /********** wxDbTable::SetCursor() **********/
2204 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2206 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2207 hstmt
= *hstmtDefault
;
2209 hstmt
= *hstmtActivate
;
2211 } // wxDbTable::SetCursor()
2214 /********** wxDbTable::Count(const wxString &) **********/
2215 ULONG
wxDbTable::Count(const wxString
&args
)
2221 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2222 sqlStmt
= wxT("SELECT COUNT(");
2224 sqlStmt
+= wxT(") FROM ");
2225 sqlStmt
+= queryTableName
;
2226 #if wxODBC_BACKWARD_COMPATABILITY
2227 if (from
&& wxStrlen(from
))
2233 // Add the where clause if one is provided
2234 #if wxODBC_BACKWARD_COMPATABILITY
2235 if (where
&& wxStrlen(where
))
2240 sqlStmt
+= wxT(" WHERE ");
2244 pDb
->WriteSqlLog(sqlStmt
);
2246 // Initialize the Count cursor if it's not already initialized
2249 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2250 wxASSERT(hstmtCount
);
2255 // Execute the SQL statement
2256 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2258 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2263 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2265 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2269 // Obtain the result
2270 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2272 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2277 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2278 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2280 // Return the record count
2283 } // wxDbTable::Count()
2286 /********** wxDbTable::Refresh() **********/
2287 bool wxDbTable::Refresh(void)
2291 // Switch to the internal cursor so any active cursors are not corrupted
2292 HSTMT currCursor
= GetCursor();
2293 hstmt
= hstmtInternal
;
2294 #if wxODBC_BACKWARD_COMPATABILITY
2295 // Save the where and order by clauses
2296 char *saveWhere
= where
;
2297 char *saveOrderBy
= orderBy
;
2299 wxString saveWhere
= where
;
2300 wxString saveOrderBy
= orderBy
;
2302 // Build a where clause to refetch the record with. Try and use the
2303 // ROWID if it's available, ow use the key fields.
2304 wxString whereClause
;
2305 whereClause
.Empty();
2307 if (CanUpdByROWID())
2310 wxChar rowid
[wxDB_ROWID_LEN
+1];
2312 // Get the ROWID value. If not successful retreiving the ROWID,
2313 // simply fall down through the code and build the WHERE clause
2314 // based on the key fields.
2315 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2317 whereClause
+= queryTableName
;
2318 whereClause
+= wxT(".ROWID = '");
2319 whereClause
+= rowid
;
2320 whereClause
+= wxT("'");
2324 // If unable to use the ROWID, build a where clause from the keyfields
2325 if (wxStrlen(whereClause
) == 0)
2326 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2328 // Requery the record
2329 where
= whereClause
;
2334 if (result
&& !GetNext())
2337 // Switch back to original cursor
2338 SetCursor(&currCursor
);
2340 // Free the internal cursor
2341 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2342 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2344 // Restore the original where and order by clauses
2346 orderBy
= saveOrderBy
;
2350 } // wxDbTable::Refresh()
2353 /********** wxDbTable::SetColNull() **********/
2354 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2358 colDefs
[colNo
].Null
= set
;
2359 if (set
) // Blank out the values in the member variable
2360 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2366 } // wxDbTable::SetColNull()
2369 /********** wxDbTable::SetColNull() **********/
2370 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2373 for (i
= 0; i
< noCols
; i
++)
2375 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2381 colDefs
[i
].Null
= set
;
2382 if (set
) // Blank out the values in the member variable
2383 ClearMemberVar(i
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2389 } // wxDbTable::SetColNull()
2392 /********** wxDbTable::GetNewCursor() **********/
2393 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2395 HSTMT
*newHSTMT
= new HSTMT
;
2400 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2402 pDb
->DispAllErrors(henv
, hdbc
);
2407 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2409 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2416 if (!bindCols(*newHSTMT
))
2424 SetCursor(newHSTMT
);
2428 } // wxDbTable::GetNewCursor()
2431 /********** wxDbTable::DeleteCursor() **********/
2432 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2436 if (!hstmtDel
) // Cursor already deleted
2440 ODBC 3.0 says to use this form
2441 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2444 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2446 pDb
->DispAllErrors(henv
, hdbc
);
2454 } // wxDbTable::DeleteCursor()
2456 //////////////////////////////////////////////////////////////
2457 // wxDbGrid support functions
2458 //////////////////////////////////////////////////////////////
2460 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2462 if (!m_hstmtGridQuery
)
2464 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2465 if (!bindCols(*m_hstmtGridQuery
))
2469 m_rowmode
= rowmode
;
2472 case WX_ROW_MODE_QUERY
:
2473 SetCursor(m_hstmtGridQuery
);
2475 case WX_ROW_MODE_INDIVIDUAL
:
2476 SetCursor(hstmtDefault
);
2481 } // wxDbTable::SetRowMode()
2484 wxVariant
wxDbTable::GetCol(const int col
) const
2487 if ((col
< noCols
) && (!IsColNull(col
)))
2489 switch (colDefs
[col
].SqlCtype
)
2493 val
= (char *)(colDefs
[col
].PtrDataObj
);
2497 val
= *(long *)(colDefs
[col
].PtrDataObj
);
2501 val
= (long int )(*(short *)(colDefs
[col
].PtrDataObj
));
2504 val
= (long)(*(unsigned long *)(colDefs
[col
].PtrDataObj
));
2507 val
= (long)(*(char *)(colDefs
[col
].PtrDataObj
));
2509 case SQL_C_UTINYINT
:
2510 val
= (long)(*(unsigned char *)(colDefs
[col
].PtrDataObj
));
2513 val
= (long)(*(UWORD
*)(colDefs
[col
].PtrDataObj
));
2516 val
= (DATE_STRUCT
*)(colDefs
[col
].PtrDataObj
);
2519 val
= (TIME_STRUCT
*)(colDefs
[col
].PtrDataObj
);
2521 case SQL_C_TIMESTAMP
:
2522 val
= (TIMESTAMP_STRUCT
*)(colDefs
[col
].PtrDataObj
);
2525 val
= *(double *)(colDefs
[col
].PtrDataObj
);
2532 } // wxDbTable::GetCol()
2535 void csstrncpyt(char *s
, const char *t
, int n
)
2537 while ((*s
++ = *t
++) && --n
)
2543 void wxDbTable::SetCol(const int col
, const wxVariant val
)
2545 //FIXME: Add proper wxDateTime support to wxVariant..
2548 SetColNull(col
, val
.IsNull());
2552 if ((colDefs
[col
].SqlCtype
== SQL_C_DATE
)
2553 || (colDefs
[col
].SqlCtype
== SQL_C_TIME
)
2554 || (colDefs
[col
].SqlCtype
== SQL_C_TIMESTAMP
))
2556 //Returns null if invalid!
2557 if (!dateval
.ParseDate(val
.GetString()))
2558 SetColNull(col
,TRUE
);
2561 switch (colDefs
[col
].SqlCtype
)
2565 csstrncpyt((char *)(colDefs
[col
].PtrDataObj
),
2566 val
.GetString().c_str(),
2567 colDefs
[col
].SzDataObj
-1);
2571 *(long *)(colDefs
[col
].PtrDataObj
) = val
;
2575 *(short *)(colDefs
[col
].PtrDataObj
) = val
.GetLong();
2578 *(unsigned long *)(colDefs
[col
].PtrDataObj
) = val
.GetLong();
2581 *(char *)(colDefs
[col
].PtrDataObj
) = val
.GetChar();
2583 case SQL_C_UTINYINT
:
2584 *(unsigned char *)(colDefs
[col
].PtrDataObj
) = val
.GetChar();
2587 *(unsigned short *)(colDefs
[col
].PtrDataObj
) = val
.GetLong();
2589 //FIXME: Add proper wxDateTime support to wxVariant..
2592 DATE_STRUCT
*dataptr
=
2593 (DATE_STRUCT
*)colDefs
[col
].PtrDataObj
;
2595 dataptr
->year
= dateval
.GetYear();
2596 dataptr
->month
= dateval
.GetMonth()+1;
2597 dataptr
->day
= dateval
.GetDay();
2602 TIME_STRUCT
*dataptr
=
2603 (TIME_STRUCT
*)colDefs
[col
].PtrDataObj
;
2605 dataptr
->hour
= dateval
.GetHour();
2606 dataptr
->minute
= dateval
.GetMinute();
2607 dataptr
->second
= dateval
.GetSecond();
2610 case SQL_C_TIMESTAMP
:
2612 TIMESTAMP_STRUCT
*dataptr
=
2613 (TIMESTAMP_STRUCT
*)colDefs
[col
].PtrDataObj
;
2614 dataptr
->year
= dateval
.GetYear();
2615 dataptr
->month
= dateval
.GetMonth()+1;
2616 dataptr
->day
= dateval
.GetDay();
2618 dataptr
->hour
= dateval
.GetHour();
2619 dataptr
->minute
= dateval
.GetMinute();
2620 dataptr
->second
= dateval
.GetSecond();
2624 *(double *)(colDefs
[col
].PtrDataObj
) = val
;
2629 } // if (!val.IsNull())
2630 } // wxDbTable::SetCol()
2633 GenericKey
wxDbTable::GetKey()
2638 blk
= malloc(m_keysize
);
2639 blkptr
= (char *) blk
;
2642 for (i
=0; i
< noCols
; i
++)
2644 if (colDefs
[i
].KeyField
)
2646 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2647 blkptr
+= colDefs
[i
].SzDataObj
;
2651 GenericKey k
= GenericKey(blk
, m_keysize
);
2655 } // wxDbTable::GetKey()
2658 void wxDbTable::SetKey(const GenericKey
& k
)
2664 blkptr
= (char *)blk
;
2667 for (i
=0; i
< noCols
; i
++)
2669 if (colDefs
[i
].KeyField
)
2671 SetColNull(i
, FALSE
);
2672 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2673 blkptr
+= colDefs
[i
].SzDataObj
;
2676 } // wxDbTable::SetKey()
2679 #endif // wxUSE_ODBC