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 // Use this line for wxWindows v1.x
30 // Use this line for wxWindows v2.x
31 #include "wx/wxprec.h"
32 #include "wx/version.h"
34 #if wxMAJOR_VERSION == 2
36 #pragma implementation "dbtable.h"
40 #ifdef DBDEBUG_CONSOLE
41 #include "wx/ioswrap.h"
49 #if wxMAJOR_VERSION == 2
51 #include "wx/string.h"
52 #include "wx/object.h"
55 #include "wx/msgdlg.h"
58 #include "wx/filefn.h"
61 #if wxMAJOR_VERSION == 1
62 # if defined(wx_msw) || defined(wx_x)
80 #if wxMAJOR_VERSION == 1
82 #elif wxMAJOR_VERSION == 2
83 #include "wx/dbtable.h"
87 // The HPUX preprocessor lines below were commented out on 8/20/97
88 // because macros.h currently redefines DEBUG and is unneeded.
90 // # include <macros.h>
93 # include <sys/minmax.h>
97 ULONG lastTableID
= 0;
105 /********** wxDbTable::wxDbTable() **********/
106 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const int nCols
,
107 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
109 if (!initialize(pwxDb
, tblName
, nCols
, qryTblName
, qryOnly
, tblPath
))
111 } // wxDbTable::wxDbTable()
114 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
115 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const int nCols
,
116 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
118 wxString tempQryTblName
;
119 tempQryTblName
= qryTblName
;
120 if (!initialize(pwxDb
, tblName
, nCols
, 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 int nCols
,
133 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
135 // Initializing member variables
136 pDb
= pwxDb
; // Pointer to the wxDb object
140 hstmtDefault
= 0; // Initialized below
141 hstmtCount
= 0; // Initialized first time it is needed
148 noCols
= nCols
; // No. of cols in the table
149 where
.Empty(); // Where clause
150 orderBy
.Empty(); // Order By clause
151 from
.Empty(); // From clause
152 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
157 queryTableName
.Empty();
159 wxASSERT(tblName
.Length());
165 tableName
= tblName
; // Table Name
166 if (tblPath
.Length())
167 tablePath
= tblPath
; // Table Path - used for dBase files
171 if (qryTblName
.Length()) // Name of the table/view to query
172 queryTableName
= qryTblName
;
174 queryTableName
= tblName
;
176 pDb
->incrementTableCount();
179 tableID
= ++lastTableID
;
180 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
183 wxTablesInUse
*tableInUse
;
184 tableInUse
= new wxTablesInUse();
185 tableInUse
->tableName
= tblName
;
186 tableInUse
->tableID
= tableID
;
187 tableInUse
->pDb
= pDb
;
188 TablesInUse
.Append(tableInUse
);
193 // Grab the HENV and HDBC from the wxDb object
194 henv
= pDb
->GetHENV();
195 hdbc
= pDb
->GetHDBC();
197 // Allocate space for column definitions
199 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
201 // Allocate statement handles for the table
204 // Allocate a separate statement handle for performing inserts
205 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
206 pDb
->DispAllErrors(henv
, hdbc
);
207 // Allocate a separate statement handle for performing deletes
208 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
209 pDb
->DispAllErrors(henv
, hdbc
);
210 // Allocate a separate statement handle for performing updates
211 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
212 pDb
->DispAllErrors(henv
, hdbc
);
214 // Allocate a separate statement handle for internal use
215 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
216 pDb
->DispAllErrors(henv
, hdbc
);
218 // Set the cursor type for the statement handles
219 cursorType
= SQL_CURSOR_STATIC
;
221 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
223 // Check to see if cursor type is supported
224 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
225 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
227 // Datasource does not support static cursors. Driver
228 // will substitute a cursor type. Call SQLGetStmtOption()
229 // to determine which cursor type was selected.
230 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
231 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
232 #ifdef DBDEBUG_CONSOLE
233 cout
<< wxT("Static cursor changed to: ");
236 case SQL_CURSOR_FORWARD_ONLY
:
237 cout
<< wxT("Forward Only");
239 case SQL_CURSOR_STATIC
:
240 cout
<< wxT("Static");
242 case SQL_CURSOR_KEYSET_DRIVEN
:
243 cout
<< wxT("Keyset Driven");
245 case SQL_CURSOR_DYNAMIC
:
246 cout
<< wxT("Dynamic");
249 cout
<< endl
<< endl
;
252 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
254 // Force the use of a forward only cursor...
255 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
256 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
258 // Should never happen
259 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
266 pDb
->DispNextError();
267 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
270 #ifdef DBDEBUG_CONSOLE
272 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
277 // Set the cursor type for the INSERT statement handle
278 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
279 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
280 // Set the cursor type for the DELETE statement handle
281 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
282 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
283 // Set the cursor type for the UPDATE statement handle
284 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
285 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
288 // Make the default cursor the active cursor
289 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
290 wxASSERT(hstmtDefault
);
291 hstmt
= *hstmtDefault
;
295 } // wxDbTable::initialize()
298 void wxDbTable::cleanup()
303 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
310 TablesInUse
.DeleteContents(TRUE
);
314 pNode
= TablesInUse
.First();
315 while (pNode
&& !found
)
317 if (((wxTablesInUse
*)pNode
->Data())->tableID
== tableID
)
320 if (!TablesInUse
.DeleteNode(pNode
))
321 wxLogDebug (s
,wxT("Unable to delete node!"));
324 pNode
= pNode
->Next();
329 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
);
330 wxLogDebug (msg
,wxT("NOTICE..."));
335 // Decrement the wxDb table count
337 pDb
->decrementTableCount();
339 // Delete memory allocated for column definitions
343 // Free statement handles
349 ODBC 3.0 says to use this form
350 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
352 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
353 pDb
->DispAllErrors(henv
, hdbc
);
359 ODBC 3.0 says to use this form
360 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
362 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
363 pDb
->DispAllErrors(henv
, hdbc
);
369 ODBC 3.0 says to use this form
370 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
372 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
373 pDb
->DispAllErrors(henv
, hdbc
);
379 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
380 pDb
->DispAllErrors(henv
, hdbc
);
383 // Delete dynamically allocated cursors
385 DeleteCursor(hstmtDefault
);
388 DeleteCursor(hstmtCount
);
389 } // wxDbTable::cleanup()
392 /***************************** PRIVATE FUNCTIONS *****************************/
395 /********** wxDbTable::bindUpdateParams() **********/
396 bool wxDbTable::bindParams(bool forUpdate
)
398 wxASSERT(!queryOnly
);
403 UDWORD precision
= 0;
406 // Bind each column of the table that should be bound
407 // to a parameter marker
409 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
413 if (! colDefs
[i
].Updateable
)
418 if (! colDefs
[i
].InsertAllowed
)
422 switch(colDefs
[i
].DbDataType
)
424 case DB_DATA_TYPE_VARCHAR
:
425 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
426 precision
= colDefs
[i
].SzDataObj
;
429 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
431 colDefs
[i
].CbValue
= SQL_NTS
;
433 case DB_DATA_TYPE_INTEGER
:
434 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
435 precision
= pDb
->GetTypeInfInteger().Precision
;
438 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
440 colDefs
[i
].CbValue
= 0;
442 case DB_DATA_TYPE_FLOAT
:
443 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
444 precision
= pDb
->GetTypeInfFloat().Precision
;
445 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
446 // SQL Sybase Anywhere v5.5 returned a negative number for the
447 // MaxScale. This caused ODBC to kick out an error on ibscale.
448 // I check for this here and set the scale = precision.
450 // scale = (short) precision;
452 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
454 colDefs
[i
].CbValue
= 0;
456 case DB_DATA_TYPE_DATE
:
457 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
458 precision
= pDb
->GetTypeInfDate().Precision
;
461 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
463 colDefs
[i
].CbValue
= 0;
468 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
469 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
470 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
472 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
477 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
478 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
479 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
481 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
486 // Completed successfully
489 } // wxDbTable::bindParams()
492 /********** wxDbTable::bindInsertParams() **********/
493 bool wxDbTable::bindInsertParams(void)
495 return bindParams(FALSE
);
496 } // wxDbTable::bindInsertParams()
499 /********** wxDbTable::bindUpdateParams() **********/
500 bool wxDbTable::bindUpdateParams(void)
502 return bindParams(TRUE
);
503 } // wxDbTable::bindUpdateParams()
506 /********** wxDbTable::bindCols() **********/
507 bool wxDbTable::bindCols(HSTMT cursor
)
509 //RG-NULL static SDWORD cb;
511 // Bind each column of the table to a memory address for fetching data
513 for (i
= 0; i
< noCols
; i
++)
515 if (SQLBindCol(cursor
, i
+1, colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
516 //RG-NULL colDefs[i].SzDataObj, &cb) != SQL_SUCCESS)
517 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
519 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
523 // Completed successfully
526 } // wxDbTable::bindCols()
529 /********** wxDbTable::getRec() **********/
530 bool wxDbTable::getRec(UWORD fetchType
)
534 if (!pDb
->FwdOnlyCursors())
536 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
540 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
541 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
543 if (retcode
== SQL_NO_DATA_FOUND
)
546 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
550 // Set the Null member variable to indicate the Null state
551 // of each column just read in.
553 for (i
= 0; i
< noCols
; i
++)
554 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
559 // Fetch the next record from the record set
560 retcode
= SQLFetch(hstmt
);
561 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
563 if (retcode
== SQL_NO_DATA_FOUND
)
566 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
570 // Set the Null member variable to indicate the Null state
571 // of each column just read in.
573 for (i
= 0; i
< noCols
; i
++)
574 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
578 // Completed successfully
581 } // wxDbTable::getRec()
584 /********** wxDbTable::execDelete() **********/
585 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
587 // Execute the DELETE statement
588 if (SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
589 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
591 // Record deleted successfully
594 } // wxDbTable::execDelete()
597 /********** wxDbTable::execUpdate() **********/
598 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
600 // Execute the UPDATE statement
601 if (SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
602 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
604 // Record deleted successfully
607 } // wxDbTable::execUpdate()
610 /********** wxDbTable::query() **********/
611 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
616 // The user may wish to select for update, but the DBMS may not be capable
617 selectForUpdate
= CanSelectForUpdate();
619 selectForUpdate
= FALSE
;
621 // Set the SQL SELECT string
622 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
623 { // so generate a select statement.
624 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
625 pDb
->WriteSqlLog(sqlStmt
);
628 This is the block of code that got added during the 2.2.1 merge with
629 the 2.2 main branch that somehow got added here when it should not have. - gt
632 wxStrcpy(sqlStmt, pSqlStmt);
634 SQLFreeStmt(hstmt, SQL_CLOSE);
635 if (SQLExecDirect(hstmt, (UCHAR FAR *) sqlStmt, SQL_NTS) == SQL_SUCCESS)
639 pDb->DispAllErrors(henv, hdbc, hstmt);
643 // Make sure the cursor is closed first
644 if (!CloseCursor(hstmt
))
647 // Execute the SQL SELECT statement
649 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
650 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
651 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
653 // Completed successfully
656 } // wxDbTable::query()
659 /***************************** PUBLIC FUNCTIONS *****************************/
662 /********** wxDbTable::Open() **********/
663 bool wxDbTable::Open(bool checkPrivileges
)
673 // Verify that the table exists in the database
674 if (!pDb
->TableExists(tableName
,/*pDb->GetUsername()*/NULL
,tablePath
))
676 s
= wxT("Table/view does not exist in the database");
677 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
678 s
+= wxT(", or you have no permissions.\n");
682 else if (checkPrivileges
)
684 // Verify the user has rights to access the table.
685 // Shortcut boolean evaluation to optimize out call to
688 // Unfortunately this optimization doesn't seem to be
690 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
691 !pDb
->TablePrivileges(tableName
,wxT("SELECT"),NULL
,pDb
->GetUsername(),tablePath
))
692 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
699 if (!tablePath
.IsEmpty())
700 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
702 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
705 pDb
->LogError(p
.GetData());
710 // Bind the member variables for field exchange between
711 // the wxDbTable object and the ODBC record.
714 if (!bindInsertParams()) // Inserts
717 if (!bindUpdateParams()) // Updates
721 if (!bindCols(*hstmtDefault
)) // Selects
724 if (!bindCols(hstmtInternal
)) // Internal use only
728 * Do NOT bind the hstmtCount cursor!!!
731 // Build an insert statement using parameter markers
732 if (!queryOnly
&& noCols
> 0)
734 bool needComma
= FALSE
;
735 sqlStmt
.Printf(wxT("INSERT INTO %s ("), tableName
.c_str());
736 for (i
= 0; i
< noCols
; i
++)
738 if (! colDefs
[i
].InsertAllowed
)
742 sqlStmt
+= colDefs
[i
].ColName
;
746 sqlStmt
+= wxT(") VALUES (");
748 int insertableCount
= 0;
750 for (i
= 0; i
< noCols
; i
++)
752 if (! colDefs
[i
].InsertAllowed
)
762 // Prepare the insert statement for execution
765 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
766 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
772 // Completed successfully
775 } // wxDbTable::Open()
778 /********** wxDbTable::Query() **********/
779 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
782 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
784 } // wxDbTable::Query()
787 /********** wxDbTable::QueryBySqlStmt() **********/
788 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
790 pDb
->WriteSqlLog(pSqlStmt
);
792 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
794 } // wxDbTable::QueryBySqlStmt()
797 /********** wxDbTable::QueryMatching() **********/
798 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
801 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
803 } // wxDbTable::QueryMatching()
806 /********** wxDbTable::QueryOnKeyFields() **********/
807 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
810 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
812 } // wxDbTable::QueryOnKeyFields()
815 /********** wxDbTable::GetPrev() **********/
816 bool wxDbTable::GetPrev(void)
818 if (pDb
->FwdOnlyCursors())
820 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
824 return(getRec(SQL_FETCH_PRIOR
));
826 } // wxDbTable::GetPrev()
829 /********** wxDbTable::operator-- **********/
830 bool wxDbTable::operator--(int)
832 if (pDb
->FwdOnlyCursors())
834 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
838 return(getRec(SQL_FETCH_PRIOR
));
840 } // wxDbTable::operator--
843 /********** wxDbTable::GetFirst() **********/
844 bool wxDbTable::GetFirst(void)
846 if (pDb
->FwdOnlyCursors())
848 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
852 return(getRec(SQL_FETCH_FIRST
));
854 } // wxDbTable::GetFirst()
857 /********** wxDbTable::GetLast() **********/
858 bool wxDbTable::GetLast(void)
860 if (pDb
->FwdOnlyCursors())
862 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
866 return(getRec(SQL_FETCH_LAST
));
868 } // wxDbTable::GetLast()
871 /********** wxDbTable::BuildDeleteStmt() **********/
872 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
874 wxASSERT(!queryOnly
);
878 wxString whereClause
;
882 // Handle the case of DeleteWhere() and the where clause is blank. It should
883 // delete all records from the database in this case.
884 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
886 pSqlStmt
.Printf(wxT("DELETE FROM %s"), tableName
.c_str());
890 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "), tableName
.c_str());
892 // Append the WHERE clause to the SQL DELETE statement
895 case DB_DEL_KEYFIELDS
:
896 // If the datasource supports the ROWID column, build
897 // the where on ROWID for efficiency purposes.
898 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
902 wxChar rowid
[wxDB_ROWID_LEN
+1];
904 // Get the ROWID value. If not successful retreiving the ROWID,
905 // simply fall down through the code and build the WHERE clause
906 // based on the key fields.
907 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
909 pSqlStmt
+= wxT("ROWID = '");
911 pSqlStmt
+= wxT("'");
915 // Unable to delete by ROWID, so build a WHERE
916 // clause based on the keyfields.
917 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
918 pSqlStmt
+= whereClause
;
921 pSqlStmt
+= pWhereClause
;
923 case DB_DEL_MATCHING
:
924 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
925 pSqlStmt
+= whereClause
;
929 } // BuildDeleteStmt()
932 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
933 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
935 wxString tempSqlStmt
;
936 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
937 wxStrcpy(pSqlStmt
, tempSqlStmt
);
938 } // wxDbTable::BuildDeleteStmt()
941 /********** wxDbTable::BuildSelectStmt() **********/
942 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
944 wxString whereClause
;
947 // Build a select statement to query the database
948 pSqlStmt
= wxT("SELECT ");
950 // SELECT DISTINCT values only?
952 pSqlStmt
+= wxT("DISTINCT ");
954 // Was a FROM clause specified to join tables to the base table?
955 // Available for ::Query() only!!!
956 bool appendFromClause
= FALSE
;
957 #if wxODBC_BACKWARD_COMPATABILITY
958 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
959 appendFromClause
= TRUE
;
961 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
962 appendFromClause
= TRUE
;
965 // Add the column list
967 for (i
= 0; i
< noCols
; i
++)
969 // If joining tables, the base table column names must be qualified to avoid ambiguity
970 if (appendFromClause
)
972 pSqlStmt
+= queryTableName
;
973 pSqlStmt
+= wxT(".");
975 pSqlStmt
+= colDefs
[i
].ColName
;
977 pSqlStmt
+= wxT(",");
980 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
981 // the ROWID if querying distinct records. The rowid will always be unique.
982 if (!distinct
&& CanUpdByROWID())
984 // If joining tables, the base table column names must be qualified to avoid ambiguity
985 if (appendFromClause
)
987 pSqlStmt
+= wxT(",");
988 pSqlStmt
+= queryTableName
;
989 pSqlStmt
+= wxT(".ROWID");
992 pSqlStmt
+= wxT(",ROWID");
995 // Append the FROM tablename portion
996 pSqlStmt
+= wxT(" FROM ");
997 pSqlStmt
+= queryTableName
;
999 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1000 // The HOLDLOCK keyword follows the table name in the from clause.
1001 // Each table in the from clause must specify HOLDLOCK or
1002 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1003 // is parsed but ignored in SYBASE Transact-SQL.
1004 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1005 pSqlStmt
+= wxT(" HOLDLOCK");
1007 if (appendFromClause
)
1010 // Append the WHERE clause. Either append the where clause for the class
1011 // or build a where clause. The typeOfSelect determines this.
1012 switch(typeOfSelect
)
1014 case DB_SELECT_WHERE
:
1015 #if wxODBC_BACKWARD_COMPATABILITY
1016 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1018 if (where
.Length()) // May not want a where clause!!!
1021 pSqlStmt
+= wxT(" WHERE ");
1025 case DB_SELECT_KEYFIELDS
:
1026 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1027 if (whereClause
.Length())
1029 pSqlStmt
+= wxT(" WHERE ");
1030 pSqlStmt
+= whereClause
;
1033 case DB_SELECT_MATCHING
:
1034 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1035 if (whereClause
.Length())
1037 pSqlStmt
+= wxT(" WHERE ");
1038 pSqlStmt
+= whereClause
;
1043 // Append the ORDER BY clause
1044 #if wxODBC_BACKWARD_COMPATABILITY
1045 if (orderBy
&& wxStrlen(orderBy
))
1047 if (orderBy
.Length())
1050 pSqlStmt
+= wxT(" ORDER BY ");
1051 pSqlStmt
+= orderBy
;
1054 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1055 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1056 // HOLDLOCK for Sybase.
1057 if (selectForUpdate
&& CanSelectForUpdate())
1058 pSqlStmt
+= wxT(" FOR UPDATE");
1060 } // wxDbTable::BuildSelectStmt()
1063 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1064 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1066 wxString tempSqlStmt
;
1067 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1068 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1069 } // wxDbTable::BuildSelectStmt()
1072 /********** wxDbTable::BuildUpdateStmt() **********/
1073 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1075 wxASSERT(!queryOnly
);
1079 wxString whereClause
;
1080 whereClause
.Empty();
1082 bool firstColumn
= TRUE
;
1084 pSqlStmt
.Printf(wxT("UPDATE %s SET "), tableName
.c_str());
1086 // Append a list of columns to be updated
1088 for (i
= 0; i
< noCols
; i
++)
1090 // Only append Updateable columns
1091 if (colDefs
[i
].Updateable
)
1094 pSqlStmt
+= wxT(",");
1096 firstColumn
= FALSE
;
1097 pSqlStmt
+= colDefs
[i
].ColName
;
1098 pSqlStmt
+= wxT(" = ?");
1102 // Append the WHERE clause to the SQL UPDATE statement
1103 pSqlStmt
+= wxT(" WHERE ");
1106 case DB_UPD_KEYFIELDS
:
1107 // If the datasource supports the ROWID column, build
1108 // the where on ROWID for efficiency purposes.
1109 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1110 if (CanUpdByROWID())
1113 wxChar rowid
[wxDB_ROWID_LEN
+1];
1115 // Get the ROWID value. If not successful retreiving the ROWID,
1116 // simply fall down through the code and build the WHERE clause
1117 // based on the key fields.
1118 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1120 pSqlStmt
+= wxT("ROWID = '");
1122 pSqlStmt
+= wxT("'");
1126 // Unable to delete by ROWID, so build a WHERE
1127 // clause based on the keyfields.
1128 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1129 pSqlStmt
+= whereClause
;
1132 pSqlStmt
+= pWhereClause
;
1135 } // BuildUpdateStmt()
1138 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1139 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1141 wxString tempSqlStmt
;
1142 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1143 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1144 } // BuildUpdateStmt()
1147 /********** wxDbTable::BuildWhereClause() **********/
1148 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1149 const wxString
&qualTableName
, bool useLikeComparison
)
1151 * Note: BuildWhereClause() currently ignores timestamp columns.
1152 * They are not included as part of the where clause.
1155 bool moreThanOneColumn
= FALSE
;
1158 // Loop through the columns building a where clause as you go
1160 for (i
= 0; i
< noCols
; i
++)
1162 // Determine if this column should be included in the WHERE clause
1163 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1164 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(i
))))
1166 // Skip over timestamp columns
1167 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1169 // If there is more than 1 column, join them with the keyword "AND"
1170 if (moreThanOneColumn
)
1171 pWhereClause
+= wxT(" AND ");
1173 moreThanOneColumn
= TRUE
;
1174 // Concatenate where phrase for the column
1175 if (qualTableName
.Length())
1177 pWhereClause
+= qualTableName
;
1178 pWhereClause
+= wxT(".");
1180 pWhereClause
+= colDefs
[i
].ColName
;
1181 if (useLikeComparison
&& (colDefs
[i
].SqlCtype
== SQL_C_CHAR
))
1182 pWhereClause
+= wxT(" LIKE ");
1184 pWhereClause
+= wxT(" = ");
1185 switch(colDefs
[i
].SqlCtype
)
1188 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1191 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[i
].PtrDataObj
));
1194 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[i
].PtrDataObj
));
1197 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1200 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1203 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1206 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1209 pWhereClause
+= colValue
;
1212 } // wxDbTable::BuildWhereClause()
1215 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1216 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1217 const wxString
&qualTableName
, bool useLikeComparison
)
1219 wxString tempSqlStmt
;
1220 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1221 wxStrcpy(pWhereClause
, tempSqlStmt
);
1222 } // wxDbTable::BuildWhereClause()
1225 /********** wxDbTable::GetRowNum() **********/
1226 UWORD
wxDbTable::GetRowNum(void)
1230 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1232 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1236 // Completed successfully
1237 return((UWORD
) rowNum
);
1239 } // wxDbTable::GetRowNum()
1242 /********** wxDbTable::CloseCursor() **********/
1243 bool wxDbTable::CloseCursor(HSTMT cursor
)
1245 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1246 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1248 // Completed successfully
1251 } // wxDbTable::CloseCursor()
1254 /********** wxDbTable::CreateTable() **********/
1255 bool wxDbTable::CreateTable(bool attemptDrop
)
1263 #ifdef DBDEBUG_CONSOLE
1264 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1268 if (attemptDrop
&& !DropTable())
1272 #ifdef DBDEBUG_CONSOLE
1273 for (i
= 0; i
< noCols
; i
++)
1275 // Exclude derived columns since they are NOT part of the base table
1276 if (colDefs
[i
].DerivedCol
)
1278 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1279 switch(colDefs
[i
].DbDataType
)
1281 case DB_DATA_TYPE_VARCHAR
:
1282 cout
<< pDb
->typeInfVarchar
.TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1284 case DB_DATA_TYPE_INTEGER
:
1285 cout
<< pDb
->typeInfInteger
.TypeName
;
1287 case DB_DATA_TYPE_FLOAT
:
1288 cout
<< pDb
->typeInfFloat
.TypeName
;
1290 case DB_DATA_TYPE_DATE
:
1291 cout
<< pDb
->typeInfDate
.TypeName
;
1298 // Build a CREATE TABLE string from the colDefs structure.
1299 bool needComma
= FALSE
;
1300 sqlStmt
.Printf(wxT("CREATE TABLE %s ("), tableName
.c_str());
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
)
1309 sqlStmt
+= wxT(",");
1311 sqlStmt
+= colDefs
[i
].ColName
;
1312 sqlStmt
+= wxT(" ");
1314 switch(colDefs
[i
].DbDataType
)
1316 case DB_DATA_TYPE_VARCHAR
:
1317 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1319 case DB_DATA_TYPE_INTEGER
:
1320 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1322 case DB_DATA_TYPE_FLOAT
:
1323 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1325 case DB_DATA_TYPE_DATE
:
1326 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1329 // For varchars, append the size of the string
1330 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1333 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1337 if (pDb
->Dbms() == dbmsDB2
||
1338 pDb
->Dbms() == dbmsMY_SQL
||
1339 pDb
->Dbms() == dbmsSYBASE_ASE
||
1340 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1342 if (colDefs
[i
].KeyField
)
1344 sqlStmt
+= wxT(" NOT NULL");
1350 // If there is a primary key defined, include it in the create statement
1351 for (i
= j
= 0; i
< noCols
; i
++)
1353 if (colDefs
[i
].KeyField
)
1359 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
1361 if (pDb
->Dbms() != dbmsMY_SQL
)
1363 sqlStmt
+= wxT(",CONSTRAINT ");
1364 sqlStmt
+= tableName
;
1365 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1369 /* MySQL goes out on this one. We also declare the relevant key NON NULL above */
1370 sqlStmt
+= wxT(", PRIMARY KEY (");
1373 // List column name(s) of column(s) comprising the primary key
1374 for (i
= j
= 0; i
< noCols
; i
++)
1376 if (colDefs
[i
].KeyField
)
1378 if (j
++) // Multi part key, comma separate names
1379 sqlStmt
+= wxT(",");
1380 sqlStmt
+= colDefs
[i
].ColName
;
1383 sqlStmt
+= wxT(")");
1385 // Append the closing parentheses for the create table statement
1386 sqlStmt
+= wxT(")");
1388 pDb
->WriteSqlLog(sqlStmt
);
1390 #ifdef DBDEBUG_CONSOLE
1391 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1394 // Execute the CREATE TABLE statement
1395 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1396 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1398 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1399 pDb
->RollbackTrans();
1404 // Commit the transaction and close the cursor
1405 if (!pDb
->CommitTrans())
1407 if (!CloseCursor(hstmt
))
1410 // Database table created successfully
1413 } // wxDbTable::CreateTable()
1416 /********** wxDbTable::DropTable() **********/
1417 bool wxDbTable::DropTable()
1419 // NOTE: This function returns TRUE if the Table does not exist, but
1420 // only for identified databases. Code will need to be added
1421 // below for any other databases when those databases are defined
1422 // to handle this situation consistently
1426 sqlStmt
.Printf(wxT("DROP TABLE %s"), tableName
.c_str());
1428 pDb
->WriteSqlLog(sqlStmt
);
1430 #ifdef DBDEBUG_CONSOLE
1431 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1434 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1436 // Check for "Base table not found" error and ignore
1437 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1438 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) &&
1439 wxStrcmp(pDb
->sqlState
, wxT("S1000"))) // "Base table not found"
1441 // Check for product specific error codes
1442 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1443 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1444 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1446 pDb
->DispNextError();
1447 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1448 pDb
->RollbackTrans();
1455 // Commit the transaction and close the cursor
1456 if (! pDb
->CommitTrans())
1458 if (! CloseCursor(hstmt
))
1462 } // wxDbTable::DropTable()
1465 /********** wxDbTable::CreateIndex() **********/
1466 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, int noIdxCols
, wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1470 // Drop the index first
1471 if (attemptDrop
&& !DropIndex(idxName
))
1474 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1475 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1476 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1477 // table was created, then months later you determine that an additional index while
1478 // give better performance, so you want to add an index).
1480 // The following block of code will modify the column definition to make the column be
1481 // defined with the "NOT NULL" qualifier.
1482 if (pDb
->Dbms() == dbmsMY_SQL
)
1487 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1491 // Find the column definition that has the ColName that matches the
1492 // index column name. We need to do this to get the DB_DATA_TYPE of
1493 // the index column, as MySQL's syntax for the ALTER column requires
1495 while (!found
&& (j
< this->noCols
))
1497 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1505 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1506 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1511 wxODBC_ERRORS retcode
;
1512 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1513 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1514 // This line is just here for debug checking of the value
1515 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1525 pDb
->RollbackTrans();
1530 // Build a CREATE INDEX statement
1531 sqlStmt
= wxT("CREATE ");
1533 sqlStmt
+= wxT("UNIQUE ");
1535 sqlStmt
+= wxT("INDEX ");
1537 sqlStmt
+= wxT(" ON ");
1538 sqlStmt
+= tableName
;
1539 sqlStmt
+= wxT(" (");
1541 // Append list of columns making up index
1543 for (i
= 0; i
< noIdxCols
; i
++)
1545 sqlStmt
+= pIdxDefs
[i
].ColName
;
1546 /* Postgres doesn't cope with ASC */
1547 if (pDb
->Dbms() != dbmsPOSTGRES
)
1549 if (pIdxDefs
[i
].Ascending
)
1550 sqlStmt
+= wxT(" ASC");
1552 sqlStmt
+= wxT(" DESC");
1555 if ((i
+ 1) < noIdxCols
)
1556 sqlStmt
+= wxT(",");
1559 // Append closing parentheses
1560 sqlStmt
+= wxT(")");
1562 pDb
->WriteSqlLog(sqlStmt
);
1564 #ifdef DBDEBUG_CONSOLE
1565 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1568 // Execute the CREATE INDEX statement
1569 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1571 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1572 pDb
->RollbackTrans();
1577 // Commit the transaction and close the cursor
1578 if (! pDb
->CommitTrans())
1580 if (! CloseCursor(hstmt
))
1583 // Index Created Successfully
1586 } // wxDbTable::CreateIndex()
1589 /********** wxDbTable::DropIndex() **********/
1590 bool wxDbTable::DropIndex(const wxString
&idxName
)
1592 // NOTE: This function returns TRUE if the Index does not exist, but
1593 // only for identified databases. Code will need to be added
1594 // below for any other databases when those databases are defined
1595 // to handle this situation consistently
1599 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
)
1600 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),idxName
.c_str(), tableName
.c_str());
1601 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1602 (pDb
->Dbms() == dbmsSYBASE_ASE
))
1603 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),tableName
.c_str(), idxName
.c_str());
1605 sqlStmt
.Printf(wxT("DROP INDEX %s"),idxName
.c_str());
1607 pDb
->WriteSqlLog(sqlStmt
);
1609 #ifdef DBDEBUG_CONSOLE
1610 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1613 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1615 // Check for "Index not found" error and ignore
1616 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1617 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1619 // Check for product specific error codes
1620 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1621 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1622 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1623 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1624 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1625 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1628 pDb
->DispNextError();
1629 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1630 pDb
->RollbackTrans();
1637 // Commit the transaction and close the cursor
1638 if (! pDb
->CommitTrans())
1640 if (! CloseCursor(hstmt
))
1644 } // wxDbTable::DropIndex()
1647 /********** wxDbTable::SetOrderByColNums() **********/
1648 bool wxDbTable::SetOrderByColNums(int first
, ... )
1656 va_start(argptr
, first
); /* Initialize variable arguments. */
1657 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1659 // Make sure the passed in column number
1660 // is within the valid range of columns
1662 // Valid columns are 0 thru noCols-1
1663 if (colNo
>= noCols
|| colNo
< 0)
1670 tempStr
+= wxT(",");
1672 tempStr
+= colDefs
[colNo
].ColName
;
1673 colNo
= va_arg (argptr
, int);
1675 va_end (argptr
); /* Reset variable arguments. */
1677 SetOrderByClause(tempStr
);
1680 } // wxDbTable::SetOrderByColNums()
1683 /********** wxDbTable::Insert() **********/
1684 int wxDbTable::Insert(void)
1686 wxASSERT(!queryOnly
);
1687 if (queryOnly
|| !insertable
)
1692 // Insert the record by executing the already prepared insert statement
1694 retcode
=SQLExecute(hstmtInsert
);
1695 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1697 // Check to see if integrity constraint was violated
1698 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1699 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1700 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1703 pDb
->DispNextError();
1704 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1709 // Record inserted into the datasource successfully
1712 } // wxDbTable::Insert()
1715 /********** wxDbTable::Update() **********/
1716 bool wxDbTable::Update(void)
1718 wxASSERT(!queryOnly
);
1724 // Build the SQL UPDATE statement
1725 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1727 pDb
->WriteSqlLog(sqlStmt
);
1729 #ifdef DBDEBUG_CONSOLE
1730 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1733 // Execute the SQL UPDATE statement
1734 return(execUpdate(sqlStmt
));
1736 } // wxDbTable::Update()
1739 /********** wxDbTable::Update(pSqlStmt) **********/
1740 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1742 wxASSERT(!queryOnly
);
1746 pDb
->WriteSqlLog(pSqlStmt
);
1748 return(execUpdate(pSqlStmt
));
1750 } // wxDbTable::Update(pSqlStmt)
1753 /********** wxDbTable::UpdateWhere() **********/
1754 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1756 wxASSERT(!queryOnly
);
1762 // Build the SQL UPDATE statement
1763 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1765 pDb
->WriteSqlLog(sqlStmt
);
1767 #ifdef DBDEBUG_CONSOLE
1768 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1771 // Execute the SQL UPDATE statement
1772 return(execUpdate(sqlStmt
));
1774 } // wxDbTable::UpdateWhere()
1777 /********** wxDbTable::Delete() **********/
1778 bool wxDbTable::Delete(void)
1780 wxASSERT(!queryOnly
);
1787 // Build the SQL DELETE statement
1788 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1790 pDb
->WriteSqlLog(sqlStmt
);
1792 // Execute the SQL DELETE statement
1793 return(execDelete(sqlStmt
));
1795 } // wxDbTable::Delete()
1798 /********** wxDbTable::DeleteWhere() **********/
1799 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
1801 wxASSERT(!queryOnly
);
1808 // Build the SQL DELETE statement
1809 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1811 pDb
->WriteSqlLog(sqlStmt
);
1813 // Execute the SQL DELETE statement
1814 return(execDelete(sqlStmt
));
1816 } // wxDbTable::DeleteWhere()
1819 /********** wxDbTable::DeleteMatching() **********/
1820 bool wxDbTable::DeleteMatching(void)
1822 wxASSERT(!queryOnly
);
1829 // Build the SQL DELETE statement
1830 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1832 pDb
->WriteSqlLog(sqlStmt
);
1834 // Execute the SQL DELETE statement
1835 return(execDelete(sqlStmt
));
1837 } // wxDbTable::DeleteMatching()
1840 /********** wxDbTable::IsColNull() **********/
1841 bool wxDbTable::IsColNull(int colNo
)
1844 This logic is just not right. It would indicate TRUE
1845 if a numeric field were set to a value of 0.
1847 switch(colDefs[colNo].SqlCtype)
1850 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
1852 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
1854 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
1856 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1858 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1860 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
1862 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
1863 case SQL_C_TIMESTAMP:
1864 TIMESTAMP_STRUCT *pDt;
1865 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
1866 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
1874 return (colDefs
[colNo
].Null
);
1875 } // wxDbTable::IsColNull()
1878 /********** wxDbTable::CanSelectForUpdate() **********/
1879 bool wxDbTable::CanSelectForUpdate(void)
1884 if (pDb
->Dbms() == dbmsMY_SQL
)
1887 if ((pDb
->Dbms() == dbmsORACLE
) ||
1888 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
1893 } // wxDbTable::CanSelectForUpdate()
1896 /********** wxDbTable::CanUpdByROWID() **********/
1897 bool wxDbTable::CanUpdByROWID(void)
1900 * NOTE: Returning FALSE for now until this can be debugged,
1901 * as the ROWID is not getting updated correctly
1905 if (pDb
->Dbms() == dbmsORACLE
)
1910 } // wxDbTable::CanUpdByROWID()
1913 /********** wxDbTable::IsCursorClosedOnCommit() **********/
1914 bool wxDbTable::IsCursorClosedOnCommit(void)
1916 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
1921 } // wxDbTable::IsCursorClosedOnCommit()
1925 /********** wxDbTable::ClearMemberVar() **********/
1926 void wxDbTable::ClearMemberVar(int colNo
, bool setToNull
)
1928 wxASSERT(colNo
< noCols
);
1930 switch(colDefs
[colNo
].SqlCtype
)
1933 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
1936 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
1939 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
1942 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
1945 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
1948 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
1951 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
1953 case SQL_C_TIMESTAMP
:
1954 TIMESTAMP_STRUCT
*pDt
;
1955 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
1968 } // wxDbTable::ClearMemberVar()
1971 /********** wxDbTable::ClearMemberVars() **********/
1972 void wxDbTable::ClearMemberVars(bool setToNull
)
1976 // Loop through the columns setting each member variable to zero
1977 for (i
=0; i
< noCols
; i
++)
1978 ClearMemberVar(i
,setToNull
);
1980 } // wxDbTable::ClearMemberVars()
1983 /********** wxDbTable::SetQueryTimeout() **********/
1984 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
1986 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1987 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
1988 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1989 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
1990 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1991 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
1992 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1993 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
1995 // Completed Successfully
1998 } // wxDbTable::SetQueryTimeout()
2001 /********** wxDbTable::SetColDefs() **********/
2002 void wxDbTable::SetColDefs(int index
, const wxString
&fieldName
, int dataType
, void *pData
,
2003 int cType
, int size
, bool keyField
, bool upd
,
2004 bool insAllow
, bool derivedCol
)
2006 if (!colDefs
) // May happen if the database connection fails
2009 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2011 wxStrncpy (colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2012 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2015 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2017 colDefs
[index
].DbDataType
= dataType
;
2018 colDefs
[index
].PtrDataObj
= pData
;
2019 colDefs
[index
].SqlCtype
= cType
;
2020 colDefs
[index
].SzDataObj
= size
;
2021 colDefs
[index
].KeyField
= keyField
;
2022 colDefs
[index
].DerivedCol
= derivedCol
;
2023 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2026 colDefs
[index
].Updateable
= FALSE
;
2027 colDefs
[index
].InsertAllowed
= FALSE
;
2031 colDefs
[index
].Updateable
= upd
;
2032 colDefs
[index
].InsertAllowed
= insAllow
;
2035 colDefs
[index
].Null
= FALSE
;
2037 } // wxDbTable::SetColDefs()
2040 /********** wxDbTable::SetColDefs() **********/
2041 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, ULONG numCols
)
2044 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2050 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2052 for (index
= 0; index
< numCols
; index
++)
2054 // Process the fields
2055 switch (pColInfs
[index
].dbDataType
)
2057 case DB_DATA_TYPE_VARCHAR
:
2058 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2059 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2060 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2062 case DB_DATA_TYPE_INTEGER
:
2063 // Can be long or short
2064 if (pColInfs
[index
].bufferLength
== sizeof(long))
2066 pColDataPtrs
[index
].PtrDataObj
= new long;
2067 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2068 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2072 pColDataPtrs
[index
].PtrDataObj
= new short;
2073 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2074 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2077 case DB_DATA_TYPE_FLOAT
:
2078 // Can be float or double
2079 if (pColInfs
[index
].bufferLength
== sizeof(float))
2081 pColDataPtrs
[index
].PtrDataObj
= new float;
2082 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2083 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2087 pColDataPtrs
[index
].PtrDataObj
= new double;
2088 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2089 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2092 case DB_DATA_TYPE_DATE
:
2093 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2094 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2095 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2098 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2102 return (pColDataPtrs
);
2104 } // wxDbTable::SetColDefs()
2107 /********** wxDbTable::SetCursor() **********/
2108 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2110 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2111 hstmt
= *hstmtDefault
;
2113 hstmt
= *hstmtActivate
;
2115 } // wxDbTable::SetCursor()
2118 /********** wxDbTable::Count(const wxString &) **********/
2119 ULONG
wxDbTable::Count(const wxString
&args
)
2125 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2126 sqlStmt
= wxT("SELECT COUNT(");
2128 sqlStmt
+= wxT(") FROM ");
2129 sqlStmt
+= queryTableName
;
2130 #if wxODBC_BACKWARD_COMPATABILITY
2131 if (from
&& wxStrlen(from
))
2137 // Add the where clause if one is provided
2138 #if wxODBC_BACKWARD_COMPATABILITY
2139 if (where
&& wxStrlen(where
))
2144 sqlStmt
+= wxT(" WHERE ");
2148 pDb
->WriteSqlLog(sqlStmt
);
2150 // Initialize the Count cursor if it's not already initialized
2153 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2154 wxASSERT(hstmtCount
);
2159 // Execute the SQL statement
2160 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2162 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2167 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2169 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2173 // Obtain the result
2174 if (SQLGetData(*hstmtCount
, 1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2176 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2181 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2182 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2184 // Return the record count
2187 } // wxDbTable::Count()
2190 /********** wxDbTable::Refresh() **********/
2191 bool wxDbTable::Refresh(void)
2195 // Switch to the internal cursor so any active cursors are not corrupted
2196 HSTMT currCursor
= GetCursor();
2197 hstmt
= hstmtInternal
;
2198 #if wxODBC_BACKWARD_COMPATABILITY
2199 // Save the where and order by clauses
2200 char *saveWhere
= where
;
2201 char *saveOrderBy
= orderBy
;
2203 wxString saveWhere
= where
;
2204 wxString saveOrderBy
= orderBy
;
2206 // Build a where clause to refetch the record with. Try and use the
2207 // ROWID if it's available, ow use the key fields.
2208 wxString whereClause
;
2209 whereClause
.Empty();
2211 if (CanUpdByROWID())
2214 wxChar rowid
[wxDB_ROWID_LEN
+1];
2216 // Get the ROWID value. If not successful retreiving the ROWID,
2217 // simply fall down through the code and build the WHERE clause
2218 // based on the key fields.
2219 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2221 whereClause
+= queryTableName
;
2222 whereClause
+= wxT(".ROWID = '");
2223 whereClause
+= rowid
;
2224 whereClause
+= wxT("'");
2228 // If unable to use the ROWID, build a where clause from the keyfields
2229 if (wxStrlen(whereClause
) == 0)
2230 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2232 // Requery the record
2233 where
= whereClause
;
2238 if (result
&& !GetNext())
2241 // Switch back to original cursor
2242 SetCursor(&currCursor
);
2244 // Free the internal cursor
2245 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2246 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2248 // Restore the original where and order by clauses
2250 orderBy
= saveOrderBy
;
2254 } // wxDbTable::Refresh()
2257 /********** wxDbTable::SetColNull(int colNo, bool set) **********/
2258 bool wxDbTable::SetColNull(int colNo
, bool set
)
2262 colDefs
[colNo
].Null
= set
;
2263 if (set
) // Blank out the values in the member variable
2264 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2270 } // wxDbTable::SetColNull()
2273 /********** wxDbTable::SetColNull(const wxString &colName, bool set) **********/
2274 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2277 for (i
= 0; i
< noCols
; i
++)
2279 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2285 colDefs
[i
].Null
= set
;
2286 if (set
) // Blank out the values in the member variable
2287 ClearMemberVar(i
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2293 } // wxDbTable::SetColNull()
2296 /********** wxDbTable::GetNewCursor() **********/
2297 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2299 HSTMT
*newHSTMT
= new HSTMT
;
2304 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2306 pDb
->DispAllErrors(henv
, hdbc
);
2311 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2313 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2320 if(!bindCols(*newHSTMT
))
2328 SetCursor(newHSTMT
);
2332 } // wxDbTable::GetNewCursor()
2335 /********** wxDbTable::DeleteCursor() **********/
2336 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2340 if (!hstmtDel
) // Cursor already deleted
2344 ODBC 3.0 says to use this form
2345 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2348 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2350 pDb
->DispAllErrors(henv
, hdbc
);
2358 } // wxDbTable::DeleteCursor()
2360 #endif // wxUSE_ODBC