1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence, plus:
12 // Notice: This class library and its intellectual design are free of charge for use,
13 // modification, enhancement, debugging under the following conditions:
14 // 1) These classes may only be used as part of the implementation of a
15 // wxWindows-based application
16 // 2) All enhancements and bug fixes are to be submitted back to the wxWindows
17 // user groups free of all charges for use with the wxWindows library.
18 // 3) These classes may not be distributed as part of any other class library,
19 // DLL, text (written or electronic), other than a complete distribution of
20 // the wxWindows GUI development toolkit.
21 ///////////////////////////////////////////////////////////////////////////////
28 // Use this line for wxWindows v1.x
30 // Use this line for wxWindows v2.x
31 #include "wx/wxprec.h"
32 #include "wx/version.h"
34 #if wxMAJOR_VERSION == 2
36 #pragma implementation "dbtable.h"
40 #ifdef DBDEBUG_CONSOLE
41 #include "wx/ioswrap.h"
49 #if wxMAJOR_VERSION == 2
51 #include "wx/string.h"
52 #include "wx/object.h"
55 #include "wx/msgdlg.h"
58 #include "wx/filefn.h"
61 #if wxMAJOR_VERSION == 1
62 # 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 /********** wxDbTable::wxDbTable() **********/
106 wxDbTable::wxDbTable(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
= ""; // Where clause
123 orderBy
= ""; // Order By clause
124 from
= ""; // From clause
125 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
128 wxStrcpy(tablePath
,"");
129 wxStrcpy(tableName
,"");
130 wxStrcpy(queryTableName
,"");
134 wxStrcpy(tableName
, tblName
); // Table Name
136 wxStrcpy(tablePath
, tblPath
); // Table Path - used for dBase files
138 if (qryTblName
) // Name of the table/view to query
139 wxStrcpy(queryTableName
, qryTblName
);
141 wxStrcpy(queryTableName
, tblName
);
146 pDb
->incrementTableCount();
149 tableID
= ++lastTableID
;
150 s
.sprintf("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]", tblName
,tableID
,pDb
);
153 wxTablesInUse
*tableInUse
;
154 tableInUse
= new wxTablesInUse();
155 tableInUse
->tableName
= tblName
;
156 tableInUse
->tableID
= tableID
;
157 tableInUse
->pDb
= pDb
;
158 TablesInUse
.Append(tableInUse
);
161 pDb
->WriteSqlLog(s
.c_str());
163 // Grab the HENV and HDBC from the wxDb object
164 henv
= pDb
->GetHENV();
165 hdbc
= pDb
->GetHDBC();
167 // Allocate space for column definitions
169 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column defintion
171 // Allocate statement handles for the table
174 // Allocate a separate statement handle for performing inserts
175 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
176 pDb
->DispAllErrors(henv
, hdbc
);
177 // Allocate a separate statement handle for performing deletes
178 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
179 pDb
->DispAllErrors(henv
, hdbc
);
180 // Allocate a separate statement handle for performing updates
181 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
182 pDb
->DispAllErrors(henv
, hdbc
);
184 // Allocate a separate statement handle for internal use
185 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
186 pDb
->DispAllErrors(henv
, hdbc
);
188 // Set the cursor type for the statement handles
189 cursorType
= SQL_CURSOR_STATIC
;
191 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
193 // Check to see if cursor type is supported
194 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
195 if (! wxStrcmp(pDb
->sqlState
, "01S02")) // Option Value Changed
197 // Datasource does not support static cursors. Driver
198 // will substitute a cursor type. Call SQLGetStmtOption()
199 // to determine which cursor type was selected.
200 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
201 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
202 #ifdef DBDEBUG_CONSOLE
203 cout
<< "Static cursor changed to: ";
206 case SQL_CURSOR_FORWARD_ONLY
:
207 cout
<< "Forward Only";
209 case SQL_CURSOR_STATIC
:
212 case SQL_CURSOR_KEYSET_DRIVEN
:
213 cout
<< "Keyset Driven";
215 case SQL_CURSOR_DYNAMIC
:
219 cout
<< endl
<< endl
;
222 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
224 // Force the use of a forward only cursor...
225 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
226 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
228 // Should never happen
229 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
236 pDb
->DispNextError();
237 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
240 #ifdef DBDEBUG_CONSOLE
242 cout
<< "Cursor Type set to STATIC" << endl
<< endl
;
247 // Set the cursor type for the INSERT statement handle
248 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
249 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
250 // Set the cursor type for the DELETE statement handle
251 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
252 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
253 // Set the cursor type for the UPDATE statement handle
254 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
255 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
258 // Make the default cursor the active cursor
259 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
260 assert(hstmtDefault
);
261 hstmt
= *hstmtDefault
;
263 } // wxDbTable::wxDbTable()
266 /********** wxDbTable::~wxDbTable() **********/
267 wxDbTable::~wxDbTable()
272 s
.sprintf("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]", tableName
,tableID
,pDb
);
273 pDb
->WriteSqlLog(s
.c_str());
279 TablesInUse
.DeleteContents(TRUE
);
283 pNode
= TablesInUse
.First();
284 while (pNode
&& !found
)
286 if (((wxTablesInUse
*)pNode
->Data())->tableID
== tableID
)
289 if (!TablesInUse
.DeleteNode(pNode
))
290 wxLogDebug (s
.c_str(),wxT("Unable to delete node!"));
293 pNode
= pNode
->Next();
298 msg
.sprintf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
299 wxLogDebug (msg
.c_str(),wxT("NOTICE..."));
304 // Decrement the wxDb table count
306 pDb
->decrementTableCount();
308 // Delete memory allocated for column definitions
312 // Free statement handles
316 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
317 pDb
->DispAllErrors(henv
, hdbc
);
320 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
323 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
324 pDb
->DispAllErrors(henv
, hdbc
);
328 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
329 pDb
->DispAllErrors(henv
, hdbc
);
331 // Delete dynamically allocated cursors
333 DeleteCursor(hstmtDefault
);
336 DeleteCursor(hstmtCount
);
338 } // wxDbTable::~wxDbTable()
342 /***************************** PRIVATE FUNCTIONS *****************************/
346 /********** wxDbTable::bindInsertParams() **********/
347 bool wxDbTable::bindInsertParams(void)
354 UDWORD precision
= 0;
357 // Bind each column (that can be inserted) of the table to a parameter marker
359 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
361 if (! colDefs
[i
].InsertAllowed
)
363 switch(colDefs
[i
].DbDataType
)
365 case DB_DATA_TYPE_VARCHAR
:
366 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
367 precision
= colDefs
[i
].SzDataObj
;
369 colDefs
[i
].CbValue
= SQL_NTS
;
371 case DB_DATA_TYPE_INTEGER
:
372 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
373 precision
= pDb
->GetTypeInfInteger().Precision
;
375 colDefs
[i
].CbValue
= 0;
377 case DB_DATA_TYPE_FLOAT
:
378 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
379 precision
= pDb
->GetTypeInfFloat().Precision
;
380 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
381 // SQL Sybase Anywhere v5.5 returned a negative number for the
382 // MaxScale. This caused ODBC to kick out an error on ibscale.
383 // I check for this here and set the scale = precision.
385 // scale = (short) precision;
386 colDefs
[i
].CbValue
= 0;
388 case DB_DATA_TYPE_DATE
:
389 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
390 precision
= pDb
->GetTypeInfDate().Precision
;
392 colDefs
[i
].CbValue
= 0;
398 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
399 colDefs
[i
].Null
= FALSE
;
402 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
403 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
404 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
406 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
410 // Completed successfully
413 } // wxDbTable::bindInsertParams()
416 /********** wxDbTable::bindUpdateParams() **********/
417 bool wxDbTable::bindUpdateParams(void)
424 UDWORD precision
= 0;
427 // Bind each UPDATEABLE column of the table to a parameter marker
429 for (i
= 0, colNo
= 1; i
< noCols
; i
++)
431 if (! colDefs
[i
].Updateable
)
433 switch(colDefs
[i
].DbDataType
)
435 case DB_DATA_TYPE_VARCHAR
:
436 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
437 precision
= colDefs
[i
].SzDataObj
;
439 colDefs
[i
].CbValue
= SQL_NTS
;
441 case DB_DATA_TYPE_INTEGER
:
442 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
443 precision
= pDb
->GetTypeInfInteger().Precision
;
445 colDefs
[i
].CbValue
= 0;
447 case DB_DATA_TYPE_FLOAT
:
448 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
449 precision
= pDb
->GetTypeInfFloat().Precision
;
450 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
451 // SQL Sybase Anywhere v5.5 returned a negative number for the
452 // MaxScale. This caused ODBC to kick out an error on ibscale.
453 // I check for this here and set the scale = precision.
455 // scale = (short) precision;
456 colDefs
[i
].CbValue
= 0;
458 case DB_DATA_TYPE_DATE
:
459 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
460 precision
= pDb
->GetTypeInfDate().Precision
;
462 colDefs
[i
].CbValue
= 0;
466 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
467 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
468 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
470 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
474 // Completed successfully
477 } // wxDbTable::bindUpdateParams()
480 /********** wxDbTable::bindCols() **********/
481 bool wxDbTable::bindCols(HSTMT cursor
)
485 // Bind each column of the table to a memory address for fetching data
487 for (i
= 0; i
< noCols
; i
++)
489 if (SQLBindCol(cursor
, i
+1, colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
490 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
492 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
496 // Completed successfully
499 } // wxDbTable::bindCols()
502 /********** wxDbTable::getRec() **********/
503 bool wxDbTable::getRec(UWORD fetchType
)
507 if (!pDb
->FwdOnlyCursors())
509 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
513 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
514 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
516 if (retcode
== SQL_NO_DATA_FOUND
)
519 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
524 // Fetch the next record from the record set
525 retcode
= SQLFetch(hstmt
);
526 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
528 if (retcode
== SQL_NO_DATA_FOUND
)
531 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
535 // Completed successfully
538 } // wxDbTable::getRec()
541 /********** wxDbTable::execDelete() **********/
542 bool wxDbTable::execDelete(const char *pSqlStmt
)
544 // Execute the DELETE statement
545 if (SQLExecDirect(hstmtDelete
, (UCHAR FAR
*) pSqlStmt
, SQL_NTS
) != SQL_SUCCESS
)
546 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
548 // Record deleted successfully
551 } // wxDbTable::execDelete()
554 /********** wxDbTable::execUpdate() **********/
555 bool wxDbTable::execUpdate(const char *pSqlStmt
)
557 // Execute the UPDATE statement
558 if (SQLExecDirect(hstmtUpdate
, (UCHAR FAR
*) pSqlStmt
, SQL_NTS
) != SQL_SUCCESS
)
559 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
561 // Record deleted successfully
564 } // wxDbTable::execUpdate()
567 /********** wxDbTable::query() **********/
568 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const char *pSqlStmt
)
570 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
572 // Set the selectForUpdate member variable
574 // The user may wish to select for update, but the DBMS may not be capable
575 selectForUpdate
= CanSelectForUpdate();
577 selectForUpdate
= FALSE
;
579 // Set the SQL SELECT string
580 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
581 { // so generate a select statement.
582 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
583 pDb
->WriteSqlLog(sqlStmt
);
586 This is the block of code that got added during the 2.2.1 merge with
587 the 2.2 main branch that somehow got added here when it should not have. - gt
590 wxStrcpy(sqlStmt, pSqlStmt);
592 SQLFreeStmt(hstmt, SQL_CLOSE);
593 if (SQLExecDirect(hstmt, (UCHAR FAR *) sqlStmt, SQL_NTS) == SQL_SUCCESS)
597 pDb->DispAllErrors(henv, hdbc, hstmt);
601 // Make sure the cursor is closed first
602 if (!CloseCursor(hstmt
))
605 // Execute the SQL SELECT statement
607 retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
: sqlStmt
), SQL_NTS
);
608 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
609 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
611 // Completed successfully
614 } // wxDbTable::query()
617 /***************************** PUBLIC FUNCTIONS *****************************/
620 /********** wxDbTable::Open() **********/
621 bool wxDbTable::Open(void)
629 // Verify that the table exists in the database
630 if (!pDb
->TableExists(tableName
,pDb
->GetUsername(),tablePath
))
633 if (wxStrcmp(tablePath
,""))
634 s
.sprintf(wxT("Error opening '%s/%s'.\n"),tablePath
,tableName
);
636 s
.sprintf(wxT("Error opening '%s'.\n"), tableName
);
637 if (!pDb
->TableExists(tableName
,NULL
,tablePath
))
638 s
+= wxT("Table/view does not exist in the database.\n");
640 s
+= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
641 pDb
->LogError(s
.c_str());
645 // Bind the member variables for field exchange between
646 // the wxDbTable object and the ODBC record.
649 if (!bindInsertParams()) // Inserts
652 if (!bindUpdateParams()) // Updates
656 if (!bindCols(*hstmtDefault
)) // Selects
659 if (!bindCols(hstmtInternal
)) // Internal use only
663 * Do NOT bind the hstmtCount cursor!!!
666 // Build an insert statement using parameter markers
667 if (!queryOnly
&& noCols
> 0)
669 bool needComma
= FALSE
;
670 sqlStmt
.sprintf("INSERT INTO %s (", tableName
);
671 for (i
= 0; i
< noCols
; i
++)
673 if (! colDefs
[i
].InsertAllowed
)
677 sqlStmt
+= colDefs
[i
].ColName
;
681 sqlStmt
+= ") VALUES (";
683 int insertableCount
= 0;
685 for (i
= 0; i
< noCols
; i
++)
687 if (! colDefs
[i
].InsertAllowed
)
697 // Prepare the insert statement for execution
700 if (SQLPrepare(hstmtInsert
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
701 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
707 // Completed successfully
710 } // wxDbTable::Open()
713 /********** wxDbTable::Query() **********/
714 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
717 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
719 } // wxDbTable::Query()
722 /********** wxDbTable::QueryBySqlStmt() **********/
723 bool wxDbTable::QueryBySqlStmt(const char *pSqlStmt
)
725 pDb
->WriteSqlLog(pSqlStmt
);
727 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
729 } // wxDbTable::QueryBySqlStmt()
732 /********** wxDbTable::QueryMatching() **********/
733 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
736 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
738 } // wxDbTable::QueryMatching()
741 /********** wxDbTable::QueryOnKeyFields() **********/
742 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
745 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
747 } // wxDbTable::QueryOnKeyFields()
750 /********** wxDbTable::GetPrev() **********/
751 bool wxDbTable::GetPrev(void)
753 if (pDb
->FwdOnlyCursors())
755 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
759 return(getRec(SQL_FETCH_PRIOR
));
761 } // wxDbTable::GetPrev()
764 /********** wxDbTable::operator-- **********/
765 bool wxDbTable::operator--(int)
767 if (pDb
->FwdOnlyCursors())
769 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
773 return(getRec(SQL_FETCH_PRIOR
));
775 } // wxDbTable::operator--
778 /********** wxDbTable::GetFirst() **********/
779 bool wxDbTable::GetFirst(void)
781 if (pDb
->FwdOnlyCursors())
783 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
787 return(getRec(SQL_FETCH_FIRST
));
789 } // wxDbTable::GetFirst()
792 /********** wxDbTable::GetLast() **********/
793 bool wxDbTable::GetLast(void)
795 if (pDb
->FwdOnlyCursors())
797 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
801 return(getRec(SQL_FETCH_LAST
));
803 } // wxDbTable::GetLast()
806 /********** wxDbTable::BuildSelectStmt() **********/
807 void wxDbTable::BuildSelectStmt(char *pSqlStmt
, int typeOfSelect
, bool distinct
)
809 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
813 // Build a select statement to query the database
814 wxStrcpy(pSqlStmt
, "SELECT ");
816 // SELECT DISTINCT values only?
818 wxStrcat(pSqlStmt
, "DISTINCT ");
820 // Was a FROM clause specified to join tables to the base table?
821 // Available for ::Query() only!!!
822 bool appendFromClause
= FALSE
;
823 #if wxODBC_BACKWARD_COMPATABILITY
824 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
825 appendFromClause
= TRUE
;
827 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
828 appendFromClause
= TRUE
;
831 // Add the column list
833 for (i
= 0; i
< noCols
; i
++)
835 // If joining tables, the base table column names must be qualified to avoid ambiguity
836 if (appendFromClause
)
838 wxStrcat(pSqlStmt
, queryTableName
);
839 wxStrcat(pSqlStmt
, ".");
841 wxStrcat(pSqlStmt
, colDefs
[i
].ColName
);
843 wxStrcat(pSqlStmt
, ",");
846 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
847 // the ROWID if querying distinct records. The rowid will always be unique.
848 if (!distinct
&& CanUpdByROWID())
850 // If joining tables, the base table column names must be qualified to avoid ambiguity
851 if (appendFromClause
)
853 wxStrcat(pSqlStmt
, ",");
854 wxStrcat(pSqlStmt
, queryTableName
);
855 wxStrcat(pSqlStmt
, ".ROWID");
858 wxStrcat(pSqlStmt
, ",ROWID");
861 // Append the FROM tablename portion
862 wxStrcat(pSqlStmt
, " FROM ");
863 wxStrcat(pSqlStmt
, queryTableName
);
865 // Sybase uses the HOLDLOCK keyword to lock a record during query.
866 // The HOLDLOCK keyword follows the table name in the from clause.
867 // Each table in the from clause must specify HOLDLOCK or
868 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
869 // is parsed but ignored in SYBASE Transact-SQL.
870 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
871 wxStrcat(pSqlStmt
, " HOLDLOCK");
873 if (appendFromClause
)
874 wxStrcat(pSqlStmt
, from
);
876 // Append the WHERE clause. Either append the where clause for the class
877 // or build a where clause. The typeOfSelect determines this.
880 case DB_SELECT_WHERE
:
881 #if wxODBC_BACKWARD_COMPATABILITY
882 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
884 if (where
.Length()) // May not want a where clause!!!
887 wxStrcat(pSqlStmt
, " WHERE ");
888 wxStrcat(pSqlStmt
, where
);
891 case DB_SELECT_KEYFIELDS
:
892 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
893 if (wxStrlen(whereClause
))
895 wxStrcat(pSqlStmt
, " WHERE ");
896 wxStrcat(pSqlStmt
, whereClause
);
899 case DB_SELECT_MATCHING
:
900 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
901 if (wxStrlen(whereClause
))
903 wxStrcat(pSqlStmt
, " WHERE ");
904 wxStrcat(pSqlStmt
, whereClause
);
909 // Append the ORDER BY clause
910 #if wxODBC_BACKWARD_COMPATABILITY
911 if (orderBy
&& wxStrlen(orderBy
))
913 if (orderBy
.Length())
916 wxStrcat(pSqlStmt
, " ORDER BY ");
917 wxStrcat(pSqlStmt
, orderBy
);
920 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
921 // parses the FOR UPDATE clause but ignores it. See the comment above on the
922 // HOLDLOCK for Sybase.
923 if (selectForUpdate
&& CanSelectForUpdate())
924 wxStrcat(pSqlStmt
, " FOR UPDATE");
926 } // wxDbTable::BuildSelectStmt()
929 /********** wxDbTable::GetRowNum() **********/
930 UWORD
wxDbTable::GetRowNum(void)
934 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
936 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
940 // Completed successfully
941 return((UWORD
) rowNum
);
943 } // wxDbTable::GetRowNum()
946 /********** wxDbTable::CloseCursor() **********/
947 bool wxDbTable::CloseCursor(HSTMT cursor
)
949 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
950 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
952 // Completed successfully
955 } // wxDbTable::CloseCursor()
958 /********** wxDbTable::CreateTable() **********/
959 bool wxDbTable::CreateTable(bool attemptDrop
)
967 #ifdef DBDEBUG_CONSOLE
968 cout
<< "Creating Table " << tableName
<< "..." << endl
;
972 if (attemptDrop
&& !DropTable())
976 #ifdef DBDEBUG_CONSOLE
977 for (i
= 0; i
< noCols
; i
++)
979 // Exclude derived columns since they are NOT part of the base table
980 if (colDefs
[i
].DerivedCol
)
982 cout
<< i
+ 1 << ": " << colDefs
[i
].ColName
<< "; ";
983 switch(colDefs
[i
].DbDataType
)
985 case DB_DATA_TYPE_VARCHAR
:
986 cout
<< pDb
->typeInfVarchar
.TypeName
<< "(" << colDefs
[i
].SzDataObj
<< ")";
988 case DB_DATA_TYPE_INTEGER
:
989 cout
<< pDb
->typeInfInteger
.TypeName
;
991 case DB_DATA_TYPE_FLOAT
:
992 cout
<< pDb
->typeInfFloat
.TypeName
;
994 case DB_DATA_TYPE_DATE
:
995 cout
<< pDb
->typeInfDate
.TypeName
;
1002 // Build a CREATE TABLE string from the colDefs structure.
1003 bool needComma
= FALSE
;
1004 sqlStmt
.sprintf("CREATE TABLE %s (", tableName
);
1006 for (i
= 0; i
< noCols
; i
++)
1008 // Exclude derived columns since they are NOT part of the base table
1009 if (colDefs
[i
].DerivedCol
)
1015 sqlStmt
+= colDefs
[i
].ColName
;
1018 switch(colDefs
[i
].DbDataType
)
1020 case DB_DATA_TYPE_VARCHAR
:
1021 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1023 case DB_DATA_TYPE_INTEGER
:
1024 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1026 case DB_DATA_TYPE_FLOAT
:
1027 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1029 case DB_DATA_TYPE_DATE
:
1030 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1033 // For varchars, append the size of the string
1034 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1037 // wxStrcat(sqlStmt, "(");
1038 // wxStrcat(sqlStmt, itoa(colDefs[i].SzDataObj, s, 10));
1039 // wxStrcat(sqlStmt, ")");
1040 s
.sprintf("(%d)", colDefs
[i
].SzDataObj
);
1041 sqlStmt
+= s
.c_str();
1044 if (pDb
->Dbms() == dbmsDB2
||
1045 pDb
->Dbms() == dbmsMY_SQL
||
1046 pDb
->Dbms() == dbmsSYBASE_ASE
||
1047 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1049 if (colDefs
[i
].KeyField
)
1051 sqlStmt
+= " NOT NULL";
1057 // If there is a primary key defined, include it in the create statement
1058 for (i
= j
= 0; i
< noCols
; i
++)
1060 if (colDefs
[i
].KeyField
)
1066 if (j
&& pDb
->Dbms() != dbmsDBASE
) // Found a keyfield
1068 if (pDb
->Dbms() != dbmsMY_SQL
)
1070 sqlStmt
+= ",CONSTRAINT ";
1071 sqlStmt
+= tableName
;
1072 sqlStmt
+= "_PIDX PRIMARY KEY (";
1076 /* MySQL goes out on this one. We also declare the relevant key NON NULL above */
1077 sqlStmt
+= ", PRIMARY KEY (";
1080 // List column name(s) of column(s) comprising the primary key
1081 for (i
= j
= 0; i
< noCols
; i
++)
1083 if (colDefs
[i
].KeyField
)
1085 if (j
++) // Multi part key, comma separate names
1087 sqlStmt
+= colDefs
[i
].ColName
;
1092 // Append the closing parentheses for the create table statement
1095 pDb
->WriteSqlLog(sqlStmt
.c_str());
1097 #ifdef DBDEBUG_CONSOLE
1098 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1101 // Execute the CREATE TABLE statement
1102 RETCODE retcode
= SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1103 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1105 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1106 pDb
->RollbackTrans();
1111 // Commit the transaction and close the cursor
1112 if (!pDb
->CommitTrans())
1114 if (!CloseCursor(hstmt
))
1117 // Database table created successfully
1120 } // wxDbTable::CreateTable()
1123 /********** wxDbTable::DropTable() **********/
1124 bool wxDbTable::DropTable()
1126 // NOTE: This function returns TRUE if the Table does not exist, but
1127 // only for identified databases. Code will need to be added
1128 // below for any other databases when those databases are defined
1129 // to handle this situation consistently
1133 sqlStmt
.sprintf("DROP TABLE %s", tableName
);
1135 pDb
->WriteSqlLog(sqlStmt
.c_str());
1137 #ifdef DBDEBUG_CONSOLE
1138 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1141 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1143 // Check for "Base table not found" error and ignore
1144 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1145 if (wxStrcmp(pDb
->sqlState
,"S0002") && wxStrcmp(pDb
->sqlState
, "S1000")) // "Base table not found"
1147 // Check for product specific error codes
1148 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,"42000")) || // 5.x (and lower?)
1149 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,"37000")) ||
1150 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,"08S01"))))
1152 pDb
->DispNextError();
1153 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1154 pDb
->RollbackTrans();
1161 // Commit the transaction and close the cursor
1162 if (! pDb
->CommitTrans())
1164 if (! CloseCursor(hstmt
))
1168 } // wxDbTable::DropTable()
1171 /********** wxDbTable::CreateIndex() **********/
1172 bool wxDbTable::CreateIndex(const char * idxName
, bool unique
, int noIdxCols
, wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1176 // Drop the index first
1177 if (attemptDrop
&& !DropIndex(idxName
))
1180 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1181 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1182 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1183 // table was created, then months later you determine that an additional index while
1184 // give better performance, so you want to add an index).
1186 // The following block of code will modify the column definition to make the column be
1187 // defined with the "NOT NULL" qualifier.
1188 if (pDb
->Dbms() == dbmsMY_SQL
)
1193 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1197 // Find the column definition that has the ColName that matches the
1198 // index column name. We need to do this to get the DB_DATA_TYPE of
1199 // the index column, as MySQL's syntax for the ALTER column requires
1201 while (!found
&& (j
< this->noCols
))
1203 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1211 wxString typeNameAndSize
;
1213 switch(colDefs
[j
].DbDataType
)
1215 case DB_DATA_TYPE_VARCHAR
:
1216 typeNameAndSize
= pDb
->GetTypeInfVarchar().TypeName
;
1218 case DB_DATA_TYPE_INTEGER
:
1219 typeNameAndSize
= pDb
->GetTypeInfInteger().TypeName
;
1221 case DB_DATA_TYPE_FLOAT
:
1222 typeNameAndSize
= pDb
->GetTypeInfFloat().TypeName
;
1224 case DB_DATA_TYPE_DATE
:
1225 typeNameAndSize
= pDb
->GetTypeInfDate().TypeName
;
1229 // For varchars, append the size of the string
1230 if (colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1233 s
.sprintf("(%d)", colDefs
[i
].SzDataObj
);
1234 typeNameAndSize
+= s
.c_str();
1237 sqlStmt
.sprintf("ALTER TABLE %s MODIFY %s %s NOT NULL",tableName
,pIdxDefs
[i
].ColName
,typeNameAndSize
.c_str());
1238 ok
= pDb
->ExecSql(sqlStmt
.c_str());
1242 wxODBC_ERRORS retcode
;
1243 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1244 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1245 // This line is just here for debug checking of the value
1246 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1256 pDb
->RollbackTrans();
1261 // Build a CREATE INDEX statement
1262 sqlStmt
= "CREATE ";
1264 sqlStmt
+= "UNIQUE ";
1266 sqlStmt
+= "INDEX ";
1269 sqlStmt
+= tableName
;
1272 // Append list of columns making up index
1274 for (i
= 0; i
< noIdxCols
; i
++)
1276 sqlStmt
+= pIdxDefs
[i
].ColName
;
1277 /* Postgres doesn't cope with ASC */
1278 if (pDb
->Dbms() != dbmsPOSTGRES
)
1280 if (pIdxDefs
[i
].Ascending
)
1286 if ((i
+ 1) < noIdxCols
)
1290 // Append closing parentheses
1293 pDb
->WriteSqlLog(sqlStmt
.c_str());
1295 #ifdef DBDEBUG_CONSOLE
1296 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1299 // Execute the CREATE INDEX statement
1300 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1302 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1303 pDb
->RollbackTrans();
1308 // Commit the transaction and close the cursor
1309 if (! pDb
->CommitTrans())
1311 if (! CloseCursor(hstmt
))
1314 // Index Created Successfully
1317 } // wxDbTable::CreateIndex()
1320 /********** wxDbTable::DropIndex() **********/
1321 bool wxDbTable::DropIndex(const char * idxName
)
1323 // NOTE: This function returns TRUE if the Index does not exist, but
1324 // only for identified databases. Code will need to be added
1325 // below for any other databases when those databases are defined
1326 // to handle this situation consistently
1330 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
)
1331 sqlStmt
.sprintf("DROP INDEX %s ON %s",idxName
,tableName
);
1332 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1333 (pDb
->Dbms() == dbmsSYBASE_ASE
))
1334 sqlStmt
.sprintf("DROP INDEX %s.%s",tableName
,idxName
);
1336 sqlStmt
.sprintf("DROP INDEX %s",idxName
);
1338 pDb
->WriteSqlLog(sqlStmt
.c_str());
1340 #ifdef DBDEBUG_CONSOLE
1341 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1344 if (SQLExecDirect(hstmt
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1346 // Check for "Index not found" error and ignore
1347 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1348 if (wxStrcmp(pDb
->sqlState
,"S0012")) // "Index not found"
1350 // Check for product specific error codes
1351 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,"42000")) || // v5.x (and lower?)
1352 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,"37000")) ||
1353 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,"S1000")) ||
1354 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,"S0002")) || // Base table not found
1355 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,"42S12")) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1356 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,"08S01"))
1359 pDb
->DispNextError();
1360 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1361 pDb
->RollbackTrans();
1368 // Commit the transaction and close the cursor
1369 if (! pDb
->CommitTrans())
1371 if (! CloseCursor(hstmt
))
1375 } // wxDbTable::DropIndex()
1378 /********** wxDbTable::Insert() **********/
1379 int wxDbTable::Insert(void)
1382 if (queryOnly
|| !insertable
)
1387 // Insert the record by executing the already prepared insert statement
1389 retcode
=SQLExecute(hstmtInsert
);
1390 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1392 // Check to see if integrity constraint was violated
1393 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1394 if (! wxStrcmp(pDb
->sqlState
, "23000")) // Integrity constraint violated
1395 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1398 pDb
->DispNextError();
1399 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1404 // Record inserted into the datasource successfully
1407 } // wxDbTable::Insert()
1410 /********** wxDbTable::Update() **********/
1411 bool wxDbTable::Update(void)
1417 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1419 // Build the SQL UPDATE statement
1420 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1422 pDb
->WriteSqlLog(sqlStmt
);
1424 #ifdef DBDEBUG_CONSOLE
1425 cout
<< endl
<< sqlStmt
<< endl
<< endl
;
1428 // Execute the SQL UPDATE statement
1429 return(execUpdate(sqlStmt
));
1431 } // wxDbTable::Update()
1434 /********** wxDbTable::Update(pSqlStmt) **********/
1435 bool wxDbTable::Update(const char *pSqlStmt
)
1441 pDb
->WriteSqlLog(pSqlStmt
);
1443 return(execUpdate(pSqlStmt
));
1445 } // wxDbTable::Update(pSqlStmt)
1448 /********** wxDbTable::UpdateWhere() **********/
1449 bool wxDbTable::UpdateWhere(const char *pWhereClause
)
1455 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1457 // Build the SQL UPDATE statement
1458 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1460 pDb
->WriteSqlLog(sqlStmt
);
1462 #ifdef DBDEBUG_CONSOLE
1463 cout
<< endl
<< sqlStmt
<< endl
<< endl
;
1466 // Execute the SQL UPDATE statement
1467 return(execUpdate(sqlStmt
));
1469 } // wxDbTable::UpdateWhere()
1472 /********** wxDbTable::Delete() **********/
1473 bool wxDbTable::Delete(void)
1479 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1481 // Build the SQL DELETE statement
1482 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
1484 pDb
->WriteSqlLog(sqlStmt
);
1486 // Execute the SQL DELETE statement
1487 return(execDelete(sqlStmt
));
1489 } // wxDbTable::Delete()
1492 /********** wxDbTable::DeleteWhere() **********/
1493 bool wxDbTable::DeleteWhere(const char *pWhereClause
)
1499 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1501 // Build the SQL DELETE statement
1502 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
1504 pDb
->WriteSqlLog(sqlStmt
);
1506 // Execute the SQL DELETE statement
1507 return(execDelete(sqlStmt
));
1509 } // wxDbTable::DeleteWhere()
1512 /********** wxDbTable::DeleteMatching() **********/
1513 bool wxDbTable::DeleteMatching(void)
1519 char sqlStmt
[DB_MAX_STATEMENT_LEN
];
1521 // Build the SQL DELETE statement
1522 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
1524 pDb
->WriteSqlLog(sqlStmt
);
1526 // Execute the SQL DELETE statement
1527 return(execDelete(sqlStmt
));
1529 } // wxDbTable::DeleteMatching()
1532 /********** wxDbTable::BuildUpdateStmt() **********/
1533 void wxDbTable::BuildUpdateStmt(char *pSqlStmt
, int typeOfUpd
, const char *pWhereClause
)
1539 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
1540 bool firstColumn
= TRUE
;
1543 sprintf(pSqlStmt
, "UPDATE %s SET ", tableName
);
1545 // Append a list of columns to be updated
1547 for (i
= 0; i
< noCols
; i
++)
1549 // Only append Updateable columns
1550 if (colDefs
[i
].Updateable
)
1553 wxStrcat(pSqlStmt
, ",");
1555 firstColumn
= FALSE
;
1556 wxStrcat(pSqlStmt
, colDefs
[i
].ColName
);
1557 wxStrcat(pSqlStmt
, " = ?");
1561 // Append the WHERE clause to the SQL UPDATE statement
1562 wxStrcat(pSqlStmt
, " WHERE ");
1565 case DB_UPD_KEYFIELDS
:
1566 // If the datasource supports the ROWID column, build
1567 // the where on ROWID for efficiency purposes.
1568 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1569 if (CanUpdByROWID())
1572 char rowid
[wxDB_ROWID_LEN
];
1574 // Get the ROWID value. If not successful retreiving the ROWID,
1575 // simply fall down through the code and build the WHERE clause
1576 // based on the key fields.
1577 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1579 wxStrcat(pSqlStmt
, "ROWID = '");
1580 wxStrcat(pSqlStmt
, rowid
);
1581 wxStrcat(pSqlStmt
, "'");
1585 // Unable to delete by ROWID, so build a WHERE
1586 // clause based on the keyfields.
1587 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1588 wxStrcat(pSqlStmt
, whereClause
);
1591 wxStrcat(pSqlStmt
, pWhereClause
);
1594 } // BuildUpdateStmt()
1597 /********** wxDbTable::BuildDeleteStmt() **********/
1598 void wxDbTable::BuildDeleteStmt(char *pSqlStmt
, int typeOfDel
, const char *pWhereClause
)
1604 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
];
1608 // Handle the case of DeleteWhere() and the where clause is blank. It should
1609 // delete all records from the database in this case.
1610 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
== 0 || wxStrlen(pWhereClause
) == 0))
1612 sprintf(pSqlStmt
, "DELETE FROM %s", tableName
);
1616 sprintf(pSqlStmt
, "DELETE FROM %s WHERE ", tableName
);
1618 // Append the WHERE clause to the SQL DELETE statement
1621 case DB_DEL_KEYFIELDS
:
1622 // If the datasource supports the ROWID column, build
1623 // the where on ROWID for efficiency purposes.
1624 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1625 if (CanUpdByROWID())
1628 char rowid
[wxDB_ROWID_LEN
];
1630 // Get the ROWID value. If not successful retreiving the ROWID,
1631 // simply fall down through the code and build the WHERE clause
1632 // based on the key fields.
1633 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1635 wxStrcat(pSqlStmt
, "ROWID = '");
1636 wxStrcat(pSqlStmt
, rowid
);
1637 wxStrcat(pSqlStmt
, "'");
1641 // Unable to delete by ROWID, so build a WHERE
1642 // clause based on the keyfields.
1643 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1644 wxStrcat(pSqlStmt
, whereClause
);
1647 wxStrcat(pSqlStmt
, pWhereClause
);
1649 case DB_DEL_MATCHING
:
1650 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1651 wxStrcat(pSqlStmt
, whereClause
);
1655 } // BuildDeleteStmt()
1658 /********** wxDbTable::BuildWhereClause() **********/
1659 void wxDbTable::BuildWhereClause(char *pWhereClause
, int typeOfWhere
,
1660 const char *qualTableName
, bool useLikeComparison
)
1662 * Note: BuildWhereClause() currently ignores timestamp columns.
1663 * They are not included as part of the where clause.
1666 bool moreThanOneColumn
= FALSE
;
1669 // Loop through the columns building a where clause as you go
1671 for (i
= 0; i
< noCols
; i
++)
1673 // Determine if this column should be included in the WHERE clause
1674 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[i
].KeyField
) ||
1675 (typeOfWhere
== DB_WHERE_MATCHING
&& (! IsColNull(i
))))
1677 // Skip over timestamp columns
1678 if (colDefs
[i
].SqlCtype
== SQL_C_TIMESTAMP
)
1680 // If there is more than 1 column, join them with the keyword "AND"
1681 if (moreThanOneColumn
)
1682 wxStrcat(pWhereClause
, " AND ");
1684 moreThanOneColumn
= TRUE
;
1685 // Concatenate where phrase for the column
1686 if (qualTableName
&& wxStrlen(qualTableName
))
1688 wxStrcat(pWhereClause
, qualTableName
);
1689 wxStrcat(pWhereClause
, ".");
1691 wxStrcat(pWhereClause
, colDefs
[i
].ColName
);
1692 if (useLikeComparison
&& (colDefs
[i
].SqlCtype
== SQL_C_CHAR
))
1693 wxStrcat(pWhereClause
, " LIKE ");
1695 wxStrcat(pWhereClause
, " = ");
1696 switch(colDefs
[i
].SqlCtype
)
1699 sprintf(colValue
, "'%s'", (UCHAR FAR
*) colDefs
[i
].PtrDataObj
);
1702 sprintf(colValue
, "%hi", *((SWORD
*) colDefs
[i
].PtrDataObj
));
1705 sprintf(colValue
, "%hu", *((UWORD
*) colDefs
[i
].PtrDataObj
));
1708 sprintf(colValue
, "%li", *((SDWORD
*) colDefs
[i
].PtrDataObj
));
1711 sprintf(colValue
, "%lu", *((UDWORD
*) colDefs
[i
].PtrDataObj
));
1714 sprintf(colValue
, "%.6f", *((SFLOAT
*) colDefs
[i
].PtrDataObj
));
1717 sprintf(colValue
, "%.6f", *((SDOUBLE
*) colDefs
[i
].PtrDataObj
));
1720 wxStrcat(pWhereClause
, colValue
);
1723 } // wxDbTable::BuildWhereClause()
1726 /********** wxDbTable::IsColNull() **********/
1727 bool wxDbTable::IsColNull(int colNo
)
1729 switch(colDefs
[colNo
].SqlCtype
)
1732 return(((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] == 0);
1734 return(( *((SWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1736 return(( *((UWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1738 return(( *((SDWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1740 return(( *((UDWORD
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1742 return(( *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1744 return((*((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
)) == 0);
1745 case SQL_C_TIMESTAMP
:
1746 TIMESTAMP_STRUCT
*pDt
;
1747 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
1748 if (pDt
->year
== 0 && pDt
->month
== 0 && pDt
->day
== 0)
1755 } // wxDbTable::IsColNull()
1758 /********** wxDbTable::CanSelectForUpdate() **********/
1759 bool wxDbTable::CanSelectForUpdate(void)
1761 if (pDb
->Dbms() == dbmsMY_SQL
)
1764 if ((pDb
->Dbms() == dbmsORACLE
) ||
1765 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
1770 } // wxDbTable::CanSelectForUpdate()
1773 /********** wxDbTable::CanUpdByROWID() **********/
1774 bool wxDbTable::CanUpdByROWID(void)
1777 * NOTE: Returning FALSE for now until this can be debugged,
1778 * as the ROWID is not getting updated correctly
1782 if (pDb
->Dbms() == dbmsORACLE
)
1787 } // wxDbTable::CanUpdByROWID()
1790 /********** wxDbTable::IsCursorClosedOnCommit() **********/
1791 bool wxDbTable::IsCursorClosedOnCommit(void)
1793 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
1798 } // wxDbTable::IsCursorClosedOnCommit()
1801 /********** wxDbTable::ClearMemberVars() **********/
1802 void wxDbTable::ClearMemberVars(void)
1804 // Loop through the columns setting each member variable to zero
1806 for (i
= 0; i
< noCols
; i
++)
1808 switch(colDefs
[i
].SqlCtype
)
1811 ((UCHAR FAR
*) colDefs
[i
].PtrDataObj
)[0] = 0;
1814 *((SWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1817 *((UWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1820 *((SDWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1823 *((UDWORD
*) colDefs
[i
].PtrDataObj
) = 0;
1826 *((SFLOAT
*) colDefs
[i
].PtrDataObj
) = 0.0f
;
1829 *((SDOUBLE
*) colDefs
[i
].PtrDataObj
) = 0.0f
;
1831 case SQL_C_TIMESTAMP
:
1832 TIMESTAMP_STRUCT
*pDt
;
1833 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[i
].PtrDataObj
;
1845 } // wxDbTable::ClearMemberVars()
1848 /********** wxDbTable::SetQueryTimeout() **********/
1849 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
1851 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1852 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
1853 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1854 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
1855 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1856 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
1857 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
1858 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
1860 // Completed Successfully
1863 } // wxDbTable::SetQueryTimeout()
1866 /********** wxDbTable::SetColDefs() **********/
1867 void wxDbTable::SetColDefs(int index
, const char *fieldName
, int dataType
, void *pData
,
1868 int cType
, int size
, bool keyField
, bool upd
,
1869 bool insAllow
, bool derivedCol
)
1871 if (!colDefs
) // May happen if the database connection fails
1874 if (wxStrlen(fieldName
) > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
1876 wxStrncpy (colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
1877 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
1880 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
1882 colDefs
[index
].DbDataType
= dataType
;
1883 colDefs
[index
].PtrDataObj
= pData
;
1884 colDefs
[index
].SqlCtype
= cType
;
1885 colDefs
[index
].SzDataObj
= size
;
1886 colDefs
[index
].KeyField
= keyField
;
1887 colDefs
[index
].DerivedCol
= derivedCol
;
1888 // Derived columns by definition would NOT be "Insertable" or "Updateable"
1891 colDefs
[index
].Updateable
= FALSE
;
1892 colDefs
[index
].InsertAllowed
= FALSE
;
1896 colDefs
[index
].Updateable
= upd
;
1897 colDefs
[index
].InsertAllowed
= insAllow
;
1900 colDefs
[index
].Null
= FALSE
;
1902 } // wxDbTable::SetColDefs()
1905 /********** wxDbTable::SetColDefs() **********/
1906 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, ULONG numCols
)
1909 wxDbColDataPtr
*pColDataPtrs
= NULL
;
1915 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
1917 for (index
= 0; index
< numCols
; index
++)
1919 // Process the fields
1920 switch (pColInfs
[index
].dbDataType
)
1922 case DB_DATA_TYPE_VARCHAR
:
1923 pColDataPtrs
[index
].PtrDataObj
= new char[pColInfs
[index
].bufferLength
+1];
1924 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
1925 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
1927 case DB_DATA_TYPE_INTEGER
:
1928 // Can be long or short
1929 if (pColInfs
[index
].bufferLength
== sizeof(long))
1931 pColDataPtrs
[index
].PtrDataObj
= new long;
1932 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
1933 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
1937 pColDataPtrs
[index
].PtrDataObj
= new short;
1938 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
1939 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
1942 case DB_DATA_TYPE_FLOAT
:
1943 // Can be float or double
1944 if (pColInfs
[index
].bufferLength
== sizeof(float))
1946 pColDataPtrs
[index
].PtrDataObj
= new float;
1947 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
1948 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
1952 pColDataPtrs
[index
].PtrDataObj
= new double;
1953 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
1954 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
1957 case DB_DATA_TYPE_DATE
:
1958 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
1959 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
1960 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
1963 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
1967 return (pColDataPtrs
);
1969 } // wxDbTable::SetColDefs()
1972 /********** wxDbTable::SetCursor() **********/
1973 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
1975 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
1976 hstmt
= *hstmtDefault
;
1978 hstmt
= *hstmtActivate
;
1980 } // wxDbTable::SetCursor()
1983 /********** wxDbTable::Count(const char *) **********/
1984 ULONG
wxDbTable::Count(const char *args
)
1990 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
1991 sqlStmt
= "SELECT COUNT(";
1993 sqlStmt
+= ") FROM ";
1994 sqlStmt
+= queryTableName
;
1995 #if wxODBC_BACKWARD_COMPATABILITY
1996 if (from
&& wxStrlen(from
))
2002 // Add the where clause if one is provided
2003 #if wxODBC_BACKWARD_COMPATABILITY
2004 if (where
&& wxStrlen(where
))
2009 sqlStmt
+= " WHERE ";
2013 pDb
->WriteSqlLog(sqlStmt
.c_str());
2015 // Initialize the Count cursor if it's not already initialized
2018 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2024 // Execute the SQL statement
2025 if (SQLExecDirect(*hstmtCount
, (UCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2027 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2032 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2034 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2038 // Obtain the result
2039 if (SQLGetData(*hstmtCount
, 1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2041 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2046 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2047 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2049 // Return the record count
2052 } // wxDbTable::Count()
2055 /********** wxDbTable::Refresh() **********/
2056 bool wxDbTable::Refresh(void)
2060 // Switch to the internal cursor so any active cursors are not corrupted
2061 HSTMT currCursor
= GetCursor();
2062 hstmt
= hstmtInternal
;
2063 #if wxODBC_BACKWARD_COMPATABILITY
2064 // Save the where and order by clauses
2065 char *saveWhere
= where
;
2066 char *saveOrderBy
= orderBy
;
2068 wxString saveWhere
= where
;
2069 wxString saveOrderBy
= orderBy
;
2071 // Build a where clause to refetch the record with. Try and use the
2072 // ROWID if it's available, ow use the key fields.
2073 char whereClause
[DB_MAX_WHERE_CLAUSE_LEN
+1];
2074 wxStrcpy(whereClause
, "");
2075 if (CanUpdByROWID())
2078 char rowid
[wxDB_ROWID_LEN
+1];
2080 // Get the ROWID value. If not successful retreiving the ROWID,
2081 // simply fall down through the code and build the WHERE clause
2082 // based on the key fields.
2083 if (SQLGetData(hstmt
, noCols
+1, SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2085 wxStrcat(whereClause
, queryTableName
);
2086 wxStrcat(whereClause
, ".ROWID = '");
2087 wxStrcat(whereClause
, rowid
);
2088 wxStrcat(whereClause
, "'");
2092 // If unable to use the ROWID, build a where clause from the keyfields
2093 if (wxStrlen(whereClause
) == 0)
2094 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2096 // Requery the record
2097 where
= whereClause
;
2102 if (result
&& !GetNext())
2105 // Switch back to original cursor
2106 SetCursor(&currCursor
);
2108 // Free the internal cursor
2109 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2110 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2112 // Restore the original where and order by clauses
2114 orderBy
= saveOrderBy
;
2118 } // wxDbTable::Refresh()
2121 /********** wxDbTable::SetNull(int colNo) **********/
2122 bool wxDbTable::SetNull(int colNo
)
2125 return(colDefs
[colNo
].Null
= TRUE
);
2129 } // wxDbTable::SetNull(int colNo)
2132 /********** wxDbTable::SetNull(char *colName) **********/
2133 bool wxDbTable::SetNull(const char *colName
)
2136 for (i
= 0; i
< noCols
; i
++)
2138 if (!wxStricmp(colName
, colDefs
[i
].ColName
))
2143 return(colDefs
[i
].Null
= TRUE
);
2147 } // wxDbTable::SetNull(char *colName)
2150 /********** wxDbTable::GetNewCursor() **********/
2151 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2153 HSTMT
*newHSTMT
= new HSTMT
;
2158 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2160 pDb
->DispAllErrors(henv
, hdbc
);
2165 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2167 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2174 if(!bindCols(*newHSTMT
))
2182 SetCursor(newHSTMT
);
2186 } // wxDbTable::GetNewCursor()
2189 /********** wxDbTable::DeleteCursor() **********/
2190 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2194 if (!hstmtDel
) // Cursor already deleted
2197 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2199 pDb
->DispAllErrors(henv
, hdbc
);
2207 } // wxDbTable::DeleteCursor()
2209 #endif // wxUSE_ODBC