1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/dbtable.cpp
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence
12 ///////////////////////////////////////////////////////////////////////////////
19 #include "wx/wxprec.h"
27 #ifdef DBDEBUG_CONSOLE
33 #include "wx/ioswrap.h"
37 #include "wx/string.h"
38 #include "wx/object.h"
43 #include "wx/filefn.h"
49 #include "wx/dbtable.h"
52 // The HPUX preprocessor lines below were commented out on 8/20/97
53 // because macros.h currently redefines DEBUG and is unneeded.
55 // # include <macros.h>
58 # include <sys/minmax.h>
62 ULONG lastTableID
= 0;
70 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
72 while ( (*target
++ = *source
++) != '\0' && --n
)
80 /********** wxDbColDef::wxDbColDef() Constructor **********/
81 wxDbColDef::wxDbColDef()
87 bool wxDbColDef::Initialize()
90 DbDataType
= DB_DATA_TYPE_INTEGER
;
91 SqlCtype
= SQL_C_LONG
;
96 InsertAllowed
= false;
102 } // wxDbColDef::Initialize()
105 /********** wxDbTable::wxDbTable() Constructor **********/
106 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
107 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
109 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
111 } // wxDbTable::wxDbTable()
114 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
115 #if WXWIN_COMPATIBILITY_2_4
116 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
117 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
119 wxString tempQryTblName
;
120 tempQryTblName
= qryTblName
;
121 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
123 } // wxDbTable::wxDbTable()
124 #endif // WXWIN_COMPATIBILITY_2_4
127 /********** wxDbTable::~wxDbTable() **********/
128 wxDbTable::~wxDbTable()
131 } // wxDbTable::~wxDbTable()
134 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
135 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
137 // Initializing member variables
138 pDb
= pwxDb
; // Pointer to the wxDb object
142 m_hstmtGridQuery
= 0;
143 hstmtDefault
= 0; // Initialized below
144 hstmtCount
= 0; // Initialized first time it is needed
151 m_numCols
= numColumns
; // Number of columns in the table
152 where
.Empty(); // Where clause
153 orderBy
.Empty(); // Order By clause
154 from
.Empty(); // From clause
155 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
160 queryTableName
.Empty();
162 wxASSERT(tblName
.length());
168 tableName
= tblName
; // Table Name
169 if ((pDb
->Dbms() == dbmsORACLE
) ||
170 (pDb
->Dbms() == dbmsFIREBIRD
) ||
171 (pDb
->Dbms() == dbmsINTERBASE
))
172 tableName
= tableName
.Upper();
174 if (tblPath
.length())
175 tablePath
= tblPath
; // Table Path - used for dBase files
179 if (qryTblName
.length()) // Name of the table/view to query
180 queryTableName
= qryTblName
;
182 queryTableName
= tblName
;
184 if ((pDb
->Dbms() == dbmsORACLE
) ||
185 (pDb
->Dbms() == dbmsFIREBIRD
) ||
186 (pDb
->Dbms() == dbmsINTERBASE
))
187 queryTableName
= queryTableName
.Upper();
189 pDb
->incrementTableCount();
192 tableID
= ++lastTableID
;
193 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
196 wxTablesInUse
*tableInUse
;
197 tableInUse
= new wxTablesInUse();
198 tableInUse
->tableName
= tblName
;
199 tableInUse
->tableID
= tableID
;
200 tableInUse
->pDb
= pDb
;
201 TablesInUse
.Append(tableInUse
);
206 // Grab the HENV and HDBC from the wxDb object
207 henv
= pDb
->GetHENV();
208 hdbc
= pDb
->GetHDBC();
210 // Allocate space for column definitions
212 colDefs
= new wxDbColDef
[m_numCols
]; // Points to the first column definition
214 // Allocate statement handles for the table
217 // Allocate a separate statement handle for performing inserts
218 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
219 pDb
->DispAllErrors(henv
, hdbc
);
220 // Allocate a separate statement handle for performing deletes
221 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
222 pDb
->DispAllErrors(henv
, hdbc
);
223 // Allocate a separate statement handle for performing updates
224 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
225 pDb
->DispAllErrors(henv
, hdbc
);
227 // Allocate a separate statement handle for internal use
228 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
229 pDb
->DispAllErrors(henv
, hdbc
);
231 // Set the cursor type for the statement handles
232 cursorType
= SQL_CURSOR_STATIC
;
234 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
236 // Check to see if cursor type is supported
237 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
238 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
240 // Datasource does not support static cursors. Driver
241 // will substitute a cursor type. Call SQLGetStmtOption()
242 // to determine which cursor type was selected.
243 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
244 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
245 #ifdef DBDEBUG_CONSOLE
246 cout
<< wxT("Static cursor changed to: ");
249 case SQL_CURSOR_FORWARD_ONLY
:
250 cout
<< wxT("Forward Only");
252 case SQL_CURSOR_STATIC
:
253 cout
<< wxT("Static");
255 case SQL_CURSOR_KEYSET_DRIVEN
:
256 cout
<< wxT("Keyset Driven");
258 case SQL_CURSOR_DYNAMIC
:
259 cout
<< wxT("Dynamic");
262 cout
<< endl
<< endl
;
265 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
267 // Force the use of a forward only cursor...
268 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
269 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
271 // Should never happen
272 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
279 pDb
->DispNextError();
280 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
283 #ifdef DBDEBUG_CONSOLE
285 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
290 // Set the cursor type for the INSERT statement handle
291 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
292 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
293 // Set the cursor type for the DELETE statement handle
294 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
295 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
296 // Set the cursor type for the UPDATE statement handle
297 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
298 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
301 // Make the default cursor the active cursor
302 hstmtDefault
= GetNewCursor(false,false);
303 wxASSERT(hstmtDefault
);
304 hstmt
= *hstmtDefault
;
308 } // wxDbTable::initialize()
311 void wxDbTable::cleanup()
316 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
325 wxList::compatibility_iterator pNode
;
326 pNode
= TablesInUse
.GetFirst();
327 while (pNode
&& !found
)
329 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
332 delete (wxTablesInUse
*)pNode
->GetData();
333 TablesInUse
.Erase(pNode
);
336 pNode
= pNode
->GetNext();
341 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
342 wxLogDebug (msg
,wxT("NOTICE..."));
347 // Decrement the wxDb table count
349 pDb
->decrementTableCount();
351 // Delete memory allocated for column definitions
355 // Free statement handles
361 ODBC 3.0 says to use this form
362 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
364 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
365 pDb
->DispAllErrors(henv
, hdbc
);
371 ODBC 3.0 says to use this form
372 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
374 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
375 pDb
->DispAllErrors(henv
, hdbc
);
381 ODBC 3.0 says to use this form
382 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
384 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
385 pDb
->DispAllErrors(henv
, hdbc
);
391 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
392 pDb
->DispAllErrors(henv
, hdbc
);
395 // Delete dynamically allocated cursors
397 DeleteCursor(hstmtDefault
);
400 DeleteCursor(hstmtCount
);
402 if (m_hstmtGridQuery
)
403 DeleteCursor(m_hstmtGridQuery
);
405 } // wxDbTable::cleanup()
408 /***************************** PRIVATE FUNCTIONS *****************************/
411 void wxDbTable::setCbValueForColumn(int columnIndex
)
413 switch(colDefs
[columnIndex
].DbDataType
)
415 case DB_DATA_TYPE_VARCHAR
:
416 case DB_DATA_TYPE_MEMO
:
417 if (colDefs
[columnIndex
].Null
)
418 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
420 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
422 case DB_DATA_TYPE_INTEGER
:
423 if (colDefs
[columnIndex
].Null
)
424 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
426 colDefs
[columnIndex
].CbValue
= 0;
428 case DB_DATA_TYPE_FLOAT
:
429 if (colDefs
[columnIndex
].Null
)
430 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
432 colDefs
[columnIndex
].CbValue
= 0;
434 case DB_DATA_TYPE_DATE
:
435 if (colDefs
[columnIndex
].Null
)
436 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
438 colDefs
[columnIndex
].CbValue
= 0;
440 case DB_DATA_TYPE_BLOB
:
441 if (colDefs
[columnIndex
].Null
)
442 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
444 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
445 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
447 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
452 /********** wxDbTable::bindParams() **********/
453 bool wxDbTable::bindParams(bool forUpdate
)
455 wxASSERT(!queryOnly
);
460 SDWORD precision
= 0;
463 // Bind each column of the table that should be bound
464 // to a parameter marker
468 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
472 if (!colDefs
[i
].Updateable
)
477 if (!colDefs
[i
].InsertAllowed
)
481 switch(colDefs
[i
].DbDataType
)
483 case DB_DATA_TYPE_VARCHAR
:
484 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
485 precision
= colDefs
[i
].SzDataObj
;
488 case DB_DATA_TYPE_MEMO
:
489 fSqlType
= pDb
->GetTypeInfMemo().FsqlType
;
490 precision
= colDefs
[i
].SzDataObj
;
493 case DB_DATA_TYPE_INTEGER
:
494 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
495 precision
= pDb
->GetTypeInfInteger().Precision
;
498 case DB_DATA_TYPE_FLOAT
:
499 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
500 precision
= pDb
->GetTypeInfFloat().Precision
;
501 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
502 // SQL Sybase Anywhere v5.5 returned a negative number for the
503 // MaxScale. This caused ODBC to kick out an error on ibscale.
504 // I check for this here and set the scale = precision.
506 // scale = (short) precision;
508 case DB_DATA_TYPE_DATE
:
509 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
510 precision
= pDb
->GetTypeInfDate().Precision
;
513 case DB_DATA_TYPE_BLOB
:
514 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
515 precision
= colDefs
[i
].SzDataObj
;
520 setCbValueForColumn(i
);
524 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
525 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
526 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
528 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
533 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
534 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
535 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
537 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
542 // Completed successfully
545 } // wxDbTable::bindParams()
548 /********** wxDbTable::bindInsertParams() **********/
549 bool wxDbTable::bindInsertParams(void)
551 return bindParams(false);
552 } // wxDbTable::bindInsertParams()
555 /********** wxDbTable::bindUpdateParams() **********/
556 bool wxDbTable::bindUpdateParams(void)
558 return bindParams(true);
559 } // wxDbTable::bindUpdateParams()
562 /********** wxDbTable::bindCols() **********/
563 bool wxDbTable::bindCols(HSTMT cursor
)
567 // Bind each column of the table to a memory address for fetching data
569 for (i
= 0; i
< m_numCols
; i
++)
571 cb
= colDefs
[i
].CbValue
;
572 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
573 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
574 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
577 // Completed successfully
580 } // wxDbTable::bindCols()
583 /********** wxDbTable::getRec() **********/
584 bool wxDbTable::getRec(UWORD fetchType
)
588 if (!pDb
->FwdOnlyCursors())
590 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
591 SQLULEN cRowsFetched
;
594 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
595 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
597 if (retcode
== SQL_NO_DATA_FOUND
)
600 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
604 // Set the Null member variable to indicate the Null state
605 // of each column just read in.
607 for (i
= 0; i
< m_numCols
; i
++)
608 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
613 // Fetch the next record from the record set
614 retcode
= SQLFetch(hstmt
);
615 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
617 if (retcode
== SQL_NO_DATA_FOUND
)
620 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
624 // Set the Null member variable to indicate the Null state
625 // of each column just read in.
627 for (i
= 0; i
< m_numCols
; i
++)
628 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
632 // Completed successfully
635 } // wxDbTable::getRec()
638 /********** wxDbTable::execDelete() **********/
639 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
643 // Execute the DELETE statement
644 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
646 if (retcode
== SQL_SUCCESS
||
647 retcode
== SQL_NO_DATA_FOUND
||
648 retcode
== SQL_SUCCESS_WITH_INFO
)
650 // Record deleted successfully
654 // Problem deleting record
655 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
657 } // wxDbTable::execDelete()
660 /********** wxDbTable::execUpdate() **********/
661 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
665 // Execute the UPDATE statement
666 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
668 if (retcode
== SQL_SUCCESS
||
669 retcode
== SQL_NO_DATA_FOUND
||
670 retcode
== SQL_SUCCESS_WITH_INFO
)
672 // Record updated successfully
675 else if (retcode
== SQL_NEED_DATA
)
678 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
679 while (retcode
== SQL_NEED_DATA
)
681 // Find the parameter
683 for (i
=0; i
< m_numCols
; i
++)
685 if (colDefs
[i
].PtrDataObj
== pParmID
)
687 // We found it. Store the parameter.
688 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
689 if (retcode
!= SQL_SUCCESS
)
691 pDb
->DispNextError();
692 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
697 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
699 if (retcode
== SQL_SUCCESS
||
700 retcode
== SQL_NO_DATA_FOUND
||
701 retcode
== SQL_SUCCESS_WITH_INFO
)
703 // Record updated successfully
708 // Problem updating record
709 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
711 } // wxDbTable::execUpdate()
714 /********** wxDbTable::query() **********/
715 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
720 // The user may wish to select for update, but the DBMS may not be capable
721 selectForUpdate
= CanSelectForUpdate();
723 selectForUpdate
= false;
725 // Set the SQL SELECT string
726 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
727 { // so generate a select statement.
728 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
729 pDb
->WriteSqlLog(sqlStmt
);
732 // Make sure the cursor is closed first
733 if (!CloseCursor(hstmt
))
736 // Execute the SQL SELECT statement
738 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
739 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
740 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
742 // Completed successfully
745 } // wxDbTable::query()
748 /***************************** PUBLIC FUNCTIONS *****************************/
751 /********** wxDbTable::Open() **********/
752 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
761 // Calculate the maximum size of the concatenated
762 // keys for use with wxDbGrid
764 for (i
=0; i
< m_numCols
; i
++)
766 if (colDefs
[i
].KeyField
)
768 m_keysize
+= colDefs
[i
].SzDataObj
;
775 if (checkTableExists
)
777 if (pDb
->Dbms() == dbmsPOSTGRES
)
778 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
780 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
783 // Verify that the table exists in the database
786 s
= wxT("Table/view does not exist in the database");
787 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
788 s
+= wxT(", or you have no permissions.\n");
792 else if (checkPrivileges
)
794 // Verify the user has rights to access the table.
795 bool hasPrivs
wxDUMMY_INITIALIZE(true);
797 if (pDb
->Dbms() == dbmsPOSTGRES
)
798 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
800 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
803 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
810 if (!tablePath
.empty())
811 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
813 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
816 pDb
->LogError(p
.GetData());
821 // Bind the member variables for field exchange between
822 // the wxDbTable object and the ODBC record.
825 if (!bindInsertParams()) // Inserts
828 if (!bindUpdateParams()) // Updates
832 if (!bindCols(*hstmtDefault
)) // Selects
835 if (!bindCols(hstmtInternal
)) // Internal use only
839 * Do NOT bind the hstmtCount cursor!!!
842 // Build an insert statement using parameter markers
843 if (!queryOnly
&& m_numCols
> 0)
845 bool needComma
= false;
846 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
847 pDb
->SQLTableName(tableName
.c_str()).c_str());
848 for (i
= 0; i
< m_numCols
; i
++)
850 if (! colDefs
[i
].InsertAllowed
)
854 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
858 sqlStmt
+= wxT(") VALUES (");
860 int insertableCount
= 0;
862 for (i
= 0; i
< m_numCols
; i
++)
864 if (! colDefs
[i
].InsertAllowed
)
874 // Prepare the insert statement for execution
877 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
878 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
884 // Completed successfully
887 } // wxDbTable::Open()
890 /********** wxDbTable::Query() **********/
891 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
894 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
896 } // wxDbTable::Query()
899 /********** wxDbTable::QueryBySqlStmt() **********/
900 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
902 pDb
->WriteSqlLog(pSqlStmt
);
904 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
906 } // wxDbTable::QueryBySqlStmt()
909 /********** wxDbTable::QueryMatching() **********/
910 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
913 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
915 } // wxDbTable::QueryMatching()
918 /********** wxDbTable::QueryOnKeyFields() **********/
919 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
922 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
924 } // wxDbTable::QueryOnKeyFields()
927 /********** wxDbTable::GetPrev() **********/
928 bool wxDbTable::GetPrev(void)
930 if (pDb
->FwdOnlyCursors())
932 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
936 return(getRec(SQL_FETCH_PRIOR
));
938 } // wxDbTable::GetPrev()
941 /********** wxDbTable::operator-- **********/
942 bool wxDbTable::operator--(int)
944 if (pDb
->FwdOnlyCursors())
946 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
950 return(getRec(SQL_FETCH_PRIOR
));
952 } // wxDbTable::operator--
955 /********** wxDbTable::GetFirst() **********/
956 bool wxDbTable::GetFirst(void)
958 if (pDb
->FwdOnlyCursors())
960 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
964 return(getRec(SQL_FETCH_FIRST
));
966 } // wxDbTable::GetFirst()
969 /********** wxDbTable::GetLast() **********/
970 bool wxDbTable::GetLast(void)
972 if (pDb
->FwdOnlyCursors())
974 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
978 return(getRec(SQL_FETCH_LAST
));
980 } // wxDbTable::GetLast()
983 /********** wxDbTable::BuildDeleteStmt() **********/
984 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
986 wxASSERT(!queryOnly
);
990 wxString whereClause
;
994 // Handle the case of DeleteWhere() and the where clause is blank. It should
995 // delete all records from the database in this case.
996 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.length() == 0))
998 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
999 pDb
->SQLTableName(tableName
.c_str()).c_str());
1003 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
1004 pDb
->SQLTableName(tableName
.c_str()).c_str());
1006 // Append the WHERE clause to the SQL DELETE statement
1009 case DB_DEL_KEYFIELDS
:
1010 // If the datasource supports the ROWID column, build
1011 // the where on ROWID for efficiency purposes.
1012 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1013 if (CanUpdateByROWID())
1016 wxChar rowid
[wxDB_ROWID_LEN
+1];
1018 // Get the ROWID value. If not successful retreiving the ROWID,
1019 // simply fall down through the code and build the WHERE clause
1020 // based on the key fields.
1021 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1023 pSqlStmt
+= wxT("ROWID = '");
1025 pSqlStmt
+= wxT("'");
1029 // Unable to delete by ROWID, so build a WHERE
1030 // clause based on the keyfields.
1031 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1032 pSqlStmt
+= whereClause
;
1035 pSqlStmt
+= pWhereClause
;
1037 case DB_DEL_MATCHING
:
1038 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1039 pSqlStmt
+= whereClause
;
1043 } // BuildDeleteStmt()
1046 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1047 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1049 wxString tempSqlStmt
;
1050 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1051 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1052 } // wxDbTable::BuildDeleteStmt()
1055 /********** wxDbTable::BuildSelectStmt() **********/
1056 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1058 wxString whereClause
;
1059 whereClause
.Empty();
1061 // Build a select statement to query the database
1062 pSqlStmt
= wxT("SELECT ");
1064 // SELECT DISTINCT values only?
1066 pSqlStmt
+= wxT("DISTINCT ");
1068 // Was a FROM clause specified to join tables to the base table?
1069 // Available for ::Query() only!!!
1070 bool appendFromClause
= false;
1071 #if wxODBC_BACKWARD_COMPATABILITY
1072 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1073 appendFromClause
= true;
1075 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.length())
1076 appendFromClause
= true;
1079 // Add the column list
1082 for (i
= 0; i
< m_numCols
; i
++)
1084 tStr
= colDefs
[i
].ColName
;
1085 // If joining tables, the base table column names must be qualified to avoid ambiguity
1086 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1088 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1089 pSqlStmt
+= wxT(".");
1091 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1092 if (i
+ 1 < m_numCols
)
1093 pSqlStmt
+= wxT(",");
1096 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1097 // the ROWID if querying distinct records. The rowid will always be unique.
1098 if (!distinct
&& CanUpdateByROWID())
1100 // If joining tables, the base table column names must be qualified to avoid ambiguity
1101 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1103 pSqlStmt
+= wxT(",");
1104 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1105 pSqlStmt
+= wxT(".ROWID");
1108 pSqlStmt
+= wxT(",ROWID");
1111 // Append the FROM tablename portion
1112 pSqlStmt
+= wxT(" FROM ");
1113 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1114 // pSqlStmt += queryTableName;
1116 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1117 // The HOLDLOCK keyword follows the table name in the from clause.
1118 // Each table in the from clause must specify HOLDLOCK or
1119 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1120 // is parsed but ignored in SYBASE Transact-SQL.
1121 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1122 pSqlStmt
+= wxT(" HOLDLOCK");
1124 if (appendFromClause
)
1127 // Append the WHERE clause. Either append the where clause for the class
1128 // or build a where clause. The typeOfSelect determines this.
1129 switch(typeOfSelect
)
1131 case DB_SELECT_WHERE
:
1132 #if wxODBC_BACKWARD_COMPATABILITY
1133 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1135 if (where
.length()) // May not want a where clause!!!
1138 pSqlStmt
+= wxT(" WHERE ");
1142 case DB_SELECT_KEYFIELDS
:
1143 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1144 if (whereClause
.length())
1146 pSqlStmt
+= wxT(" WHERE ");
1147 pSqlStmt
+= whereClause
;
1150 case DB_SELECT_MATCHING
:
1151 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1152 if (whereClause
.length())
1154 pSqlStmt
+= wxT(" WHERE ");
1155 pSqlStmt
+= whereClause
;
1160 // Append the ORDER BY clause
1161 #if wxODBC_BACKWARD_COMPATABILITY
1162 if (orderBy
&& wxStrlen(orderBy
))
1164 if (orderBy
.length())
1167 pSqlStmt
+= wxT(" ORDER BY ");
1168 pSqlStmt
+= orderBy
;
1171 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1172 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1173 // HOLDLOCK for Sybase.
1174 if (selectForUpdate
&& CanSelectForUpdate())
1175 pSqlStmt
+= wxT(" FOR UPDATE");
1177 } // wxDbTable::BuildSelectStmt()
1180 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1181 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1183 wxString tempSqlStmt
;
1184 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1185 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1186 } // wxDbTable::BuildSelectStmt()
1189 /********** wxDbTable::BuildUpdateStmt() **********/
1190 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1192 wxASSERT(!queryOnly
);
1196 wxString whereClause
;
1197 whereClause
.Empty();
1199 bool firstColumn
= true;
1201 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1202 pDb
->SQLTableName(tableName
.c_str()).c_str());
1204 // Append a list of columns to be updated
1206 for (i
= 0; i
< m_numCols
; i
++)
1208 // Only append Updateable columns
1209 if (colDefs
[i
].Updateable
)
1212 pSqlStmt
+= wxT(",");
1214 firstColumn
= false;
1216 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1217 // pSqlStmt += colDefs[i].ColName;
1218 pSqlStmt
+= wxT(" = ?");
1222 // Append the WHERE clause to the SQL UPDATE statement
1223 pSqlStmt
+= wxT(" WHERE ");
1224 switch(typeOfUpdate
)
1226 case DB_UPD_KEYFIELDS
:
1227 // If the datasource supports the ROWID column, build
1228 // the where on ROWID for efficiency purposes.
1229 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1230 if (CanUpdateByROWID())
1233 wxChar rowid
[wxDB_ROWID_LEN
+1];
1235 // Get the ROWID value. If not successful retreiving the ROWID,
1236 // simply fall down through the code and build the WHERE clause
1237 // based on the key fields.
1238 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1240 pSqlStmt
+= wxT("ROWID = '");
1242 pSqlStmt
+= wxT("'");
1246 // Unable to delete by ROWID, so build a WHERE
1247 // clause based on the keyfields.
1248 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1249 pSqlStmt
+= whereClause
;
1252 pSqlStmt
+= pWhereClause
;
1255 } // BuildUpdateStmt()
1258 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1259 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1261 wxString tempSqlStmt
;
1262 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1263 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1264 } // BuildUpdateStmt()
1267 /********** wxDbTable::BuildWhereClause() **********/
1268 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1269 const wxString
&qualTableName
, bool useLikeComparison
)
1271 * Note: BuildWhereClause() currently ignores timestamp columns.
1272 * They are not included as part of the where clause.
1275 bool moreThanOneColumn
= false;
1278 // Loop through the columns building a where clause as you go
1280 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1282 // Determine if this column should be included in the WHERE clause
1283 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1284 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1286 // Skip over timestamp columns
1287 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1289 // If there is more than 1 column, join them with the keyword "AND"
1290 if (moreThanOneColumn
)
1291 pWhereClause
+= wxT(" AND ");
1293 moreThanOneColumn
= true;
1295 // Concatenate where phrase for the column
1296 wxString tStr
= colDefs
[colNumber
].ColName
;
1298 if (qualTableName
.length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1300 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1301 pWhereClause
+= wxT(".");
1303 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1305 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1306 pWhereClause
+= wxT(" LIKE ");
1308 pWhereClause
+= wxT(" = ");
1310 switch(colDefs
[colNumber
].SqlCtype
)
1316 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1317 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
);
1321 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1324 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1328 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1331 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1334 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1337 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1342 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1343 colNumber
,colDefs
[colNumber
].ColName
);
1344 wxFAIL_MSG(strMsg
.c_str());
1348 pWhereClause
+= colValue
;
1351 } // wxDbTable::BuildWhereClause()
1354 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1355 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1356 const wxString
&qualTableName
, bool useLikeComparison
)
1358 wxString tempSqlStmt
;
1359 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1360 wxStrcpy(pWhereClause
, tempSqlStmt
);
1361 } // wxDbTable::BuildWhereClause()
1364 /********** wxDbTable::GetRowNum() **********/
1365 UWORD
wxDbTable::GetRowNum(void)
1369 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1371 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1375 // Completed successfully
1376 return((UWORD
) rowNum
);
1378 } // wxDbTable::GetRowNum()
1381 /********** wxDbTable::CloseCursor() **********/
1382 bool wxDbTable::CloseCursor(HSTMT cursor
)
1384 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1385 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1387 // Completed successfully
1390 } // wxDbTable::CloseCursor()
1393 /********** wxDbTable::CreateTable() **********/
1394 bool wxDbTable::CreateTable(bool attemptDrop
)
1402 #ifdef DBDEBUG_CONSOLE
1403 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1407 if (attemptDrop
&& !DropTable())
1411 #ifdef DBDEBUG_CONSOLE
1412 for (i
= 0; i
< m_numCols
; i
++)
1414 // Exclude derived columns since they are NOT part of the base table
1415 if (colDefs
[i
].DerivedCol
)
1417 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1418 switch(colDefs
[i
].DbDataType
)
1420 case DB_DATA_TYPE_VARCHAR
:
1421 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1423 case DB_DATA_TYPE_MEMO
:
1424 cout
<< pDb
->GetTypeInfMemo().TypeName
;
1426 case DB_DATA_TYPE_INTEGER
:
1427 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1429 case DB_DATA_TYPE_FLOAT
:
1430 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1432 case DB_DATA_TYPE_DATE
:
1433 cout
<< pDb
->GetTypeInfDate().TypeName
;
1435 case DB_DATA_TYPE_BLOB
:
1436 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1443 // Build a CREATE TABLE string from the colDefs structure.
1444 bool needComma
= false;
1446 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1447 pDb
->SQLTableName(tableName
.c_str()).c_str());
1449 for (i
= 0; i
< m_numCols
; i
++)
1451 // Exclude derived columns since they are NOT part of the base table
1452 if (colDefs
[i
].DerivedCol
)
1456 sqlStmt
+= wxT(",");
1458 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1459 // sqlStmt += colDefs[i].ColName;
1460 sqlStmt
+= wxT(" ");
1462 switch(colDefs
[i
].DbDataType
)
1464 case DB_DATA_TYPE_VARCHAR
:
1465 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1467 case DB_DATA_TYPE_MEMO
:
1468 sqlStmt
+= pDb
->GetTypeInfMemo().TypeName
;
1470 case DB_DATA_TYPE_INTEGER
:
1471 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1473 case DB_DATA_TYPE_FLOAT
:
1474 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1476 case DB_DATA_TYPE_DATE
:
1477 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1479 case DB_DATA_TYPE_BLOB
:
1480 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1483 // For varchars, append the size of the string
1484 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1485 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1486 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1489 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1493 if (pDb
->Dbms() == dbmsDB2
||
1494 pDb
->Dbms() == dbmsMY_SQL
||
1495 pDb
->Dbms() == dbmsSYBASE_ASE
||
1496 pDb
->Dbms() == dbmsINTERBASE
||
1497 pDb
->Dbms() == dbmsFIREBIRD
||
1498 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1500 if (colDefs
[i
].KeyField
)
1502 sqlStmt
+= wxT(" NOT NULL");
1508 // If there is a primary key defined, include it in the create statement
1509 for (i
= j
= 0; i
< m_numCols
; i
++)
1511 if (colDefs
[i
].KeyField
)
1517 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1518 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1520 switch (pDb
->Dbms())
1524 case dbmsSYBASE_ASA
:
1525 case dbmsSYBASE_ASE
:
1529 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1530 sqlStmt
+= wxT(",PRIMARY KEY (");
1535 sqlStmt
+= wxT(",CONSTRAINT ");
1536 // DB2 is limited to 18 characters for index names
1537 if (pDb
->Dbms() == dbmsDB2
)
1539 wxASSERT_MSG((tableName
&& wxStrlen(tableName
) <= 13), wxT("DB2 table/index names must be no longer than 13 characters in length.\n\nTruncating table name to 13 characters."));
1540 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1541 // sqlStmt += tableName.substr(0, 13);
1544 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1545 // sqlStmt += tableName;
1547 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1552 // List column name(s) of column(s) comprising the primary key
1553 for (i
= j
= 0; i
< m_numCols
; i
++)
1555 if (colDefs
[i
].KeyField
)
1557 if (j
++) // Multi part key, comma separate names
1558 sqlStmt
+= wxT(",");
1559 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1561 if (pDb
->Dbms() == dbmsMY_SQL
&&
1562 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1565 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1570 sqlStmt
+= wxT(")");
1572 if (pDb
->Dbms() == dbmsINFORMIX
||
1573 pDb
->Dbms() == dbmsSYBASE_ASA
||
1574 pDb
->Dbms() == dbmsSYBASE_ASE
)
1576 sqlStmt
+= wxT(" CONSTRAINT ");
1577 sqlStmt
+= pDb
->SQLTableName(tableName
);
1578 // sqlStmt += tableName;
1579 sqlStmt
+= wxT("_PIDX");
1582 // Append the closing parentheses for the create table statement
1583 sqlStmt
+= wxT(")");
1585 pDb
->WriteSqlLog(sqlStmt
);
1587 #ifdef DBDEBUG_CONSOLE
1588 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1591 // Execute the CREATE TABLE statement
1592 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1593 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1595 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1596 pDb
->RollbackTrans();
1601 // Commit the transaction and close the cursor
1602 if (!pDb
->CommitTrans())
1604 if (!CloseCursor(hstmt
))
1607 // Database table created successfully
1610 } // wxDbTable::CreateTable()
1613 /********** wxDbTable::DropTable() **********/
1614 bool wxDbTable::DropTable()
1616 // NOTE: This function returns true if the Table does not exist, but
1617 // only for identified databases. Code will need to be added
1618 // below for any other databases when those databases are defined
1619 // to handle this situation consistently
1623 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1624 pDb
->SQLTableName(tableName
.c_str()).c_str());
1626 pDb
->WriteSqlLog(sqlStmt
);
1628 #ifdef DBDEBUG_CONSOLE
1629 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1632 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1633 if (retcode
!= SQL_SUCCESS
)
1635 // Check for "Base table not found" error and ignore
1636 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1637 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1638 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1640 // Check for product specific error codes
1641 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1642 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1643 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1644 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1646 pDb
->DispNextError();
1647 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1648 pDb
->RollbackTrans();
1649 // CloseCursor(hstmt);
1655 // Commit the transaction and close the cursor
1656 if (! pDb
->CommitTrans())
1658 if (! CloseCursor(hstmt
))
1662 } // wxDbTable::DropTable()
1665 /********** wxDbTable::CreateIndex() **********/
1666 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1667 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1671 // Drop the index first
1672 if (attemptDrop
&& !DropIndex(indexName
))
1675 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1676 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1677 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1678 // table was created, then months later you determine that an additional index while
1679 // give better performance, so you want to add an index).
1681 // The following block of code will modify the column definition to make the column be
1682 // defined with the "NOT NULL" qualifier.
1683 if (pDb
->Dbms() == dbmsMY_SQL
)
1688 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1692 // Find the column definition that has the ColName that matches the
1693 // index column name. We need to do this to get the DB_DATA_TYPE of
1694 // the index column, as MySQL's syntax for the ALTER column requires
1696 while (!found
&& (j
< this->m_numCols
))
1698 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1706 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1707 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1713 // retcode is not used
1714 wxODBC_ERRORS retcode
;
1715 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1716 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1717 // This line is just here for debug checking of the value
1718 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1729 pDb
->RollbackTrans();
1734 // Build a CREATE INDEX statement
1735 sqlStmt
= wxT("CREATE ");
1737 sqlStmt
+= wxT("UNIQUE ");
1739 sqlStmt
+= wxT("INDEX ");
1740 sqlStmt
+= pDb
->SQLTableName(indexName
);
1741 sqlStmt
+= wxT(" ON ");
1743 sqlStmt
+= pDb
->SQLTableName(tableName
);
1744 // sqlStmt += tableName;
1745 sqlStmt
+= wxT(" (");
1747 // Append list of columns making up index
1749 for (i
= 0; i
< numIndexColumns
; i
++)
1751 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1752 // sqlStmt += pIndexDefs[i].ColName;
1754 // MySQL requires a key length on VARCHAR keys
1755 if ( pDb
->Dbms() == dbmsMY_SQL
)
1757 // Find the details on this column
1759 for ( j
= 0; j
< m_numCols
; ++j
)
1761 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1766 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1769 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1774 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1775 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1776 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1777 !(pDb
->Dbms() == dbmsPOSTGRES
))
1779 if (pIndexDefs
[i
].Ascending
)
1780 sqlStmt
+= wxT(" ASC");
1782 sqlStmt
+= wxT(" DESC");
1785 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1787 if ((i
+ 1) < numIndexColumns
)
1788 sqlStmt
+= wxT(",");
1791 // Append closing parentheses
1792 sqlStmt
+= wxT(")");
1794 pDb
->WriteSqlLog(sqlStmt
);
1796 #ifdef DBDEBUG_CONSOLE
1797 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1800 // Execute the CREATE INDEX statement
1801 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1802 if (retcode
!= SQL_SUCCESS
)
1804 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1805 pDb
->RollbackTrans();
1810 // Commit the transaction and close the cursor
1811 if (! pDb
->CommitTrans())
1813 if (! CloseCursor(hstmt
))
1816 // Index Created Successfully
1819 } // wxDbTable::CreateIndex()
1822 /********** wxDbTable::DropIndex() **********/
1823 bool wxDbTable::DropIndex(const wxString
&indexName
)
1825 // NOTE: This function returns true if the Index does not exist, but
1826 // only for identified databases. Code will need to be added
1827 // below for any other databases when those databases are defined
1828 // to handle this situation consistently
1832 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1833 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1834 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1835 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1836 pDb
->SQLTableName(tableName
.c_str()).c_str());
1837 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1838 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1839 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1840 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1841 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1842 pDb
->SQLTableName(indexName
.c_str()).c_str());
1844 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1845 pDb
->SQLTableName(indexName
.c_str()).c_str());
1847 pDb
->WriteSqlLog(sqlStmt
);
1849 #ifdef DBDEBUG_CONSOLE
1850 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1852 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1853 if (retcode
!= SQL_SUCCESS
)
1855 // Check for "Index not found" error and ignore
1856 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1857 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1859 // Check for product specific error codes
1860 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1861 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1862 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1863 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1864 (pDb
->Dbms() == dbmsMAXDB
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1865 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1866 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1867 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1868 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1871 pDb
->DispNextError();
1872 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1873 pDb
->RollbackTrans();
1880 // Commit the transaction and close the cursor
1881 if (! pDb
->CommitTrans())
1883 if (! CloseCursor(hstmt
))
1887 } // wxDbTable::DropIndex()
1890 /********** wxDbTable::SetOrderByColNums() **********/
1891 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1893 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1899 va_start(argptr
, first
); /* Initialize variable arguments. */
1900 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1902 // Make sure the passed in column number
1903 // is within the valid range of columns
1905 // Valid columns are 0 thru m_numCols-1
1906 if (colNumber
>= m_numCols
|| colNumber
< 0)
1912 if (colNumber
!= first
)
1913 tempStr
+= wxT(",");
1915 tempStr
+= colDefs
[colNumber
].ColName
;
1916 colNumber
= va_arg (argptr
, int);
1918 va_end (argptr
); /* Reset variable arguments. */
1920 SetOrderByClause(tempStr
);
1923 } // wxDbTable::SetOrderByColNums()
1926 /********** wxDbTable::Insert() **********/
1927 int wxDbTable::Insert(void)
1929 wxASSERT(!queryOnly
);
1930 if (queryOnly
|| !insertable
)
1935 // Insert the record by executing the already prepared insert statement
1937 retcode
= SQLExecute(hstmtInsert
);
1938 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1939 retcode
!= SQL_NEED_DATA
)
1941 // Check to see if integrity constraint was violated
1942 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1943 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1944 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1947 pDb
->DispNextError();
1948 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1952 if (retcode
== SQL_NEED_DATA
)
1955 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1956 while (retcode
== SQL_NEED_DATA
)
1958 // Find the parameter
1960 for (i
=0; i
< m_numCols
; i
++)
1962 if (colDefs
[i
].PtrDataObj
== pParmID
)
1964 // We found it. Store the parameter.
1965 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1966 if (retcode
!= SQL_SUCCESS
)
1968 pDb
->DispNextError();
1969 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1975 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1976 if (retcode
!= SQL_SUCCESS
&&
1977 retcode
!= SQL_SUCCESS_WITH_INFO
)
1979 // record was not inserted
1980 pDb
->DispNextError();
1981 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1987 // Record inserted into the datasource successfully
1990 } // wxDbTable::Insert()
1993 /********** wxDbTable::Update() **********/
1994 bool wxDbTable::Update(void)
1996 wxASSERT(!queryOnly
);
2002 // Build the SQL UPDATE statement
2003 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
2005 pDb
->WriteSqlLog(sqlStmt
);
2007 #ifdef DBDEBUG_CONSOLE
2008 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2011 // Execute the SQL UPDATE statement
2012 return(execUpdate(sqlStmt
));
2014 } // wxDbTable::Update()
2017 /********** wxDbTable::Update(pSqlStmt) **********/
2018 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2020 wxASSERT(!queryOnly
);
2024 pDb
->WriteSqlLog(pSqlStmt
);
2026 return(execUpdate(pSqlStmt
));
2028 } // wxDbTable::Update(pSqlStmt)
2031 /********** wxDbTable::UpdateWhere() **********/
2032 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2034 wxASSERT(!queryOnly
);
2040 // Build the SQL UPDATE statement
2041 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2043 pDb
->WriteSqlLog(sqlStmt
);
2045 #ifdef DBDEBUG_CONSOLE
2046 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2049 // Execute the SQL UPDATE statement
2050 return(execUpdate(sqlStmt
));
2052 } // wxDbTable::UpdateWhere()
2055 /********** wxDbTable::Delete() **********/
2056 bool wxDbTable::Delete(void)
2058 wxASSERT(!queryOnly
);
2065 // Build the SQL DELETE statement
2066 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2068 pDb
->WriteSqlLog(sqlStmt
);
2070 // Execute the SQL DELETE statement
2071 return(execDelete(sqlStmt
));
2073 } // wxDbTable::Delete()
2076 /********** wxDbTable::DeleteWhere() **********/
2077 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2079 wxASSERT(!queryOnly
);
2086 // Build the SQL DELETE statement
2087 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2089 pDb
->WriteSqlLog(sqlStmt
);
2091 // Execute the SQL DELETE statement
2092 return(execDelete(sqlStmt
));
2094 } // wxDbTable::DeleteWhere()
2097 /********** wxDbTable::DeleteMatching() **********/
2098 bool wxDbTable::DeleteMatching(void)
2100 wxASSERT(!queryOnly
);
2107 // Build the SQL DELETE statement
2108 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2110 pDb
->WriteSqlLog(sqlStmt
);
2112 // Execute the SQL DELETE statement
2113 return(execDelete(sqlStmt
));
2115 } // wxDbTable::DeleteMatching()
2118 /********** wxDbTable::IsColNull() **********/
2119 bool wxDbTable::IsColNull(UWORD colNumber
) const
2122 This logic is just not right. It would indicate true
2123 if a numeric field were set to a value of 0.
2125 switch(colDefs[colNumber].SqlCtype)
2129 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2130 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2132 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2134 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2136 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2138 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2140 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2142 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2143 case SQL_C_TIMESTAMP:
2144 TIMESTAMP_STRUCT *pDt;
2145 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2146 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2154 return (colDefs
[colNumber
].Null
);
2155 } // wxDbTable::IsColNull()
2158 /********** wxDbTable::CanSelectForUpdate() **********/
2159 bool wxDbTable::CanSelectForUpdate(void)
2164 if (pDb
->Dbms() == dbmsMY_SQL
)
2167 if ((pDb
->Dbms() == dbmsORACLE
) ||
2168 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2173 } // wxDbTable::CanSelectForUpdate()
2176 /********** wxDbTable::CanUpdateByROWID() **********/
2177 bool wxDbTable::CanUpdateByROWID(void)
2180 * NOTE: Returning false for now until this can be debugged,
2181 * as the ROWID is not getting updated correctly
2185 if (pDb->Dbms() == dbmsORACLE)
2190 } // wxDbTable::CanUpdateByROWID()
2193 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2194 bool wxDbTable::IsCursorClosedOnCommit(void)
2196 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2201 } // wxDbTable::IsCursorClosedOnCommit()
2205 /********** wxDbTable::ClearMemberVar() **********/
2206 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2208 wxASSERT(colNumber
< m_numCols
);
2210 switch(colDefs
[colNumber
].SqlCtype
)
2216 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2217 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2220 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2223 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2227 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2230 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2233 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2236 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2238 case SQL_C_TIMESTAMP
:
2239 TIMESTAMP_STRUCT
*pDt
;
2240 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2252 SetColNull(colNumber
);
2253 } // wxDbTable::ClearMemberVar()
2256 /********** wxDbTable::ClearMemberVars() **********/
2257 void wxDbTable::ClearMemberVars(bool setToNull
)
2261 // Loop through the columns setting each member variable to zero
2262 for (i
=0; i
< m_numCols
; i
++)
2263 ClearMemberVar((UWORD
)i
,setToNull
);
2265 } // wxDbTable::ClearMemberVars()
2268 /********** wxDbTable::SetQueryTimeout() **********/
2269 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2271 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2272 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2273 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2274 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2275 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2276 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2277 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2278 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2280 // Completed Successfully
2283 } // wxDbTable::SetQueryTimeout()
2286 /********** wxDbTable::SetColDefs() **********/
2287 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2288 SWORD cType
, int size
, bool keyField
, bool updateable
,
2289 bool insertAllowed
, bool derivedColumn
)
2293 if (index
>= m_numCols
) // Columns numbers are zero based....
2295 tmpStr
.Printf(wxT("Specified column index (%d) exceeds the maximum number of columns (%d) registered for this table definition. Column definition not added."), index
, m_numCols
);
2301 if (!colDefs
) // May happen if the database connection fails
2304 if (fieldName
.length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2306 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2307 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2309 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2310 fieldName
.c_str(),colDefs
[index
].ColName
);
2315 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2317 colDefs
[index
].DbDataType
= dataType
;
2318 colDefs
[index
].PtrDataObj
= pData
;
2319 colDefs
[index
].SqlCtype
= cType
;
2320 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2321 colDefs
[index
].KeyField
= keyField
;
2322 colDefs
[index
].DerivedCol
= derivedColumn
;
2323 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2326 colDefs
[index
].Updateable
= false;
2327 colDefs
[index
].InsertAllowed
= false;
2331 colDefs
[index
].Updateable
= updateable
;
2332 colDefs
[index
].InsertAllowed
= insertAllowed
;
2335 colDefs
[index
].Null
= false;
2339 } // wxDbTable::SetColDefs()
2342 /********** wxDbTable::SetColDefs() **********/
2343 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2346 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2352 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2354 for (index
= 0; index
< numCols
; index
++)
2356 // Process the fields
2357 switch (pColInfs
[index
].dbDataType
)
2359 case DB_DATA_TYPE_VARCHAR
:
2360 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2361 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2362 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2364 case DB_DATA_TYPE_MEMO
:
2365 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2366 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2367 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2369 case DB_DATA_TYPE_INTEGER
:
2370 // Can be long or short
2371 if (pColInfs
[index
].bufferSize
== sizeof(long))
2373 pColDataPtrs
[index
].PtrDataObj
= new long;
2374 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2375 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2379 pColDataPtrs
[index
].PtrDataObj
= new short;
2380 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2381 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2384 case DB_DATA_TYPE_FLOAT
:
2385 // Can be float or double
2386 if (pColInfs
[index
].bufferSize
== sizeof(float))
2388 pColDataPtrs
[index
].PtrDataObj
= new float;
2389 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2390 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2394 pColDataPtrs
[index
].PtrDataObj
= new double;
2395 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2396 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2399 case DB_DATA_TYPE_DATE
:
2400 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2401 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2402 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2404 case DB_DATA_TYPE_BLOB
:
2405 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2406 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2407 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2408 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2411 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2412 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2415 // Unable to build all the column definitions, as either one of
2416 // the calls to "new" failed above, or there was a BLOB field
2417 // to have a column definition for. If BLOBs are to be used,
2418 // the other form of ::SetColDefs() must be used, as it is impossible
2419 // to know the maximum size to create the PtrDataObj to be.
2420 delete [] pColDataPtrs
;
2426 return (pColDataPtrs
);
2428 } // wxDbTable::SetColDefs()
2431 /********** wxDbTable::SetCursor() **********/
2432 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2434 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2435 hstmt
= *hstmtDefault
;
2437 hstmt
= *hstmtActivate
;
2439 } // wxDbTable::SetCursor()
2442 /********** wxDbTable::Count(const wxString &) **********/
2443 ULONG
wxDbTable::Count(const wxString
&args
)
2449 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2450 sqlStmt
= wxT("SELECT COUNT(");
2452 sqlStmt
+= wxT(") FROM ");
2453 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2454 // sqlStmt += queryTableName;
2455 #if wxODBC_BACKWARD_COMPATABILITY
2456 if (from
&& wxStrlen(from
))
2462 // Add the where clause if one is provided
2463 #if wxODBC_BACKWARD_COMPATABILITY
2464 if (where
&& wxStrlen(where
))
2469 sqlStmt
+= wxT(" WHERE ");
2473 pDb
->WriteSqlLog(sqlStmt
);
2475 // Initialize the Count cursor if it's not already initialized
2478 hstmtCount
= GetNewCursor(false,false);
2479 wxASSERT(hstmtCount
);
2484 // Execute the SQL statement
2485 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2487 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2492 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2494 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2498 // Obtain the result
2499 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2501 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2506 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2507 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2509 // Return the record count
2512 } // wxDbTable::Count()
2515 /********** wxDbTable::Refresh() **********/
2516 bool wxDbTable::Refresh(void)
2520 // Switch to the internal cursor so any active cursors are not corrupted
2521 HSTMT currCursor
= GetCursor();
2522 hstmt
= hstmtInternal
;
2523 #if wxODBC_BACKWARD_COMPATABILITY
2524 // Save the where and order by clauses
2525 wxChar
*saveWhere
= where
;
2526 wxChar
*saveOrderBy
= orderBy
;
2528 wxString saveWhere
= where
;
2529 wxString saveOrderBy
= orderBy
;
2531 // Build a where clause to refetch the record with. Try and use the
2532 // ROWID if it's available, ow use the key fields.
2533 wxString whereClause
;
2534 whereClause
.Empty();
2536 if (CanUpdateByROWID())
2539 wxChar rowid
[wxDB_ROWID_LEN
+1];
2541 // Get the ROWID value. If not successful retreiving the ROWID,
2542 // simply fall down through the code and build the WHERE clause
2543 // based on the key fields.
2544 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2546 whereClause
+= pDb
->SQLTableName(queryTableName
);
2547 // whereClause += queryTableName;
2548 whereClause
+= wxT(".ROWID = '");
2549 whereClause
+= rowid
;
2550 whereClause
+= wxT("'");
2554 // If unable to use the ROWID, build a where clause from the keyfields
2555 if (wxStrlen(whereClause
) == 0)
2556 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2558 // Requery the record
2559 where
= whereClause
;
2564 if (result
&& !GetNext())
2567 // Switch back to original cursor
2568 SetCursor(&currCursor
);
2570 // Free the internal cursor
2571 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2572 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2574 // Restore the original where and order by clauses
2576 orderBy
= saveOrderBy
;
2580 } // wxDbTable::Refresh()
2583 /********** wxDbTable::SetColNull() **********/
2584 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2586 if (colNumber
< m_numCols
)
2588 colDefs
[colNumber
].Null
= set
;
2589 if (set
) // Blank out the values in the member variable
2590 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2592 setCbValueForColumn(colNumber
);
2599 } // wxDbTable::SetColNull()
2602 /********** wxDbTable::SetColNull() **********/
2603 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2606 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2608 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2612 if (colNumber
< m_numCols
)
2614 colDefs
[colNumber
].Null
= set
;
2615 if (set
) // Blank out the values in the member variable
2616 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2618 setCbValueForColumn(colNumber
);
2625 } // wxDbTable::SetColNull()
2628 /********** wxDbTable::GetNewCursor() **********/
2629 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2631 HSTMT
*newHSTMT
= new HSTMT
;
2636 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2638 pDb
->DispAllErrors(henv
, hdbc
);
2643 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2645 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2652 if (!bindCols(*newHSTMT
))
2660 SetCursor(newHSTMT
);
2664 } // wxDbTable::GetNewCursor()
2667 /********** wxDbTable::DeleteCursor() **********/
2668 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2672 if (!hstmtDel
) // Cursor already deleted
2676 ODBC 3.0 says to use this form
2677 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2680 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2682 pDb
->DispAllErrors(henv
, hdbc
);
2690 } // wxDbTable::DeleteCursor()
2692 //////////////////////////////////////////////////////////////
2693 // wxDbGrid support functions
2694 //////////////////////////////////////////////////////////////
2696 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2698 if (!m_hstmtGridQuery
)
2700 m_hstmtGridQuery
= GetNewCursor(false,false);
2701 if (!bindCols(*m_hstmtGridQuery
))
2705 m_rowmode
= rowmode
;
2708 case WX_ROW_MODE_QUERY
:
2709 SetCursor(m_hstmtGridQuery
);
2711 case WX_ROW_MODE_INDIVIDUAL
:
2712 SetCursor(hstmtDefault
);
2717 } // wxDbTable::SetRowMode()
2720 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2723 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2725 switch (colDefs
[colNumber
].SqlCtype
)
2728 #if defined(SQL_WCHAR)
2731 #if defined(SQL_WVARCHAR)
2737 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2741 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2745 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2748 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2751 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2753 case SQL_C_UTINYINT
:
2754 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2757 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2760 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2763 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2765 case SQL_C_TIMESTAMP
:
2766 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2769 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2776 } // wxDbTable::GetCol()
2779 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2781 //FIXME: Add proper wxDateTime support to wxVariant..
2784 SetColNull((UWORD
)colNumber
, val
.IsNull());
2788 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2789 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2790 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2792 //Returns null if invalid!
2793 if (!dateval
.ParseDate(val
.GetString()))
2794 SetColNull((UWORD
)colNumber
, true);
2797 switch (colDefs
[colNumber
].SqlCtype
)
2800 #if defined(SQL_WCHAR)
2803 #if defined(SQL_WVARCHAR)
2809 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2810 val
.GetString().c_str(),
2811 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2815 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2819 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2822 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2825 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2827 case SQL_C_UTINYINT
:
2828 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2831 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2833 //FIXME: Add proper wxDateTime support to wxVariant..
2836 DATE_STRUCT
*dataptr
=
2837 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2839 dataptr
->year
= (SWORD
)dateval
.GetYear();
2840 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2841 dataptr
->day
= (UWORD
)dateval
.GetDay();
2846 TIME_STRUCT
*dataptr
=
2847 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2849 dataptr
->hour
= dateval
.GetHour();
2850 dataptr
->minute
= dateval
.GetMinute();
2851 dataptr
->second
= dateval
.GetSecond();
2854 case SQL_C_TIMESTAMP
:
2856 TIMESTAMP_STRUCT
*dataptr
=
2857 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2858 dataptr
->year
= (SWORD
)dateval
.GetYear();
2859 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2860 dataptr
->day
= (UWORD
)dateval
.GetDay();
2862 dataptr
->hour
= dateval
.GetHour();
2863 dataptr
->minute
= dateval
.GetMinute();
2864 dataptr
->second
= dateval
.GetSecond();
2868 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2873 } // if (!val.IsNull())
2874 } // wxDbTable::SetCol()
2877 GenericKey
wxDbTable::GetKey()
2882 blk
= malloc(m_keysize
);
2883 blkptr
= (wxChar
*) blk
;
2886 for (i
=0; i
< m_numCols
; i
++)
2888 if (colDefs
[i
].KeyField
)
2890 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2891 blkptr
+= colDefs
[i
].SzDataObj
;
2895 GenericKey k
= GenericKey(blk
, m_keysize
);
2899 } // wxDbTable::GetKey()
2902 void wxDbTable::SetKey(const GenericKey
& k
)
2908 blkptr
= (wxChar
*)blk
;
2911 for (i
=0; i
< m_numCols
; i
++)
2913 if (colDefs
[i
].KeyField
)
2915 SetColNull((UWORD
)i
, false);
2916 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2917 blkptr
+= colDefs
[i
].SzDataObj
;
2920 } // wxDbTable::SetKey()
2923 #endif // wxUSE_ODBC