1 ///////////////////////////////////////////////////////////////////////////////
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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
20 #pragma implementation "dbtable.h"
23 #include "wx/wxprec.h"
29 #ifdef DBDEBUG_CONSOLE
35 #include "wx/ioswrap.h"
39 #include "wx/string.h"
40 #include "wx/object.h"
45 #include "wx/filefn.h"
53 #include "wx/dbtable.h"
56 // The HPUX preprocessor lines below were commented out on 8/20/97
57 // because macros.h currently redefines DEBUG and is unneeded.
59 // # include <macros.h>
62 # include <sys/minmax.h>
66 ULONG lastTableID
= 0;
74 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
76 while ( (*target
++ = *source
++) != '\0' && --n
)
84 /********** wxDbColDef::wxDbColDef() Constructor **********/
85 wxDbColDef::wxDbColDef()
91 bool wxDbColDef::Initialize()
94 DbDataType
= DB_DATA_TYPE_INTEGER
;
95 SqlCtype
= SQL_C_LONG
;
100 InsertAllowed
= false;
106 } // wxDbColDef::Initialize()
109 /********** wxDbTable::wxDbTable() Constructor **********/
110 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
111 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
113 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
115 } // wxDbTable::wxDbTable()
118 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
119 #if WXWIN_COMPATIBILITY_2_4
120 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
121 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
123 wxString tempQryTblName
;
124 tempQryTblName
= qryTblName
;
125 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
127 } // wxDbTable::wxDbTable()
128 #endif // WXWIN_COMPATIBILITY_2_4
131 /********** wxDbTable::~wxDbTable() **********/
132 wxDbTable::~wxDbTable()
135 } // wxDbTable::~wxDbTable()
138 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
139 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
141 // Initializing member variables
142 pDb
= pwxDb
; // Pointer to the wxDb object
146 m_hstmtGridQuery
= 0;
147 hstmtDefault
= 0; // Initialized below
148 hstmtCount
= 0; // Initialized first time it is needed
155 m_numCols
= numColumns
; // Number of columns in the table
156 where
.Empty(); // Where clause
157 orderBy
.Empty(); // Order By clause
158 from
.Empty(); // From clause
159 selectForUpdate
= false; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
164 queryTableName
.Empty();
166 wxASSERT(tblName
.Length());
172 tableName
= tblName
; // Table Name
173 if ((pDb
->Dbms() == dbmsORACLE
) ||
174 (pDb
->Dbms() == dbmsFIREBIRD
) ||
175 (pDb
->Dbms() == dbmsINTERBASE
))
176 tableName
= tableName
.Upper();
178 if (tblPath
.Length())
179 tablePath
= tblPath
; // Table Path - used for dBase files
183 if (qryTblName
.Length()) // Name of the table/view to query
184 queryTableName
= qryTblName
;
186 queryTableName
= tblName
;
188 if ((pDb
->Dbms() == dbmsORACLE
) ||
189 (pDb
->Dbms() == dbmsFIREBIRD
) ||
190 (pDb
->Dbms() == dbmsINTERBASE
))
191 queryTableName
= queryTableName
.Upper();
193 pDb
->incrementTableCount();
196 tableID
= ++lastTableID
;
197 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
200 wxTablesInUse
*tableInUse
;
201 tableInUse
= new wxTablesInUse();
202 tableInUse
->tableName
= tblName
;
203 tableInUse
->tableID
= tableID
;
204 tableInUse
->pDb
= pDb
;
205 TablesInUse
.Append(tableInUse
);
210 // Grab the HENV and HDBC from the wxDb object
211 henv
= pDb
->GetHENV();
212 hdbc
= pDb
->GetHDBC();
214 // Allocate space for column definitions
216 colDefs
= new wxDbColDef
[m_numCols
]; // Points to the first column definition
218 // Allocate statement handles for the table
221 // Allocate a separate statement handle for performing inserts
222 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
223 pDb
->DispAllErrors(henv
, hdbc
);
224 // Allocate a separate statement handle for performing deletes
225 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
226 pDb
->DispAllErrors(henv
, hdbc
);
227 // Allocate a separate statement handle for performing updates
228 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
229 pDb
->DispAllErrors(henv
, hdbc
);
231 // Allocate a separate statement handle for internal use
232 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
233 pDb
->DispAllErrors(henv
, hdbc
);
235 // Set the cursor type for the statement handles
236 cursorType
= SQL_CURSOR_STATIC
;
238 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
240 // Check to see if cursor type is supported
241 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
242 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
244 // Datasource does not support static cursors. Driver
245 // will substitute a cursor type. Call SQLGetStmtOption()
246 // to determine which cursor type was selected.
247 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
248 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
249 #ifdef DBDEBUG_CONSOLE
250 cout
<< wxT("Static cursor changed to: ");
253 case SQL_CURSOR_FORWARD_ONLY
:
254 cout
<< wxT("Forward Only");
256 case SQL_CURSOR_STATIC
:
257 cout
<< wxT("Static");
259 case SQL_CURSOR_KEYSET_DRIVEN
:
260 cout
<< wxT("Keyset Driven");
262 case SQL_CURSOR_DYNAMIC
:
263 cout
<< wxT("Dynamic");
266 cout
<< endl
<< endl
;
269 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
271 // Force the use of a forward only cursor...
272 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
273 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
275 // Should never happen
276 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
283 pDb
->DispNextError();
284 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
287 #ifdef DBDEBUG_CONSOLE
289 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
294 // Set the cursor type for the INSERT statement handle
295 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
296 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
297 // Set the cursor type for the DELETE statement handle
298 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
299 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
300 // Set the cursor type for the UPDATE statement handle
301 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
302 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
305 // Make the default cursor the active cursor
306 hstmtDefault
= GetNewCursor(false,false);
307 wxASSERT(hstmtDefault
);
308 hstmt
= *hstmtDefault
;
312 } // wxDbTable::initialize()
315 void wxDbTable::cleanup()
320 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
329 wxList::compatibility_iterator pNode
;
330 pNode
= TablesInUse
.GetFirst();
331 while (pNode
&& !found
)
333 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
336 delete (wxTablesInUse
*)pNode
->GetData();
337 TablesInUse
.Erase(pNode
);
340 pNode
= pNode
->GetNext();
345 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
346 wxLogDebug (msg
,wxT("NOTICE..."));
351 // Decrement the wxDb table count
353 pDb
->decrementTableCount();
355 // Delete memory allocated for column definitions
359 // Free statement handles
365 ODBC 3.0 says to use this form
366 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
368 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
369 pDb
->DispAllErrors(henv
, hdbc
);
375 ODBC 3.0 says to use this form
376 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
378 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
379 pDb
->DispAllErrors(henv
, hdbc
);
385 ODBC 3.0 says to use this form
386 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
388 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
389 pDb
->DispAllErrors(henv
, hdbc
);
395 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
396 pDb
->DispAllErrors(henv
, hdbc
);
399 // Delete dynamically allocated cursors
401 DeleteCursor(hstmtDefault
);
404 DeleteCursor(hstmtCount
);
406 if (m_hstmtGridQuery
)
407 DeleteCursor(m_hstmtGridQuery
);
409 } // wxDbTable::cleanup()
412 /***************************** PRIVATE FUNCTIONS *****************************/
415 void wxDbTable::setCbValueForColumn(int columnIndex
)
417 switch(colDefs
[columnIndex
].DbDataType
)
419 case DB_DATA_TYPE_VARCHAR
:
420 if (colDefs
[columnIndex
].Null
)
421 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
423 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
425 case DB_DATA_TYPE_INTEGER
:
426 if (colDefs
[columnIndex
].Null
)
427 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
429 colDefs
[columnIndex
].CbValue
= 0;
431 case DB_DATA_TYPE_FLOAT
:
432 if (colDefs
[columnIndex
].Null
)
433 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
435 colDefs
[columnIndex
].CbValue
= 0;
437 case DB_DATA_TYPE_DATE
:
438 if (colDefs
[columnIndex
].Null
)
439 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
441 colDefs
[columnIndex
].CbValue
= 0;
443 case DB_DATA_TYPE_BLOB
:
444 if (colDefs
[columnIndex
].Null
)
445 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
447 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_WXCHAR
)
448 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
450 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
455 /********** wxDbTable::bindParams() **********/
456 bool wxDbTable::bindParams(bool forUpdate
)
458 wxASSERT(!queryOnly
);
463 SDWORD precision
= 0;
466 // Bind each column of the table that should be bound
467 // to a parameter marker
471 for (i
=0, colNumber
=1; i
< m_numCols
; i
++)
475 if (!colDefs
[i
].Updateable
)
480 if (!colDefs
[i
].InsertAllowed
)
484 switch(colDefs
[i
].DbDataType
)
486 case DB_DATA_TYPE_VARCHAR
:
487 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
488 precision
= colDefs
[i
].SzDataObj
;
491 case DB_DATA_TYPE_INTEGER
:
492 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
493 precision
= pDb
->GetTypeInfInteger().Precision
;
496 case DB_DATA_TYPE_FLOAT
:
497 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
498 precision
= pDb
->GetTypeInfFloat().Precision
;
499 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
500 // SQL Sybase Anywhere v5.5 returned a negative number for the
501 // MaxScale. This caused ODBC to kick out an error on ibscale.
502 // I check for this here and set the scale = precision.
504 // scale = (short) precision;
506 case DB_DATA_TYPE_DATE
:
507 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
508 precision
= pDb
->GetTypeInfDate().Precision
;
511 case DB_DATA_TYPE_BLOB
:
512 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
513 precision
= colDefs
[i
].SzDataObj
;
518 setCbValueForColumn(i
);
522 if (SQLBindParameter(hstmtUpdate
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
523 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
524 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
526 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
531 if (SQLBindParameter(hstmtInsert
, colNumber
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
532 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
533 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
535 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
540 // Completed successfully
543 } // wxDbTable::bindParams()
546 /********** wxDbTable::bindInsertParams() **********/
547 bool wxDbTable::bindInsertParams(void)
549 return bindParams(false);
550 } // wxDbTable::bindInsertParams()
553 /********** wxDbTable::bindUpdateParams() **********/
554 bool wxDbTable::bindUpdateParams(void)
556 return bindParams(true);
557 } // wxDbTable::bindUpdateParams()
560 /********** wxDbTable::bindCols() **********/
561 bool wxDbTable::bindCols(HSTMT cursor
)
565 // Bind each column of the table to a memory address for fetching data
567 for (i
= 0; i
< m_numCols
; i
++)
569 cb
= colDefs
[i
].CbValue
;
570 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
571 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
572 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
575 // Completed successfully
578 } // wxDbTable::bindCols()
581 /********** wxDbTable::getRec() **********/
582 bool wxDbTable::getRec(UWORD fetchType
)
586 if (!pDb
->FwdOnlyCursors())
588 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
592 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
593 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
595 if (retcode
== SQL_NO_DATA_FOUND
)
598 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
602 // Set the Null member variable to indicate the Null state
603 // of each column just read in.
605 for (i
= 0; i
< m_numCols
; i
++)
606 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
611 // Fetch the next record from the record set
612 retcode
= SQLFetch(hstmt
);
613 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
615 if (retcode
== SQL_NO_DATA_FOUND
)
618 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
622 // Set the Null member variable to indicate the Null state
623 // of each column just read in.
625 for (i
= 0; i
< m_numCols
; i
++)
626 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
630 // Completed successfully
633 } // wxDbTable::getRec()
636 /********** wxDbTable::execDelete() **********/
637 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
641 // Execute the DELETE statement
642 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
644 if (retcode
== SQL_SUCCESS
||
645 retcode
== SQL_NO_DATA_FOUND
||
646 retcode
== SQL_SUCCESS_WITH_INFO
)
648 // Record deleted successfully
652 // Problem deleting record
653 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
655 } // wxDbTable::execDelete()
658 /********** wxDbTable::execUpdate() **********/
659 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
663 // Execute the UPDATE statement
664 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
666 if (retcode
== SQL_SUCCESS
||
667 retcode
== SQL_NO_DATA_FOUND
||
668 retcode
== SQL_SUCCESS_WITH_INFO
)
670 // Record updated successfully
673 else if (retcode
== SQL_NEED_DATA
)
676 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
677 while (retcode
== SQL_NEED_DATA
)
679 // Find the parameter
681 for (i
=0; i
< m_numCols
; i
++)
683 if (colDefs
[i
].PtrDataObj
== pParmID
)
685 // We found it. Store the parameter.
686 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
687 if (retcode
!= SQL_SUCCESS
)
689 pDb
->DispNextError();
690 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
695 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
697 if (retcode
== SQL_SUCCESS
||
698 retcode
== SQL_NO_DATA_FOUND
||
699 retcode
== SQL_SUCCESS_WITH_INFO
)
701 // Record updated successfully
706 // Problem updating record
707 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
709 } // wxDbTable::execUpdate()
712 /********** wxDbTable::query() **********/
713 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
718 // The user may wish to select for update, but the DBMS may not be capable
719 selectForUpdate
= CanSelectForUpdate();
721 selectForUpdate
= false;
723 // Set the SQL SELECT string
724 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
725 { // so generate a select statement.
726 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
727 pDb
->WriteSqlLog(sqlStmt
);
730 // Make sure the cursor is closed first
731 if (!CloseCursor(hstmt
))
734 // Execute the SQL SELECT statement
736 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
737 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
738 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
740 // Completed successfully
743 } // wxDbTable::query()
746 /***************************** PUBLIC FUNCTIONS *****************************/
749 /********** wxDbTable::Open() **********/
750 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
759 // Calculate the maximum size of the concatenated
760 // keys for use with wxDbGrid
762 for (i
=0; i
< m_numCols
; i
++)
764 if (colDefs
[i
].KeyField
)
766 m_keysize
+= colDefs
[i
].SzDataObj
;
773 if (checkTableExists
)
775 if (pDb
->Dbms() == dbmsPOSTGRES
)
776 exists
= pDb
->TableExists(tableName
, NULL
, tablePath
);
778 exists
= pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
);
781 // Verify that the table exists in the database
784 s
= wxT("Table/view does not exist in the database");
785 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
786 s
+= wxT(", or you have no permissions.\n");
790 else if (checkPrivileges
)
792 // Verify the user has rights to access the table.
793 bool hasPrivs
wxDUMMY_INITIALIZE(true);
795 if (pDb
->Dbms() == dbmsPOSTGRES
)
796 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), NULL
, tablePath
);
798 hasPrivs
= pDb
->TablePrivileges(tableName
, wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
);
801 s
= wxT("Connecting user does not have sufficient privileges to access this table.\n");
808 if (!tablePath
.empty())
809 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
811 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
814 pDb
->LogError(p
.GetData());
819 // Bind the member variables for field exchange between
820 // the wxDbTable object and the ODBC record.
823 if (!bindInsertParams()) // Inserts
826 if (!bindUpdateParams()) // Updates
830 if (!bindCols(*hstmtDefault
)) // Selects
833 if (!bindCols(hstmtInternal
)) // Internal use only
837 * Do NOT bind the hstmtCount cursor!!!
840 // Build an insert statement using parameter markers
841 if (!queryOnly
&& m_numCols
> 0)
843 bool needComma
= false;
844 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
845 pDb
->SQLTableName(tableName
.c_str()).c_str());
846 for (i
= 0; i
< m_numCols
; i
++)
848 if (! colDefs
[i
].InsertAllowed
)
852 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
856 sqlStmt
+= wxT(") VALUES (");
858 int insertableCount
= 0;
860 for (i
= 0; i
< m_numCols
; i
++)
862 if (! colDefs
[i
].InsertAllowed
)
872 // Prepare the insert statement for execution
875 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
876 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
882 // Completed successfully
885 } // wxDbTable::Open()
888 /********** wxDbTable::Query() **********/
889 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
892 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
894 } // wxDbTable::Query()
897 /********** wxDbTable::QueryBySqlStmt() **********/
898 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
900 pDb
->WriteSqlLog(pSqlStmt
);
902 return(query(DB_SELECT_STATEMENT
, false, false, pSqlStmt
));
904 } // wxDbTable::QueryBySqlStmt()
907 /********** wxDbTable::QueryMatching() **********/
908 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
911 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
913 } // wxDbTable::QueryMatching()
916 /********** wxDbTable::QueryOnKeyFields() **********/
917 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
920 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
922 } // wxDbTable::QueryOnKeyFields()
925 /********** wxDbTable::GetPrev() **********/
926 bool wxDbTable::GetPrev(void)
928 if (pDb
->FwdOnlyCursors())
930 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
934 return(getRec(SQL_FETCH_PRIOR
));
936 } // wxDbTable::GetPrev()
939 /********** wxDbTable::operator-- **********/
940 bool wxDbTable::operator--(int)
942 if (pDb
->FwdOnlyCursors())
944 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
948 return(getRec(SQL_FETCH_PRIOR
));
950 } // wxDbTable::operator--
953 /********** wxDbTable::GetFirst() **********/
954 bool wxDbTable::GetFirst(void)
956 if (pDb
->FwdOnlyCursors())
958 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
962 return(getRec(SQL_FETCH_FIRST
));
964 } // wxDbTable::GetFirst()
967 /********** wxDbTable::GetLast() **********/
968 bool wxDbTable::GetLast(void)
970 if (pDb
->FwdOnlyCursors())
972 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
976 return(getRec(SQL_FETCH_LAST
));
978 } // wxDbTable::GetLast()
981 /********** wxDbTable::BuildDeleteStmt() **********/
982 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
984 wxASSERT(!queryOnly
);
988 wxString whereClause
;
992 // Handle the case of DeleteWhere() and the where clause is blank. It should
993 // delete all records from the database in this case.
994 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
996 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
997 pDb
->SQLTableName(tableName
.c_str()).c_str());
1001 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
1002 pDb
->SQLTableName(tableName
.c_str()).c_str());
1004 // Append the WHERE clause to the SQL DELETE statement
1007 case DB_DEL_KEYFIELDS
:
1008 // If the datasource supports the ROWID column, build
1009 // the where on ROWID for efficiency purposes.
1010 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1011 if (CanUpdateByROWID())
1014 wxChar rowid
[wxDB_ROWID_LEN
+1];
1016 // Get the ROWID value. If not successful retreiving the ROWID,
1017 // simply fall down through the code and build the WHERE clause
1018 // based on the key fields.
1019 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1021 pSqlStmt
+= wxT("ROWID = '");
1023 pSqlStmt
+= wxT("'");
1027 // Unable to delete by ROWID, so build a WHERE
1028 // clause based on the keyfields.
1029 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1030 pSqlStmt
+= whereClause
;
1033 pSqlStmt
+= pWhereClause
;
1035 case DB_DEL_MATCHING
:
1036 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1037 pSqlStmt
+= whereClause
;
1041 } // BuildDeleteStmt()
1044 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1045 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1047 wxString tempSqlStmt
;
1048 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1049 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1050 } // wxDbTable::BuildDeleteStmt()
1053 /********** wxDbTable::BuildSelectStmt() **********/
1054 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1056 wxString whereClause
;
1057 whereClause
.Empty();
1059 // Build a select statement to query the database
1060 pSqlStmt
= wxT("SELECT ");
1062 // SELECT DISTINCT values only?
1064 pSqlStmt
+= wxT("DISTINCT ");
1066 // Was a FROM clause specified to join tables to the base table?
1067 // Available for ::Query() only!!!
1068 bool appendFromClause
= false;
1069 #if wxODBC_BACKWARD_COMPATABILITY
1070 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1071 appendFromClause
= true;
1073 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1074 appendFromClause
= true;
1077 // Add the column list
1080 for (i
= 0; i
< m_numCols
; i
++)
1082 tStr
= colDefs
[i
].ColName
;
1083 // If joining tables, the base table column names must be qualified to avoid ambiguity
1084 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1086 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1087 pSqlStmt
+= wxT(".");
1089 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1090 if (i
+ 1 < m_numCols
)
1091 pSqlStmt
+= wxT(",");
1094 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1095 // the ROWID if querying distinct records. The rowid will always be unique.
1096 if (!distinct
&& CanUpdateByROWID())
1098 // If joining tables, the base table column names must be qualified to avoid ambiguity
1099 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1101 pSqlStmt
+= wxT(",");
1102 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1103 pSqlStmt
+= wxT(".ROWID");
1106 pSqlStmt
+= wxT(",ROWID");
1109 // Append the FROM tablename portion
1110 pSqlStmt
+= wxT(" FROM ");
1111 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1112 // pSqlStmt += queryTableName;
1114 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1115 // The HOLDLOCK keyword follows the table name in the from clause.
1116 // Each table in the from clause must specify HOLDLOCK or
1117 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1118 // is parsed but ignored in SYBASE Transact-SQL.
1119 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1120 pSqlStmt
+= wxT(" HOLDLOCK");
1122 if (appendFromClause
)
1125 // Append the WHERE clause. Either append the where clause for the class
1126 // or build a where clause. The typeOfSelect determines this.
1127 switch(typeOfSelect
)
1129 case DB_SELECT_WHERE
:
1130 #if wxODBC_BACKWARD_COMPATABILITY
1131 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1133 if (where
.Length()) // May not want a where clause!!!
1136 pSqlStmt
+= wxT(" WHERE ");
1140 case DB_SELECT_KEYFIELDS
:
1141 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1142 if (whereClause
.Length())
1144 pSqlStmt
+= wxT(" WHERE ");
1145 pSqlStmt
+= whereClause
;
1148 case DB_SELECT_MATCHING
:
1149 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1150 if (whereClause
.Length())
1152 pSqlStmt
+= wxT(" WHERE ");
1153 pSqlStmt
+= whereClause
;
1158 // Append the ORDER BY clause
1159 #if wxODBC_BACKWARD_COMPATABILITY
1160 if (orderBy
&& wxStrlen(orderBy
))
1162 if (orderBy
.Length())
1165 pSqlStmt
+= wxT(" ORDER BY ");
1166 pSqlStmt
+= orderBy
;
1169 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1170 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1171 // HOLDLOCK for Sybase.
1172 if (selectForUpdate
&& CanSelectForUpdate())
1173 pSqlStmt
+= wxT(" FOR UPDATE");
1175 } // wxDbTable::BuildSelectStmt()
1178 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1179 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1181 wxString tempSqlStmt
;
1182 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1183 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1184 } // wxDbTable::BuildSelectStmt()
1187 /********** wxDbTable::BuildUpdateStmt() **********/
1188 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1190 wxASSERT(!queryOnly
);
1194 wxString whereClause
;
1195 whereClause
.Empty();
1197 bool firstColumn
= true;
1199 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1200 pDb
->SQLTableName(tableName
.c_str()).c_str());
1202 // Append a list of columns to be updated
1204 for (i
= 0; i
< m_numCols
; i
++)
1206 // Only append Updateable columns
1207 if (colDefs
[i
].Updateable
)
1210 pSqlStmt
+= wxT(",");
1212 firstColumn
= false;
1214 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1215 // pSqlStmt += colDefs[i].ColName;
1216 pSqlStmt
+= wxT(" = ?");
1220 // Append the WHERE clause to the SQL UPDATE statement
1221 pSqlStmt
+= wxT(" WHERE ");
1222 switch(typeOfUpdate
)
1224 case DB_UPD_KEYFIELDS
:
1225 // If the datasource supports the ROWID column, build
1226 // the where on ROWID for efficiency purposes.
1227 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1228 if (CanUpdateByROWID())
1231 wxChar rowid
[wxDB_ROWID_LEN
+1];
1233 // Get the ROWID value. If not successful retreiving the ROWID,
1234 // simply fall down through the code and build the WHERE clause
1235 // based on the key fields.
1236 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
1238 pSqlStmt
+= wxT("ROWID = '");
1240 pSqlStmt
+= wxT("'");
1244 // Unable to delete by ROWID, so build a WHERE
1245 // clause based on the keyfields.
1246 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1247 pSqlStmt
+= whereClause
;
1250 pSqlStmt
+= pWhereClause
;
1253 } // BuildUpdateStmt()
1256 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1257 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpdate
, const wxString
&pWhereClause
)
1259 wxString tempSqlStmt
;
1260 BuildUpdateStmt(tempSqlStmt
, typeOfUpdate
, pWhereClause
);
1261 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1262 } // BuildUpdateStmt()
1265 /********** wxDbTable::BuildWhereClause() **********/
1266 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1267 const wxString
&qualTableName
, bool useLikeComparison
)
1269 * Note: BuildWhereClause() currently ignores timestamp columns.
1270 * They are not included as part of the where clause.
1273 bool moreThanOneColumn
= false;
1276 // Loop through the columns building a where clause as you go
1278 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
1280 // Determine if this column should be included in the WHERE clause
1281 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNumber
].KeyField
) ||
1282 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull((UWORD
)colNumber
))))
1284 // Skip over timestamp columns
1285 if (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
)
1287 // If there is more than 1 column, join them with the keyword "AND"
1288 if (moreThanOneColumn
)
1289 pWhereClause
+= wxT(" AND ");
1291 moreThanOneColumn
= true;
1293 // Concatenate where phrase for the column
1294 wxString tStr
= colDefs
[colNumber
].ColName
;
1296 if (qualTableName
.Length() && tStr
.Find(wxT('.')) == wxNOT_FOUND
)
1298 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1299 pWhereClause
+= wxT(".");
1301 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNumber
].ColName
);
1303 if (useLikeComparison
&& (colDefs
[colNumber
].SqlCtype
== SQL_C_WXCHAR
))
1304 pWhereClause
+= wxT(" LIKE ");
1306 pWhereClause
+= wxT(" = ");
1308 switch(colDefs
[colNumber
].SqlCtype
)
1314 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
1315 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
);
1319 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNumber
].PtrDataObj
));
1322 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNumber
].PtrDataObj
));
1326 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1329 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
));
1332 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
));
1335 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
));
1340 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1341 colNumber
,colDefs
[colNumber
].ColName
);
1342 wxFAIL_MSG(strMsg
.c_str());
1346 pWhereClause
+= colValue
;
1349 } // wxDbTable::BuildWhereClause()
1352 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1353 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1354 const wxString
&qualTableName
, bool useLikeComparison
)
1356 wxString tempSqlStmt
;
1357 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1358 wxStrcpy(pWhereClause
, tempSqlStmt
);
1359 } // wxDbTable::BuildWhereClause()
1362 /********** wxDbTable::GetRowNum() **********/
1363 UWORD
wxDbTable::GetRowNum(void)
1367 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1369 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1373 // Completed successfully
1374 return((UWORD
) rowNum
);
1376 } // wxDbTable::GetRowNum()
1379 /********** wxDbTable::CloseCursor() **********/
1380 bool wxDbTable::CloseCursor(HSTMT cursor
)
1382 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1383 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1385 // Completed successfully
1388 } // wxDbTable::CloseCursor()
1391 /********** wxDbTable::CreateTable() **********/
1392 bool wxDbTable::CreateTable(bool attemptDrop
)
1400 #ifdef DBDEBUG_CONSOLE
1401 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1405 if (attemptDrop
&& !DropTable())
1409 #ifdef DBDEBUG_CONSOLE
1410 for (i
= 0; i
< m_numCols
; i
++)
1412 // Exclude derived columns since they are NOT part of the base table
1413 if (colDefs
[i
].DerivedCol
)
1415 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1416 switch(colDefs
[i
].DbDataType
)
1418 case DB_DATA_TYPE_VARCHAR
:
1419 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)) << wxT(")");
1421 case DB_DATA_TYPE_INTEGER
:
1422 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1424 case DB_DATA_TYPE_FLOAT
:
1425 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1427 case DB_DATA_TYPE_DATE
:
1428 cout
<< pDb
->GetTypeInfDate().TypeName
;
1430 case DB_DATA_TYPE_BLOB
:
1431 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1438 // Build a CREATE TABLE string from the colDefs structure.
1439 bool needComma
= false;
1441 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1442 pDb
->SQLTableName(tableName
.c_str()).c_str());
1444 for (i
= 0; i
< m_numCols
; i
++)
1446 // Exclude derived columns since they are NOT part of the base table
1447 if (colDefs
[i
].DerivedCol
)
1451 sqlStmt
+= wxT(",");
1453 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1454 // sqlStmt += colDefs[i].ColName;
1455 sqlStmt
+= wxT(" ");
1457 switch(colDefs
[i
].DbDataType
)
1459 case DB_DATA_TYPE_VARCHAR
:
1460 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1462 case DB_DATA_TYPE_INTEGER
:
1463 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1465 case DB_DATA_TYPE_FLOAT
:
1466 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1468 case DB_DATA_TYPE_DATE
:
1469 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1471 case DB_DATA_TYPE_BLOB
:
1472 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1475 // For varchars, append the size of the string
1476 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1477 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1478 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1481 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1485 if (pDb
->Dbms() == dbmsDB2
||
1486 pDb
->Dbms() == dbmsMY_SQL
||
1487 pDb
->Dbms() == dbmsSYBASE_ASE
||
1488 pDb
->Dbms() == dbmsINTERBASE
||
1489 pDb
->Dbms() == dbmsFIREBIRD
||
1490 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1492 if (colDefs
[i
].KeyField
)
1494 sqlStmt
+= wxT(" NOT NULL");
1500 // If there is a primary key defined, include it in the create statement
1501 for (i
= j
= 0; i
< m_numCols
; i
++)
1503 if (colDefs
[i
].KeyField
)
1509 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1510 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1512 switch (pDb
->Dbms())
1516 case dbmsSYBASE_ASA
:
1517 case dbmsSYBASE_ASE
:
1521 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1522 sqlStmt
+= wxT(",PRIMARY KEY (");
1527 sqlStmt
+= wxT(",CONSTRAINT ");
1528 // DB2 is limited to 18 characters for index names
1529 if (pDb
->Dbms() == dbmsDB2
)
1531 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."));
1532 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1533 // sqlStmt += tableName.substr(0, 13);
1536 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1537 // sqlStmt += tableName;
1539 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1544 // List column name(s) of column(s) comprising the primary key
1545 for (i
= j
= 0; i
< m_numCols
; i
++)
1547 if (colDefs
[i
].KeyField
)
1549 if (j
++) // Multi part key, comma separate names
1550 sqlStmt
+= wxT(",");
1551 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1553 if (pDb
->Dbms() == dbmsMY_SQL
&&
1554 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1557 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1562 sqlStmt
+= wxT(")");
1564 if (pDb
->Dbms() == dbmsINFORMIX
||
1565 pDb
->Dbms() == dbmsSYBASE_ASA
||
1566 pDb
->Dbms() == dbmsSYBASE_ASE
)
1568 sqlStmt
+= wxT(" CONSTRAINT ");
1569 sqlStmt
+= pDb
->SQLTableName(tableName
);
1570 // sqlStmt += tableName;
1571 sqlStmt
+= wxT("_PIDX");
1574 // Append the closing parentheses for the create table statement
1575 sqlStmt
+= wxT(")");
1577 pDb
->WriteSqlLog(sqlStmt
);
1579 #ifdef DBDEBUG_CONSOLE
1580 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1583 // Execute the CREATE TABLE statement
1584 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1585 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1587 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1588 pDb
->RollbackTrans();
1593 // Commit the transaction and close the cursor
1594 if (!pDb
->CommitTrans())
1596 if (!CloseCursor(hstmt
))
1599 // Database table created successfully
1602 } // wxDbTable::CreateTable()
1605 /********** wxDbTable::DropTable() **********/
1606 bool wxDbTable::DropTable()
1608 // NOTE: This function returns true if the Table does not exist, but
1609 // only for identified databases. Code will need to be added
1610 // below for any other databases when those databases are defined
1611 // to handle this situation consistently
1615 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1616 pDb
->SQLTableName(tableName
.c_str()).c_str());
1618 pDb
->WriteSqlLog(sqlStmt
);
1620 #ifdef DBDEBUG_CONSOLE
1621 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1624 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1625 if (retcode
!= SQL_SUCCESS
)
1627 // Check for "Base table not found" error and ignore
1628 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1629 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1630 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1632 // Check for product specific error codes
1633 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1634 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1635 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1636 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1638 pDb
->DispNextError();
1639 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1640 pDb
->RollbackTrans();
1641 // CloseCursor(hstmt);
1647 // Commit the transaction and close the cursor
1648 if (! pDb
->CommitTrans())
1650 if (! CloseCursor(hstmt
))
1654 } // wxDbTable::DropTable()
1657 /********** wxDbTable::CreateIndex() **********/
1658 bool wxDbTable::CreateIndex(const wxString
&indexName
, bool unique
, UWORD numIndexColumns
,
1659 wxDbIdxDef
*pIndexDefs
, bool attemptDrop
)
1663 // Drop the index first
1664 if (attemptDrop
&& !DropIndex(indexName
))
1667 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1668 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1669 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1670 // table was created, then months later you determine that an additional index while
1671 // give better performance, so you want to add an index).
1673 // The following block of code will modify the column definition to make the column be
1674 // defined with the "NOT NULL" qualifier.
1675 if (pDb
->Dbms() == dbmsMY_SQL
)
1680 for (i
= 0; i
< numIndexColumns
&& ok
; i
++)
1684 // Find the column definition that has the ColName that matches the
1685 // index column name. We need to do this to get the DB_DATA_TYPE of
1686 // the index column, as MySQL's syntax for the ALTER column requires
1688 while (!found
&& (j
< this->m_numCols
))
1690 if (wxStrcmp(colDefs
[j
].ColName
,pIndexDefs
[i
].ColName
) == 0)
1698 ok
= pDb
->ModifyColumn(tableName
, pIndexDefs
[i
].ColName
,
1699 colDefs
[j
].DbDataType
, (int)(colDefs
[j
].SzDataObj
/ sizeof(wxChar
)),
1705 // retcode is not used
1706 wxODBC_ERRORS retcode
;
1707 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1708 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1709 // This line is just here for debug checking of the value
1710 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1721 pDb
->RollbackTrans();
1726 // Build a CREATE INDEX statement
1727 sqlStmt
= wxT("CREATE ");
1729 sqlStmt
+= wxT("UNIQUE ");
1731 sqlStmt
+= wxT("INDEX ");
1732 sqlStmt
+= pDb
->SQLTableName(indexName
);
1733 sqlStmt
+= wxT(" ON ");
1735 sqlStmt
+= pDb
->SQLTableName(tableName
);
1736 // sqlStmt += tableName;
1737 sqlStmt
+= wxT(" (");
1739 // Append list of columns making up index
1741 for (i
= 0; i
< numIndexColumns
; i
++)
1743 sqlStmt
+= pDb
->SQLColumnName(pIndexDefs
[i
].ColName
);
1744 // sqlStmt += pIndexDefs[i].ColName;
1746 // MySQL requires a key length on VARCHAR keys
1747 if ( pDb
->Dbms() == dbmsMY_SQL
)
1749 // Find the details on this column
1751 for ( j
= 0; j
< m_numCols
; ++j
)
1753 if ( wxStrcmp( pIndexDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1758 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1761 s
.Printf(wxT("(%d)"), (int)(colDefs
[i
].SzDataObj
/ sizeof(wxChar
)));
1766 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1767 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1768 !(pDb
->Dbms() == dbmsFIREBIRD
) &&
1769 !(pDb
->Dbms() == dbmsPOSTGRES
))
1771 if (pIndexDefs
[i
].Ascending
)
1772 sqlStmt
+= wxT(" ASC");
1774 sqlStmt
+= wxT(" DESC");
1777 wxASSERT_MSG(pIndexDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1779 if ((i
+ 1) < numIndexColumns
)
1780 sqlStmt
+= wxT(",");
1783 // Append closing parentheses
1784 sqlStmt
+= wxT(")");
1786 pDb
->WriteSqlLog(sqlStmt
);
1788 #ifdef DBDEBUG_CONSOLE
1789 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1792 // Execute the CREATE INDEX statement
1793 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1794 if (retcode
!= SQL_SUCCESS
)
1796 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1797 pDb
->RollbackTrans();
1802 // Commit the transaction and close the cursor
1803 if (! pDb
->CommitTrans())
1805 if (! CloseCursor(hstmt
))
1808 // Index Created Successfully
1811 } // wxDbTable::CreateIndex()
1814 /********** wxDbTable::DropIndex() **********/
1815 bool wxDbTable::DropIndex(const wxString
&indexName
)
1817 // NOTE: This function returns true if the Index does not exist, but
1818 // only for identified databases. Code will need to be added
1819 // below for any other databases when those databases are defined
1820 // to handle this situation consistently
1824 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1825 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1826 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1827 pDb
->SQLTableName(indexName
.c_str()).c_str(),
1828 pDb
->SQLTableName(tableName
.c_str()).c_str());
1829 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1830 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1831 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1832 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1833 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1834 pDb
->SQLTableName(indexName
.c_str()).c_str());
1836 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1837 pDb
->SQLTableName(indexName
.c_str()).c_str());
1839 pDb
->WriteSqlLog(sqlStmt
);
1841 #ifdef DBDEBUG_CONSOLE
1842 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1844 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1845 if (retcode
!= SQL_SUCCESS
)
1847 // Check for "Index not found" error and ignore
1848 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1849 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1851 // Check for product specific error codes
1852 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1853 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1854 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1855 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1856 (pDb
->Dbms() == dbmsFIREBIRD
&& !wxStrcmp(pDb
->sqlState
,wxT("HY000"))) ||
1857 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1858 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1859 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1862 pDb
->DispNextError();
1863 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1864 pDb
->RollbackTrans();
1871 // Commit the transaction and close the cursor
1872 if (! pDb
->CommitTrans())
1874 if (! CloseCursor(hstmt
))
1878 } // wxDbTable::DropIndex()
1881 /********** wxDbTable::SetOrderByColNums() **********/
1882 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1884 int colNumber
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1890 va_start(argptr
, first
); /* Initialize variable arguments. */
1891 while (!abort
&& (colNumber
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1893 // Make sure the passed in column number
1894 // is within the valid range of columns
1896 // Valid columns are 0 thru m_numCols-1
1897 if (colNumber
>= m_numCols
|| colNumber
< 0)
1903 if (colNumber
!= first
)
1904 tempStr
+= wxT(",");
1906 tempStr
+= colDefs
[colNumber
].ColName
;
1907 colNumber
= va_arg (argptr
, int);
1909 va_end (argptr
); /* Reset variable arguments. */
1911 SetOrderByClause(tempStr
);
1914 } // wxDbTable::SetOrderByColNums()
1917 /********** wxDbTable::Insert() **********/
1918 int wxDbTable::Insert(void)
1920 wxASSERT(!queryOnly
);
1921 if (queryOnly
|| !insertable
)
1926 // Insert the record by executing the already prepared insert statement
1928 retcode
= SQLExecute(hstmtInsert
);
1929 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1930 retcode
!= SQL_NEED_DATA
)
1932 // Check to see if integrity constraint was violated
1933 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1934 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1935 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1938 pDb
->DispNextError();
1939 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1943 if (retcode
== SQL_NEED_DATA
)
1946 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1947 while (retcode
== SQL_NEED_DATA
)
1949 // Find the parameter
1951 for (i
=0; i
< m_numCols
; i
++)
1953 if (colDefs
[i
].PtrDataObj
== pParmID
)
1955 // We found it. Store the parameter.
1956 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1957 if (retcode
!= SQL_SUCCESS
)
1959 pDb
->DispNextError();
1960 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1966 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1967 if (retcode
!= SQL_SUCCESS
&&
1968 retcode
!= SQL_SUCCESS_WITH_INFO
)
1970 // record was not inserted
1971 pDb
->DispNextError();
1972 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1978 // Record inserted into the datasource successfully
1981 } // wxDbTable::Insert()
1984 /********** wxDbTable::Update() **********/
1985 bool wxDbTable::Update(void)
1987 wxASSERT(!queryOnly
);
1993 // Build the SQL UPDATE statement
1994 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1996 pDb
->WriteSqlLog(sqlStmt
);
1998 #ifdef DBDEBUG_CONSOLE
1999 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2002 // Execute the SQL UPDATE statement
2003 return(execUpdate(sqlStmt
));
2005 } // wxDbTable::Update()
2008 /********** wxDbTable::Update(pSqlStmt) **********/
2009 bool wxDbTable::Update(const wxString
&pSqlStmt
)
2011 wxASSERT(!queryOnly
);
2015 pDb
->WriteSqlLog(pSqlStmt
);
2017 return(execUpdate(pSqlStmt
));
2019 } // wxDbTable::Update(pSqlStmt)
2022 /********** wxDbTable::UpdateWhere() **********/
2023 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
2025 wxASSERT(!queryOnly
);
2031 // Build the SQL UPDATE statement
2032 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2034 pDb
->WriteSqlLog(sqlStmt
);
2036 #ifdef DBDEBUG_CONSOLE
2037 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2040 // Execute the SQL UPDATE statement
2041 return(execUpdate(sqlStmt
));
2043 } // wxDbTable::UpdateWhere()
2046 /********** wxDbTable::Delete() **********/
2047 bool wxDbTable::Delete(void)
2049 wxASSERT(!queryOnly
);
2056 // Build the SQL DELETE statement
2057 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2059 pDb
->WriteSqlLog(sqlStmt
);
2061 // Execute the SQL DELETE statement
2062 return(execDelete(sqlStmt
));
2064 } // wxDbTable::Delete()
2067 /********** wxDbTable::DeleteWhere() **********/
2068 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2070 wxASSERT(!queryOnly
);
2077 // Build the SQL DELETE statement
2078 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2080 pDb
->WriteSqlLog(sqlStmt
);
2082 // Execute the SQL DELETE statement
2083 return(execDelete(sqlStmt
));
2085 } // wxDbTable::DeleteWhere()
2088 /********** wxDbTable::DeleteMatching() **********/
2089 bool wxDbTable::DeleteMatching(void)
2091 wxASSERT(!queryOnly
);
2098 // Build the SQL DELETE statement
2099 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2101 pDb
->WriteSqlLog(sqlStmt
);
2103 // Execute the SQL DELETE statement
2104 return(execDelete(sqlStmt
));
2106 } // wxDbTable::DeleteMatching()
2109 /********** wxDbTable::IsColNull() **********/
2110 bool wxDbTable::IsColNull(UWORD colNumber
) const
2113 This logic is just not right. It would indicate true
2114 if a numeric field were set to a value of 0.
2116 switch(colDefs[colNumber].SqlCtype)
2120 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2121 return(((UCHAR FAR *) colDefs[colNumber].PtrDataObj)[0] == 0);
2123 return(( *((SWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2125 return(( *((UWORD*) colDefs[colNumber].PtrDataObj)) == 0);
2127 return(( *((SDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2129 return(( *((UDWORD *) colDefs[colNumber].PtrDataObj)) == 0);
2131 return(( *((SFLOAT *) colDefs[colNumber].PtrDataObj)) == 0);
2133 return((*((SDOUBLE *) colDefs[colNumber].PtrDataObj)) == 0);
2134 case SQL_C_TIMESTAMP:
2135 TIMESTAMP_STRUCT *pDt;
2136 pDt = (TIMESTAMP_STRUCT *) colDefs[colNumber].PtrDataObj;
2137 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2145 return (colDefs
[colNumber
].Null
);
2146 } // wxDbTable::IsColNull()
2149 /********** wxDbTable::CanSelectForUpdate() **********/
2150 bool wxDbTable::CanSelectForUpdate(void)
2155 if (pDb
->Dbms() == dbmsMY_SQL
)
2158 if ((pDb
->Dbms() == dbmsORACLE
) ||
2159 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2164 } // wxDbTable::CanSelectForUpdate()
2167 /********** wxDbTable::CanUpdateByROWID() **********/
2168 bool wxDbTable::CanUpdateByROWID(void)
2171 * NOTE: Returning false for now until this can be debugged,
2172 * as the ROWID is not getting updated correctly
2176 if (pDb->Dbms() == dbmsORACLE)
2181 } // wxDbTable::CanUpdateByROWID()
2184 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2185 bool wxDbTable::IsCursorClosedOnCommit(void)
2187 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2192 } // wxDbTable::IsCursorClosedOnCommit()
2196 /********** wxDbTable::ClearMemberVar() **********/
2197 void wxDbTable::ClearMemberVar(UWORD colNumber
, bool setToNull
)
2199 wxASSERT(colNumber
< m_numCols
);
2201 switch(colDefs
[colNumber
].SqlCtype
)
2207 //case SQL_C_WXCHAR: SQL_C_WXCHAR is covered by either SQL_C_CHAR or SQL_C_WCHAR
2208 ((UCHAR FAR
*) colDefs
[colNumber
].PtrDataObj
)[0] = 0;
2211 *((SWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2214 *((UWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2218 *((SDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2221 *((UDWORD
*) colDefs
[colNumber
].PtrDataObj
) = 0;
2224 *((SFLOAT
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2227 *((SDOUBLE
*) colDefs
[colNumber
].PtrDataObj
) = 0.0f
;
2229 case SQL_C_TIMESTAMP
:
2230 TIMESTAMP_STRUCT
*pDt
;
2231 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNumber
].PtrDataObj
;
2243 SetColNull(colNumber
);
2244 } // wxDbTable::ClearMemberVar()
2247 /********** wxDbTable::ClearMemberVars() **********/
2248 void wxDbTable::ClearMemberVars(bool setToNull
)
2252 // Loop through the columns setting each member variable to zero
2253 for (i
=0; i
< m_numCols
; i
++)
2254 ClearMemberVar((UWORD
)i
,setToNull
);
2256 } // wxDbTable::ClearMemberVars()
2259 /********** wxDbTable::SetQueryTimeout() **********/
2260 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2262 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2263 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2264 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2265 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2266 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2267 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2268 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2269 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2271 // Completed Successfully
2274 } // wxDbTable::SetQueryTimeout()
2277 /********** wxDbTable::SetColDefs() **********/
2278 bool wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2279 SWORD cType
, int size
, bool keyField
, bool updateable
,
2280 bool insertAllowed
, bool derivedColumn
)
2284 if (index
>= m_numCols
) // Columns numbers are zero based....
2286 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
);
2292 if (!colDefs
) // May happen if the database connection fails
2295 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2297 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2298 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0; // Prevent buffer overrun
2300 tmpStr
.Printf(wxT("Column name '%s' is too long. Truncated to '%s'."),
2301 fieldName
.c_str(),colDefs
[index
].ColName
);
2306 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2308 colDefs
[index
].DbDataType
= dataType
;
2309 colDefs
[index
].PtrDataObj
= pData
;
2310 colDefs
[index
].SqlCtype
= cType
;
2311 colDefs
[index
].SzDataObj
= size
; //TODO: glt ??? * sizeof(wxChar) ???
2312 colDefs
[index
].KeyField
= keyField
;
2313 colDefs
[index
].DerivedCol
= derivedColumn
;
2314 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2317 colDefs
[index
].Updateable
= false;
2318 colDefs
[index
].InsertAllowed
= false;
2322 colDefs
[index
].Updateable
= updateable
;
2323 colDefs
[index
].InsertAllowed
= insertAllowed
;
2326 colDefs
[index
].Null
= false;
2330 } // wxDbTable::SetColDefs()
2333 /********** wxDbTable::SetColDefs() **********/
2334 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2337 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2343 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2345 for (index
= 0; index
< numCols
; index
++)
2347 // Process the fields
2348 switch (pColInfs
[index
].dbDataType
)
2350 case DB_DATA_TYPE_VARCHAR
:
2351 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
))];
2352 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].bufferSize
+(1*sizeof(wxChar
));
2353 pColDataPtrs
[index
].SqlCtype
= SQL_C_WXCHAR
;
2355 case DB_DATA_TYPE_INTEGER
:
2356 // Can be long or short
2357 if (pColInfs
[index
].bufferSize
== sizeof(long))
2359 pColDataPtrs
[index
].PtrDataObj
= new long;
2360 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2361 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2365 pColDataPtrs
[index
].PtrDataObj
= new short;
2366 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2367 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2370 case DB_DATA_TYPE_FLOAT
:
2371 // Can be float or double
2372 if (pColInfs
[index
].bufferSize
== sizeof(float))
2374 pColDataPtrs
[index
].PtrDataObj
= new float;
2375 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2376 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2380 pColDataPtrs
[index
].PtrDataObj
= new double;
2381 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2382 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2385 case DB_DATA_TYPE_DATE
:
2386 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2387 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2388 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2390 case DB_DATA_TYPE_BLOB
:
2391 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2392 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2393 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2394 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2397 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2398 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2401 // Unable to build all the column definitions, as either one of
2402 // the calls to "new" failed above, or there was a BLOB field
2403 // to have a column definition for. If BLOBs are to be used,
2404 // the other form of ::SetColDefs() must be used, as it is impossible
2405 // to know the maximum size to create the PtrDataObj to be.
2406 delete [] pColDataPtrs
;
2412 return (pColDataPtrs
);
2414 } // wxDbTable::SetColDefs()
2417 /********** wxDbTable::SetCursor() **********/
2418 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2420 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2421 hstmt
= *hstmtDefault
;
2423 hstmt
= *hstmtActivate
;
2425 } // wxDbTable::SetCursor()
2428 /********** wxDbTable::Count(const wxString &) **********/
2429 ULONG
wxDbTable::Count(const wxString
&args
)
2435 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2436 sqlStmt
= wxT("SELECT COUNT(");
2438 sqlStmt
+= wxT(") FROM ");
2439 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2440 // sqlStmt += queryTableName;
2441 #if wxODBC_BACKWARD_COMPATABILITY
2442 if (from
&& wxStrlen(from
))
2448 // Add the where clause if one is provided
2449 #if wxODBC_BACKWARD_COMPATABILITY
2450 if (where
&& wxStrlen(where
))
2455 sqlStmt
+= wxT(" WHERE ");
2459 pDb
->WriteSqlLog(sqlStmt
);
2461 // Initialize the Count cursor if it's not already initialized
2464 hstmtCount
= GetNewCursor(false,false);
2465 wxASSERT(hstmtCount
);
2470 // Execute the SQL statement
2471 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2473 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2478 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2480 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2484 // Obtain the result
2485 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2487 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2492 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2493 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2495 // Return the record count
2498 } // wxDbTable::Count()
2501 /********** wxDbTable::Refresh() **********/
2502 bool wxDbTable::Refresh(void)
2506 // Switch to the internal cursor so any active cursors are not corrupted
2507 HSTMT currCursor
= GetCursor();
2508 hstmt
= hstmtInternal
;
2509 #if wxODBC_BACKWARD_COMPATABILITY
2510 // Save the where and order by clauses
2511 wxChar
*saveWhere
= where
;
2512 wxChar
*saveOrderBy
= orderBy
;
2514 wxString saveWhere
= where
;
2515 wxString saveOrderBy
= orderBy
;
2517 // Build a where clause to refetch the record with. Try and use the
2518 // ROWID if it's available, ow use the key fields.
2519 wxString whereClause
;
2520 whereClause
.Empty();
2522 if (CanUpdateByROWID())
2525 wxChar rowid
[wxDB_ROWID_LEN
+1];
2527 // Get the ROWID value. If not successful retreiving the ROWID,
2528 // simply fall down through the code and build the WHERE clause
2529 // based on the key fields.
2530 if (SQLGetData(hstmt
, (UWORD
)(m_numCols
+1), SQL_C_WXCHAR
, (UCHAR
*) rowid
, sizeof(rowid
), &cb
) == SQL_SUCCESS
)
2532 whereClause
+= pDb
->SQLTableName(queryTableName
);
2533 // whereClause += queryTableName;
2534 whereClause
+= wxT(".ROWID = '");
2535 whereClause
+= rowid
;
2536 whereClause
+= wxT("'");
2540 // If unable to use the ROWID, build a where clause from the keyfields
2541 if (wxStrlen(whereClause
) == 0)
2542 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2544 // Requery the record
2545 where
= whereClause
;
2550 if (result
&& !GetNext())
2553 // Switch back to original cursor
2554 SetCursor(&currCursor
);
2556 // Free the internal cursor
2557 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2558 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2560 // Restore the original where and order by clauses
2562 orderBy
= saveOrderBy
;
2566 } // wxDbTable::Refresh()
2569 /********** wxDbTable::SetColNull() **********/
2570 bool wxDbTable::SetColNull(UWORD colNumber
, bool set
)
2572 if (colNumber
< m_numCols
)
2574 colDefs
[colNumber
].Null
= set
;
2575 if (set
) // Blank out the values in the member variable
2576 ClearMemberVar(colNumber
, false); // Must call with false here, or infinite recursion will happen
2578 setCbValueForColumn(colNumber
);
2585 } // wxDbTable::SetColNull()
2588 /********** wxDbTable::SetColNull() **********/
2589 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2592 for (colNumber
= 0; colNumber
< m_numCols
; colNumber
++)
2594 if (!wxStricmp(colName
, colDefs
[colNumber
].ColName
))
2598 if (colNumber
< m_numCols
)
2600 colDefs
[colNumber
].Null
= set
;
2601 if (set
) // Blank out the values in the member variable
2602 ClearMemberVar((UWORD
)colNumber
,false); // Must call with false here, or infinite recursion will happen
2604 setCbValueForColumn(colNumber
);
2611 } // wxDbTable::SetColNull()
2614 /********** wxDbTable::GetNewCursor() **********/
2615 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2617 HSTMT
*newHSTMT
= new HSTMT
;
2622 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2624 pDb
->DispAllErrors(henv
, hdbc
);
2629 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2631 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2638 if (!bindCols(*newHSTMT
))
2646 SetCursor(newHSTMT
);
2650 } // wxDbTable::GetNewCursor()
2653 /********** wxDbTable::DeleteCursor() **********/
2654 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2658 if (!hstmtDel
) // Cursor already deleted
2662 ODBC 3.0 says to use this form
2663 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2666 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2668 pDb
->DispAllErrors(henv
, hdbc
);
2676 } // wxDbTable::DeleteCursor()
2678 //////////////////////////////////////////////////////////////
2679 // wxDbGrid support functions
2680 //////////////////////////////////////////////////////////////
2682 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2684 if (!m_hstmtGridQuery
)
2686 m_hstmtGridQuery
= GetNewCursor(false,false);
2687 if (!bindCols(*m_hstmtGridQuery
))
2691 m_rowmode
= rowmode
;
2694 case WX_ROW_MODE_QUERY
:
2695 SetCursor(m_hstmtGridQuery
);
2697 case WX_ROW_MODE_INDIVIDUAL
:
2698 SetCursor(hstmtDefault
);
2703 } // wxDbTable::SetRowMode()
2706 wxVariant
wxDbTable::GetColumn(const int colNumber
) const
2709 if ((colNumber
< m_numCols
) && (!IsColNull((UWORD
)colNumber
)))
2711 switch (colDefs
[colNumber
].SqlCtype
)
2714 #if defined(SQL_WCHAR)
2717 #if defined(SQL_WVARCHAR)
2723 val
= (wxChar
*)(colDefs
[colNumber
].PtrDataObj
);
2727 val
= *(long *)(colDefs
[colNumber
].PtrDataObj
);
2731 val
= (long int )(*(short *)(colDefs
[colNumber
].PtrDataObj
));
2734 val
= (long)(*(unsigned long *)(colDefs
[colNumber
].PtrDataObj
));
2737 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2739 case SQL_C_UTINYINT
:
2740 val
= (long)(*(wxChar
*)(colDefs
[colNumber
].PtrDataObj
));
2743 val
= (long)(*(UWORD
*)(colDefs
[colNumber
].PtrDataObj
));
2746 val
= (DATE_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2749 val
= (TIME_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2751 case SQL_C_TIMESTAMP
:
2752 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNumber
].PtrDataObj
);
2755 val
= *(double *)(colDefs
[colNumber
].PtrDataObj
);
2762 } // wxDbTable::GetCol()
2765 void wxDbTable::SetColumn(const int colNumber
, const wxVariant val
)
2767 //FIXME: Add proper wxDateTime support to wxVariant..
2770 SetColNull((UWORD
)colNumber
, val
.IsNull());
2774 if ((colDefs
[colNumber
].SqlCtype
== SQL_C_DATE
)
2775 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIME
)
2776 || (colDefs
[colNumber
].SqlCtype
== SQL_C_TIMESTAMP
))
2778 //Returns null if invalid!
2779 if (!dateval
.ParseDate(val
.GetString()))
2780 SetColNull((UWORD
)colNumber
, true);
2783 switch (colDefs
[colNumber
].SqlCtype
)
2786 #if defined(SQL_WCHAR)
2789 #if defined(SQL_WVARCHAR)
2795 csstrncpyt((wxChar
*)(colDefs
[colNumber
].PtrDataObj
),
2796 val
.GetString().c_str(),
2797 colDefs
[colNumber
].SzDataObj
-1); //TODO: glt ??? * sizeof(wxChar) ???
2801 *(long *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2805 *(short *)(colDefs
[colNumber
].PtrDataObj
) = (short)val
.GetLong();
2808 *(unsigned long *)(colDefs
[colNumber
].PtrDataObj
) = val
.GetLong();
2811 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2813 case SQL_C_UTINYINT
:
2814 *(wxChar
*)(colDefs
[colNumber
].PtrDataObj
) = val
.GetChar();
2817 *(unsigned short *)(colDefs
[colNumber
].PtrDataObj
) = (unsigned short)val
.GetLong();
2819 //FIXME: Add proper wxDateTime support to wxVariant..
2822 DATE_STRUCT
*dataptr
=
2823 (DATE_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2825 dataptr
->year
= (SWORD
)dateval
.GetYear();
2826 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2827 dataptr
->day
= (UWORD
)dateval
.GetDay();
2832 TIME_STRUCT
*dataptr
=
2833 (TIME_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2835 dataptr
->hour
= dateval
.GetHour();
2836 dataptr
->minute
= dateval
.GetMinute();
2837 dataptr
->second
= dateval
.GetSecond();
2840 case SQL_C_TIMESTAMP
:
2842 TIMESTAMP_STRUCT
*dataptr
=
2843 (TIMESTAMP_STRUCT
*)colDefs
[colNumber
].PtrDataObj
;
2844 dataptr
->year
= (SWORD
)dateval
.GetYear();
2845 dataptr
->month
= (UWORD
)(dateval
.GetMonth()+1);
2846 dataptr
->day
= (UWORD
)dateval
.GetDay();
2848 dataptr
->hour
= dateval
.GetHour();
2849 dataptr
->minute
= dateval
.GetMinute();
2850 dataptr
->second
= dateval
.GetSecond();
2854 *(double *)(colDefs
[colNumber
].PtrDataObj
) = val
;
2859 } // if (!val.IsNull())
2860 } // wxDbTable::SetCol()
2863 GenericKey
wxDbTable::GetKey()
2868 blk
= malloc(m_keysize
);
2869 blkptr
= (wxChar
*) blk
;
2872 for (i
=0; i
< m_numCols
; i
++)
2874 if (colDefs
[i
].KeyField
)
2876 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2877 blkptr
+= colDefs
[i
].SzDataObj
;
2881 GenericKey k
= GenericKey(blk
, m_keysize
);
2885 } // wxDbTable::GetKey()
2888 void wxDbTable::SetKey(const GenericKey
& k
)
2894 blkptr
= (wxChar
*)blk
;
2897 for (i
=0; i
< m_numCols
; i
++)
2899 if (colDefs
[i
].KeyField
)
2901 SetColNull((UWORD
)i
, false);
2902 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2903 blkptr
+= colDefs
[i
].SzDataObj
;
2906 } // wxDbTable::SetKey()
2909 #endif // wxUSE_ODBC