Fixed a multiple define problem for strnicmp and stricmp by using the definition...
[wxWidgets.git] / include / wx / db.h
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: db.h
3 // Purpose: Header file wxDB class. The wxDB class represents a connection
4 // to an ODBC data source. The wxDB class allows operations on the data
5 // source such as opening and closing the data source.
6 // Author: Doug Card
7 // Modified by:
8 // Mods: Dec, 1998:
9 // -Added support for SQL statement logging and database cataloging
10 // April, 1999
11 // -Added QUERY_ONLY mode support to reduce default number of cursors
12 // -Added additional SQL logging code
13 // -Added DEBUG-ONLY tracking of Ctable objects to detect orphaned DB connections
14 // -Set ODBC option to only read committed writes to the DB so all
15 // databases operate the same in that respect
16 //
17 // Created: 9.96
18 // RCS-ID: $Id$
19 // Copyright: (c) 1996 Remstar International, Inc.
20 // Licence: wxWindows licence, plus:
21 // Notice: This class library and its intellectual design are free of charge for use,
22 // modification, enhancement, debugging under the following conditions:
23 // 1) These classes may only be used as part of the implementation of a
24 // wxWindows-based application
25 // 2) All enhancements and bug fixes are to be submitted back to the wxWindows
26 // user groups free of all charges for use with the wxWindows library.
27 // 3) These classes may not be distributed as part of any other class library,
28 // DLL, text (written or electronic), other than a complete distribution of
29 // the wxWindows GUI development toolkit.
30 //
31 ///////////////////////////////////////////////////////////////////////////////
32
33 /*
34 // SYNOPSIS START
35 // SYNOPSIS STOP
36 */
37
38 #ifndef DB_DOT_H
39 #define DB_DOT_H
40
41 // Use this line for wxWindows v1.x
42 //#include "wx_ver.h"
43 // Use this line for wxWindows v2.x
44 #include "wx/version.h"
45
46 #if wxMAJOR_VERSION == 2
47 #ifdef __GNUG__
48 #pragma interface "db.h"
49 #endif
50 #endif
51
52 #if defined(wx_msw) || defined(__WXMSW__) || defined(WIN32)
53 #include <windows.h>
54 #endif
55
56 #ifdef __UNIX__
57 #if wxMAJOR_VERSION == 2
58 extern "C" {
59 #include "../../src/iodbc/isql.h"
60 #include "../../src/iodbc/isqlext.h"
61 }
62 #else // version == 1
63 extern "C" {
64 #include "iodbc.h"
65 #include "isqlext.h"
66 }
67 #endif
68 typedef float SFLOAT;
69 typedef double SDOUBLE;
70 typedef unsigned int UINT;
71 #define ULONG UDWORD
72 #else // msw
73 #define ODBCVER 0x0250
74 #include <sql.h>
75 #include <sqlext.h>
76 #endif
77
78 #if wxMAJOR_VERSION == 2
79 #include "utils.h"
80 #else
81 #ifdef __UNIX__
82 # ifndef strnicmp
83 # define strnicmp strncasecmp
84 # endif
85 # ifndef stricmp
86 # define stricmp strcasecmp
87 # endif
88 #else
89 # include <io.h>
90 #endif
91 #endif
92
93 enum enumDummy {enumDum1};
94
95 #define SQL_C_BOOLEAN(datatype) (sizeof(datatype) == 1 ? SQL_C_UTINYINT : (sizeof(datatype) == 2 ? SQL_C_USHORT : SQL_C_ULONG))
96 // #define SQL_C_BOOLEAN (sizeof(Bool) == 2 ? SQL_C_USHORT : SQL_C_ULONG)
97
98 #define SQL_C_ENUM (sizeof(enumDummy) == 2 ? SQL_C_USHORT : SQL_C_ULONG)
99
100 #ifndef TRUE
101 #define TRUE 1
102 #endif
103
104 #ifndef FALSE
105 #define FALSE 0
106 #endif
107
108 const int DB_PATH_MAX = 254;
109
110 // Database Globals
111 const int DB_TYPE_NAME_LEN = 40;
112 const int DB_MAX_STATEMENT_LEN = 2048;
113 const int DB_MAX_WHERE_CLAUSE_LEN = 1024;
114 const int DB_MAX_ERROR_MSG_LEN = 512;
115 const int DB_MAX_ERROR_HISTORY = 5;
116 const int DB_MAX_TABLE_NAME_LEN = 128;
117 const int DB_MAX_COLUMN_NAME_LEN = 128;
118
119 const int DB_DATA_TYPE_VARCHAR = 1;
120 const int DB_DATA_TYPE_INTEGER = 2;
121 const int DB_DATA_TYPE_FLOAT = 3;
122 const int DB_DATA_TYPE_DATE = 4;
123
124 const int DB_SELECT_KEYFIELDS = 1;
125 const int DB_SELECT_WHERE = 2;
126 const int DB_SELECT_MATCHING = 3;
127 const int DB_SELECT_STATEMENT = 4;
128
129 const int DB_UPD_KEYFIELDS = 1;
130 const int DB_UPD_WHERE = 2;
131
132 const int DB_DEL_KEYFIELDS = 1;
133 const int DB_DEL_WHERE = 2;
134 const int DB_DEL_MATCHING = 3;
135
136 const int DB_WHERE_KEYFIELDS = 1;
137 const int DB_WHERE_MATCHING = 2;
138
139 const int DB_GRANT_SELECT = 1;
140 const int DB_GRANT_INSERT = 2;
141 const int DB_GRANT_UPDATE = 4;
142 const int DB_GRANT_DELETE = 8;
143 const int DB_GRANT_ALL = DB_GRANT_SELECT | DB_GRANT_INSERT | DB_GRANT_UPDATE | DB_GRANT_DELETE;
144
145 // ODBC Error codes (derived from ODBC SqlState codes)
146 enum ODBC_ERRORS
147 {
148 DB_FAILURE = 0,
149 DB_SUCCESS = 1,
150 DB_ERR_NOT_IN_USE,
151 DB_ERR_GENERAL_WARNING, // SqlState = '01000'
152 DB_ERR_DISCONNECT_ERROR, // SqlState = '01002'
153 DB_ERR_DATA_TRUNCATED, // SqlState = '01004'
154 DB_ERR_PRIV_NOT_REVOKED, // SqlState = '01006'
155 DB_ERR_INVALID_CONN_STR_ATTR, // SqlState = '01S00'
156 DB_ERR_ERROR_IN_ROW, // SqlState = '01S01'
157 DB_ERR_OPTION_VALUE_CHANGED, // SqlState = '01S02'
158 DB_ERR_NO_ROWS_UPD_OR_DEL, // SqlState = '01S03'
159 DB_ERR_MULTI_ROWS_UPD_OR_DEL, // SqlState = '01S04'
160 DB_ERR_WRONG_NO_OF_PARAMS, // SqlState = '07001'
161 DB_ERR_DATA_TYPE_ATTR_VIOL, // SqlState = '07006'
162 DB_ERR_UNABLE_TO_CONNECT, // SqlState = '08001'
163 DB_ERR_CONNECTION_IN_USE, // SqlState = '08002'
164 DB_ERR_CONNECTION_NOT_OPEN, // SqlState = '08003'
165 DB_ERR_REJECTED_CONNECTION, // SqlState = '08004'
166 DB_ERR_CONN_FAIL_IN_TRANS, // SqlState = '08007'
167 DB_ERR_COMM_LINK_FAILURE, // SqlState = '08S01'
168 DB_ERR_INSERT_VALUE_LIST_MISMATCH, // SqlState = '21S01'
169 DB_ERR_DERIVED_TABLE_MISMATCH, // SqlState = '21S02'
170 DB_ERR_STRING_RIGHT_TRUNC, // SqlState = '22001'
171 DB_ERR_NUMERIC_VALUE_OUT_OF_RNG, // SqlState = '22003'
172 DB_ERR_ERROR_IN_ASSIGNMENT, // SqlState = '22005'
173 DB_ERR_DATETIME_FLD_OVERFLOW, // SqlState = '22008'
174 DB_ERR_DIVIDE_BY_ZERO, // SqlState = '22012'
175 DB_ERR_STR_DATA_LENGTH_MISMATCH, // SqlState = '22026'
176 DB_ERR_INTEGRITY_CONSTRAINT_VIOL, // SqlState = '23000'
177 DB_ERR_INVALID_CURSOR_STATE, // SqlState = '24000'
178 DB_ERR_INVALID_TRANS_STATE, // SqlState = '25000'
179 DB_ERR_INVALID_AUTH_SPEC, // SqlState = '28000'
180 DB_ERR_INVALID_CURSOR_NAME, // SqlState = '34000'
181 DB_ERR_SYNTAX_ERROR_OR_ACCESS_VIOL, // SqlState = '37000'
182 DB_ERR_DUPLICATE_CURSOR_NAME, // SqlState = '3C000'
183 DB_ERR_SERIALIZATION_FAILURE, // SqlState = '40001'
184 DB_ERR_SYNTAX_ERROR_OR_ACCESS_VIOL2, // SqlState = '42000'
185 DB_ERR_OPERATION_ABORTED, // SqlState = '70100'
186 DB_ERR_UNSUPPORTED_FUNCTION, // SqlState = 'IM001'
187 DB_ERR_NO_DATA_SOURCE, // SqlState = 'IM002'
188 DB_ERR_DRIVER_LOAD_ERROR, // SqlState = 'IM003'
189 DB_ERR_SQLALLOCENV_FAILED, // SqlState = 'IM004'
190 DB_ERR_SQLALLOCCONNECT_FAILED, // SqlState = 'IM005'
191 DB_ERR_SQLSETCONNECTOPTION_FAILED, // SqlState = 'IM006'
192 DB_ERR_NO_DATA_SOURCE_DLG_PROHIB, // SqlState = 'IM007'
193 DB_ERR_DIALOG_FAILED, // SqlState = 'IM008'
194 DB_ERR_UNABLE_TO_LOAD_TRANSLATION_DLL, // SqlState = 'IM009'
195 DB_ERR_DATA_SOURCE_NAME_TOO_LONG, // SqlState = 'IM010'
196 DB_ERR_DRIVER_NAME_TOO_LONG, // SqlState = 'IM011'
197 DB_ERR_DRIVER_KEYWORD_SYNTAX_ERROR, // SqlState = 'IM012'
198 DB_ERR_TRACE_FILE_ERROR, // SqlState = 'IM013'
199 DB_ERR_TABLE_OR_VIEW_ALREADY_EXISTS, // SqlState = 'S0001'
200 DB_ERR_TABLE_NOT_FOUND, // SqlState = 'S0002'
201 DB_ERR_INDEX_ALREADY_EXISTS, // SqlState = 'S0011'
202 DB_ERR_INDEX_NOT_FOUND, // SqlState = 'S0012'
203 DB_ERR_COLUMN_ALREADY_EXISTS, // SqlState = 'S0021'
204 DB_ERR_COLUMN_NOT_FOUND, // SqlState = 'S0022'
205 DB_ERR_NO_DEFAULT_FOR_COLUMN, // SqlState = 'S0023'
206 DB_ERR_GENERAL_ERROR, // SqlState = 'S1000'
207 DB_ERR_MEMORY_ALLOCATION_FAILURE, // SqlState = 'S1001'
208 DB_ERR_INVALID_COLUMN_NUMBER, // SqlState = 'S1002'
209 DB_ERR_PROGRAM_TYPE_OUT_OF_RANGE, // SqlState = 'S1003'
210 DB_ERR_SQL_DATA_TYPE_OUT_OF_RANGE, // SqlState = 'S1004'
211 DB_ERR_OPERATION_CANCELLED, // SqlState = 'S1008'
212 DB_ERR_INVALID_ARGUMENT_VALUE, // SqlState = 'S1009'
213 DB_ERR_FUNCTION_SEQUENCE_ERROR, // SqlState = 'S1010'
214 DB_ERR_OPERATION_INVALID_AT_THIS_TIME, // SqlState = 'S1011'
215 DB_ERR_INVALID_TRANS_OPERATION_CODE, // SqlState = 'S1012'
216 DB_ERR_NO_CURSOR_NAME_AVAIL, // SqlState = 'S1015'
217 DB_ERR_INVALID_STR_OR_BUF_LEN, // SqlState = 'S1090'
218 DB_ERR_DESCRIPTOR_TYPE_OUT_OF_RANGE, // SqlState = 'S1091'
219 DB_ERR_OPTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1092'
220 DB_ERR_INVALID_PARAM_NO, // SqlState = 'S1093'
221 DB_ERR_INVALID_SCALE_VALUE, // SqlState = 'S1094'
222 DB_ERR_FUNCTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1095'
223 DB_ERR_INF_TYPE_OUT_OF_RANGE, // SqlState = 'S1096'
224 DB_ERR_COLUMN_TYPE_OUT_OF_RANGE, // SqlState = 'S1097'
225 DB_ERR_SCOPE_TYPE_OUT_OF_RANGE, // SqlState = 'S1098'
226 DB_ERR_NULLABLE_TYPE_OUT_OF_RANGE, // SqlState = 'S1099'
227 DB_ERR_UNIQUENESS_OPTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1100'
228 DB_ERR_ACCURACY_OPTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1101'
229 DB_ERR_DIRECTION_OPTION_OUT_OF_RANGE, // SqlState = 'S1103'
230 DB_ERR_INVALID_PRECISION_VALUE, // SqlState = 'S1104'
231 DB_ERR_INVALID_PARAM_TYPE, // SqlState = 'S1105'
232 DB_ERR_FETCH_TYPE_OUT_OF_RANGE, // SqlState = 'S1106'
233 DB_ERR_ROW_VALUE_OUT_OF_RANGE, // SqlState = 'S1107'
234 DB_ERR_CONCURRENCY_OPTION_OUT_OF_RANGE, // SqlState = 'S1108'
235 DB_ERR_INVALID_CURSOR_POSITION, // SqlState = 'S1109'
236 DB_ERR_INVALID_DRIVER_COMPLETION, // SqlState = 'S1110'
237 DB_ERR_INVALID_BOOKMARK_VALUE, // SqlState = 'S1111'
238 DB_ERR_DRIVER_NOT_CAPABLE, // SqlState = 'S1C00'
239 DB_ERR_TIMEOUT_EXPIRED // SqlState = 'S1T00'
240 };
241
242 struct DbStuff
243 {
244 HENV Henv;
245 char Dsn[SQL_MAX_DSN_LENGTH+1]; // Data Source Name
246 char Uid[20+1]; // User ID
247 char AuthStr[20+1]; // Authorization string (password)
248
249 char description[SQL_MAX_DSN_LENGTH+1]; // Not sure what the max length is
250 char fileType[SQL_MAX_DSN_LENGTH+1]; // Not sure what the max length is
251
252 // Optionals needed for some databases like dBase
253 char defaultDir[DB_PATH_MAX]; // Directory that db file resides in
254 };
255
256 typedef struct
257 {
258 char TypeName[DB_TYPE_NAME_LEN];
259 int FsqlType;
260 long Precision;
261 short CaseSensitive;
262 // short MinimumScale;
263 short MaximumScale;
264 } SqlTypeInfo;
265
266 class WXDLLEXPORT CcolInf
267 {
268 public:
269 char tableName[DB_MAX_TABLE_NAME_LEN+1];
270 char colName[DB_MAX_COLUMN_NAME_LEN+1];
271 int sqlDataType;
272 };
273
274 enum sqlLog
275 {
276 sqlLogOFF,
277 sqlLogON
278 };
279
280 enum dbms
281 {
282 dbmsUNIDENTIFIED,
283 dbmsORACLE,
284 dbmsSYBASE_ASA, // Adaptive Server Anywhere
285 dbmsSYBASE_ASE, // Adaptive Server Enterprise
286 dbmsMS_SQL_SERVER,
287 dbmsMY_SQL,
288 dbmsPOSTGRES,
289 dbmsACCESS,
290 dbmsDBASE
291 };
292
293 typedef enum dbms DBMS;
294
295 // The wxDB::errorList is copied to this variable when the wxDB object
296 // is closed. This way, the error list is still available after the
297 // database object is closed. This is necessary if the database
298 // connection fails so the calling application can show the operator
299 // why the connection failed. Note: as each wxDB object is closed, it
300 // will overwrite the errors of the previously destroyed wxDB object in
301 // this variable.
302 extern char DBerrorList[DB_MAX_ERROR_HISTORY][DB_MAX_ERROR_MSG_LEN];
303
304 class WXDLLEXPORT wxDB
305 {
306 private:
307
308 // Private data
309 bool dbIsOpen;
310 char *dsn; // Data source name
311 char *uid; // User ID
312 char *authStr; // Authorization string (password)
313 FILE *fpSqlLog; // Sql Log file pointer
314 enum sqlLog sqlLogState; // On or Off
315
316 // Private member functions
317 bool getDbInfo(void);
318 bool getDataTypeInfo(SWORD fSqlType, SqlTypeInfo &structSQLTypeInfo);
319 bool setConnectionOptions(void);
320 void logError(char *errMsg, char *SQLState);
321
322 public:
323
324 // The following structure contains database information gathered from the
325 // datasource when the datasource is first opened.
326 struct
327 {
328 char dbmsName[40]; // Name of the dbms product
329 char dbmsVer[64]; // Version # of the dbms product
330 char driverName[40]; // Driver name
331 char odbcVer[60]; // ODBC version of the driver
332 char drvMgrOdbcVer[60]; // ODBC version of the driver manager
333 char driverVer[60]; // Driver version
334 char serverName[80]; // Server Name, typically a connect string
335 char databaseName[128]; // Database filename
336 char outerJoins[2]; // Indicates whether the data source supports outer joins
337 char procedureSupport[2]; // Indicates whether the data source supports stored procedures
338 UWORD maxConnections; // Maximum # of connections the data source supports
339 UWORD maxStmts; // Maximum # of HSTMTs per HDBC
340 UWORD apiConfLvl; // ODBC API conformance level
341 UWORD cliConfLvl; // Indicates whether the data source is SAG compliant
342 UWORD sqlConfLvl; // SQL conformance level
343 UWORD cursorCommitBehavior; // Indicates how cursors are affected by a db commit
344 UWORD cursorRollbackBehavior; // Indicates how cursors are affected by a db rollback
345 UWORD supportNotNullClause; // Indicates if data source supports NOT NULL clause
346 char supportIEF[2]; // Integrity Enhancement Facility (Referential Integrity)
347 UDWORD txnIsolation; // Default transaction isolation level supported by the driver
348 UDWORD txnIsolationOptions; // Transaction isolation level options available
349 UDWORD fetchDirections; // Fetch directions supported
350 UDWORD lockTypes; // Lock types supported in SQLSetPos
351 UDWORD posOperations; // Position operations supported in SQLSetPos
352 UDWORD posStmts; // Position statements supported
353 UDWORD scrollConcurrency; // Concurrency control options supported for scrollable cursors
354 UDWORD scrollOptions; // Scroll Options supported for scrollable cursors
355 UDWORD staticSensitivity; // Indicates if additions, deletions and updates can be detected
356 UWORD txnCapable; // Indicates if the data source supports transactions
357 UDWORD loginTimeout; // Number seconds to wait for a login request
358 } dbInf;
359
360 // ODBC handles
361 HENV henv; // ODBC Environment handle
362 HDBC hdbc; // ODBC DB Connection handle
363 HSTMT hstmt; // ODBC Statement handle
364
365 // ODBC Error Inf.
366 char sqlState[20];
367 SDWORD nativeError;
368 char errorMsg[SQL_MAX_MESSAGE_LENGTH];
369 SWORD cbErrorMsg;
370 char errorList[DB_MAX_ERROR_HISTORY][DB_MAX_ERROR_MSG_LEN];
371 int DB_STATUS;
372
373 //Error reporting mode
374 bool silent;
375
376 // Number of Ctable objects connected to this db object
377 unsigned int nTables;
378
379 // Inf. about logical data types VARCHAR, INTEGER, FLOAT and DATE.
380 // This inf. is obtained from the ODBC driver by use of the
381 // SQLGetTypeInfo() function. The key piece of inf. is the
382 // type name the data source uses for each logical data type.
383 // e.g. VARCHAR; Oracle calls it VARCHAR2.
384 SqlTypeInfo typeInfVarchar, typeInfInteger, typeInfFloat, typeInfDate;
385
386 // Public member functions
387 wxDB(HENV &aHenv);
388 bool Open(char *Dsn, char *Uid, char *AuthStr); // Data Source Name, User ID, Password
389 void Close(void);
390 bool CommitTrans(void);
391 bool RollbackTrans(void);
392 bool DispAllErrors(HENV aHenv, HDBC aHdbc = SQL_NULL_HDBC, HSTMT aHstmt = SQL_NULL_HSTMT);
393 bool GetNextError(HENV aHenv, HDBC aHdbc = SQL_NULL_HDBC, HSTMT aHstmt = SQL_NULL_HSTMT);
394 void DispNextError(void);
395 bool CreateView(char *viewName, char *colList, char *pSqlStmt, bool attemptDrop=TRUE);
396 bool DropView(char *viewName);
397 bool ExecSql(char *pSqlStmt);
398 bool GetNext(void);
399 bool GetData(UWORD colNo, SWORD cType, PTR pData, SDWORD maxLen, SDWORD FAR *cbReturned);
400 bool Grant(int privileges, char *tableName, char *userList = "PUBLIC");
401 int TranslateSqlState(char *SQLState);
402 bool Catalog(char *userID, char *fileName = "Catalog.txt");
403 CcolInf *GetColumns(char *tableName[], char *userID=NULL);
404 char *GetDatabaseName(void) {return dbInf.dbmsName;}
405 char *GetDataSource(void) {return dsn;}
406 char *GetUsername(void) {return uid;}
407 char *GetPassword(void) {return authStr;}
408 bool IsOpen(void) {return dbIsOpen;}
409 HENV GetHENV(void) {return henv;}
410 HDBC GetHDBC(void) {return hdbc;}
411 HSTMT GetHSTMT(void) {return hstmt;}
412 bool TableExists(char *tableName, char *userID=NULL, char *path=NULL); // Table name can refer to a table, view, alias or synonym
413 void LogError(char *errMsg, char *SQLState = 0) {logError(errMsg, SQLState);}
414 bool SqlLog(enum sqlLog state, char *filename = "sqllog.txt", bool append = FALSE);
415 bool WriteSqlLog(char *logMsg);
416 DBMS Dbms(void);
417
418 }; // wxDB
419
420 // This structure forms a node in a linked list. The linked list of "DbList" objects
421 // keeps track of allocated database connections. This allows the application to
422 // open more than one database connection through ODBC for multiple transaction support
423 // or for multiple database support.
424
425 struct DbList
426 {
427 DbList *PtrPrev; // Pointer to previous item in the list
428 char Dsn[SQL_MAX_DSN_LENGTH+1]; // Data Source Name
429 wxDB *PtrDb; // Pointer to the wxDB object
430 bool Free; // Is item free or in use?
431 DbList *PtrNext; // Pointer to next item in the list
432 };
433
434
435 #if __WXDEBUG__ > 0
436 #include "wx/object.h"
437 class CstructTablesInUse : public wxObject
438 {
439 public:
440 const char *tableName;
441 ULONG tableID;
442 class wxDB *pDb;
443 }; // CstructTablesInUse
444 #endif
445
446 // The following routines allow a user to get new database connections, free them
447 // for other code segments to use, or close all of them when the application has
448 // completed.
449
450 wxDB WXDLLEXPORT *GetDbConnection(DbStuff *pDbStuff);
451 bool WXDLLEXPORT FreeDbConnection(wxDB *pDb);
452 void WXDLLEXPORT CloseDbConnections(void);
453 int WXDLLEXPORT NumberDbConnectionsInUse(void);
454
455 // This function sets the sql log state for all open wxDB objects
456 bool SqlLog(enum sqlLog state, char *filename = "sqllog.txt");
457
458 // This routine allows you to query a driver manager
459 // for a list of available datasources. Call this routine
460 // the first time using SQL_FETCH_FIRST. Continue to call it
461 // using SQL_FETCH_NEXT until you've exhausted the list.
462 bool WXDLLEXPORT GetDataSource(HENV henv, char *Dsn, SWORD DsnMax, char *DsDesc, SWORD DsDescMax,
463 UWORD direction = SQL_FETCH_NEXT);
464
465 #endif