1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence
12 ///////////////////////////////////////////////////////////////////////////////
19 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
20 #pragma implementation "dbtable.h"
23 #include "wx/wxprec.h"
29 #ifdef DBDEBUG_CONSOLE
35 #include "wx/ioswrap.h"
39 #include "wx/string.h"
40 #include "wx/object.h"
45 #include "wx/filefn.h"
53 #include "wx/dbtable.h"
56 // The HPUX preprocessor lines below were commented out on 8/20/97
57 // because macros.h currently redefines DEBUG and is unneeded.
59 // # include <macros.h>
62 # include <sys/minmax.h>
66 ULONG lastTableID
= 0;
74 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
76 while ( (*target
++ = *source
++) != '\0' && --n
)
84 /********** wxDbColDef::wxDbColDef() Constructor **********/
85 wxDbColDef::wxDbColDef()
91 bool wxDbColDef::Initialize()
94 DbDataType
= DB_DATA_TYPE_INTEGER
;
95 SqlCtype
= SQL_C_LONG
;
100 InsertAllowed
= FALSE
;
106 } // wxDbColDef::Initialize()
109 /********** wxDbTable::wxDbTable() Constructor **********/
110 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
111 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
113 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
115 } // wxDbTable::wxDbTable()
118 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
119 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
120 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
122 wxString tempQryTblName
;
123 tempQryTblName
= qryTblName
;
124 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
126 } // wxDbTable::wxDbTable()
129 /********** wxDbTable::~wxDbTable() **********/
130 wxDbTable::~wxDbTable()
133 } // wxDbTable::~wxDbTable()
136 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
137 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
139 // Initializing member variables
140 pDb
= pwxDb
; // Pointer to the wxDb object
144 m_hstmtGridQuery
= 0;
145 hstmtDefault
= 0; // Initialized below
146 hstmtCount
= 0; // Initialized first time it is needed
153 noCols
= numColumns
; // Number of cols in the table
154 where
.Empty(); // Where clause
155 orderBy
.Empty(); // Order By clause
156 from
.Empty(); // From clause
157 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
162 queryTableName
.Empty();
164 wxASSERT(tblName
.Length());
170 tableName
= tblName
; // Table Name
171 if (tblPath
.Length())
172 tablePath
= tblPath
; // Table Path - used for dBase files
176 if (qryTblName
.Length()) // Name of the table/view to query
177 queryTableName
= qryTblName
;
179 queryTableName
= tblName
;
181 pDb
->incrementTableCount();
184 tableID
= ++lastTableID
;
185 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
188 wxTablesInUse
*tableInUse
;
189 tableInUse
= new wxTablesInUse();
190 tableInUse
->tableName
= tblName
;
191 tableInUse
->tableID
= tableID
;
192 tableInUse
->pDb
= pDb
;
193 TablesInUse
.Append(tableInUse
);
198 // Grab the HENV and HDBC from the wxDb object
199 henv
= pDb
->GetHENV();
200 hdbc
= pDb
->GetHDBC();
202 // Allocate space for column definitions
204 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
206 // Allocate statement handles for the table
209 // Allocate a separate statement handle for performing inserts
210 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
211 pDb
->DispAllErrors(henv
, hdbc
);
212 // Allocate a separate statement handle for performing deletes
213 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
214 pDb
->DispAllErrors(henv
, hdbc
);
215 // Allocate a separate statement handle for performing updates
216 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
217 pDb
->DispAllErrors(henv
, hdbc
);
219 // Allocate a separate statement handle for internal use
220 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
221 pDb
->DispAllErrors(henv
, hdbc
);
223 // Set the cursor type for the statement handles
224 cursorType
= SQL_CURSOR_STATIC
;
226 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
228 // Check to see if cursor type is supported
229 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
230 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
232 // Datasource does not support static cursors. Driver
233 // will substitute a cursor type. Call SQLGetStmtOption()
234 // to determine which cursor type was selected.
235 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
236 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
237 #ifdef DBDEBUG_CONSOLE
238 cout
<< wxT("Static cursor changed to: ");
241 case SQL_CURSOR_FORWARD_ONLY
:
242 cout
<< wxT("Forward Only");
244 case SQL_CURSOR_STATIC
:
245 cout
<< wxT("Static");
247 case SQL_CURSOR_KEYSET_DRIVEN
:
248 cout
<< wxT("Keyset Driven");
250 case SQL_CURSOR_DYNAMIC
:
251 cout
<< wxT("Dynamic");
254 cout
<< endl
<< endl
;
257 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
259 // Force the use of a forward only cursor...
260 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
261 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
263 // Should never happen
264 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
271 pDb
->DispNextError();
272 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
275 #ifdef DBDEBUG_CONSOLE
277 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
282 // Set the cursor type for the INSERT statement handle
283 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
284 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
285 // Set the cursor type for the DELETE statement handle
286 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
287 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
288 // Set the cursor type for the UPDATE statement handle
289 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
290 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
293 // Make the default cursor the active cursor
294 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
295 wxASSERT(hstmtDefault
);
296 hstmt
= *hstmtDefault
;
300 } // wxDbTable::initialize()
303 void wxDbTable::cleanup()
308 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
317 wxList::compatibility_iterator pNode
;
318 pNode
= TablesInUse
.GetFirst();
319 while (pNode
&& !found
)
321 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
324 delete (wxTablesInUse
*)pNode
->GetData();
325 TablesInUse
.Erase(pNode
);
328 pNode
= pNode
->GetNext();
333 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
334 wxLogDebug (msg
,wxT("NOTICE..."));
339 // Decrement the wxDb table count
341 pDb
->decrementTableCount();
343 // Delete memory allocated for column definitions
347 // Free statement handles
353 ODBC 3.0 says to use this form
354 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
356 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
357 pDb
->DispAllErrors(henv
, hdbc
);
363 ODBC 3.0 says to use this form
364 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
366 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
367 pDb
->DispAllErrors(henv
, hdbc
);
373 ODBC 3.0 says to use this form
374 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
376 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
377 pDb
->DispAllErrors(henv
, hdbc
);
383 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
384 pDb
->DispAllErrors(henv
, hdbc
);
387 // Delete dynamically allocated cursors
389 DeleteCursor(hstmtDefault
);
392 DeleteCursor(hstmtCount
);
394 if (m_hstmtGridQuery
)
395 DeleteCursor(m_hstmtGridQuery
);
397 } // wxDbTable::cleanup()
400 /***************************** PRIVATE FUNCTIONS *****************************/
403 void wxDbTable::setCbValueForColumn(int columnIndex
)
405 switch(colDefs
[columnIndex
].DbDataType
)
407 case DB_DATA_TYPE_VARCHAR
:
408 if (colDefs
[columnIndex
].Null
)
409 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
411 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
413 case DB_DATA_TYPE_INTEGER
:
414 if (colDefs
[columnIndex
].Null
)
415 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
417 colDefs
[columnIndex
].CbValue
= 0;
419 case DB_DATA_TYPE_FLOAT
:
420 if (colDefs
[columnIndex
].Null
)
421 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
423 colDefs
[columnIndex
].CbValue
= 0;
425 case DB_DATA_TYPE_DATE
:
426 if (colDefs
[columnIndex
].Null
)
427 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
429 colDefs
[columnIndex
].CbValue
= 0;
431 case DB_DATA_TYPE_BLOB
:
432 if (colDefs
[columnIndex
].Null
)
433 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
435 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_CHAR
)
436 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
438 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
443 /********** wxDbTable::bindParams() **********/
444 bool wxDbTable::bindParams(bool forUpdate
)
446 wxASSERT(!queryOnly
);
451 SDWORD precision
= 0;
454 // Bind each column of the table that should be bound
455 // to a parameter marker
459 for (i
=0, colNo
=1; i
< noCols
; i
++)
463 if (!colDefs
[i
].Updateable
)
468 if (!colDefs
[i
].InsertAllowed
)
472 switch(colDefs
[i
].DbDataType
)
474 case DB_DATA_TYPE_VARCHAR
:
475 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
476 precision
= colDefs
[i
].SzDataObj
;
479 case DB_DATA_TYPE_INTEGER
:
480 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
481 precision
= pDb
->GetTypeInfInteger().Precision
;
484 case DB_DATA_TYPE_FLOAT
:
485 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
486 precision
= pDb
->GetTypeInfFloat().Precision
;
487 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
488 // SQL Sybase Anywhere v5.5 returned a negative number for the
489 // MaxScale. This caused ODBC to kick out an error on ibscale.
490 // I check for this here and set the scale = precision.
492 // scale = (short) precision;
494 case DB_DATA_TYPE_DATE
:
495 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
496 precision
= pDb
->GetTypeInfDate().Precision
;
499 case DB_DATA_TYPE_BLOB
:
500 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
501 precision
= colDefs
[i
].SzDataObj
;
506 setCbValueForColumn(i
);
510 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
511 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
512 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
514 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
519 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
520 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
521 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
523 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
528 // Completed successfully
531 } // wxDbTable::bindParams()
534 /********** wxDbTable::bindInsertParams() **********/
535 bool wxDbTable::bindInsertParams(void)
537 return bindParams(FALSE
);
538 } // wxDbTable::bindInsertParams()
541 /********** wxDbTable::bindUpdateParams() **********/
542 bool wxDbTable::bindUpdateParams(void)
544 return bindParams(TRUE
);
545 } // wxDbTable::bindUpdateParams()
548 /********** wxDbTable::bindCols() **********/
549 bool wxDbTable::bindCols(HSTMT cursor
)
553 // Bind each column of the table to a memory address for fetching data
555 for (i
= 0; i
< noCols
; i
++)
557 cb
= colDefs
[i
].CbValue
;
558 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
559 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
560 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
563 // Completed successfully
566 } // wxDbTable::bindCols()
569 /********** wxDbTable::getRec() **********/
570 bool wxDbTable::getRec(UWORD fetchType
)
574 if (!pDb
->FwdOnlyCursors())
576 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
580 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
581 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
583 if (retcode
== SQL_NO_DATA_FOUND
)
586 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
590 // Set the Null member variable to indicate the Null state
591 // of each column just read in.
593 for (i
= 0; i
< noCols
; i
++)
594 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
599 // Fetch the next record from the record set
600 retcode
= SQLFetch(hstmt
);
601 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
603 if (retcode
== SQL_NO_DATA_FOUND
)
606 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
610 // Set the Null member variable to indicate the Null state
611 // of each column just read in.
613 for (i
= 0; i
< noCols
; i
++)
614 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
618 // Completed successfully
621 } // wxDbTable::getRec()
624 /********** wxDbTable::execDelete() **********/
625 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
629 // Execute the DELETE statement
630 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
632 if (retcode
== SQL_SUCCESS
||
633 retcode
== SQL_NO_DATA_FOUND
||
634 retcode
== SQL_SUCCESS_WITH_INFO
)
636 // Record deleted successfully
640 // Problem deleting record
641 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
643 } // wxDbTable::execDelete()
646 /********** wxDbTable::execUpdate() **********/
647 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
651 // Execute the UPDATE statement
652 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
654 if (retcode
== SQL_SUCCESS
||
655 retcode
== SQL_NO_DATA_FOUND
||
656 retcode
== SQL_SUCCESS_WITH_INFO
)
658 // Record updated successfully
661 else if (retcode
== SQL_NEED_DATA
)
664 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
665 while (retcode
== SQL_NEED_DATA
)
667 // Find the parameter
669 for (i
=0; i
< noCols
; i
++)
671 if (colDefs
[i
].PtrDataObj
== pParmID
)
673 // We found it. Store the parameter.
674 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
675 if (retcode
!= SQL_SUCCESS
)
677 pDb
->DispNextError();
678 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
683 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
685 if (retcode
== SQL_SUCCESS
||
686 retcode
== SQL_NO_DATA_FOUND
||
687 retcode
== SQL_SUCCESS_WITH_INFO
)
689 // Record updated successfully
694 // Problem updating record
695 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
697 } // wxDbTable::execUpdate()
700 /********** wxDbTable::query() **********/
701 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
706 // The user may wish to select for update, but the DBMS may not be capable
707 selectForUpdate
= CanSelectForUpdate();
709 selectForUpdate
= FALSE
;
711 // Set the SQL SELECT string
712 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
713 { // so generate a select statement.
714 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
715 pDb
->WriteSqlLog(sqlStmt
);
718 // Make sure the cursor is closed first
719 if (!CloseCursor(hstmt
))
722 // Execute the SQL SELECT statement
724 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
725 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
726 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
728 // Completed successfully
731 } // wxDbTable::query()
734 /***************************** PUBLIC FUNCTIONS *****************************/
737 /********** wxDbTable::Open() **********/
738 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
748 // Calculate the maximum size of the concatenated
749 // keys for use with wxDbGrid
751 for (i
=0; i
< noCols
; i
++)
753 if (colDefs
[i
].KeyField
)
756 m_keysize
+= colDefs
[i
].SzDataObj
;
761 // Verify that the table exists in the database
762 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
764 s
= wxT("Table/view does not exist in the database");
765 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
766 s
+= wxT(", or you have no permissions.\n");
770 else if (checkPrivileges
)
772 // Verify the user has rights to access the table.
773 // Shortcut boolean evaluation to optimize out call to
776 // Unfortunately this optimization doesn't seem to be
778 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
779 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
780 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
787 if (!tablePath
.IsEmpty())
788 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
790 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
793 pDb
->LogError(p
.GetData());
798 // Bind the member variables for field exchange between
799 // the wxDbTable object and the ODBC record.
802 if (!bindInsertParams()) // Inserts
805 if (!bindUpdateParams()) // Updates
809 if (!bindCols(*hstmtDefault
)) // Selects
812 if (!bindCols(hstmtInternal
)) // Internal use only
816 * Do NOT bind the hstmtCount cursor!!!
819 // Build an insert statement using parameter markers
820 if (!queryOnly
&& noCols
> 0)
822 bool needComma
= FALSE
;
823 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
824 pDb
->SQLTableName(tableName
.c_str()).c_str());
825 for (i
= 0; i
< noCols
; i
++)
827 if (! colDefs
[i
].InsertAllowed
)
831 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
832 // sqlStmt += colDefs[i].ColName;
836 sqlStmt
+= wxT(") VALUES (");
838 int insertableCount
= 0;
840 for (i
= 0; i
< noCols
; i
++)
842 if (! colDefs
[i
].InsertAllowed
)
852 // Prepare the insert statement for execution
855 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
856 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
862 // Completed successfully
865 } // wxDbTable::Open()
868 /********** wxDbTable::Query() **********/
869 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
872 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
874 } // wxDbTable::Query()
877 /********** wxDbTable::QueryBySqlStmt() **********/
878 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
880 pDb
->WriteSqlLog(pSqlStmt
);
882 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
884 } // wxDbTable::QueryBySqlStmt()
887 /********** wxDbTable::QueryMatching() **********/
888 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
891 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
893 } // wxDbTable::QueryMatching()
896 /********** wxDbTable::QueryOnKeyFields() **********/
897 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
900 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
902 } // wxDbTable::QueryOnKeyFields()
905 /********** wxDbTable::GetPrev() **********/
906 bool wxDbTable::GetPrev(void)
908 if (pDb
->FwdOnlyCursors())
910 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
914 return(getRec(SQL_FETCH_PRIOR
));
916 } // wxDbTable::GetPrev()
919 /********** wxDbTable::operator-- **********/
920 bool wxDbTable::operator--(int)
922 if (pDb
->FwdOnlyCursors())
924 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
928 return(getRec(SQL_FETCH_PRIOR
));
930 } // wxDbTable::operator--
933 /********** wxDbTable::GetFirst() **********/
934 bool wxDbTable::GetFirst(void)
936 if (pDb
->FwdOnlyCursors())
938 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
942 return(getRec(SQL_FETCH_FIRST
));
944 } // wxDbTable::GetFirst()
947 /********** wxDbTable::GetLast() **********/
948 bool wxDbTable::GetLast(void)
950 if (pDb
->FwdOnlyCursors())
952 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
956 return(getRec(SQL_FETCH_LAST
));
958 } // wxDbTable::GetLast()
961 /********** wxDbTable::BuildDeleteStmt() **********/
962 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
964 wxASSERT(!queryOnly
);
968 wxString whereClause
;
972 // Handle the case of DeleteWhere() and the where clause is blank. It should
973 // delete all records from the database in this case.
974 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
976 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
977 pDb
->SQLTableName(tableName
.c_str()).c_str());
981 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
982 pDb
->SQLTableName(tableName
.c_str()).c_str());
984 // Append the WHERE clause to the SQL DELETE statement
987 case DB_DEL_KEYFIELDS
:
988 // If the datasource supports the ROWID column, build
989 // the where on ROWID for efficiency purposes.
990 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
994 wxChar rowid
[wxDB_ROWID_LEN
+1];
996 // Get the ROWID value. If not successful retreiving the ROWID,
997 // simply fall down through the code and build the WHERE clause
998 // based on the key fields.
999 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1001 pSqlStmt
+= wxT("ROWID = '");
1003 pSqlStmt
+= wxT("'");
1007 // Unable to delete by ROWID, so build a WHERE
1008 // clause based on the keyfields.
1009 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1010 pSqlStmt
+= whereClause
;
1013 pSqlStmt
+= pWhereClause
;
1015 case DB_DEL_MATCHING
:
1016 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1017 pSqlStmt
+= whereClause
;
1021 } // BuildDeleteStmt()
1024 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1025 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1027 wxString tempSqlStmt
;
1028 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1029 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1030 } // wxDbTable::BuildDeleteStmt()
1033 /********** wxDbTable::BuildSelectStmt() **********/
1034 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1036 wxString whereClause
;
1037 whereClause
.Empty();
1039 // Build a select statement to query the database
1040 pSqlStmt
= wxT("SELECT ");
1042 // SELECT DISTINCT values only?
1044 pSqlStmt
+= wxT("DISTINCT ");
1046 // Was a FROM clause specified to join tables to the base table?
1047 // Available for ::Query() only!!!
1048 bool appendFromClause
= FALSE
;
1049 #if wxODBC_BACKWARD_COMPATABILITY
1050 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1051 appendFromClause
= TRUE
;
1053 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1054 appendFromClause
= TRUE
;
1057 // Add the column list
1060 for (i
= 0; i
< noCols
; i
++)
1062 tStr
= colDefs
[i
].ColName
;
1063 // If joining tables, the base table column names must be qualified to avoid ambiguity
1064 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1066 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1067 pSqlStmt
+= wxT(".");
1069 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1071 pSqlStmt
+= wxT(",");
1074 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1075 // the ROWID if querying distinct records. The rowid will always be unique.
1076 if (!distinct
&& CanUpdByROWID())
1078 // If joining tables, the base table column names must be qualified to avoid ambiguity
1079 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1081 pSqlStmt
+= wxT(",");
1082 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1083 // pSqlStmt += queryTableName;
1084 pSqlStmt
+= wxT(".ROWID");
1087 pSqlStmt
+= wxT(",ROWID");
1090 // Append the FROM tablename portion
1091 pSqlStmt
+= wxT(" FROM ");
1092 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1093 // pSqlStmt += queryTableName;
1095 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1096 // The HOLDLOCK keyword follows the table name in the from clause.
1097 // Each table in the from clause must specify HOLDLOCK or
1098 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1099 // is parsed but ignored in SYBASE Transact-SQL.
1100 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1101 pSqlStmt
+= wxT(" HOLDLOCK");
1103 if (appendFromClause
)
1106 // Append the WHERE clause. Either append the where clause for the class
1107 // or build a where clause. The typeOfSelect determines this.
1108 switch(typeOfSelect
)
1110 case DB_SELECT_WHERE
:
1111 #if wxODBC_BACKWARD_COMPATABILITY
1112 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1114 if (where
.Length()) // May not want a where clause!!!
1117 pSqlStmt
+= wxT(" WHERE ");
1121 case DB_SELECT_KEYFIELDS
:
1122 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1123 if (whereClause
.Length())
1125 pSqlStmt
+= wxT(" WHERE ");
1126 pSqlStmt
+= whereClause
;
1129 case DB_SELECT_MATCHING
:
1130 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1131 if (whereClause
.Length())
1133 pSqlStmt
+= wxT(" WHERE ");
1134 pSqlStmt
+= whereClause
;
1139 // Append the ORDER BY clause
1140 #if wxODBC_BACKWARD_COMPATABILITY
1141 if (orderBy
&& wxStrlen(orderBy
))
1143 if (orderBy
.Length())
1146 pSqlStmt
+= wxT(" ORDER BY ");
1147 pSqlStmt
+= orderBy
;
1150 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1151 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1152 // HOLDLOCK for Sybase.
1153 if (selectForUpdate
&& CanSelectForUpdate())
1154 pSqlStmt
+= wxT(" FOR UPDATE");
1156 } // wxDbTable::BuildSelectStmt()
1159 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1160 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1162 wxString tempSqlStmt
;
1163 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1164 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1165 } // wxDbTable::BuildSelectStmt()
1168 /********** wxDbTable::BuildUpdateStmt() **********/
1169 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1171 wxASSERT(!queryOnly
);
1175 wxString whereClause
;
1176 whereClause
.Empty();
1178 bool firstColumn
= TRUE
;
1180 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1181 pDb
->SQLTableName(tableName
.c_str()).c_str());
1183 // Append a list of columns to be updated
1185 for (i
= 0; i
< noCols
; i
++)
1187 // Only append Updateable columns
1188 if (colDefs
[i
].Updateable
)
1191 pSqlStmt
+= wxT(",");
1193 firstColumn
= FALSE
;
1195 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1196 // pSqlStmt += colDefs[i].ColName;
1197 pSqlStmt
+= wxT(" = ?");
1201 // Append the WHERE clause to the SQL UPDATE statement
1202 pSqlStmt
+= wxT(" WHERE ");
1205 case DB_UPD_KEYFIELDS
:
1206 // If the datasource supports the ROWID column, build
1207 // the where on ROWID for efficiency purposes.
1208 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1209 if (CanUpdByROWID())
1212 wxChar rowid
[wxDB_ROWID_LEN
+1];
1214 // Get the ROWID value. If not successful retreiving the ROWID,
1215 // simply fall down through the code and build the WHERE clause
1216 // based on the key fields.
1217 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1219 pSqlStmt
+= wxT("ROWID = '");
1221 pSqlStmt
+= wxT("'");
1225 // Unable to delete by ROWID, so build a WHERE
1226 // clause based on the keyfields.
1227 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1228 pSqlStmt
+= whereClause
;
1231 pSqlStmt
+= pWhereClause
;
1234 } // BuildUpdateStmt()
1237 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1238 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1240 wxString tempSqlStmt
;
1241 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1242 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1243 } // BuildUpdateStmt()
1246 /********** wxDbTable::BuildWhereClause() **********/
1247 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1248 const wxString
&qualTableName
, bool useLikeComparison
)
1250 * Note: BuildWhereClause() currently ignores timestamp columns.
1251 * They are not included as part of the where clause.
1254 bool moreThanOneColumn
= FALSE
;
1257 // Loop through the columns building a where clause as you go
1259 for (colNo
= 0; colNo
< noCols
; colNo
++)
1261 // Determine if this column should be included in the WHERE clause
1262 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNo
].KeyField
) ||
1263 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(colNo
))))
1265 // Skip over timestamp columns
1266 if (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
)
1268 // If there is more than 1 column, join them with the keyword "AND"
1269 if (moreThanOneColumn
)
1270 pWhereClause
+= wxT(" AND ");
1272 moreThanOneColumn
= TRUE
;
1274 // Concatenate where phrase for the column
1275 wxString tStr
= colDefs
[colNo
].ColName
;
1277 if (qualTableName
.Length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1279 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1280 pWhereClause
+= wxT(".");
1282 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNo
].ColName
);
1284 if (useLikeComparison
&& (colDefs
[colNo
].SqlCtype
== SQL_C_CHAR
))
1285 pWhereClause
+= wxT(" LIKE ");
1287 pWhereClause
+= wxT(" = ");
1289 switch(colDefs
[colNo
].SqlCtype
)
1292 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
);
1296 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNo
].PtrDataObj
));
1299 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNo
].PtrDataObj
));
1303 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNo
].PtrDataObj
));
1306 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNo
].PtrDataObj
));
1309 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
));
1312 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
));
1317 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1318 colNo
,colDefs
[colNo
].ColName
);
1319 wxFAIL_MSG(strMsg
.c_str());
1323 pWhereClause
+= colValue
;
1326 } // wxDbTable::BuildWhereClause()
1329 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1330 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1331 const wxString
&qualTableName
, bool useLikeComparison
)
1333 wxString tempSqlStmt
;
1334 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1335 wxStrcpy(pWhereClause
, tempSqlStmt
);
1336 } // wxDbTable::BuildWhereClause()
1339 /********** wxDbTable::GetRowNum() **********/
1340 UWORD
wxDbTable::GetRowNum(void)
1344 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1346 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1350 // Completed successfully
1351 return((UWORD
) rowNum
);
1353 } // wxDbTable::GetRowNum()
1356 /********** wxDbTable::CloseCursor() **********/
1357 bool wxDbTable::CloseCursor(HSTMT cursor
)
1359 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1360 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1362 // Completed successfully
1365 } // wxDbTable::CloseCursor()
1368 /********** wxDbTable::CreateTable() **********/
1369 bool wxDbTable::CreateTable(bool attemptDrop
)
1377 #ifdef DBDEBUG_CONSOLE
1378 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1382 if (attemptDrop
&& !DropTable())
1386 #ifdef DBDEBUG_CONSOLE
1387 for (i
= 0; i
< noCols
; i
++)
1389 // Exclude derived columns since they are NOT part of the base table
1390 if (colDefs
[i
].DerivedCol
)
1392 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1393 switch(colDefs
[i
].DbDataType
)
1395 case DB_DATA_TYPE_VARCHAR
:
1396 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1398 case DB_DATA_TYPE_INTEGER
:
1399 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1401 case DB_DATA_TYPE_FLOAT
:
1402 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1404 case DB_DATA_TYPE_DATE
:
1405 cout
<< pDb
->GetTypeInfDate().TypeName
;
1407 case DB_DATA_TYPE_BLOB
:
1408 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1415 // Build a CREATE TABLE string from the colDefs structure.
1416 bool needComma
= FALSE
;
1418 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1419 pDb
->SQLTableName(tableName
.c_str()).c_str());
1421 for (i
= 0; i
< noCols
; i
++)
1423 // Exclude derived columns since they are NOT part of the base table
1424 if (colDefs
[i
].DerivedCol
)
1428 sqlStmt
+= wxT(",");
1430 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1431 // sqlStmt += colDefs[i].ColName;
1432 sqlStmt
+= wxT(" ");
1434 switch(colDefs
[i
].DbDataType
)
1436 case DB_DATA_TYPE_VARCHAR
:
1437 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1439 case DB_DATA_TYPE_INTEGER
:
1440 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1442 case DB_DATA_TYPE_FLOAT
:
1443 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1445 case DB_DATA_TYPE_DATE
:
1446 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1448 case DB_DATA_TYPE_BLOB
:
1449 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1452 // For varchars, append the size of the string
1453 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1454 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1455 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1458 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1462 if (pDb
->Dbms() == dbmsDB2
||
1463 pDb
->Dbms() == dbmsMY_SQL
||
1464 pDb
->Dbms() == dbmsSYBASE_ASE
||
1465 pDb
->Dbms() == dbmsINTERBASE
||
1466 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1468 if (colDefs
[i
].KeyField
)
1470 sqlStmt
+= wxT(" NOT NULL");
1476 // If there is a primary key defined, include it in the create statement
1477 for (i
= j
= 0; i
< noCols
; i
++)
1479 if (colDefs
[i
].KeyField
)
1485 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1486 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1488 switch (pDb
->Dbms())
1492 case dbmsSYBASE_ASA
:
1493 case dbmsSYBASE_ASE
:
1496 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1497 sqlStmt
+= wxT(",PRIMARY KEY (");
1502 sqlStmt
+= wxT(",CONSTRAINT ");
1503 // DB2 is limited to 18 characters for index names
1504 if (pDb
->Dbms() == dbmsDB2
)
1506 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."));
1507 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1508 // sqlStmt += tableName.substr(0, 13);
1511 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1512 // sqlStmt += tableName;
1514 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1519 // List column name(s) of column(s) comprising the primary key
1520 for (i
= j
= 0; i
< noCols
; i
++)
1522 if (colDefs
[i
].KeyField
)
1524 if (j
++) // Multi part key, comma separate names
1525 sqlStmt
+= wxT(",");
1526 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1528 if (pDb
->Dbms() == dbmsMY_SQL
&&
1529 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1532 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1537 sqlStmt
+= wxT(")");
1539 if (pDb
->Dbms() == dbmsINFORMIX
||
1540 pDb
->Dbms() == dbmsSYBASE_ASA
||
1541 pDb
->Dbms() == dbmsSYBASE_ASE
)
1543 sqlStmt
+= wxT(" CONSTRAINT ");
1544 sqlStmt
+= pDb
->SQLTableName(tableName
);
1545 // sqlStmt += tableName;
1546 sqlStmt
+= wxT("_PIDX");
1549 // Append the closing parentheses for the create table statement
1550 sqlStmt
+= wxT(")");
1552 pDb
->WriteSqlLog(sqlStmt
);
1554 #ifdef DBDEBUG_CONSOLE
1555 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1558 // Execute the CREATE TABLE statement
1559 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1560 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1562 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1563 pDb
->RollbackTrans();
1568 // Commit the transaction and close the cursor
1569 if (!pDb
->CommitTrans())
1571 if (!CloseCursor(hstmt
))
1574 // Database table created successfully
1577 } // wxDbTable::CreateTable()
1580 /********** wxDbTable::DropTable() **********/
1581 bool wxDbTable::DropTable()
1583 // NOTE: This function returns TRUE if the Table does not exist, but
1584 // only for identified databases. Code will need to be added
1585 // below for any other databases when those databases are defined
1586 // to handle this situation consistently
1590 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1591 pDb
->SQLTableName(tableName
.c_str()).c_str());
1593 pDb
->WriteSqlLog(sqlStmt
);
1595 #ifdef DBDEBUG_CONSOLE
1596 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1599 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1600 if (retcode
!= SQL_SUCCESS
)
1602 // Check for "Base table not found" error and ignore
1603 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1604 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1605 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1607 // Check for product specific error codes
1608 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1609 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1610 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1611 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1613 pDb
->DispNextError();
1614 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1615 pDb
->RollbackTrans();
1616 // CloseCursor(hstmt);
1622 // Commit the transaction and close the cursor
1623 if (! pDb
->CommitTrans())
1625 if (! CloseCursor(hstmt
))
1629 } // wxDbTable::DropTable()
1632 /********** wxDbTable::CreateIndex() **********/
1633 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1634 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1638 // Drop the index first
1639 if (attemptDrop
&& !DropIndex(idxName
))
1642 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1643 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1644 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1645 // table was created, then months later you determine that an additional index while
1646 // give better performance, so you want to add an index).
1648 // The following block of code will modify the column definition to make the column be
1649 // defined with the "NOT NULL" qualifier.
1650 if (pDb
->Dbms() == dbmsMY_SQL
)
1655 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1659 // Find the column definition that has the ColName that matches the
1660 // index column name. We need to do this to get the DB_DATA_TYPE of
1661 // the index column, as MySQL's syntax for the ALTER column requires
1663 while (!found
&& (j
< this->noCols
))
1665 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1673 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1674 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1680 // retcode is not used
1681 wxODBC_ERRORS retcode
;
1682 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1683 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1684 // This line is just here for debug checking of the value
1685 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1696 pDb
->RollbackTrans();
1701 // Build a CREATE INDEX statement
1702 sqlStmt
= wxT("CREATE ");
1704 sqlStmt
+= wxT("UNIQUE ");
1706 sqlStmt
+= wxT("INDEX ");
1707 sqlStmt
+= pDb
->SQLTableName(idxName
);
1708 sqlStmt
+= wxT(" ON ");
1710 sqlStmt
+= pDb
->SQLTableName(tableName
);
1711 // sqlStmt += tableName;
1712 sqlStmt
+= wxT(" (");
1714 // Append list of columns making up index
1716 for (i
= 0; i
< noIdxCols
; i
++)
1718 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1719 // sqlStmt += pIdxDefs[i].ColName;
1721 // MySQL requires a key length on VARCHAR keys
1722 if ( pDb
->Dbms() == dbmsMY_SQL
)
1724 // Find the details on this column
1726 for ( j
= 0; j
< noCols
; ++j
)
1728 if ( wxStrcmp( pIdxDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1733 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1736 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1741 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1742 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1743 !(pDb
->Dbms() == dbmsPOSTGRES
))
1745 if (pIdxDefs
[i
].Ascending
)
1746 sqlStmt
+= wxT(" ASC");
1748 sqlStmt
+= wxT(" DESC");
1751 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1753 if ((i
+ 1) < noIdxCols
)
1754 sqlStmt
+= wxT(",");
1757 // Append closing parentheses
1758 sqlStmt
+= wxT(")");
1760 pDb
->WriteSqlLog(sqlStmt
);
1762 #ifdef DBDEBUG_CONSOLE
1763 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1766 // Execute the CREATE INDEX statement
1767 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1769 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1770 pDb
->RollbackTrans();
1775 // Commit the transaction and close the cursor
1776 if (! pDb
->CommitTrans())
1778 if (! CloseCursor(hstmt
))
1781 // Index Created Successfully
1784 } // wxDbTable::CreateIndex()
1787 /********** wxDbTable::DropIndex() **********/
1788 bool wxDbTable::DropIndex(const wxString
&idxName
)
1790 // NOTE: This function returns TRUE if the Index does not exist, but
1791 // only for identified databases. Code will need to be added
1792 // below for any other databases when those databases are defined
1793 // to handle this situation consistently
1797 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1798 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1799 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1800 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1801 pDb
->SQLTableName(tableName
.c_str()).c_str());
1802 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1803 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1804 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1805 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1806 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1807 pDb
->SQLTableName(idxName
.c_str()).c_str());
1809 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1810 pDb
->SQLTableName(idxName
.c_str()).c_str());
1812 pDb
->WriteSqlLog(sqlStmt
);
1814 #ifdef DBDEBUG_CONSOLE
1815 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1818 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1820 // Check for "Index not found" error and ignore
1821 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1822 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1824 // Check for product specific error codes
1825 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1826 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1827 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1828 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1829 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1830 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1831 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1834 pDb
->DispNextError();
1835 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1836 pDb
->RollbackTrans();
1843 // Commit the transaction and close the cursor
1844 if (! pDb
->CommitTrans())
1846 if (! CloseCursor(hstmt
))
1850 } // wxDbTable::DropIndex()
1853 /********** wxDbTable::SetOrderByColNums() **********/
1854 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1856 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1862 va_start(argptr
, first
); /* Initialize variable arguments. */
1863 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1865 // Make sure the passed in column number
1866 // is within the valid range of columns
1868 // Valid columns are 0 thru noCols-1
1869 if (colNo
>= noCols
|| colNo
< 0)
1876 tempStr
+= wxT(",");
1878 tempStr
+= colDefs
[colNo
].ColName
;
1879 colNo
= va_arg (argptr
, int);
1881 va_end (argptr
); /* Reset variable arguments. */
1883 SetOrderByClause(tempStr
);
1886 } // wxDbTable::SetOrderByColNums()
1889 /********** wxDbTable::Insert() **********/
1890 int wxDbTable::Insert(void)
1892 wxASSERT(!queryOnly
);
1893 if (queryOnly
|| !insertable
)
1898 // Insert the record by executing the already prepared insert statement
1900 retcode
=SQLExecute(hstmtInsert
);
1901 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1902 retcode
!= SQL_NEED_DATA
)
1904 // Check to see if integrity constraint was violated
1905 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1906 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1907 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1910 pDb
->DispNextError();
1911 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1915 if (retcode
== SQL_NEED_DATA
)
1918 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1919 while (retcode
== SQL_NEED_DATA
)
1921 // Find the parameter
1923 for (i
=0; i
< noCols
; i
++)
1925 if (colDefs
[i
].PtrDataObj
== pParmID
)
1927 // We found it. Store the parameter.
1928 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1929 if (retcode
!= SQL_SUCCESS
)
1931 pDb
->DispNextError();
1932 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1938 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1939 if (retcode
!= SQL_SUCCESS
&&
1940 retcode
!= SQL_SUCCESS_WITH_INFO
)
1942 // record was not inserted
1943 pDb
->DispNextError();
1944 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1950 // Record inserted into the datasource successfully
1953 } // wxDbTable::Insert()
1956 /********** wxDbTable::Update() **********/
1957 bool wxDbTable::Update(void)
1959 wxASSERT(!queryOnly
);
1965 // Build the SQL UPDATE statement
1966 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1968 pDb
->WriteSqlLog(sqlStmt
);
1970 #ifdef DBDEBUG_CONSOLE
1971 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1974 // Execute the SQL UPDATE statement
1975 return(execUpdate(sqlStmt
));
1977 } // wxDbTable::Update()
1980 /********** wxDbTable::Update(pSqlStmt) **********/
1981 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1983 wxASSERT(!queryOnly
);
1987 pDb
->WriteSqlLog(pSqlStmt
);
1989 return(execUpdate(pSqlStmt
));
1991 } // wxDbTable::Update(pSqlStmt)
1994 /********** wxDbTable::UpdateWhere() **********/
1995 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1997 wxASSERT(!queryOnly
);
2003 // Build the SQL UPDATE statement
2004 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2006 pDb
->WriteSqlLog(sqlStmt
);
2008 #ifdef DBDEBUG_CONSOLE
2009 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2012 // Execute the SQL UPDATE statement
2013 return(execUpdate(sqlStmt
));
2015 } // wxDbTable::UpdateWhere()
2018 /********** wxDbTable::Delete() **********/
2019 bool wxDbTable::Delete(void)
2021 wxASSERT(!queryOnly
);
2028 // Build the SQL DELETE statement
2029 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2031 pDb
->WriteSqlLog(sqlStmt
);
2033 // Execute the SQL DELETE statement
2034 return(execDelete(sqlStmt
));
2036 } // wxDbTable::Delete()
2039 /********** wxDbTable::DeleteWhere() **********/
2040 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2042 wxASSERT(!queryOnly
);
2049 // Build the SQL DELETE statement
2050 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2052 pDb
->WriteSqlLog(sqlStmt
);
2054 // Execute the SQL DELETE statement
2055 return(execDelete(sqlStmt
));
2057 } // wxDbTable::DeleteWhere()
2060 /********** wxDbTable::DeleteMatching() **********/
2061 bool wxDbTable::DeleteMatching(void)
2063 wxASSERT(!queryOnly
);
2070 // Build the SQL DELETE statement
2071 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2073 pDb
->WriteSqlLog(sqlStmt
);
2075 // Execute the SQL DELETE statement
2076 return(execDelete(sqlStmt
));
2078 } // wxDbTable::DeleteMatching()
2081 /********** wxDbTable::IsColNull() **********/
2082 bool wxDbTable::IsColNull(UWORD colNo
) const
2085 This logic is just not right. It would indicate TRUE
2086 if a numeric field were set to a value of 0.
2088 switch(colDefs[colNo].SqlCtype)
2091 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
2093 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
2095 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
2097 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2099 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2101 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
2103 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
2104 case SQL_C_TIMESTAMP:
2105 TIMESTAMP_STRUCT *pDt;
2106 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
2107 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2115 return (colDefs
[colNo
].Null
);
2116 } // wxDbTable::IsColNull()
2119 /********** wxDbTable::CanSelectForUpdate() **********/
2120 bool wxDbTable::CanSelectForUpdate(void)
2125 if (pDb
->Dbms() == dbmsMY_SQL
)
2128 if ((pDb
->Dbms() == dbmsORACLE
) ||
2129 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2134 } // wxDbTable::CanSelectForUpdate()
2137 /********** wxDbTable::CanUpdByROWID() **********/
2138 bool wxDbTable::CanUpdByROWID(void)
2141 * NOTE: Returning FALSE for now until this can be debugged,
2142 * as the ROWID is not getting updated correctly
2146 if (pDb->Dbms() == dbmsORACLE)
2151 } // wxDbTable::CanUpdByROWID()
2154 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2155 bool wxDbTable::IsCursorClosedOnCommit(void)
2157 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2162 } // wxDbTable::IsCursorClosedOnCommit()
2166 /********** wxDbTable::ClearMemberVar() **********/
2167 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2169 wxASSERT(colNo
< noCols
);
2171 switch(colDefs
[colNo
].SqlCtype
)
2174 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2177 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2180 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2183 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2186 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2189 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2192 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2194 case SQL_C_TIMESTAMP
:
2195 TIMESTAMP_STRUCT
*pDt
;
2196 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2209 } // wxDbTable::ClearMemberVar()
2212 /********** wxDbTable::ClearMemberVars() **********/
2213 void wxDbTable::ClearMemberVars(bool setToNull
)
2217 // Loop through the columns setting each member variable to zero
2218 for (i
=0; i
< noCols
; i
++)
2219 ClearMemberVar(i
,setToNull
);
2221 } // wxDbTable::ClearMemberVars()
2224 /********** wxDbTable::SetQueryTimeout() **********/
2225 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2227 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2228 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2229 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2230 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2231 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2232 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2233 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2234 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2236 // Completed Successfully
2239 } // wxDbTable::SetQueryTimeout()
2242 /********** wxDbTable::SetColDefs() **********/
2243 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2244 SWORD cType
, int size
, bool keyField
, bool upd
,
2245 bool insAllow
, bool derivedCol
)
2247 wxASSERT_MSG( index
< noCols
,
2248 _T("Specified column index exceeds the maximum number of columns for this table.") );
2250 if (!colDefs
) // May happen if the database connection fails
2253 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2255 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2256 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2260 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2261 fieldName
.c_str(),colDefs
[index
].ColName
);
2263 #endif // __WXDEBUG__
2266 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2268 colDefs
[index
].DbDataType
= dataType
;
2269 colDefs
[index
].PtrDataObj
= pData
;
2270 colDefs
[index
].SqlCtype
= cType
;
2271 colDefs
[index
].SzDataObj
= size
;
2272 colDefs
[index
].KeyField
= keyField
;
2273 colDefs
[index
].DerivedCol
= derivedCol
;
2274 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2277 colDefs
[index
].Updateable
= FALSE
;
2278 colDefs
[index
].InsertAllowed
= FALSE
;
2282 colDefs
[index
].Updateable
= upd
;
2283 colDefs
[index
].InsertAllowed
= insAllow
;
2286 colDefs
[index
].Null
= FALSE
;
2288 } // wxDbTable::SetColDefs()
2291 /********** wxDbTable::SetColDefs() **********/
2292 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2295 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2301 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2303 for (index
= 0; index
< numCols
; index
++)
2305 // Process the fields
2306 switch (pColInfs
[index
].dbDataType
)
2308 case DB_DATA_TYPE_VARCHAR
:
2309 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2310 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2311 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2313 case DB_DATA_TYPE_INTEGER
:
2314 // Can be long or short
2315 if (pColInfs
[index
].bufferLength
== sizeof(long))
2317 pColDataPtrs
[index
].PtrDataObj
= new long;
2318 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2319 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2323 pColDataPtrs
[index
].PtrDataObj
= new short;
2324 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2325 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2328 case DB_DATA_TYPE_FLOAT
:
2329 // Can be float or double
2330 if (pColInfs
[index
].bufferLength
== sizeof(float))
2332 pColDataPtrs
[index
].PtrDataObj
= new float;
2333 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2334 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2338 pColDataPtrs
[index
].PtrDataObj
= new double;
2339 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2340 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2343 case DB_DATA_TYPE_DATE
:
2344 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2345 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2346 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2348 case DB_DATA_TYPE_BLOB
:
2349 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2350 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2351 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2352 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2355 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2356 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2359 // Unable to build all the column definitions, as either one of
2360 // the calls to "new" failed above, or there was a BLOB field
2361 // to have a column definition for. If BLOBs are to be used,
2362 // the other form of ::SetColDefs() must be used, as it is impossible
2363 // to know the maximum size to create the PtrDataObj to be.
2364 delete [] pColDataPtrs
;
2370 return (pColDataPtrs
);
2372 } // wxDbTable::SetColDefs()
2375 /********** wxDbTable::SetCursor() **********/
2376 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2378 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2379 hstmt
= *hstmtDefault
;
2381 hstmt
= *hstmtActivate
;
2383 } // wxDbTable::SetCursor()
2386 /********** wxDbTable::Count(const wxString &) **********/
2387 ULONG
wxDbTable::Count(const wxString
&args
)
2393 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2394 sqlStmt
= wxT("SELECT COUNT(");
2396 sqlStmt
+= wxT(") FROM ");
2397 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2398 // sqlStmt += queryTableName;
2399 #if wxODBC_BACKWARD_COMPATABILITY
2400 if (from
&& wxStrlen(from
))
2406 // Add the where clause if one is provided
2407 #if wxODBC_BACKWARD_COMPATABILITY
2408 if (where
&& wxStrlen(where
))
2413 sqlStmt
+= wxT(" WHERE ");
2417 pDb
->WriteSqlLog(sqlStmt
);
2419 // Initialize the Count cursor if it's not already initialized
2422 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2423 wxASSERT(hstmtCount
);
2428 // Execute the SQL statement
2429 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2431 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2436 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2438 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2442 // Obtain the result
2443 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2445 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2450 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2451 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2453 // Return the record count
2456 } // wxDbTable::Count()
2459 /********** wxDbTable::Refresh() **********/
2460 bool wxDbTable::Refresh(void)
2464 // Switch to the internal cursor so any active cursors are not corrupted
2465 HSTMT currCursor
= GetCursor();
2466 hstmt
= hstmtInternal
;
2467 #if wxODBC_BACKWARD_COMPATABILITY
2468 // Save the where and order by clauses
2469 wxChar
*saveWhere
= where
;
2470 wxChar
*saveOrderBy
= orderBy
;
2472 wxString saveWhere
= where
;
2473 wxString saveOrderBy
= orderBy
;
2475 // Build a where clause to refetch the record with. Try and use the
2476 // ROWID if it's available, ow use the key fields.
2477 wxString whereClause
;
2478 whereClause
.Empty();
2480 if (CanUpdByROWID())
2483 wxChar rowid
[wxDB_ROWID_LEN
+1];
2485 // Get the ROWID value. If not successful retreiving the ROWID,
2486 // simply fall down through the code and build the WHERE clause
2487 // based on the key fields.
2488 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2490 whereClause
+= pDb
->SQLTableName(queryTableName
);
2491 // whereClause += queryTableName;
2492 whereClause
+= wxT(".ROWID = '");
2493 whereClause
+= rowid
;
2494 whereClause
+= wxT("'");
2498 // If unable to use the ROWID, build a where clause from the keyfields
2499 if (wxStrlen(whereClause
) == 0)
2500 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2502 // Requery the record
2503 where
= whereClause
;
2508 if (result
&& !GetNext())
2511 // Switch back to original cursor
2512 SetCursor(&currCursor
);
2514 // Free the internal cursor
2515 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2516 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2518 // Restore the original where and order by clauses
2520 orderBy
= saveOrderBy
;
2524 } // wxDbTable::Refresh()
2527 /********** wxDbTable::SetColNull() **********/
2528 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2532 colDefs
[colNo
].Null
= set
;
2533 if (set
) // Blank out the values in the member variable
2534 ClearMemberVar(colNo
, FALSE
); // Must call with FALSE here, or infinite recursion will happen
2536 setCbValueForColumn(colNo
);
2543 } // wxDbTable::SetColNull()
2546 /********** wxDbTable::SetColNull() **********/
2547 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2550 for (colNo
= 0; colNo
< noCols
; colNo
++)
2552 if (!wxStricmp(colName
, colDefs
[colNo
].ColName
))
2558 colDefs
[colNo
].Null
= set
;
2559 if (set
) // Blank out the values in the member variable
2560 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE here, or infinite recursion will happen
2562 setCbValueForColumn(colNo
);
2569 } // wxDbTable::SetColNull()
2572 /********** wxDbTable::GetNewCursor() **********/
2573 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2575 HSTMT
*newHSTMT
= new HSTMT
;
2580 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2582 pDb
->DispAllErrors(henv
, hdbc
);
2587 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2589 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2596 if (!bindCols(*newHSTMT
))
2604 SetCursor(newHSTMT
);
2608 } // wxDbTable::GetNewCursor()
2611 /********** wxDbTable::DeleteCursor() **********/
2612 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2616 if (!hstmtDel
) // Cursor already deleted
2620 ODBC 3.0 says to use this form
2621 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2624 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2626 pDb
->DispAllErrors(henv
, hdbc
);
2634 } // wxDbTable::DeleteCursor()
2636 //////////////////////////////////////////////////////////////
2637 // wxDbGrid support functions
2638 //////////////////////////////////////////////////////////////
2640 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2642 if (!m_hstmtGridQuery
)
2644 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2645 if (!bindCols(*m_hstmtGridQuery
))
2649 m_rowmode
= rowmode
;
2652 case WX_ROW_MODE_QUERY
:
2653 SetCursor(m_hstmtGridQuery
);
2655 case WX_ROW_MODE_INDIVIDUAL
:
2656 SetCursor(hstmtDefault
);
2661 } // wxDbTable::SetRowMode()
2664 wxVariant
wxDbTable::GetCol(const int colNo
) const
2667 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2669 switch (colDefs
[colNo
].SqlCtype
)
2673 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2677 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2681 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2684 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2687 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2689 case SQL_C_UTINYINT
:
2690 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2693 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2696 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2699 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2701 case SQL_C_TIMESTAMP
:
2702 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2705 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2712 } // wxDbTable::GetCol()
2715 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2717 //FIXME: Add proper wxDateTime support to wxVariant..
2720 SetColNull(colNo
, val
.IsNull());
2724 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2725 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2726 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2728 //Returns null if invalid!
2729 if (!dateval
.ParseDate(val
.GetString()))
2730 SetColNull(colNo
, TRUE
);
2733 switch (colDefs
[colNo
].SqlCtype
)
2737 csstrncpyt((wxChar
*)(colDefs
[colNo
].PtrDataObj
),
2738 val
.GetString().c_str(),
2739 colDefs
[colNo
].SzDataObj
-1);
2743 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2747 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2750 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2753 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2755 case SQL_C_UTINYINT
:
2756 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2759 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2761 //FIXME: Add proper wxDateTime support to wxVariant..
2764 DATE_STRUCT
*dataptr
=
2765 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2767 dataptr
->year
= dateval
.GetYear();
2768 dataptr
->month
= dateval
.GetMonth()+1;
2769 dataptr
->day
= dateval
.GetDay();
2774 TIME_STRUCT
*dataptr
=
2775 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2777 dataptr
->hour
= dateval
.GetHour();
2778 dataptr
->minute
= dateval
.GetMinute();
2779 dataptr
->second
= dateval
.GetSecond();
2782 case SQL_C_TIMESTAMP
:
2784 TIMESTAMP_STRUCT
*dataptr
=
2785 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2786 dataptr
->year
= dateval
.GetYear();
2787 dataptr
->month
= dateval
.GetMonth()+1;
2788 dataptr
->day
= dateval
.GetDay();
2790 dataptr
->hour
= dateval
.GetHour();
2791 dataptr
->minute
= dateval
.GetMinute();
2792 dataptr
->second
= dateval
.GetSecond();
2796 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2801 } // if (!val.IsNull())
2802 } // wxDbTable::SetCol()
2805 GenericKey
wxDbTable::GetKey()
2810 blk
= malloc(m_keysize
);
2811 blkptr
= (wxChar
*) blk
;
2814 for (i
=0; i
< noCols
; i
++)
2816 if (colDefs
[i
].KeyField
)
2818 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2819 blkptr
+= colDefs
[i
].SzDataObj
;
2823 GenericKey k
= GenericKey(blk
, m_keysize
);
2827 } // wxDbTable::GetKey()
2830 void wxDbTable::SetKey(const GenericKey
& k
)
2836 blkptr
= (wxChar
*)blk
;
2839 for (i
=0; i
< noCols
; i
++)
2841 if (colDefs
[i
].KeyField
)
2843 SetColNull(i
, FALSE
);
2844 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2845 blkptr
+= colDefs
[i
].SzDataObj
;
2848 } // wxDbTable::SetKey()
2851 #endif // wxUSE_ODBC