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
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 wxMessageBox (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 wxMessageBox (msg
.GetData(),"NOTICE...");
283 // Decrement the wxDB table count
287 // Delete memory allocated for column definitions
291 // Free statement handles
295 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
296 pDb
->DispAllErrors(henv
, hdbc
);
298 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
299 pDb
->DispAllErrors(henv
, hdbc
);
301 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
302 pDb
->DispAllErrors(henv
, hdbc
);
305 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
306 pDb
->DispAllErrors(henv
, hdbc
);
308 // Delete dynamically allocated cursors
310 DeleteCursor(hstmtDefault
);
312 DeleteCursor(hstmtCount
);
314 } // wxTable::~wxTable()
318 /***************************** PRIVATE FUNCTIONS *****************************/
322 /********** wxTable::bindInsertParams() **********/
323 bool wxTable::bindInsertParams(void)
330 UDWORD precision
= 0;
333 // Bind each column (that can be inserted) of the table to a parameter marker
335 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
337 if (! colDefs
[i
].InsertAllowed
)
339 switch(colDefs
[i
].DbDataType
)
341 case DB_DATA_TYPE_VARCHAR
:
342 fSqlType
= pDb
->typeInfVarchar
.FsqlType
;
343 precision
= colDefs
[i
].SzDataObj
;
345 colDefs
[i
].CbValue
= SQL_NTS
;
347 case DB_DATA_TYPE_INTEGER
:
348 fSqlType
= pDb
->typeInfInteger
.FsqlType
;
349 precision
= pDb
->typeInfInteger
.Precision
;
351 colDefs
[i
].CbValue
= 0;
353 case DB_DATA_TYPE_FLOAT
:
354 fSqlType
= pDb
->typeInfFloat
.FsqlType
;
355 precision
= pDb
->typeInfFloat
.Precision
;
356 scale
= pDb
->typeInfFloat
.MaximumScale
;
357 // SQL Sybase Anywhere v5.5 returned a negative number for the
358 // MaxScale. This caused ODBC to kick out an error on ibscale.
359 // I check for this here and set the scale = precision.
361 // scale = (short) precision;
362 colDefs
[i
].CbValue
= 0;
364 case DB_DATA_TYPE_DATE
:
365 fSqlType
= pDb
->typeInfDate
.FsqlType
;
366 precision
= pDb
->typeInfDate
.Precision
;
368 colDefs
[i
].CbValue
= 0;
374 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
375 colDefs
[i
].Null
= FALSE
;
377 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
378 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
379 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
380 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
383 // Completed successfully
386 } // wxTable::bindInsertParams()
389 /********** wxTable::bindUpdateParams() **********/
390 bool wxTable::bindUpdateParams(void)
397 UDWORD precision
= 0;
400 // Bind each UPDATEABLE column of the table to a parameter marker
402 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
404 if (! colDefs
[i
].Updateable
)
406 switch(colDefs
[i
].DbDataType
)
408 case DB_DATA_TYPE_VARCHAR
:
409 fSqlType
= pDb
->typeInfVarchar
.FsqlType
;
410 precision
= colDefs
[i
].SzDataObj
;
412 colDefs
[i
].CbValue
= SQL_NTS
;
414 case DB_DATA_TYPE_INTEGER
:
415 fSqlType
= pDb
->typeInfInteger
.FsqlType
;
416 precision
= pDb
->typeInfInteger
.Precision
;
418 colDefs
[i
].CbValue
= 0;
420 case DB_DATA_TYPE_FLOAT
:
421 fSqlType
= pDb
->typeInfFloat
.FsqlType
;
422 precision
= pDb
->typeInfFloat
.Precision
;
423 scale
= pDb
->typeInfFloat
.MaximumScale
;
424 // SQL Sybase Anywhere v5.5 returned a negative number for the
425 // MaxScale. This caused ODBC to kick out an error on ibscale.
426 // I check for this here and set the scale = precision.
428 // scale = (short) precision;
429 colDefs
[i
].CbValue
= 0;
431 case DB_DATA_TYPE_DATE
:
432 fSqlType
= pDb
->typeInfDate
.FsqlType
;
433 precision
= pDb
->typeInfDate
.Precision
;
435 colDefs
[i
].CbValue
= 0;
438 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
439 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
440 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
441 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
444 // Completed successfully
447 } // wxTable::bindUpdateParams()
450 /********** wxTable::bindCols() **********/
451 bool wxTable::bindCols(HSTMT cursor
)
455 // Bind each column of the table to a memory address for fetching data
457 for (i
= 0; i
< noCols
; i
++)
459 if (SQLBindCol(cursor
, i
+1, colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
460 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
461 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
464 // Completed successfully
467 } // wxTable::bindCols()
470 /********** wxTable::getRec() **********/
471 bool wxTable::getRec(UWORD fetchType
)
475 if (!pDb
->FwdOnlyCursors())
477 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
481 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
482 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
483 if (retcode
== SQL_NO_DATA_FOUND
)
486 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
490 // Fetch the next record from the record set
491 retcode
= SQLFetch(hstmt
);
492 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
494 if (retcode
== SQL_NO_DATA_FOUND
)
497 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
501 // Completed successfully
504 } // wxTable::getRec()
507 /********** wxTable::execDelete() **********/
508 bool wxTable::execDelete(const char *pSqlStmt
)
510 // Execute the DELETE statement
511 if (SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
, SQL_NTS
) != SQL_SUCCESS
)
512 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
514 // Record deleted successfully
517 } // wxTable::execDelete()
520 /********** wxTable::execUpdate() **********/
521 bool wxTable::execUpdate(const char *pSqlStmt
)
523 // Execute the UPDATE statement
524 if (SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
, SQL_NTS
) != SQL_SUCCESS
)
525 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
527 // Record deleted successfully
530 } // wxTable::execUpdate()
533 /********** wxTable::query() **********/
534 bool wxTable::query(int queryType
, bool forUpdate
, bool distinct
, char *pSqlStmt
)
536 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
538 // Set the selectForUpdate member variable
540 // The user may wish to select for update, but the DBMS may not be capable
541 selectForUpdate
= CanSelectForUpdate();
543 selectForUpdate
= FALSE
;
545 // Set the SQL SELECT string
546 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
547 { // so generate a select statement.
548 GetSelectStmt(sqlStmt
, queryType
, distinct
);
549 pDb
->WriteSqlLog(sqlStmt
);
552 // Make sure the cursor is closed first
553 if (! CloseCursor(hstmt
))
556 // Execute the SQL SELECT statement
559 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
: sqlStmt
), SQL_NTS
);
560 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
561 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
563 // Completed successfully
566 } // wxTable::query()
569 /***************************** PUBLIC FUNCTIONS *****************************/
572 /********** wxTable::Open() **********/
573 bool wxTable::Open(void)
579 // char sqlStmt[DB_MAX_STATEMENT_LEN];
582 // Verify that the table exists in the database
583 if (!pDb
->TableExists(tableName
,pDb
->GetUsername(),tablePath
))
586 if (wxStrcmp(tablePath
,""))
587 s
.sprintf("Error opening '%s/%s'.\n",tablePath
,tableName
);
589 s
.sprintf("Error opening '%s'.\n", tableName
);
590 if (!pDb
->TableExists(tableName
,NULL
,tablePath
))
591 s
+= "Table/view does not exist in the database.\n";
593 s
+= "Current logged in user does not have sufficient privileges to access this table.\n";
594 pDb
->LogError(s
.GetData());
598 // Bind the member variables for field exchange between
599 // the wxTable object and the ODBC record.
602 if (!bindInsertParams()) // Inserts
604 if (!bindUpdateParams()) // Updates
607 if (!bindCols(*hstmtDefault
)) // Selects
609 if (!bindCols(hstmtInternal
)) // Internal use only
612 * Do NOT bind the hstmtCount cursor!!!
615 // Build an insert statement using parameter markers
616 if (!queryOnly
&& noCols
> 0)
618 bool needComma
= FALSE
;
619 sqlStmt
.sprintf("INSERT INTO %s (", tableName
);
620 for (i
= 0; i
< noCols
; i
++)
622 if (! colDefs
[i
].InsertAllowed
)
626 sqlStmt
+= colDefs
[i
].ColName
;
630 sqlStmt
+= ") VALUES (";
631 for (i
= 0; i
< noCols
; i
++)
633 if (! colDefs
[i
].InsertAllowed
)
642 // pDb->WriteSqlLog(sqlStmt);
644 // Prepare the insert statement for execution
645 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
646 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
649 // Completed successfully
655 /********** wxTable::Query() **********/
656 bool wxTable::Query(bool forUpdate
, bool distinct
)
659 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
661 } // wxTable::Query()
664 /********** wxTable::QueryBySqlStmt() **********/
665 bool wxTable::QueryBySqlStmt(char *pSqlStmt
)
667 pDb
->WriteSqlLog(pSqlStmt
);
669 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
671 } // wxTable::QueryBySqlStmt()
674 /********** wxTable::QueryMatching() **********/
675 bool wxTable::QueryMatching(bool forUpdate
, bool distinct
)
678 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
680 } // wxTable::QueryMatching()
683 /********** wxTable::QueryOnKeyFields() **********/
684 bool wxTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
687 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
689 } // wxTable::QueryOnKeyFields()
692 /********** wxTable::GetPrev() **********/
693 bool wxTable::GetPrev(void)
695 if (pDb
->FwdOnlyCursors())
697 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxTable"));
701 return(getRec(SQL_FETCH_PRIOR
));
702 } // wxTable::GetPrev()
705 /********** wxTable::operator-- **********/
706 bool wxTable::operator--(int)
708 if (pDb
->FwdOnlyCursors())
710 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxTable"));
714 return(getRec(SQL_FETCH_PRIOR
));
715 } // wxTable::operator--
718 /********** wxTable::GetFirst() **********/
719 bool wxTable::GetFirst(void)
721 if (pDb
->FwdOnlyCursors())
723 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxTable"));
727 return(getRec(SQL_FETCH_FIRST
));
728 } // wxTable::GetFirst()
731 /********** wxTable::GetLast() **********/
732 bool wxTable::GetLast(void)
734 if (pDb
->FwdOnlyCursors())
736 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxTable"));
740 return(getRec(SQL_FETCH_LAST
));
741 } // wxTable::GetLast()
744 /********** wxTable::GetSelectStmt() **********/
745 void wxTable::GetSelectStmt(char *pSqlStmt
, int typeOfSelect
, bool distinct
)
747 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
751 // Build a select statement to query the database
752 wxStrcpy(pSqlStmt
, "SELECT ");
754 // SELECT DISTINCT values only?
756 wxStrcat(pSqlStmt
, "DISTINCT ");
758 // Was a FROM clause specified to join tables to the base table?
759 // Available for ::Query() only!!!
760 bool appendFromClause
= FALSE
;
761 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
762 appendFromClause
= TRUE
;
764 // Add the column list
766 for (i
= 0; i
< noCols
; i
++)
768 // If joining tables, the base table column names must be qualified to avoid ambiguity
769 if (appendFromClause
)
771 wxStrcat(pSqlStmt
, queryTableName
);
772 wxStrcat(pSqlStmt
, ".");
774 wxStrcat(pSqlStmt
, colDefs
[i
].ColName
);
776 wxStrcat(pSqlStmt
, ",");
779 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
780 // the ROWID if querying distinct records. The rowid will always be unique.
781 if (!distinct
&& CanUpdByROWID())
783 // If joining tables, the base table column names must be qualified to avoid ambiguity
784 if (appendFromClause
)
786 wxStrcat(pSqlStmt
, ",");
787 wxStrcat(pSqlStmt
, queryTableName
);
788 wxStrcat(pSqlStmt
, ".ROWID");
791 wxStrcat(pSqlStmt
, ",ROWID");
794 // Append the FROM tablename portion
795 wxStrcat(pSqlStmt
, " FROM ");
796 wxStrcat(pSqlStmt
, queryTableName
);
798 // Sybase uses the HOLDLOCK keyword to lock a record during query.
799 // The HOLDLOCK keyword follows the table name in the from clause.
800 // Each table in the from clause must specify HOLDLOCK or
801 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
802 // is parsed but ignored in SYBASE Transact-SQL.
803 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
804 wxStrcat(pSqlStmt
, " HOLDLOCK");
806 if (appendFromClause
)
807 wxStrcat(pSqlStmt
, from
);
809 // Append the WHERE clause. Either append the where clause for the class
810 // or build a where clause. The typeOfSelect determines this.
813 case DB_SELECT_WHERE
:
814 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
816 wxStrcat(pSqlStmt
, " WHERE ");
817 wxStrcat(pSqlStmt
, where
);
820 case DB_SELECT_KEYFIELDS
:
821 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
822 if (wxStrlen(whereClause
))
824 wxStrcat(pSqlStmt
, " WHERE ");
825 wxStrcat(pSqlStmt
, whereClause
);
828 case DB_SELECT_MATCHING
:
829 GetWhereClause(whereClause
, DB_WHERE_MATCHING
);
830 if (wxStrlen(whereClause
))
832 wxStrcat(pSqlStmt
, " WHERE ");
833 wxStrcat(pSqlStmt
, whereClause
);
838 // Append the ORDER BY clause
839 if (orderBy
&& wxStrlen(orderBy
))
841 wxStrcat(pSqlStmt
, " ORDER BY ");
842 wxStrcat(pSqlStmt
, orderBy
);
845 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
846 // parses the FOR UPDATE clause but ignores it. See the comment above on the
847 // HOLDLOCK for Sybase.
848 if (selectForUpdate
&& CanSelectForUpdate())
849 wxStrcat(pSqlStmt
, " FOR UPDATE");
851 } // wxTable::GetSelectStmt()
854 /********** wxTable::GetRowNum() **********/
855 UWORD
wxTable::GetRowNum(void)
859 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
861 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
865 // Completed successfully
866 return((UWORD
) rowNum
);
868 } // wxTable::GetRowNum()
871 /********** wxTable::CloseCursor() **********/
872 bool wxTable::CloseCursor(HSTMT cursor
)
874 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
875 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
877 // Completed successfully
880 } // wxTable::CloseCursor()
883 /********** wxTable::CreateTable() **********/
884 bool wxTable::CreateTable(bool attemptDrop
)
890 // char sqlStmt[DB_MAX_STATEMENT_LEN];
893 #ifdef DBDEBUG_CONSOLE
894 cout
<< "Creating Table " << tableName
<< "..." << endl
;
898 if (attemptDrop
&& !DropTable())
902 #ifdef DBDEBUG_CONSOLE
903 for (i
= 0; i
< noCols
; i
++)
905 // Exclude derived columns since they are NOT part of the base table
906 if (colDefs
[i
].DerivedCol
)
908 cout
<< i
+ 1 << ": " << colDefs
[i
].ColName
<< "; ";
909 switch(colDefs
[i
].DbDataType
)
911 case DB_DATA_TYPE_VARCHAR
:
912 cout
<< pDb
->typeInfVarchar
.TypeName
<< "(" << colDefs
[i
].SzDataObj
<< ")";
914 case DB_DATA_TYPE_INTEGER
:
915 cout
<< pDb
->typeInfInteger
.TypeName
;
917 case DB_DATA_TYPE_FLOAT
:
918 cout
<< pDb
->typeInfFloat
.TypeName
;
920 case DB_DATA_TYPE_DATE
:
921 cout
<< pDb
->typeInfDate
.TypeName
;
928 // Build a CREATE TABLE string from the colDefs structure.
929 bool needComma
= FALSE
;
930 sqlStmt
.sprintf("CREATE TABLE %s (", tableName
);
932 for (i
= 0; i
< noCols
; i
++)
934 // Exclude derived columns since they are NOT part of the base table
935 if (colDefs
[i
].DerivedCol
)
941 sqlStmt
+= colDefs
[i
].ColName
;
944 switch(colDefs
[i
].DbDataType
)
946 case DB_DATA_TYPE_VARCHAR
:
947 sqlStmt
+= pDb
->typeInfVarchar
.TypeName
; break;
948 case DB_DATA_TYPE_INTEGER
:
949 sqlStmt
+= pDb
->typeInfInteger
.TypeName
; break;
950 case DB_DATA_TYPE_FLOAT
:
951 sqlStmt
+= pDb
->typeInfFloat
.TypeName
; break;
952 case DB_DATA_TYPE_DATE
:
953 sqlStmt
+= pDb
->typeInfDate
.TypeName
; break;
955 // For varchars, append the size of the string
956 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
959 // wxStrcat(sqlStmt, "(");
960 // wxStrcat(sqlStmt, itoa(colDefs[i].SzDataObj, s, 10));
961 // wxStrcat(sqlStmt, ")");
962 s
.sprintf("(%d)", colDefs
[i
].SzDataObj
);
963 sqlStmt
+= s
.GetData();
966 if (pDb
->Dbms() == dbmsSYBASE_ASE
|| pDb
->Dbms() == dbmsMY_SQL
)
968 if (colDefs
[i
].KeyField
)
970 sqlStmt
+= " NOT NULL";
976 // If there is a primary key defined, include it in the create statement
977 for (i
= j
= 0; i
< noCols
; i
++)
979 if (colDefs
[i
].KeyField
)
985 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
987 if (pDb
->Dbms() != dbmsMY_SQL
)
989 sqlStmt
+= ",CONSTRAINT ";
990 sqlStmt
+= tableName
;
991 sqlStmt
+= "_PIDX PRIMARY KEY (";
995 /* MySQL goes out on this one. We also declare the relevant key NON NULL above */
996 sqlStmt
+= ", PRIMARY KEY (";
999 // List column name(s) of column(s) comprising the primary key
1000 for (i
= j
= 0; i
< noCols
; i
++)
1002 if (colDefs
[i
].KeyField
)
1004 if (j
++) // Multi part key, comma separate names
1006 sqlStmt
+= colDefs
[i
].ColName
;
1011 // Append the closing parentheses for the create table statement
1014 pDb
->WriteSqlLog(sqlStmt
.GetData());
1016 #ifdef DBDEBUG_CONSOLE
1017 cout
<< endl
<< sqlStmt
.GetData() << endl
;
1020 // Execute the CREATE TABLE statement
1021 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
);
1022 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1024 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1025 pDb
->RollbackTrans();
1030 // Commit the transaction and close the cursor
1031 if (! pDb
->CommitTrans())
1033 if (! CloseCursor(hstmt
))
1036 // Database table created successfully
1039 } // wxTable::CreateTable()
1042 /********** wxTable::DropTable() **********/
1043 bool wxTable::DropTable()
1045 // NOTE: This function returns TRUE if the Table does not exist, but
1046 // only for identified databases. Code will need to be added
1047 // below for any other databases when those databases are defined
1048 // to handle this situation consistently
1050 // char sqlStmt[DB_MAX_STATEMENT_LEN];
1053 sqlStmt
.sprintf("DROP TABLE %s", tableName
);
1055 pDb
->WriteSqlLog(sqlStmt
.GetData());
1057 #ifdef DBDEBUG_CONSOLE
1058 cout
<< endl
<< sqlStmt
.GetData() << endl
;
1061 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1063 // Check for "Base table not found" error and ignore
1064 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1065 if (wxStrcmp(pDb
->sqlState
,"S0002")) // "Base table not found"
1067 // Check for product specific error codes
1068 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,"42000")) || // 5.x (and lower?)
1069 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,"S1000")) || // untested
1070 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,"08S01")))) // untested
1072 pDb
->DispNextError();
1073 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1074 pDb
->RollbackTrans();
1081 // Commit the transaction and close the cursor
1082 if (! pDb
->CommitTrans())
1084 if (! CloseCursor(hstmt
))
1088 } // wxTable::DropTable()
1091 /********** wxTable::CreateIndex() **********/
1092 bool wxTable::CreateIndex(const char * idxName
, bool unique
, int noIdxCols
, CidxDef
*pIdxDefs
, bool attemptDrop
)
1094 // char sqlStmt[DB_MAX_STATEMENT_LEN];
1097 // Drop the index first
1098 if (attemptDrop
&& !DropIndex(idxName
))
1101 // Build a CREATE INDEX statement
1102 sqlStmt
= "CREATE ";
1104 sqlStmt
+= "UNIQUE ";
1106 sqlStmt
+= "INDEX ";
1109 sqlStmt
+= tableName
;
1112 // Append list of columns making up index
1114 for (i
= 0; i
< noIdxCols
; i
++)
1116 sqlStmt
+= pIdxDefs
[i
].ColName
;
1117 /* Postgres doesn't cope with ASC */
1118 if (pDb
->Dbms() != dbmsPOSTGRES
)
1120 if (pIdxDefs
[i
].Ascending
)
1126 if ((i
+ 1) < noIdxCols
)
1130 // Append closing parentheses
1133 pDb
->WriteSqlLog(sqlStmt
.GetData());
1135 #ifdef DBDEBUG_CONSOLE
1136 cout
<< endl
<< sqlStmt
.GetData() << endl
<< endl
;
1139 // Execute the CREATE INDEX statement
1140 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1142 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1143 pDb
->RollbackTrans();
1148 // Commit the transaction and close the cursor
1149 if (! pDb
->CommitTrans())
1151 if (! CloseCursor(hstmt
))
1154 // Index Created Successfully
1157 } // wxTable::CreateIndex()
1160 /********** wxTable::DropIndex() **********/
1161 bool wxTable::DropIndex(const char * idxName
)
1163 // NOTE: This function returns TRUE if the Index does not exist, but
1164 // only for identified databases. Code will need to be added
1165 // below for any other databases when those databases are defined
1166 // to handle this situation consistently
1168 // char sqlStmt[DB_MAX_STATEMENT_LEN];
1171 if (pDb
->Dbms() == dbmsACCESS
)
1172 sqlStmt
.sprintf("DROP INDEX %s ON %s",idxName
,tableName
);
1173 else if (pDb
->Dbms() == dbmsSYBASE_ASE
)
1174 sqlStmt
.sprintf("DROP INDEX %s.%s",tableName
,idxName
);
1176 sqlStmt
.sprintf("DROP INDEX %s",idxName
);
1178 pDb
->WriteSqlLog(sqlStmt
.GetData());
1180 #ifdef DBDEBUG_CONSOLE
1181 cout
<< endl
<< sqlStmt
.GetData() << endl
;
1184 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1186 // Check for "Index not found" error and ignore
1187 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1188 if (wxStrcmp(pDb
->sqlState
,"S0012")) // "Index not found"
1190 // Check for product specific error codes
1191 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,"42000")) || // v5.x (and lower?)
1192 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,"S0002")) || // Base table not found
1193 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,"42S02")) // untested
1196 pDb
->DispNextError();
1197 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1198 pDb
->RollbackTrans();
1205 // Commit the transaction and close the cursor
1206 if (! pDb
->CommitTrans())
1208 if (! CloseCursor(hstmt
))
1212 } // wxTable::DropIndex()
1215 /********** wxTable::Insert() **********/
1216 int wxTable::Insert(void)
1224 // Insert the record by executing the already prepared insert statement
1226 retcode
=SQLExecute(hstmtInsert
);
1227 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1229 // Check to see if integrity constraint was violated
1230 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1231 if (! wxStrcmp(pDb
->sqlState
, "23000")) // Integrity constraint violated
1232 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1235 pDb
->DispNextError();
1236 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1241 // Record inserted into the datasource successfully
1244 } // wxTable::Insert()
1247 /********** wxTable::Update() **********/
1248 bool wxTable::Update(void)
1254 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1256 // Build the SQL UPDATE statement
1257 GetUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1259 pDb
->WriteSqlLog(sqlStmt
);
1261 #ifdef DBDEBUG_CONSOLE
1262 cout
<< endl
<< sqlStmt
.GetData() << endl
<< endl
;
1265 // Execute the SQL UPDATE statement
1266 return(execUpdate(sqlStmt
));
1268 } // wxTable::Update()
1271 /********** wxTable::Update(pSqlStmt) **********/
1272 bool wxTable::Update(const char *pSqlStmt
)
1278 pDb
->WriteSqlLog(pSqlStmt
);
1280 return(execUpdate(pSqlStmt
));
1282 } // wxTable::Update(pSqlStmt)
1285 /********** wxTable::UpdateWhere() **********/
1286 bool wxTable::UpdateWhere(const char *pWhereClause
)
1292 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1294 // Build the SQL UPDATE statement
1295 GetUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1297 pDb
->WriteSqlLog(sqlStmt
);
1299 #ifdef DBDEBUG_CONSOLE
1300 cout
<< endl
<< sqlStmt
.GetData() << endl
<< endl
;
1303 // Execute the SQL UPDATE statement
1304 return(execUpdate(sqlStmt
));
1306 } // wxTable::UpdateWhere()
1309 /********** wxTable::Delete() **********/
1310 bool wxTable::Delete(void)
1316 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1318 // Build the SQL DELETE statement
1319 GetDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1321 pDb
->WriteSqlLog(sqlStmt
);
1323 // Execute the SQL DELETE statement
1324 return(execDelete(sqlStmt
));
1326 } // wxTable::Delete()
1329 /********** wxTable::DeleteWhere() **********/
1330 bool wxTable::DeleteWhere(const char *pWhereClause
)
1336 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1338 // Build the SQL DELETE statement
1339 GetDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1341 pDb
->WriteSqlLog(sqlStmt
);
1343 // Execute the SQL DELETE statement
1344 return(execDelete(sqlStmt
));
1346 } // wxTable::DeleteWhere()
1349 /********** wxTable::DeleteMatching() **********/
1350 bool wxTable::DeleteMatching(void)
1356 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1358 // Build the SQL DELETE statement
1359 GetDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1361 pDb
->WriteSqlLog(sqlStmt
);
1363 // Execute the SQL DELETE statement
1364 return(execDelete(sqlStmt
));
1366 } // wxTable::DeleteMatching()
1369 /********** wxTable::GetUpdateStmt() **********/
1370 void wxTable::GetUpdateStmt(char *pSqlStmt
, int typeOfUpd
, const char *pWhereClause
)
1376 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
1377 bool firstColumn
= TRUE
;
1380 sprintf(pSqlStmt
, "UPDATE %s SET ", tableName
);
1382 // Append a list of columns to be updated
1384 for (i
= 0; i
< noCols
; i
++)
1386 // Only append Updateable columns
1387 if (colDefs
[i
].Updateable
)
1390 wxStrcat(pSqlStmt
, ",");
1392 firstColumn
= FALSE
;
1393 wxStrcat(pSqlStmt
, colDefs
[i
].ColName
);
1394 wxStrcat(pSqlStmt
, " = ?");
1398 // Append the WHERE clause to the SQL UPDATE statement
1399 wxStrcat(pSqlStmt
, " WHERE ");
1402 case DB_UPD_KEYFIELDS
:
1403 // If the datasource supports the ROWID column, build
1404 // the where on ROWID for efficiency purposes.
1405 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1406 if (CanUpdByROWID())
1409 char rowid
[ROWID_LEN
];
1411 // Get the ROWID value. If not successful retreiving the ROWID,
1412 // simply fall down through the code and build the WHERE clause
1413 // based on the key fields.
1414 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1416 wxStrcat(pSqlStmt
, "ROWID = '");
1417 wxStrcat(pSqlStmt
, rowid
);
1418 wxStrcat(pSqlStmt
, "'");
1422 // Unable to delete by ROWID, so build a WHERE
1423 // clause based on the keyfields.
1424 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1425 wxStrcat(pSqlStmt
, whereClause
);
1428 wxStrcat(pSqlStmt
, pWhereClause
);
1431 } // GetUpdateStmt()
1434 /********** wxTable::GetDeleteStmt() **********/
1435 void wxTable::GetDeleteStmt(char *pSqlStmt
, int typeOfDel
, const char *pWhereClause
)
1441 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
1445 // Handle the case of DeleteWhere() and the where clause is blank. It should
1446 // delete all records from the database in this case.
1447 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
== 0 || wxStrlen(pWhereClause
) == 0))
1449 sprintf(pSqlStmt
, "DELETE FROM %s", tableName
);
1453 sprintf(pSqlStmt
, "DELETE FROM %s WHERE ", tableName
);
1455 // Append the WHERE clause to the SQL DELETE statement
1458 case DB_DEL_KEYFIELDS
:
1459 // If the datasource supports the ROWID column, build
1460 // the where on ROWID for efficiency purposes.
1461 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1462 if (CanUpdByROWID())
1465 char rowid
[ROWID_LEN
];
1467 // Get the ROWID value. If not successful retreiving the ROWID,
1468 // simply fall down through the code and build the WHERE clause
1469 // based on the key fields.
1470 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1472 wxStrcat(pSqlStmt
, "ROWID = '");
1473 wxStrcat(pSqlStmt
, rowid
);
1474 wxStrcat(pSqlStmt
, "'");
1478 // Unable to delete by ROWID, so build a WHERE
1479 // clause based on the keyfields.
1480 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1481 wxStrcat(pSqlStmt
, whereClause
);
1484 wxStrcat(pSqlStmt
, pWhereClause
);
1486 case DB_DEL_MATCHING
:
1487 GetWhereClause(whereClause
, DB_WHERE_MATCHING
);
1488 wxStrcat(pSqlStmt
, whereClause
);
1492 } // GetDeleteStmt()
1495 /********** wxTable::GetWhereClause() **********/
1496 void wxTable::GetWhereClause(char *pWhereClause
, int typeOfWhere
, const char *qualTableName
)
1498 * Note: GetWhereClause() currently ignores timestamp columns.
1499 * They are not included as part of the where clause.
1502 bool moreThanOneColumn
= FALSE
;
1505 // Loop through the columns building a where clause as you go
1507 for (i
= 0; i
< noCols
; i
++)
1509 // Determine if this column should be included in the WHERE clause
1510 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1511 (typeOfWhere
== DB_WHERE_MATCHING
&& (! IsColNull(i
))))
1513 // Skip over timestamp columns
1514 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1516 // If there is more than 1 column, join them with the keyword "AND"
1517 if (moreThanOneColumn
)
1518 wxStrcat(pWhereClause
, " AND ");
1520 moreThanOneColumn
= TRUE
;
1521 // Concatenate where phrase for the column
1522 if (qualTableName
&& wxStrlen(qualTableName
))
1524 wxStrcat(pWhereClause
, qualTableName
);
1525 wxStrcat(pWhereClause
, ".");
1527 wxStrcat(pWhereClause
, colDefs
[i
].ColName
);
1528 wxStrcat(pWhereClause
, " = ");
1529 switch(colDefs
[i
].SqlCtype
)
1532 sprintf(colValue
, "'%s'", (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1535 sprintf(colValue
, "%hi", *((SWORD
*) colDefs
[i
].PtrDataObj
));
1538 sprintf(colValue
, "%hu", *((UWORD
*) colDefs
[i
].PtrDataObj
));
1541 sprintf(colValue
, "%li", *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1544 sprintf(colValue
, "%lu", *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1547 sprintf(colValue
, "%.6f", *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1550 sprintf(colValue
, "%.6f", *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1553 wxStrcat(pWhereClause
, colValue
);
1556 } // wxTable::GetWhereClause()
1559 /********** wxTable::IsColNull() **********/
1560 bool wxTable::IsColNull(int colNo
)
1562 switch(colDefs
[colNo
].SqlCtype
)
1565 return(((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] == 0);
1567 return(( *((SWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1569 return(( *((UWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1571 return(( *((SDWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1573 return(( *((UDWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1575 return(( *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1577 return((*((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1578 case SQL_C_TIMESTAMP
:
1579 TIMESTAMP_STRUCT
*pDt
;
1580 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
1581 if (pDt
->year
== 0 && pDt
->month
== 0 && pDt
->day
== 0)
1588 } // wxTable::IsColNull()
1591 /********** wxTable::CanSelectForUpdate() **********/
1592 bool wxTable::CanSelectForUpdate(void)
1594 if (pDb
->Dbms() == dbmsMY_SQL
)
1597 if (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
)
1602 } // wxTable::CanSelectForUpdate()
1605 /********** wxTable::CanUpdByROWID() **********/
1606 bool wxTable::CanUpdByROWID(void)
1609 * NOTE: Returning FALSE for now until this can be debugged,
1610 * as the ROWID is not getting updated correctly
1614 if (pDb
->Dbms() == dbmsORACLE
)
1619 } // wxTable::CanUpdByROWID()
1622 /********** wxTable::IsCursorClosedOnCommit() **********/
1623 bool wxTable::IsCursorClosedOnCommit(void)
1625 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
1630 } // wxTable::IsCursorClosedOnCommit()
1633 /********** wxTable::ClearMemberVars() **********/
1634 void wxTable::ClearMemberVars(void)
1636 // Loop through the columns setting each member variable to zero
1638 for (i
= 0; i
< noCols
; i
++)
1640 switch(colDefs
[i
].SqlCtype
)
1643 ((UCHAR FAR
*) colDefs
[i
].PtrDataObj
)[0] = 0;
1646 *((SWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1649 *((UWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1652 *((SDWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1655 *((UDWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1658 *((SFLOAT
*) colDefs
[i
].PtrDataObj
) = 0.0f
;
1661 *((SDOUBLE
*) colDefs
[i
].PtrDataObj
) = 0.0f
;
1663 case SQL_C_TIMESTAMP
:
1664 TIMESTAMP_STRUCT
*pDt
;
1665 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[i
].PtrDataObj
;
1677 } // wxTable::ClearMemberVars()
1680 /********** wxTable::SetQueryTimeout() **********/
1681 bool wxTable::SetQueryTimeout(UDWORD nSeconds
)
1683 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1684 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
1685 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1686 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
1687 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1688 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
1689 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1690 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
1692 // Completed Successfully
1695 } // wxTable::SetQueryTimeout()
1698 /********** wxTable::SetColDefs() **********/
1699 void wxTable::SetColDefs (int index
, const char *fieldName
, int dataType
, void *pData
,
1700 int cType
, int size
, bool keyField
, bool upd
,
1701 bool insAllow
, bool derivedCol
)
1703 if (!colDefs
) // May happen if the database connection fails
1706 if (wxStrlen(fieldName
) > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
1708 wxStrncpy (colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
1709 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
1712 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
1714 colDefs
[index
].DbDataType
= dataType
;
1715 colDefs
[index
].PtrDataObj
= pData
;
1716 colDefs
[index
].SqlCtype
= cType
;
1717 colDefs
[index
].SzDataObj
= size
;
1718 colDefs
[index
].KeyField
= keyField
;
1719 colDefs
[index
].DerivedCol
= derivedCol
;
1720 // Derived columns by definition would NOT be "Insertable" or "Updateable"
1723 colDefs
[index
].Updateable
= FALSE
;
1724 colDefs
[index
].InsertAllowed
= FALSE
;
1728 colDefs
[index
].Updateable
= upd
;
1729 colDefs
[index
].InsertAllowed
= insAllow
;
1732 colDefs
[index
].Null
= FALSE
;
1734 } // wxTable::SetColDefs()
1737 /********** wxTable::SetColDef() **********/
1738 // BJO20000121 : changed prototype in order to return proper pointer on wxColDataPtr's array
1739 //bool wxTable::SetColDefs(wxColInf *pColInfs, ULONG numCols, wxColDataPtr *pColDataPtrs)
1740 wxColDataPtr
* wxTable::SetColDefs (wxColInf
*pColInfs
, ULONG numCols
)
1743 wxColDataPtr
*pColDataPtrs
= NULL
;
1750 pColDataPtrs
= new wxColDataPtr
[numCols
+1];
1752 for (index
= 0; index
< numCols
; index
++)
1756 title.sprintf("Catalog: %s, Schema: %s, Table name: %s",pColInfs[index].catalog,pColInfs[index].schema,pColInfs[index].tableName);
1757 msg.sprintf("Column name: %s\nData type: %04d\nType name: %s\nColumn size: %d\nBuffer len: %d\nDecimals:%d\nRadix: %d\nNullable: %d\nRemarks: %s",
1758 pColInfs[index].colName,pColInfs[index].sqlDataType,pColInfs[index].typeName,pColInfs[index].columnSize,pColInfs[index].bufferLength,pColInfs[index].decimalDigits,pColInfs[index].numPrecRadix,pColInfs[index].nullable,pColInfs[index].remarks);
1759 msg += " \nDB_DATA_TYPE: ";
1760 switch(pColInfs[index].dbDataType)
1762 case DB_DATA_TYPE_VARCHAR:
1763 msg += pDb->typeInfVarchar.TypeName; break;
1764 case DB_DATA_TYPE_INTEGER:
1765 msg += pDb->typeInfInteger.TypeName; break;
1766 case DB_DATA_TYPE_FLOAT:
1767 msg += pDb->typeInfFloat.TypeName; break;
1768 case DB_DATA_TYPE_DATE:
1769 msg += pDb->typeInfDate.TypeName; break;
1771 wxMessageBox(msg.GetData(),title.GetData());
1773 // Process the fields
1774 switch (pColInfs
[index
].dbDataType
)
1776 case DB_DATA_TYPE_VARCHAR
:
1778 pColDataPtrs
[index
].PtrDataObj
= new char[pColInfs
[index
].bufferLength
+1];
1779 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferLength
;
1780 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
1783 case DB_DATA_TYPE_INTEGER
:
1785 // Can be long or short
1786 if (pColInfs
[index
].bufferLength
== sizeof(long))
1788 pColDataPtrs
[index
].PtrDataObj
= new long;
1789 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
1790 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
1794 pColDataPtrs
[index
].PtrDataObj
= new short;
1795 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
1796 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
1800 case DB_DATA_TYPE_FLOAT
:
1802 // Can be float or double
1803 if (pColInfs
[index
].bufferLength
== sizeof(float))
1805 pColDataPtrs
[index
].PtrDataObj
= new float;
1806 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
1807 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
1811 pColDataPtrs
[index
].PtrDataObj
= new double;
1812 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
1813 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
1817 case DB_DATA_TYPE_DATE
:
1819 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
1820 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
1821 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
1826 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
1829 return (pColDataPtrs
);
1830 } // wxTable::SetColDef()
1833 /********** wxTable::SetCursor() **********/
1834 void wxTable::SetCursor(HSTMT
*hstmtActivate
)
1836 if (hstmtActivate
== DEFAULT_CURSOR
)
1837 hstmt
= *hstmtDefault
;
1839 hstmt
= *hstmtActivate
;
1841 } // wxTable::SetCursor()
1844 /********** wxTable::Count(const char *) **********/
1845 ULONG
wxTable::Count(const char *args
)
1848 // char sqlStmt[DB_MAX_STATEMENT_LEN];
1852 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
1853 sqlStmt
= "SELECT COUNT(";
1855 sqlStmt
+= ") FROM ";
1856 sqlStmt
+= queryTableName
;
1858 if (from
&& wxStrlen(from
))
1861 // Add the where clause if one is provided
1862 if (where
&& wxStrlen(where
))
1864 sqlStmt
+= " WHERE ";
1868 pDb
->WriteSqlLog(sqlStmt
.GetData());
1870 // Initialize the Count cursor if it's not already initialized
1873 hstmtCount
= NewCursor(FALSE
,FALSE
);
1879 // Execute the SQL statement
1880 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.GetData(), SQL_NTS
) != SQL_SUCCESS
)
1882 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1887 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
1889 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1893 // Obtain the result
1894 if (SQLGetData(*hstmtCount
, 1, SQL_C_ULONG
, &l
, sizeof(l
), &cb
) != SQL_SUCCESS
)
1896 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1901 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
1902 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
1904 // Return the record count
1907 } // wxTable::Count()
1910 /********** wxTable::Refresh() **********/
1911 bool wxTable::Refresh(void)
1915 // Switch to the internal cursor so any active cursors are not corrupted
1916 HSTMT currCursor
= GetCursor();
1917 hstmt
= hstmtInternal
;
1919 // Save the where and order by clauses
1920 char *saveWhere
= where
;
1921 char *saveOrderBy
= orderBy
;
1923 // Build a where clause to refetch the record with. Try and use the
1924 // ROWID if it's available, ow use the key fields.
1925 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
+1];
1926 wxStrcpy(whereClause
, "");
1927 if (CanUpdByROWID())
1930 char rowid
[ROWID_LEN
+1];
1932 // Get the ROWID value. If not successful retreiving the ROWID,
1933 // simply fall down through the code and build the WHERE clause
1934 // based on the key fields.
1935 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1937 wxStrcat(whereClause
, queryTableName
);
1938 wxStrcat(whereClause
, ".ROWID = '");
1939 wxStrcat(whereClause
, rowid
);
1940 wxStrcat(whereClause
, "'");
1944 // If unable to use the ROWID, build a where clause from the keyfields
1945 if (wxStrlen(whereClause
) == 0)
1946 GetWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
1948 // Requery the record
1949 where
= whereClause
;
1954 if (result
&& !GetNext())
1957 // Switch back to original cursor
1958 SetCursor(&currCursor
);
1960 // Free the internal cursor
1961 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
1962 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
1964 // Restore the original where and order by clauses
1966 orderBy
= saveOrderBy
;
1970 } // wxTable::Refresh()
1973 /********** wxTable::SetNull(int colNo) **********/
1974 bool wxTable::SetNull(int colNo
)
1977 return(colDefs
[colNo
].Null
= TRUE
);
1981 } // wxTable::SetNull(int colNo)
1984 /********** wxTable::SetNull(char *colName) **********/
1985 bool wxTable::SetNull(const char *colName
)
1988 for (i
= 0; i
< noCols
; i
++)
1990 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
1995 return(colDefs
[i
].Null
= TRUE
);
1999 } // wxTable::SetNull(char *colName)
2002 /********** wxTable::NewCursor() **********/
2003 HSTMT
*wxTable::NewCursor(bool setCursor
, bool bindColumns
)
2005 HSTMT
*newHSTMT
= new HSTMT
;
2010 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2012 pDb
->DispAllErrors(henv
, hdbc
);
2017 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2019 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2026 if(!bindCols(*newHSTMT
))
2034 SetCursor(newHSTMT
);
2038 } // wxTable::NewCursor()
2041 /********** wxTable::DeleteCursor() **********/
2042 bool wxTable::DeleteCursor(HSTMT
*hstmtDel
)
2046 if (!hstmtDel
) // Cursor already deleted
2049 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2051 pDb
->DispAllErrors(henv
, hdbc
);
2059 } // wxTable::DeleteCursor()
2061 #endif // wxUSE_ODBC