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
43 #include "wx/ioswrap.h"
47 #include "wx/string.h"
48 #include "wx/object.h"
52 #include "wx/msgdlg.h"
56 #include "wx/filefn.h"
65 #include "wx/dbtable.h"
68 // The HPUX preprocessor lines below were commented out on 8/20/97
69 // because macros.h currently redefines DEBUG and is unneeded.
71 // # include <macros.h>
74 # include <sys/minmax.h>
78 ULONG lastTableID
= 0;
86 /********** wxDbColDef::wxDbColDef() Constructor **********/
87 wxDbColDef::wxDbColDef()
93 bool wxDbColDef::Initialize()
96 DbDataType
= DB_DATA_TYPE_INTEGER
;
97 SqlCtype
= SQL_C_LONG
;
102 InsertAllowed
= FALSE
;
108 } // wxDbColDef::Initialize()
111 /********** wxDbTable::wxDbTable() Constructor **********/
112 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
113 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
115 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
117 } // wxDbTable::wxDbTable()
120 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
121 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
122 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
124 wxString tempQryTblName
;
125 tempQryTblName
= qryTblName
;
126 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
128 } // wxDbTable::wxDbTable()
131 /********** wxDbTable::~wxDbTable() **********/
132 wxDbTable::~wxDbTable()
135 } // wxDbTable::~wxDbTable()
138 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
139 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
141 // Initializing member variables
142 pDb
= pwxDb
; // Pointer to the wxDb object
146 m_hstmtGridQuery
= 0;
147 hstmtDefault
= 0; // Initialized below
148 hstmtCount
= 0; // Initialized first time it is needed
155 noCols
= numColumns
; // Number of cols in the table
156 where
.Empty(); // Where clause
157 orderBy
.Empty(); // Order By clause
158 from
.Empty(); // From clause
159 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
164 queryTableName
.Empty();
166 wxASSERT(tblName
.Length());
172 tableName
= tblName
; // Table Name
173 if (tblPath
.Length())
174 tablePath
= tblPath
; // Table Path - used for dBase files
178 if (qryTblName
.Length()) // Name of the table/view to query
179 queryTableName
= qryTblName
;
181 queryTableName
= tblName
;
183 pDb
->incrementTableCount();
186 tableID
= ++lastTableID
;
187 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
190 wxTablesInUse
*tableInUse
;
191 tableInUse
= new wxTablesInUse();
192 tableInUse
->tableName
= tblName
;
193 tableInUse
->tableID
= tableID
;
194 tableInUse
->pDb
= pDb
;
195 TablesInUse
.Append(tableInUse
);
200 // Grab the HENV and HDBC from the wxDb object
201 henv
= pDb
->GetHENV();
202 hdbc
= pDb
->GetHDBC();
204 // Allocate space for column definitions
206 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
208 // Allocate statement handles for the table
211 // Allocate a separate statement handle for performing inserts
212 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
213 pDb
->DispAllErrors(henv
, hdbc
);
214 // Allocate a separate statement handle for performing deletes
215 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
216 pDb
->DispAllErrors(henv
, hdbc
);
217 // Allocate a separate statement handle for performing updates
218 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
219 pDb
->DispAllErrors(henv
, hdbc
);
221 // Allocate a separate statement handle for internal use
222 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
223 pDb
->DispAllErrors(henv
, hdbc
);
225 // Set the cursor type for the statement handles
226 cursorType
= SQL_CURSOR_STATIC
;
228 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
230 // Check to see if cursor type is supported
231 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
232 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
234 // Datasource does not support static cursors. Driver
235 // will substitute a cursor type. Call SQLGetStmtOption()
236 // to determine which cursor type was selected.
237 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
238 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
239 #ifdef DBDEBUG_CONSOLE
240 cout
<< wxT("Static cursor changed to: ");
243 case SQL_CURSOR_FORWARD_ONLY
:
244 cout
<< wxT("Forward Only");
246 case SQL_CURSOR_STATIC
:
247 cout
<< wxT("Static");
249 case SQL_CURSOR_KEYSET_DRIVEN
:
250 cout
<< wxT("Keyset Driven");
252 case SQL_CURSOR_DYNAMIC
:
253 cout
<< wxT("Dynamic");
256 cout
<< endl
<< endl
;
259 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
261 // Force the use of a forward only cursor...
262 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
263 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
265 // Should never happen
266 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
273 pDb
->DispNextError();
274 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
277 #ifdef DBDEBUG_CONSOLE
279 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
284 // Set the cursor type for the INSERT statement handle
285 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
286 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
287 // Set the cursor type for the DELETE statement handle
288 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
289 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
290 // Set the cursor type for the UPDATE statement handle
291 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
292 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
295 // Make the default cursor the active cursor
296 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
297 wxASSERT(hstmtDefault
);
298 hstmt
= *hstmtDefault
;
302 } // wxDbTable::initialize()
305 void wxDbTable::cleanup()
310 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
317 TablesInUse
.DeleteContents(TRUE
);
321 pNode
= TablesInUse
.First();
322 while (pNode
&& !found
)
324 if (((wxTablesInUse
*)pNode
->Data())->tableID
== tableID
)
327 if (!TablesInUse
.DeleteNode(pNode
))
328 wxLogDebug (s
,wxT("Unable to delete node!"));
331 pNode
= pNode
->Next();
336 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
337 wxLogDebug (msg
,wxT("NOTICE..."));
342 // Decrement the wxDb table count
344 pDb
->decrementTableCount();
346 // Delete memory allocated for column definitions
350 // Free statement handles
356 ODBC 3.0 says to use this form
357 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
359 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
360 pDb
->DispAllErrors(henv
, hdbc
);
366 ODBC 3.0 says to use this form
367 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
369 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
370 pDb
->DispAllErrors(henv
, hdbc
);
376 ODBC 3.0 says to use this form
377 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
379 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
380 pDb
->DispAllErrors(henv
, hdbc
);
386 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
387 pDb
->DispAllErrors(henv
, hdbc
);
390 // Delete dynamically allocated cursors
392 DeleteCursor(hstmtDefault
);
395 DeleteCursor(hstmtCount
);
397 if (m_hstmtGridQuery
)
398 DeleteCursor(m_hstmtGridQuery
);
400 } // wxDbTable::cleanup()
403 /***************************** PRIVATE FUNCTIONS *****************************/
406 /********** wxDbTable::bindParams() **********/
407 bool wxDbTable::bindParams(bool forUpdate
)
409 wxASSERT(!queryOnly
);
414 UDWORD precision
= 0;
417 // Bind each column of the table that should be bound
418 // to a parameter marker
422 for (i
=0, colNo
=1; i
< noCols
; i
++)
426 if (!colDefs
[i
].Updateable
)
431 if (!colDefs
[i
].InsertAllowed
)
435 switch(colDefs
[i
].DbDataType
)
437 case DB_DATA_TYPE_VARCHAR
:
438 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
439 precision
= colDefs
[i
].SzDataObj
;
442 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
444 colDefs
[i
].CbValue
= SQL_NTS
;
446 case DB_DATA_TYPE_INTEGER
:
447 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
448 precision
= pDb
->GetTypeInfInteger().Precision
;
451 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
453 colDefs
[i
].CbValue
= 0;
455 case DB_DATA_TYPE_FLOAT
:
456 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
457 precision
= pDb
->GetTypeInfFloat().Precision
;
458 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
459 // SQL Sybase Anywhere v5.5 returned a negative number for the
460 // MaxScale. This caused ODBC to kick out an error on ibscale.
461 // I check for this here and set the scale = precision.
463 // scale = (short) precision;
465 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
467 colDefs
[i
].CbValue
= 0;
469 case DB_DATA_TYPE_DATE
:
470 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
471 precision
= pDb
->GetTypeInfDate().Precision
;
474 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
476 colDefs
[i
].CbValue
= 0;
478 case DB_DATA_TYPE_BLOB
:
479 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
483 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
485 colDefs
[i
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[i
].SzDataObj
);
490 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
491 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
492 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
494 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
499 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
500 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
501 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
503 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
508 // Completed successfully
511 } // wxDbTable::bindParams()
514 /********** wxDbTable::bindInsertParams() **********/
515 bool wxDbTable::bindInsertParams(void)
517 return bindParams(FALSE
);
518 } // wxDbTable::bindInsertParams()
521 /********** wxDbTable::bindUpdateParams() **********/
522 bool wxDbTable::bindUpdateParams(void)
524 return bindParams(TRUE
);
525 } // wxDbTable::bindUpdateParams()
528 /********** wxDbTable::bindCols() **********/
529 bool wxDbTable::bindCols(HSTMT cursor
)
531 // Bind each column of the table to a memory address for fetching data
533 for (i
= 0; i
< noCols
; i
++)
535 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
536 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
538 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
542 // Completed successfully
545 } // wxDbTable::bindCols()
548 /********** wxDbTable::getRec() **********/
549 bool wxDbTable::getRec(UWORD fetchType
)
553 if (!pDb
->FwdOnlyCursors())
555 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
559 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
560 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
562 if (retcode
== SQL_NO_DATA_FOUND
)
565 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
569 // Set the Null member variable to indicate the Null state
570 // of each column just read in.
572 for (i
= 0; i
< noCols
; i
++)
573 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
578 // Fetch the next record from the record set
579 retcode
= SQLFetch(hstmt
);
580 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
582 if (retcode
== SQL_NO_DATA_FOUND
)
585 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
589 // Set the Null member variable to indicate the Null state
590 // of each column just read in.
592 for (i
= 0; i
< noCols
; i
++)
593 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
597 // Completed successfully
600 } // wxDbTable::getRec()
603 /********** wxDbTable::execDelete() **********/
604 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
608 // Execute the DELETE statement
609 retcode
= SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
611 if (retcode
== SQL_SUCCESS
||
612 retcode
== SQL_NO_DATA_FOUND
||
613 retcode
== SQL_SUCCESS_WITH_INFO
)
615 // Record deleted successfully
619 // Problem deleting record
620 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
622 } // wxDbTable::execDelete()
625 /********** wxDbTable::execUpdate() **********/
626 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
630 // Execute the UPDATE statement
631 retcode
= SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
633 if (retcode
== SQL_SUCCESS
||
634 retcode
== SQL_NO_DATA_FOUND
||
635 retcode
== SQL_SUCCESS_WITH_INFO
)
637 // Record updated successfully
641 // Problem updating record
642 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
644 } // wxDbTable::execUpdate()
647 /********** wxDbTable::query() **********/
648 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
653 // The user may wish to select for update, but the DBMS may not be capable
654 selectForUpdate
= CanSelectForUpdate();
656 selectForUpdate
= FALSE
;
658 // Set the SQL SELECT string
659 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
660 { // so generate a select statement.
661 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
662 pDb
->WriteSqlLog(sqlStmt
);
665 // Make sure the cursor is closed first
666 if (!CloseCursor(hstmt
))
669 // Execute the SQL SELECT statement
671 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
672 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
673 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
675 // Completed successfully
678 } // wxDbTable::query()
681 /***************************** PUBLIC FUNCTIONS *****************************/
684 /********** wxDbTable::Open() **********/
685 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
695 // Calculate the maximum size of the concatenated
696 // keys for use with wxDbGrid
698 for (i
=0; i
< noCols
; i
++)
700 if (colDefs
[i
].KeyField
)
703 m_keysize
+= colDefs
[i
].SzDataObj
;
708 // Verify that the table exists in the database
709 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
711 s
= wxT("Table/view does not exist in the database");
712 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
713 s
+= wxT(", or you have no permissions.\n");
717 else if (checkPrivileges
)
719 // Verify the user has rights to access the table.
720 // Shortcut boolean evaluation to optimize out call to
723 // Unfortunately this optimization doesn't seem to be
725 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
726 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
727 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
734 if (!tablePath
.IsEmpty())
735 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
737 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
740 pDb
->LogError(p
.GetData());
745 // Bind the member variables for field exchange between
746 // the wxDbTable object and the ODBC record.
749 if (!bindInsertParams()) // Inserts
752 if (!bindUpdateParams()) // Updates
756 if (!bindCols(*hstmtDefault
)) // Selects
759 if (!bindCols(hstmtInternal
)) // Internal use only
763 * Do NOT bind the hstmtCount cursor!!!
766 // Build an insert statement using parameter markers
767 if (!queryOnly
&& noCols
> 0)
769 bool needComma
= FALSE
;
770 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
771 pDb
->SQLTableName(tableName
.c_str()).c_str());
772 for (i
= 0; i
< noCols
; i
++)
774 if (! colDefs
[i
].InsertAllowed
)
778 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
779 // sqlStmt += colDefs[i].ColName;
783 sqlStmt
+= wxT(") VALUES (");
785 int insertableCount
= 0;
787 for (i
= 0; i
< noCols
; i
++)
789 if (! colDefs
[i
].InsertAllowed
)
799 // Prepare the insert statement for execution
802 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
803 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
809 // Completed successfully
812 } // wxDbTable::Open()
815 /********** wxDbTable::Query() **********/
816 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
819 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
821 } // wxDbTable::Query()
824 /********** wxDbTable::QueryBySqlStmt() **********/
825 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
827 pDb
->WriteSqlLog(pSqlStmt
);
829 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
831 } // wxDbTable::QueryBySqlStmt()
834 /********** wxDbTable::QueryMatching() **********/
835 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
838 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
840 } // wxDbTable::QueryMatching()
843 /********** wxDbTable::QueryOnKeyFields() **********/
844 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
847 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
849 } // wxDbTable::QueryOnKeyFields()
852 /********** wxDbTable::GetPrev() **********/
853 bool wxDbTable::GetPrev(void)
855 if (pDb
->FwdOnlyCursors())
857 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
861 return(getRec(SQL_FETCH_PRIOR
));
863 } // wxDbTable::GetPrev()
866 /********** wxDbTable::operator-- **********/
867 bool wxDbTable::operator--(int)
869 if (pDb
->FwdOnlyCursors())
871 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
875 return(getRec(SQL_FETCH_PRIOR
));
877 } // wxDbTable::operator--
880 /********** wxDbTable::GetFirst() **********/
881 bool wxDbTable::GetFirst(void)
883 if (pDb
->FwdOnlyCursors())
885 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
889 return(getRec(SQL_FETCH_FIRST
));
891 } // wxDbTable::GetFirst()
894 /********** wxDbTable::GetLast() **********/
895 bool wxDbTable::GetLast(void)
897 if (pDb
->FwdOnlyCursors())
899 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
903 return(getRec(SQL_FETCH_LAST
));
905 } // wxDbTable::GetLast()
908 /********** wxDbTable::BuildDeleteStmt() **********/
909 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
911 wxASSERT(!queryOnly
);
915 wxString whereClause
;
919 // Handle the case of DeleteWhere() and the where clause is blank. It should
920 // delete all records from the database in this case.
921 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
923 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
924 pDb
->SQLTableName(tableName
.c_str()).c_str());
928 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
929 pDb
->SQLTableName(tableName
.c_str()).c_str());
931 // Append the WHERE clause to the SQL DELETE statement
934 case DB_DEL_KEYFIELDS
:
935 // If the datasource supports the ROWID column, build
936 // the where on ROWID for efficiency purposes.
937 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
941 wxChar rowid
[wxDB_ROWID_LEN
+1];
943 // Get the ROWID value. If not successful retreiving the ROWID,
944 // simply fall down through the code and build the WHERE clause
945 // based on the key fields.
946 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
948 pSqlStmt
+= wxT("ROWID = '");
950 pSqlStmt
+= wxT("'");
954 // Unable to delete by ROWID, so build a WHERE
955 // clause based on the keyfields.
956 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
957 pSqlStmt
+= whereClause
;
960 pSqlStmt
+= pWhereClause
;
962 case DB_DEL_MATCHING
:
963 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
964 pSqlStmt
+= whereClause
;
968 } // BuildDeleteStmt()
971 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
972 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
974 wxString tempSqlStmt
;
975 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
976 wxStrcpy(pSqlStmt
, tempSqlStmt
);
977 } // wxDbTable::BuildDeleteStmt()
980 /********** wxDbTable::BuildSelectStmt() **********/
981 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
983 wxString whereClause
;
986 // Build a select statement to query the database
987 pSqlStmt
= wxT("SELECT ");
989 // SELECT DISTINCT values only?
991 pSqlStmt
+= wxT("DISTINCT ");
993 // Was a FROM clause specified to join tables to the base table?
994 // Available for ::Query() only!!!
995 bool appendFromClause
= FALSE
;
996 #if wxODBC_BACKWARD_COMPATABILITY
997 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
998 appendFromClause
= TRUE
;
1000 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1001 appendFromClause
= TRUE
;
1004 // Add the column list
1006 for (i
= 0; i
< noCols
; i
++)
1008 // If joining tables, the base table column names must be qualified to avoid ambiguity
1009 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1011 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1012 // pSqlStmt += queryTableName;
1013 pSqlStmt
+= wxT(".");
1015 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1016 // pSqlStmt += colDefs[i].ColName;
1018 pSqlStmt
+= wxT(",");
1021 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1022 // the ROWID if querying distinct records. The rowid will always be unique.
1023 if (!distinct
&& CanUpdByROWID())
1025 // If joining tables, the base table column names must be qualified to avoid ambiguity
1026 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1028 pSqlStmt
+= wxT(",");
1029 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1030 // pSqlStmt += queryTableName;
1031 pSqlStmt
+= wxT(".ROWID");
1034 pSqlStmt
+= wxT(",ROWID");
1037 // Append the FROM tablename portion
1038 pSqlStmt
+= wxT(" FROM ");
1039 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1040 // pSqlStmt += queryTableName;
1042 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1043 // The HOLDLOCK keyword follows the table name in the from clause.
1044 // Each table in the from clause must specify HOLDLOCK or
1045 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1046 // is parsed but ignored in SYBASE Transact-SQL.
1047 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1048 pSqlStmt
+= wxT(" HOLDLOCK");
1050 if (appendFromClause
)
1053 // Append the WHERE clause. Either append the where clause for the class
1054 // or build a where clause. The typeOfSelect determines this.
1055 switch(typeOfSelect
)
1057 case DB_SELECT_WHERE
:
1058 #if wxODBC_BACKWARD_COMPATABILITY
1059 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1061 if (where
.Length()) // May not want a where clause!!!
1064 pSqlStmt
+= wxT(" WHERE ");
1068 case DB_SELECT_KEYFIELDS
:
1069 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1070 if (whereClause
.Length())
1072 pSqlStmt
+= wxT(" WHERE ");
1073 pSqlStmt
+= whereClause
;
1076 case DB_SELECT_MATCHING
:
1077 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1078 if (whereClause
.Length())
1080 pSqlStmt
+= wxT(" WHERE ");
1081 pSqlStmt
+= whereClause
;
1086 // Append the ORDER BY clause
1087 #if wxODBC_BACKWARD_COMPATABILITY
1088 if (orderBy
&& wxStrlen(orderBy
))
1090 if (orderBy
.Length())
1093 pSqlStmt
+= wxT(" ORDER BY ");
1094 pSqlStmt
+= orderBy
;
1097 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1098 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1099 // HOLDLOCK for Sybase.
1100 if (selectForUpdate
&& CanSelectForUpdate())
1101 pSqlStmt
+= wxT(" FOR UPDATE");
1103 } // wxDbTable::BuildSelectStmt()
1106 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1107 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1109 wxString tempSqlStmt
;
1110 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1111 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1112 } // wxDbTable::BuildSelectStmt()
1115 /********** wxDbTable::BuildUpdateStmt() **********/
1116 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1118 wxASSERT(!queryOnly
);
1122 wxString whereClause
;
1123 whereClause
.Empty();
1125 bool firstColumn
= TRUE
;
1127 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1128 pDb
->SQLTableName(tableName
.c_str()).c_str());
1130 // Append a list of columns to be updated
1132 for (i
= 0; i
< noCols
; i
++)
1134 // Only append Updateable columns
1135 if (colDefs
[i
].Updateable
)
1138 pSqlStmt
+= wxT(",");
1140 firstColumn
= FALSE
;
1142 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1143 // pSqlStmt += colDefs[i].ColName;
1144 pSqlStmt
+= wxT(" = ?");
1148 // Append the WHERE clause to the SQL UPDATE statement
1149 pSqlStmt
+= wxT(" WHERE ");
1152 case DB_UPD_KEYFIELDS
:
1153 // If the datasource supports the ROWID column, build
1154 // the where on ROWID for efficiency purposes.
1155 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1156 if (CanUpdByROWID())
1159 wxChar rowid
[wxDB_ROWID_LEN
+1];
1161 // Get the ROWID value. If not successful retreiving the ROWID,
1162 // simply fall down through the code and build the WHERE clause
1163 // based on the key fields.
1164 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1166 pSqlStmt
+= wxT("ROWID = '");
1168 pSqlStmt
+= wxT("'");
1172 // Unable to delete by ROWID, so build a WHERE
1173 // clause based on the keyfields.
1174 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1175 pSqlStmt
+= whereClause
;
1178 pSqlStmt
+= pWhereClause
;
1181 } // BuildUpdateStmt()
1184 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1185 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1187 wxString tempSqlStmt
;
1188 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1189 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1190 } // BuildUpdateStmt()
1193 /********** wxDbTable::BuildWhereClause() **********/
1194 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1195 const wxString
&qualTableName
, bool useLikeComparison
)
1197 * Note: BuildWhereClause() currently ignores timestamp columns.
1198 * They are not included as part of the where clause.
1201 bool moreThanOneColumn
= FALSE
;
1204 // Loop through the columns building a where clause as you go
1206 for (i
= 0; i
< noCols
; i
++)
1208 // Determine if this column should be included in the WHERE clause
1209 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1210 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(i
))))
1212 // Skip over timestamp columns
1213 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1215 // If there is more than 1 column, join them with the keyword "AND"
1216 if (moreThanOneColumn
)
1217 pWhereClause
+= wxT(" AND ");
1219 moreThanOneColumn
= TRUE
;
1220 // Concatenate where phrase for the column
1221 if (qualTableName
.Length())
1223 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1224 // pWhereClause += qualTableName;
1225 pWhereClause
+= wxT(".");
1227 pWhereClause
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1228 // pWhereClause += colDefs[i].ColName;
1229 if (useLikeComparison
&& (colDefs
[i
].SqlCtype
== SQL_C_CHAR
))
1230 pWhereClause
+= wxT(" LIKE ");
1232 pWhereClause
+= wxT(" = ");
1233 switch(colDefs
[i
].SqlCtype
)
1236 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1239 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[i
].PtrDataObj
));
1242 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[i
].PtrDataObj
));
1245 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1248 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1251 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1254 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1257 pWhereClause
+= colValue
;
1260 } // wxDbTable::BuildWhereClause()
1263 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1264 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1265 const wxString
&qualTableName
, bool useLikeComparison
)
1267 wxString tempSqlStmt
;
1268 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1269 wxStrcpy(pWhereClause
, tempSqlStmt
);
1270 } // wxDbTable::BuildWhereClause()
1273 /********** wxDbTable::GetRowNum() **********/
1274 UWORD
wxDbTable::GetRowNum(void)
1278 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1280 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1284 // Completed successfully
1285 return((UWORD
) rowNum
);
1287 } // wxDbTable::GetRowNum()
1290 /********** wxDbTable::CloseCursor() **********/
1291 bool wxDbTable::CloseCursor(HSTMT cursor
)
1293 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1294 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1296 // Completed successfully
1299 } // wxDbTable::CloseCursor()
1302 /********** wxDbTable::CreateTable() **********/
1303 bool wxDbTable::CreateTable(bool attemptDrop
)
1311 #ifdef DBDEBUG_CONSOLE
1312 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1316 if (attemptDrop
&& !DropTable())
1320 #ifdef DBDEBUG_CONSOLE
1321 for (i
= 0; i
< noCols
; i
++)
1323 // Exclude derived columns since they are NOT part of the base table
1324 if (colDefs
[i
].DerivedCol
)
1326 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1327 switch(colDefs
[i
].DbDataType
)
1329 case DB_DATA_TYPE_VARCHAR
:
1330 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1332 case DB_DATA_TYPE_INTEGER
:
1333 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1335 case DB_DATA_TYPE_FLOAT
:
1336 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1338 case DB_DATA_TYPE_DATE
:
1339 cout
<< pDb
->GetTypeInfDate().TypeName
;
1341 case DB_DATA_TYPE_BLOB
:
1342 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1349 // Build a CREATE TABLE string from the colDefs structure.
1350 bool needComma
= FALSE
;
1352 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1353 pDb
->SQLTableName(tableName
.c_str()).c_str());
1355 for (i
= 0; i
< noCols
; i
++)
1357 // Exclude derived columns since they are NOT part of the base table
1358 if (colDefs
[i
].DerivedCol
)
1362 sqlStmt
+= wxT(",");
1364 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1365 // sqlStmt += colDefs[i].ColName;
1366 sqlStmt
+= wxT(" ");
1368 switch(colDefs
[i
].DbDataType
)
1370 case DB_DATA_TYPE_VARCHAR
:
1371 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1373 case DB_DATA_TYPE_INTEGER
:
1374 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1376 case DB_DATA_TYPE_FLOAT
:
1377 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1379 case DB_DATA_TYPE_DATE
:
1380 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1382 case DB_DATA_TYPE_BLOB
:
1383 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1386 // For varchars, append the size of the string
1387 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1388 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= "text"))// ||
1389 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1392 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1396 if (pDb
->Dbms() == dbmsDB2
||
1397 pDb
->Dbms() == dbmsMY_SQL
||
1398 pDb
->Dbms() == dbmsSYBASE_ASE
||
1399 pDb
->Dbms() == dbmsINTERBASE
||
1400 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1402 if (colDefs
[i
].KeyField
)
1404 sqlStmt
+= wxT(" NOT NULL");
1410 // If there is a primary key defined, include it in the create statement
1411 for (i
= j
= 0; i
< noCols
; i
++)
1413 if (colDefs
[i
].KeyField
)
1419 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
1421 switch (pDb
->Dbms())
1425 case dbmsSYBASE_ASA
:
1426 case dbmsSYBASE_ASE
:
1429 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1430 sqlStmt
+= wxT(",PRIMARY KEY (");
1435 sqlStmt
+= wxT(",CONSTRAINT ");
1436 // DB2 is limited to 18 characters for index names
1437 if (pDb
->Dbms() == dbmsDB2
)
1439 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."));
1440 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1441 // sqlStmt += tableName.substr(0, 13);
1444 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1445 // sqlStmt += tableName;
1447 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1452 // List column name(s) of column(s) comprising the primary key
1453 for (i
= j
= 0; i
< noCols
; i
++)
1455 if (colDefs
[i
].KeyField
)
1457 if (j
++) // Multi part key, comma separate names
1458 sqlStmt
+= wxT(",");
1459 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1461 if (pDb
->Dbms() == dbmsMY_SQL
&&
1462 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1465 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1470 sqlStmt
+= wxT(")");
1472 if (pDb
->Dbms() == dbmsINFORMIX
||
1473 pDb
->Dbms() == dbmsSYBASE_ASA
||
1474 pDb
->Dbms() == dbmsSYBASE_ASE
)
1476 sqlStmt
+= wxT(" CONSTRAINT ");
1477 sqlStmt
+= pDb
->SQLTableName(tableName
);
1478 // sqlStmt += tableName;
1479 sqlStmt
+= wxT("_PIDX");
1482 // Append the closing parentheses for the create table statement
1483 sqlStmt
+= wxT(")");
1485 pDb
->WriteSqlLog(sqlStmt
);
1487 #ifdef DBDEBUG_CONSOLE
1488 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1491 // Execute the CREATE TABLE statement
1492 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1493 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1495 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1496 pDb
->RollbackTrans();
1501 // Commit the transaction and close the cursor
1502 if (!pDb
->CommitTrans())
1504 if (!CloseCursor(hstmt
))
1507 // Database table created successfully
1510 } // wxDbTable::CreateTable()
1513 /********** wxDbTable::DropTable() **********/
1514 bool wxDbTable::DropTable()
1516 // NOTE: This function returns TRUE if the Table does not exist, but
1517 // only for identified databases. Code will need to be added
1518 // below for any other databases when those databases are defined
1519 // to handle this situation consistently
1523 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1524 pDb
->SQLTableName(tableName
.c_str()).c_str());
1526 pDb
->WriteSqlLog(sqlStmt
);
1528 #ifdef DBDEBUG_CONSOLE
1529 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1532 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1533 if (retcode
!= SQL_SUCCESS
)
1535 // Check for "Base table not found" error and ignore
1536 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1537 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1538 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1540 // Check for product specific error codes
1541 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1542 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1543 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1544 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1546 pDb
->DispNextError();
1547 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1548 pDb
->RollbackTrans();
1549 // CloseCursor(hstmt);
1555 // Commit the transaction and close the cursor
1556 if (! pDb
->CommitTrans())
1558 if (! CloseCursor(hstmt
))
1562 } // wxDbTable::DropTable()
1565 /********** wxDbTable::CreateIndex() **********/
1566 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1567 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1571 // Drop the index first
1572 if (attemptDrop
&& !DropIndex(idxName
))
1575 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1576 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1577 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1578 // table was created, then months later you determine that an additional index while
1579 // give better performance, so you want to add an index).
1581 // The following block of code will modify the column definition to make the column be
1582 // defined with the "NOT NULL" qualifier.
1583 if (pDb
->Dbms() == dbmsMY_SQL
)
1588 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1592 // Find the column definition that has the ColName that matches the
1593 // index column name. We need to do this to get the DB_DATA_TYPE of
1594 // the index column, as MySQL's syntax for the ALTER column requires
1596 while (!found
&& (j
< this->noCols
))
1598 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1606 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1607 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1612 wxODBC_ERRORS retcode
;
1613 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1614 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1615 // This line is just here for debug checking of the value
1616 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1626 pDb
->RollbackTrans();
1631 // Build a CREATE INDEX statement
1632 sqlStmt
= wxT("CREATE ");
1634 sqlStmt
+= wxT("UNIQUE ");
1636 sqlStmt
+= wxT("INDEX ");
1637 sqlStmt
+= pDb
->SQLTableName(idxName
);
1638 sqlStmt
+= wxT(" ON ");
1640 sqlStmt
+= pDb
->SQLTableName(tableName
);
1641 // sqlStmt += tableName;
1642 sqlStmt
+= wxT(" (");
1644 // Append list of columns making up index
1646 for (i
= 0; i
< noIdxCols
; i
++)
1648 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1649 // sqlStmt += pIdxDefs[i].ColName;
1651 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1652 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (strncmp(pDb
->dbInf
.dbmsVer
,"07",2)==0)) &&
1653 !(pDb
->Dbms() == dbmsPOSTGRES
))
1655 if (pIdxDefs
[i
].Ascending
)
1656 sqlStmt
+= wxT(" ASC");
1658 sqlStmt
+= wxT(" DESC");
1661 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, "Datasource does not support DESCending index columns");
1663 if ((i
+ 1) < noIdxCols
)
1664 sqlStmt
+= wxT(",");
1667 // Append closing parentheses
1668 sqlStmt
+= wxT(")");
1670 pDb
->WriteSqlLog(sqlStmt
);
1672 #ifdef DBDEBUG_CONSOLE
1673 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1676 // Execute the CREATE INDEX statement
1677 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1679 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1680 pDb
->RollbackTrans();
1685 // Commit the transaction and close the cursor
1686 if (! pDb
->CommitTrans())
1688 if (! CloseCursor(hstmt
))
1691 // Index Created Successfully
1694 } // wxDbTable::CreateIndex()
1697 /********** wxDbTable::DropIndex() **********/
1698 bool wxDbTable::DropIndex(const wxString
&idxName
)
1700 // NOTE: This function returns TRUE if the Index does not exist, but
1701 // only for identified databases. Code will need to be added
1702 // below for any other databases when those databases are defined
1703 // to handle this situation consistently
1707 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1708 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1709 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1710 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1711 pDb
->SQLTableName(tableName
.c_str()).c_str());
1712 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1713 (pDb
->Dbms() == dbmsSYBASE_ASE
))
1714 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1715 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1716 pDb
->SQLTableName(idxName
.c_str()).c_str());
1718 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1719 pDb
->SQLTableName(idxName
.c_str()).c_str());
1721 pDb
->WriteSqlLog(sqlStmt
);
1723 #ifdef DBDEBUG_CONSOLE
1724 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1727 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1729 // Check for "Index not found" error and ignore
1730 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1731 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1733 // Check for product specific error codes
1734 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1735 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1736 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1737 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1738 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1739 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1740 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1743 pDb
->DispNextError();
1744 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1745 pDb
->RollbackTrans();
1752 // Commit the transaction and close the cursor
1753 if (! pDb
->CommitTrans())
1755 if (! CloseCursor(hstmt
))
1759 } // wxDbTable::DropIndex()
1762 /********** wxDbTable::SetOrderByColNums() **********/
1763 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1765 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1771 va_start(argptr
, first
); /* Initialize variable arguments. */
1772 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1774 // Make sure the passed in column number
1775 // is within the valid range of columns
1777 // Valid columns are 0 thru noCols-1
1778 if (colNo
>= noCols
|| colNo
< 0)
1785 tempStr
+= wxT(",");
1787 tempStr
+= colDefs
[colNo
].ColName
;
1788 colNo
= va_arg (argptr
, int);
1790 va_end (argptr
); /* Reset variable arguments. */
1792 SetOrderByClause(tempStr
);
1795 } // wxDbTable::SetOrderByColNums()
1798 /********** wxDbTable::Insert() **********/
1799 int wxDbTable::Insert(void)
1801 wxASSERT(!queryOnly
);
1802 if (queryOnly
|| !insertable
)
1807 // Insert the record by executing the already prepared insert statement
1809 retcode
=SQLExecute(hstmtInsert
);
1810 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1812 // Check to see if integrity constraint was violated
1813 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1814 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1815 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1818 pDb
->DispNextError();
1819 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1824 // Record inserted into the datasource successfully
1827 } // wxDbTable::Insert()
1830 /********** wxDbTable::Update() **********/
1831 bool wxDbTable::Update(void)
1833 wxASSERT(!queryOnly
);
1839 // Build the SQL UPDATE statement
1840 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1842 pDb
->WriteSqlLog(sqlStmt
);
1844 #ifdef DBDEBUG_CONSOLE
1845 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1848 // Execute the SQL UPDATE statement
1849 return(execUpdate(sqlStmt
));
1851 } // wxDbTable::Update()
1854 /********** wxDbTable::Update(pSqlStmt) **********/
1855 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1857 wxASSERT(!queryOnly
);
1861 pDb
->WriteSqlLog(pSqlStmt
);
1863 return(execUpdate(pSqlStmt
));
1865 } // wxDbTable::Update(pSqlStmt)
1868 /********** wxDbTable::UpdateWhere() **********/
1869 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1871 wxASSERT(!queryOnly
);
1877 // Build the SQL UPDATE statement
1878 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1880 pDb
->WriteSqlLog(sqlStmt
);
1882 #ifdef DBDEBUG_CONSOLE
1883 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1886 // Execute the SQL UPDATE statement
1887 return(execUpdate(sqlStmt
));
1889 } // wxDbTable::UpdateWhere()
1892 /********** wxDbTable::Delete() **********/
1893 bool wxDbTable::Delete(void)
1895 wxASSERT(!queryOnly
);
1902 // Build the SQL DELETE statement
1903 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1905 pDb
->WriteSqlLog(sqlStmt
);
1907 // Execute the SQL DELETE statement
1908 return(execDelete(sqlStmt
));
1910 } // wxDbTable::Delete()
1913 /********** wxDbTable::DeleteWhere() **********/
1914 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
1916 wxASSERT(!queryOnly
);
1923 // Build the SQL DELETE statement
1924 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1926 pDb
->WriteSqlLog(sqlStmt
);
1928 // Execute the SQL DELETE statement
1929 return(execDelete(sqlStmt
));
1931 } // wxDbTable::DeleteWhere()
1934 /********** wxDbTable::DeleteMatching() **********/
1935 bool wxDbTable::DeleteMatching(void)
1937 wxASSERT(!queryOnly
);
1944 // Build the SQL DELETE statement
1945 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1947 pDb
->WriteSqlLog(sqlStmt
);
1949 // Execute the SQL DELETE statement
1950 return(execDelete(sqlStmt
));
1952 } // wxDbTable::DeleteMatching()
1955 /********** wxDbTable::IsColNull() **********/
1956 bool wxDbTable::IsColNull(UWORD colNo
) const
1959 This logic is just not right. It would indicate TRUE
1960 if a numeric field were set to a value of 0.
1962 switch(colDefs[colNo].SqlCtype)
1965 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
1967 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
1969 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
1971 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1973 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1975 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
1977 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
1978 case SQL_C_TIMESTAMP:
1979 TIMESTAMP_STRUCT *pDt;
1980 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
1981 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
1989 return (colDefs
[colNo
].Null
);
1990 } // wxDbTable::IsColNull()
1993 /********** wxDbTable::CanSelectForUpdate() **********/
1994 bool wxDbTable::CanSelectForUpdate(void)
1999 if (pDb
->Dbms() == dbmsMY_SQL
)
2002 if ((pDb
->Dbms() == dbmsORACLE
) ||
2003 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2008 } // wxDbTable::CanSelectForUpdate()
2011 /********** wxDbTable::CanUpdByROWID() **********/
2012 bool wxDbTable::CanUpdByROWID(void)
2015 * NOTE: Returning FALSE for now until this can be debugged,
2016 * as the ROWID is not getting updated correctly
2020 if (pDb->Dbms() == dbmsORACLE)
2025 } // wxDbTable::CanUpdByROWID()
2028 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2029 bool wxDbTable::IsCursorClosedOnCommit(void)
2031 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2036 } // wxDbTable::IsCursorClosedOnCommit()
2040 /********** wxDbTable::ClearMemberVar() **********/
2041 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2043 wxASSERT(colNo
< noCols
);
2045 switch(colDefs
[colNo
].SqlCtype
)
2048 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2051 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2054 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2057 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2060 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2063 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2066 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2068 case SQL_C_TIMESTAMP
:
2069 TIMESTAMP_STRUCT
*pDt
;
2070 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2083 } // wxDbTable::ClearMemberVar()
2086 /********** wxDbTable::ClearMemberVars() **********/
2087 void wxDbTable::ClearMemberVars(bool setToNull
)
2091 // Loop through the columns setting each member variable to zero
2092 for (i
=0; i
< noCols
; i
++)
2093 ClearMemberVar(i
,setToNull
);
2095 } // wxDbTable::ClearMemberVars()
2098 /********** wxDbTable::SetQueryTimeout() **********/
2099 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2101 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2102 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2103 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2104 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2105 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2106 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2107 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2108 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2110 // Completed Successfully
2113 } // wxDbTable::SetQueryTimeout()
2116 /********** wxDbTable::SetColDefs() **********/
2117 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2118 SWORD cType
, int size
, bool keyField
, bool upd
,
2119 bool insAllow
, bool derivedCol
)
2121 if (!colDefs
) // May happen if the database connection fails
2124 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2126 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2127 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2131 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2132 fieldName
.c_str(),colDefs
[index
].ColName
);
2134 #endif // __WXDEBUG__
2137 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2139 colDefs
[index
].DbDataType
= dataType
;
2140 colDefs
[index
].PtrDataObj
= pData
;
2141 colDefs
[index
].SqlCtype
= cType
;
2142 colDefs
[index
].SzDataObj
= size
;
2143 colDefs
[index
].KeyField
= keyField
;
2144 colDefs
[index
].DerivedCol
= derivedCol
;
2145 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2148 colDefs
[index
].Updateable
= FALSE
;
2149 colDefs
[index
].InsertAllowed
= FALSE
;
2153 colDefs
[index
].Updateable
= upd
;
2154 colDefs
[index
].InsertAllowed
= insAllow
;
2157 colDefs
[index
].Null
= FALSE
;
2159 } // wxDbTable::SetColDefs()
2162 /********** wxDbTable::SetColDefs() **********/
2163 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2166 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2172 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2174 for (index
= 0; index
< numCols
; index
++)
2176 // Process the fields
2177 switch (pColInfs
[index
].dbDataType
)
2179 case DB_DATA_TYPE_VARCHAR
:
2180 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2181 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2182 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2184 case DB_DATA_TYPE_INTEGER
:
2185 // Can be long or short
2186 if (pColInfs
[index
].bufferLength
== sizeof(long))
2188 pColDataPtrs
[index
].PtrDataObj
= new long;
2189 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2190 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2194 pColDataPtrs
[index
].PtrDataObj
= new short;
2195 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2196 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2199 case DB_DATA_TYPE_FLOAT
:
2200 // Can be float or double
2201 if (pColInfs
[index
].bufferLength
== sizeof(float))
2203 pColDataPtrs
[index
].PtrDataObj
= new float;
2204 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2205 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2209 pColDataPtrs
[index
].PtrDataObj
= new double;
2210 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2211 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2214 case DB_DATA_TYPE_DATE
:
2215 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2216 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2217 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2219 case DB_DATA_TYPE_BLOB
:
2220 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2221 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2222 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2223 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2226 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2227 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2230 // Unable to build all the column definitions, as either one of
2231 // the calls to "new" failed above, or there was a BLOB field
2232 // to have a column definition for. If BLOBs are to be used,
2233 // the other form of ::SetColDefs() must be used, as it is impossible
2234 // to know the maximum size to create the PtrDataObj to be.
2235 delete [] pColDataPtrs
;
2241 return (pColDataPtrs
);
2243 } // wxDbTable::SetColDefs()
2246 /********** wxDbTable::SetCursor() **********/
2247 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2249 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2250 hstmt
= *hstmtDefault
;
2252 hstmt
= *hstmtActivate
;
2254 } // wxDbTable::SetCursor()
2257 /********** wxDbTable::Count(const wxString &) **********/
2258 ULONG
wxDbTable::Count(const wxString
&args
)
2264 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2265 sqlStmt
= wxT("SELECT COUNT(");
2267 sqlStmt
+= wxT(") FROM ");
2268 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2269 // sqlStmt += queryTableName;
2270 #if wxODBC_BACKWARD_COMPATABILITY
2271 if (from
&& wxStrlen(from
))
2277 // Add the where clause if one is provided
2278 #if wxODBC_BACKWARD_COMPATABILITY
2279 if (where
&& wxStrlen(where
))
2284 sqlStmt
+= wxT(" WHERE ");
2288 pDb
->WriteSqlLog(sqlStmt
);
2290 // Initialize the Count cursor if it's not already initialized
2293 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2294 wxASSERT(hstmtCount
);
2299 // Execute the SQL statement
2300 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2302 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2307 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2309 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2313 // Obtain the result
2314 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2316 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2321 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2322 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2324 // Return the record count
2327 } // wxDbTable::Count()
2330 /********** wxDbTable::Refresh() **********/
2331 bool wxDbTable::Refresh(void)
2335 // Switch to the internal cursor so any active cursors are not corrupted
2336 HSTMT currCursor
= GetCursor();
2337 hstmt
= hstmtInternal
;
2338 #if wxODBC_BACKWARD_COMPATABILITY
2339 // Save the where and order by clauses
2340 char *saveWhere
= where
;
2341 char *saveOrderBy
= orderBy
;
2343 wxString saveWhere
= where
;
2344 wxString saveOrderBy
= orderBy
;
2346 // Build a where clause to refetch the record with. Try and use the
2347 // ROWID if it's available, ow use the key fields.
2348 wxString whereClause
;
2349 whereClause
.Empty();
2351 if (CanUpdByROWID())
2354 wxChar rowid
[wxDB_ROWID_LEN
+1];
2356 // Get the ROWID value. If not successful retreiving the ROWID,
2357 // simply fall down through the code and build the WHERE clause
2358 // based on the key fields.
2359 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2361 whereClause
+= pDb
->SQLTableName(queryTableName
);
2362 // whereClause += queryTableName;
2363 whereClause
+= wxT(".ROWID = '");
2364 whereClause
+= rowid
;
2365 whereClause
+= wxT("'");
2369 // If unable to use the ROWID, build a where clause from the keyfields
2370 if (wxStrlen(whereClause
) == 0)
2371 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2373 // Requery the record
2374 where
= whereClause
;
2379 if (result
&& !GetNext())
2382 // Switch back to original cursor
2383 SetCursor(&currCursor
);
2385 // Free the internal cursor
2386 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2387 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2389 // Restore the original where and order by clauses
2391 orderBy
= saveOrderBy
;
2395 } // wxDbTable::Refresh()
2398 /********** wxDbTable::SetColNull() **********/
2399 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2403 colDefs
[colNo
].Null
= set
;
2404 if (set
) // Blank out the values in the member variable
2405 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2411 } // wxDbTable::SetColNull()
2414 /********** wxDbTable::SetColNull() **********/
2415 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2418 for (i
= 0; i
< noCols
; i
++)
2420 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2426 colDefs
[i
].Null
= set
;
2427 if (set
) // Blank out the values in the member variable
2428 ClearMemberVar(i
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2434 } // wxDbTable::SetColNull()
2437 /********** wxDbTable::GetNewCursor() **********/
2438 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2440 HSTMT
*newHSTMT
= new HSTMT
;
2445 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2447 pDb
->DispAllErrors(henv
, hdbc
);
2452 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2454 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2461 if (!bindCols(*newHSTMT
))
2469 SetCursor(newHSTMT
);
2473 } // wxDbTable::GetNewCursor()
2476 /********** wxDbTable::DeleteCursor() **********/
2477 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2481 if (!hstmtDel
) // Cursor already deleted
2485 ODBC 3.0 says to use this form
2486 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2489 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2491 pDb
->DispAllErrors(henv
, hdbc
);
2499 } // wxDbTable::DeleteCursor()
2501 //////////////////////////////////////////////////////////////
2502 // wxDbGrid support functions
2503 //////////////////////////////////////////////////////////////
2505 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2507 if (!m_hstmtGridQuery
)
2509 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2510 if (!bindCols(*m_hstmtGridQuery
))
2514 m_rowmode
= rowmode
;
2517 case WX_ROW_MODE_QUERY
:
2518 SetCursor(m_hstmtGridQuery
);
2520 case WX_ROW_MODE_INDIVIDUAL
:
2521 SetCursor(hstmtDefault
);
2526 } // wxDbTable::SetRowMode()
2529 wxVariant
wxDbTable::GetCol(const int colNo
) const
2532 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2534 switch (colDefs
[colNo
].SqlCtype
)
2538 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2542 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2546 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2549 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2552 val
= (long)(*(char *)(colDefs
[colNo
].PtrDataObj
));
2554 case SQL_C_UTINYINT
:
2555 val
= (long)(*(unsigned char *)(colDefs
[colNo
].PtrDataObj
));
2558 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2561 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2564 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2566 case SQL_C_TIMESTAMP
:
2567 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2570 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2577 } // wxDbTable::GetCol()
2580 void csstrncpyt(char *s
, const char *t
, int n
)
2582 while ((*s
++ = *t
++) && --n
)
2588 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2590 //FIXME: Add proper wxDateTime support to wxVariant..
2593 SetColNull(colNo
, val
.IsNull());
2597 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2598 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2599 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2601 //Returns null if invalid!
2602 if (!dateval
.ParseDate(val
.GetString()))
2603 SetColNull(colNo
, TRUE
);
2606 switch (colDefs
[colNo
].SqlCtype
)
2610 csstrncpyt((char *)(colDefs
[colNo
].PtrDataObj
),
2611 val
.GetString().c_str(),
2612 colDefs
[colNo
].SzDataObj
-1);
2616 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2620 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2623 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2626 *(char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2628 case SQL_C_UTINYINT
:
2629 *(unsigned char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2632 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2634 //FIXME: Add proper wxDateTime support to wxVariant..
2637 DATE_STRUCT
*dataptr
=
2638 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2640 dataptr
->year
= dateval
.GetYear();
2641 dataptr
->month
= dateval
.GetMonth()+1;
2642 dataptr
->day
= dateval
.GetDay();
2647 TIME_STRUCT
*dataptr
=
2648 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2650 dataptr
->hour
= dateval
.GetHour();
2651 dataptr
->minute
= dateval
.GetMinute();
2652 dataptr
->second
= dateval
.GetSecond();
2655 case SQL_C_TIMESTAMP
:
2657 TIMESTAMP_STRUCT
*dataptr
=
2658 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2659 dataptr
->year
= dateval
.GetYear();
2660 dataptr
->month
= dateval
.GetMonth()+1;
2661 dataptr
->day
= dateval
.GetDay();
2663 dataptr
->hour
= dateval
.GetHour();
2664 dataptr
->minute
= dateval
.GetMinute();
2665 dataptr
->second
= dateval
.GetSecond();
2669 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2674 } // if (!val.IsNull())
2675 } // wxDbTable::SetCol()
2678 GenericKey
wxDbTable::GetKey()
2683 blk
= malloc(m_keysize
);
2684 blkptr
= (wxChar
*) blk
;
2687 for (i
=0; i
< noCols
; i
++)
2689 if (colDefs
[i
].KeyField
)
2691 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2692 blkptr
+= colDefs
[i
].SzDataObj
;
2696 GenericKey k
= GenericKey(blk
, m_keysize
);
2700 } // wxDbTable::GetKey()
2703 void wxDbTable::SetKey(const GenericKey
& k
)
2709 blkptr
= (wxChar
*)blk
;
2712 for (i
=0; i
< noCols
; i
++)
2714 if (colDefs
[i
].KeyField
)
2716 SetColNull(i
, FALSE
);
2717 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2718 blkptr
+= colDefs
[i
].SzDataObj
;
2721 } // wxDbTable::SetKey()
2724 #endif // wxUSE_ODBC