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 ///////////////////////////////////////////////////////////////////////////////
14 #include "wx/wxprec.h"
23 #include "wx/object.h"
25 #include "wx/string.h"
30 #ifdef DBDEBUG_CONSOLE
36 #include "wx/ioswrap.h"
39 #include "wx/filefn.h"
45 #include "wx/dbtable.h"
48 // The HPUX preprocessor lines below were commented out on 8/20/97
49 // because macros.h currently redefines DEBUG and is unneeded.
51 // # include <macros.h>
54 # include <sys/minmax.h>
58 ULONG lastTableID
= 0;
63 wxCriticalSection csTablesInUse
;
67 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
69 while ( (*target
++ = *source
++) != '\0' && --n
!= 0 )
77 /********** wxDbColDef::wxDbColDef() Constructor **********/
78 wxDbColDef::wxDbColDef()
84 bool wxDbColDef::Initialize()
87 DbDataType
= DB_DATA_TYPE_INTEGER
;
88 SqlCtype
= SQL_C_LONG
;
93 InsertAllowed
= false;
99 } // wxDbColDef::Initialize()
102 /********** wxDbTable::wxDbTable() Constructor **********/
103 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
104 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
106 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
108 } // wxDbTable::wxDbTable()
111 /********** wxDbTable::~wxDbTable() **********/
112 wxDbTable::~wxDbTable()
115 } // wxDbTable::~wxDbTable()
118 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
119 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
121 // Initializing member variables
122 pDb
= pwxDb
; // Pointer to the wxDb object
126 m_hstmtGridQuery
= 0;
127 hstmtDefault
= 0; // Initialized below
128 hstmtCount
= 0; // Initialized first time it is needed
135 m_numCols
= numColumns
; // Number of columns in the table
136 where
.Empty(); // Where clause
137 orderBy
.Empty(); // Order By clause
138 from
.Empty(); // From clause
139 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
144 queryTableName
.Empty();
146 wxASSERT(tblName
.length());
152 tableName
= tblName
; // Table Name
153 if ((pDb
->Dbms() == dbmsORACLE
) ||
154 (pDb
->Dbms() == dbmsFIREBIRD
) ||
155 (pDb
->Dbms() == dbmsINTERBASE
))
156 tableName
= tableName
.Upper();
158 if (tblPath
.length())
159 tablePath
= tblPath
; // Table Path - used for dBase files
163 if (qryTblName
.length()) // Name of the table/view to query
164 queryTableName
= qryTblName
;
166 queryTableName
= tblName
;
168 if ((pDb
->Dbms() == dbmsORACLE
) ||
169 (pDb
->Dbms() == dbmsFIREBIRD
) ||
170 (pDb
->Dbms() == dbmsINTERBASE
))
171 queryTableName
= queryTableName
.Upper();
173 pDb
->incrementTableCount();
176 tableID
= ++lastTableID
;
177 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"),
178 tblName
.c_str(), tableID
, wx_static_cast(void*, pDb
));
181 wxTablesInUse
*tableInUse
;
182 tableInUse
= new wxTablesInUse();
183 tableInUse
->tableName
= tblName
;
184 tableInUse
->tableID
= tableID
;
185 tableInUse
->pDb
= pDb
;
187 wxCriticalSectionLocker
lock(csTablesInUse
);
188 TablesInUse
.Append(tableInUse
);
194 // Grab the HENV and HDBC from the wxDb object
195 henv
= pDb
->GetHENV();
196 hdbc
= pDb
->GetHDBC();
198 // Allocate space for column definitions
200 colDefs
= new wxDbColDef
[m_numCols
]; // Points to the first column definition
202 // Allocate statement handles for the table
205 // Allocate a separate statement handle for performing inserts
206 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
207 pDb
->DispAllErrors(henv
, hdbc
);
208 // Allocate a separate statement handle for performing deletes
209 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
210 pDb
->DispAllErrors(henv
, hdbc
);
211 // Allocate a separate statement handle for performing updates
212 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
213 pDb
->DispAllErrors(henv
, hdbc
);
215 // Allocate a separate statement handle for internal use
216 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
217 pDb
->DispAllErrors(henv
, hdbc
);
219 // Set the cursor type for the statement handles
220 cursorType
= SQL_CURSOR_STATIC
;
222 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
224 // Check to see if cursor type is supported
225 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
226 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
228 // Datasource does not support static cursors. Driver
229 // will substitute a cursor type. Call SQLGetStmtOption()
230 // to determine which cursor type was selected.
231 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
232 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
233 #ifdef DBDEBUG_CONSOLE
234 cout
<< wxT("Static cursor changed to: ");
237 case SQL_CURSOR_FORWARD_ONLY
:
238 cout
<< wxT("Forward Only");
240 case SQL_CURSOR_STATIC
:
241 cout
<< wxT("Static");
243 case SQL_CURSOR_KEYSET_DRIVEN
:
244 cout
<< wxT("Keyset Driven");
246 case SQL_CURSOR_DYNAMIC
:
247 cout
<< wxT("Dynamic");
250 cout
<< endl
<< endl
;
253 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
255 // Force the use of a forward only cursor...
256 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
257 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
259 // Should never happen
260 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
267 pDb
->DispNextError();
268 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
271 #ifdef DBDEBUG_CONSOLE
273 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
278 // Set the cursor type for the INSERT statement handle
279 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
280 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
281 // Set the cursor type for the DELETE statement handle
282 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
283 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
284 // Set the cursor type for the UPDATE statement handle
285 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
286 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
289 // Make the default cursor the active cursor
290 hstmtDefault
= GetNewCursor(false,false);
291 wxASSERT(hstmtDefault
);
292 hstmt
= *hstmtDefault
;
296 } // wxDbTable::initialize()
299 void wxDbTable::cleanup()
304 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"),
305 tableName
.c_str(), tableID
, wx_static_cast(void*, pDb
));
314 wxList::compatibility_iterator pNode
;
316 wxCriticalSectionLocker
lock(csTablesInUse
);
317 pNode
= TablesInUse
.GetFirst();
318 while (!found
&& pNode
)
320 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
323 delete (wxTablesInUse
*)pNode
->GetData();
324 TablesInUse
.Erase(pNode
);
327 pNode
= pNode
->GetNext();
333 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
334 wxLogDebug (msg
,wxT("NOTICE..."));
339 // Decrement the wxDb table count
341 pDb
->decrementTableCount();
343 // Delete memory allocated for column definitions
347 // Free statement handles
353 ODBC 3.0 says to use this form
354 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
356 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
357 pDb
->DispAllErrors(henv
, hdbc
);
363 ODBC 3.0 says to use this form
364 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
366 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
367 pDb
->DispAllErrors(henv
, hdbc
);
373 ODBC 3.0 says to use this form
374 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
376 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
377 pDb
->DispAllErrors(henv
, hdbc
);
383 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
384 pDb
->DispAllErrors(henv
, hdbc
);
387 // Delete dynamically allocated cursors
389 DeleteCursor(hstmtDefault
);
392 DeleteCursor(hstmtCount
);
394 if (m_hstmtGridQuery
)
395 DeleteCursor(m_hstmtGridQuery
);
397 } // wxDbTable::cleanup()
400 /***************************** PRIVATE FUNCTIONS *****************************/
403 void wxDbTable::setCbValueForColumn(int columnIndex
)
405 switch(colDefs
[columnIndex
].DbDataType
)
407 case DB_DATA_TYPE_VARCHAR
:
408 case DB_DATA_TYPE_MEMO
:
409 if (colDefs
[columnIndex
].Null
)
410 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
412 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
414 case DB_DATA_TYPE_INTEGER
:
415 if (colDefs
[columnIndex
].Null
)
416 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
418 colDefs
[columnIndex
].CbValue
= 0;
420 case DB_DATA_TYPE_FLOAT
:
421 if (colDefs
[columnIndex
].Null
)
422 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
424 colDefs
[columnIndex
].CbValue
= 0;
426 case DB_DATA_TYPE_DATE
:
427 if (colDefs
[columnIndex
].Null
)
428 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
430 colDefs
[columnIndex
].CbValue
= 0;
432 case DB_DATA_TYPE_BLOB
:
433 if (colDefs
[columnIndex
].Null
)
434 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
436 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
437 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
439 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
444 /********** wxDbTable::bindParams() **********/
445 bool wxDbTable::bindParams(bool forUpdate
)
447 wxASSERT(!queryOnly
);
452 SDWORD precision
= 0;
455 // Bind each column of the table that should be bound
456 // to a parameter marker
460 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
464 if (!colDefs
[i
].Updateable
)
469 if (!colDefs
[i
].InsertAllowed
)
473 switch(colDefs
[i
].DbDataType
)
475 case DB_DATA_TYPE_VARCHAR
:
476 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
477 precision
= colDefs
[i
].SzDataObj
;
480 case DB_DATA_TYPE_MEMO
:
481 fSqlType
= pDb
->GetTypeInfMemo().FsqlType
;
482 precision
= colDefs
[i
].SzDataObj
;
485 case DB_DATA_TYPE_INTEGER
:
486 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
487 precision
= pDb
->GetTypeInfInteger().Precision
;
490 case DB_DATA_TYPE_FLOAT
:
491 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
492 precision
= pDb
->GetTypeInfFloat().Precision
;
493 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
494 // SQL Sybase Anywhere v5.5 returned a negative number for the
495 // MaxScale. This caused ODBC to kick out an error on ibscale.
496 // I check for this here and set the scale = precision.
498 // scale = (short) precision;
500 case DB_DATA_TYPE_DATE
:
501 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
502 precision
= pDb
->GetTypeInfDate().Precision
;
505 case DB_DATA_TYPE_BLOB
:
506 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
507 precision
= colDefs
[i
].SzDataObj
;
512 setCbValueForColumn(i
);
516 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
517 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
518 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
520 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
525 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
526 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
527 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
529 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
534 // Completed successfully
537 } // wxDbTable::bindParams()
540 /********** wxDbTable::bindInsertParams() **********/
541 bool wxDbTable::bindInsertParams(void)
543 return bindParams(false);
544 } // wxDbTable::bindInsertParams()
547 /********** wxDbTable::bindUpdateParams() **********/
548 bool wxDbTable::bindUpdateParams(void)
550 return bindParams(true);
551 } // wxDbTable::bindUpdateParams()
554 /********** wxDbTable::bindCols() **********/
555 bool wxDbTable::bindCols(HSTMT cursor
)
557 // Bind each column of the table to a memory address for fetching data
559 for (i
= 0; i
< m_numCols
; i
++)
561 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
562 colDefs
[i
].SzDataObj
, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
563 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
566 // Completed successfully
568 } // wxDbTable::bindCols()
571 /********** wxDbTable::getRec() **********/
572 bool wxDbTable::getRec(UWORD fetchType
)
576 if (!pDb
->FwdOnlyCursors())
578 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
579 SQLULEN cRowsFetched
;
582 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
583 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
585 if (retcode
== SQL_NO_DATA_FOUND
)
588 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
592 // Set the Null member variable to indicate the Null state
593 // of each column just read in.
595 for (i
= 0; i
< m_numCols
; i
++)
596 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
601 // Fetch the next record from the record set
602 retcode
= SQLFetch(hstmt
);
603 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
605 if (retcode
== SQL_NO_DATA_FOUND
)
608 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
612 // Set the Null member variable to indicate the Null state
613 // of each column just read in.
615 for (i
= 0; i
< m_numCols
; i
++)
616 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
620 // Completed successfully
623 } // wxDbTable::getRec()
626 /********** wxDbTable::execDelete() **********/
627 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
631 // Execute the DELETE statement
632 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
634 if (retcode
== SQL_SUCCESS
||
635 retcode
== SQL_NO_DATA_FOUND
||
636 retcode
== SQL_SUCCESS_WITH_INFO
)
638 // Record deleted successfully
642 // Problem deleting record
643 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
645 } // wxDbTable::execDelete()
648 /********** wxDbTable::execUpdate() **********/
649 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
653 // Execute the UPDATE statement
654 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
656 if (retcode
== SQL_SUCCESS
||
657 retcode
== SQL_NO_DATA_FOUND
||
658 retcode
== SQL_SUCCESS_WITH_INFO
)
660 // Record updated successfully
663 else if (retcode
== SQL_NEED_DATA
)
666 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
667 while (retcode
== SQL_NEED_DATA
)
669 // Find the parameter
671 for (i
=0; i
< m_numCols
; i
++)
673 if (colDefs
[i
].PtrDataObj
== pParmID
)
675 // We found it. Store the parameter.
676 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
677 if (retcode
!= SQL_SUCCESS
)
679 pDb
->DispNextError();
680 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
685 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
687 if (retcode
== SQL_SUCCESS
||
688 retcode
== SQL_NO_DATA_FOUND
||
689 retcode
== SQL_SUCCESS_WITH_INFO
)
691 // Record updated successfully
696 // Problem updating record
697 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
699 } // wxDbTable::execUpdate()
702 /********** wxDbTable::query() **********/
703 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
708 // The user may wish to select for update, but the DBMS may not be capable
709 selectForUpdate
= CanSelectForUpdate();
711 selectForUpdate
= false;
713 // Set the SQL SELECT string
714 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
715 { // so generate a select statement.
716 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
717 pDb
->WriteSqlLog(sqlStmt
);
720 // Make sure the cursor is closed first
721 if (!CloseCursor(hstmt
))
724 // Execute the SQL SELECT statement
726 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
727 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
728 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
730 // Completed successfully
733 } // wxDbTable::query()
736 /***************************** PUBLIC FUNCTIONS *****************************/
739 /********** wxDbTable::Open() **********/
740 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
749 // Calculate the maximum size of the concatenated
750 // keys for use with wxDbGrid
752 for (i
=0; i
< m_numCols
; i
++)
754 if (colDefs
[i
].KeyField
)
756 m_keysize
+= colDefs
[i
].SzDataObj
;
763 if (checkTableExists
)
765 if (pDb
->Dbms() == dbmsPOSTGRES
)
766 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
768 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
771 // Verify that the table exists in the database
774 s
= wxT("Table/view does not exist in the database");
775 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
776 s
+= wxT(", or you have no permissions.\n");
780 else if (checkPrivileges
)
782 // Verify the user has rights to access the table.
783 bool hasPrivs
wxDUMMY_INITIALIZE(true);
785 if (pDb
->Dbms() == dbmsPOSTGRES
)
786 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
788 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
791 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
798 if (!tablePath
.empty())
799 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
801 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
804 pDb
->LogError(p
.GetData());
809 // Bind the member variables for field exchange between
810 // the wxDbTable object and the ODBC record.
813 if (!bindInsertParams()) // Inserts
816 if (!bindUpdateParams()) // Updates
820 if (!bindCols(*hstmtDefault
)) // Selects
823 if (!bindCols(hstmtInternal
)) // Internal use only
827 * Do NOT bind the hstmtCount cursor!!!
830 // Build an insert statement using parameter markers
831 if (!queryOnly
&& m_numCols
> 0)
833 bool needComma
= false;
834 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
835 pDb
->SQLTableName(tableName
.c_str()).c_str());
836 for (i
= 0; i
< m_numCols
; i
++)
838 if (! colDefs
[i
].InsertAllowed
)
842 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
846 sqlStmt
+= wxT(") VALUES (");
848 int insertableCount
= 0;
850 for (i
= 0; i
< m_numCols
; i
++)
852 if (! colDefs
[i
].InsertAllowed
)
862 // Prepare the insert statement for execution
865 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
866 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
872 // Completed successfully
875 } // wxDbTable::Open()
878 /********** wxDbTable::Query() **********/
879 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
882 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
884 } // wxDbTable::Query()
887 /********** wxDbTable::QueryBySqlStmt() **********/
888 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
890 pDb
->WriteSqlLog(pSqlStmt
);
892 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
894 } // wxDbTable::QueryBySqlStmt()
897 /********** wxDbTable::QueryMatching() **********/
898 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
901 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
903 } // wxDbTable::QueryMatching()
906 /********** wxDbTable::QueryOnKeyFields() **********/
907 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
910 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
912 } // wxDbTable::QueryOnKeyFields()
915 /********** wxDbTable::GetPrev() **********/
916 bool wxDbTable::GetPrev(void)
918 if (pDb
->FwdOnlyCursors())
920 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
924 return(getRec(SQL_FETCH_PRIOR
));
926 } // wxDbTable::GetPrev()
929 /********** wxDbTable::operator-- **********/
930 bool wxDbTable::operator--(int)
932 if (pDb
->FwdOnlyCursors())
934 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
938 return(getRec(SQL_FETCH_PRIOR
));
940 } // wxDbTable::operator--
943 /********** wxDbTable::GetFirst() **********/
944 bool wxDbTable::GetFirst(void)
946 if (pDb
->FwdOnlyCursors())
948 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
952 return(getRec(SQL_FETCH_FIRST
));
954 } // wxDbTable::GetFirst()
957 /********** wxDbTable::GetLast() **********/
958 bool wxDbTable::GetLast(void)
960 if (pDb
->FwdOnlyCursors())
962 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
966 return(getRec(SQL_FETCH_LAST
));
968 } // wxDbTable::GetLast()
971 /********** wxDbTable::BuildDeleteStmt() **********/
972 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
974 wxASSERT(!queryOnly
);
978 wxString whereClause
;
982 // Handle the case of DeleteWhere() and the where clause is blank. It should
983 // delete all records from the database in this case.
984 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.length() == 0))
986 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
987 pDb
->SQLTableName(tableName
.c_str()).c_str());
991 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
992 pDb
->SQLTableName(tableName
.c_str()).c_str());
994 // Append the WHERE clause to the SQL DELETE statement
997 case DB_DEL_KEYFIELDS
:
998 // If the datasource supports the ROWID column, build
999 // the where on ROWID for efficiency purposes.
1000 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1001 if (CanUpdateByROWID())
1004 wxChar rowid
[wxDB_ROWID_LEN
+1];
1006 // Get the ROWID value. If not successful retreiving the ROWID,
1007 // simply fall down through the code and build the WHERE clause
1008 // based on the key fields.
1009 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1011 pSqlStmt
+= wxT("ROWID = '");
1013 pSqlStmt
+= wxT("'");
1017 // Unable to delete by ROWID, so build a WHERE
1018 // clause based on the keyfields.
1019 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1020 pSqlStmt
+= whereClause
;
1023 pSqlStmt
+= pWhereClause
;
1025 case DB_DEL_MATCHING
:
1026 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1027 pSqlStmt
+= whereClause
;
1031 } // BuildDeleteStmt()
1034 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1035 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1037 wxString tempSqlStmt
;
1038 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1039 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1040 } // wxDbTable::BuildDeleteStmt()
1043 /********** wxDbTable::BuildSelectStmt() **********/
1044 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1046 wxString whereClause
;
1047 whereClause
.Empty();
1049 // Build a select statement to query the database
1050 pSqlStmt
= wxT("SELECT ");
1052 // SELECT DISTINCT values only?
1054 pSqlStmt
+= wxT("DISTINCT ");
1056 // Was a FROM clause specified to join tables to the base table?
1057 // Available for ::Query() only!!!
1058 bool appendFromClause
= false;
1059 #if wxODBC_BACKWARD_COMPATABILITY
1060 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1061 appendFromClause
= true;
1063 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.length())
1064 appendFromClause
= true;
1067 // Add the column list
1070 for (i
= 0; i
< m_numCols
; i
++)
1072 tStr
= colDefs
[i
].ColName
;
1073 // If joining tables, the base table column names must be qualified to avoid ambiguity
1074 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1076 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1077 pSqlStmt
+= wxT(".");
1079 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1080 if (i
+ 1 < m_numCols
)
1081 pSqlStmt
+= wxT(",");
1084 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1085 // the ROWID if querying distinct records. The rowid will always be unique.
1086 if (!distinct
&& CanUpdateByROWID())
1088 // If joining tables, the base table column names must be qualified to avoid ambiguity
1089 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1091 pSqlStmt
+= wxT(",");
1092 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1093 pSqlStmt
+= wxT(".ROWID");
1096 pSqlStmt
+= wxT(",ROWID");
1099 // Append the FROM tablename portion
1100 pSqlStmt
+= wxT(" FROM ");
1101 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1102 // pSqlStmt += queryTableName;
1104 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1105 // The HOLDLOCK keyword follows the table name in the from clause.
1106 // Each table in the from clause must specify HOLDLOCK or
1107 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1108 // is parsed but ignored in SYBASE Transact-SQL.
1109 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1110 pSqlStmt
+= wxT(" HOLDLOCK");
1112 if (appendFromClause
)
1115 // Append the WHERE clause. Either append the where clause for the class
1116 // or build a where clause. The typeOfSelect determines this.
1117 switch(typeOfSelect
)
1119 case DB_SELECT_WHERE
:
1120 #if wxODBC_BACKWARD_COMPATABILITY
1121 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1123 if (where
.length()) // May not want a where clause!!!
1126 pSqlStmt
+= wxT(" WHERE ");
1130 case DB_SELECT_KEYFIELDS
:
1131 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1132 if (whereClause
.length())
1134 pSqlStmt
+= wxT(" WHERE ");
1135 pSqlStmt
+= whereClause
;
1138 case DB_SELECT_MATCHING
:
1139 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1140 if (whereClause
.length())
1142 pSqlStmt
+= wxT(" WHERE ");
1143 pSqlStmt
+= whereClause
;
1148 // Append the ORDER BY clause
1149 #if wxODBC_BACKWARD_COMPATABILITY
1150 if (orderBy
&& wxStrlen(orderBy
))
1152 if (orderBy
.length())
1155 pSqlStmt
+= wxT(" ORDER BY ");
1156 pSqlStmt
+= orderBy
;
1159 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1160 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1161 // HOLDLOCK for Sybase.
1162 if (selectForUpdate
&& CanSelectForUpdate())
1163 pSqlStmt
+= wxT(" FOR UPDATE");
1165 } // wxDbTable::BuildSelectStmt()
1168 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1169 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1171 wxString tempSqlStmt
;
1172 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1173 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1174 } // wxDbTable::BuildSelectStmt()
1177 /********** wxDbTable::BuildUpdateStmt() **********/
1178 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1180 wxASSERT(!queryOnly
);
1184 wxString whereClause
;
1185 whereClause
.Empty();
1187 bool firstColumn
= true;
1189 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1190 pDb
->SQLTableName(tableName
.c_str()).c_str());
1192 // Append a list of columns to be updated
1194 for (i
= 0; i
< m_numCols
; i
++)
1196 // Only append Updateable columns
1197 if (colDefs
[i
].Updateable
)
1200 pSqlStmt
+= wxT(",");
1202 firstColumn
= false;
1204 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1205 // pSqlStmt += colDefs[i].ColName;
1206 pSqlStmt
+= wxT(" = ?");
1210 // Append the WHERE clause to the SQL UPDATE statement
1211 pSqlStmt
+= wxT(" WHERE ");
1212 switch(typeOfUpdate
)
1214 case DB_UPD_KEYFIELDS
:
1215 // If the datasource supports the ROWID column, build
1216 // the where on ROWID for efficiency purposes.
1217 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1218 if (CanUpdateByROWID())
1221 wxChar rowid
[wxDB_ROWID_LEN
+1];
1223 // Get the ROWID value. If not successful retreiving the ROWID,
1224 // simply fall down through the code and build the WHERE clause
1225 // based on the key fields.
1226 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1228 pSqlStmt
+= wxT("ROWID = '");
1230 pSqlStmt
+= wxT("'");
1234 // Unable to delete by ROWID, so build a WHERE
1235 // clause based on the keyfields.
1236 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1237 pSqlStmt
+= whereClause
;
1240 pSqlStmt
+= pWhereClause
;
1243 } // BuildUpdateStmt()
1246 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1247 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1249 wxString tempSqlStmt
;
1250 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1251 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1252 } // BuildUpdateStmt()
1255 /********** wxDbTable::BuildWhereClause() **********/
1256 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1257 const wxString
&qualTableName
, bool useLikeComparison
)
1259 * Note: BuildWhereClause() currently ignores timestamp columns.
1260 * They are not included as part of the where clause.
1263 bool moreThanOneColumn
= false;
1266 // Loop through the columns building a where clause as you go
1268 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1270 // Determine if this column should be included in the WHERE clause
1271 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1272 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1274 // Skip over timestamp columns
1275 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1277 // If there is more than 1 column, join them with the keyword "AND"
1278 if (moreThanOneColumn
)
1279 pWhereClause
+= wxT(" AND ");
1281 moreThanOneColumn
= true;
1283 // Concatenate where phrase for the column
1284 wxString tStr
= colDefs
[colNumber
].ColName
;
1286 if (qualTableName
.length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1288 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1289 pWhereClause
+= wxT(".");
1291 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1293 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1294 pWhereClause
+= wxT(" LIKE ");
1296 pWhereClause
+= wxT(" = ");
1298 switch(colDefs
[colNumber
].SqlCtype
)
1304 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1305 colValue
.Printf(wxT("'%s'"), GetDb()->EscapeSqlChars((wxChar
*)colDefs
[colNumber
].PtrDataObj
).c_str());
1309 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1312 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1316 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1319 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1322 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1325 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1330 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1331 colNumber
,colDefs
[colNumber
].ColName
);
1332 wxFAIL_MSG(strMsg
.c_str());
1336 pWhereClause
+= colValue
;
1339 } // wxDbTable::BuildWhereClause()
1342 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1343 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1344 const wxString
&qualTableName
, bool useLikeComparison
)
1346 wxString tempSqlStmt
;
1347 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1348 wxStrcpy(pWhereClause
, tempSqlStmt
);
1349 } // wxDbTable::BuildWhereClause()
1352 /********** wxDbTable::GetRowNum() **********/
1353 UWORD
wxDbTable::GetRowNum(void)
1357 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1359 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1363 // Completed successfully
1364 return((UWORD
) rowNum
);
1366 } // wxDbTable::GetRowNum()
1369 /********** wxDbTable::CloseCursor() **********/
1370 bool wxDbTable::CloseCursor(HSTMT cursor
)
1372 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1373 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1375 // Completed successfully
1378 } // wxDbTable::CloseCursor()
1381 /********** wxDbTable::CreateTable() **********/
1382 bool wxDbTable::CreateTable(bool attemptDrop
)
1390 #ifdef DBDEBUG_CONSOLE
1391 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1395 if (attemptDrop
&& !DropTable())
1399 #ifdef DBDEBUG_CONSOLE
1400 for (i
= 0; i
< m_numCols
; i
++)
1402 // Exclude derived columns since they are NOT part of the base table
1403 if (colDefs
[i
].DerivedCol
)
1405 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1406 switch(colDefs
[i
].DbDataType
)
1408 case DB_DATA_TYPE_VARCHAR
:
1409 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1411 case DB_DATA_TYPE_MEMO
:
1412 cout
<< pDb
->GetTypeInfMemo().TypeName
;
1414 case DB_DATA_TYPE_INTEGER
:
1415 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1417 case DB_DATA_TYPE_FLOAT
:
1418 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1420 case DB_DATA_TYPE_DATE
:
1421 cout
<< pDb
->GetTypeInfDate().TypeName
;
1423 case DB_DATA_TYPE_BLOB
:
1424 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1431 // Build a CREATE TABLE string from the colDefs structure.
1432 bool needComma
= false;
1434 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1435 pDb
->SQLTableName(tableName
.c_str()).c_str());
1437 for (i
= 0; i
< m_numCols
; i
++)
1439 // Exclude derived columns since they are NOT part of the base table
1440 if (colDefs
[i
].DerivedCol
)
1444 sqlStmt
+= wxT(",");
1446 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1447 // sqlStmt += colDefs[i].ColName;
1448 sqlStmt
+= wxT(" ");
1450 switch(colDefs
[i
].DbDataType
)
1452 case DB_DATA_TYPE_VARCHAR
:
1453 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1455 case DB_DATA_TYPE_MEMO
:
1456 sqlStmt
+= pDb
->GetTypeInfMemo().TypeName
;
1458 case DB_DATA_TYPE_INTEGER
:
1459 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1461 case DB_DATA_TYPE_FLOAT
:
1462 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1464 case DB_DATA_TYPE_DATE
:
1465 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1467 case DB_DATA_TYPE_BLOB
:
1468 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1471 // For varchars, append the size of the string
1472 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1473 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1474 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1477 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1481 if (pDb
->Dbms() == dbmsDB2
||
1482 pDb
->Dbms() == dbmsMY_SQL
||
1483 pDb
->Dbms() == dbmsSYBASE_ASE
||
1484 pDb
->Dbms() == dbmsINTERBASE
||
1485 pDb
->Dbms() == dbmsFIREBIRD
||
1486 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1488 if (colDefs
[i
].KeyField
)
1490 sqlStmt
+= wxT(" NOT NULL");
1496 // If there is a primary key defined, include it in the create statement
1497 for (i
= j
= 0; i
< m_numCols
; i
++)
1499 if (colDefs
[i
].KeyField
)
1505 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1506 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1508 switch (pDb
->Dbms())
1512 case dbmsSYBASE_ASA
:
1513 case dbmsSYBASE_ASE
:
1517 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1518 sqlStmt
+= wxT(",PRIMARY KEY (");
1523 sqlStmt
+= wxT(",CONSTRAINT ");
1524 // DB2 is limited to 18 characters for index names
1525 if (pDb
->Dbms() == dbmsDB2
)
1527 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."));
1528 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1529 // sqlStmt += tableName.substr(0, 13);
1532 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1533 // sqlStmt += tableName;
1535 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1540 // List column name(s) of column(s) comprising the primary key
1541 for (i
= j
= 0; i
< m_numCols
; i
++)
1543 if (colDefs
[i
].KeyField
)
1545 if (j
++) // Multi part key, comma separate names
1546 sqlStmt
+= wxT(",");
1547 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1549 if (pDb
->Dbms() == dbmsMY_SQL
&&
1550 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1553 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1558 sqlStmt
+= wxT(")");
1560 if (pDb
->Dbms() == dbmsINFORMIX
||
1561 pDb
->Dbms() == dbmsSYBASE_ASA
||
1562 pDb
->Dbms() == dbmsSYBASE_ASE
)
1564 sqlStmt
+= wxT(" CONSTRAINT ");
1565 sqlStmt
+= pDb
->SQLTableName(tableName
);
1566 // sqlStmt += tableName;
1567 sqlStmt
+= wxT("_PIDX");
1570 // Append the closing parentheses for the create table statement
1571 sqlStmt
+= wxT(")");
1573 pDb
->WriteSqlLog(sqlStmt
);
1575 #ifdef DBDEBUG_CONSOLE
1576 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1579 // Execute the CREATE TABLE statement
1580 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1581 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1583 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1584 pDb
->RollbackTrans();
1589 // Commit the transaction and close the cursor
1590 if (!pDb
->CommitTrans())
1592 if (!CloseCursor(hstmt
))
1595 // Database table created successfully
1598 } // wxDbTable::CreateTable()
1601 /********** wxDbTable::DropTable() **********/
1602 bool wxDbTable::DropTable()
1604 // NOTE: This function returns true if the Table does not exist, but
1605 // only for identified databases. Code will need to be added
1606 // below for any other databases when those databases are defined
1607 // to handle this situation consistently
1611 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1612 pDb
->SQLTableName(tableName
.c_str()).c_str());
1614 pDb
->WriteSqlLog(sqlStmt
);
1616 #ifdef DBDEBUG_CONSOLE
1617 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1620 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1621 if (retcode
!= SQL_SUCCESS
)
1623 // Check for "Base table not found" error and ignore
1624 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1625 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1626 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1628 // Check for product specific error codes
1629 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1630 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1631 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1632 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1634 pDb
->DispNextError();
1635 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1636 pDb
->RollbackTrans();
1637 // CloseCursor(hstmt);
1643 // Commit the transaction and close the cursor
1644 if (! pDb
->CommitTrans())
1646 if (! CloseCursor(hstmt
))
1650 } // wxDbTable::DropTable()
1653 /********** wxDbTable::CreateIndex() **********/
1654 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1655 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1659 // Drop the index first
1660 if (attemptDrop
&& !DropIndex(indexName
))
1663 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1664 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1665 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1666 // table was created, then months later you determine that an additional index while
1667 // give better performance, so you want to add an index).
1669 // The following block of code will modify the column definition to make the column be
1670 // defined with the "NOT NULL" qualifier.
1671 if (pDb
->Dbms() == dbmsMY_SQL
)
1676 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1680 // Find the column definition that has the ColName that matches the
1681 // index column name. We need to do this to get the DB_DATA_TYPE of
1682 // the index column, as MySQL's syntax for the ALTER column requires
1684 while (!found
&& (j
< this->m_numCols
))
1686 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1694 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1695 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1701 // retcode is not used
1702 wxODBC_ERRORS retcode
;
1703 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1704 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1705 // This line is just here for debug checking of the value
1706 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1717 pDb
->RollbackTrans();
1722 // Build a CREATE INDEX statement
1723 sqlStmt
= wxT("CREATE ");
1725 sqlStmt
+= wxT("UNIQUE ");
1727 sqlStmt
+= wxT("INDEX ");
1728 sqlStmt
+= pDb
->SQLTableName(indexName
);
1729 sqlStmt
+= wxT(" ON ");
1731 sqlStmt
+= pDb
->SQLTableName(tableName
);
1732 // sqlStmt += tableName;
1733 sqlStmt
+= wxT(" (");
1735 // Append list of columns making up index
1737 for (i
= 0; i
< numIndexColumns
; i
++)
1739 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1740 // sqlStmt += pIndexDefs[i].ColName;
1742 // MySQL requires a key length on VARCHAR keys
1743 if ( pDb
->Dbms() == dbmsMY_SQL
)
1745 // Find the details on this column
1747 for ( j
= 0; j
< m_numCols
; ++j
)
1749 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1754 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1757 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1762 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1763 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1764 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1765 !(pDb
->Dbms() == dbmsPOSTGRES
))
1767 if (pIndexDefs
[i
].Ascending
)
1768 sqlStmt
+= wxT(" ASC");
1770 sqlStmt
+= wxT(" DESC");
1773 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1775 if ((i
+ 1) < numIndexColumns
)
1776 sqlStmt
+= wxT(",");
1779 // Append closing parentheses
1780 sqlStmt
+= wxT(")");
1782 pDb
->WriteSqlLog(sqlStmt
);
1784 #ifdef DBDEBUG_CONSOLE
1785 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1788 // Execute the CREATE INDEX statement
1789 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1790 if (retcode
!= SQL_SUCCESS
)
1792 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1793 pDb
->RollbackTrans();
1798 // Commit the transaction and close the cursor
1799 if (! pDb
->CommitTrans())
1801 if (! CloseCursor(hstmt
))
1804 // Index Created Successfully
1807 } // wxDbTable::CreateIndex()
1810 /********** wxDbTable::DropIndex() **********/
1811 bool wxDbTable::DropIndex(const wxString
&indexName
)
1813 // NOTE: This function returns true if the Index does not exist, but
1814 // only for identified databases. Code will need to be added
1815 // below for any other databases when those databases are defined
1816 // to handle this situation consistently
1820 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1821 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1822 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1823 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1824 pDb
->SQLTableName(tableName
.c_str()).c_str());
1825 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1826 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1827 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1828 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1829 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1830 pDb
->SQLTableName(indexName
.c_str()).c_str());
1832 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1833 pDb
->SQLTableName(indexName
.c_str()).c_str());
1835 pDb
->WriteSqlLog(sqlStmt
);
1837 #ifdef DBDEBUG_CONSOLE
1838 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1840 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1841 if (retcode
!= SQL_SUCCESS
)
1843 // Check for "Index not found" error and ignore
1844 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1845 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1847 // Check for product specific error codes
1848 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1849 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1850 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1851 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1852 (pDb
->Dbms() == dbmsMAXDB
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1853 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1854 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1855 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1856 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1859 pDb
->DispNextError();
1860 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1861 pDb
->RollbackTrans();
1868 // Commit the transaction and close the cursor
1869 if (! pDb
->CommitTrans())
1871 if (! CloseCursor(hstmt
))
1875 } // wxDbTable::DropIndex()
1878 /********** wxDbTable::SetOrderByColNums() **********/
1879 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1881 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1887 va_start(argptr
, first
); /* Initialize variable arguments. */
1888 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1890 // Make sure the passed in column number
1891 // is within the valid range of columns
1893 // Valid columns are 0 thru m_numCols-1
1894 if (colNumber
>= m_numCols
|| colNumber
< 0)
1900 if (colNumber
!= first
)
1901 tempStr
+= wxT(",");
1903 tempStr
+= colDefs
[colNumber
].ColName
;
1904 colNumber
= va_arg (argptr
, int);
1906 va_end (argptr
); /* Reset variable arguments. */
1908 SetOrderByClause(tempStr
);
1911 } // wxDbTable::SetOrderByColNums()
1914 /********** wxDbTable::Insert() **********/
1915 int wxDbTable::Insert(void)
1917 wxASSERT(!queryOnly
);
1918 if (queryOnly
|| !insertable
)
1923 // Insert the record by executing the already prepared insert statement
1925 retcode
= SQLExecute(hstmtInsert
);
1926 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1927 retcode
!= SQL_NEED_DATA
)
1929 // Check to see if integrity constraint was violated
1930 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1931 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1932 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1935 pDb
->DispNextError();
1936 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1940 if (retcode
== SQL_NEED_DATA
)
1943 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1944 while (retcode
== SQL_NEED_DATA
)
1946 // Find the parameter
1948 for (i
=0; i
< m_numCols
; i
++)
1950 if (colDefs
[i
].PtrDataObj
== pParmID
)
1952 // We found it. Store the parameter.
1953 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1954 if (retcode
!= SQL_SUCCESS
)
1956 pDb
->DispNextError();
1957 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1963 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1964 if (retcode
!= SQL_SUCCESS
&&
1965 retcode
!= SQL_SUCCESS_WITH_INFO
)
1967 // record was not inserted
1968 pDb
->DispNextError();
1969 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1975 // Record inserted into the datasource successfully
1978 } // wxDbTable::Insert()
1981 /********** wxDbTable::Update() **********/
1982 bool wxDbTable::Update(void)
1984 wxASSERT(!queryOnly
);
1990 // Build the SQL UPDATE statement
1991 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1993 pDb
->WriteSqlLog(sqlStmt
);
1995 #ifdef DBDEBUG_CONSOLE
1996 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1999 // Execute the SQL UPDATE statement
2000 return(execUpdate(sqlStmt
));
2002 } // wxDbTable::Update()
2005 /********** wxDbTable::Update(pSqlStmt) **********/
2006 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2008 wxASSERT(!queryOnly
);
2012 pDb
->WriteSqlLog(pSqlStmt
);
2014 return(execUpdate(pSqlStmt
));
2016 } // wxDbTable::Update(pSqlStmt)
2019 /********** wxDbTable::UpdateWhere() **********/
2020 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2022 wxASSERT(!queryOnly
);
2028 // Build the SQL UPDATE statement
2029 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2031 pDb
->WriteSqlLog(sqlStmt
);
2033 #ifdef DBDEBUG_CONSOLE
2034 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2037 // Execute the SQL UPDATE statement
2038 return(execUpdate(sqlStmt
));
2040 } // wxDbTable::UpdateWhere()
2043 /********** wxDbTable::Delete() **********/
2044 bool wxDbTable::Delete(void)
2046 wxASSERT(!queryOnly
);
2053 // Build the SQL DELETE statement
2054 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2056 pDb
->WriteSqlLog(sqlStmt
);
2058 // Execute the SQL DELETE statement
2059 return(execDelete(sqlStmt
));
2061 } // wxDbTable::Delete()
2064 /********** wxDbTable::DeleteWhere() **********/
2065 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2067 wxASSERT(!queryOnly
);
2074 // Build the SQL DELETE statement
2075 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2077 pDb
->WriteSqlLog(sqlStmt
);
2079 // Execute the SQL DELETE statement
2080 return(execDelete(sqlStmt
));
2082 } // wxDbTable::DeleteWhere()
2085 /********** wxDbTable::DeleteMatching() **********/
2086 bool wxDbTable::DeleteMatching(void)
2088 wxASSERT(!queryOnly
);
2095 // Build the SQL DELETE statement
2096 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2098 pDb
->WriteSqlLog(sqlStmt
);
2100 // Execute the SQL DELETE statement
2101 return(execDelete(sqlStmt
));
2103 } // wxDbTable::DeleteMatching()
2106 /********** wxDbTable::IsColNull() **********/
2107 bool wxDbTable::IsColNull(UWORD colNumber
) const
2110 This logic is just not right. It would indicate true
2111 if a numeric field were set to a value of 0.
2113 switch(colDefs[colNumber].SqlCtype)
2117 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2118 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2120 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2122 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2124 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2126 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2128 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2130 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2131 case SQL_C_TIMESTAMP:
2132 TIMESTAMP_STRUCT *pDt;
2133 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2134 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2142 return (colDefs
[colNumber
].Null
);
2143 } // wxDbTable::IsColNull()
2146 /********** wxDbTable::CanSelectForUpdate() **********/
2147 bool wxDbTable::CanSelectForUpdate(void)
2152 if (pDb
->Dbms() == dbmsMY_SQL
)
2155 if ((pDb
->Dbms() == dbmsORACLE
) ||
2156 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2161 } // wxDbTable::CanSelectForUpdate()
2164 /********** wxDbTable::CanUpdateByROWID() **********/
2165 bool wxDbTable::CanUpdateByROWID(void)
2168 * NOTE: Returning false for now until this can be debugged,
2169 * as the ROWID is not getting updated correctly
2173 if (pDb->Dbms() == dbmsORACLE)
2178 } // wxDbTable::CanUpdateByROWID()
2181 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2182 bool wxDbTable::IsCursorClosedOnCommit(void)
2184 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2189 } // wxDbTable::IsCursorClosedOnCommit()
2193 /********** wxDbTable::ClearMemberVar() **********/
2194 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2196 wxASSERT(colNumber
< m_numCols
);
2198 switch(colDefs
[colNumber
].SqlCtype
)
2204 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2205 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2208 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2211 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2215 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2218 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2221 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2224 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2226 case SQL_C_TIMESTAMP
:
2227 TIMESTAMP_STRUCT
*pDt
;
2228 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2239 pDtd
= (DATE_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2246 pDtt
= (TIME_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2254 SetColNull(colNumber
);
2255 } // wxDbTable::ClearMemberVar()
2258 /********** wxDbTable::ClearMemberVars() **********/
2259 void wxDbTable::ClearMemberVars(bool setToNull
)
2263 // Loop through the columns setting each member variable to zero
2264 for (i
=0; i
< m_numCols
; i
++)
2265 ClearMemberVar((UWORD
)i
,setToNull
);
2267 } // wxDbTable::ClearMemberVars()
2270 /********** wxDbTable::SetQueryTimeout() **********/
2271 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2273 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2274 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2275 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2276 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2277 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2278 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2279 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2280 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2282 // Completed Successfully
2285 } // wxDbTable::SetQueryTimeout()
2288 /********** wxDbTable::SetColDefs() **********/
2289 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2290 SWORD cType
, int size
, bool keyField
, bool updateable
,
2291 bool insertAllowed
, bool derivedColumn
)
2295 if (index
>= m_numCols
) // Columns numbers are zero based....
2297 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
);
2303 if (!colDefs
) // May happen if the database connection fails
2306 if (fieldName
.length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2308 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2309 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2311 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2312 fieldName
.c_str(),colDefs
[index
].ColName
);
2317 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2319 colDefs
[index
].DbDataType
= dataType
;
2320 colDefs
[index
].PtrDataObj
= pData
;
2321 colDefs
[index
].SqlCtype
= cType
;
2322 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2323 colDefs
[index
].KeyField
= keyField
;
2324 colDefs
[index
].DerivedCol
= derivedColumn
;
2325 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2328 colDefs
[index
].Updateable
= false;
2329 colDefs
[index
].InsertAllowed
= false;
2333 colDefs
[index
].Updateable
= updateable
;
2334 colDefs
[index
].InsertAllowed
= insertAllowed
;
2337 colDefs
[index
].Null
= false;
2341 } // wxDbTable::SetColDefs()
2344 /********** wxDbTable::SetColDefs() **********/
2345 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2348 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2354 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2356 for (index
= 0; index
< numCols
; index
++)
2358 // Process the fields
2359 switch (pColInfs
[index
].dbDataType
)
2361 case DB_DATA_TYPE_VARCHAR
:
2362 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2363 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2364 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2366 case DB_DATA_TYPE_MEMO
:
2367 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2368 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2369 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2371 case DB_DATA_TYPE_INTEGER
:
2372 // Can be long or short
2373 if (pColInfs
[index
].bufferSize
== sizeof(long))
2375 pColDataPtrs
[index
].PtrDataObj
= new long;
2376 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2377 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2381 pColDataPtrs
[index
].PtrDataObj
= new short;
2382 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2383 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2386 case DB_DATA_TYPE_FLOAT
:
2387 // Can be float or double
2388 if (pColInfs
[index
].bufferSize
== sizeof(float))
2390 pColDataPtrs
[index
].PtrDataObj
= new float;
2391 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2392 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2396 pColDataPtrs
[index
].PtrDataObj
= new double;
2397 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2398 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2401 case DB_DATA_TYPE_DATE
:
2402 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2403 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2404 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2406 case DB_DATA_TYPE_BLOB
:
2407 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2408 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2409 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2410 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2413 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2414 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2417 // Unable to build all the column definitions, as either one of
2418 // the calls to "new" failed above, or there was a BLOB field
2419 // to have a column definition for. If BLOBs are to be used,
2420 // the other form of ::SetColDefs() must be used, as it is impossible
2421 // to know the maximum size to create the PtrDataObj to be.
2422 delete [] pColDataPtrs
;
2428 return (pColDataPtrs
);
2430 } // wxDbTable::SetColDefs()
2433 /********** wxDbTable::SetCursor() **********/
2434 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2436 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2437 hstmt
= *hstmtDefault
;
2439 hstmt
= *hstmtActivate
;
2441 } // wxDbTable::SetCursor()
2444 /********** wxDbTable::Count(const wxString &) **********/
2445 ULONG
wxDbTable::Count(const wxString
&args
)
2451 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2452 sqlStmt
= wxT("SELECT COUNT(");
2454 sqlStmt
+= wxT(") FROM ");
2455 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2456 // sqlStmt += queryTableName;
2457 #if wxODBC_BACKWARD_COMPATABILITY
2458 if (from
&& wxStrlen(from
))
2464 // Add the where clause if one is provided
2465 #if wxODBC_BACKWARD_COMPATABILITY
2466 if (where
&& wxStrlen(where
))
2471 sqlStmt
+= wxT(" WHERE ");
2475 pDb
->WriteSqlLog(sqlStmt
);
2477 // Initialize the Count cursor if it's not already initialized
2480 hstmtCount
= GetNewCursor(false,false);
2481 wxASSERT(hstmtCount
);
2486 // Execute the SQL statement
2487 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2489 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2494 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2496 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2500 // Obtain the result
2501 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2503 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2508 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2509 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2511 // Return the record count
2514 } // wxDbTable::Count()
2517 /********** wxDbTable::Refresh() **********/
2518 bool wxDbTable::Refresh(void)
2522 // Switch to the internal cursor so any active cursors are not corrupted
2523 HSTMT currCursor
= GetCursor();
2524 hstmt
= hstmtInternal
;
2525 #if wxODBC_BACKWARD_COMPATABILITY
2526 // Save the where and order by clauses
2527 wxChar
*saveWhere
= where
;
2528 wxChar
*saveOrderBy
= orderBy
;
2530 wxString saveWhere
= where
;
2531 wxString saveOrderBy
= orderBy
;
2533 // Build a where clause to refetch the record with. Try and use the
2534 // ROWID if it's available, ow use the key fields.
2535 wxString whereClause
;
2536 whereClause
.Empty();
2538 if (CanUpdateByROWID())
2541 wxChar rowid
[wxDB_ROWID_LEN
+1];
2543 // Get the ROWID value. If not successful retreiving the ROWID,
2544 // simply fall down through the code and build the WHERE clause
2545 // based on the key fields.
2546 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2548 whereClause
+= pDb
->SQLTableName(queryTableName
);
2549 // whereClause += queryTableName;
2550 whereClause
+= wxT(".ROWID = '");
2551 whereClause
+= rowid
;
2552 whereClause
+= wxT("'");
2556 // If unable to use the ROWID, build a where clause from the keyfields
2557 if (wxStrlen(whereClause
) == 0)
2558 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2560 // Requery the record
2561 where
= whereClause
;
2566 if (result
&& !GetNext())
2569 // Switch back to original cursor
2570 SetCursor(&currCursor
);
2572 // Free the internal cursor
2573 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2574 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2576 // Restore the original where and order by clauses
2578 orderBy
= saveOrderBy
;
2582 } // wxDbTable::Refresh()
2585 /********** wxDbTable::SetColNull() **********/
2586 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2588 if (colNumber
< m_numCols
)
2590 colDefs
[colNumber
].Null
= set
;
2591 if (set
) // Blank out the values in the member variable
2592 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2594 setCbValueForColumn(colNumber
);
2601 } // wxDbTable::SetColNull()
2604 /********** wxDbTable::SetColNull() **********/
2605 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2608 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2610 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2614 if (colNumber
< m_numCols
)
2616 colDefs
[colNumber
].Null
= set
;
2617 if (set
) // Blank out the values in the member variable
2618 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2620 setCbValueForColumn(colNumber
);
2627 } // wxDbTable::SetColNull()
2630 /********** wxDbTable::GetNewCursor() **********/
2631 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2633 HSTMT
*newHSTMT
= new HSTMT
;
2638 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2640 pDb
->DispAllErrors(henv
, hdbc
);
2645 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2647 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2654 if (!bindCols(*newHSTMT
))
2662 SetCursor(newHSTMT
);
2666 } // wxDbTable::GetNewCursor()
2669 /********** wxDbTable::DeleteCursor() **********/
2670 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2674 if (!hstmtDel
) // Cursor already deleted
2678 ODBC 3.0 says to use this form
2679 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2682 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2684 pDb
->DispAllErrors(henv
, hdbc
);
2692 } // wxDbTable::DeleteCursor()
2694 //////////////////////////////////////////////////////////////
2695 // wxDbGrid support functions
2696 //////////////////////////////////////////////////////////////
2698 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2700 if (!m_hstmtGridQuery
)
2702 m_hstmtGridQuery
= GetNewCursor(false,false);
2703 if (!bindCols(*m_hstmtGridQuery
))
2707 m_rowmode
= rowmode
;
2710 case WX_ROW_MODE_QUERY
:
2711 SetCursor(m_hstmtGridQuery
);
2713 case WX_ROW_MODE_INDIVIDUAL
:
2714 SetCursor(hstmtDefault
);
2719 } // wxDbTable::SetRowMode()
2722 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2725 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2727 switch (colDefs
[colNumber
].SqlCtype
)
2730 #if defined(SQL_WCHAR)
2733 #if defined(SQL_WVARCHAR)
2739 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2743 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2747 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2750 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2753 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2755 case SQL_C_UTINYINT
:
2756 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2759 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2762 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2765 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2767 case SQL_C_TIMESTAMP
:
2768 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2771 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2778 } // wxDbTable::GetCol()
2781 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2783 //FIXME: Add proper wxDateTime support to wxVariant..
2786 SetColNull((UWORD
)colNumber
, val
.IsNull());
2790 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2791 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2792 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2794 //Returns null if invalid!
2795 if (!dateval
.ParseDate(val
.GetString()))
2796 SetColNull((UWORD
)colNumber
, true);
2799 switch (colDefs
[colNumber
].SqlCtype
)
2802 #if defined(SQL_WCHAR)
2805 #if defined(SQL_WVARCHAR)
2811 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2812 val
.GetString().c_str(),
2813 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2817 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2821 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2824 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2827 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2829 case SQL_C_UTINYINT
:
2830 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2833 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2835 //FIXME: Add proper wxDateTime support to wxVariant..
2838 DATE_STRUCT
*dataptr
=
2839 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2841 dataptr
->year
= (SWORD
)dateval
.GetYear();
2842 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2843 dataptr
->day
= (UWORD
)dateval
.GetDay();
2848 TIME_STRUCT
*dataptr
=
2849 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2851 dataptr
->hour
= dateval
.GetHour();
2852 dataptr
->minute
= dateval
.GetMinute();
2853 dataptr
->second
= dateval
.GetSecond();
2856 case SQL_C_TIMESTAMP
:
2858 TIMESTAMP_STRUCT
*dataptr
=
2859 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2860 dataptr
->year
= (SWORD
)dateval
.GetYear();
2861 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2862 dataptr
->day
= (UWORD
)dateval
.GetDay();
2864 dataptr
->hour
= dateval
.GetHour();
2865 dataptr
->minute
= dateval
.GetMinute();
2866 dataptr
->second
= dateval
.GetSecond();
2870 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2875 } // if (!val.IsNull())
2876 } // wxDbTable::SetCol()
2879 GenericKey
wxDbTable::GetKey()
2884 blk
= malloc(m_keysize
);
2885 blkptr
= (wxChar
*) blk
;
2888 for (i
=0; i
< m_numCols
; i
++)
2890 if (colDefs
[i
].KeyField
)
2892 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2893 blkptr
+= colDefs
[i
].SzDataObj
;
2897 GenericKey k
= GenericKey(blk
, m_keysize
);
2901 } // wxDbTable::GetKey()
2904 void wxDbTable::SetKey(const GenericKey
& k
)
2910 blkptr
= (wxChar
*)blk
;
2913 for (i
=0; i
< m_numCols
; i
++)
2915 if (colDefs
[i
].KeyField
)
2917 SetColNull((UWORD
)i
, false);
2918 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2919 blkptr
+= colDefs
[i
].SzDataObj
;
2922 } // wxDbTable::SetKey()
2925 #endif // wxUSE_ODBC