1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxTable class.
5 // Modified by: George Tasker
7 // -Dynamic cursor support - Only one predefined cursor, as many others as
8 // you need may be created on demand
9 // -Reduced number of active cursors significantly
10 // -Query-Only wxTable objects
13 // Copyright: (c) 1996 Remstar International, Inc.
14 // Licence: wxWindows licence, plus:
15 // Notice: This class library and its intellectual design are free of charge for use,
16 // modification, enhancement, debugging under the following conditions:
17 // 1) These classes may only be used as part of the implementation of a
18 // wxWindows-based application
19 // 2) All enhancements and bug fixes are to be submitted back to the wxWindows
20 // user groups free of all charges for use with the wxWindows library.
21 // 3) These classes may not be distributed as part of any other class library,
22 // DLL, text (written or electronic), other than a complete distribution of
23 // the wxWindows GUI development toolkit.
24 ///////////////////////////////////////////////////////////////////////////////
31 // Use this line for wxWindows v1.x
33 // Use this line for wxWindows v2.x
34 #include "wx/version.h"
35 #include "wx/wxprec.h"
37 #if wxMAJOR_VERSION == 2
39 # pragma implementation "dbtable.h"
43 #ifdef DBDEBUG_CONSOLE
44 #include "wx/ioswrap.h"
51 #if wxMAJOR_VERSION == 2
53 #include "wx/string.h"
54 #include "wx/object.h"
57 #include "wx/msgdlg.h"
59 #include "wx/filefn.h"
62 #if wxMAJOR_VERSION == 1
63 # if defined(wx_msw) || defined(wx_x)
80 #if wxMAJOR_VERSION == 1
82 #elif wxMAJOR_VERSION == 2
83 #include "wx/dbtable.h"
87 // The HPUX preprocessor lines below were commented out on 8/20/97
88 // because macros.h currently redefines DEBUG and is unneeded.
90 // # include <macros.h>
93 # include <sys/minmax.h>
97 ULONG lastTableID
= 0;
105 /********** wxTable::wxTable() **********/
106 wxTable::wxTable(wxDB
*pwxDB
, const char *tblName
, const int nCols
,
107 const char *qryTblName
, bool qryOnly
, const char *tblPath
)
109 pDb
= pwxDB
; // Pointer to the wxDB object
113 hstmtDefault
= 0; // Initialized below
114 hstmtCount
= 0; // Initialized first time it is needed
121 noCols
= nCols
; // No. of cols in the table
122 where
= 0; // Where clause
123 orderBy
= 0; // Order By clause
124 from
= 0; // From clause
125 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
130 wxStrcpy(tableName
, tblName
); // Table Name
132 wxStrcpy(tablePath
, tblPath
); // Table Path - used for dBase files
134 if (qryTblName
) // Name of the table/view to query
135 wxStrcpy(queryTableName
, qryTblName
);
137 wxStrcpy(queryTableName
, tblName
);
145 tableID
= ++lastTableID
;
146 s
.sprintf("wxTable constructor (%-20s) tableID:[%6lu] pDb:[%p]", tblName
,tableID
,pDb
);
149 CstructTablesInUse
*tableInUse
;
150 tableInUse
= new CstructTablesInUse();
151 tableInUse
->tableName
= tblName
;
152 tableInUse
->tableID
= tableID
;
153 tableInUse
->pDb
= pDb
;
154 TablesInUse
.Append(tableInUse
);
157 pDb
->WriteSqlLog(s
.GetData());
159 // Grab the HENV and HDBC from the wxDB object
163 // Allocate space for column definitions
165 colDefs
= new wxColDef
[noCols
]; // Points to the first column defintion
167 // Allocate statement handles for the table
170 // Allocate a separate statement handle for performing inserts
171 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
172 pDb
->DispAllErrors(henv
, hdbc
);
173 // Allocate a separate statement handle for performing deletes
174 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
175 pDb
->DispAllErrors(henv
, hdbc
);
176 // Allocate a separate statement handle for performing updates
177 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
178 pDb
->DispAllErrors(henv
, hdbc
);
180 // Allocate a separate statement handle for internal use
181 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
182 pDb
->DispAllErrors(henv
, hdbc
);
184 // Set the cursor type for the statement handles
185 cursorType
= SQL_CURSOR_STATIC
;
186 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
188 // Check to see if cursor type is supported
189 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
190 if (! wxStrcmp(pDb
->sqlState
, "01S02")) // Option Value Changed
192 // Datasource does not support static cursors. Driver
193 // will substitute a cursor type. Call SQLGetStmtOption()
194 // to determine which cursor type was selected.
195 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
196 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
197 #ifdef DBDEBUG_CONSOLE
198 cout
<< "Static cursor changed to: ";
201 case SQL_CURSOR_FORWARD_ONLY
:
202 cout
<< "Forward Only"; break;
203 case SQL_CURSOR_STATIC
:
204 cout
<< "Static"; break;
205 case SQL_CURSOR_KEYSET_DRIVEN
:
206 cout
<< "Keyset Driven"; break;
207 case SQL_CURSOR_DYNAMIC
:
208 cout
<< "Dynamic"; break;
210 cout
<< endl
<< endl
;
215 pDb
->DispNextError();
216 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
219 #ifdef DBDEBUG_CONSOLE
221 cout
<< "Cursor Type set to STATIC" << endl
<< endl
;
226 // Set the cursor type for the INSERT statement handle
227 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
228 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
229 // Set the cursor type for the DELETE statement handle
230 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
231 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
232 // Set the cursor type for the UPDATE statement handle
233 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
234 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
237 // Make the default cursor the active cursor
238 hstmtDefault
= NewCursor(FALSE
,FALSE
);
239 assert(hstmtDefault
);
240 hstmt
= *hstmtDefault
;
242 } // wxTable::wxTable()
245 /********** wxTable::~wxTable() **********/
251 s
.sprintf("wxTable destructor (%-20s) tableID:[%6lu] pDb:[%p]", tableName
,tableID
,pDb
);
252 pDb
->WriteSqlLog(s
.GetData());
258 TablesInUse
.DeleteContents(TRUE
);
262 pNode
= TablesInUse
.First();
263 while (pNode
&& !found
)
265 if (((CstructTablesInUse
*)pNode
->Data())->tableID
== tableID
)
268 if (!TablesInUse
.DeleteNode(pNode
))
269 wxLogDebug (s
.GetData(),"Unable to delete node!");
272 pNode
= pNode
->Next();
277 msg
.sprintf("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s",s
.GetData());
278 wxLogDebug (msg
.GetData(),"NOTICE...");
285 // Decrement the wxDB table count
289 // Delete memory allocated for column definitions
293 // Free statement handles
297 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
298 pDb
->DispAllErrors(henv
, hdbc
);
301 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
304 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
305 pDb
->DispAllErrors(henv
, hdbc
);
309 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
310 pDb
->DispAllErrors(henv
, hdbc
);
312 // Delete dynamically allocated cursors
314 DeleteCursor(hstmtDefault
);
317 DeleteCursor(hstmtCount
);
320 } // wxTable::~wxTable()
324 /***************************** PRIVATE FUNCTIONS *****************************/
328 /********** wxTable::bindInsertParams() **********/
329 bool wxTable::bindInsertParams(void)
336 UDWORD precision
= 0;
339 // Bind each column (that can be inserted) of the table to a parameter marker
341 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
343 if (! colDefs
[i
].InsertAllowed
)
345 switch(colDefs
[i
].DbDataType
)
347 case DB_DATA_TYPE_VARCHAR
:
348 fSqlType
= pDb
->typeInfVarchar
.FsqlType
;
349 precision
= colDefs
[i
].SzDataObj
;
351 colDefs
[i
].CbValue
= SQL_NTS
;
353 case DB_DATA_TYPE_INTEGER
:
354 fSqlType
= pDb
->typeInfInteger
.FsqlType
;
355 precision
= pDb
->typeInfInteger
.Precision
;
357 colDefs
[i
].CbValue
= 0;
359 case DB_DATA_TYPE_FLOAT
:
360 fSqlType
= pDb
->typeInfFloat
.FsqlType
;
361 precision
= pDb
->typeInfFloat
.Precision
;
362 scale
= pDb
->typeInfFloat
.MaximumScale
;
363 // SQL Sybase Anywhere v5.5 returned a negative number for the
364 // MaxScale. This caused ODBC to kick out an error on ibscale.
365 // I check for this here and set the scale = precision.
367 // scale = (short) precision;
368 colDefs
[i
].CbValue
= 0;
370 case DB_DATA_TYPE_DATE
:
371 fSqlType
= pDb
->typeInfDate
.FsqlType
;
372 precision
= pDb
->typeInfDate
.Precision
;
374 colDefs
[i
].CbValue
= 0;
380 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
381 colDefs
[i
].Null
= FALSE
;
383 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
384 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
385 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
386 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
389 // Completed successfully
392 } // wxTable::bindInsertParams()
395 /********** wxTable::bindUpdateParams() **********/
396 bool wxTable::bindUpdateParams(void)
403 UDWORD precision
= 0;
406 // Bind each UPDATEABLE column of the table to a parameter marker
408 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
410 if (! colDefs
[i
].Updateable
)
412 switch(colDefs
[i
].DbDataType
)
414 case DB_DATA_TYPE_VARCHAR
:
415 fSqlType
= pDb
->typeInfVarchar
.FsqlType
;
416 precision
= colDefs
[i
].SzDataObj
;
418 colDefs
[i
].CbValue
= SQL_NTS
;
420 case DB_DATA_TYPE_INTEGER
:
421 fSqlType
= pDb
->typeInfInteger
.FsqlType
;
422 precision
= pDb
->typeInfInteger
.Precision
;
424 colDefs
[i
].CbValue
= 0;
426 case DB_DATA_TYPE_FLOAT
:
427 fSqlType
= pDb
->typeInfFloat
.FsqlType
;
428 precision
= pDb
->typeInfFloat
.Precision
;
429 scale
= pDb
->typeInfFloat
.MaximumScale
;
430 // SQL Sybase Anywhere v5.5 returned a negative number for the
431 // MaxScale. This caused ODBC to kick out an error on ibscale.
432 // I check for this here and set the scale = precision.
434 // scale = (short) precision;
435 colDefs
[i
].CbValue
= 0;
437 case DB_DATA_TYPE_DATE
:
438 fSqlType
= pDb
->typeInfDate
.FsqlType
;
439 precision
= pDb
->typeInfDate
.Precision
;
441 colDefs
[i
].CbValue
= 0;
444 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
445 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
446 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
447 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
450 // Completed successfully
453 } // wxTable::bindUpdateParams()
456 /********** wxTable::bindCols() **********/
457 bool wxTable::bindCols(HSTMT cursor
)
461 // Bind each column of the table to a memory address for fetching data
463 for (i
= 0; i
< noCols
; i
++)
465 if (SQLBindCol(cursor
, i
+1, colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
466 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
467 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
470 // Completed successfully
473 } // wxTable::bindCols()
476 /********** wxTable::getRec() **********/
477 bool wxTable::getRec(UWORD fetchType
)
481 if (!pDb
->FwdOnlyCursors())
483 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
487 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
488 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
489 if (retcode
== SQL_NO_DATA_FOUND
)
492 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
496 // Fetch the next record from the record set
497 retcode
= SQLFetch(hstmt
);
498 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
500 if (retcode
== SQL_NO_DATA_FOUND
)
503 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
507 // Completed successfully
510 } // wxTable::getRec()
513 /********** wxTable::execDelete() **********/
514 bool wxTable::execDelete(const char *pSqlStmt
)
516 // Execute the DELETE statement
517 if (SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
, SQL_NTS
) != SQL_SUCCESS
)
518 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
520 // Record deleted successfully
523 } // wxTable::execDelete()
526 /********** wxTable::execUpdate() **********/
527 bool wxTable::execUpdate(const char *pSqlStmt
)
529 // Execute the UPDATE statement
530 if (SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
, SQL_NTS
) != SQL_SUCCESS
)
531 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
533 // Record deleted successfully
536 } // wxTable::execUpdate()
539 /********** wxTable::query() **********/
540 bool wxTable::query(int queryType
, bool forUpdate
, bool distinct
, char *pSqlStmt
)
542 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
544 // Set the selectForUpdate member variable
546 // The user may wish to select for update, but the DBMS may not be capable
547 selectForUpdate
= CanSelectForUpdate();
549 selectForUpdate
= FALSE
;
551 // Set the SQL SELECT string
552 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
553 { // so generate a select statement.
554 GetSelectStmt(sqlStmt
, queryType
, distinct
);
555 pDb
->WriteSqlLog(sqlStmt
);
558 // Make sure the cursor is closed first
559 if (! CloseCursor(hstmt
))
562 // Execute the SQL SELECT statement
565 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
: sqlStmt
), SQL_NTS
);
566 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
567 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
569 // Completed successfully
572 } // wxTable::query()
575 /***************************** PUBLIC FUNCTIONS *****************************/
578 /********** wxTable::Open() **********/
579 bool wxTable::Open(void)
587 // Verify that the table exists in the database
588 if (!pDb
->TableExists(tableName
,pDb
->GetUsername(),tablePath
))
591 if (wxStrcmp(tablePath
,""))
592 s
.sprintf("Error opening '%s/%s'.\n",tablePath
,tableName
);
594 s
.sprintf("Error opening '%s'.\n", tableName
);
595 if (!pDb
->TableExists(tableName
,NULL
,tablePath
))
596 s
+= "Table/view does not exist in the database.\n";
598 s
+= "Current logged in user does not have sufficient privileges to access this table.\n";
599 pDb
->LogError(s
.GetData());
603 // Bind the member variables for field exchange between
604 // the wxTable object and the ODBC record.
607 if (!bindInsertParams()) // Inserts
609 if (!bindUpdateParams()) // Updates
612 if (!bindCols(*hstmtDefault
)) // Selects
614 if (!bindCols(hstmtInternal
)) // Internal use only
617 * Do NOT bind the hstmtCount cursor!!!
620 // Build an insert statement using parameter markers
621 if (!queryOnly
&& noCols
> 0)
623 bool needComma
= FALSE
;
624 sqlStmt
.sprintf("INSERT INTO %s (", tableName
);
625 for (i
= 0; i
< noCols
; i
++)
627 if (! colDefs
[i
].InsertAllowed
)
631 sqlStmt
+= colDefs
[i
].ColName
;
635 sqlStmt
+= ") VALUES (";
636 for (i
= 0; i
< noCols
; i
++)
638 if (! colDefs
[i
].InsertAllowed
)
647 // pDb->WriteSqlLog(sqlStmt);
649 // Prepare the insert statement for execution
650 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
651 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
654 // Completed successfully
660 /********** wxTable::Query() **********/
661 bool wxTable::Query(bool forUpdate
, bool distinct
)
664 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
666 } // wxTable::Query()
669 /********** wxTable::QueryBySqlStmt() **********/
670 bool wxTable::QueryBySqlStmt(char *pSqlStmt
)
672 pDb
->WriteSqlLog(pSqlStmt
);
674 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
676 } // wxTable::QueryBySqlStmt()
679 /********** wxTable::QueryMatching() **********/
680 bool wxTable::QueryMatching(bool forUpdate
, bool distinct
)
683 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
685 } // wxTable::QueryMatching()
688 /********** wxTable::QueryOnKeyFields() **********/
689 bool wxTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
692 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
694 } // wxTable::QueryOnKeyFields()
697 /********** wxTable::GetPrev() **********/
698 bool wxTable::GetPrev(void)
700 if (pDb
->FwdOnlyCursors())
702 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxTable"));
706 return(getRec(SQL_FETCH_PRIOR
));
707 } // wxTable::GetPrev()
710 /********** wxTable::operator-- **********/
711 bool wxTable::operator--(int)
713 if (pDb
->FwdOnlyCursors())
715 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxTable"));
719 return(getRec(SQL_FETCH_PRIOR
));
720 } // wxTable::operator--
723 /********** wxTable::GetFirst() **********/
724 bool wxTable::GetFirst(void)
726 if (pDb
->FwdOnlyCursors())
728 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxTable"));
732 return(getRec(SQL_FETCH_FIRST
));
733 } // wxTable::GetFirst()
736 /********** wxTable::GetLast() **********/
737 bool wxTable::GetLast(void)
739 if (pDb
->FwdOnlyCursors())
741 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxTable"));
745 return(getRec(SQL_FETCH_LAST
));
746 } // wxTable::GetLast()
749 /********** wxTable::GetSelectStmt() **********/
750 void wxTable::GetSelectStmt(char *pSqlStmt
, int typeOfSelect
, bool distinct
)
752 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
756 // Build a select statement to query the database
757 wxStrcpy(pSqlStmt
, "SELECT ");
759 // SELECT DISTINCT values only?
761 wxStrcat(pSqlStmt
, "DISTINCT ");
763 // Was a FROM clause specified to join tables to the base table?
764 // Available for ::Query() only!!!
765 bool appendFromClause
= FALSE
;
766 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
767 appendFromClause
= TRUE
;
769 // Add the column list
771 for (i
= 0; i
< noCols
; i
++)
773 // If joining tables, the base table column names must be qualified to avoid ambiguity
774 if (appendFromClause
)
776 wxStrcat(pSqlStmt
, queryTableName
);
777 wxStrcat(pSqlStmt
, ".");
779 wxStrcat(pSqlStmt
, colDefs
[i
].ColName
);
781 wxStrcat(pSqlStmt
, ",");
784 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
785 // the ROWID if querying distinct records. The rowid will always be unique.
786 if (!distinct
&& CanUpdByROWID())
788 // If joining tables, the base table column names must be qualified to avoid ambiguity
789 if (appendFromClause
)
791 wxStrcat(pSqlStmt
, ",");
792 wxStrcat(pSqlStmt
, queryTableName
);
793 wxStrcat(pSqlStmt
, ".ROWID");
796 wxStrcat(pSqlStmt
, ",ROWID");
799 // Append the FROM tablename portion
800 wxStrcat(pSqlStmt
, " FROM ");
801 wxStrcat(pSqlStmt
, queryTableName
);
803 // Sybase uses the HOLDLOCK keyword to lock a record during query.
804 // The HOLDLOCK keyword follows the table name in the from clause.
805 // Each table in the from clause must specify HOLDLOCK or
806 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
807 // is parsed but ignored in SYBASE Transact-SQL.
808 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
809 wxStrcat(pSqlStmt
, " HOLDLOCK");
811 if (appendFromClause
)
812 wxStrcat(pSqlStmt
, from
);
814 // Append the WHERE clause. Either append the where clause for the class
815 // or build a where clause. The typeOfSelect determines this.
818 case DB_SELECT_WHERE
:
819 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
821 wxStrcat(pSqlStmt
, " WHERE ");
822 wxStrcat(pSqlStmt
, where
);
825 case DB_SELECT_KEYFIELDS
:
826 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
827 if (wxStrlen(whereClause
))
829 wxStrcat(pSqlStmt
, " WHERE ");
830 wxStrcat(pSqlStmt
, whereClause
);
833 case DB_SELECT_MATCHING
:
834 GetWhereClause(whereClause
, DB_WHERE_MATCHING
);
835 if (wxStrlen(whereClause
))
837 wxStrcat(pSqlStmt
, " WHERE ");
838 wxStrcat(pSqlStmt
, whereClause
);
843 // Append the ORDER BY clause
844 if (orderBy
&& wxStrlen(orderBy
))
846 wxStrcat(pSqlStmt
, " ORDER BY ");
847 wxStrcat(pSqlStmt
, orderBy
);
850 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
851 // parses the FOR UPDATE clause but ignores it. See the comment above on the
852 // HOLDLOCK for Sybase.
853 if (selectForUpdate
&& CanSelectForUpdate())
854 wxStrcat(pSqlStmt
, " FOR UPDATE");
856 } // wxTable::GetSelectStmt()
859 /********** wxTable::GetRowNum() **********/
860 UWORD
wxTable::GetRowNum(void)
864 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
866 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
870 // Completed successfully
871 return((UWORD
) rowNum
);
873 } // wxTable::GetRowNum()
876 /********** wxTable::CloseCursor() **********/
877 bool wxTable::CloseCursor(HSTMT cursor
)
879 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
880 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
882 // Completed successfully
885 } // wxTable::CloseCursor()
888 /********** wxTable::CreateTable() **********/
889 bool wxTable::CreateTable(bool attemptDrop
)
895 // char sqlStmt[DB_MAX_STATEMENT_LEN];
898 #ifdef DBDEBUG_CONSOLE
899 cout
<< "Creating Table " << tableName
<< "..." << endl
;
903 if (attemptDrop
&& !DropTable())
907 #ifdef DBDEBUG_CONSOLE
908 for (i
= 0; i
< noCols
; i
++)
910 // Exclude derived columns since they are NOT part of the base table
911 if (colDefs
[i
].DerivedCol
)
913 cout
<< i
+ 1 << ": " << colDefs
[i
].ColName
<< "; ";
914 switch(colDefs
[i
].DbDataType
)
916 case DB_DATA_TYPE_VARCHAR
:
917 cout
<< pDb
->typeInfVarchar
.TypeName
<< "(" << colDefs
[i
].SzDataObj
<< ")";
919 case DB_DATA_TYPE_INTEGER
:
920 cout
<< pDb
->typeInfInteger
.TypeName
;
922 case DB_DATA_TYPE_FLOAT
:
923 cout
<< pDb
->typeInfFloat
.TypeName
;
925 case DB_DATA_TYPE_DATE
:
926 cout
<< pDb
->typeInfDate
.TypeName
;
933 // Build a CREATE TABLE string from the colDefs structure.
934 bool needComma
= FALSE
;
935 sqlStmt
.sprintf("CREATE TABLE %s (", tableName
);
937 for (i
= 0; i
< noCols
; i
++)
939 // Exclude derived columns since they are NOT part of the base table
940 if (colDefs
[i
].DerivedCol
)
946 sqlStmt
+= colDefs
[i
].ColName
;
949 switch(colDefs
[i
].DbDataType
)
951 case DB_DATA_TYPE_VARCHAR
:
952 sqlStmt
+= pDb
->typeInfVarchar
.TypeName
; break;
953 case DB_DATA_TYPE_INTEGER
:
954 sqlStmt
+= pDb
->typeInfInteger
.TypeName
; break;
955 case DB_DATA_TYPE_FLOAT
:
956 sqlStmt
+= pDb
->typeInfFloat
.TypeName
; break;
957 case DB_DATA_TYPE_DATE
:
958 sqlStmt
+= pDb
->typeInfDate
.TypeName
; break;
960 // For varchars, append the size of the string
961 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
964 // wxStrcat(sqlStmt, "(");
965 // wxStrcat(sqlStmt, itoa(colDefs[i].SzDataObj, s, 10));
966 // wxStrcat(sqlStmt, ")");
967 s
.sprintf("(%d)", colDefs
[i
].SzDataObj
);
968 sqlStmt
+= s
.GetData();
971 if (pDb
->Dbms() == dbmsSYBASE_ASE
|| pDb
->Dbms() == dbmsMY_SQL
)
973 if (colDefs
[i
].KeyField
)
975 sqlStmt
+= " NOT NULL";
981 // If there is a primary key defined, include it in the create statement
982 for (i
= j
= 0; i
< noCols
; i
++)
984 if (colDefs
[i
].KeyField
)
990 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
992 if (pDb
->Dbms() != dbmsMY_SQL
)
994 sqlStmt
+= ",CONSTRAINT ";
995 sqlStmt
+= tableName
;
996 sqlStmt
+= "_PIDX PRIMARY KEY (";
1000 /* MySQL goes out on this one. We also declare the relevant key NON NULL above */
1001 sqlStmt
+= ", PRIMARY KEY (";
1004 // List column name(s) of column(s) comprising the primary key
1005 for (i
= j
= 0; i
< noCols
; i
++)
1007 if (colDefs
[i
].KeyField
)
1009 if (j
++) // Multi part key, comma separate names
1011 sqlStmt
+= colDefs
[i
].ColName
;
1016 // Append the closing parentheses for the create table statement
1019 pDb
->WriteSqlLog(sqlStmt
.GetData());
1021 #ifdef DBDEBUG_CONSOLE
1022 cout
<< endl
<< sqlStmt
.GetData() << endl
;
1025 // Execute the CREATE TABLE statement
1026 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
);
1027 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1029 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1030 pDb
->RollbackTrans();
1035 // Commit the transaction and close the cursor
1036 if (! pDb
->CommitTrans())
1038 if (! CloseCursor(hstmt
))
1041 // Database table created successfully
1044 } // wxTable::CreateTable()
1047 /********** wxTable::DropTable() **********/
1048 bool wxTable::DropTable()
1050 // NOTE: This function returns TRUE if the Table does not exist, but
1051 // only for identified databases. Code will need to be added
1052 // below for any other databases when those databases are defined
1053 // to handle this situation consistently
1057 sqlStmt
.sprintf("DROP TABLE %s", tableName
);
1059 pDb
->WriteSqlLog(sqlStmt
.GetData());
1061 #ifdef DBDEBUG_CONSOLE
1062 cout
<< endl
<< sqlStmt
.GetData() << endl
;
1065 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1067 // Check for "Base table not found" error and ignore
1068 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1069 if (wxStrcmp(pDb
->sqlState
,"S0002")) // "Base table not found"
1071 // Check for product specific error codes
1072 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,"42000")) || // 5.x (and lower?)
1073 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,"S1000")) || // untested
1074 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,"08S01")))) // untested
1076 pDb
->DispNextError();
1077 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1078 pDb
->RollbackTrans();
1085 // Commit the transaction and close the cursor
1086 if (! pDb
->CommitTrans())
1088 if (! CloseCursor(hstmt
))
1092 } // wxTable::DropTable()
1095 /********** wxTable::CreateIndex() **********/
1096 bool wxTable::CreateIndex(const char * idxName
, bool unique
, int noIdxCols
, CidxDef
*pIdxDefs
, bool attemptDrop
)
1098 // char sqlStmt[DB_MAX_STATEMENT_LEN];
1101 // Drop the index first
1102 if (attemptDrop
&& !DropIndex(idxName
))
1105 // Build a CREATE INDEX statement
1106 sqlStmt
= "CREATE ";
1108 sqlStmt
+= "UNIQUE ";
1110 sqlStmt
+= "INDEX ";
1113 sqlStmt
+= tableName
;
1116 // Append list of columns making up index
1118 for (i
= 0; i
< noIdxCols
; i
++)
1120 sqlStmt
+= pIdxDefs
[i
].ColName
;
1121 /* Postgres doesn't cope with ASC */
1122 if (pDb
->Dbms() != dbmsPOSTGRES
)
1124 if (pIdxDefs
[i
].Ascending
)
1130 if ((i
+ 1) < noIdxCols
)
1134 // Append closing parentheses
1137 pDb
->WriteSqlLog(sqlStmt
.GetData());
1139 #ifdef DBDEBUG_CONSOLE
1140 cout
<< endl
<< sqlStmt
.GetData() << endl
<< endl
;
1143 // Execute the CREATE INDEX statement
1144 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1146 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1147 pDb
->RollbackTrans();
1152 // Commit the transaction and close the cursor
1153 if (! pDb
->CommitTrans())
1155 if (! CloseCursor(hstmt
))
1158 // Index Created Successfully
1161 } // wxTable::CreateIndex()
1164 /********** wxTable::DropIndex() **********/
1165 bool wxTable::DropIndex(const char * idxName
)
1167 // NOTE: This function returns TRUE if the Index does not exist, but
1168 // only for identified databases. Code will need to be added
1169 // below for any other databases when those databases are defined
1170 // to handle this situation consistently
1174 if (pDb
->Dbms() == dbmsACCESS
)
1175 sqlStmt
.sprintf("DROP INDEX %s ON %s",idxName
,tableName
);
1176 else if (pDb
->Dbms() == dbmsSYBASE_ASE
)
1177 sqlStmt
.sprintf("DROP INDEX %s.%s",tableName
,idxName
);
1179 sqlStmt
.sprintf("DROP INDEX %s",idxName
);
1181 pDb
->WriteSqlLog(sqlStmt
.GetData());
1183 #ifdef DBDEBUG_CONSOLE
1184 cout
<< endl
<< sqlStmt
.GetData() << endl
;
1187 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1189 // Check for "Index not found" error and ignore
1190 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1191 if (wxStrcmp(pDb
->sqlState
,"S0012")) // "Index not found"
1193 // Check for product specific error codes
1194 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,"42000")) || // v5.x (and lower?)
1195 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,"S0002")) || // Base table not found
1196 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,"42S02")) // untested
1199 pDb
->DispNextError();
1200 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1201 pDb
->RollbackTrans();
1208 // Commit the transaction and close the cursor
1209 if (! pDb
->CommitTrans())
1211 if (! CloseCursor(hstmt
))
1215 } // wxTable::DropIndex()
1218 /********** wxTable::Insert() **********/
1219 int wxTable::Insert(void)
1227 // Insert the record by executing the already prepared insert statement
1229 retcode
=SQLExecute(hstmtInsert
);
1230 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1232 // Check to see if integrity constraint was violated
1233 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1234 if (! wxStrcmp(pDb
->sqlState
, "23000")) // Integrity constraint violated
1235 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1238 pDb
->DispNextError();
1239 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1244 // Record inserted into the datasource successfully
1247 } // wxTable::Insert()
1250 /********** wxTable::Update() **********/
1251 bool wxTable::Update(void)
1257 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1259 // Build the SQL UPDATE statement
1260 GetUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1262 pDb
->WriteSqlLog(sqlStmt
);
1264 #ifdef DBDEBUG_CONSOLE
1265 cout
<< endl
<< sqlStmt
<< endl
<< endl
;
1268 // Execute the SQL UPDATE statement
1269 return(execUpdate(sqlStmt
));
1271 } // wxTable::Update()
1274 /********** wxTable::Update(pSqlStmt) **********/
1275 bool wxTable::Update(const char *pSqlStmt
)
1281 pDb
->WriteSqlLog(pSqlStmt
);
1283 return(execUpdate(pSqlStmt
));
1285 } // wxTable::Update(pSqlStmt)
1288 /********** wxTable::UpdateWhere() **********/
1289 bool wxTable::UpdateWhere(const char *pWhereClause
)
1295 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1297 // Build the SQL UPDATE statement
1298 GetUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1300 pDb
->WriteSqlLog(sqlStmt
);
1302 #ifdef DBDEBUG_CONSOLE
1303 cout
<< endl
<< sqlStmt
<< endl
<< endl
;
1306 // Execute the SQL UPDATE statement
1307 return(execUpdate(sqlStmt
));
1309 } // wxTable::UpdateWhere()
1312 /********** wxTable::Delete() **********/
1313 bool wxTable::Delete(void)
1319 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1321 // Build the SQL DELETE statement
1322 GetDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1324 pDb
->WriteSqlLog(sqlStmt
);
1326 // Execute the SQL DELETE statement
1327 return(execDelete(sqlStmt
));
1329 } // wxTable::Delete()
1332 /********** wxTable::DeleteWhere() **********/
1333 bool wxTable::DeleteWhere(const char *pWhereClause
)
1339 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1341 // Build the SQL DELETE statement
1342 GetDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1344 pDb
->WriteSqlLog(sqlStmt
);
1346 // Execute the SQL DELETE statement
1347 return(execDelete(sqlStmt
));
1349 } // wxTable::DeleteWhere()
1352 /********** wxTable::DeleteMatching() **********/
1353 bool wxTable::DeleteMatching(void)
1359 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1361 // Build the SQL DELETE statement
1362 GetDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1364 pDb
->WriteSqlLog(sqlStmt
);
1366 // Execute the SQL DELETE statement
1367 return(execDelete(sqlStmt
));
1369 } // wxTable::DeleteMatching()
1372 /********** wxTable::GetUpdateStmt() **********/
1373 void wxTable::GetUpdateStmt(char *pSqlStmt
, int typeOfUpd
, const char *pWhereClause
)
1379 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
1380 bool firstColumn
= TRUE
;
1383 sprintf(pSqlStmt
, "UPDATE %s SET ", tableName
);
1385 // Append a list of columns to be updated
1387 for (i
= 0; i
< noCols
; i
++)
1389 // Only append Updateable columns
1390 if (colDefs
[i
].Updateable
)
1393 wxStrcat(pSqlStmt
, ",");
1395 firstColumn
= FALSE
;
1396 wxStrcat(pSqlStmt
, colDefs
[i
].ColName
);
1397 wxStrcat(pSqlStmt
, " = ?");
1401 // Append the WHERE clause to the SQL UPDATE statement
1402 wxStrcat(pSqlStmt
, " WHERE ");
1405 case DB_UPD_KEYFIELDS
:
1406 // If the datasource supports the ROWID column, build
1407 // the where on ROWID for efficiency purposes.
1408 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1409 if (CanUpdByROWID())
1412 char rowid
[ROWID_LEN
];
1414 // Get the ROWID value. If not successful retreiving the ROWID,
1415 // simply fall down through the code and build the WHERE clause
1416 // based on the key fields.
1417 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1419 wxStrcat(pSqlStmt
, "ROWID = '");
1420 wxStrcat(pSqlStmt
, rowid
);
1421 wxStrcat(pSqlStmt
, "'");
1425 // Unable to delete by ROWID, so build a WHERE
1426 // clause based on the keyfields.
1427 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1428 wxStrcat(pSqlStmt
, whereClause
);
1431 wxStrcat(pSqlStmt
, pWhereClause
);
1434 } // GetUpdateStmt()
1437 /********** wxTable::GetDeleteStmt() **********/
1438 void wxTable::GetDeleteStmt(char *pSqlStmt
, int typeOfDel
, const char *pWhereClause
)
1444 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
1448 // Handle the case of DeleteWhere() and the where clause is blank. It should
1449 // delete all records from the database in this case.
1450 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
== 0 || wxStrlen(pWhereClause
) == 0))
1452 sprintf(pSqlStmt
, "DELETE FROM %s", tableName
);
1456 sprintf(pSqlStmt
, "DELETE FROM %s WHERE ", tableName
);
1458 // Append the WHERE clause to the SQL DELETE statement
1461 case DB_DEL_KEYFIELDS
:
1462 // If the datasource supports the ROWID column, build
1463 // the where on ROWID for efficiency purposes.
1464 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1465 if (CanUpdByROWID())
1468 char rowid
[ROWID_LEN
];
1470 // Get the ROWID value. If not successful retreiving the ROWID,
1471 // simply fall down through the code and build the WHERE clause
1472 // based on the key fields.
1473 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1475 wxStrcat(pSqlStmt
, "ROWID = '");
1476 wxStrcat(pSqlStmt
, rowid
);
1477 wxStrcat(pSqlStmt
, "'");
1481 // Unable to delete by ROWID, so build a WHERE
1482 // clause based on the keyfields.
1483 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1484 wxStrcat(pSqlStmt
, whereClause
);
1487 wxStrcat(pSqlStmt
, pWhereClause
);
1489 case DB_DEL_MATCHING
:
1490 GetWhereClause(whereClause
, DB_WHERE_MATCHING
);
1491 wxStrcat(pSqlStmt
, whereClause
);
1495 } // GetDeleteStmt()
1498 /********** wxTable::GetWhereClause() **********/
1499 void wxTable::GetWhereClause(char *pWhereClause
, int typeOfWhere
, const char *qualTableName
)
1501 * Note: GetWhereClause() currently ignores timestamp columns.
1502 * They are not included as part of the where clause.
1505 bool moreThanOneColumn
= FALSE
;
1508 // Loop through the columns building a where clause as you go
1510 for (i
= 0; i
< noCols
; i
++)
1512 // Determine if this column should be included in the WHERE clause
1513 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1514 (typeOfWhere
== DB_WHERE_MATCHING
&& (! IsColNull(i
))))
1516 // Skip over timestamp columns
1517 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1519 // If there is more than 1 column, join them with the keyword "AND"
1520 if (moreThanOneColumn
)
1521 wxStrcat(pWhereClause
, " AND ");
1523 moreThanOneColumn
= TRUE
;
1524 // Concatenate where phrase for the column
1525 if (qualTableName
&& wxStrlen(qualTableName
))
1527 wxStrcat(pWhereClause
, qualTableName
);
1528 wxStrcat(pWhereClause
, ".");
1530 wxStrcat(pWhereClause
, colDefs
[i
].ColName
);
1531 wxStrcat(pWhereClause
, " = ");
1532 switch(colDefs
[i
].SqlCtype
)
1535 sprintf(colValue
, "'%s'", (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1538 sprintf(colValue
, "%hi", *((SWORD
*) colDefs
[i
].PtrDataObj
));
1541 sprintf(colValue
, "%hu", *((UWORD
*) colDefs
[i
].PtrDataObj
));
1544 sprintf(colValue
, "%li", *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1547 sprintf(colValue
, "%lu", *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1550 sprintf(colValue
, "%.6f", *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1553 sprintf(colValue
, "%.6f", *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1556 wxStrcat(pWhereClause
, colValue
);
1559 } // wxTable::GetWhereClause()
1562 /********** wxTable::IsColNull() **********/
1563 bool wxTable::IsColNull(int colNo
)
1565 switch(colDefs
[colNo
].SqlCtype
)
1568 return(((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] == 0);
1570 return(( *((SWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1572 return(( *((UWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1574 return(( *((SDWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1576 return(( *((UDWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1578 return(( *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1580 return((*((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1581 case SQL_C_TIMESTAMP
:
1582 TIMESTAMP_STRUCT
*pDt
;
1583 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
1584 if (pDt
->year
== 0 && pDt
->month
== 0 && pDt
->day
== 0)
1591 } // wxTable::IsColNull()
1594 /********** wxTable::CanSelectForUpdate() **********/
1595 bool wxTable::CanSelectForUpdate(void)
1597 if (pDb
->Dbms() == dbmsMY_SQL
)
1600 if (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
)
1605 } // wxTable::CanSelectForUpdate()
1608 /********** wxTable::CanUpdByROWID() **********/
1609 bool wxTable::CanUpdByROWID(void)
1612 * NOTE: Returning FALSE for now until this can be debugged,
1613 * as the ROWID is not getting updated correctly
1617 if (pDb
->Dbms() == dbmsORACLE
)
1622 } // wxTable::CanUpdByROWID()
1625 /********** wxTable::IsCursorClosedOnCommit() **********/
1626 bool wxTable::IsCursorClosedOnCommit(void)
1628 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
1633 } // wxTable::IsCursorClosedOnCommit()
1636 /********** wxTable::ClearMemberVars() **********/
1637 void wxTable::ClearMemberVars(void)
1639 // Loop through the columns setting each member variable to zero
1641 for (i
= 0; i
< noCols
; i
++)
1643 switch(colDefs
[i
].SqlCtype
)
1646 ((UCHAR FAR
*) colDefs
[i
].PtrDataObj
)[0] = 0;
1649 *((SWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1652 *((UWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1655 *((SDWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1658 *((UDWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1661 *((SFLOAT
*) colDefs
[i
].PtrDataObj
) = 0.0f
;
1664 *((SDOUBLE
*) colDefs
[i
].PtrDataObj
) = 0.0f
;
1666 case SQL_C_TIMESTAMP
:
1667 TIMESTAMP_STRUCT
*pDt
;
1668 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[i
].PtrDataObj
;
1681 } // wxTable::ClearMemberVars()
1684 /********** wxTable::SetQueryTimeout() **********/
1685 bool wxTable::SetQueryTimeout(UDWORD nSeconds
)
1687 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1688 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
1689 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1690 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
1691 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1692 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
1693 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1694 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
1696 // Completed Successfully
1699 } // wxTable::SetQueryTimeout()
1702 /********** wxTable::SetColDefs() **********/
1703 void wxTable::SetColDefs (int index
, const char *fieldName
, int dataType
, void *pData
,
1704 int cType
, int size
, bool keyField
, bool upd
,
1705 bool insAllow
, bool derivedCol
)
1707 if (!colDefs
) // May happen if the database connection fails
1710 if (wxStrlen(fieldName
) > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
1712 wxStrncpy (colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
1713 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
1716 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
1718 colDefs
[index
].DbDataType
= dataType
;
1719 colDefs
[index
].PtrDataObj
= pData
;
1720 colDefs
[index
].SqlCtype
= cType
;
1721 colDefs
[index
].SzDataObj
= size
;
1722 colDefs
[index
].KeyField
= keyField
;
1723 colDefs
[index
].DerivedCol
= derivedCol
;
1724 // Derived columns by definition would NOT be "Insertable" or "Updateable"
1727 colDefs
[index
].Updateable
= FALSE
;
1728 colDefs
[index
].InsertAllowed
= FALSE
;
1732 colDefs
[index
].Updateable
= upd
;
1733 colDefs
[index
].InsertAllowed
= insAllow
;
1736 colDefs
[index
].Null
= FALSE
;
1738 } // wxTable::SetColDefs()
1741 /********** wxTable::SetColDef() **********/
1742 wxColDataPtr
* wxTable::SetColDefs (wxColInf
*pColInfs
, ULONG numCols
)
1745 wxColDataPtr
*pColDataPtrs
= NULL
;
1752 pColDataPtrs
= new wxColDataPtr
[numCols
+1];
1754 for (index
= 0; index
< numCols
; index
++)
1756 // Process the fields
1757 switch (pColInfs
[index
].dbDataType
)
1759 case DB_DATA_TYPE_VARCHAR
:
1761 pColDataPtrs
[index
].PtrDataObj
= new char[pColInfs
[index
].bufferLength
+1];
1762 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
1763 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
1766 case DB_DATA_TYPE_INTEGER
:
1768 // Can be long or short
1769 if (pColInfs
[index
].bufferLength
== sizeof(long))
1771 pColDataPtrs
[index
].PtrDataObj
= new long;
1772 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
1773 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
1777 pColDataPtrs
[index
].PtrDataObj
= new short;
1778 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
1779 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
1783 case DB_DATA_TYPE_FLOAT
:
1785 // Can be float or double
1786 if (pColInfs
[index
].bufferLength
== sizeof(float))
1788 pColDataPtrs
[index
].PtrDataObj
= new float;
1789 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
1790 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
1794 pColDataPtrs
[index
].PtrDataObj
= new double;
1795 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
1796 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
1800 case DB_DATA_TYPE_DATE
:
1802 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
1803 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
1804 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
1809 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
1812 return (pColDataPtrs
);
1813 } // wxTable::SetColDef()
1816 /********** wxTable::SetCursor() **********/
1817 void wxTable::SetCursor(HSTMT
*hstmtActivate
)
1819 if (hstmtActivate
== DEFAULT_CURSOR
)
1820 hstmt
= *hstmtDefault
;
1822 hstmt
= *hstmtActivate
;
1824 } // wxTable::SetCursor()
1827 /********** wxTable::Count(const char *) **********/
1828 ULONG
wxTable::Count(const char *args
)
1834 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
1835 sqlStmt
= "SELECT COUNT(";
1837 sqlStmt
+= ") FROM ";
1838 sqlStmt
+= queryTableName
;
1840 if (from
&& wxStrlen(from
))
1843 // Add the where clause if one is provided
1844 if (where
&& wxStrlen(where
))
1846 sqlStmt
+= " WHERE ";
1850 pDb
->WriteSqlLog(sqlStmt
.GetData());
1852 // Initialize the Count cursor if it's not already initialized
1855 hstmtCount
= NewCursor(FALSE
,FALSE
);
1861 // Execute the SQL statement
1862 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1864 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1869 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
1871 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1875 // Obtain the result
1876 if (SQLGetData(*hstmtCount
, 1, SQL_C_ULONG
, &l
, sizeof(l
), &cb
) != SQL_SUCCESS
)
1878 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1883 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
1884 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1886 // Return the record count
1889 } // wxTable::Count()
1892 /********** wxTable::Refresh() **********/
1893 bool wxTable::Refresh(void)
1897 // Switch to the internal cursor so any active cursors are not corrupted
1898 HSTMT currCursor
= GetCursor();
1899 hstmt
= hstmtInternal
;
1901 // Save the where and order by clauses
1902 char *saveWhere
= where
;
1903 char *saveOrderBy
= orderBy
;
1905 // Build a where clause to refetch the record with. Try and use the
1906 // ROWID if it's available, ow use the key fields.
1907 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
+1];
1908 wxStrcpy(whereClause
, "");
1909 if (CanUpdByROWID())
1912 char rowid
[ROWID_LEN
+1];
1914 // Get the ROWID value. If not successful retreiving the ROWID,
1915 // simply fall down through the code and build the WHERE clause
1916 // based on the key fields.
1917 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1919 wxStrcat(whereClause
, queryTableName
);
1920 wxStrcat(whereClause
, ".ROWID = '");
1921 wxStrcat(whereClause
, rowid
);
1922 wxStrcat(whereClause
, "'");
1926 // If unable to use the ROWID, build a where clause from the keyfields
1927 if (wxStrlen(whereClause
) == 0)
1928 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
1930 // Requery the record
1931 where
= whereClause
;
1936 if (result
&& !GetNext())
1939 // Switch back to original cursor
1940 SetCursor(&currCursor
);
1942 // Free the internal cursor
1943 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
1944 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
1946 // Restore the original where and order by clauses
1948 orderBy
= saveOrderBy
;
1952 } // wxTable::Refresh()
1955 /********** wxTable::SetNull(int colNo) **********/
1956 bool wxTable::SetNull(int colNo
)
1959 return(colDefs
[colNo
].Null
= TRUE
);
1963 } // wxTable::SetNull(int colNo)
1966 /********** wxTable::SetNull(char *colName) **********/
1967 bool wxTable::SetNull(const char *colName
)
1970 for (i
= 0; i
< noCols
; i
++)
1972 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
1977 return(colDefs
[i
].Null
= TRUE
);
1981 } // wxTable::SetNull(char *colName)
1984 /********** wxTable::NewCursor() **********/
1985 HSTMT
*wxTable::NewCursor(bool setCursor
, bool bindColumns
)
1987 HSTMT
*newHSTMT
= new HSTMT
;
1992 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
1994 pDb
->DispAllErrors(henv
, hdbc
);
1999 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2001 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2008 if(!bindCols(*newHSTMT
))
2016 SetCursor(newHSTMT
);
2020 } // wxTable::NewCursor()
2023 /********** wxTable::DeleteCursor() **********/
2024 bool wxTable::DeleteCursor(HSTMT
*hstmtDel
)
2028 if (!hstmtDel
) // Cursor already deleted
2031 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2033 pDb
->DispAllErrors(henv
, hdbc
);
2041 } // wxTable::DeleteCursor()
2043 #endif // wxUSE_ODBC