1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence, plus:
12 // Notice: This class library and its intellectual design are free of charge for use,
13 // modification, enhancement, debugging under the following conditions:
14 // 1) These classes may only be used as part of the implementation of a
15 // wxWidgets-based application
16 // 2) All enhancements and bug fixes are to be submitted back to the wxWidgets
17 // user groups free of all charges for use with the wxWidgets library.
18 // 3) These classes may not be distributed as part of any other class library,
19 // DLL, text (written or electronic), other than a complete distribution of
20 // the wxWidgets GUI development toolkit.
21 ///////////////////////////////////////////////////////////////////////////////
28 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
29 #pragma implementation "dbtable.h"
32 #include "wx/wxprec.h"
38 #ifdef DBDEBUG_CONSOLE
44 #include "wx/ioswrap.h"
48 #include "wx/string.h"
49 #include "wx/object.h"
54 #include "wx/filefn.h"
62 #include "wx/dbtable.h"
65 // The HPUX preprocessor lines below were commented out on 8/20/97
66 // because macros.h currently redefines DEBUG and is unneeded.
68 // # include <macros.h>
71 # include <sys/minmax.h>
75 ULONG lastTableID
= 0;
83 void csstrncpyt(wxChar
*target
, const wxChar
*source
, int n
)
85 while ( (*target
++ = *source
++) != '\0' && --n
)
93 /********** wxDbColDef::wxDbColDef() Constructor **********/
94 wxDbColDef::wxDbColDef()
100 bool wxDbColDef::Initialize()
103 DbDataType
= DB_DATA_TYPE_INTEGER
;
104 SqlCtype
= SQL_C_LONG
;
109 InsertAllowed
= FALSE
;
115 } // wxDbColDef::Initialize()
118 /********** wxDbTable::wxDbTable() Constructor **********/
119 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
120 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
122 if (!initialize(pwxDb
, tblName
, numColumns
, qryTblName
, qryOnly
, tblPath
))
124 } // wxDbTable::wxDbTable()
127 /***** DEPRECATED: use wxDbTable::wxDbTable() format above *****/
128 wxDbTable::wxDbTable(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
129 const wxChar
*qryTblName
, bool qryOnly
, const wxString
&tblPath
)
131 wxString tempQryTblName
;
132 tempQryTblName
= qryTblName
;
133 if (!initialize(pwxDb
, tblName
, numColumns
, tempQryTblName
, qryOnly
, tblPath
))
135 } // wxDbTable::wxDbTable()
138 /********** wxDbTable::~wxDbTable() **********/
139 wxDbTable::~wxDbTable()
142 } // wxDbTable::~wxDbTable()
145 bool wxDbTable::initialize(wxDb
*pwxDb
, const wxString
&tblName
, const UWORD numColumns
,
146 const wxString
&qryTblName
, bool qryOnly
, const wxString
&tblPath
)
148 // Initializing member variables
149 pDb
= pwxDb
; // Pointer to the wxDb object
153 m_hstmtGridQuery
= 0;
154 hstmtDefault
= 0; // Initialized below
155 hstmtCount
= 0; // Initialized first time it is needed
162 noCols
= numColumns
; // Number of cols in the table
163 where
.Empty(); // Where clause
164 orderBy
.Empty(); // Order By clause
165 from
.Empty(); // From clause
166 selectForUpdate
= FALSE
; // SELECT ... FOR UPDATE; Indicates whether to include the FOR UPDATE phrase
171 queryTableName
.Empty();
173 wxASSERT(tblName
.Length());
179 tableName
= tblName
; // Table Name
180 if (tblPath
.Length())
181 tablePath
= tblPath
; // Table Path - used for dBase files
185 if (qryTblName
.Length()) // Name of the table/view to query
186 queryTableName
= qryTblName
;
188 queryTableName
= tblName
;
190 pDb
->incrementTableCount();
193 tableID
= ++lastTableID
;
194 s
.Printf(wxT("wxDbTable constructor (%-20s) tableID:[%6lu] pDb:[%p]"), tblName
.c_str(), tableID
, pDb
);
197 wxTablesInUse
*tableInUse
;
198 tableInUse
= new wxTablesInUse();
199 tableInUse
->tableName
= tblName
;
200 tableInUse
->tableID
= tableID
;
201 tableInUse
->pDb
= pDb
;
202 TablesInUse
.Append(tableInUse
);
207 // Grab the HENV and HDBC from the wxDb object
208 henv
= pDb
->GetHENV();
209 hdbc
= pDb
->GetHDBC();
211 // Allocate space for column definitions
213 colDefs
= new wxDbColDef
[noCols
]; // Points to the first column definition
215 // Allocate statement handles for the table
218 // Allocate a separate statement handle for performing inserts
219 if (SQLAllocStmt(hdbc
, &hstmtInsert
) != SQL_SUCCESS
)
220 pDb
->DispAllErrors(henv
, hdbc
);
221 // Allocate a separate statement handle for performing deletes
222 if (SQLAllocStmt(hdbc
, &hstmtDelete
) != SQL_SUCCESS
)
223 pDb
->DispAllErrors(henv
, hdbc
);
224 // Allocate a separate statement handle for performing updates
225 if (SQLAllocStmt(hdbc
, &hstmtUpdate
) != SQL_SUCCESS
)
226 pDb
->DispAllErrors(henv
, hdbc
);
228 // Allocate a separate statement handle for internal use
229 if (SQLAllocStmt(hdbc
, &hstmtInternal
) != SQL_SUCCESS
)
230 pDb
->DispAllErrors(henv
, hdbc
);
232 // Set the cursor type for the statement handles
233 cursorType
= SQL_CURSOR_STATIC
;
235 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
237 // Check to see if cursor type is supported
238 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
239 if (! wxStrcmp(pDb
->sqlState
, wxT("01S02"))) // Option Value Changed
241 // Datasource does not support static cursors. Driver
242 // will substitute a cursor type. Call SQLGetStmtOption()
243 // to determine which cursor type was selected.
244 if (SQLGetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, &cursorType
) != SQL_SUCCESS
)
245 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
246 #ifdef DBDEBUG_CONSOLE
247 cout
<< wxT("Static cursor changed to: ");
250 case SQL_CURSOR_FORWARD_ONLY
:
251 cout
<< wxT("Forward Only");
253 case SQL_CURSOR_STATIC
:
254 cout
<< wxT("Static");
256 case SQL_CURSOR_KEYSET_DRIVEN
:
257 cout
<< wxT("Keyset Driven");
259 case SQL_CURSOR_DYNAMIC
:
260 cout
<< wxT("Dynamic");
263 cout
<< endl
<< endl
;
266 if (pDb
->FwdOnlyCursors() && cursorType
!= SQL_CURSOR_FORWARD_ONLY
)
268 // Force the use of a forward only cursor...
269 cursorType
= SQL_CURSOR_FORWARD_ONLY
;
270 if (SQLSetStmtOption(hstmtInternal
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
272 // Should never happen
273 pDb
->GetNextError(henv
, hdbc
, hstmtInternal
);
280 pDb
->DispNextError();
281 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
284 #ifdef DBDEBUG_CONSOLE
286 cout
<< wxT("Cursor Type set to STATIC") << endl
<< endl
;
291 // Set the cursor type for the INSERT statement handle
292 if (SQLSetStmtOption(hstmtInsert
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
293 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
294 // Set the cursor type for the DELETE statement handle
295 if (SQLSetStmtOption(hstmtDelete
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
296 pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
);
297 // Set the cursor type for the UPDATE statement handle
298 if (SQLSetStmtOption(hstmtUpdate
, SQL_CURSOR_TYPE
, SQL_CURSOR_FORWARD_ONLY
) != SQL_SUCCESS
)
299 pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
302 // Make the default cursor the active cursor
303 hstmtDefault
= GetNewCursor(FALSE
,FALSE
);
304 wxASSERT(hstmtDefault
);
305 hstmt
= *hstmtDefault
;
309 } // wxDbTable::initialize()
312 void wxDbTable::cleanup()
317 s
.Printf(wxT("wxDbTable destructor (%-20s) tableID:[%6lu] pDb:[%p]"), tableName
.c_str(), tableID
, pDb
);
326 wxList::compatibility_iterator pNode
;
327 pNode
= TablesInUse
.GetFirst();
328 while (pNode
&& !found
)
330 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
333 delete (wxTablesInUse
*)pNode
->GetData();
334 TablesInUse
.Erase(pNode
);
337 pNode
= pNode
->GetNext();
342 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
343 wxLogDebug (msg
,wxT("NOTICE..."));
348 // Decrement the wxDb table count
350 pDb
->decrementTableCount();
352 // Delete memory allocated for column definitions
356 // Free statement handles
362 ODBC 3.0 says to use this form
363 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
365 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
366 pDb
->DispAllErrors(henv
, hdbc
);
372 ODBC 3.0 says to use this form
373 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
375 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
376 pDb
->DispAllErrors(henv
, hdbc
);
382 ODBC 3.0 says to use this form
383 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
385 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
386 pDb
->DispAllErrors(henv
, hdbc
);
392 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
393 pDb
->DispAllErrors(henv
, hdbc
);
396 // Delete dynamically allocated cursors
398 DeleteCursor(hstmtDefault
);
401 DeleteCursor(hstmtCount
);
403 if (m_hstmtGridQuery
)
404 DeleteCursor(m_hstmtGridQuery
);
406 } // wxDbTable::cleanup()
409 /***************************** PRIVATE FUNCTIONS *****************************/
412 void wxDbTable::setCbValueForColumn(int columnIndex
)
414 switch(colDefs
[columnIndex
].DbDataType
)
416 case DB_DATA_TYPE_VARCHAR
:
417 if (colDefs
[columnIndex
].Null
)
418 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
420 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
422 case DB_DATA_TYPE_INTEGER
:
423 if (colDefs
[columnIndex
].Null
)
424 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
426 colDefs
[columnIndex
].CbValue
= 0;
428 case DB_DATA_TYPE_FLOAT
:
429 if (colDefs
[columnIndex
].Null
)
430 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
432 colDefs
[columnIndex
].CbValue
= 0;
434 case DB_DATA_TYPE_DATE
:
435 if (colDefs
[columnIndex
].Null
)
436 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
438 colDefs
[columnIndex
].CbValue
= 0;
440 case DB_DATA_TYPE_BLOB
:
441 if (colDefs
[columnIndex
].Null
)
442 colDefs
[columnIndex
].CbValue
= SQL_NULL_DATA
;
444 if (colDefs
[columnIndex
].SqlCtype
== SQL_C_CHAR
)
445 colDefs
[columnIndex
].CbValue
= SQL_NTS
;
447 colDefs
[columnIndex
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[columnIndex
].SzDataObj
);
452 /********** wxDbTable::bindParams() **********/
453 bool wxDbTable::bindParams(bool forUpdate
)
455 wxASSERT(!queryOnly
);
460 SDWORD precision
= 0;
463 // Bind each column of the table that should be bound
464 // to a parameter marker
468 for (i
=0, colNo
=1; i
< noCols
; i
++)
472 if (!colDefs
[i
].Updateable
)
477 if (!colDefs
[i
].InsertAllowed
)
481 switch(colDefs
[i
].DbDataType
)
483 case DB_DATA_TYPE_VARCHAR
:
484 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
485 precision
= colDefs
[i
].SzDataObj
;
488 case DB_DATA_TYPE_INTEGER
:
489 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
490 precision
= pDb
->GetTypeInfInteger().Precision
;
493 case DB_DATA_TYPE_FLOAT
:
494 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
495 precision
= pDb
->GetTypeInfFloat().Precision
;
496 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
497 // SQL Sybase Anywhere v5.5 returned a negative number for the
498 // MaxScale. This caused ODBC to kick out an error on ibscale.
499 // I check for this here and set the scale = precision.
501 // scale = (short) precision;
503 case DB_DATA_TYPE_DATE
:
504 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
505 precision
= pDb
->GetTypeInfDate().Precision
;
508 case DB_DATA_TYPE_BLOB
:
509 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
510 precision
= colDefs
[i
].SzDataObj
;
515 setCbValueForColumn(i
);
519 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
520 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
521 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
523 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
528 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
529 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
530 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
532 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
537 // Completed successfully
540 } // wxDbTable::bindParams()
543 /********** wxDbTable::bindInsertParams() **********/
544 bool wxDbTable::bindInsertParams(void)
546 return bindParams(FALSE
);
547 } // wxDbTable::bindInsertParams()
550 /********** wxDbTable::bindUpdateParams() **********/
551 bool wxDbTable::bindUpdateParams(void)
553 return bindParams(TRUE
);
554 } // wxDbTable::bindUpdateParams()
557 /********** wxDbTable::bindCols() **********/
558 bool wxDbTable::bindCols(HSTMT cursor
)
562 // Bind each column of the table to a memory address for fetching data
564 for (i
= 0; i
< noCols
; i
++)
566 cb
= colDefs
[i
].CbValue
;
567 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
568 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
569 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
572 // Completed successfully
575 } // wxDbTable::bindCols()
578 /********** wxDbTable::getRec() **********/
579 bool wxDbTable::getRec(UWORD fetchType
)
583 if (!pDb
->FwdOnlyCursors())
585 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
589 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
590 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
592 if (retcode
== SQL_NO_DATA_FOUND
)
595 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
599 // Set the Null member variable to indicate the Null state
600 // of each column just read in.
602 for (i
= 0; i
< noCols
; i
++)
603 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
608 // Fetch the next record from the record set
609 retcode
= SQLFetch(hstmt
);
610 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
612 if (retcode
== SQL_NO_DATA_FOUND
)
615 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
619 // Set the Null member variable to indicate the Null state
620 // of each column just read in.
622 for (i
= 0; i
< noCols
; i
++)
623 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
627 // Completed successfully
630 } // wxDbTable::getRec()
633 /********** wxDbTable::execDelete() **********/
634 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
638 // Execute the DELETE statement
639 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
641 if (retcode
== SQL_SUCCESS
||
642 retcode
== SQL_NO_DATA_FOUND
||
643 retcode
== SQL_SUCCESS_WITH_INFO
)
645 // Record deleted successfully
649 // Problem deleting record
650 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
652 } // wxDbTable::execDelete()
655 /********** wxDbTable::execUpdate() **********/
656 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
660 // Execute the UPDATE statement
661 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
663 if (retcode
== SQL_SUCCESS
||
664 retcode
== SQL_NO_DATA_FOUND
||
665 retcode
== SQL_SUCCESS_WITH_INFO
)
667 // Record updated successfully
670 else if (retcode
== SQL_NEED_DATA
)
673 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
674 while (retcode
== SQL_NEED_DATA
)
676 // Find the parameter
678 for (i
=0; i
< noCols
; i
++)
680 if (colDefs
[i
].PtrDataObj
== pParmID
)
682 // We found it. Store the parameter.
683 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
684 if (retcode
!= SQL_SUCCESS
)
686 pDb
->DispNextError();
687 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
692 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
694 if (retcode
== SQL_SUCCESS
||
695 retcode
== SQL_NO_DATA_FOUND
||
696 retcode
== SQL_SUCCESS_WITH_INFO
)
698 // Record updated successfully
703 // Problem updating record
704 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
706 } // wxDbTable::execUpdate()
709 /********** wxDbTable::query() **********/
710 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
715 // The user may wish to select for update, but the DBMS may not be capable
716 selectForUpdate
= CanSelectForUpdate();
718 selectForUpdate
= FALSE
;
720 // Set the SQL SELECT string
721 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
722 { // so generate a select statement.
723 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
724 pDb
->WriteSqlLog(sqlStmt
);
727 // Make sure the cursor is closed first
728 if (!CloseCursor(hstmt
))
731 // Execute the SQL SELECT statement
733 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
734 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
735 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
737 // Completed successfully
740 } // wxDbTable::query()
743 /***************************** PUBLIC FUNCTIONS *****************************/
746 /********** wxDbTable::Open() **********/
747 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
757 // Calculate the maximum size of the concatenated
758 // keys for use with wxDbGrid
760 for (i
=0; i
< noCols
; i
++)
762 if (colDefs
[i
].KeyField
)
765 m_keysize
+= colDefs
[i
].SzDataObj
;
770 // Verify that the table exists in the database
771 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
773 s
= wxT("Table/view does not exist in the database");
774 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
775 s
+= wxT(", or you have no permissions.\n");
779 else if (checkPrivileges
)
781 // Verify the user has rights to access the table.
782 // Shortcut boolean evaluation to optimize out call to
785 // Unfortunately this optimization doesn't seem to be
787 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
788 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
789 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
796 if (!tablePath
.IsEmpty())
797 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
799 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
802 pDb
->LogError(p
.GetData());
807 // Bind the member variables for field exchange between
808 // the wxDbTable object and the ODBC record.
811 if (!bindInsertParams()) // Inserts
814 if (!bindUpdateParams()) // Updates
818 if (!bindCols(*hstmtDefault
)) // Selects
821 if (!bindCols(hstmtInternal
)) // Internal use only
825 * Do NOT bind the hstmtCount cursor!!!
828 // Build an insert statement using parameter markers
829 if (!queryOnly
&& noCols
> 0)
831 bool needComma
= FALSE
;
832 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
833 pDb
->SQLTableName(tableName
.c_str()).c_str());
834 for (i
= 0; i
< noCols
; i
++)
836 if (! colDefs
[i
].InsertAllowed
)
840 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
841 // sqlStmt += colDefs[i].ColName;
845 sqlStmt
+= wxT(") VALUES (");
847 int insertableCount
= 0;
849 for (i
= 0; i
< noCols
; i
++)
851 if (! colDefs
[i
].InsertAllowed
)
861 // Prepare the insert statement for execution
864 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
865 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
871 // Completed successfully
874 } // wxDbTable::Open()
877 /********** wxDbTable::Query() **********/
878 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
881 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
883 } // wxDbTable::Query()
886 /********** wxDbTable::QueryBySqlStmt() **********/
887 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
889 pDb
->WriteSqlLog(pSqlStmt
);
891 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
893 } // wxDbTable::QueryBySqlStmt()
896 /********** wxDbTable::QueryMatching() **********/
897 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
900 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
902 } // wxDbTable::QueryMatching()
905 /********** wxDbTable::QueryOnKeyFields() **********/
906 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
909 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
911 } // wxDbTable::QueryOnKeyFields()
914 /********** wxDbTable::GetPrev() **********/
915 bool wxDbTable::GetPrev(void)
917 if (pDb
->FwdOnlyCursors())
919 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
923 return(getRec(SQL_FETCH_PRIOR
));
925 } // wxDbTable::GetPrev()
928 /********** wxDbTable::operator-- **********/
929 bool wxDbTable::operator--(int)
931 if (pDb
->FwdOnlyCursors())
933 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
937 return(getRec(SQL_FETCH_PRIOR
));
939 } // wxDbTable::operator--
942 /********** wxDbTable::GetFirst() **********/
943 bool wxDbTable::GetFirst(void)
945 if (pDb
->FwdOnlyCursors())
947 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
951 return(getRec(SQL_FETCH_FIRST
));
953 } // wxDbTable::GetFirst()
956 /********** wxDbTable::GetLast() **********/
957 bool wxDbTable::GetLast(void)
959 if (pDb
->FwdOnlyCursors())
961 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
965 return(getRec(SQL_FETCH_LAST
));
967 } // wxDbTable::GetLast()
970 /********** wxDbTable::BuildDeleteStmt() **********/
971 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
973 wxASSERT(!queryOnly
);
977 wxString whereClause
;
981 // Handle the case of DeleteWhere() and the where clause is blank. It should
982 // delete all records from the database in this case.
983 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
985 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
986 pDb
->SQLTableName(tableName
.c_str()).c_str());
990 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
991 pDb
->SQLTableName(tableName
.c_str()).c_str());
993 // Append the WHERE clause to the SQL DELETE statement
996 case DB_DEL_KEYFIELDS
:
997 // If the datasource supports the ROWID column, build
998 // the where on ROWID for efficiency purposes.
999 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
1000 if (CanUpdByROWID())
1003 wxChar rowid
[wxDB_ROWID_LEN
+1];
1005 // Get the ROWID value. If not successful retreiving the ROWID,
1006 // simply fall down through the code and build the WHERE clause
1007 // based on the key fields.
1008 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1010 pSqlStmt
+= wxT("ROWID = '");
1012 pSqlStmt
+= wxT("'");
1016 // Unable to delete by ROWID, so build a WHERE
1017 // clause based on the keyfields.
1018 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1019 pSqlStmt
+= whereClause
;
1022 pSqlStmt
+= pWhereClause
;
1024 case DB_DEL_MATCHING
:
1025 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1026 pSqlStmt
+= whereClause
;
1030 } // BuildDeleteStmt()
1033 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1034 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1036 wxString tempSqlStmt
;
1037 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1038 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1039 } // wxDbTable::BuildDeleteStmt()
1042 /********** wxDbTable::BuildSelectStmt() **********/
1043 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1045 wxString whereClause
;
1046 whereClause
.Empty();
1048 // Build a select statement to query the database
1049 pSqlStmt
= wxT("SELECT ");
1051 // SELECT DISTINCT values only?
1053 pSqlStmt
+= wxT("DISTINCT ");
1055 // Was a FROM clause specified to join tables to the base table?
1056 // Available for ::Query() only!!!
1057 bool appendFromClause
= FALSE
;
1058 #if wxODBC_BACKWARD_COMPATABILITY
1059 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1060 appendFromClause
= TRUE
;
1062 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1063 appendFromClause
= TRUE
;
1066 // Add the column list
1069 for (i
= 0; i
< noCols
; i
++)
1071 tStr
= colDefs
[i
].ColName
;
1072 // If joining tables, the base table column names must be qualified to avoid ambiguity
1073 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && !tStr
.Find(wxT('.')))
1075 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1076 pSqlStmt
+= wxT(".");
1078 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1080 pSqlStmt
+= wxT(",");
1083 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1084 // the ROWID if querying distinct records. The rowid will always be unique.
1085 if (!distinct
&& CanUpdByROWID())
1087 // If joining tables, the base table column names must be qualified to avoid ambiguity
1088 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1090 pSqlStmt
+= wxT(",");
1091 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1092 // pSqlStmt += 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 typeOfUpd
, 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
< noCols
; 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 ");
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 (CanUpdByROWID())
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
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &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 typeOfUpd
, const wxString
&pWhereClause
)
1249 wxString tempSqlStmt
;
1250 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, 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 (colNo
= 0; colNo
< noCols
; colNo
++)
1270 // Determine if this column should be included in the WHERE clause
1271 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNo
].KeyField
) ||
1272 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(colNo
))))
1274 // Skip over timestamp columns
1275 if (colDefs
[colNo
].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
[colNo
].ColName
;
1286 if (qualTableName
.Length() && !tStr
.Find(wxT('.')))
1288 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1289 pWhereClause
+= wxT(".");
1291 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNo
].ColName
);
1293 if (useLikeComparison
&& (colDefs
[colNo
].SqlCtype
== SQL_C_CHAR
))
1294 pWhereClause
+= wxT(" LIKE ");
1296 pWhereClause
+= wxT(" = ");
1298 switch(colDefs
[colNo
].SqlCtype
)
1301 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
);
1305 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNo
].PtrDataObj
));
1308 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNo
].PtrDataObj
));
1312 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNo
].PtrDataObj
));
1315 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNo
].PtrDataObj
));
1318 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
));
1321 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
));
1326 strMsg
.Printf(wxT("wxDbTable::bindParams(): Unknown column type for colDefs %d colName %s"),
1327 colNo
,colDefs
[colNo
].ColName
);
1328 wxFAIL_MSG(strMsg
.c_str());
1332 pWhereClause
+= colValue
;
1335 } // wxDbTable::BuildWhereClause()
1338 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1339 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1340 const wxString
&qualTableName
, bool useLikeComparison
)
1342 wxString tempSqlStmt
;
1343 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1344 wxStrcpy(pWhereClause
, tempSqlStmt
);
1345 } // wxDbTable::BuildWhereClause()
1348 /********** wxDbTable::GetRowNum() **********/
1349 UWORD
wxDbTable::GetRowNum(void)
1353 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1355 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1359 // Completed successfully
1360 return((UWORD
) rowNum
);
1362 } // wxDbTable::GetRowNum()
1365 /********** wxDbTable::CloseCursor() **********/
1366 bool wxDbTable::CloseCursor(HSTMT cursor
)
1368 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1369 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1371 // Completed successfully
1374 } // wxDbTable::CloseCursor()
1377 /********** wxDbTable::CreateTable() **********/
1378 bool wxDbTable::CreateTable(bool attemptDrop
)
1386 #ifdef DBDEBUG_CONSOLE
1387 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1391 if (attemptDrop
&& !DropTable())
1395 #ifdef DBDEBUG_CONSOLE
1396 for (i
= 0; i
< noCols
; i
++)
1398 // Exclude derived columns since they are NOT part of the base table
1399 if (colDefs
[i
].DerivedCol
)
1401 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1402 switch(colDefs
[i
].DbDataType
)
1404 case DB_DATA_TYPE_VARCHAR
:
1405 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1407 case DB_DATA_TYPE_INTEGER
:
1408 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1410 case DB_DATA_TYPE_FLOAT
:
1411 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1413 case DB_DATA_TYPE_DATE
:
1414 cout
<< pDb
->GetTypeInfDate().TypeName
;
1416 case DB_DATA_TYPE_BLOB
:
1417 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1424 // Build a CREATE TABLE string from the colDefs structure.
1425 bool needComma
= FALSE
;
1427 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1428 pDb
->SQLTableName(tableName
.c_str()).c_str());
1430 for (i
= 0; i
< noCols
; i
++)
1432 // Exclude derived columns since they are NOT part of the base table
1433 if (colDefs
[i
].DerivedCol
)
1437 sqlStmt
+= wxT(",");
1439 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1440 // sqlStmt += colDefs[i].ColName;
1441 sqlStmt
+= wxT(" ");
1443 switch(colDefs
[i
].DbDataType
)
1445 case DB_DATA_TYPE_VARCHAR
:
1446 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1448 case DB_DATA_TYPE_INTEGER
:
1449 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1451 case DB_DATA_TYPE_FLOAT
:
1452 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1454 case DB_DATA_TYPE_DATE
:
1455 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1457 case DB_DATA_TYPE_BLOB
:
1458 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1461 // For varchars, append the size of the string
1462 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1463 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1464 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1467 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1471 if (pDb
->Dbms() == dbmsDB2
||
1472 pDb
->Dbms() == dbmsMY_SQL
||
1473 pDb
->Dbms() == dbmsSYBASE_ASE
||
1474 pDb
->Dbms() == dbmsINTERBASE
||
1475 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1477 if (colDefs
[i
].KeyField
)
1479 sqlStmt
+= wxT(" NOT NULL");
1485 // If there is a primary key defined, include it in the create statement
1486 for (i
= j
= 0; i
< noCols
; i
++)
1488 if (colDefs
[i
].KeyField
)
1494 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1495 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1497 switch (pDb
->Dbms())
1501 case dbmsSYBASE_ASA
:
1502 case dbmsSYBASE_ASE
:
1505 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1506 sqlStmt
+= wxT(",PRIMARY KEY (");
1511 sqlStmt
+= wxT(",CONSTRAINT ");
1512 // DB2 is limited to 18 characters for index names
1513 if (pDb
->Dbms() == dbmsDB2
)
1515 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."));
1516 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1517 // sqlStmt += tableName.substr(0, 13);
1520 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1521 // sqlStmt += tableName;
1523 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1528 // List column name(s) of column(s) comprising the primary key
1529 for (i
= j
= 0; i
< noCols
; i
++)
1531 if (colDefs
[i
].KeyField
)
1533 if (j
++) // Multi part key, comma separate names
1534 sqlStmt
+= wxT(",");
1535 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1537 if (pDb
->Dbms() == dbmsMY_SQL
&&
1538 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1541 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1546 sqlStmt
+= wxT(")");
1548 if (pDb
->Dbms() == dbmsINFORMIX
||
1549 pDb
->Dbms() == dbmsSYBASE_ASA
||
1550 pDb
->Dbms() == dbmsSYBASE_ASE
)
1552 sqlStmt
+= wxT(" CONSTRAINT ");
1553 sqlStmt
+= pDb
->SQLTableName(tableName
);
1554 // sqlStmt += tableName;
1555 sqlStmt
+= wxT("_PIDX");
1558 // Append the closing parentheses for the create table statement
1559 sqlStmt
+= wxT(")");
1561 pDb
->WriteSqlLog(sqlStmt
);
1563 #ifdef DBDEBUG_CONSOLE
1564 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1567 // Execute the CREATE TABLE statement
1568 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1569 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1571 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1572 pDb
->RollbackTrans();
1577 // Commit the transaction and close the cursor
1578 if (!pDb
->CommitTrans())
1580 if (!CloseCursor(hstmt
))
1583 // Database table created successfully
1586 } // wxDbTable::CreateTable()
1589 /********** wxDbTable::DropTable() **********/
1590 bool wxDbTable::DropTable()
1592 // NOTE: This function returns TRUE if the Table does not exist, but
1593 // only for identified databases. Code will need to be added
1594 // below for any other databases when those databases are defined
1595 // to handle this situation consistently
1599 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1600 pDb
->SQLTableName(tableName
.c_str()).c_str());
1602 pDb
->WriteSqlLog(sqlStmt
);
1604 #ifdef DBDEBUG_CONSOLE
1605 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1608 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1609 if (retcode
!= SQL_SUCCESS
)
1611 // Check for "Base table not found" error and ignore
1612 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1613 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1614 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1616 // Check for product specific error codes
1617 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1618 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1619 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1620 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1622 pDb
->DispNextError();
1623 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1624 pDb
->RollbackTrans();
1625 // CloseCursor(hstmt);
1631 // Commit the transaction and close the cursor
1632 if (! pDb
->CommitTrans())
1634 if (! CloseCursor(hstmt
))
1638 } // wxDbTable::DropTable()
1641 /********** wxDbTable::CreateIndex() **********/
1642 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1643 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1647 // Drop the index first
1648 if (attemptDrop
&& !DropIndex(idxName
))
1651 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1652 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1653 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1654 // table was created, then months later you determine that an additional index while
1655 // give better performance, so you want to add an index).
1657 // The following block of code will modify the column definition to make the column be
1658 // defined with the "NOT NULL" qualifier.
1659 if (pDb
->Dbms() == dbmsMY_SQL
)
1664 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1668 // Find the column definition that has the ColName that matches the
1669 // index column name. We need to do this to get the DB_DATA_TYPE of
1670 // the index column, as MySQL's syntax for the ALTER column requires
1672 while (!found
&& (j
< this->noCols
))
1674 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1682 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1683 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1689 // retcode is not used
1690 wxODBC_ERRORS retcode
;
1691 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1692 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1693 // This line is just here for debug checking of the value
1694 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1705 pDb
->RollbackTrans();
1710 // Build a CREATE INDEX statement
1711 sqlStmt
= wxT("CREATE ");
1713 sqlStmt
+= wxT("UNIQUE ");
1715 sqlStmt
+= wxT("INDEX ");
1716 sqlStmt
+= pDb
->SQLTableName(idxName
);
1717 sqlStmt
+= wxT(" ON ");
1719 sqlStmt
+= pDb
->SQLTableName(tableName
);
1720 // sqlStmt += tableName;
1721 sqlStmt
+= wxT(" (");
1723 // Append list of columns making up index
1725 for (i
= 0; i
< noIdxCols
; i
++)
1727 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1728 // sqlStmt += pIdxDefs[i].ColName;
1730 // MySQL requires a key length on VARCHAR keys
1731 if ( pDb
->Dbms() == dbmsMY_SQL
)
1733 // Find the details on this column
1735 for ( j
= 0; j
< noCols
; ++j
)
1737 if ( wxStrcmp( pIdxDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1742 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1745 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1750 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1751 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1752 !(pDb
->Dbms() == dbmsPOSTGRES
))
1754 if (pIdxDefs
[i
].Ascending
)
1755 sqlStmt
+= wxT(" ASC");
1757 sqlStmt
+= wxT(" DESC");
1760 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1762 if ((i
+ 1) < noIdxCols
)
1763 sqlStmt
+= wxT(",");
1766 // Append closing parentheses
1767 sqlStmt
+= wxT(")");
1769 pDb
->WriteSqlLog(sqlStmt
);
1771 #ifdef DBDEBUG_CONSOLE
1772 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1775 // Execute the CREATE INDEX statement
1776 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1778 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1779 pDb
->RollbackTrans();
1784 // Commit the transaction and close the cursor
1785 if (! pDb
->CommitTrans())
1787 if (! CloseCursor(hstmt
))
1790 // Index Created Successfully
1793 } // wxDbTable::CreateIndex()
1796 /********** wxDbTable::DropIndex() **********/
1797 bool wxDbTable::DropIndex(const wxString
&idxName
)
1799 // NOTE: This function returns TRUE if the Index does not exist, but
1800 // only for identified databases. Code will need to be added
1801 // below for any other databases when those databases are defined
1802 // to handle this situation consistently
1806 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1807 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1808 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1809 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1810 pDb
->SQLTableName(tableName
.c_str()).c_str());
1811 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1812 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1813 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1814 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1815 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1816 pDb
->SQLTableName(idxName
.c_str()).c_str());
1818 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1819 pDb
->SQLTableName(idxName
.c_str()).c_str());
1821 pDb
->WriteSqlLog(sqlStmt
);
1823 #ifdef DBDEBUG_CONSOLE
1824 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1827 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1829 // Check for "Index not found" error and ignore
1830 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1831 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1833 // Check for product specific error codes
1834 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1835 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1836 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1837 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1838 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1839 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1840 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1843 pDb
->DispNextError();
1844 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1845 pDb
->RollbackTrans();
1852 // Commit the transaction and close the cursor
1853 if (! pDb
->CommitTrans())
1855 if (! CloseCursor(hstmt
))
1859 } // wxDbTable::DropIndex()
1862 /********** wxDbTable::SetOrderByColNums() **********/
1863 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1865 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1871 va_start(argptr
, first
); /* Initialize variable arguments. */
1872 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1874 // Make sure the passed in column number
1875 // is within the valid range of columns
1877 // Valid columns are 0 thru noCols-1
1878 if (colNo
>= noCols
|| colNo
< 0)
1885 tempStr
+= wxT(",");
1887 tempStr
+= colDefs
[colNo
].ColName
;
1888 colNo
= va_arg (argptr
, int);
1890 va_end (argptr
); /* Reset variable arguments. */
1892 SetOrderByClause(tempStr
);
1895 } // wxDbTable::SetOrderByColNums()
1898 /********** wxDbTable::Insert() **********/
1899 int wxDbTable::Insert(void)
1901 wxASSERT(!queryOnly
);
1902 if (queryOnly
|| !insertable
)
1907 // Insert the record by executing the already prepared insert statement
1909 retcode
=SQLExecute(hstmtInsert
);
1910 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1911 retcode
!= SQL_NEED_DATA
)
1913 // Check to see if integrity constraint was violated
1914 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1915 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1916 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1919 pDb
->DispNextError();
1920 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1924 if (retcode
== SQL_NEED_DATA
)
1927 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1928 while (retcode
== SQL_NEED_DATA
)
1930 // Find the parameter
1932 for (i
=0; i
< noCols
; i
++)
1934 if (colDefs
[i
].PtrDataObj
== pParmID
)
1936 // We found it. Store the parameter.
1937 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1938 if (retcode
!= SQL_SUCCESS
)
1940 pDb
->DispNextError();
1941 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1947 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1951 // Record inserted into the datasource successfully
1954 } // wxDbTable::Insert()
1957 /********** wxDbTable::Update() **********/
1958 bool wxDbTable::Update(void)
1960 wxASSERT(!queryOnly
);
1966 // Build the SQL UPDATE statement
1967 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1969 pDb
->WriteSqlLog(sqlStmt
);
1971 #ifdef DBDEBUG_CONSOLE
1972 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1975 // Execute the SQL UPDATE statement
1976 return(execUpdate(sqlStmt
));
1978 } // wxDbTable::Update()
1981 /********** wxDbTable::Update(pSqlStmt) **********/
1982 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1984 wxASSERT(!queryOnly
);
1988 pDb
->WriteSqlLog(pSqlStmt
);
1990 return(execUpdate(pSqlStmt
));
1992 } // wxDbTable::Update(pSqlStmt)
1995 /********** wxDbTable::UpdateWhere() **********/
1996 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1998 wxASSERT(!queryOnly
);
2004 // Build the SQL UPDATE statement
2005 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
2007 pDb
->WriteSqlLog(sqlStmt
);
2009 #ifdef DBDEBUG_CONSOLE
2010 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
2013 // Execute the SQL UPDATE statement
2014 return(execUpdate(sqlStmt
));
2016 } // wxDbTable::UpdateWhere()
2019 /********** wxDbTable::Delete() **********/
2020 bool wxDbTable::Delete(void)
2022 wxASSERT(!queryOnly
);
2029 // Build the SQL DELETE statement
2030 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2032 pDb
->WriteSqlLog(sqlStmt
);
2034 // Execute the SQL DELETE statement
2035 return(execDelete(sqlStmt
));
2037 } // wxDbTable::Delete()
2040 /********** wxDbTable::DeleteWhere() **********/
2041 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2043 wxASSERT(!queryOnly
);
2050 // Build the SQL DELETE statement
2051 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2053 pDb
->WriteSqlLog(sqlStmt
);
2055 // Execute the SQL DELETE statement
2056 return(execDelete(sqlStmt
));
2058 } // wxDbTable::DeleteWhere()
2061 /********** wxDbTable::DeleteMatching() **********/
2062 bool wxDbTable::DeleteMatching(void)
2064 wxASSERT(!queryOnly
);
2071 // Build the SQL DELETE statement
2072 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2074 pDb
->WriteSqlLog(sqlStmt
);
2076 // Execute the SQL DELETE statement
2077 return(execDelete(sqlStmt
));
2079 } // wxDbTable::DeleteMatching()
2082 /********** wxDbTable::IsColNull() **********/
2083 bool wxDbTable::IsColNull(UWORD colNo
) const
2086 This logic is just not right. It would indicate TRUE
2087 if a numeric field were set to a value of 0.
2089 switch(colDefs[colNo].SqlCtype)
2092 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
2094 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
2096 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
2098 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2100 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2102 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
2104 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
2105 case SQL_C_TIMESTAMP:
2106 TIMESTAMP_STRUCT *pDt;
2107 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
2108 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2116 return (colDefs
[colNo
].Null
);
2117 } // wxDbTable::IsColNull()
2120 /********** wxDbTable::CanSelectForUpdate() **********/
2121 bool wxDbTable::CanSelectForUpdate(void)
2126 if (pDb
->Dbms() == dbmsMY_SQL
)
2129 if ((pDb
->Dbms() == dbmsORACLE
) ||
2130 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2135 } // wxDbTable::CanSelectForUpdate()
2138 /********** wxDbTable::CanUpdByROWID() **********/
2139 bool wxDbTable::CanUpdByROWID(void)
2142 * NOTE: Returning FALSE for now until this can be debugged,
2143 * as the ROWID is not getting updated correctly
2147 if (pDb->Dbms() == dbmsORACLE)
2152 } // wxDbTable::CanUpdByROWID()
2155 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2156 bool wxDbTable::IsCursorClosedOnCommit(void)
2158 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2163 } // wxDbTable::IsCursorClosedOnCommit()
2167 /********** wxDbTable::ClearMemberVar() **********/
2168 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2170 wxASSERT(colNo
< noCols
);
2172 switch(colDefs
[colNo
].SqlCtype
)
2175 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2178 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2181 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2184 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2187 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2190 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2193 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2195 case SQL_C_TIMESTAMP
:
2196 TIMESTAMP_STRUCT
*pDt
;
2197 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2210 } // wxDbTable::ClearMemberVar()
2213 /********** wxDbTable::ClearMemberVars() **********/
2214 void wxDbTable::ClearMemberVars(bool setToNull
)
2218 // Loop through the columns setting each member variable to zero
2219 for (i
=0; i
< noCols
; i
++)
2220 ClearMemberVar(i
,setToNull
);
2222 } // wxDbTable::ClearMemberVars()
2225 /********** wxDbTable::SetQueryTimeout() **********/
2226 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2228 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2229 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2230 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2231 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2232 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2233 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2234 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2235 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2237 // Completed Successfully
2240 } // wxDbTable::SetQueryTimeout()
2243 /********** wxDbTable::SetColDefs() **********/
2244 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2245 SWORD cType
, int size
, bool keyField
, bool upd
,
2246 bool insAllow
, bool derivedCol
)
2248 wxASSERT_MSG( index
< noCols
,
2249 _T("Specified column index exceeds the maximum number of columns for this table.") );
2251 if (!colDefs
) // May happen if the database connection fails
2254 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2256 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2257 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2261 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2262 fieldName
.c_str(),colDefs
[index
].ColName
);
2264 #endif // __WXDEBUG__
2267 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2269 colDefs
[index
].DbDataType
= dataType
;
2270 colDefs
[index
].PtrDataObj
= pData
;
2271 colDefs
[index
].SqlCtype
= cType
;
2272 colDefs
[index
].SzDataObj
= size
;
2273 colDefs
[index
].KeyField
= keyField
;
2274 colDefs
[index
].DerivedCol
= derivedCol
;
2275 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2278 colDefs
[index
].Updateable
= FALSE
;
2279 colDefs
[index
].InsertAllowed
= FALSE
;
2283 colDefs
[index
].Updateable
= upd
;
2284 colDefs
[index
].InsertAllowed
= insAllow
;
2287 colDefs
[index
].Null
= FALSE
;
2289 } // wxDbTable::SetColDefs()
2292 /********** wxDbTable::SetColDefs() **********/
2293 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2296 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2302 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2304 for (index
= 0; index
< numCols
; index
++)
2306 // Process the fields
2307 switch (pColInfs
[index
].dbDataType
)
2309 case DB_DATA_TYPE_VARCHAR
:
2310 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2311 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2312 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2314 case DB_DATA_TYPE_INTEGER
:
2315 // Can be long or short
2316 if (pColInfs
[index
].bufferLength
== sizeof(long))
2318 pColDataPtrs
[index
].PtrDataObj
= new long;
2319 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2320 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2324 pColDataPtrs
[index
].PtrDataObj
= new short;
2325 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2326 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2329 case DB_DATA_TYPE_FLOAT
:
2330 // Can be float or double
2331 if (pColInfs
[index
].bufferLength
== sizeof(float))
2333 pColDataPtrs
[index
].PtrDataObj
= new float;
2334 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2335 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2339 pColDataPtrs
[index
].PtrDataObj
= new double;
2340 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2341 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2344 case DB_DATA_TYPE_DATE
:
2345 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2346 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2347 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2349 case DB_DATA_TYPE_BLOB
:
2350 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2351 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2352 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2353 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2356 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2357 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2360 // Unable to build all the column definitions, as either one of
2361 // the calls to "new" failed above, or there was a BLOB field
2362 // to have a column definition for. If BLOBs are to be used,
2363 // the other form of ::SetColDefs() must be used, as it is impossible
2364 // to know the maximum size to create the PtrDataObj to be.
2365 delete [] pColDataPtrs
;
2371 return (pColDataPtrs
);
2373 } // wxDbTable::SetColDefs()
2376 /********** wxDbTable::SetCursor() **********/
2377 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2379 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2380 hstmt
= *hstmtDefault
;
2382 hstmt
= *hstmtActivate
;
2384 } // wxDbTable::SetCursor()
2387 /********** wxDbTable::Count(const wxString &) **********/
2388 ULONG
wxDbTable::Count(const wxString
&args
)
2394 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2395 sqlStmt
= wxT("SELECT COUNT(");
2397 sqlStmt
+= wxT(") FROM ");
2398 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2399 // sqlStmt += queryTableName;
2400 #if wxODBC_BACKWARD_COMPATABILITY
2401 if (from
&& wxStrlen(from
))
2407 // Add the where clause if one is provided
2408 #if wxODBC_BACKWARD_COMPATABILITY
2409 if (where
&& wxStrlen(where
))
2414 sqlStmt
+= wxT(" WHERE ");
2418 pDb
->WriteSqlLog(sqlStmt
);
2420 // Initialize the Count cursor if it's not already initialized
2423 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2424 wxASSERT(hstmtCount
);
2429 // Execute the SQL statement
2430 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2432 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2437 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2439 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2443 // Obtain the result
2444 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2446 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2451 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2452 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2454 // Return the record count
2457 } // wxDbTable::Count()
2460 /********** wxDbTable::Refresh() **********/
2461 bool wxDbTable::Refresh(void)
2465 // Switch to the internal cursor so any active cursors are not corrupted
2466 HSTMT currCursor
= GetCursor();
2467 hstmt
= hstmtInternal
;
2468 #if wxODBC_BACKWARD_COMPATABILITY
2469 // Save the where and order by clauses
2470 wxChar
*saveWhere
= where
;
2471 wxChar
*saveOrderBy
= orderBy
;
2473 wxString saveWhere
= where
;
2474 wxString saveOrderBy
= orderBy
;
2476 // Build a where clause to refetch the record with. Try and use the
2477 // ROWID if it's available, ow use the key fields.
2478 wxString whereClause
;
2479 whereClause
.Empty();
2481 if (CanUpdByROWID())
2484 wxChar rowid
[wxDB_ROWID_LEN
+1];
2486 // Get the ROWID value. If not successful retreiving the ROWID,
2487 // simply fall down through the code and build the WHERE clause
2488 // based on the key fields.
2489 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2491 whereClause
+= pDb
->SQLTableName(queryTableName
);
2492 // whereClause += queryTableName;
2493 whereClause
+= wxT(".ROWID = '");
2494 whereClause
+= rowid
;
2495 whereClause
+= wxT("'");
2499 // If unable to use the ROWID, build a where clause from the keyfields
2500 if (wxStrlen(whereClause
) == 0)
2501 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2503 // Requery the record
2504 where
= whereClause
;
2509 if (result
&& !GetNext())
2512 // Switch back to original cursor
2513 SetCursor(&currCursor
);
2515 // Free the internal cursor
2516 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2517 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2519 // Restore the original where and order by clauses
2521 orderBy
= saveOrderBy
;
2525 } // wxDbTable::Refresh()
2528 /********** wxDbTable::SetColNull() **********/
2529 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2533 colDefs
[colNo
].Null
= set
;
2534 if (set
) // Blank out the values in the member variable
2535 ClearMemberVar(colNo
, FALSE
); // Must call with FALSE here, or infinite recursion will happen
2537 setCbValueForColumn(colNo
);
2544 } // wxDbTable::SetColNull()
2547 /********** wxDbTable::SetColNull() **********/
2548 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2551 for (colNo
= 0; colNo
< noCols
; colNo
++)
2553 if (!wxStricmp(colName
, colDefs
[colNo
].ColName
))
2559 colDefs
[colNo
].Null
= set
;
2560 if (set
) // Blank out the values in the member variable
2561 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE here, or infinite recursion will happen
2563 setCbValueForColumn(colNo
);
2570 } // wxDbTable::SetColNull()
2573 /********** wxDbTable::GetNewCursor() **********/
2574 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2576 HSTMT
*newHSTMT
= new HSTMT
;
2581 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2583 pDb
->DispAllErrors(henv
, hdbc
);
2588 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2590 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2597 if (!bindCols(*newHSTMT
))
2605 SetCursor(newHSTMT
);
2609 } // wxDbTable::GetNewCursor()
2612 /********** wxDbTable::DeleteCursor() **********/
2613 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2617 if (!hstmtDel
) // Cursor already deleted
2621 ODBC 3.0 says to use this form
2622 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2625 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2627 pDb
->DispAllErrors(henv
, hdbc
);
2635 } // wxDbTable::DeleteCursor()
2637 //////////////////////////////////////////////////////////////
2638 // wxDbGrid support functions
2639 //////////////////////////////////////////////////////////////
2641 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2643 if (!m_hstmtGridQuery
)
2645 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2646 if (!bindCols(*m_hstmtGridQuery
))
2650 m_rowmode
= rowmode
;
2653 case WX_ROW_MODE_QUERY
:
2654 SetCursor(m_hstmtGridQuery
);
2656 case WX_ROW_MODE_INDIVIDUAL
:
2657 SetCursor(hstmtDefault
);
2662 } // wxDbTable::SetRowMode()
2665 wxVariant
wxDbTable::GetCol(const int colNo
) const
2668 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2670 switch (colDefs
[colNo
].SqlCtype
)
2674 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2678 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2682 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2685 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2688 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2690 case SQL_C_UTINYINT
:
2691 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2694 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2697 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2700 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2702 case SQL_C_TIMESTAMP
:
2703 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2706 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2713 } // wxDbTable::GetCol()
2716 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2718 //FIXME: Add proper wxDateTime support to wxVariant..
2721 SetColNull(colNo
, val
.IsNull());
2725 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2726 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2727 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2729 //Returns null if invalid!
2730 if (!dateval
.ParseDate(val
.GetString()))
2731 SetColNull(colNo
, TRUE
);
2734 switch (colDefs
[colNo
].SqlCtype
)
2738 csstrncpyt((wxChar
*)(colDefs
[colNo
].PtrDataObj
),
2739 val
.GetString().c_str(),
2740 colDefs
[colNo
].SzDataObj
-1);
2744 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2748 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2751 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2754 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2756 case SQL_C_UTINYINT
:
2757 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2760 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2762 //FIXME: Add proper wxDateTime support to wxVariant..
2765 DATE_STRUCT
*dataptr
=
2766 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2768 dataptr
->year
= dateval
.GetYear();
2769 dataptr
->month
= dateval
.GetMonth()+1;
2770 dataptr
->day
= dateval
.GetDay();
2775 TIME_STRUCT
*dataptr
=
2776 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2778 dataptr
->hour
= dateval
.GetHour();
2779 dataptr
->minute
= dateval
.GetMinute();
2780 dataptr
->second
= dateval
.GetSecond();
2783 case SQL_C_TIMESTAMP
:
2785 TIMESTAMP_STRUCT
*dataptr
=
2786 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2787 dataptr
->year
= dateval
.GetYear();
2788 dataptr
->month
= dateval
.GetMonth()+1;
2789 dataptr
->day
= dateval
.GetDay();
2791 dataptr
->hour
= dateval
.GetHour();
2792 dataptr
->minute
= dateval
.GetMinute();
2793 dataptr
->second
= dateval
.GetSecond();
2797 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2802 } // if (!val.IsNull())
2803 } // wxDbTable::SetCol()
2806 GenericKey
wxDbTable::GetKey()
2811 blk
= malloc(m_keysize
);
2812 blkptr
= (wxChar
*) blk
;
2815 for (i
=0; i
< noCols
; i
++)
2817 if (colDefs
[i
].KeyField
)
2819 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2820 blkptr
+= colDefs
[i
].SzDataObj
;
2824 GenericKey k
= GenericKey(blk
, m_keysize
);
2828 } // wxDbTable::GetKey()
2831 void wxDbTable::SetKey(const GenericKey
& k
)
2837 blkptr
= (wxChar
*)blk
;
2840 for (i
=0; i
< noCols
; i
++)
2842 if (colDefs
[i
].KeyField
)
2844 SetColNull(i
, FALSE
);
2845 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2846 blkptr
+= colDefs
[i
].SzDataObj
;
2849 } // wxDbTable::SetKey()
2852 #endif // wxUSE_ODBC