do not include <windows.h> directly
[wxWidgets.git] / include / wx / db.h
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: wx/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: George Tasker
8 // Bart Jourquin
9 // Mark Johnson, wxWindows@mj10777.de
10 // Mods: Dec, 1998:
11 // -Added support for SQL statement logging and database cataloging
12 // April, 1999
13 // -Added QUERY_ONLY mode support to reduce default number of cursors
14 // -Added additional SQL logging code
15 // -Added DEBUG-ONLY tracking of Ctable objects to detect orphaned DB connections
16 // -Set ODBC option to only read committed writes to the DB so all
17 // databases operate the same in that respect
18 //
19 // Created: 9.96
20 // RCS-ID: $Id$
21 // Copyright: (c) 1996 Remstar International, Inc.
22 // Licence: wxWindows licence
23 ///////////////////////////////////////////////////////////////////////////////
24
25 #ifndef _WX_DB_H_
26 #define _WX_DB_H_
27
28
29 // BJO 20000503: introduce new GetColumns members which are more database independent and
30 // return columns in the order they were created
31 #define OLD_GETCOLUMNS 1
32 #define EXPERIMENTAL_WXDB_FUNCTIONS 1
33
34 #include "wx/defs.h"
35 #include "wx/string.h"
36
37 #if defined(__VISUALC__)
38 // we need to include standard Windows headers but we can't include
39 // <windows.h> directly when using MFC because it includes it itself in a
40 // different manner
41 #if wxUSE_MFC
42 #include <afxwin.h>
43 #else // !wxUSE_MFC
44 #include "wx/msw/wrapwin.h"
45 #endif // wxUSE_MFC/!wxUSE_MFC
46
47 // If you use the wxDbCreateDataSource() function with MSW/VC6,
48 // you cannot use the iODBC headers, you must use the VC headers,
49 // plus the odbcinst.h header - gt Nov 2 2000
50 //
51 // Must add "odbccp32.lib" in \wx2\wxWidgets\src\makevc.env to the WINLIBS= line
52 //
53 #include "sql.h"
54 #include "sqlext.h"
55 //#if wxUSE_UNICODE
56 // #include <sqlucode.h>
57 //#endif
58 #include "odbcinst.h"
59 #else
60 #if defined(__WINDOWS__) && ( defined(HAVE_W32API_H) || defined(__BORLANDC__) )
61 #include "wx/msw/wrapwin.h"
62 #endif
63 extern "C" {
64 #if defined(wxUSE_BUILTIN_IODBC) && wxUSE_BUILTIN_IODBC
65 // Use the ones from the library
66 #include "wx/isql.h"
67 #include "wx/isqlext.h"
68 // Not available in v2.x of iODBC
69 #ifndef __WXMSW__
70 #if wxUSE_UNICODE
71 typedef wxChar SQLTCHAR;
72 #else
73 typedef UCHAR SQLTCHAR;
74 #endif
75 #endif
76 #else
77 #if defined( __WXMOTIF__ ) && defined( __VMS )
78 // solves a type definition mismatch between IODBC and MOTIF on OpenVMS
79 #define BOOL int
80 #endif
81 #include <sql.h>
82 #include <sqlext.h>
83 //#if wxUSE_UNICODE
84 // #include <sqlucode.h>
85 //#endif
86 #if defined( __WXMOTIF__ ) && defined( __VMS )
87 #undef BOOL
88 #endif
89 #endif
90 }
91 #endif
92
93 #if wxUSE_UNICODE
94 #define SQL_C_WXCHAR SQL_C_WCHAR
95 #else
96 #define SQL_C_WXCHAR SQL_C_CHAR
97 #endif
98
99 #ifdef __DIGITALMARS__
100 #if wxUSE_UNICODE
101 typedef wxChar SQLTCHAR;
102 #else
103 typedef UCHAR SQLTCHAR;
104 #endif
105 #endif
106
107 typedef float SFLOAT;
108 typedef double SDOUBLE;
109 typedef unsigned int UINT;
110 #define ULONG UDWORD
111
112 #ifndef wxODBC_FWD_ONLY_CURSORS
113 #define wxODBC_FWD_ONLY_CURSORS 1
114 #endif
115
116 enum enumDummy {enumDum1};
117
118 #ifndef SQL_C_BOOLEAN
119 #define SQL_C_BOOLEAN(datatype) (sizeof(datatype) == 1 ? SQL_C_UTINYINT : (sizeof(datatype) == 2 ? SQL_C_USHORT : SQL_C_ULONG))
120 #endif
121
122 #ifndef SQL_C_ENUM
123 #define SQL_C_ENUM (sizeof(enumDummy) == 2 ? SQL_C_USHORT : SQL_C_ULONG)
124 #endif
125
126 // NOTE: If SQL_C_BLOB is defined, and it is not SQL_C_BINARY, iODBC 2.x
127 // may not function correctly. Likely best to use SQL_C_BINARY direct
128 #ifndef SQL_C_BLOB
129 #ifdef SQL_C_BINARY
130 #define SQL_C_BLOB SQL_C_BINARY
131 #endif
132 #endif
133
134 #ifndef _WIN64
135 #ifndef SQLLEN
136 #define SQLLEN SQLINTEGER
137 #endif
138 #ifndef SQLULEN
139 #define SQLULEN SQLUINTEGER
140 #endif
141 #endif
142
143 const int wxDB_PATH_MAX = 254;
144
145 extern WXDLLIMPEXP_DATA_ODBC(wxChar const *) SQL_LOG_FILENAME;
146 extern WXDLLIMPEXP_DATA_ODBC(wxChar const *) SQL_CATALOG_FILENAME;
147
148 // Database Globals
149 const int DB_TYPE_NAME_LEN = 40;
150 const int DB_MAX_STATEMENT_LEN = 4096;
151 const int DB_MAX_WHERE_CLAUSE_LEN = 2048;
152 const int DB_MAX_ERROR_MSG_LEN = 512;
153 const int DB_MAX_ERROR_HISTORY = 5;
154 const int DB_MAX_TABLE_NAME_LEN = 128;
155 const int DB_MAX_COLUMN_NAME_LEN = 128;
156
157 const int DB_DATA_TYPE_VARCHAR = 1;
158 const int DB_DATA_TYPE_INTEGER = 2;
159 const int DB_DATA_TYPE_FLOAT = 3;
160 const int DB_DATA_TYPE_DATE = 4;
161 const int DB_DATA_TYPE_BLOB = 5;
162 const int DB_DATA_TYPE_MEMO = 6;
163
164 const int DB_SELECT_KEYFIELDS = 1;
165 const int DB_SELECT_WHERE = 2;
166 const int DB_SELECT_MATCHING = 3;
167 const int DB_SELECT_STATEMENT = 4;
168
169 const int DB_UPD_KEYFIELDS = 1;
170 const int DB_UPD_WHERE = 2;
171
172 const int DB_DEL_KEYFIELDS = 1;
173 const int DB_DEL_WHERE = 2;
174 const int DB_DEL_MATCHING = 3;
175
176 const int DB_WHERE_KEYFIELDS = 1;
177 const int DB_WHERE_MATCHING = 2;
178
179 const int DB_GRANT_SELECT = 1;
180 const int DB_GRANT_INSERT = 2;
181 const int DB_GRANT_UPDATE = 4;
182 const int DB_GRANT_DELETE = 8;
183 const int DB_GRANT_ALL = DB_GRANT_SELECT | DB_GRANT_INSERT | DB_GRANT_UPDATE | DB_GRANT_DELETE;
184
185 // ODBC Error codes (derived from ODBC SqlState codes)
186 enum wxODBC_ERRORS
187 {
188 DB_FAILURE = 0,
189 DB_SUCCESS = 1,
190 DB_ERR_NOT_IN_USE,
191 DB_ERR_GENERAL_WARNING, // SqlState = '01000'
192 DB_ERR_DISCONNECT_ERROR, // SqlState = '01002'
193 DB_ERR_DATA_TRUNCATED, // SqlState = '01004'
194 DB_ERR_PRIV_NOT_REVOKED, // SqlState = '01006'
195 DB_ERR_INVALID_CONN_STR_ATTR, // SqlState = '01S00'
196 DB_ERR_ERROR_IN_ROW, // SqlState = '01S01'
197 DB_ERR_OPTION_VALUE_CHANGED, // SqlState = '01S02'
198 DB_ERR_NO_ROWS_UPD_OR_DEL, // SqlState = '01S03'
199 DB_ERR_MULTI_ROWS_UPD_OR_DEL, // SqlState = '01S04'
200 DB_ERR_WRONG_NO_OF_PARAMS, // SqlState = '07001'
201 DB_ERR_DATA_TYPE_ATTR_VIOL, // SqlState = '07006'
202 DB_ERR_UNABLE_TO_CONNECT, // SqlState = '08001'
203 DB_ERR_CONNECTION_IN_USE, // SqlState = '08002'
204 DB_ERR_CONNECTION_NOT_OPEN, // SqlState = '08003'
205 DB_ERR_REJECTED_CONNECTION, // SqlState = '08004'
206 DB_ERR_CONN_FAIL_IN_TRANS, // SqlState = '08007'
207 DB_ERR_COMM_LINK_FAILURE, // SqlState = '08S01'
208 DB_ERR_INSERT_VALUE_LIST_MISMATCH, // SqlState = '21S01'
209 DB_ERR_DERIVED_TABLE_MISMATCH, // SqlState = '21S02'
210 DB_ERR_STRING_RIGHT_TRUNC, // SqlState = '22001'
211 DB_ERR_NUMERIC_VALUE_OUT_OF_RNG, // SqlState = '22003'
212 DB_ERR_ERROR_IN_ASSIGNMENT, // SqlState = '22005'
213 DB_ERR_DATETIME_FLD_OVERFLOW, // SqlState = '22008'
214 DB_ERR_DIVIDE_BY_ZERO, // SqlState = '22012'
215 DB_ERR_STR_DATA_LENGTH_MISMATCH, // SqlState = '22026'
216 DB_ERR_INTEGRITY_CONSTRAINT_VIOL, // SqlState = '23000'
217 DB_ERR_INVALID_CURSOR_STATE, // SqlState = '24000'
218 DB_ERR_INVALID_TRANS_STATE, // SqlState = '25000'
219 DB_ERR_INVALID_AUTH_SPEC, // SqlState = '28000'
220 DB_ERR_INVALID_CURSOR_NAME, // SqlState = '34000'
221 DB_ERR_SYNTAX_ERROR_OR_ACCESS_VIOL, // SqlState = '37000'
222 DB_ERR_DUPLICATE_CURSOR_NAME, // SqlState = '3C000'
223 DB_ERR_SERIALIZATION_FAILURE, // SqlState = '40001'
224 DB_ERR_SYNTAX_ERROR_OR_ACCESS_VIOL2, // SqlState = '42000'
225 DB_ERR_OPERATION_ABORTED, // SqlState = '70100'
226 DB_ERR_UNSUPPORTED_FUNCTION, // SqlState = 'IM001'
227 DB_ERR_NO_DATA_SOURCE, // SqlState = 'IM002'
228 DB_ERR_DRIVER_LOAD_ERROR, // SqlState = 'IM003'
229 DB_ERR_SQLALLOCENV_FAILED, // SqlState = 'IM004'
230 DB_ERR_SQLALLOCCONNECT_FAILED, // SqlState = 'IM005'
231 DB_ERR_SQLSETCONNECTOPTION_FAILED, // SqlState = 'IM006'
232 DB_ERR_NO_DATA_SOURCE_DLG_PROHIB, // SqlState = 'IM007'
233 DB_ERR_DIALOG_FAILED, // SqlState = 'IM008'
234 DB_ERR_UNABLE_TO_LOAD_TRANSLATION_DLL, // SqlState = 'IM009'
235 DB_ERR_DATA_SOURCE_NAME_TOO_LONG, // SqlState = 'IM010'
236 DB_ERR_DRIVER_NAME_TOO_LONG, // SqlState = 'IM011'
237 DB_ERR_DRIVER_KEYWORD_SYNTAX_ERROR, // SqlState = 'IM012'
238 DB_ERR_TRACE_FILE_ERROR, // SqlState = 'IM013'
239 DB_ERR_TABLE_OR_VIEW_ALREADY_EXISTS, // SqlState = 'S0001'
240 DB_ERR_TABLE_NOT_FOUND, // SqlState = 'S0002'
241 DB_ERR_INDEX_ALREADY_EXISTS, // SqlState = 'S0011'
242 DB_ERR_INDEX_NOT_FOUND, // SqlState = 'S0012'
243 DB_ERR_COLUMN_ALREADY_EXISTS, // SqlState = 'S0021'
244 DB_ERR_COLUMN_NOT_FOUND, // SqlState = 'S0022'
245 DB_ERR_NO_DEFAULT_FOR_COLUMN, // SqlState = 'S0023'
246 DB_ERR_GENERAL_ERROR, // SqlState = 'S1000'
247 DB_ERR_MEMORY_ALLOCATION_FAILURE, // SqlState = 'S1001'
248 DB_ERR_INVALID_COLUMN_NUMBER, // SqlState = 'S1002'
249 DB_ERR_PROGRAM_TYPE_OUT_OF_RANGE, // SqlState = 'S1003'
250 DB_ERR_SQL_DATA_TYPE_OUT_OF_RANGE, // SqlState = 'S1004'
251 DB_ERR_OPERATION_CANCELLED, // SqlState = 'S1008'
252 DB_ERR_INVALID_ARGUMENT_VALUE, // SqlState = 'S1009'
253 DB_ERR_FUNCTION_SEQUENCE_ERROR, // SqlState = 'S1010'
254 DB_ERR_OPERATION_INVALID_AT_THIS_TIME, // SqlState = 'S1011'
255 DB_ERR_INVALID_TRANS_OPERATION_CODE, // SqlState = 'S1012'
256 DB_ERR_NO_CURSOR_NAME_AVAIL, // SqlState = 'S1015'
257 DB_ERR_INVALID_STR_OR_BUF_LEN, // SqlState = 'S1090'
258 DB_ERR_DESCRIPTOR_TYPE_OUT_OF_RANGE, // SqlState = 'S1091'
259 DB_ERR_OPTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1092'
260 DB_ERR_INVALID_PARAM_NO, // SqlState = 'S1093'
261 DB_ERR_INVALID_SCALE_VALUE, // SqlState = 'S1094'
262 DB_ERR_FUNCTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1095'
263 DB_ERR_INF_TYPE_OUT_OF_RANGE, // SqlState = 'S1096'
264 DB_ERR_COLUMN_TYPE_OUT_OF_RANGE, // SqlState = 'S1097'
265 DB_ERR_SCOPE_TYPE_OUT_OF_RANGE, // SqlState = 'S1098'
266 DB_ERR_NULLABLE_TYPE_OUT_OF_RANGE, // SqlState = 'S1099'
267 DB_ERR_UNIQUENESS_OPTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1100'
268 DB_ERR_ACCURACY_OPTION_TYPE_OUT_OF_RANGE, // SqlState = 'S1101'
269 DB_ERR_DIRECTION_OPTION_OUT_OF_RANGE, // SqlState = 'S1103'
270 DB_ERR_INVALID_PRECISION_VALUE, // SqlState = 'S1104'
271 DB_ERR_INVALID_PARAM_TYPE, // SqlState = 'S1105'
272 DB_ERR_FETCH_TYPE_OUT_OF_RANGE, // SqlState = 'S1106'
273 DB_ERR_ROW_VALUE_OUT_OF_RANGE, // SqlState = 'S1107'
274 DB_ERR_CONCURRENCY_OPTION_OUT_OF_RANGE, // SqlState = 'S1108'
275 DB_ERR_INVALID_CURSOR_POSITION, // SqlState = 'S1109'
276 DB_ERR_INVALID_DRIVER_COMPLETION, // SqlState = 'S1110'
277 DB_ERR_INVALID_BOOKMARK_VALUE, // SqlState = 'S1111'
278 DB_ERR_DRIVER_NOT_CAPABLE, // SqlState = 'S1C00'
279 DB_ERR_TIMEOUT_EXPIRED // SqlState = 'S1T00'
280 };
281
282 #ifndef MAXNAME
283 #define MAXNAME 31
284 #endif
285
286 #ifndef SQL_MAX_AUTHSTR_LEN
287 // There does not seem to be a standard for this, so I am
288 // defaulting to the value that MS uses
289 #define SQL_MAX_AUTHSTR_LEN MAXNAME
290 #endif
291
292 #ifndef SQL_MAX_CONNECTSTR_LEN
293 // There does not seem to be a standard for this, so I am
294 // defaulting to the value that MS recommends
295 #define SQL_MAX_CONNECTSTR_LEN 1024
296 #endif
297
298
299 class WXDLLIMPEXP_ODBC wxDbConnectInf
300 {
301 private:
302 bool freeHenvOnDestroy;
303 bool useConnectionStr;
304
305 public:
306 HENV Henv;
307 wxChar Dsn[SQL_MAX_DSN_LENGTH+1]; // Data Source Name
308 wxChar Uid[SQL_MAX_USER_NAME_LEN+1]; // User ID
309 wxChar AuthStr[SQL_MAX_AUTHSTR_LEN+1]; // Authorization string (password)
310 wxChar ConnectionStr[SQL_MAX_CONNECTSTR_LEN+1]; // Connection string (password)
311
312 wxString Description; // Not sure what the max length is
313 wxString FileType; // Not sure what the max length is
314
315 // Optionals needed for some databases like dBase
316 wxString DefaultDir; // Directory that db file resides in
317
318 public:
319
320 wxDbConnectInf();
321 wxDbConnectInf(HENV henv, const wxString &dsn, const wxString &userID=wxEmptyString,
322 const wxString &password=wxEmptyString, const wxString &defaultDir=wxEmptyString,
323 const wxString &description=wxEmptyString, const wxString &fileType=wxEmptyString);
324
325 ~wxDbConnectInf();
326
327 bool Initialize();
328
329 bool AllocHenv();
330 void FreeHenv();
331
332 // Accessors
333 const HENV &GetHenv() { return Henv; };
334
335 const wxChar *GetDsn() { return Dsn; };
336
337 const wxChar *GetUid() { return Uid; };
338 const wxChar *GetUserID() { return Uid; };
339
340 const wxChar *GetAuthStr() { return AuthStr; };
341 const wxChar *GetPassword() { return AuthStr; };
342
343 const wxChar *GetConnectionStr() { return ConnectionStr; };
344 bool UseConnectionStr() { return useConnectionStr; };
345
346 const wxChar *GetDescription() { return Description; };
347 const wxChar *GetFileType() { return FileType; };
348 const wxChar *GetDefaultDir() { return DefaultDir; };
349
350 void SetHenv(const HENV henv) { Henv = henv; };
351
352 void SetDsn(const wxString &dsn);
353
354 void SetUserID(const wxString &userID);
355 void SetUid(const wxString &uid) { SetUserID(uid); };
356
357 void SetPassword(const wxString &password);
358 void SetAuthStr(const wxString &authstr) { SetPassword(authstr); };
359
360 void SetConnectionStr(const wxString &connectStr);
361
362 void SetDescription(const wxString &desc) { Description = desc; };
363 void SetFileType(const wxString &fileType) { FileType = fileType; };
364 void SetDefaultDir(const wxString &defDir) { DefaultDir = defDir; };
365 }; // class wxDbConnectInf
366
367
368 struct WXDLLIMPEXP_ODBC wxDbSqlTypeInfo
369 {
370 wxString TypeName;
371 SWORD FsqlType;
372 long Precision;
373 short CaseSensitive;
374 short MaximumScale;
375 };
376
377
378 class WXDLLIMPEXP_ODBC wxDbColFor
379 {
380 public:
381 wxString s_Field; // Formatted String for Output
382 wxString s_Format[7]; // Formatted Objects - TIMESTAMP has the biggest (7)
383 wxString s_Amount[7]; // Formatted Objects - amount of things that can be formatted
384 int i_Amount[7]; // Formatted Objects - TT MM YYYY HH MM SS m
385 int i_Nation; // 0 = timestamp , 1=EU, 2=UK, 3=International, 4=US
386 int i_dbDataType; // conversion of the 'sqlDataType' to the generic data type used by these classes
387 SWORD i_sqlDataType;
388
389 wxDbColFor();
390 ~wxDbColFor(){}
391
392 void Initialize();
393 int Format(int Nation, int dbDataType, SWORD sqlDataType, short columnLength, short decimalDigits);
394 };
395
396
397 class WXDLLIMPEXP_ODBC wxDbColInf
398 {
399 public:
400 wxChar catalog[128+1];
401 wxChar schema[128+1];
402 wxChar tableName[DB_MAX_TABLE_NAME_LEN+1];
403 wxChar colName[DB_MAX_COLUMN_NAME_LEN+1];
404 SWORD sqlDataType;
405 wxChar typeName[128+1];
406 SWORD columnLength;
407 SWORD bufferSize;
408 short decimalDigits;
409 short numPrecRadix;
410 short nullable;
411 wxChar remarks[254+1];
412 int dbDataType; // conversion of the 'sqlDataType' to the generic data type used by these classes
413 // mj10777.19991224 : new
414 int PkCol; // Primary key column 0=No; 1= First Key, 2 = Second Key etc.
415 wxChar PkTableName[DB_MAX_TABLE_NAME_LEN+1]; // Tables that use this PKey as a FKey
416 int FkCol; // Foreign key column 0=No; 1= First Key, 2 = Second Key etc.
417 wxChar FkTableName[DB_MAX_TABLE_NAME_LEN+1]; // Foreign key table name
418 wxDbColFor *pColFor; // How should this columns be formatted
419
420 wxDbColInf();
421 ~wxDbColInf();
422
423 bool Initialize();
424 };
425
426
427 class WXDLLIMPEXP_ODBC wxDbTableInf // Description of a Table
428 {
429 public:
430 wxChar tableName[DB_MAX_TABLE_NAME_LEN+1];
431 wxChar tableType[254+1]; // "TABLE" or "SYSTEM TABLE" etc.
432 wxChar tableRemarks[254+1];
433 UWORD numCols; // How many Columns does this Table have: GetColumnCount(..);
434 wxDbColInf *pColInf; // pColInf = NULL ; User can later call GetColumns(..);
435
436 wxDbTableInf();
437 ~wxDbTableInf();
438
439 bool Initialize();
440 };
441
442
443 class WXDLLIMPEXP_ODBC wxDbInf // Description of a Database
444 {
445 public:
446 wxChar catalog[128+1];
447 wxChar schema[128+1];
448 int numTables; // How many tables does this database have
449 wxDbTableInf *pTableInf; // pTableInf = new wxDbTableInf[numTables];
450
451 wxDbInf();
452 ~wxDbInf();
453
454 bool Initialize();
455 };
456
457
458 enum wxDbSqlLogState
459 {
460 sqlLogOFF,
461 sqlLogON
462 };
463
464 // These are the databases currently tested and working with these classes
465 // See the comments in wxDb::Dbms() for exceptions/issues with
466 // each of these database engines
467 enum wxDBMS
468 {
469 dbmsUNIDENTIFIED,
470 dbmsORACLE,
471 dbmsSYBASE_ASA, // Adaptive Server Anywhere
472 dbmsSYBASE_ASE, // Adaptive Server Enterprise
473 dbmsMS_SQL_SERVER,
474 dbmsMY_SQL,
475 dbmsPOSTGRES,
476 dbmsACCESS,
477 dbmsDBASE,
478 dbmsINFORMIX,
479 dbmsVIRTUOSO,
480 dbmsDB2,
481 dbmsINTERBASE,
482 dbmsPERVASIVE_SQL,
483 dbmsXBASE_SEQUITER,
484 dbmsFIREBIRD,
485 dbmsMAXDB,
486 dbmsFuture1,
487 dbmsFuture2,
488 dbmsFuture3,
489 dbmsFuture4,
490 dbmsFuture5,
491 dbmsFuture6,
492 dbmsFuture7,
493 dbmsFuture8,
494 dbmsFuture9,
495 dbmsFuture10
496 };
497
498
499 // The wxDb::errorList is copied to this variable when the wxDb object
500 // is closed. This way, the error list is still available after the
501 // database object is closed. This is necessary if the database
502 // connection fails so the calling application can show the operator
503 // why the connection failed. Note: as each wxDb object is closed, it
504 // will overwrite the errors of the previously destroyed wxDb object in
505 // this variable.
506
507 extern WXDLLIMPEXP_DATA_ODBC(wxChar)
508 DBerrorList[DB_MAX_ERROR_HISTORY][DB_MAX_ERROR_MSG_LEN+1];
509
510
511 class WXDLLIMPEXP_ODBC wxDb
512 {
513 private:
514 bool dbIsOpen;
515 bool dbIsCached; // Was connection created by caching functions
516 bool dbOpenedWithConnectionString; // Was the database connection opened with a connection string
517 wxString dsn; // Data source name
518 wxString uid; // User ID
519 wxString authStr; // Authorization string (password)
520 wxString inConnectionStr; // Connection string used to connect to the database
521 wxString outConnectionStr;// Connection string returned by the database when a connection is successfully opened
522 FILE *fpSqlLog; // Sql Log file pointer
523 wxDbSqlLogState sqlLogState; // On or Off
524 bool fwdOnlyCursors;
525 wxDBMS dbmsType; // Type of datasource - i.e. Oracle, dBase, SQLServer, etc
526
527 // Private member functions
528 bool getDbInfo(bool failOnDataTypeUnsupported=true);
529 bool getDataTypeInfo(SWORD fSqlType, wxDbSqlTypeInfo &structSQLTypeInfo);
530 bool setConnectionOptions(void);
531 void logError(const wxString &errMsg, const wxString &SQLState);
532 const wxChar *convertUserID(const wxChar *userID, wxString &UserID);
533 bool determineDataTypes(bool failOnDataTypeUnsupported);
534 void initialize();
535 bool open(bool failOnDataTypeUnsupported=true);
536
537 #if !wxODBC_BACKWARD_COMPATABILITY
538 // ODBC handles
539 HENV henv; // ODBC Environment handle
540 HDBC hdbc; // ODBC DB Connection handle
541 HSTMT hstmt; // ODBC Statement handle
542
543 //Error reporting mode
544 bool silent;
545
546 // Number of Ctable objects connected to this db object. FOR INTERNAL USE ONLY!!!
547 unsigned int nTables;
548
549 // Information about logical data types VARCHAR, INTEGER, FLOAT and DATE.
550 //
551 // This information is obtained from the ODBC driver by use of the
552 // SQLGetTypeInfo() function. The key piece of information is the
553 // type name the data source uses for each logical data type.
554 // e.g. VARCHAR; Oracle calls it VARCHAR2.
555 wxDbSqlTypeInfo typeInfVarchar;
556 wxDbSqlTypeInfo typeInfInteger;
557 wxDbSqlTypeInfo typeInfFloat;
558 wxDbSqlTypeInfo typeInfDate;
559 wxDbSqlTypeInfo typeInfBlob;
560 wxDbSqlTypeInfo typeInfMemo;
561 #endif
562
563 public:
564
565 void setCached(bool cached) { dbIsCached = cached; }; // This function must only be called by wxDbGetConnection() and wxDbCloseConnections!!!
566 bool IsCached() { return dbIsCached; };
567
568 bool GetDataTypeInfo(SWORD fSqlType, wxDbSqlTypeInfo &structSQLTypeInfo)
569 { return getDataTypeInfo(fSqlType, structSQLTypeInfo); }
570
571 #if wxODBC_BACKWARD_COMPATABILITY
572 // ODBC handles
573 HENV henv; // ODBC Environment handle
574 HDBC hdbc; // ODBC DB Connection handle
575 HSTMT hstmt; // ODBC Statement handle
576
577 //Error reporting mode
578 bool silent;
579
580 // Number of Ctable objects connected to this db object. FOR INTERNAL USE ONLY!!!
581 unsigned int nTables;
582 #endif
583
584 // The following structure contains database information gathered from the
585 // datasource when the datasource is first opened.
586 struct
587 {
588 wxChar dbmsName[40]; // Name of the dbms product
589 wxChar dbmsVer[64]; // Version # of the dbms product
590 wxChar driverName[40]; // Driver name
591 wxChar odbcVer[60]; // ODBC version of the driver
592 wxChar drvMgrOdbcVer[60]; // ODBC version of the driver manager
593 wxChar driverVer[60]; // Driver version
594 wxChar serverName[80]; // Server Name, typically a connect string
595 wxChar databaseName[128]; // Database filename
596 wxChar outerJoins[2]; // Indicates whether the data source supports outer joins
597 wxChar procedureSupport[2]; // Indicates whether the data source supports stored procedures
598 wxChar accessibleTables[2]; // Indicates whether the data source only reports accessible tables in SQLTables.
599 UWORD maxConnections; // Maximum # of connections the data source supports
600 UWORD maxStmts; // Maximum # of HSTMTs per HDBC
601 UWORD apiConfLvl; // ODBC API conformance level
602 UWORD cliConfLvl; // Indicates whether the data source is SAG compliant
603 UWORD sqlConfLvl; // SQL conformance level
604 UWORD cursorCommitBehavior; // Indicates how cursors are affected by a db commit
605 UWORD cursorRollbackBehavior; // Indicates how cursors are affected by a db rollback
606 UWORD supportNotNullClause; // Indicates if data source supports NOT NULL clause
607 wxChar supportIEF[2]; // Integrity Enhancement Facility (Referential Integrity)
608 UDWORD txnIsolation; // Default transaction isolation level supported by the driver
609 UDWORD txnIsolationOptions; // Transaction isolation level options available
610 UDWORD fetchDirections; // Fetch directions supported
611 UDWORD lockTypes; // Lock types supported in SQLSetPos
612 UDWORD posOperations; // Position operations supported in SQLSetPos
613 UDWORD posStmts; // Position statements supported
614 UDWORD scrollConcurrency; // Concurrency control options supported for scrollable cursors
615 UDWORD scrollOptions; // Scroll Options supported for scrollable cursors
616 UDWORD staticSensitivity; // Indicates if additions, deletions and updates can be detected
617 UWORD txnCapable; // Indicates if the data source supports transactions
618 UDWORD loginTimeout; // Number seconds to wait for a login request
619 } dbInf;
620
621 // ODBC Error Inf.
622 SWORD cbErrorMsg;
623 int DB_STATUS;
624 #ifdef __VMS
625 // The DECC compiler chokes when in db.cpp the array is accessed outside
626 // its bounds. Maybe this change should also applied for other platforms.
627 wxChar errorList[DB_MAX_ERROR_HISTORY][DB_MAX_ERROR_MSG_LEN+1];
628 #else
629 wxChar errorList[DB_MAX_ERROR_HISTORY][DB_MAX_ERROR_MSG_LEN];
630 #endif
631 wxChar errorMsg[SQL_MAX_MESSAGE_LENGTH];
632 SQLINTEGER nativeError;
633 wxChar sqlState[20];
634
635 #if wxODBC_BACKWARD_COMPATABILITY
636 // Information about logical data types VARCHAR, INTEGER, FLOAT and DATE.
637 //
638 // This information is obtained from the ODBC driver by use of the
639 // SQLGetTypeInfo() function. The key piece of information is the
640 // type name the data source uses for each logical data type.
641 // e.g. VARCHAR; Oracle calls it VARCHAR2.
642 wxDbSqlTypeInfo typeInfVarchar;
643 wxDbSqlTypeInfo typeInfInteger;
644 wxDbSqlTypeInfo typeInfFloat;
645 wxDbSqlTypeInfo typeInfDate;
646 wxDbSqlTypeInfo typeInfBlob;
647 #endif
648
649 // Public member functions
650 wxDb(const HENV &aHenv, bool FwdOnlyCursors=(bool)wxODBC_FWD_ONLY_CURSORS);
651 ~wxDb();
652
653 // Data Source Name, User ID, Password and whether open should fail on data type not supported
654 bool Open(const wxString& inConnectStr, bool failOnDataTypeUnsupported=true);
655 ///This version of Open will open the odbc source selection dialog. Cast a wxWindow::GetHandle() to SQLHWND to use.
656 bool Open(const wxString& inConnectStr, SQLHWND parentWnd, bool failOnDataTypeUnsupported=true);
657 bool Open(const wxString &Dsn, const wxString &Uid, const wxString &AuthStr, bool failOnDataTypeUnsupported=true);
658 bool Open(wxDbConnectInf *dbConnectInf, bool failOnDataTypeUnsupported=true);
659 bool Open(wxDb *copyDb); // pointer to a wxDb whose connection info should be copied rather than re-queried
660 void Close(void);
661 bool CommitTrans(void);
662 bool RollbackTrans(void);
663 bool DispAllErrors(HENV aHenv, HDBC aHdbc = SQL_NULL_HDBC, HSTMT aHstmt = SQL_NULL_HSTMT);
664 bool GetNextError(HENV aHenv, HDBC aHdbc = SQL_NULL_HDBC, HSTMT aHstmt = SQL_NULL_HSTMT);
665 void DispNextError(void);
666 bool CreateView(const wxString &viewName, const wxString &colList, const wxString &pSqlStmt, bool attemptDrop=true);
667 bool DropView(const wxString &viewName);
668 bool ExecSql(const wxString &pSqlStmt);
669 bool ExecSql(const wxString &pSqlStmt, wxDbColInf** columns, short& numcols);
670 bool GetNext(void);
671 bool GetData(UWORD colNo, SWORD cType, PTR pData, SDWORD maxLen, SQLLEN FAR *cbReturned);
672 bool Grant(int privileges, const wxString &tableName, const wxString &userList = wxT("PUBLIC"));
673 int TranslateSqlState(const wxString &SQLState);
674 wxDbInf *GetCatalog(const wxChar *userID=NULL);
675 bool Catalog(const wxChar *userID=NULL, const wxString &fileName=SQL_CATALOG_FILENAME);
676 int GetKeyFields(const wxString &tableName, wxDbColInf* colInf, UWORD noCols);
677
678 wxDbColInf *GetColumns(wxChar *tableName[], const wxChar *userID=NULL);
679 wxDbColInf *GetColumns(const wxString &tableName, UWORD *numCols, const wxChar *userID=NULL);
680
681 int GetColumnCount(const wxString &tableName, const wxChar *userID=NULL);
682 const wxChar *GetDatabaseName(void) {return dbInf.dbmsName;}
683 const wxString &GetDataSource(void) {return dsn;}
684 const wxString &GetDatasourceName(void){return dsn;}
685 const wxString &GetUsername(void) {return uid;}
686 const wxString &GetPassword(void) {return authStr;}
687 const wxString &GetConnectionInStr(void) {return inConnectionStr;}
688 const wxString &GetConnectionOutStr(void) {return outConnectionStr;}
689 bool IsOpen(void) {return dbIsOpen;}
690 bool OpenedWithConnectionString(void) {return dbOpenedWithConnectionString;}
691 HENV GetHENV(void) {return henv;}
692 HDBC GetHDBC(void) {return hdbc;}
693 HSTMT GetHSTMT(void) {return hstmt;}
694 int GetTableCount() {return nTables;} // number of tables using this connection
695 wxDbSqlTypeInfo GetTypeInfVarchar() {return typeInfVarchar;}
696 wxDbSqlTypeInfo GetTypeInfInteger() {return typeInfInteger;}
697 wxDbSqlTypeInfo GetTypeInfFloat() {return typeInfFloat;}
698 wxDbSqlTypeInfo GetTypeInfDate() {return typeInfDate;}
699 wxDbSqlTypeInfo GetTypeInfBlob() {return typeInfBlob;}
700 wxDbSqlTypeInfo GetTypeInfMemo() {return typeInfMemo;}
701
702 // tableName can refer to a table, view, alias or synonym
703 bool TableExists(const wxString &tableName, const wxChar *userID=NULL,
704 const wxString &tablePath=wxEmptyString);
705 bool TablePrivileges(const wxString &tableName, const wxString &priv,
706 const wxChar *userID=NULL, const wxChar *schema=NULL,
707 const wxString &path=wxEmptyString);
708
709 // These two functions return the table name or column name in a form ready
710 // for use in SQL statements. For example, if the datasource allows spaces
711 // in the table name or column name, the returned string will have the
712 // correct enclosing marks around the name to allow it to be properly
713 // included in a SQL statement
714 const wxString SQLTableName(const wxChar *tableName);
715 const wxString SQLColumnName(const wxChar *colName);
716
717 void LogError(const wxString &errMsg, const wxString &SQLState = wxEmptyString)
718 { logError(errMsg, SQLState); }
719 void SetDebugErrorMessages(bool state) { silent = !state; }
720 bool SetSqlLogging(wxDbSqlLogState state, const wxString &filename = SQL_LOG_FILENAME,
721 bool append = false);
722 bool WriteSqlLog(const wxString &logMsg);
723
724 wxDBMS Dbms(void);
725 bool ModifyColumn(const wxString &tableName, const wxString &columnName,
726 int dataType, ULONG columnLength=0,
727 const wxString &optionalParam=wxEmptyString);
728
729 bool FwdOnlyCursors(void) {return fwdOnlyCursors;}
730
731 // return the string with all special SQL characters escaped
732 wxString EscapeSqlChars(const wxString& value);
733
734 // These two functions are provided strictly for use by wxDbTable.
735 // DO NOT USE THESE FUNCTIONS, OR MEMORY LEAKS MAY OCCUR
736 void incrementTableCount() { nTables++; return; }
737 void decrementTableCount() { nTables--; return; }
738
739 }; // wxDb
740
741
742 // This structure forms a node in a linked list. The linked list of "DbList" objects
743 // keeps track of allocated database connections. This allows the application to
744 // open more than one database connection through ODBC for multiple transaction support
745 // or for multiple database support.
746 struct wxDbList
747 {
748 wxDbList *PtrPrev; // Pointer to previous item in the list
749 wxString Dsn; // Data Source Name
750 wxString Uid; // User ID
751 wxString AuthStr; // Authorization string (password)
752 wxString ConnectionStr; // Connection string used instead of DSN
753 wxDb *PtrDb; // Pointer to the wxDb object
754 bool Free; // Is item free or in use?
755 wxDbList *PtrNext; // Pointer to next item in the list
756 };
757
758
759 #ifdef __WXDEBUG__
760 #include "wx/object.h"
761 class wxTablesInUse : public wxObject
762 {
763 public:
764 const wxChar *tableName;
765 ULONG tableID;
766 class wxDb *pDb;
767 }; // wxTablesInUse
768 #endif
769
770
771 // The following routines allow a user to get new database connections, free them
772 // for other code segments to use, or close all of them when the application has
773 // completed.
774 wxDb WXDLLIMPEXP_ODBC *wxDbGetConnection(wxDbConnectInf *pDbConfig, bool FwdOnlyCursors=(bool)wxODBC_FWD_ONLY_CURSORS);
775 bool WXDLLIMPEXP_ODBC wxDbFreeConnection(wxDb *pDb);
776 void WXDLLIMPEXP_ODBC wxDbCloseConnections(void);
777 int WXDLLIMPEXP_ODBC wxDbConnectionsInUse(void);
778
779
780 // Writes a message to the wxLog window (stdout usually) when an internal error
781 // situation occurs. This function only works in DEBUG builds
782 const wxChar WXDLLIMPEXP_ODBC *
783 wxDbLogExtendedErrorMsg(const wxChar *userText,
784 wxDb *pDb,
785 const wxChar *ErrFile,
786 int ErrLine);
787
788
789 // This function sets the sql log state for all open wxDb objects
790 bool WXDLLIMPEXP_ODBC
791 wxDbSqlLog(wxDbSqlLogState state, const wxString &filename = SQL_LOG_FILENAME);
792
793
794 #if 0
795 // MSW/VC6 ONLY!!! Experimental
796 int WXDLLEXPORT wxDbCreateDataSource(const wxString &driverName, const wxString &dsn, const wxString &description=wxEmptyString,
797 bool sysDSN=false, const wxString &defDir=wxEmptyString, wxWindow *parent=NULL);
798 #endif
799
800 // This routine allows you to query a driver manager
801 // for a list of available datasources. Call this routine
802 // the first time using SQL_FETCH_FIRST. Continue to call it
803 // using SQL_FETCH_NEXT until you've exhausted the list.
804 bool WXDLLIMPEXP_ODBC
805 wxDbGetDataSource(HENV henv, wxChar *Dsn, SWORD DsnMaxLength, wxChar *DsDesc,
806 SWORD DsDescMaxLength, UWORD direction = SQL_FETCH_NEXT);
807
808
809 // Change this to 0 to remove use of all deprecated functions
810 #if wxODBC_BACKWARD_COMPATABILITY
811 //#################################################################################
812 //############### DEPRECATED functions for backward compatibility #################
813 //#################################################################################
814
815 // Backward compability structures/classes. This will eventually go away
816 const int DB_PATH_MAX = wxDB_PATH_MAX;
817
818 typedef wxDb wxDB;
819 typedef wxDbTableInf wxTableInf;
820 typedef wxDbColInf wxColInf;
821 typedef wxDbColInf CcolInf;
822 typedef wxDbColFor wxColFor;
823 typedef wxDbSqlTypeInfo SqlTypeInfo;
824 typedef wxDbSqlTypeInfo wxSqlTypeInfo;
825 typedef enum wxDbSqlLogState sqlLog;
826 typedef enum wxDbSqlLogState wxSqlLogState;
827 typedef enum wxDBMS dbms;
828 typedef enum wxDBMS DBMS;
829 typedef wxODBC_ERRORS ODBC_ERRORS;
830 typedef wxDbConnectInf DbStuff;
831 typedef wxDbList DbList;
832 #ifdef __WXDEBUG__
833 typedef wxTablesInUse CstructTablesInUse;
834 #endif
835
836 // Deprecated function names that are replaced by the function names listed above
837 wxDB WXDLLIMPEXP_ODBC
838 *GetDbConnection(DbStuff *pDbStuff, bool FwdOnlyCursors=(bool)wxODBC_FWD_ONLY_CURSORS);
839 bool WXDLLIMPEXP_ODBC FreeDbConnection(wxDB *pDb);
840 void WXDLLIMPEXP_ODBC CloseDbConnections(void);
841 int WXDLLIMPEXP_ODBC NumberDbConnectionsInUse(void);
842
843 bool SqlLog(sqlLog state, const wxChar *filename = SQL_LOG_FILENAME);
844
845 bool WXDLLIMPEXP_ODBC
846 GetDataSource(HENV henv, char *Dsn, SWORD DsnMaxLength, char *DsDesc, SWORD DsDescMaxLength,
847 UWORD direction = SQL_FETCH_NEXT);
848
849 #endif // Deprecated structures/classes/functions
850
851 #endif // _WX_DB_H_
852