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