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 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1391 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1395 if (pDb
->Dbms() == dbmsDB2
||
1396 pDb
->Dbms() == dbmsMY_SQL
||
1397 pDb
->Dbms() == dbmsSYBASE_ASE
||
1398 pDb
->Dbms() == dbmsINTERBASE
||
1399 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1401 if (colDefs
[i
].KeyField
)
1403 sqlStmt
+= wxT(" NOT NULL");
1409 // If there is a primary key defined, include it in the create statement
1410 for (i
= j
= 0; i
< noCols
; i
++)
1412 if (colDefs
[i
].KeyField
)
1418 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
1420 switch (pDb
->Dbms())
1424 case dbmsSYBASE_ASA
:
1425 case dbmsSYBASE_ASE
:
1428 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1429 sqlStmt
+= wxT(",PRIMARY KEY (");
1434 sqlStmt
+= wxT(",CONSTRAINT ");
1435 // DB2 is limited to 18 characters for index names
1436 if (pDb
->Dbms() == dbmsDB2
)
1438 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."));
1439 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1440 // sqlStmt += tableName.substr(0, 13);
1443 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1444 // sqlStmt += tableName;
1446 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1451 // List column name(s) of column(s) comprising the primary key
1452 for (i
= j
= 0; i
< noCols
; i
++)
1454 if (colDefs
[i
].KeyField
)
1456 if (j
++) // Multi part key, comma separate names
1457 sqlStmt
+= wxT(",");
1458 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1459 // sqlStmt += colDefs[i].ColName;
1462 sqlStmt
+= wxT(")");
1464 if (pDb
->Dbms() == dbmsINFORMIX
||
1465 pDb
->Dbms() == dbmsSYBASE_ASA
||
1466 pDb
->Dbms() == dbmsSYBASE_ASE
)
1468 sqlStmt
+= wxT(" CONSTRAINT ");
1469 sqlStmt
+= pDb
->SQLTableName(tableName
);
1470 // sqlStmt += tableName;
1471 sqlStmt
+= wxT("_PIDX");
1474 // Append the closing parentheses for the create table statement
1475 sqlStmt
+= wxT(")");
1477 pDb
->WriteSqlLog(sqlStmt
);
1479 #ifdef DBDEBUG_CONSOLE
1480 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1483 // Execute the CREATE TABLE statement
1484 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1485 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1487 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1488 pDb
->RollbackTrans();
1493 // Commit the transaction and close the cursor
1494 if (!pDb
->CommitTrans())
1496 if (!CloseCursor(hstmt
))
1499 // Database table created successfully
1502 } // wxDbTable::CreateTable()
1505 /********** wxDbTable::DropTable() **********/
1506 bool wxDbTable::DropTable()
1508 // NOTE: This function returns TRUE if the Table does not exist, but
1509 // only for identified databases. Code will need to be added
1510 // below for any other databases when those databases are defined
1511 // to handle this situation consistently
1515 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1516 pDb
->SQLTableName(tableName
.c_str()).c_str());
1518 pDb
->WriteSqlLog(sqlStmt
);
1520 #ifdef DBDEBUG_CONSOLE
1521 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1524 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1525 if (retcode
!= SQL_SUCCESS
)
1527 // Check for "Base table not found" error and ignore
1528 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1529 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1530 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1532 // Check for product specific error codes
1533 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1534 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1535 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1536 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1538 pDb
->DispNextError();
1539 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1540 pDb
->RollbackTrans();
1541 // CloseCursor(hstmt);
1547 // Commit the transaction and close the cursor
1548 if (! pDb
->CommitTrans())
1550 if (! CloseCursor(hstmt
))
1554 } // wxDbTable::DropTable()
1557 /********** wxDbTable::CreateIndex() **********/
1558 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1559 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1563 // Drop the index first
1564 if (attemptDrop
&& !DropIndex(idxName
))
1567 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1568 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1569 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1570 // table was created, then months later you determine that an additional index while
1571 // give better performance, so you want to add an index).
1573 // The following block of code will modify the column definition to make the column be
1574 // defined with the "NOT NULL" qualifier.
1575 if (pDb
->Dbms() == dbmsMY_SQL
)
1580 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1584 // Find the column definition that has the ColName that matches the
1585 // index column name. We need to do this to get the DB_DATA_TYPE of
1586 // the index column, as MySQL's syntax for the ALTER column requires
1588 while (!found
&& (j
< this->noCols
))
1590 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1598 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1599 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1604 wxODBC_ERRORS retcode
;
1605 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1606 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1607 // This line is just here for debug checking of the value
1608 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1618 pDb
->RollbackTrans();
1623 // Build a CREATE INDEX statement
1624 sqlStmt
= wxT("CREATE ");
1626 sqlStmt
+= wxT("UNIQUE ");
1628 sqlStmt
+= wxT("INDEX ");
1629 sqlStmt
+= pDb
->SQLTableName(idxName
);
1630 sqlStmt
+= wxT(" ON ");
1632 sqlStmt
+= pDb
->SQLTableName(tableName
);
1633 // sqlStmt += tableName;
1634 sqlStmt
+= wxT(" (");
1636 // Append list of columns making up index
1638 for (i
= 0; i
< noIdxCols
; i
++)
1640 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1641 // sqlStmt += pIdxDefs[i].ColName;
1643 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1644 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (strncmp(pDb
->dbInf
.dbmsVer
,"07",2)==0)) &&
1645 !(pDb
->Dbms() == dbmsPOSTGRES
))
1647 if (pIdxDefs
[i
].Ascending
)
1648 sqlStmt
+= wxT(" ASC");
1650 sqlStmt
+= wxT(" DESC");
1653 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, "Datasource does not support DESCending index columns");
1655 if ((i
+ 1) < noIdxCols
)
1656 sqlStmt
+= wxT(",");
1659 // Append closing parentheses
1660 sqlStmt
+= wxT(")");
1662 pDb
->WriteSqlLog(sqlStmt
);
1664 #ifdef DBDEBUG_CONSOLE
1665 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1668 // Execute the CREATE INDEX statement
1669 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1671 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1672 pDb
->RollbackTrans();
1677 // Commit the transaction and close the cursor
1678 if (! pDb
->CommitTrans())
1680 if (! CloseCursor(hstmt
))
1683 // Index Created Successfully
1686 } // wxDbTable::CreateIndex()
1689 /********** wxDbTable::DropIndex() **********/
1690 bool wxDbTable::DropIndex(const wxString
&idxName
)
1692 // NOTE: This function returns TRUE if the Index does not exist, but
1693 // only for identified databases. Code will need to be added
1694 // below for any other databases when those databases are defined
1695 // to handle this situation consistently
1699 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1700 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1701 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1702 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1703 pDb
->SQLTableName(tableName
.c_str()).c_str());
1704 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1705 (pDb
->Dbms() == dbmsSYBASE_ASE
))
1706 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1707 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1708 pDb
->SQLTableName(idxName
.c_str()).c_str());
1710 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1711 pDb
->SQLTableName(idxName
.c_str()).c_str());
1713 pDb
->WriteSqlLog(sqlStmt
);
1715 #ifdef DBDEBUG_CONSOLE
1716 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1719 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1721 // Check for "Index not found" error and ignore
1722 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1723 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1725 // Check for product specific error codes
1726 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1727 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1728 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1729 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1730 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1731 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1732 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1735 pDb
->DispNextError();
1736 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1737 pDb
->RollbackTrans();
1744 // Commit the transaction and close the cursor
1745 if (! pDb
->CommitTrans())
1747 if (! CloseCursor(hstmt
))
1751 } // wxDbTable::DropIndex()
1754 /********** wxDbTable::SetOrderByColNums() **********/
1755 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1757 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1763 va_start(argptr
, first
); /* Initialize variable arguments. */
1764 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1766 // Make sure the passed in column number
1767 // is within the valid range of columns
1769 // Valid columns are 0 thru noCols-1
1770 if (colNo
>= noCols
|| colNo
< 0)
1777 tempStr
+= wxT(",");
1779 tempStr
+= colDefs
[colNo
].ColName
;
1780 colNo
= va_arg (argptr
, int);
1782 va_end (argptr
); /* Reset variable arguments. */
1784 SetOrderByClause(tempStr
);
1787 } // wxDbTable::SetOrderByColNums()
1790 /********** wxDbTable::Insert() **********/
1791 int wxDbTable::Insert(void)
1793 wxASSERT(!queryOnly
);
1794 if (queryOnly
|| !insertable
)
1799 // Insert the record by executing the already prepared insert statement
1801 retcode
=SQLExecute(hstmtInsert
);
1802 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1804 // Check to see if integrity constraint was violated
1805 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1806 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1807 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1810 pDb
->DispNextError();
1811 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1816 // Record inserted into the datasource successfully
1819 } // wxDbTable::Insert()
1822 /********** wxDbTable::Update() **********/
1823 bool wxDbTable::Update(void)
1825 wxASSERT(!queryOnly
);
1831 // Build the SQL UPDATE statement
1832 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1834 pDb
->WriteSqlLog(sqlStmt
);
1836 #ifdef DBDEBUG_CONSOLE
1837 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1840 // Execute the SQL UPDATE statement
1841 return(execUpdate(sqlStmt
));
1843 } // wxDbTable::Update()
1846 /********** wxDbTable::Update(pSqlStmt) **********/
1847 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1849 wxASSERT(!queryOnly
);
1853 pDb
->WriteSqlLog(pSqlStmt
);
1855 return(execUpdate(pSqlStmt
));
1857 } // wxDbTable::Update(pSqlStmt)
1860 /********** wxDbTable::UpdateWhere() **********/
1861 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1863 wxASSERT(!queryOnly
);
1869 // Build the SQL UPDATE statement
1870 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1872 pDb
->WriteSqlLog(sqlStmt
);
1874 #ifdef DBDEBUG_CONSOLE
1875 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1878 // Execute the SQL UPDATE statement
1879 return(execUpdate(sqlStmt
));
1881 } // wxDbTable::UpdateWhere()
1884 /********** wxDbTable::Delete() **********/
1885 bool wxDbTable::Delete(void)
1887 wxASSERT(!queryOnly
);
1894 // Build the SQL DELETE statement
1895 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1897 pDb
->WriteSqlLog(sqlStmt
);
1899 // Execute the SQL DELETE statement
1900 return(execDelete(sqlStmt
));
1902 } // wxDbTable::Delete()
1905 /********** wxDbTable::DeleteWhere() **********/
1906 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
1908 wxASSERT(!queryOnly
);
1915 // Build the SQL DELETE statement
1916 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1918 pDb
->WriteSqlLog(sqlStmt
);
1920 // Execute the SQL DELETE statement
1921 return(execDelete(sqlStmt
));
1923 } // wxDbTable::DeleteWhere()
1926 /********** wxDbTable::DeleteMatching() **********/
1927 bool wxDbTable::DeleteMatching(void)
1929 wxASSERT(!queryOnly
);
1936 // Build the SQL DELETE statement
1937 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1939 pDb
->WriteSqlLog(sqlStmt
);
1941 // Execute the SQL DELETE statement
1942 return(execDelete(sqlStmt
));
1944 } // wxDbTable::DeleteMatching()
1947 /********** wxDbTable::IsColNull() **********/
1948 bool wxDbTable::IsColNull(UWORD colNo
) const
1951 This logic is just not right. It would indicate TRUE
1952 if a numeric field were set to a value of 0.
1954 switch(colDefs[colNo].SqlCtype)
1957 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
1959 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
1961 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
1963 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1965 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
1967 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
1969 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
1970 case SQL_C_TIMESTAMP:
1971 TIMESTAMP_STRUCT *pDt;
1972 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
1973 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
1981 return (colDefs
[colNo
].Null
);
1982 } // wxDbTable::IsColNull()
1985 /********** wxDbTable::CanSelectForUpdate() **********/
1986 bool wxDbTable::CanSelectForUpdate(void)
1991 if (pDb
->Dbms() == dbmsMY_SQL
)
1994 if ((pDb
->Dbms() == dbmsORACLE
) ||
1995 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2000 } // wxDbTable::CanSelectForUpdate()
2003 /********** wxDbTable::CanUpdByROWID() **********/
2004 bool wxDbTable::CanUpdByROWID(void)
2007 * NOTE: Returning FALSE for now until this can be debugged,
2008 * as the ROWID is not getting updated correctly
2012 if (pDb->Dbms() == dbmsORACLE)
2017 } // wxDbTable::CanUpdByROWID()
2020 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2021 bool wxDbTable::IsCursorClosedOnCommit(void)
2023 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2028 } // wxDbTable::IsCursorClosedOnCommit()
2032 /********** wxDbTable::ClearMemberVar() **********/
2033 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2035 wxASSERT(colNo
< noCols
);
2037 switch(colDefs
[colNo
].SqlCtype
)
2040 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2043 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2046 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2049 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2052 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2055 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2058 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2060 case SQL_C_TIMESTAMP
:
2061 TIMESTAMP_STRUCT
*pDt
;
2062 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2075 } // wxDbTable::ClearMemberVar()
2078 /********** wxDbTable::ClearMemberVars() **********/
2079 void wxDbTable::ClearMemberVars(bool setToNull
)
2083 // Loop through the columns setting each member variable to zero
2084 for (i
=0; i
< noCols
; i
++)
2085 ClearMemberVar(i
,setToNull
);
2087 } // wxDbTable::ClearMemberVars()
2090 /********** wxDbTable::SetQueryTimeout() **********/
2091 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2093 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2094 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2095 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2096 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2097 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2098 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2099 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2100 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2102 // Completed Successfully
2105 } // wxDbTable::SetQueryTimeout()
2108 /********** wxDbTable::SetColDefs() **********/
2109 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2110 SWORD cType
, int size
, bool keyField
, bool upd
,
2111 bool insAllow
, bool derivedCol
)
2113 if (!colDefs
) // May happen if the database connection fails
2116 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2118 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2119 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2123 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2124 fieldName
.c_str(),colDefs
[index
].ColName
);
2126 #endif // __WXDEBUG__
2129 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2131 colDefs
[index
].DbDataType
= dataType
;
2132 colDefs
[index
].PtrDataObj
= pData
;
2133 colDefs
[index
].SqlCtype
= cType
;
2134 colDefs
[index
].SzDataObj
= size
;
2135 colDefs
[index
].KeyField
= keyField
;
2136 colDefs
[index
].DerivedCol
= derivedCol
;
2137 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2140 colDefs
[index
].Updateable
= FALSE
;
2141 colDefs
[index
].InsertAllowed
= FALSE
;
2145 colDefs
[index
].Updateable
= upd
;
2146 colDefs
[index
].InsertAllowed
= insAllow
;
2149 colDefs
[index
].Null
= FALSE
;
2151 } // wxDbTable::SetColDefs()
2154 /********** wxDbTable::SetColDefs() **********/
2155 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2158 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2164 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2166 for (index
= 0; index
< numCols
; index
++)
2168 // Process the fields
2169 switch (pColInfs
[index
].dbDataType
)
2171 case DB_DATA_TYPE_VARCHAR
:
2172 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2173 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2174 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2176 case DB_DATA_TYPE_INTEGER
:
2177 // Can be long or short
2178 if (pColInfs
[index
].bufferLength
== sizeof(long))
2180 pColDataPtrs
[index
].PtrDataObj
= new long;
2181 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2182 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2186 pColDataPtrs
[index
].PtrDataObj
= new short;
2187 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2188 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2191 case DB_DATA_TYPE_FLOAT
:
2192 // Can be float or double
2193 if (pColInfs
[index
].bufferLength
== sizeof(float))
2195 pColDataPtrs
[index
].PtrDataObj
= new float;
2196 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2197 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2201 pColDataPtrs
[index
].PtrDataObj
= new double;
2202 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2203 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2206 case DB_DATA_TYPE_DATE
:
2207 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2208 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2209 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2211 case DB_DATA_TYPE_BLOB
:
2212 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2213 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2214 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2215 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2218 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2219 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2222 // Unable to build all the column definitions, as either one of
2223 // the calls to "new" failed above, or there was a BLOB field
2224 // to have a column definition for. If BLOBs are to be used,
2225 // the other form of ::SetColDefs() must be used, as it is impossible
2226 // to know the maximum size to create the PtrDataObj to be.
2227 delete [] pColDataPtrs
;
2233 return (pColDataPtrs
);
2235 } // wxDbTable::SetColDefs()
2238 /********** wxDbTable::SetCursor() **********/
2239 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2241 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2242 hstmt
= *hstmtDefault
;
2244 hstmt
= *hstmtActivate
;
2246 } // wxDbTable::SetCursor()
2249 /********** wxDbTable::Count(const wxString &) **********/
2250 ULONG
wxDbTable::Count(const wxString
&args
)
2256 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2257 sqlStmt
= wxT("SELECT COUNT(");
2259 sqlStmt
+= wxT(") FROM ");
2260 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2261 // sqlStmt += queryTableName;
2262 #if wxODBC_BACKWARD_COMPATABILITY
2263 if (from
&& wxStrlen(from
))
2269 // Add the where clause if one is provided
2270 #if wxODBC_BACKWARD_COMPATABILITY
2271 if (where
&& wxStrlen(where
))
2276 sqlStmt
+= wxT(" WHERE ");
2280 pDb
->WriteSqlLog(sqlStmt
);
2282 // Initialize the Count cursor if it's not already initialized
2285 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2286 wxASSERT(hstmtCount
);
2291 // Execute the SQL statement
2292 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2294 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2299 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2301 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2305 // Obtain the result
2306 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2308 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2313 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2314 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2316 // Return the record count
2319 } // wxDbTable::Count()
2322 /********** wxDbTable::Refresh() **********/
2323 bool wxDbTable::Refresh(void)
2327 // Switch to the internal cursor so any active cursors are not corrupted
2328 HSTMT currCursor
= GetCursor();
2329 hstmt
= hstmtInternal
;
2330 #if wxODBC_BACKWARD_COMPATABILITY
2331 // Save the where and order by clauses
2332 char *saveWhere
= where
;
2333 char *saveOrderBy
= orderBy
;
2335 wxString saveWhere
= where
;
2336 wxString saveOrderBy
= orderBy
;
2338 // Build a where clause to refetch the record with. Try and use the
2339 // ROWID if it's available, ow use the key fields.
2340 wxString whereClause
;
2341 whereClause
.Empty();
2343 if (CanUpdByROWID())
2346 wxChar rowid
[wxDB_ROWID_LEN
+1];
2348 // Get the ROWID value. If not successful retreiving the ROWID,
2349 // simply fall down through the code and build the WHERE clause
2350 // based on the key fields.
2351 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2353 whereClause
+= pDb
->SQLTableName(queryTableName
);
2354 // whereClause += queryTableName;
2355 whereClause
+= wxT(".ROWID = '");
2356 whereClause
+= rowid
;
2357 whereClause
+= wxT("'");
2361 // If unable to use the ROWID, build a where clause from the keyfields
2362 if (wxStrlen(whereClause
) == 0)
2363 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2365 // Requery the record
2366 where
= whereClause
;
2371 if (result
&& !GetNext())
2374 // Switch back to original cursor
2375 SetCursor(&currCursor
);
2377 // Free the internal cursor
2378 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2379 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2381 // Restore the original where and order by clauses
2383 orderBy
= saveOrderBy
;
2387 } // wxDbTable::Refresh()
2390 /********** wxDbTable::SetColNull() **********/
2391 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2395 colDefs
[colNo
].Null
= set
;
2396 if (set
) // Blank out the values in the member variable
2397 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2403 } // wxDbTable::SetColNull()
2406 /********** wxDbTable::SetColNull() **********/
2407 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2410 for (i
= 0; i
< noCols
; i
++)
2412 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2418 colDefs
[i
].Null
= set
;
2419 if (set
) // Blank out the values in the member variable
2420 ClearMemberVar(i
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2426 } // wxDbTable::SetColNull()
2429 /********** wxDbTable::GetNewCursor() **********/
2430 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2432 HSTMT
*newHSTMT
= new HSTMT
;
2437 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2439 pDb
->DispAllErrors(henv
, hdbc
);
2444 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2446 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2453 if (!bindCols(*newHSTMT
))
2461 SetCursor(newHSTMT
);
2465 } // wxDbTable::GetNewCursor()
2468 /********** wxDbTable::DeleteCursor() **********/
2469 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2473 if (!hstmtDel
) // Cursor already deleted
2477 ODBC 3.0 says to use this form
2478 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2481 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2483 pDb
->DispAllErrors(henv
, hdbc
);
2491 } // wxDbTable::DeleteCursor()
2493 //////////////////////////////////////////////////////////////
2494 // wxDbGrid support functions
2495 //////////////////////////////////////////////////////////////
2497 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2499 if (!m_hstmtGridQuery
)
2501 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2502 if (!bindCols(*m_hstmtGridQuery
))
2506 m_rowmode
= rowmode
;
2509 case WX_ROW_MODE_QUERY
:
2510 SetCursor(m_hstmtGridQuery
);
2512 case WX_ROW_MODE_INDIVIDUAL
:
2513 SetCursor(hstmtDefault
);
2518 } // wxDbTable::SetRowMode()
2521 wxVariant
wxDbTable::GetCol(const int colNo
) const
2524 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2526 switch (colDefs
[colNo
].SqlCtype
)
2530 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2534 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2538 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2541 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2544 val
= (long)(*(char *)(colDefs
[colNo
].PtrDataObj
));
2546 case SQL_C_UTINYINT
:
2547 val
= (long)(*(unsigned char *)(colDefs
[colNo
].PtrDataObj
));
2550 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2553 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2556 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2558 case SQL_C_TIMESTAMP
:
2559 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2562 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2569 } // wxDbTable::GetCol()
2572 void csstrncpyt(char *s
, const char *t
, int n
)
2574 while ((*s
++ = *t
++) && --n
)
2580 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2582 //FIXME: Add proper wxDateTime support to wxVariant..
2585 SetColNull(colNo
, val
.IsNull());
2589 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2590 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2591 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2593 //Returns null if invalid!
2594 if (!dateval
.ParseDate(val
.GetString()))
2595 SetColNull(colNo
, TRUE
);
2598 switch (colDefs
[colNo
].SqlCtype
)
2602 csstrncpyt((char *)(colDefs
[colNo
].PtrDataObj
),
2603 val
.GetString().c_str(),
2604 colDefs
[colNo
].SzDataObj
-1);
2608 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2612 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2615 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2618 *(char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2620 case SQL_C_UTINYINT
:
2621 *(unsigned char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2624 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2626 //FIXME: Add proper wxDateTime support to wxVariant..
2629 DATE_STRUCT
*dataptr
=
2630 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2632 dataptr
->year
= dateval
.GetYear();
2633 dataptr
->month
= dateval
.GetMonth()+1;
2634 dataptr
->day
= dateval
.GetDay();
2639 TIME_STRUCT
*dataptr
=
2640 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2642 dataptr
->hour
= dateval
.GetHour();
2643 dataptr
->minute
= dateval
.GetMinute();
2644 dataptr
->second
= dateval
.GetSecond();
2647 case SQL_C_TIMESTAMP
:
2649 TIMESTAMP_STRUCT
*dataptr
=
2650 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2651 dataptr
->year
= dateval
.GetYear();
2652 dataptr
->month
= dateval
.GetMonth()+1;
2653 dataptr
->day
= dateval
.GetDay();
2655 dataptr
->hour
= dateval
.GetHour();
2656 dataptr
->minute
= dateval
.GetMinute();
2657 dataptr
->second
= dateval
.GetSecond();
2661 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2666 } // if (!val.IsNull())
2667 } // wxDbTable::SetCol()
2670 GenericKey
wxDbTable::GetKey()
2675 blk
= malloc(m_keysize
);
2676 blkptr
= (wxChar
*) blk
;
2679 for (i
=0; i
< noCols
; i
++)
2681 if (colDefs
[i
].KeyField
)
2683 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2684 blkptr
+= colDefs
[i
].SzDataObj
;
2688 GenericKey k
= GenericKey(blk
, m_keysize
);
2692 } // wxDbTable::GetKey()
2695 void wxDbTable::SetKey(const GenericKey
& k
)
2701 blkptr
= (wxChar
*)blk
;
2704 for (i
=0; i
< noCols
; i
++)
2706 if (colDefs
[i
].KeyField
)
2708 SetColNull(i
, FALSE
);
2709 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2710 blkptr
+= colDefs
[i
].SzDataObj
;
2713 } // wxDbTable::SetKey()
2716 #endif // wxUSE_ODBC