1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implementation of the wxDbTable class.
5 // Modified by: George Tasker
10 // Copyright: (c) 1996 Remstar International, Inc.
11 // Licence: wxWindows licence, plus:
12 // Notice: This class library and its intellectual design are free of charge for use,
13 // modification, enhancement, debugging under the following conditions:
14 // 1) These classes may only be used as part of the implementation of a
15 // wxWindows-based application
16 // 2) All enhancements and bug fixes are to be submitted back to the wxWindows
17 // user groups free of all charges for use with the wxWindows library.
18 // 3) These classes may not be distributed as part of any other class library,
19 // DLL, text (written or electronic), other than a complete distribution of
20 // the wxWindows GUI development toolkit.
21 ///////////////////////////////////////////////////////////////////////////////
28 #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
);
324 TablesInUse
.DeleteContents(TRUE
);
328 pNode
= TablesInUse
.GetFirst();
329 while (pNode
&& !found
)
331 if (((wxTablesInUse
*)pNode
->GetData())->tableID
== tableID
)
334 if (!TablesInUse
.DeleteNode(pNode
))
335 wxLogDebug (s
,wxT("Unable to delete node!"));
338 pNode
= pNode
->GetNext();
343 msg
.Printf(wxT("Unable to find the tableID in the linked\nlist of tables in use.\n\n%s"),s
.c_str());
344 wxLogDebug (msg
,wxT("NOTICE..."));
349 // Decrement the wxDb table count
351 pDb
->decrementTableCount();
353 // Delete memory allocated for column definitions
357 // Free statement handles
363 ODBC 3.0 says to use this form
364 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
366 if (SQLFreeStmt(hstmtInsert
, SQL_DROP
) != SQL_SUCCESS
)
367 pDb
->DispAllErrors(henv
, hdbc
);
373 ODBC 3.0 says to use this form
374 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
376 if (SQLFreeStmt(hstmtDelete
, SQL_DROP
) != SQL_SUCCESS
)
377 pDb
->DispAllErrors(henv
, hdbc
);
383 ODBC 3.0 says to use this form
384 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
386 if (SQLFreeStmt(hstmtUpdate
, SQL_DROP
) != SQL_SUCCESS
)
387 pDb
->DispAllErrors(henv
, hdbc
);
393 if (SQLFreeStmt(hstmtInternal
, SQL_DROP
) != SQL_SUCCESS
)
394 pDb
->DispAllErrors(henv
, hdbc
);
397 // Delete dynamically allocated cursors
399 DeleteCursor(hstmtDefault
);
402 DeleteCursor(hstmtCount
);
404 if (m_hstmtGridQuery
)
405 DeleteCursor(m_hstmtGridQuery
);
407 } // wxDbTable::cleanup()
410 /***************************** PRIVATE FUNCTIONS *****************************/
413 /********** wxDbTable::bindParams() **********/
414 bool wxDbTable::bindParams(bool forUpdate
)
416 wxASSERT(!queryOnly
);
421 SDWORD precision
= 0;
424 // Bind each column of the table that should be bound
425 // to a parameter marker
429 for (i
=0, colNo
=1; i
< noCols
; i
++)
433 if (!colDefs
[i
].Updateable
)
438 if (!colDefs
[i
].InsertAllowed
)
442 switch(colDefs
[i
].DbDataType
)
444 case DB_DATA_TYPE_VARCHAR
:
445 fSqlType
= pDb
->GetTypeInfVarchar().FsqlType
;
446 precision
= colDefs
[i
].SzDataObj
;
449 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
451 colDefs
[i
].CbValue
= SQL_NTS
;
453 case DB_DATA_TYPE_INTEGER
:
454 fSqlType
= pDb
->GetTypeInfInteger().FsqlType
;
455 precision
= pDb
->GetTypeInfInteger().Precision
;
458 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
460 colDefs
[i
].CbValue
= 0;
462 case DB_DATA_TYPE_FLOAT
:
463 fSqlType
= pDb
->GetTypeInfFloat().FsqlType
;
464 precision
= pDb
->GetTypeInfFloat().Precision
;
465 scale
= pDb
->GetTypeInfFloat().MaximumScale
;
466 // SQL Sybase Anywhere v5.5 returned a negative number for the
467 // MaxScale. This caused ODBC to kick out an error on ibscale.
468 // I check for this here and set the scale = precision.
470 // scale = (short) precision;
472 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
474 colDefs
[i
].CbValue
= 0;
476 case DB_DATA_TYPE_DATE
:
477 fSqlType
= pDb
->GetTypeInfDate().FsqlType
;
478 precision
= pDb
->GetTypeInfDate().Precision
;
481 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
483 colDefs
[i
].CbValue
= 0;
485 case DB_DATA_TYPE_BLOB
:
486 fSqlType
= pDb
->GetTypeInfBlob().FsqlType
;
490 colDefs
[i
].CbValue
= SQL_NULL_DATA
;
492 if (colDefs
[i
].SqlCtype
== SQL_C_BINARY
)
493 colDefs
[i
].CbValue
= 0;
494 else if (colDefs
[i
].SqlCtype
== SQL_C_CHAR
)
495 colDefs
[i
].CbValue
= SQL_LEN_DATA_AT_EXEC(0);
497 colDefs
[i
].CbValue
= SQL_LEN_DATA_AT_EXEC(colDefs
[i
].SzDataObj
);
502 if (SQLBindParameter(hstmtUpdate
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
503 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
504 precision
+1, &colDefs
[i
].CbValue
) != SQL_SUCCESS
)
506 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
511 if (SQLBindParameter(hstmtInsert
, colNo
++, SQL_PARAM_INPUT
, colDefs
[i
].SqlCtype
,
512 fSqlType
, precision
, scale
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
513 precision
+1,&colDefs
[i
].CbValue
) != SQL_SUCCESS
)
515 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
520 // Completed successfully
523 } // wxDbTable::bindParams()
526 /********** wxDbTable::bindInsertParams() **********/
527 bool wxDbTable::bindInsertParams(void)
529 return bindParams(FALSE
);
530 } // wxDbTable::bindInsertParams()
533 /********** wxDbTable::bindUpdateParams() **********/
534 bool wxDbTable::bindUpdateParams(void)
536 return bindParams(TRUE
);
537 } // wxDbTable::bindUpdateParams()
540 /********** wxDbTable::bindCols() **********/
541 bool wxDbTable::bindCols(HSTMT cursor
)
545 // Bind each column of the table to a memory address for fetching data
547 for (i
= 0; i
< noCols
; i
++)
549 cb
= colDefs
[i
].CbValue
;
550 if (SQLBindCol(cursor
, (UWORD
)(i
+1), colDefs
[i
].SqlCtype
, (UCHAR
*) colDefs
[i
].PtrDataObj
,
551 colDefs
[i
].SzDataObj
, &cb
) != SQL_SUCCESS
)
552 return (pDb
->DispAllErrors(henv
, hdbc
, cursor
));
555 // Completed successfully
558 } // wxDbTable::bindCols()
561 /********** wxDbTable::getRec() **********/
562 bool wxDbTable::getRec(UWORD fetchType
)
566 if (!pDb
->FwdOnlyCursors())
568 // Fetch the NEXT, PREV, FIRST or LAST record, depending on fetchType
572 retcode
= SQLExtendedFetch(hstmt
, fetchType
, 0, &cRowsFetched
, &rowStatus
);
573 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
575 if (retcode
== SQL_NO_DATA_FOUND
)
578 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
582 // Set the Null member variable to indicate the Null state
583 // of each column just read in.
585 for (i
= 0; i
< noCols
; i
++)
586 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
591 // Fetch the next record from the record set
592 retcode
= SQLFetch(hstmt
);
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
< noCols
; i
++)
606 colDefs
[i
].Null
= (colDefs
[i
].CbValue
== SQL_NULL_DATA
);
610 // Completed successfully
613 } // wxDbTable::getRec()
616 /********** wxDbTable::execDelete() **********/
617 bool wxDbTable::execDelete(const wxString
&pSqlStmt
)
621 // Execute the DELETE statement
622 retcode
= SQLExecDirect(hstmtDelete
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
624 if (retcode
== SQL_SUCCESS
||
625 retcode
== SQL_NO_DATA_FOUND
||
626 retcode
== SQL_SUCCESS_WITH_INFO
)
628 // Record deleted successfully
632 // Problem deleting record
633 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
635 } // wxDbTable::execDelete()
638 /********** wxDbTable::execUpdate() **********/
639 bool wxDbTable::execUpdate(const wxString
&pSqlStmt
)
643 // Execute the UPDATE statement
644 retcode
= SQLExecDirect(hstmtUpdate
, (SQLTCHAR FAR
*) pSqlStmt
.c_str(), SQL_NTS
);
646 if (retcode
== SQL_SUCCESS
||
647 retcode
== SQL_NO_DATA_FOUND
||
648 retcode
== SQL_SUCCESS_WITH_INFO
)
650 // Record updated successfully
653 else if (retcode
== SQL_NEED_DATA
)
656 retcode
= SQLParamData(hstmtUpdate
, &pParmID
);
657 while (retcode
== SQL_NEED_DATA
)
659 // Find the parameter
661 for (i
=0; i
< noCols
; i
++)
663 if (colDefs
[i
].PtrDataObj
== pParmID
)
665 // We found it. Store the parameter.
666 retcode
= SQLPutData(hstmtUpdate
, pParmID
, colDefs
[i
].SzDataObj
);
667 if (retcode
!= SQL_SUCCESS
)
669 pDb
->DispNextError();
670 return pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
);
676 if (retcode
== SQL_SUCCESS
||
677 retcode
== SQL_NO_DATA_FOUND
||
678 retcode
== SQL_SUCCESS_WITH_INFO
)
680 // Record updated successfully
685 // Problem updating record
686 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
688 } // wxDbTable::execUpdate()
691 /********** wxDbTable::query() **********/
692 bool wxDbTable::query(int queryType
, bool forUpdate
, bool distinct
, const wxString
&pSqlStmt
)
697 // The user may wish to select for update, but the DBMS may not be capable
698 selectForUpdate
= CanSelectForUpdate();
700 selectForUpdate
= FALSE
;
702 // Set the SQL SELECT string
703 if (queryType
!= DB_SELECT_STATEMENT
) // A select statement was not passed in,
704 { // so generate a select statement.
705 BuildSelectStmt(sqlStmt
, queryType
, distinct
);
706 pDb
->WriteSqlLog(sqlStmt
);
709 // Make sure the cursor is closed first
710 if (!CloseCursor(hstmt
))
713 // Execute the SQL SELECT statement
715 retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) (queryType
== DB_SELECT_STATEMENT
? pSqlStmt
.c_str() : sqlStmt
.c_str()), SQL_NTS
);
716 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
717 return(pDb
->DispAllErrors(henv
, hdbc
, hstmt
));
719 // Completed successfully
722 } // wxDbTable::query()
725 /***************************** PUBLIC FUNCTIONS *****************************/
728 /********** wxDbTable::Open() **********/
729 bool wxDbTable::Open(bool checkPrivileges
, bool checkTableExists
)
739 // Calculate the maximum size of the concatenated
740 // keys for use with wxDbGrid
742 for (i
=0; i
< noCols
; i
++)
744 if (colDefs
[i
].KeyField
)
747 m_keysize
+= colDefs
[i
].SzDataObj
;
752 // Verify that the table exists in the database
753 if (checkTableExists
&& !pDb
->TableExists(tableName
, pDb
->GetUsername(), tablePath
))
755 s
= wxT("Table/view does not exist in the database");
756 if ( *(pDb
->dbInf
.accessibleTables
) == wxT('Y'))
757 s
+= wxT(", or you have no permissions.\n");
761 else if (checkPrivileges
)
763 // Verify the user has rights to access the table.
764 // Shortcut boolean evaluation to optimize out call to
767 // Unfortunately this optimization doesn't seem to be
769 if (// *(pDb->dbInf.accessibleTables) == 'N' &&
770 !pDb
->TablePrivileges(tableName
,wxT("SELECT"), pDb
->GetUsername(), pDb
->GetUsername(), tablePath
))
771 s
= wxT("Current logged in user does not have sufficient privileges to access this table.\n");
778 if (!tablePath
.IsEmpty())
779 p
.Printf(wxT("Error opening '%s/%s'.\n"),tablePath
.c_str(),tableName
.c_str());
781 p
.Printf(wxT("Error opening '%s'.\n"), tableName
.c_str());
784 pDb
->LogError(p
.GetData());
789 // Bind the member variables for field exchange between
790 // the wxDbTable object and the ODBC record.
793 if (!bindInsertParams()) // Inserts
796 if (!bindUpdateParams()) // Updates
800 if (!bindCols(*hstmtDefault
)) // Selects
803 if (!bindCols(hstmtInternal
)) // Internal use only
807 * Do NOT bind the hstmtCount cursor!!!
810 // Build an insert statement using parameter markers
811 if (!queryOnly
&& noCols
> 0)
813 bool needComma
= FALSE
;
814 sqlStmt
.Printf(wxT("INSERT INTO %s ("),
815 pDb
->SQLTableName(tableName
.c_str()).c_str());
816 for (i
= 0; i
< noCols
; i
++)
818 if (! colDefs
[i
].InsertAllowed
)
822 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
823 // sqlStmt += colDefs[i].ColName;
827 sqlStmt
+= wxT(") VALUES (");
829 int insertableCount
= 0;
831 for (i
= 0; i
< noCols
; i
++)
833 if (! colDefs
[i
].InsertAllowed
)
843 // Prepare the insert statement for execution
846 if (SQLPrepare(hstmtInsert
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
847 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
853 // Completed successfully
856 } // wxDbTable::Open()
859 /********** wxDbTable::Query() **********/
860 bool wxDbTable::Query(bool forUpdate
, bool distinct
)
863 return(query(DB_SELECT_WHERE
, forUpdate
, distinct
));
865 } // wxDbTable::Query()
868 /********** wxDbTable::QueryBySqlStmt() **********/
869 bool wxDbTable::QueryBySqlStmt(const wxString
&pSqlStmt
)
871 pDb
->WriteSqlLog(pSqlStmt
);
873 return(query(DB_SELECT_STATEMENT
, FALSE
, FALSE
, pSqlStmt
));
875 } // wxDbTable::QueryBySqlStmt()
878 /********** wxDbTable::QueryMatching() **********/
879 bool wxDbTable::QueryMatching(bool forUpdate
, bool distinct
)
882 return(query(DB_SELECT_MATCHING
, forUpdate
, distinct
));
884 } // wxDbTable::QueryMatching()
887 /********** wxDbTable::QueryOnKeyFields() **********/
888 bool wxDbTable::QueryOnKeyFields(bool forUpdate
, bool distinct
)
891 return(query(DB_SELECT_KEYFIELDS
, forUpdate
, distinct
));
893 } // wxDbTable::QueryOnKeyFields()
896 /********** wxDbTable::GetPrev() **********/
897 bool wxDbTable::GetPrev(void)
899 if (pDb
->FwdOnlyCursors())
901 wxFAIL_MSG(wxT("GetPrev()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
905 return(getRec(SQL_FETCH_PRIOR
));
907 } // wxDbTable::GetPrev()
910 /********** wxDbTable::operator-- **********/
911 bool wxDbTable::operator--(int)
913 if (pDb
->FwdOnlyCursors())
915 wxFAIL_MSG(wxT("operator--:Backward scrolling cursors are not enabled for this instance of wxDbTable"));
919 return(getRec(SQL_FETCH_PRIOR
));
921 } // wxDbTable::operator--
924 /********** wxDbTable::GetFirst() **********/
925 bool wxDbTable::GetFirst(void)
927 if (pDb
->FwdOnlyCursors())
929 wxFAIL_MSG(wxT("GetFirst():Backward scrolling cursors are not enabled for this instance of wxDbTable"));
933 return(getRec(SQL_FETCH_FIRST
));
935 } // wxDbTable::GetFirst()
938 /********** wxDbTable::GetLast() **********/
939 bool wxDbTable::GetLast(void)
941 if (pDb
->FwdOnlyCursors())
943 wxFAIL_MSG(wxT("GetLast()::Backward scrolling cursors are not enabled for this instance of wxDbTable"));
947 return(getRec(SQL_FETCH_LAST
));
949 } // wxDbTable::GetLast()
952 /********** wxDbTable::BuildDeleteStmt() **********/
953 void wxDbTable::BuildDeleteStmt(wxString
&pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
955 wxASSERT(!queryOnly
);
959 wxString whereClause
;
963 // Handle the case of DeleteWhere() and the where clause is blank. It should
964 // delete all records from the database in this case.
965 if (typeOfDel
== DB_DEL_WHERE
&& (pWhereClause
.Length() == 0))
967 pSqlStmt
.Printf(wxT("DELETE FROM %s"),
968 pDb
->SQLTableName(tableName
.c_str()).c_str());
972 pSqlStmt
.Printf(wxT("DELETE FROM %s WHERE "),
973 pDb
->SQLTableName(tableName
.c_str()).c_str());
975 // Append the WHERE clause to the SQL DELETE statement
978 case DB_DEL_KEYFIELDS
:
979 // If the datasource supports the ROWID column, build
980 // the where on ROWID for efficiency purposes.
981 // e.g. DELETE FROM PARTS WHERE ROWID = '111.222.333'
985 wxChar rowid
[wxDB_ROWID_LEN
+1];
987 // Get the ROWID value. If not successful retreiving the ROWID,
988 // simply fall down through the code and build the WHERE clause
989 // based on the key fields.
990 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
992 pSqlStmt
+= wxT("ROWID = '");
994 pSqlStmt
+= wxT("'");
998 // Unable to delete by ROWID, so build a WHERE
999 // clause based on the keyfields.
1000 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1001 pSqlStmt
+= whereClause
;
1004 pSqlStmt
+= pWhereClause
;
1006 case DB_DEL_MATCHING
:
1007 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1008 pSqlStmt
+= whereClause
;
1012 } // BuildDeleteStmt()
1015 /***** DEPRECATED: use wxDbTable::BuildDeleteStmt(wxString &....) form *****/
1016 void wxDbTable::BuildDeleteStmt(wxChar
*pSqlStmt
, int typeOfDel
, const wxString
&pWhereClause
)
1018 wxString tempSqlStmt
;
1019 BuildDeleteStmt(tempSqlStmt
, typeOfDel
, pWhereClause
);
1020 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1021 } // wxDbTable::BuildDeleteStmt()
1024 /********** wxDbTable::BuildSelectStmt() **********/
1025 void wxDbTable::BuildSelectStmt(wxString
&pSqlStmt
, int typeOfSelect
, bool distinct
)
1027 wxString whereClause
;
1028 whereClause
.Empty();
1030 // Build a select statement to query the database
1031 pSqlStmt
= wxT("SELECT ");
1033 // SELECT DISTINCT values only?
1035 pSqlStmt
+= wxT("DISTINCT ");
1037 // Was a FROM clause specified to join tables to the base table?
1038 // Available for ::Query() only!!!
1039 bool appendFromClause
= FALSE
;
1040 #if wxODBC_BACKWARD_COMPATABILITY
1041 if (typeOfSelect
== DB_SELECT_WHERE
&& from
&& wxStrlen(from
))
1042 appendFromClause
= TRUE
;
1044 if (typeOfSelect
== DB_SELECT_WHERE
&& from
.Length())
1045 appendFromClause
= TRUE
;
1048 // Add the column list
1051 for (i
= 0; i
< noCols
; i
++)
1053 tStr
= colDefs
[i
].ColName
;
1054 // If joining tables, the base table column names must be qualified to avoid ambiguity
1055 if ((appendFromClause
|| pDb
->Dbms() == dbmsACCESS
) && !tStr
.Find(wxT('.')))
1057 pSqlStmt
+= pDb
->SQLTableName(queryTableName
.c_str());
1058 pSqlStmt
+= wxT(".");
1060 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1062 pSqlStmt
+= wxT(",");
1065 // If the datasource supports ROWID, get this column as well. Exception: Don't retrieve
1066 // the ROWID if querying distinct records. The rowid will always be unique.
1067 if (!distinct
&& CanUpdByROWID())
1069 // If joining tables, the base table column names must be qualified to avoid ambiguity
1070 if (appendFromClause
|| pDb
->Dbms() == dbmsACCESS
)
1072 pSqlStmt
+= wxT(",");
1073 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1074 // pSqlStmt += queryTableName;
1075 pSqlStmt
+= wxT(".ROWID");
1078 pSqlStmt
+= wxT(",ROWID");
1081 // Append the FROM tablename portion
1082 pSqlStmt
+= wxT(" FROM ");
1083 pSqlStmt
+= pDb
->SQLTableName(queryTableName
);
1084 // pSqlStmt += queryTableName;
1086 // Sybase uses the HOLDLOCK keyword to lock a record during query.
1087 // The HOLDLOCK keyword follows the table name in the from clause.
1088 // Each table in the from clause must specify HOLDLOCK or
1089 // NOHOLDLOCK (the default). Note: The "FOR UPDATE" clause
1090 // is parsed but ignored in SYBASE Transact-SQL.
1091 if (selectForUpdate
&& (pDb
->Dbms() == dbmsSYBASE_ASA
|| pDb
->Dbms() == dbmsSYBASE_ASE
))
1092 pSqlStmt
+= wxT(" HOLDLOCK");
1094 if (appendFromClause
)
1097 // Append the WHERE clause. Either append the where clause for the class
1098 // or build a where clause. The typeOfSelect determines this.
1099 switch(typeOfSelect
)
1101 case DB_SELECT_WHERE
:
1102 #if wxODBC_BACKWARD_COMPATABILITY
1103 if (where
&& wxStrlen(where
)) // May not want a where clause!!!
1105 if (where
.Length()) // May not want a where clause!!!
1108 pSqlStmt
+= wxT(" WHERE ");
1112 case DB_SELECT_KEYFIELDS
:
1113 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1114 if (whereClause
.Length())
1116 pSqlStmt
+= wxT(" WHERE ");
1117 pSqlStmt
+= whereClause
;
1120 case DB_SELECT_MATCHING
:
1121 BuildWhereClause(whereClause
, DB_WHERE_MATCHING
);
1122 if (whereClause
.Length())
1124 pSqlStmt
+= wxT(" WHERE ");
1125 pSqlStmt
+= whereClause
;
1130 // Append the ORDER BY clause
1131 #if wxODBC_BACKWARD_COMPATABILITY
1132 if (orderBy
&& wxStrlen(orderBy
))
1134 if (orderBy
.Length())
1137 pSqlStmt
+= wxT(" ORDER BY ");
1138 pSqlStmt
+= orderBy
;
1141 // SELECT FOR UPDATE if told to do so and the datasource is capable. Sybase
1142 // parses the FOR UPDATE clause but ignores it. See the comment above on the
1143 // HOLDLOCK for Sybase.
1144 if (selectForUpdate
&& CanSelectForUpdate())
1145 pSqlStmt
+= wxT(" FOR UPDATE");
1147 } // wxDbTable::BuildSelectStmt()
1150 /***** DEPRECATED: use wxDbTable::BuildSelectStmt(wxString &....) form *****/
1151 void wxDbTable::BuildSelectStmt(wxChar
*pSqlStmt
, int typeOfSelect
, bool distinct
)
1153 wxString tempSqlStmt
;
1154 BuildSelectStmt(tempSqlStmt
, typeOfSelect
, distinct
);
1155 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1156 } // wxDbTable::BuildSelectStmt()
1159 /********** wxDbTable::BuildUpdateStmt() **********/
1160 void wxDbTable::BuildUpdateStmt(wxString
&pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1162 wxASSERT(!queryOnly
);
1166 wxString whereClause
;
1167 whereClause
.Empty();
1169 bool firstColumn
= TRUE
;
1171 pSqlStmt
.Printf(wxT("UPDATE %s SET "),
1172 pDb
->SQLTableName(tableName
.c_str()).c_str());
1174 // Append a list of columns to be updated
1176 for (i
= 0; i
< noCols
; i
++)
1178 // Only append Updateable columns
1179 if (colDefs
[i
].Updateable
)
1182 pSqlStmt
+= wxT(",");
1184 firstColumn
= FALSE
;
1186 pSqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1187 // pSqlStmt += colDefs[i].ColName;
1188 pSqlStmt
+= wxT(" = ?");
1192 // Append the WHERE clause to the SQL UPDATE statement
1193 pSqlStmt
+= wxT(" WHERE ");
1196 case DB_UPD_KEYFIELDS
:
1197 // If the datasource supports the ROWID column, build
1198 // the where on ROWID for efficiency purposes.
1199 // e.g. UPDATE PARTS SET Col1 = ?, Col2 = ? WHERE ROWID = '111.222.333'
1200 if (CanUpdByROWID())
1203 wxChar rowid
[wxDB_ROWID_LEN
+1];
1205 // Get the ROWID value. If not successful retreiving the ROWID,
1206 // simply fall down through the code and build the WHERE clause
1207 // based on the key fields.
1208 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
1210 pSqlStmt
+= wxT("ROWID = '");
1212 pSqlStmt
+= wxT("'");
1216 // Unable to delete by ROWID, so build a WHERE
1217 // clause based on the keyfields.
1218 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
);
1219 pSqlStmt
+= whereClause
;
1222 pSqlStmt
+= pWhereClause
;
1225 } // BuildUpdateStmt()
1228 /***** DEPRECATED: use wxDbTable::BuildUpdateStmt(wxString &....) form *****/
1229 void wxDbTable::BuildUpdateStmt(wxChar
*pSqlStmt
, int typeOfUpd
, const wxString
&pWhereClause
)
1231 wxString tempSqlStmt
;
1232 BuildUpdateStmt(tempSqlStmt
, typeOfUpd
, pWhereClause
);
1233 wxStrcpy(pSqlStmt
, tempSqlStmt
);
1234 } // BuildUpdateStmt()
1237 /********** wxDbTable::BuildWhereClause() **********/
1238 void wxDbTable::BuildWhereClause(wxString
&pWhereClause
, int typeOfWhere
,
1239 const wxString
&qualTableName
, bool useLikeComparison
)
1241 * Note: BuildWhereClause() currently ignores timestamp columns.
1242 * They are not included as part of the where clause.
1245 bool moreThanOneColumn
= FALSE
;
1248 // Loop through the columns building a where clause as you go
1250 for (colNo
= 0; colNo
< noCols
; colNo
++)
1252 // Determine if this column should be included in the WHERE clause
1253 if ((typeOfWhere
== DB_WHERE_KEYFIELDS
&& colDefs
[colNo
].KeyField
) ||
1254 (typeOfWhere
== DB_WHERE_MATCHING
&& (!IsColNull(colNo
))))
1256 // Skip over timestamp columns
1257 if (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
)
1259 // If there is more than 1 column, join them with the keyword "AND"
1260 if (moreThanOneColumn
)
1261 pWhereClause
+= wxT(" AND ");
1263 moreThanOneColumn
= TRUE
;
1265 // Concatenate where phrase for the column
1266 wxString tStr
= colDefs
[colNo
].ColName
;
1268 if (qualTableName
.Length() && !tStr
.Find(wxT('.')))
1270 pWhereClause
+= pDb
->SQLTableName(qualTableName
);
1271 pWhereClause
+= wxT(".");
1273 pWhereClause
+= pDb
->SQLColumnName(colDefs
[colNo
].ColName
);
1275 if (useLikeComparison
&& (colDefs
[colNo
].SqlCtype
== SQL_C_CHAR
))
1276 pWhereClause
+= wxT(" LIKE ");
1278 pWhereClause
+= wxT(" = ");
1280 switch(colDefs
[colNo
].SqlCtype
)
1283 colValue
.Printf(wxT("'%s'"), (UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
);
1286 colValue
.Printf(wxT("%hi"), *((SWORD
*) colDefs
[colNo
].PtrDataObj
));
1289 colValue
.Printf(wxT("%hu"), *((UWORD
*) colDefs
[colNo
].PtrDataObj
));
1292 colValue
.Printf(wxT("%li"), *((SDWORD
*) colDefs
[colNo
].PtrDataObj
));
1295 colValue
.Printf(wxT("%lu"), *((UDWORD
*) colDefs
[colNo
].PtrDataObj
));
1298 colValue
.Printf(wxT("%.6f"), *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
));
1301 colValue
.Printf(wxT("%.6f"), *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
));
1304 pWhereClause
+= colValue
;
1307 } // wxDbTable::BuildWhereClause()
1310 /***** DEPRECATED: use wxDbTable::BuildWhereClause(wxString &....) form *****/
1311 void wxDbTable::BuildWhereClause(wxChar
*pWhereClause
, int typeOfWhere
,
1312 const wxString
&qualTableName
, bool useLikeComparison
)
1314 wxString tempSqlStmt
;
1315 BuildWhereClause(tempSqlStmt
, typeOfWhere
, qualTableName
, useLikeComparison
);
1316 wxStrcpy(pWhereClause
, tempSqlStmt
);
1317 } // wxDbTable::BuildWhereClause()
1320 /********** wxDbTable::GetRowNum() **********/
1321 UWORD
wxDbTable::GetRowNum(void)
1325 if (SQLGetStmtOption(hstmt
, SQL_ROW_NUMBER
, (UCHAR
*) &rowNum
) != SQL_SUCCESS
)
1327 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1331 // Completed successfully
1332 return((UWORD
) rowNum
);
1334 } // wxDbTable::GetRowNum()
1337 /********** wxDbTable::CloseCursor() **********/
1338 bool wxDbTable::CloseCursor(HSTMT cursor
)
1340 if (SQLFreeStmt(cursor
, SQL_CLOSE
) != SQL_SUCCESS
)
1341 return(pDb
->DispAllErrors(henv
, hdbc
, cursor
));
1343 // Completed successfully
1346 } // wxDbTable::CloseCursor()
1349 /********** wxDbTable::CreateTable() **********/
1350 bool wxDbTable::CreateTable(bool attemptDrop
)
1358 #ifdef DBDEBUG_CONSOLE
1359 cout
<< wxT("Creating Table ") << tableName
<< wxT("...") << endl
;
1363 if (attemptDrop
&& !DropTable())
1367 #ifdef DBDEBUG_CONSOLE
1368 for (i
= 0; i
< noCols
; i
++)
1370 // Exclude derived columns since they are NOT part of the base table
1371 if (colDefs
[i
].DerivedCol
)
1373 cout
<< i
+ 1 << wxT(": ") << colDefs
[i
].ColName
<< wxT("; ");
1374 switch(colDefs
[i
].DbDataType
)
1376 case DB_DATA_TYPE_VARCHAR
:
1377 cout
<< pDb
->GetTypeInfVarchar().TypeName
<< wxT("(") << colDefs
[i
].SzDataObj
<< wxT(")");
1379 case DB_DATA_TYPE_INTEGER
:
1380 cout
<< pDb
->GetTypeInfInteger().TypeName
;
1382 case DB_DATA_TYPE_FLOAT
:
1383 cout
<< pDb
->GetTypeInfFloat().TypeName
;
1385 case DB_DATA_TYPE_DATE
:
1386 cout
<< pDb
->GetTypeInfDate().TypeName
;
1388 case DB_DATA_TYPE_BLOB
:
1389 cout
<< pDb
->GetTypeInfBlob().TypeName
;
1396 // Build a CREATE TABLE string from the colDefs structure.
1397 bool needComma
= FALSE
;
1399 sqlStmt
.Printf(wxT("CREATE TABLE %s ("),
1400 pDb
->SQLTableName(tableName
.c_str()).c_str());
1402 for (i
= 0; i
< noCols
; i
++)
1404 // Exclude derived columns since they are NOT part of the base table
1405 if (colDefs
[i
].DerivedCol
)
1409 sqlStmt
+= wxT(",");
1411 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1412 // sqlStmt += colDefs[i].ColName;
1413 sqlStmt
+= wxT(" ");
1415 switch(colDefs
[i
].DbDataType
)
1417 case DB_DATA_TYPE_VARCHAR
:
1418 sqlStmt
+= pDb
->GetTypeInfVarchar().TypeName
;
1420 case DB_DATA_TYPE_INTEGER
:
1421 sqlStmt
+= pDb
->GetTypeInfInteger().TypeName
;
1423 case DB_DATA_TYPE_FLOAT
:
1424 sqlStmt
+= pDb
->GetTypeInfFloat().TypeName
;
1426 case DB_DATA_TYPE_DATE
:
1427 sqlStmt
+= pDb
->GetTypeInfDate().TypeName
;
1429 case DB_DATA_TYPE_BLOB
:
1430 sqlStmt
+= pDb
->GetTypeInfBlob().TypeName
;
1433 // For varchars, append the size of the string
1434 if (colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
&&
1435 (pDb
->Dbms() != dbmsMY_SQL
|| pDb
->GetTypeInfVarchar().TypeName
!= _T("text")))// ||
1436 // colDefs[i].DbDataType == DB_DATA_TYPE_BLOB)
1439 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1443 if (pDb
->Dbms() == dbmsDB2
||
1444 pDb
->Dbms() == dbmsMY_SQL
||
1445 pDb
->Dbms() == dbmsSYBASE_ASE
||
1446 pDb
->Dbms() == dbmsINTERBASE
||
1447 pDb
->Dbms() == dbmsMS_SQL_SERVER
)
1449 if (colDefs
[i
].KeyField
)
1451 sqlStmt
+= wxT(" NOT NULL");
1457 // If there is a primary key defined, include it in the create statement
1458 for (i
= j
= 0; i
< noCols
; i
++)
1460 if (colDefs
[i
].KeyField
)
1466 if ( j
&& (pDb
->Dbms() != dbmsDBASE
)
1467 && (pDb
->Dbms() != dbmsXBASE_SEQUITER
) ) // Found a keyfield
1469 switch (pDb
->Dbms())
1473 case dbmsSYBASE_ASA
:
1474 case dbmsSYBASE_ASE
:
1477 // MySQL goes out on this one. We also declare the relevant key NON NULL above
1478 sqlStmt
+= wxT(",PRIMARY KEY (");
1483 sqlStmt
+= wxT(",CONSTRAINT ");
1484 // DB2 is limited to 18 characters for index names
1485 if (pDb
->Dbms() == dbmsDB2
)
1487 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."));
1488 sqlStmt
+= pDb
->SQLTableName(tableName
.substr(0, 13).c_str());
1489 // sqlStmt += tableName.substr(0, 13);
1492 sqlStmt
+= pDb
->SQLTableName(tableName
.c_str());
1493 // sqlStmt += tableName;
1495 sqlStmt
+= wxT("_PIDX PRIMARY KEY (");
1500 // List column name(s) of column(s) comprising the primary key
1501 for (i
= j
= 0; i
< noCols
; i
++)
1503 if (colDefs
[i
].KeyField
)
1505 if (j
++) // Multi part key, comma separate names
1506 sqlStmt
+= wxT(",");
1507 sqlStmt
+= pDb
->SQLColumnName(colDefs
[i
].ColName
);
1509 if (pDb
->Dbms() == dbmsMY_SQL
&&
1510 colDefs
[i
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1513 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1518 sqlStmt
+= wxT(")");
1520 if (pDb
->Dbms() == dbmsINFORMIX
||
1521 pDb
->Dbms() == dbmsSYBASE_ASA
||
1522 pDb
->Dbms() == dbmsSYBASE_ASE
)
1524 sqlStmt
+= wxT(" CONSTRAINT ");
1525 sqlStmt
+= pDb
->SQLTableName(tableName
);
1526 // sqlStmt += tableName;
1527 sqlStmt
+= wxT("_PIDX");
1530 // Append the closing parentheses for the create table statement
1531 sqlStmt
+= wxT(")");
1533 pDb
->WriteSqlLog(sqlStmt
);
1535 #ifdef DBDEBUG_CONSOLE
1536 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1539 // Execute the CREATE TABLE statement
1540 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1541 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
)
1543 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1544 pDb
->RollbackTrans();
1549 // Commit the transaction and close the cursor
1550 if (!pDb
->CommitTrans())
1552 if (!CloseCursor(hstmt
))
1555 // Database table created successfully
1558 } // wxDbTable::CreateTable()
1561 /********** wxDbTable::DropTable() **********/
1562 bool wxDbTable::DropTable()
1564 // NOTE: This function returns TRUE if the Table does not exist, but
1565 // only for identified databases. Code will need to be added
1566 // below for any other databases when those databases are defined
1567 // to handle this situation consistently
1571 sqlStmt
.Printf(wxT("DROP TABLE %s"),
1572 pDb
->SQLTableName(tableName
.c_str()).c_str());
1574 pDb
->WriteSqlLog(sqlStmt
);
1576 #ifdef DBDEBUG_CONSOLE
1577 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1580 RETCODE retcode
= SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
);
1581 if (retcode
!= SQL_SUCCESS
)
1583 // Check for "Base table not found" error and ignore
1584 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1585 if (wxStrcmp(pDb
->sqlState
, wxT("S0002")) /*&&
1586 wxStrcmp(pDb->sqlState, wxT("S1000"))*/) // "Base table not found"
1588 // Check for product specific error codes
1589 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // 5.x (and lower?)
1590 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1591 (pDb
->Dbms() == dbmsPERVASIVE_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) || // Returns an S1000 then an S0002
1592 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))))
1594 pDb
->DispNextError();
1595 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1596 pDb
->RollbackTrans();
1597 // CloseCursor(hstmt);
1603 // Commit the transaction and close the cursor
1604 if (! pDb
->CommitTrans())
1606 if (! CloseCursor(hstmt
))
1610 } // wxDbTable::DropTable()
1613 /********** wxDbTable::CreateIndex() **********/
1614 bool wxDbTable::CreateIndex(const wxString
&idxName
, bool unique
, UWORD noIdxCols
,
1615 wxDbIdxDef
*pIdxDefs
, bool attemptDrop
)
1619 // Drop the index first
1620 if (attemptDrop
&& !DropIndex(idxName
))
1623 // MySQL (and possibly Sybase ASE?? - gt) require that any columns which are used as portions
1624 // of an index have the columns defined as "NOT NULL". During initial table creation though,
1625 // it may not be known which columns are necessarily going to be part of an index (e.g. the
1626 // table was created, then months later you determine that an additional index while
1627 // give better performance, so you want to add an index).
1629 // The following block of code will modify the column definition to make the column be
1630 // defined with the "NOT NULL" qualifier.
1631 if (pDb
->Dbms() == dbmsMY_SQL
)
1636 for (i
= 0; i
< noIdxCols
&& ok
; i
++)
1640 // Find the column definition that has the ColName that matches the
1641 // index column name. We need to do this to get the DB_DATA_TYPE of
1642 // the index column, as MySQL's syntax for the ALTER column requires
1644 while (!found
&& (j
< this->noCols
))
1646 if (wxStrcmp(colDefs
[j
].ColName
,pIdxDefs
[i
].ColName
) == 0)
1654 ok
= pDb
->ModifyColumn(tableName
, pIdxDefs
[i
].ColName
,
1655 colDefs
[j
].DbDataType
, colDefs
[j
].SzDataObj
,
1661 // retcode is not used
1662 wxODBC_ERRORS retcode
;
1663 // Oracle returns a DB_ERR_GENERAL_ERROR if the column is already
1664 // defined to be NOT NULL, but reportedly MySQL doesn't mind.
1665 // This line is just here for debug checking of the value
1666 retcode
= (wxODBC_ERRORS
)pDb
->DB_STATUS
;
1677 pDb
->RollbackTrans();
1682 // Build a CREATE INDEX statement
1683 sqlStmt
= wxT("CREATE ");
1685 sqlStmt
+= wxT("UNIQUE ");
1687 sqlStmt
+= wxT("INDEX ");
1688 sqlStmt
+= pDb
->SQLTableName(idxName
);
1689 sqlStmt
+= wxT(" ON ");
1691 sqlStmt
+= pDb
->SQLTableName(tableName
);
1692 // sqlStmt += tableName;
1693 sqlStmt
+= wxT(" (");
1695 // Append list of columns making up index
1697 for (i
= 0; i
< noIdxCols
; i
++)
1699 sqlStmt
+= pDb
->SQLColumnName(pIdxDefs
[i
].ColName
);
1700 // sqlStmt += pIdxDefs[i].ColName;
1702 // MySQL requires a key length on VARCHAR keys
1703 if ( pDb
->Dbms() == dbmsMY_SQL
)
1705 // Find the details on this column
1707 for ( j
= 0; j
< noCols
; ++j
)
1709 if ( wxStrcmp( pIdxDefs
[i
].ColName
, colDefs
[j
].ColName
) == 0 )
1714 if ( colDefs
[j
].DbDataType
== DB_DATA_TYPE_VARCHAR
)
1717 s
.Printf(wxT("(%d)"), colDefs
[i
].SzDataObj
);
1722 // Postgres and SQL Server 7 do not support the ASC/DESC keywords for index columns
1723 if (!((pDb
->Dbms() == dbmsMS_SQL_SERVER
) && (wxStrncmp(pDb
->dbInf
.dbmsVer
,_T("07"),2)==0)) &&
1724 !(pDb
->Dbms() == dbmsPOSTGRES
))
1726 if (pIdxDefs
[i
].Ascending
)
1727 sqlStmt
+= wxT(" ASC");
1729 sqlStmt
+= wxT(" DESC");
1732 wxASSERT_MSG(pIdxDefs
[i
].Ascending
, _T("Datasource does not support DESCending index columns"));
1734 if ((i
+ 1) < noIdxCols
)
1735 sqlStmt
+= wxT(",");
1738 // Append closing parentheses
1739 sqlStmt
+= wxT(")");
1741 pDb
->WriteSqlLog(sqlStmt
);
1743 #ifdef DBDEBUG_CONSOLE
1744 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1747 // Execute the CREATE INDEX statement
1748 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1750 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1751 pDb
->RollbackTrans();
1756 // Commit the transaction and close the cursor
1757 if (! pDb
->CommitTrans())
1759 if (! CloseCursor(hstmt
))
1762 // Index Created Successfully
1765 } // wxDbTable::CreateIndex()
1768 /********** wxDbTable::DropIndex() **********/
1769 bool wxDbTable::DropIndex(const wxString
&idxName
)
1771 // NOTE: This function returns TRUE if the Index does not exist, but
1772 // only for identified databases. Code will need to be added
1773 // below for any other databases when those databases are defined
1774 // to handle this situation consistently
1778 if (pDb
->Dbms() == dbmsACCESS
|| pDb
->Dbms() == dbmsMY_SQL
||
1779 pDb
->Dbms() == dbmsDBASE
/*|| Paradox needs this syntax too when we add support*/)
1780 sqlStmt
.Printf(wxT("DROP INDEX %s ON %s"),
1781 pDb
->SQLTableName(idxName
.c_str()).c_str(),
1782 pDb
->SQLTableName(tableName
.c_str()).c_str());
1783 else if ((pDb
->Dbms() == dbmsMS_SQL_SERVER
) ||
1784 (pDb
->Dbms() == dbmsSYBASE_ASE
) ||
1785 (pDb
->Dbms() == dbmsXBASE_SEQUITER
))
1786 sqlStmt
.Printf(wxT("DROP INDEX %s.%s"),
1787 pDb
->SQLTableName(tableName
.c_str()).c_str(),
1788 pDb
->SQLTableName(idxName
.c_str()).c_str());
1790 sqlStmt
.Printf(wxT("DROP INDEX %s"),
1791 pDb
->SQLTableName(idxName
.c_str()).c_str());
1793 pDb
->WriteSqlLog(sqlStmt
);
1795 #ifdef DBDEBUG_CONSOLE
1796 cout
<< endl
<< sqlStmt
.c_str() << endl
;
1799 if (SQLExecDirect(hstmt
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
1801 // Check for "Index not found" error and ignore
1802 pDb
->GetNextError(henv
, hdbc
, hstmt
);
1803 if (wxStrcmp(pDb
->sqlState
,wxT("S0012"))) // "Index not found"
1805 // Check for product specific error codes
1806 if (!((pDb
->Dbms() == dbmsSYBASE_ASA
&& !wxStrcmp(pDb
->sqlState
,wxT("42000"))) || // v5.x (and lower?)
1807 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("37000"))) ||
1808 (pDb
->Dbms() == dbmsMS_SQL_SERVER
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1809 (pDb
->Dbms() == dbmsINTERBASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S1000"))) ||
1810 (pDb
->Dbms() == dbmsSYBASE_ASE
&& !wxStrcmp(pDb
->sqlState
,wxT("S0002"))) || // Base table not found
1811 (pDb
->Dbms() == dbmsMY_SQL
&& !wxStrcmp(pDb
->sqlState
,wxT("42S12"))) || // tested by Christopher Ludwik Marino-Cebulski using v3.23.21beta
1812 (pDb
->Dbms() == dbmsPOSTGRES
&& !wxStrcmp(pDb
->sqlState
,wxT("08S01")))
1815 pDb
->DispNextError();
1816 pDb
->DispAllErrors(henv
, hdbc
, hstmt
);
1817 pDb
->RollbackTrans();
1824 // Commit the transaction and close the cursor
1825 if (! pDb
->CommitTrans())
1827 if (! CloseCursor(hstmt
))
1831 } // wxDbTable::DropIndex()
1834 /********** wxDbTable::SetOrderByColNums() **********/
1835 bool wxDbTable::SetOrderByColNums(UWORD first
, ... )
1837 int colNo
= first
; // using 'int' to be able to look for wxDB_NO_MORE_COLUN_NUMBERS
1843 va_start(argptr
, first
); /* Initialize variable arguments. */
1844 while (!abort
&& (colNo
!= wxDB_NO_MORE_COLUMN_NUMBERS
))
1846 // Make sure the passed in column number
1847 // is within the valid range of columns
1849 // Valid columns are 0 thru noCols-1
1850 if (colNo
>= noCols
|| colNo
< 0)
1857 tempStr
+= wxT(",");
1859 tempStr
+= colDefs
[colNo
].ColName
;
1860 colNo
= va_arg (argptr
, int);
1862 va_end (argptr
); /* Reset variable arguments. */
1864 SetOrderByClause(tempStr
);
1867 } // wxDbTable::SetOrderByColNums()
1870 /********** wxDbTable::Insert() **********/
1871 int wxDbTable::Insert(void)
1873 wxASSERT(!queryOnly
);
1874 if (queryOnly
|| !insertable
)
1879 // Insert the record by executing the already prepared insert statement
1881 retcode
=SQLExecute(hstmtInsert
);
1882 if (retcode
!= SQL_SUCCESS
&& retcode
!= SQL_SUCCESS_WITH_INFO
&&
1883 retcode
!= SQL_NEED_DATA
)
1885 // Check to see if integrity constraint was violated
1886 pDb
->GetNextError(henv
, hdbc
, hstmtInsert
);
1887 if (! wxStrcmp(pDb
->sqlState
, wxT("23000"))) // Integrity constraint violated
1888 return(DB_ERR_INTEGRITY_CONSTRAINT_VIOL
);
1891 pDb
->DispNextError();
1892 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1896 if (retcode
== SQL_NEED_DATA
)
1899 retcode
= SQLParamData(hstmtInsert
, &pParmID
);
1900 while (retcode
== SQL_NEED_DATA
)
1902 // Find the parameter
1904 for (i
=0; i
< noCols
; i
++)
1906 if (colDefs
[i
].PtrDataObj
== pParmID
)
1908 // We found it. Store the parameter.
1909 retcode
= SQLPutData(hstmtInsert
, pParmID
, colDefs
[i
].SzDataObj
);
1910 if (retcode
!= SQL_SUCCESS
)
1912 pDb
->DispNextError();
1913 pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
);
1922 // Record inserted into the datasource successfully
1925 } // wxDbTable::Insert()
1928 /********** wxDbTable::Update() **********/
1929 bool wxDbTable::Update(void)
1931 wxASSERT(!queryOnly
);
1937 // Build the SQL UPDATE statement
1938 BuildUpdateStmt(sqlStmt
, DB_UPD_KEYFIELDS
);
1940 pDb
->WriteSqlLog(sqlStmt
);
1942 #ifdef DBDEBUG_CONSOLE
1943 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1946 // Execute the SQL UPDATE statement
1947 return(execUpdate(sqlStmt
));
1949 } // wxDbTable::Update()
1952 /********** wxDbTable::Update(pSqlStmt) **********/
1953 bool wxDbTable::Update(const wxString
&pSqlStmt
)
1955 wxASSERT(!queryOnly
);
1959 pDb
->WriteSqlLog(pSqlStmt
);
1961 return(execUpdate(pSqlStmt
));
1963 } // wxDbTable::Update(pSqlStmt)
1966 /********** wxDbTable::UpdateWhere() **********/
1967 bool wxDbTable::UpdateWhere(const wxString
&pWhereClause
)
1969 wxASSERT(!queryOnly
);
1975 // Build the SQL UPDATE statement
1976 BuildUpdateStmt(sqlStmt
, DB_UPD_WHERE
, pWhereClause
);
1978 pDb
->WriteSqlLog(sqlStmt
);
1980 #ifdef DBDEBUG_CONSOLE
1981 cout
<< endl
<< sqlStmt
.c_str() << endl
<< endl
;
1984 // Execute the SQL UPDATE statement
1985 return(execUpdate(sqlStmt
));
1987 } // wxDbTable::UpdateWhere()
1990 /********** wxDbTable::Delete() **********/
1991 bool wxDbTable::Delete(void)
1993 wxASSERT(!queryOnly
);
2000 // Build the SQL DELETE statement
2001 BuildDeleteStmt(sqlStmt
, DB_DEL_KEYFIELDS
);
2003 pDb
->WriteSqlLog(sqlStmt
);
2005 // Execute the SQL DELETE statement
2006 return(execDelete(sqlStmt
));
2008 } // wxDbTable::Delete()
2011 /********** wxDbTable::DeleteWhere() **********/
2012 bool wxDbTable::DeleteWhere(const wxString
&pWhereClause
)
2014 wxASSERT(!queryOnly
);
2021 // Build the SQL DELETE statement
2022 BuildDeleteStmt(sqlStmt
, DB_DEL_WHERE
, pWhereClause
);
2024 pDb
->WriteSqlLog(sqlStmt
);
2026 // Execute the SQL DELETE statement
2027 return(execDelete(sqlStmt
));
2029 } // wxDbTable::DeleteWhere()
2032 /********** wxDbTable::DeleteMatching() **********/
2033 bool wxDbTable::DeleteMatching(void)
2035 wxASSERT(!queryOnly
);
2042 // Build the SQL DELETE statement
2043 BuildDeleteStmt(sqlStmt
, DB_DEL_MATCHING
);
2045 pDb
->WriteSqlLog(sqlStmt
);
2047 // Execute the SQL DELETE statement
2048 return(execDelete(sqlStmt
));
2050 } // wxDbTable::DeleteMatching()
2053 /********** wxDbTable::IsColNull() **********/
2054 bool wxDbTable::IsColNull(UWORD colNo
) const
2057 This logic is just not right. It would indicate TRUE
2058 if a numeric field were set to a value of 0.
2060 switch(colDefs[colNo].SqlCtype)
2063 return(((UCHAR FAR *) colDefs[colNo].PtrDataObj)[0] == 0);
2065 return(( *((SWORD *) colDefs[colNo].PtrDataObj)) == 0);
2067 return(( *((UWORD*) colDefs[colNo].PtrDataObj)) == 0);
2069 return(( *((SDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2071 return(( *((UDWORD *) colDefs[colNo].PtrDataObj)) == 0);
2073 return(( *((SFLOAT *) colDefs[colNo].PtrDataObj)) == 0);
2075 return((*((SDOUBLE *) colDefs[colNo].PtrDataObj)) == 0);
2076 case SQL_C_TIMESTAMP:
2077 TIMESTAMP_STRUCT *pDt;
2078 pDt = (TIMESTAMP_STRUCT *) colDefs[colNo].PtrDataObj;
2079 if (pDt->year == 0 && pDt->month == 0 && pDt->day == 0)
2087 return (colDefs
[colNo
].Null
);
2088 } // wxDbTable::IsColNull()
2091 /********** wxDbTable::CanSelectForUpdate() **********/
2092 bool wxDbTable::CanSelectForUpdate(void)
2097 if (pDb
->Dbms() == dbmsMY_SQL
)
2100 if ((pDb
->Dbms() == dbmsORACLE
) ||
2101 (pDb
->dbInf
.posStmts
& SQL_PS_SELECT_FOR_UPDATE
))
2106 } // wxDbTable::CanSelectForUpdate()
2109 /********** wxDbTable::CanUpdByROWID() **********/
2110 bool wxDbTable::CanUpdByROWID(void)
2113 * NOTE: Returning FALSE for now until this can be debugged,
2114 * as the ROWID is not getting updated correctly
2118 if (pDb->Dbms() == dbmsORACLE)
2123 } // wxDbTable::CanUpdByROWID()
2126 /********** wxDbTable::IsCursorClosedOnCommit() **********/
2127 bool wxDbTable::IsCursorClosedOnCommit(void)
2129 if (pDb
->dbInf
.cursorCommitBehavior
== SQL_CB_PRESERVE
)
2134 } // wxDbTable::IsCursorClosedOnCommit()
2138 /********** wxDbTable::ClearMemberVar() **********/
2139 void wxDbTable::ClearMemberVar(UWORD colNo
, bool setToNull
)
2141 wxASSERT(colNo
< noCols
);
2143 switch(colDefs
[colNo
].SqlCtype
)
2146 ((UCHAR FAR
*) colDefs
[colNo
].PtrDataObj
)[0] = 0;
2149 *((SWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2152 *((UWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2155 *((SDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2158 *((UDWORD
*) colDefs
[colNo
].PtrDataObj
) = 0;
2161 *((SFLOAT
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2164 *((SDOUBLE
*) colDefs
[colNo
].PtrDataObj
) = 0.0f
;
2166 case SQL_C_TIMESTAMP
:
2167 TIMESTAMP_STRUCT
*pDt
;
2168 pDt
= (TIMESTAMP_STRUCT
*) colDefs
[colNo
].PtrDataObj
;
2181 } // wxDbTable::ClearMemberVar()
2184 /********** wxDbTable::ClearMemberVars() **********/
2185 void wxDbTable::ClearMemberVars(bool setToNull
)
2189 // Loop through the columns setting each member variable to zero
2190 for (i
=0; i
< noCols
; i
++)
2191 ClearMemberVar(i
,setToNull
);
2193 } // wxDbTable::ClearMemberVars()
2196 /********** wxDbTable::SetQueryTimeout() **********/
2197 bool wxDbTable::SetQueryTimeout(UDWORD nSeconds
)
2199 if (SQLSetStmtOption(hstmtInsert
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2200 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInsert
));
2201 if (SQLSetStmtOption(hstmtUpdate
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2202 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtUpdate
));
2203 if (SQLSetStmtOption(hstmtDelete
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2204 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtDelete
));
2205 if (SQLSetStmtOption(hstmtInternal
, SQL_QUERY_TIMEOUT
, nSeconds
) != SQL_SUCCESS
)
2206 return(pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
));
2208 // Completed Successfully
2211 } // wxDbTable::SetQueryTimeout()
2214 /********** wxDbTable::SetColDefs() **********/
2215 void wxDbTable::SetColDefs(UWORD index
, const wxString
&fieldName
, int dataType
, void *pData
,
2216 SWORD cType
, int size
, bool keyField
, bool upd
,
2217 bool insAllow
, bool derivedCol
)
2219 wxASSERT_MSG( index
< noCols
,
2220 _T("Specified column index exceeds the maximum number of columns for this table.") );
2222 if (!colDefs
) // May happen if the database connection fails
2225 if (fieldName
.Length() > (unsigned int) DB_MAX_COLUMN_NAME_LEN
)
2227 wxStrncpy(colDefs
[index
].ColName
, fieldName
, DB_MAX_COLUMN_NAME_LEN
);
2228 colDefs
[index
].ColName
[DB_MAX_COLUMN_NAME_LEN
] = 0;
2232 tmpMsg
.Printf(_T("Column name '%s' is too long. Truncated to '%s'."),
2233 fieldName
.c_str(),colDefs
[index
].ColName
);
2235 #endif // __WXDEBUG__
2238 wxStrcpy(colDefs
[index
].ColName
, fieldName
);
2240 colDefs
[index
].DbDataType
= dataType
;
2241 colDefs
[index
].PtrDataObj
= pData
;
2242 colDefs
[index
].SqlCtype
= cType
;
2243 colDefs
[index
].SzDataObj
= size
;
2244 colDefs
[index
].KeyField
= keyField
;
2245 colDefs
[index
].DerivedCol
= derivedCol
;
2246 // Derived columns by definition would NOT be "Insertable" or "Updateable"
2249 colDefs
[index
].Updateable
= FALSE
;
2250 colDefs
[index
].InsertAllowed
= FALSE
;
2254 colDefs
[index
].Updateable
= upd
;
2255 colDefs
[index
].InsertAllowed
= insAllow
;
2258 colDefs
[index
].Null
= FALSE
;
2260 } // wxDbTable::SetColDefs()
2263 /********** wxDbTable::SetColDefs() **********/
2264 wxDbColDataPtr
* wxDbTable::SetColDefs(wxDbColInf
*pColInfs
, UWORD numCols
)
2267 wxDbColDataPtr
*pColDataPtrs
= NULL
;
2273 pColDataPtrs
= new wxDbColDataPtr
[numCols
+1];
2275 for (index
= 0; index
< numCols
; index
++)
2277 // Process the fields
2278 switch (pColInfs
[index
].dbDataType
)
2280 case DB_DATA_TYPE_VARCHAR
:
2281 pColDataPtrs
[index
].PtrDataObj
= new wxChar
[pColInfs
[index
].bufferLength
+1];
2282 pColDataPtrs
[index
].SzDataObj
= pColInfs
[index
].columnSize
;
2283 pColDataPtrs
[index
].SqlCtype
= SQL_C_CHAR
;
2285 case DB_DATA_TYPE_INTEGER
:
2286 // Can be long or short
2287 if (pColInfs
[index
].bufferLength
== sizeof(long))
2289 pColDataPtrs
[index
].PtrDataObj
= new long;
2290 pColDataPtrs
[index
].SzDataObj
= sizeof(long);
2291 pColDataPtrs
[index
].SqlCtype
= SQL_C_SLONG
;
2295 pColDataPtrs
[index
].PtrDataObj
= new short;
2296 pColDataPtrs
[index
].SzDataObj
= sizeof(short);
2297 pColDataPtrs
[index
].SqlCtype
= SQL_C_SSHORT
;
2300 case DB_DATA_TYPE_FLOAT
:
2301 // Can be float or double
2302 if (pColInfs
[index
].bufferLength
== sizeof(float))
2304 pColDataPtrs
[index
].PtrDataObj
= new float;
2305 pColDataPtrs
[index
].SzDataObj
= sizeof(float);
2306 pColDataPtrs
[index
].SqlCtype
= SQL_C_FLOAT
;
2310 pColDataPtrs
[index
].PtrDataObj
= new double;
2311 pColDataPtrs
[index
].SzDataObj
= sizeof(double);
2312 pColDataPtrs
[index
].SqlCtype
= SQL_C_DOUBLE
;
2315 case DB_DATA_TYPE_DATE
:
2316 pColDataPtrs
[index
].PtrDataObj
= new TIMESTAMP_STRUCT
;
2317 pColDataPtrs
[index
].SzDataObj
= sizeof(TIMESTAMP_STRUCT
);
2318 pColDataPtrs
[index
].SqlCtype
= SQL_C_TIMESTAMP
;
2320 case DB_DATA_TYPE_BLOB
:
2321 wxFAIL_MSG(wxT("This form of ::SetColDefs() cannot be used with BLOB columns"));
2322 pColDataPtrs
[index
].PtrDataObj
= /*BLOB ADDITION NEEDED*/NULL
;
2323 pColDataPtrs
[index
].SzDataObj
= /*BLOB ADDITION NEEDED*/sizeof(void *);
2324 pColDataPtrs
[index
].SqlCtype
= SQL_VARBINARY
;
2327 if (pColDataPtrs
[index
].PtrDataObj
!= NULL
)
2328 SetColDefs (index
,pColInfs
[index
].colName
,pColInfs
[index
].dbDataType
, pColDataPtrs
[index
].PtrDataObj
, pColDataPtrs
[index
].SqlCtype
, pColDataPtrs
[index
].SzDataObj
);
2331 // Unable to build all the column definitions, as either one of
2332 // the calls to "new" failed above, or there was a BLOB field
2333 // to have a column definition for. If BLOBs are to be used,
2334 // the other form of ::SetColDefs() must be used, as it is impossible
2335 // to know the maximum size to create the PtrDataObj to be.
2336 delete [] pColDataPtrs
;
2342 return (pColDataPtrs
);
2344 } // wxDbTable::SetColDefs()
2347 /********** wxDbTable::SetCursor() **********/
2348 void wxDbTable::SetCursor(HSTMT
*hstmtActivate
)
2350 if (hstmtActivate
== wxDB_DEFAULT_CURSOR
)
2351 hstmt
= *hstmtDefault
;
2353 hstmt
= *hstmtActivate
;
2355 } // wxDbTable::SetCursor()
2358 /********** wxDbTable::Count(const wxString &) **********/
2359 ULONG
wxDbTable::Count(const wxString
&args
)
2365 // Build a "SELECT COUNT(*) FROM queryTableName [WHERE whereClause]" SQL Statement
2366 sqlStmt
= wxT("SELECT COUNT(");
2368 sqlStmt
+= wxT(") FROM ");
2369 sqlStmt
+= pDb
->SQLTableName(queryTableName
);
2370 // sqlStmt += queryTableName;
2371 #if wxODBC_BACKWARD_COMPATABILITY
2372 if (from
&& wxStrlen(from
))
2378 // Add the where clause if one is provided
2379 #if wxODBC_BACKWARD_COMPATABILITY
2380 if (where
&& wxStrlen(where
))
2385 sqlStmt
+= wxT(" WHERE ");
2389 pDb
->WriteSqlLog(sqlStmt
);
2391 // Initialize the Count cursor if it's not already initialized
2394 hstmtCount
= GetNewCursor(FALSE
,FALSE
);
2395 wxASSERT(hstmtCount
);
2400 // Execute the SQL statement
2401 if (SQLExecDirect(*hstmtCount
, (SQLTCHAR FAR
*) sqlStmt
.c_str(), SQL_NTS
) != SQL_SUCCESS
)
2403 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2408 if (SQLFetch(*hstmtCount
) != SQL_SUCCESS
)
2410 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2414 // Obtain the result
2415 if (SQLGetData(*hstmtCount
, (UWORD
)1, SQL_C_ULONG
, &count
, sizeof(count
), &cb
) != SQL_SUCCESS
)
2417 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2422 if (SQLFreeStmt(*hstmtCount
, SQL_CLOSE
) != SQL_SUCCESS
)
2423 pDb
->DispAllErrors(henv
, hdbc
, *hstmtCount
);
2425 // Return the record count
2428 } // wxDbTable::Count()
2431 /********** wxDbTable::Refresh() **********/
2432 bool wxDbTable::Refresh(void)
2436 // Switch to the internal cursor so any active cursors are not corrupted
2437 HSTMT currCursor
= GetCursor();
2438 hstmt
= hstmtInternal
;
2439 #if wxODBC_BACKWARD_COMPATABILITY
2440 // Save the where and order by clauses
2441 wxChar
*saveWhere
= where
;
2442 wxChar
*saveOrderBy
= orderBy
;
2444 wxString saveWhere
= where
;
2445 wxString saveOrderBy
= orderBy
;
2447 // Build a where clause to refetch the record with. Try and use the
2448 // ROWID if it's available, ow use the key fields.
2449 wxString whereClause
;
2450 whereClause
.Empty();
2452 if (CanUpdByROWID())
2455 wxChar rowid
[wxDB_ROWID_LEN
+1];
2457 // Get the ROWID value. If not successful retreiving the ROWID,
2458 // simply fall down through the code and build the WHERE clause
2459 // based on the key fields.
2460 if (SQLGetData(hstmt
, (UWORD
)(noCols
+1), SQL_C_CHAR
, (UCHAR
*) rowid
, wxDB_ROWID_LEN
, &cb
) == SQL_SUCCESS
)
2462 whereClause
+= pDb
->SQLTableName(queryTableName
);
2463 // whereClause += queryTableName;
2464 whereClause
+= wxT(".ROWID = '");
2465 whereClause
+= rowid
;
2466 whereClause
+= wxT("'");
2470 // If unable to use the ROWID, build a where clause from the keyfields
2471 if (wxStrlen(whereClause
) == 0)
2472 BuildWhereClause(whereClause
, DB_WHERE_KEYFIELDS
, queryTableName
);
2474 // Requery the record
2475 where
= whereClause
;
2480 if (result
&& !GetNext())
2483 // Switch back to original cursor
2484 SetCursor(&currCursor
);
2486 // Free the internal cursor
2487 if (SQLFreeStmt(hstmtInternal
, SQL_CLOSE
) != SQL_SUCCESS
)
2488 pDb
->DispAllErrors(henv
, hdbc
, hstmtInternal
);
2490 // Restore the original where and order by clauses
2492 orderBy
= saveOrderBy
;
2496 } // wxDbTable::Refresh()
2499 /********** wxDbTable::SetColNull() **********/
2500 bool wxDbTable::SetColNull(UWORD colNo
, bool set
)
2504 colDefs
[colNo
].Null
= set
;
2505 if (set
) // Blank out the values in the member variable
2507 colDefs
[colNo
].CbValue
= SQL_NULL_DATA
; // SF PATCH#766404
2508 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2515 } // wxDbTable::SetColNull()
2518 /********** wxDbTable::SetColNull() **********/
2519 bool wxDbTable::SetColNull(const wxString
&colName
, bool set
)
2522 for (colNo
= 0; colNo
< noCols
; colNo
++)
2524 if (!wxStricmp(colName
, colDefs
[colNo
].ColName
))
2530 colDefs
[colNo
].Null
= set
;
2531 if (set
) // Blank out the values in the member variable
2533 colDefs
[colNo
].CbValue
= SQL_NULL_DATA
; // SF PATCH#766404
2534 ClearMemberVar(colNo
,FALSE
); // Must call with FALSE, or infinite recursion will happen
2541 } // wxDbTable::SetColNull()
2544 /********** wxDbTable::GetNewCursor() **********/
2545 HSTMT
*wxDbTable::GetNewCursor(bool setCursor
, bool bindColumns
)
2547 HSTMT
*newHSTMT
= new HSTMT
;
2552 if (SQLAllocStmt(hdbc
, newHSTMT
) != SQL_SUCCESS
)
2554 pDb
->DispAllErrors(henv
, hdbc
);
2559 if (SQLSetStmtOption(*newHSTMT
, SQL_CURSOR_TYPE
, cursorType
) != SQL_SUCCESS
)
2561 pDb
->DispAllErrors(henv
, hdbc
, *newHSTMT
);
2568 if (!bindCols(*newHSTMT
))
2576 SetCursor(newHSTMT
);
2580 } // wxDbTable::GetNewCursor()
2583 /********** wxDbTable::DeleteCursor() **********/
2584 bool wxDbTable::DeleteCursor(HSTMT
*hstmtDel
)
2588 if (!hstmtDel
) // Cursor already deleted
2592 ODBC 3.0 says to use this form
2593 if (SQLFreeHandle(*hstmtDel, SQL_DROP) != SQL_SUCCESS)
2596 if (SQLFreeStmt(*hstmtDel
, SQL_DROP
) != SQL_SUCCESS
)
2598 pDb
->DispAllErrors(henv
, hdbc
);
2606 } // wxDbTable::DeleteCursor()
2608 //////////////////////////////////////////////////////////////
2609 // wxDbGrid support functions
2610 //////////////////////////////////////////////////////////////
2612 void wxDbTable::SetRowMode(const rowmode_t rowmode
)
2614 if (!m_hstmtGridQuery
)
2616 m_hstmtGridQuery
= GetNewCursor(FALSE
,FALSE
);
2617 if (!bindCols(*m_hstmtGridQuery
))
2621 m_rowmode
= rowmode
;
2624 case WX_ROW_MODE_QUERY
:
2625 SetCursor(m_hstmtGridQuery
);
2627 case WX_ROW_MODE_INDIVIDUAL
:
2628 SetCursor(hstmtDefault
);
2633 } // wxDbTable::SetRowMode()
2636 wxVariant
wxDbTable::GetCol(const int colNo
) const
2639 if ((colNo
< noCols
) && (!IsColNull(colNo
)))
2641 switch (colDefs
[colNo
].SqlCtype
)
2645 val
= (wxChar
*)(colDefs
[colNo
].PtrDataObj
);
2649 val
= *(long *)(colDefs
[colNo
].PtrDataObj
);
2653 val
= (long int )(*(short *)(colDefs
[colNo
].PtrDataObj
));
2656 val
= (long)(*(unsigned long *)(colDefs
[colNo
].PtrDataObj
));
2659 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2661 case SQL_C_UTINYINT
:
2662 val
= (long)(*(wxChar
*)(colDefs
[colNo
].PtrDataObj
));
2665 val
= (long)(*(UWORD
*)(colDefs
[colNo
].PtrDataObj
));
2668 val
= (DATE_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2671 val
= (TIME_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2673 case SQL_C_TIMESTAMP
:
2674 val
= (TIMESTAMP_STRUCT
*)(colDefs
[colNo
].PtrDataObj
);
2677 val
= *(double *)(colDefs
[colNo
].PtrDataObj
);
2684 } // wxDbTable::GetCol()
2687 void wxDbTable::SetCol(const int colNo
, const wxVariant val
)
2689 //FIXME: Add proper wxDateTime support to wxVariant..
2692 SetColNull(colNo
, val
.IsNull());
2696 if ((colDefs
[colNo
].SqlCtype
== SQL_C_DATE
)
2697 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIME
)
2698 || (colDefs
[colNo
].SqlCtype
== SQL_C_TIMESTAMP
))
2700 //Returns null if invalid!
2701 if (!dateval
.ParseDate(val
.GetString()))
2702 SetColNull(colNo
, TRUE
);
2705 switch (colDefs
[colNo
].SqlCtype
)
2709 csstrncpyt((wxChar
*)(colDefs
[colNo
].PtrDataObj
),
2710 val
.GetString().c_str(),
2711 colDefs
[colNo
].SzDataObj
-1);
2715 *(long *)(colDefs
[colNo
].PtrDataObj
) = val
;
2719 *(short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2722 *(unsigned long *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2725 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2727 case SQL_C_UTINYINT
:
2728 *(wxChar
*)(colDefs
[colNo
].PtrDataObj
) = val
.GetChar();
2731 *(unsigned short *)(colDefs
[colNo
].PtrDataObj
) = val
.GetLong();
2733 //FIXME: Add proper wxDateTime support to wxVariant..
2736 DATE_STRUCT
*dataptr
=
2737 (DATE_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2739 dataptr
->year
= dateval
.GetYear();
2740 dataptr
->month
= dateval
.GetMonth()+1;
2741 dataptr
->day
= dateval
.GetDay();
2746 TIME_STRUCT
*dataptr
=
2747 (TIME_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2749 dataptr
->hour
= dateval
.GetHour();
2750 dataptr
->minute
= dateval
.GetMinute();
2751 dataptr
->second
= dateval
.GetSecond();
2754 case SQL_C_TIMESTAMP
:
2756 TIMESTAMP_STRUCT
*dataptr
=
2757 (TIMESTAMP_STRUCT
*)colDefs
[colNo
].PtrDataObj
;
2758 dataptr
->year
= dateval
.GetYear();
2759 dataptr
->month
= dateval
.GetMonth()+1;
2760 dataptr
->day
= dateval
.GetDay();
2762 dataptr
->hour
= dateval
.GetHour();
2763 dataptr
->minute
= dateval
.GetMinute();
2764 dataptr
->second
= dateval
.GetSecond();
2768 *(double *)(colDefs
[colNo
].PtrDataObj
) = val
;
2773 } // if (!val.IsNull())
2774 } // wxDbTable::SetCol()
2777 GenericKey
wxDbTable::GetKey()
2782 blk
= malloc(m_keysize
);
2783 blkptr
= (wxChar
*) blk
;
2786 for (i
=0; i
< noCols
; i
++)
2788 if (colDefs
[i
].KeyField
)
2790 memcpy(blkptr
,colDefs
[i
].PtrDataObj
, colDefs
[i
].SzDataObj
);
2791 blkptr
+= colDefs
[i
].SzDataObj
;
2795 GenericKey k
= GenericKey(blk
, m_keysize
);
2799 } // wxDbTable::GetKey()
2802 void wxDbTable::SetKey(const GenericKey
& k
)
2808 blkptr
= (wxChar
*)blk
;
2811 for (i
=0; i
< noCols
; i
++)
2813 if (colDefs
[i
].KeyField
)
2815 SetColNull(i
, FALSE
);
2816 memcpy(colDefs
[i
].PtrDataObj
, blkptr
, colDefs
[i
].SzDataObj
);
2817 blkptr
+= colDefs
[i
].SzDataObj
;
2820 } // wxDbTable::SetKey()
2823 #endif // wxUSE_ODBC