-
Notifications
You must be signed in to change notification settings - Fork 7
/
odbc.cpp
4117 lines (3611 loc) · 103 KB
/
odbc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 1999-2018 David Muse
// See the file COPYING for more information
// note that config.h must come first to avoid some macro redefinition warnings
#include <config.h>
// windows needs this and it doesn't appear to hurt on other platforms
#include <rudiments/private/winsock.h>
#include <sql.h>
#include <sqlext.h>
#include <sqlucode.h>
#include <sqltypes.h>
// more gyrations to avoid macro redefinition warnings
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
// note that sqlrserver.h must be included after sqltypes.h to
// get around a problem with CHAR/xmlChar in gnome-xml
#include <sqlrelay/sqlrserver.h>
#include <rudiments/charstring.h>
#include <rudiments/ucs2character.h>
#include <rudiments/ucs2charstring.h>
#include <rudiments/utf8character.h>
#include <rudiments/utf8charstring.h>
#include <rudiments/utf16character.h>
#include <rudiments/utf16charstring.h>
#include <rudiments/error.h>
#include <rudiments/stdio.h>
#include <rudiments/process.h>
#include <rudiments/sys.h>
#include <datatypes.h>
#include <defines.h>
#ifdef HAVE_IODBC
#include <iodbcinst.h>
#endif
#define MAX_LOB_CHUNK_SIZE 2147483647
struct odbccolumn {
char name[4096];
uint16_t namesize;
#if (ODBCVER >= 0x0300) && defined(SQLCOLATTRIBUTE_SQLLEN)
SQLLEN type;
SQLLEN size;
SQLLEN precision;
SQLLEN scale;
SQLLEN nullable;
SQLLEN unsignednumber;
SQLLEN autoincrement;
#else
SQLINTEGER type;
SQLINTEGER size;
SQLINTEGER precision;
SQLINTEGER scale;
SQLINTEGER nullable;
SQLINTEGER unsignednumber;
SQLINTEGER autoincrement;
#endif
char table[4096];
uint16_t tablesize;
};
struct datebind {
int16_t *year;
int16_t *month;
int16_t *day;
int16_t *hour;
int16_t *minute;
int16_t *second;
int32_t *microsecond;
const char **tz;
SQL_TIMESTAMP_STRUCT buffer;
};
struct charbind {
char *value;
uint32_t valuesize;
};
class odbcconnection;
class SQLRSERVER_DLLSPEC odbccursor : public sqlrservercursor {
friend class odbcconnection;
private:
odbccursor(sqlrserverconnection *conn, uint16_t id);
~odbccursor();
void allocateResultSetBuffers(int32_t columncount);
void deallocateResultSetBuffers();
bool prepareQuery(const char *query,
uint32_t size);
bool allocateStatementHandle();
void initializeColCounts();
void initializeRowCounts();
bool inputBind(const char *variable,
uint16_t variablesize,
const char *value,
uint32_t valuesize,
int16_t *isnull);
bool inputBind(const char *variable,
uint16_t variablesize,
int64_t *value);
bool inputBind(const char *variable,
uint16_t variablesize,
double *value,
uint32_t precision,
uint32_t scale);
bool inputBind(const char *variable,
uint16_t variablesize,
int64_t year,
int16_t month,
int16_t day,
int16_t hour,
int16_t minute,
int16_t second,
int32_t microsecond,
const char *tz,
bool isnegative,
int16_t *isnull);
bool inputBindBlob(const char *variable,
uint16_t variablesize,
const char *value,
uint32_t valuesize,
int16_t *isnull);
bool outputBind(const char *variable,
uint16_t variablesize,
char *value,
uint32_t valuesize,
int16_t *isnull);
bool outputBind(const char *variable,
uint16_t variablesize,
int64_t *value,
int16_t *isnull);
bool outputBind(const char *variable,
uint16_t variablesize,
double *value,
uint32_t *precision,
uint32_t *scale,
int16_t *isnull);
bool outputBind(const char *variable,
uint16_t variablesize,
int16_t *year,
int16_t *month,
int16_t *day,
int16_t *hour,
int16_t *minute,
int16_t *second,
int32_t *microsecond,
const char **tz,
bool *isnegative,
int16_t *isnull);
bool inputOutputBind(const char *variable,
uint16_t variablesize,
char *value,
uint32_t valuesize,
int16_t *isnull);
bool inputOutputBind(const char *variable,
uint16_t variablesize,
int64_t *value,
int16_t *isnull);
bool inputOutputBind(const char *variable,
uint16_t variablesize,
double *value,
uint32_t *precision,
uint32_t *scale,
int16_t *isnull);
bool inputOutputBind(const char *variable,
uint16_t variablesize,
int16_t *year,
int16_t *month,
int16_t *day,
int16_t *hour,
int16_t *minute,
int16_t *second,
int32_t *microsecond,
const char **tz,
bool *isnegative,
int16_t *isnull);
int16_t getNonNullBindValue();
int16_t getNullBindValue();
bool executeQuery(const char *query,
uint32_t size);
bool handleColumns(bool getcolumninfo,
bool bindcolumns);
void getError(char *errorbuffer,
uint32_t errorbuffersize,
uint32_t *errorsize,
int64_t *errorcode,
bool *liveconnection);
uint64_t getAffectedRows();
uint32_t colCount();
const char *getColumnName(uint32_t i);
uint16_t getColumnNameSize(uint32_t i);
uint16_t getColumnType(uint32_t i);
uint32_t getColumnSize(uint32_t i);
uint32_t getColumnPrecision(uint32_t i);
uint32_t getColumnScale(uint32_t i);
uint16_t getColumnIsNullable(uint32_t i);
uint16_t getColumnIsUnsigned(uint32_t i);
uint16_t getColumnIsBinary(uint32_t i);
uint16_t getColumnIsAutoIncrement(uint32_t i);
const char *getColumnTable(uint32_t i);
uint16_t getColumnTableSize(uint32_t i);
bool noRowsToReturn();
bool fetchRow(bool *error);
void getField(uint32_t col,
const char **field,
uint64_t *fieldsize,
bool *lob,
bool *null);
bool getLobFieldLength(uint32_t col, uint64_t *size);
bool getLobFieldSegment(uint32_t col,
char *buffer, uint64_t buffersize,
uint64_t offset, uint64_t charstoread,
uint64_t *charsread);
bool nextResultSet(bool *nextresultsetavailable);
void closeResultSet();
bool columnInfoIsValidAfterPrepare();
#if (ODBCVER >= 0x0300) && defined(SQLCOLATTRIBUTE_SQLLEN)
bool isLob(SQLLEN type);
#else
bool isLob(SQLINTEGER type);
#endif
void setConvCharError(const char *baseerror,
const char *detailerror);
SQLRETURN erg;
SQLHSTMT stmt;
SQLSMALLINT ncols;
#ifdef SQLROWCOUNT_SQLLEN
SQLLEN affectedrows;
#else
SQLINTEGER affectedrows;
#endif
int32_t columncount;
char **field;
#ifdef SQLBINDCOL_SQLLEN
SQLLEN *loblength;
SQLLEN *indicator;
#else
SQLINTEGER *loblength;
SQLINTEGER *indicator;
#endif
odbccolumn *column;
uint16_t maxbindcount;
SQL_DATE_STRUCT *indatebind;
SQL_TIME_STRUCT *intimebind;
SQL_TIMESTAMP_STRUCT *intsbind;
datebind **outdatebind;
charbind **outcharbind;
int16_t **outisnullptr;
datebind **inoutdatebind;
charbind **inoutcharbind;
int16_t **inoutisnullptr;
#ifdef SQLBINDPARAMETER_SQLLEN
SQLLEN *outisnull;
SQLLEN *inoutisnull;
SQLLEN sqlnulldata;
#else
SQLINTEGER *outisnull;
SQLINTEGER *inoutisnull;
SQLINTEGER sqlnulldata;
#endif
bool bindformaterror;
uint32_t row;
uint32_t maxrow;
uint32_t totalrows;
stringbuffer errormsg;
#ifdef HAVE_SQLCONNECTW
singlylinkedlist<byte_t *> ucsinbindstrings;
#endif
bool columninfoisvalidafterprepare;
odbcconnection *odbcconn;
char columnnamescratch[4096];
};
class SQLRSERVER_DLLSPEC odbcconnection : public sqlrserverconnection {
friend class odbccursor;
public:
odbcconnection(sqlrservercontroller *cont);
~odbcconnection();
private:
void handleConnectString();
bool logIn(const char **error, const char **warning);
char *odbcDriverConnectionString(
const char *userasc,
const char *passwordasc);
void pushConnstrValue(char **pptr,
size_t *pbuffavail,
const char *keyword,
const char *value);
char *traceFileName(const char *tracefilenameformat);
const char *logInError(const char *errmsg);
sqlrservercursor *newCursor(uint16_t id);
void deleteCursor(sqlrservercursor *curs);
void logOut();
#if (ODBCVER>=0x0300)
bool setAutoCommitOn();
bool setAutoCommitOff();
const char *beginTransactionQuery();
bool commit();
bool rollback();
void getError(char *errorbuffer,
uint32_t errorbuffersize,
uint32_t *errorsize,
int64_t *errorcode,
bool *liveconnection);
#endif
bool isLiveConnection(SQLCHAR *state);
bool ping();
const char *getDbType();
const char *getDbVersion();
const char *getBindFormat();
const char *getNextvalFormat();
const char *getLastInsertIdQuery();
bool getListsByApiCalls();
sqlrserverlistformat_t getNativeDatabaseListFormat();
sqlrserverlistformat_t getNativeSchemaListFormat();
sqlrserverlistformat_t getNativeTableListFormat();
sqlrserverlistformat_t getNativeTableTypeListFormat();
sqlrserverlistformat_t getNativeColumnListFormat();
sqlrserverlistformat_t getNativePrimaryKeyListFormat();
sqlrserverlistformat_t getNativeKeyAndIndexListFormat();
sqlrserverlistformat_t getNativeProcedureParameterListFormat();
sqlrserverlistformat_t getNativeTypeInfoListFormat();
sqlrserverlistformat_t getNativeProcedureListFormat();
bool getDatabaseList(sqlrservercursor *cursor,
const char *wild);
bool getSchemaList(sqlrservercursor *cursor,
const char *wild);
bool getTableList(sqlrservercursor *cursor,
const char *wild,
uint16_t objecttypes);
bool getTableTypeList(sqlrservercursor *cursor,
const char *wild);
bool isCurrentCatalog(const char *name);
bool getColumnList(sqlrservercursor *cursor,
const char *table,
const char *wild);
bool getPrimaryKeyList(sqlrservercursor *cursor,
const char *table,
const char *wild);
bool getKeyAndIndexList(sqlrservercursor *cursor,
const char *table,
const char *wild);
bool getProcedureParameterList(
sqlrservercursor *cursor,
const char *procedure,
const char *wild);
bool getTypeInfoList(sqlrservercursor *cursor,
const char *type,
const char *wild);
bool getProcedureList(sqlrservercursor *cursor,
const char *wild);
const char *selectDatabaseQuery();
char *getCurrentDatabase();
char *getCurrentSchema();
bool setIsolationLevel(const char *isolevel);
const char *getDbHostNameQuery();
const char *getDbIpAddressQuery();
SQLRETURN erg;
SQLHENV env;
SQLHDBC dbc;
const char *driver;
const char *driverconnect;
const char *dsn;
const char *server;
const char *db;
const char *trace;
const char *tracefile;
const char *odbcversion;
const char *lastinsertidquery;
bool mars;
bool getcolumntables;
const char *overrideschema;
bool unicode;
const char *ncharencoding;
stringbuffer errormessage;
char dbversion[512];
const char *begintxquery;
bool usecharforlobbind;
SQLSMALLINT fractionscale;
bool supportsfraction;
bool timestampfortime;
uint32_t maxallowedvarcharbindsize;
uint32_t maxvarcharbindsize;
SQLINTEGER *columninfonotvalidyeterror;
bool sqltypedatetosqlcbinary;
bool fetchlobsasstrings;
#if (ODBCVER>=0x0300)
stringbuffer errormsg;
#endif
};
#ifdef HAVE_SQLCONNECTW
#include <rudiments/iconvert.h>
size_t isUcs2(const char *encoding) {
return (charstring::contains(encoding,"UCS2") ||
charstring::contains(encoding,"UCS-2"));
}
size_t isUtf16(const char *encoding) {
return (charstring::contains(encoding,"UTF16") ||
charstring::contains(encoding,"UTF-16"));
}
size_t isUtf8(const char *encoding) {
return (charstring::contains(encoding,"UTF8") ||
charstring::contains(encoding,"UTF-8"));
}
// returns number of characters in the (null-terminated) string
size_t len(const byte_t *str, const char *encoding) {
const byte_t *ptr=str;
size_t res=0;
if (isUcs2(encoding)) {
// skip any byte-order mark
if (ucs2charstring::isByteOrderMark((const ucs2_t *)str)) {
ptr+=ucs2character::getBomSize();
}
res=ucs2charstring::getLength((ucs2_t *)ptr);
} else if (isUtf16(encoding)) {
// skip any byte-order mark
bool bigendian=false;
if (utf16charstring::isByteOrderMark(
(const utf16_t *)str)) {
bigendian=utf16charstring::isBigEndian(
(const utf16_t *)str);
ptr+=utf16character::getBomSize();
}
res=utf16charstring::getLength((utf16_t *)ptr,bigendian);
} else if (isUtf8(encoding)) {
// skip any byte-order mark
if (utf8charstring::isByteOrderMark((const utf8_t *)str)) {
ptr+=utf8character::getBomSize();
}
res=utf8charstring::getLength((utf8_t *)ptr);
} else {
res=charstring::getLength((const char *)str);
}
return res;
}
// returns number of bytes in the (null-terminated) string
size_t stringSize(const byte_t *str, const char *encoding) {
const byte_t *ptr=str;
size_t res=0;
if (isUcs2(encoding)) {
// skip any byte-order mark
if (ucs2charstring::isByteOrderMark((const ucs2_t *)str)) {
res+=ucs2character::getBomSize();
ptr+=ucs2character::getBomSize();
}
res+=ucs2charstring::getSize((ucs2_t *)ptr);
} else if (isUtf16(encoding)) {
// skip any byte-order mark
bool bigendian=false;
if (utf16charstring::isByteOrderMark(
(const utf16_t *)str)) {
bigendian=utf16charstring::isBigEndian(
(const utf16_t *)str);
res+=utf16character::getBomSize();
ptr+=utf16character::getBomSize();
}
res+=utf16charstring::getSize((utf16_t *)ptr,bigendian);
} else if (isUtf8(encoding)) {
// skip any byte-order mark
if (utf8charstring::isByteOrderMark((const utf8_t *)str)) {
res+=utf8character::getBomSize();
ptr+=utf8character::getBomSize();
}
res+=utf8charstring::getSize((utf8_t *)ptr);
} else {
res=charstring::getLength((const char *)str);
}
return res;
}
size_t nullSize(const char *encoding) {
if (isUcs2(encoding)) {
return ucs2character::getNullSize();
} else if (isUtf16(encoding)) {
return 2;
} else if (isUtf8(encoding)) {
return 1;
} else {
return character::getNullSize();
}
}
byte_t *convertCharset(const byte_t *inbuf,
size_t insize,
const char *inenc,
const char *outenc,
char **error) {
// initialize error
if (error) {
*error=NULL;
}
// get size of null terminator
size_t nullsize=nullSize(outenc);
// calculate size of output buffer (in bytes)
// (3 is max size of byte order mark)
size_t multiplier=4;
if (isUcs2(inenc) && isUcs2(outenc)) {
multiplier=1;
}
size_t outsize=len(inbuf,inenc)*multiplier+3+nullsize;
// allocate the output buffer
byte_t *outbuf=new byte_t[outsize];
// open converter
// FIXME: reuse this rather than re-creating it over and over
iconvert ic;
ic.setFromEncoding(inenc);
ic.setFromBuffer(inbuf);
ic.setFromBufferSize(insize);
ic.setToEncoding(outenc);
ic.setToBuffer(outbuf);
ic.setToBufferSize(outsize);
// convert
if (!ic.convert()) {
if (error) {
char *err=error::getErrorString();
charstring::printf(error,
"iconvert::convert(): %s "
"(in=%s/%ld/%ld out=%s/%ld/%ld)",
err,
inenc,insize,ic.getFromBufferPosition()-inbuf,
outenc,outsize,ic.getToBufferPosition()-outbuf);
delete[] err;
}
// null-terminate the output
bytestring::zero(outbuf,nullsize);
return outbuf;
}
byte_t *outbufend=(byte_t *)ic.getToBufferPosition();
// SQL Server doesn't like UTF-16 values to have a byte-order mark
// (and it wants them to be big-endian)
// FIXME: make this configurable somehow...
if (isUtf16(outenc) &&
((outbuf[0]==0xFF && outbuf[1]==0xFE) ||
(outbuf[0]==0xFE && outbuf[1]==0xFF))) {
bytestring::copyWithOverlap(outbuf,outbuf+2,outbufend-outbuf-2);
outbufend-=2;
}
// null-terminate the output
bytestring::zero(outbufend,nullsize);
return outbuf;
}
byte_t *convertCharset(const byte_t *inbuf,
const char *inenc,
const char *outenc,
char **error) {
return convertCharset(inbuf,stringSize(inbuf,inenc),inenc,outenc,error);
}
#endif
odbcconnection::odbcconnection(sqlrservercontroller *cont) :
sqlrserverconnection(cont) {
driver=NULL;
driverconnect=NULL;
dsn=NULL;
server=NULL;
db=NULL;
trace=NULL;
tracefile=NULL;
odbcversion=NULL;
lastinsertidquery=NULL;
mars=false;
getcolumntables=false;
overrideschema=NULL;
unicode=true;
ncharencoding=NULL;
columninfonotvalidyeterror=NULL;
}
odbcconnection::~odbcconnection() {
delete[] columninfonotvalidyeterror;
}
void odbcconnection::handleConnectString() {
sqlrserverconnection::handleConnectString();
driver=cont->getConnectStringValue("driver");
driverconnect=cont->getConnectStringValue("driverconnect");
dsn=cont->getConnectStringValue("dsn");
server=cont->getConnectStringValue("server");
db=cont->getConnectStringValue("db");
trace=cont->getConnectStringValue("trace");
tracefile=cont->getConnectStringValue("tracefile");
odbcversion=cont->getConnectStringValue("odbcversion");
lastinsertidquery=cont->getConnectStringValue("lastinsertidquery");
mars=charstring::isYes(cont->getConnectStringValue("mars"));
getcolumntables=charstring::isYes(
cont->getConnectStringValue("getcolumntables"));
const char *os=cont->getConnectStringValue("overrideschema");
if (!charstring::isNullOrEmpty(os)) {
overrideschema=os;
}
unicode=!charstring::isNo(cont->getConnectStringValue("unicode"));
ncharencoding=cont->getConnectStringValue("ncharencoding");
if (charstring::isNullOrEmpty(ncharencoding) ||
(charstring::compare(ncharencoding,"UCS2",4) &&
charstring::compare(ncharencoding,"UCS-2",5) &&
charstring::compare(ncharencoding,"UTF16",5) &&
charstring::compare(ncharencoding,"UTF-16",6))) {
ncharencoding="UCS-2//TRANSLIT";
}
// unixodbc doesn't support array fetches
cont->setFetchAtOnce(1);
}
bool odbcconnection::logIn(const char **error, const char **warning) {
// allocate environment handle
#if (ODBCVER >= 0x0300)
erg=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
if (erg!=SQL_SUCCESS && erg!=SQL_SUCCESS_WITH_INFO) {
*error="Failed to allocate environment handle";
SQLFreeHandle(SQL_HANDLE_ENV,env);
return false;
}
if (!charstring::compare(odbcversion,"2")) {
erg=SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,
(void *)SQL_OV_ODBC2,0);
#ifdef SQL_OV_ODBC3_80
} else if (!charstring::compare(odbcversion,"3.8")) {
erg=SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,
(void *)SQL_OV_ODBC3_80,0);
#endif
} else {
erg=SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,
(void *)SQL_OV_ODBC3,0);
}
#else
erg=SQLAllocEnv(&env);
#endif
if (erg!=SQL_SUCCESS && erg!=SQL_SUCCESS_WITH_INFO) {
*error="Failed to allocate environment handle";
return false;
}
// allocate connection handle
#if (ODBCVER >= 0x0300)
erg=SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
#else
erg=SQLAllocConnect(env,&dbc);
#endif
if (erg!=SQL_SUCCESS && erg!=SQL_SUCCESS_WITH_INFO) {
*error="Failed to allocate connection handle";
#if (ODBCVER >= 0x0300)
SQLFreeHandle(SQL_HANDLE_ENV,env);
#else
SQLFreeEnv(env);
#endif
return false;
}
#if (ODBCVER >= 0x0300)
// trace paramters may have been set in the DSN,
// but we can also override them here...
if (!charstring::isNullOrEmpty(tracefile)) {
// FIXME: does this need to persist?
char *tracefilename=traceFileName(tracefile);
erg=SQLSetConnectAttr(dbc,
SQL_ATTR_TRACEFILE,
(SQLPOINTER *)tracefilename,
SQL_NTS);
delete[] tracefilename;
}
if (charstring::isYes(trace)) {
erg=SQLSetConnectAttr(dbc,
SQL_ATTR_TRACE,
(SQLPOINTER *)SQL_OPT_TRACE_ON,
0);
} else if (charstring::isNo(trace)) {
erg=SQLSetConnectAttr(dbc,
SQL_ATTR_TRACE,
(SQLPOINTER *)SQL_OPT_TRACE_OFF,
0);
}
// set the initial db
if (!charstring::isNullOrEmpty(db)) {
erg = SQLSetConnectAttr(dbc,SQL_ATTR_CURRENT_CATALOG,
(SQLPOINTER *)db,SQL_NTS);
if (erg!=SQL_SUCCESS && erg!=SQL_SUCCESS_WITH_INFO) {
*error="Failed to set database";
SQLFreeHandle(SQL_HANDLE_DBC,dbc);
SQLFreeHandle(SQL_HANDLE_ENV,env);
return false;
}
}
// set the connect timeout
uint64_t connecttimeout=cont->getConnectTimeout();
if (connecttimeout) {
erg=SQLSetConnectAttr(dbc,SQL_LOGIN_TIMEOUT,
(SQLPOINTER *)connecttimeout,0);
if (erg!=SQL_SUCCESS && erg!=SQL_SUCCESS_WITH_INFO) {
*error="Failed to set connect timeout";
SQLFreeHandle(SQL_HANDLE_DBC,dbc);
SQLFreeHandle(SQL_HANDLE_ENV,env);
return false;
}
}
#endif
// enable SQL Server MARS, if configured to do so
if (mars) {
SQLSetConnectAttr(dbc,1224,(SQLPOINTER *)1,SQL_IS_UINTEGER);
}
// connect to the database
const char *userasc=cont->getUser();
const char *passwordasc=cont->getPassword();
if (!charstring::isNullOrEmpty(driver)) {
char *sqlconnectdriverstring=
odbcDriverConnectionString(userasc,passwordasc);
// These values are useful to look at from the debugger,
// it is not a good security practice to directly log
// the string, because it might contain a plaintext password.
SQLCHAR outconnectionstring[2048];
SQLSMALLINT outconnectionstringlen;
erg=SQLDriverConnect(dbc,
(SQLHWND)NULL,
(SQLCHAR *)sqlconnectdriverstring,
(SQLSMALLINT)charstring::getLength(
sqlconnectdriverstring),
outconnectionstring,
(SQLSMALLINT)sizeof(outconnectionstring),
&outconnectionstringlen,
(SQLSMALLINT)SQL_DRIVER_NOPROMPT);
delete[] sqlconnectdriverstring;
} else {
const char *dsnasc=dsn;
#ifdef HAVE_SQLCONNECTW
if (unicode) {
byte_t *dsnucs=(dsnasc)?
convertCharset((const byte_t *)
dsnasc,
"UTF-8",
"UCS-2//TRANSLIT",
NULL):NULL;
byte_t *userucs=(userasc)?
convertCharset((const byte_t *)
userasc,
"UTF-8",
"UCS-2//TRANSLIT",
NULL):NULL;
byte_t *passworducs=(passwordasc)?
convertCharset((const byte_t *)
passwordasc,
"UTF-8",
"UCS-2//TRANSLIT",
NULL):NULL;
erg=SQLConnectW(dbc,(SQLWCHAR *)dsnucs,SQL_NTS,
(SQLWCHAR *)userucs,SQL_NTS,
(SQLWCHAR *)passworducs,SQL_NTS);
delete[] dsnucs;
delete[] userucs;
delete[] passworducs;
} else {
#endif
erg=SQLConnect(dbc,(SQLCHAR *)dsnasc,SQL_NTS,
(SQLCHAR *)userasc,SQL_NTS,
(SQLCHAR *)passwordasc,SQL_NTS);
#ifdef HAVE_SQLCONNECTW
}
#endif
}
if (erg==SQL_SUCCESS_WITH_INFO) {
*warning=logInError(NULL);
} else if (erg!=SQL_SUCCESS) {
*error=logInError("SQLConnect failed");
#if (ODBCVER >= 0x0300)
SQLFreeHandle(SQL_HANDLE_DBC,dbc);
SQLFreeHandle(SQL_HANDLE_ENV,env);
#else
SQLFreeConnect(dbc);
SQLFreeEnv(env);
#endif
return false;
}
// get the type of database
char dbmsnamebuffer[1024];
dbmsnamebuffer[0]='\0';
SQLSMALLINT dbmsnamelen=0;
if (SQLGetInfo(dbc,
SQL_DBMS_NAME,
dbmsnamebuffer,
sizeof(dbmsnamebuffer),
&dbmsnamelen)==SQL_SUCCESS) {
dbmsnamebuffer[dbmsnamelen]='\0';
}
// set some default params
begintxquery=sqlrserverconnection::beginTransactionQuery();
usecharforlobbind=true;
// When binding dates using SQLBindParameter, the "decimal
// digits" parameter refers to the number of digits in the
// "fraction" part of the date. Since that is in nanoseconds
// (billionths of a second (0-999999999)) in ODBC, the
// "decimal digits" parameter must be 9 to accomodate the
// full range.
fractionscale=9;
supportsfraction=true;
timestampfortime=true;
maxallowedvarcharbindsize=0;
maxvarcharbindsize=0;
columninfonotvalidyeterror=NULL;
sqltypedatetosqlcbinary=true;
fetchlobsasstrings=false;
// override some default params based on the db-type
if (!charstring::compare(dbmsnamebuffer,"Teradata")) {
begintxquery="BT";
usecharforlobbind=false;
// See below... Teradata only supports 6 digits though.
fractionscale=6;
// Well... Teradata theoretically supports 6 digits of
// fractional seconds, but any attempt to actually bind
// fractional seconds results in "[Teradata][Support] (40520)
// Datetime field overflow resulting from invalid datetime."
supportsfraction=false;
// Teradata doesn't like it if you bind a SQL_TIMESTAMP_STRUCT
// to a TIME datatype.
timestampfortime=false;
} else if (!charstring::compare(dbmsnamebuffer,
"Microsoft SQL Server",20)) {
// SQL Server defines a varchar/nvarchar as 4000 characters
// long, but you can actually store up to 2Gb in them.
// However, if you send a valuesize > 4000 characters during
// a bind, then something in the chain doesn't like it. To
// work around this, you have to send 0. Go figure...
maxallowedvarcharbindsize=4000;
maxvarcharbindsize=0;
// With MS SQL Server, there are various cases where column
// metadata can't be fetched until post-execute. For example:
//
// sqlrsh commands like:
// inputbind 1 = 'hello';
// select ?;
// fail with:
// 11521:
// [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]
// The metadata could not be determined because statement
// 'select @P1' uses an undeclared parameter in a context
// that affects its metadata.
// Sored procedures that optionally execute selects which
// return different numbers of columns fail with:
// 11512:
// [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]
// The metadata could not be determined because the
// statement '...some select query...' is not compatible
// with the statement '...some other select query...' in
// procedure '...some procedure...'.
// So, in cases like this we can catch the error and defer
// getting/sending column info until later.
// Basically, it's error codes 11509-11530 but there could be
// others too...
columninfonotvalidyeterror=new SQLINTEGER[23];
columninfonotvalidyeterror[0]=11509;
columninfonotvalidyeterror[1]=11510;
columninfonotvalidyeterror[2]=11511;
columninfonotvalidyeterror[3]=11512;
columninfonotvalidyeterror[4]=11513;
columninfonotvalidyeterror[5]=11514;
columninfonotvalidyeterror[6]=11515;
columninfonotvalidyeterror[7]=11516;
columninfonotvalidyeterror[8]=11517;
columninfonotvalidyeterror[9]=11518;
columninfonotvalidyeterror[10]=11519;
columninfonotvalidyeterror[11]=11520;
columninfonotvalidyeterror[12]=11521;
columninfonotvalidyeterror[13]=11522;
columninfonotvalidyeterror[14]=11523;
columninfonotvalidyeterror[15]=11524;
columninfonotvalidyeterror[16]=11525;
columninfonotvalidyeterror[17]=11526;
columninfonotvalidyeterror[18]=11527;
columninfonotvalidyeterror[19]=11528;
columninfonotvalidyeterror[20]=11529;
columninfonotvalidyeterror[21]=11530;
columninfonotvalidyeterror[22]=0;
// SQL Server doesn't like for you to convert SQL_TYPE_DATE
// to SQL_C_BINARY
sqltypedatetosqlcbinary=false;
// SQL Server has trouble mixing SQLBindCol and SQLGetData.
// If you SQLBindCol a column (eg. column 4) then you can't use
// SQLGetData to fetch an earlier column (eg. column 3).
// A workaround is to use SQLBindCol in all cases and fetch
// LOBs as strings.
fetchlobsasstrings=true;
// SQL Server likes "BEGIN TRANSACTION" to begin transactions.
begintxquery="BEGIN TRANSACTION";
}
return true;
}
char *odbcconnection::traceFileName(const char *tracefilenameformat) {
// This would be a good candidate for promotion to rudiments,
// These format operators are enough to provide a unique log file
// name, per-process:
// %p means PID
// %t means a timestamp.
// %h means the hostname.
// If any of these appears more than once then the output filename
// may be truncated.
pid_t pid=process::getProcessId();
datetime dt;
dt.initFromSystemDateTime();
time_t now=dt.getEpoch();
char *hostname=sys::getHostName();