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 wxASSERT_MSG( index
< noCols
,
2122 _T("Specified column index exceeds the maximum number of columns for this table.") );
2124 if (!colDefs
) // May happen if the database connection fails
2127 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2129 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2130 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2134 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2135 fieldName
.c_str(),colDefs
[index
].ColName
);
2137 #endif // __WXDEBUG__
2140 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2142 colDefs
[index
].DbDataType
= dataType
;
2143 colDefs
[index
].PtrDataObj
= pData
;
2144 colDefs
[index
].SqlCtype
= cType
;
2145 colDefs
[index
].SzDataObj
= size
;
2146 colDefs
[index
].KeyField
= keyField
;
2147 colDefs
[index
].DerivedCol
= derivedCol
;
2148 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2151 colDefs
[index
].Updateable
= FALSE
;
2152 colDefs
[index
].InsertAllowed
= FALSE
;
2156 colDefs
[index
].Updateable
= upd
;
2157 colDefs
[index
].InsertAllowed
= insAllow
;
2160 colDefs
[index
].Null
= FALSE
;
2162 } // wxDbTable::SetColDefs()
2165 /********** wxDbTable::SetColDefs() **********/
2166 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2169 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2175 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2177 for (index
= 0; index
< numCols
; index
++)
2179 // Process the fields
2180 switch (pColInfs
[index
].dbDataType
)
2182 case DB_DATA_TYPE_VARCHAR
:
2183 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2184 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2185 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2187 case DB_DATA_TYPE_INTEGER
:
2188 // Can be long or short
2189 if (pColInfs
[index
].bufferLength
== sizeof(long))
2191 pColDataPtrs
[index
].PtrDataObj
= new long;
2192 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2193 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2197 pColDataPtrs
[index
].PtrDataObj
= new short;
2198 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2199 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2202 case DB_DATA_TYPE_FLOAT
:
2203 // Can be float or double
2204 if (pColInfs
[index
].bufferLength
== sizeof(float))
2206 pColDataPtrs
[index
].PtrDataObj
= new float;
2207 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2208 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2212 pColDataPtrs
[index
].PtrDataObj
= new double;
2213 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2214 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2217 case DB_DATA_TYPE_DATE
:
2218 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2219 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2220 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2222 case DB_DATA_TYPE_BLOB
:
2223 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2224 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2225 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2226 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2229 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2230 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2233 // Unable to build all the column definitions, as either one of
2234 // the calls to "new" failed above, or there was a BLOB field
2235 // to have a column definition for. If BLOBs are to be used,
2236 // the other form of ::SetColDefs() must be used, as it is impossible
2237 // to know the maximum size to create the PtrDataObj to be.
2238 delete [] pColDataPtrs
;
2244 return (pColDataPtrs
);
2246 } // wxDbTable::SetColDefs()
2249 /********** wxDbTable::SetCursor() **********/
2250 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2252 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2253 hstmt
= *hstmtDefault
;
2255 hstmt
= *hstmtActivate
;
2257 } // wxDbTable::SetCursor()
2260 /********** wxDbTable::Count(const wxString &) **********/
2261 ULONG
wxDbTable::Count(const wxString
&args
)
2267 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2268 sqlStmt
= wxT("SELECT COUNT(");
2270 sqlStmt
+= wxT(") FROM ");
2271 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2272 // sqlStmt += queryTableName;
2273 #if wxODBC_BACKWARD_COMPATABILITY
2274 if (from
&& wxStrlen(from
))
2280 // Add the where clause if one is provided
2281 #if wxODBC_BACKWARD_COMPATABILITY
2282 if (where
&& wxStrlen(where
))
2287 sqlStmt
+= wxT(" WHERE ");
2291 pDb
->WriteSqlLog(sqlStmt
);
2293 // Initialize the Count cursor if it's not already initialized
2296 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2297 wxASSERT(hstmtCount
);
2302 // Execute the SQL statement
2303 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2305 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2310 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2312 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2316 // Obtain the result
2317 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2319 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2324 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2325 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2327 // Return the record count
2330 } // wxDbTable::Count()
2333 /********** wxDbTable::Refresh() **********/
2334 bool wxDbTable::Refresh(void)
2338 // Switch to the internal cursor so any active cursors are not corrupted
2339 HSTMT currCursor
= GetCursor();
2340 hstmt
= hstmtInternal
;
2341 #if wxODBC_BACKWARD_COMPATABILITY
2342 // Save the where and order by clauses
2343 char *saveWhere
= where
;
2344 char *saveOrderBy
= orderBy
;
2346 wxString saveWhere
= where
;
2347 wxString saveOrderBy
= orderBy
;
2349 // Build a where clause to refetch the record with. Try and use the
2350 // ROWID if it's available, ow use the key fields.
2351 wxString whereClause
;
2352 whereClause
.Empty();
2354 if (CanUpdByROWID())
2357 wxChar rowid
[wxDB_ROWID_LEN
+1];
2359 // Get the ROWID value. If not successful retreiving the ROWID,
2360 // simply fall down through the code and build the WHERE clause
2361 // based on the key fields.
2362 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2364 whereClause
+= pDb
->SQLTableName(queryTableName
);
2365 // whereClause += queryTableName;
2366 whereClause
+= wxT(".ROWID = '");
2367 whereClause
+= rowid
;
2368 whereClause
+= wxT("'");
2372 // If unable to use the ROWID, build a where clause from the keyfields
2373 if (wxStrlen(whereClause
) == 0)
2374 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2376 // Requery the record
2377 where
= whereClause
;
2382 if (result
&& !GetNext())
2385 // Switch back to original cursor
2386 SetCursor(&currCursor
);
2388 // Free the internal cursor
2389 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2390 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2392 // Restore the original where and order by clauses
2394 orderBy
= saveOrderBy
;
2398 } // wxDbTable::Refresh()
2401 /********** wxDbTable::SetColNull() **********/
2402 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2406 colDefs
[colNo
].Null
= set
;
2407 if (set
) // Blank out the values in the member variable
2408 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2414 } // wxDbTable::SetColNull()
2417 /********** wxDbTable::SetColNull() **********/
2418 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2421 for (i
= 0; i
< noCols
; i
++)
2423 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2429 colDefs
[i
].Null
= set
;
2430 if (set
) // Blank out the values in the member variable
2431 ClearMemberVar(i
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2437 } // wxDbTable::SetColNull()
2440 /********** wxDbTable::GetNewCursor() **********/
2441 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2443 HSTMT
*newHSTMT
= new HSTMT
;
2448 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2450 pDb
->DispAllErrors(henv
, hdbc
);
2455 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2457 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2464 if (!bindCols(*newHSTMT
))
2472 SetCursor(newHSTMT
);
2476 } // wxDbTable::GetNewCursor()
2479 /********** wxDbTable::DeleteCursor() **********/
2480 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2484 if (!hstmtDel
) // Cursor already deleted
2488 ODBC 3.0 says to use this form
2489 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2492 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2494 pDb
->DispAllErrors(henv
, hdbc
);
2502 } // wxDbTable::DeleteCursor()
2504 //////////////////////////////////////////////////////////////
2505 // wxDbGrid support functions
2506 //////////////////////////////////////////////////////////////
2508 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2510 if (!m_hstmtGridQuery
)
2512 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2513 if (!bindCols(*m_hstmtGridQuery
))
2517 m_rowmode
= rowmode
;
2520 case WX_ROW_MODE_QUERY
:
2521 SetCursor(m_hstmtGridQuery
);
2523 case WX_ROW_MODE_INDIVIDUAL
:
2524 SetCursor(hstmtDefault
);
2529 } // wxDbTable::SetRowMode()
2532 wxVariant
wxDbTable::GetCol(const int colNo
) const
2535 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2537 switch (colDefs
[colNo
].SqlCtype
)
2541 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2545 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2549 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2552 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2555 val
= (long)(*(char *)(colDefs
[colNo
].PtrDataObj
));
2557 case SQL_C_UTINYINT
:
2558 val
= (long)(*(unsigned char *)(colDefs
[colNo
].PtrDataObj
));
2561 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2564 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2567 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2569 case SQL_C_TIMESTAMP
:
2570 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2573 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2580 } // wxDbTable::GetCol()
2583 void csstrncpyt(char *s
, const char *t
, int n
)
2585 while ((*s
++ = *t
++) && --n
)
2591 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2593 //FIXME: Add proper wxDateTime support to wxVariant..
2596 SetColNull(colNo
, val
.IsNull());
2600 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2601 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2602 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2604 //Returns null if invalid!
2605 if (!dateval
.ParseDate(val
.GetString()))
2606 SetColNull(colNo
, TRUE
);
2609 switch (colDefs
[colNo
].SqlCtype
)
2613 csstrncpyt((char *)(colDefs
[colNo
].PtrDataObj
),
2614 val
.GetString().c_str(),
2615 colDefs
[colNo
].SzDataObj
-1);
2619 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2623 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2626 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2629 *(char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2631 case SQL_C_UTINYINT
:
2632 *(unsigned char *)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2635 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2637 //FIXME: Add proper wxDateTime support to wxVariant..
2640 DATE_STRUCT
*dataptr
=
2641 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2643 dataptr
->year
= dateval
.GetYear();
2644 dataptr
->month
= dateval
.GetMonth()+1;
2645 dataptr
->day
= dateval
.GetDay();
2650 TIME_STRUCT
*dataptr
=
2651 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2653 dataptr
->hour
= dateval
.GetHour();
2654 dataptr
->minute
= dateval
.GetMinute();
2655 dataptr
->second
= dateval
.GetSecond();
2658 case SQL_C_TIMESTAMP
:
2660 TIMESTAMP_STRUCT
*dataptr
=
2661 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2662 dataptr
->year
= dateval
.GetYear();
2663 dataptr
->month
= dateval
.GetMonth()+1;
2664 dataptr
->day
= dateval
.GetDay();
2666 dataptr
->hour
= dateval
.GetHour();
2667 dataptr
->minute
= dateval
.GetMinute();
2668 dataptr
->second
= dateval
.GetSecond();
2672 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2677 } // if (!val.IsNull())
2678 } // wxDbTable::SetCol()
2681 GenericKey
wxDbTable::GetKey()
2686 blk
= malloc(m_keysize
);
2687 blkptr
= (wxChar
*) blk
;
2690 for (i
=0; i
< noCols
; i
++)
2692 if (colDefs
[i
].KeyField
)
2694 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2695 blkptr
+= colDefs
[i
].SzDataObj
;
2699 GenericKey k
= GenericKey(blk
, m_keysize
);
2703 } // wxDbTable::GetKey()
2706 void wxDbTable::SetKey(const GenericKey
& k
)
2712 blkptr
= (wxChar
*)blk
;
2715 for (i
=0; i
< noCols
; i
++)
2717 if (colDefs
[i
].KeyField
)
2719 SetColNull(i
, FALSE
);
2720 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2721 blkptr
+= colDefs
[i
].SzDataObj
;
2724 } // wxDbTable::SetKey()
2727 #endif // wxUSE_ODBC