-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathRODBC.c
1565 lines (1411 loc) · 46.5 KB
/
RODBC.c
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
/*
* RODDC/src/RODBC.c
* M. Lapsley Copyright (C) 1999-2002
* B. D. Ripley Copyright (C) 2002-2024
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License is available at
* http://www.r-project.org/Licenses/
*/
/* RODBC low level interface
*
*/
#include "config.h"
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stddef.h>
#include <math.h>
#ifdef WIN32
# include <windows.h>
# undef ERROR
/* enough of the internals of graphapp objects to allow us to find the
handle of the RGui main window */
typedef struct objinfo {
int kind, refcount;
HANDLE handle;
} *window;
__declspec(dllimport) window RConsole;
#else
# include <unistd.h>
#endif
#include <string.h>
#include <limits.h> /* for INT_MAX */
#define MAX_CHANNELS 1000
#include <sql.h>
#include <sqlext.h>
#include <R.h>
#include <Rinternals.h>
//#include <Rdefines.h>
#ifdef ENABLE_NLS
#include <libintl.h>
#define _(String) dgettext ("RODBC", String)
#define gettext_noop(String) String
#else
#define _(String) (String)
#define gettext_noop(String) String
#endif
#define my_min(a,b) ((a < b)?a:b)
#define COLMAX 256
#ifndef SQL_NO_DATA
# define SQL_NO_DATA_FOUND /* for iODBC */
#endif
#define NCOLS thisHandle->nColumns /* save some column space for typing*/
#define NROWS thisHandle->nRows
/* For 64-bit ODBC, Microsoft did some redefining, see
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/dasdkodbcoverview_64bit.asp
Some people think this corresponded to increasing the version to 3.52,
but none of MinGW, unixODBC or iodbc seem to have done so.
Given that, how do we know what these mean?
MinGW[-w64]: if _WIN64 is defined, they are 64-bit, otherwise (unsigned) long.
unixODBC: if SIZEOF_LONG == 8 && BUILD_REAL_64_BIT_MODE they are
64-bit. In applications, SIZEOF_LONG == 8 is determined by
if defined(__alpha) || defined(__sparcv9) || defined(__LP64__)
We have no way of knowing if BUILD_REAL_64_BIT_MODE was defined,
but Debian which does define also modifies the headers.
iobdc: if _WIN64 is defined, they are 64-bit
Otherwise, they are (unsigned) long.
*/
#ifndef HAVE_SQLLEN
#define SQLLEN SQLINTEGER
#endif
#ifndef HAVE_SQLULEN
#define SQLULEN SQLUINTEGER
#endif
/* Note that currently we will allocate large buffers for long char
types whatever rows_at_time is. */
#define MAX_ROWS_FETCH 1024
typedef struct cols {
SQLCHAR ColName[256];
SQLSMALLINT NameLength;
SQLSMALLINT DataType;
SQLULEN ColSize;
SQLSMALLINT DecimalDigits;
SQLSMALLINT Nullable;
char *pData;
int datalen;
SQLDOUBLE RData [MAX_ROWS_FETCH];
SQLREAL R4Data[MAX_ROWS_FETCH];
SQLINTEGER IData [MAX_ROWS_FETCH];
SQLSMALLINT I2Data[MAX_ROWS_FETCH];
SQLLEN IndPtr[MAX_ROWS_FETCH];
} COLUMNS;
typedef struct mess {
SQLCHAR *message;
struct mess *next;
} SQLMSG;
typedef struct rodbcHandle {
SQLHDBC hDbc; /* connection handle */
SQLHSTMT hStmt; /* statement handle */
SQLLEN nRows; /* number of rows and columns in result set */
SQLSMALLINT nColumns;
int channel; /* as stored on the R-level object */
int id; /* ditto */
int useNRows; /* value of believeNRows */
/* entries used to bind data for result sets and updates */
COLUMNS *ColData; /* this will be allocated as an array */
int nAllocated; /* how many cols were allocated */
SQLUINTEGER rowsFetched; /* use to indicate the number of rows fetched */
SQLUINTEGER rowArraySize; /* use to indicate the number of rows we expect back */
SQLUINTEGER rowsUsed; /* for when we fetch more than we need */
SQLMSG *msglist; /* root of linked list of messages */
SEXP extPtr; /* address of external pointer for this
channel, so we can clear it */
} RODBCHandle, *pRODBCHandle;
static unsigned int nChannels = 0; /* number of channels opened in session */
static pRODBCHandle opened_handles[MAX_CHANNELS+1];
static SQLHENV hEnv=NULL;
/* forward declarations */
static void geterr(pRODBCHandle thisHandle);
static void errorFree(SQLMSG *node);
static void errlistAppend(pRODBCHandle thisHandle, const char *string);
static int cachenbind(pRODBCHandle thisHandle, int nRows);
/* Error messages */
static char
err_SQLAllocStmt[]=gettext_noop("[RODBC] ERROR: Could not SQLAllocStmt");
/* called at first connection or first listing of data sources */
static void odbcInit(void)
{
SQLRETURN retval;
if(!hEnv) {
retval = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
if(retval == SQL_SUCCESS || retval == SQL_SUCCESS_WITH_INFO) {
SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION,
(SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
} else
Rf_error(_("[RODBC] ERROR: Could not SQLAllocEnv"));
}
}
/* called from .onUnload */
SEXP RODBCTerm(void)
{
if(!hEnv) SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
return R_NilValue;
}
/* called before SQL queries (indirect and direct) */
static void clearresults(pRODBCHandle thisHandle)
{
if(thisHandle->hStmt) {
(void)SQLFreeStmt(thisHandle->hStmt, SQL_CLOSE);
(void)SQLFreeHandle(SQL_HANDLE_STMT, thisHandle->hStmt);
thisHandle->hStmt = NULL;
}
errorFree(thisHandle->msglist);
thisHandle->msglist=NULL;
}
SEXP RODBCclearresults(SEXP chan)
{
clearresults(R_ExternalPtrAddr(chan));
return R_NilValue;
}
/**********************************************
* CONNECT
* returns channel no in stat
* or -1 on error
* saves connect data in handles[channel]
*
* ***************************************/
static void chanFinalizer(SEXP ptr);
#define buf1_len 8096
SEXP RODBCDriverConnect(SEXP connection, SEXP id, SEXP useNRows, SEXP ReadOnly)
{
SEXP ans;
SQLSMALLINT tmp1;
SQLRETURN retval;
SQLCHAR buf1[buf1_len];
pRODBCHandle thisHandle;
PROTECT(ans = Rf_allocVector(INTSXP, 1));
INTEGER(ans)[0] = -1;
if(!Rf_isString(connection)) {
Rf_warning(_("[RODBC] ERROR:invalid connection argument"));
UNPROTECT(1);
return ans;
}
thisHandle = R_Calloc(1, RODBCHandle);
++nChannels;
odbcInit();
retval = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &thisHandle->hDbc);
if(retval == SQL_SUCCESS || retval == SQL_SUCCESS_WITH_INFO) {
if(Rf_asLogical(ReadOnly))
SQLSetConnectAttr(thisHandle->hDbc, SQL_ATTR_ACCESS_MODE,
(SQLPOINTER) SQL_MODE_READ_ONLY, 0);
retval =
SQLDriverConnect(thisHandle->hDbc,
#ifdef WIN32
RConsole ? RConsole->handle : NULL,
#else
NULL,
#endif
/* This loses the const, but although the
declaration is not (const SQLCHAR *),
it should be. */
(SQLCHAR *) Rf_translateChar(STRING_ELT(connection, 0)),
SQL_NTS,
(SQLCHAR *) buf1,
(SQLSMALLINT) buf1_len,
&tmp1,
#ifdef WIN32
RConsole ? SQL_DRIVER_COMPLETE : SQL_DRIVER_NOPROMPT
#else
SQL_DRIVER_NOPROMPT
#endif
);
if(retval == SQL_SUCCESS || retval == SQL_SUCCESS_WITH_INFO) {
SEXP constr, ptr;
ptr = R_MakeExternalPtr(thisHandle, Rf_install("RODBC_channel"),
R_NilValue);
PROTECT(ptr);
R_RegisterCFinalizerEx(ptr, chanFinalizer, TRUE);
PROTECT(constr = Rf_allocVector(STRSXP, 1));
SET_STRING_ELT(constr, 0, Rf_mkChar((char *)buf1));
thisHandle->nColumns = -1;
thisHandle->channel = nChannels;
thisHandle->useNRows = Rf_asInteger(useNRows);
thisHandle->id = Rf_asInteger(id);
thisHandle->extPtr = ptr;
/* return the channel no */
INTEGER(ans)[0] = nChannels;
/* and the connection string as an attribute */
Rf_setAttrib(ans, Rf_install("connection.string"), constr);
Rf_setAttrib(ans, Rf_install("handle_ptr"), ptr);
/* Rprintf("opening %d (%p, %p)\n", nChannels,
ptr, thisHandle); */
if(nChannels <= MAX_CHANNELS) opened_handles[nChannels] = thisHandle;
UNPROTECT(3);
return ans;
} else {
if (retval == SQL_ERROR) {
SQLCHAR state[6], msg[1000];
SQLSMALLINT buffsize=1000, msglen, i=1;
SQLINTEGER code;
while(1) {
retval = SQLGetDiagRec(SQL_HANDLE_DBC,
thisHandle->hDbc, i++,
state, &code, msg, buffsize,
&msglen);
if(retval == SQL_NO_DATA_FOUND) break;
Rf_warning(_("[RODBC] ERROR: state %s, code %d, message %s"),
state, (int)code, msg);
}
} else Rf_warning(_("[RODBC] ERROR: Could not SQLDriverConnect"));
(void)SQLFreeHandle(SQL_HANDLE_DBC, thisHandle->hDbc);
}
} else {
Rf_warning(_("[RODBC] ERROR: Could not SQLAllocConnect"));
}
UNPROTECT(1);
return ans;
}
/**********************************************************
*
* QUERY
* run the query on channel pointed to by chan
* cache rols and cols returned in handles[channel]
* cache col descriptor data in handles[channel].ColData
* return -1 in stat on error or 1
* *****************************************************/
SEXP RODBCQuery(SEXP chan, SEXP query, SEXP sRows)
{
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
SQLRETURN res;
int nRows = Rf_asInteger(sRows), stat = 1;
const char *cquery;
if(nRows == NA_INTEGER || nRows < 1) nRows = 1;
clearresults(thisHandle);
res = SQLAllocHandle(SQL_HANDLE_STMT, thisHandle->hDbc,
&thisHandle->hStmt);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
errlistAppend(thisHandle, err_SQLAllocStmt);
stat = -1;
} else {
cquery = Rf_translateChar(STRING_ELT(query, 0));
/* another case of a missing 'const' */
res = SQLExecDirect(thisHandle->hStmt,
(SQLCHAR *) Rf_translateChar(STRING_ELT(query, 0)),
SQL_NTS);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
char *message = R_Calloc(strlen(cquery)+50, char);
snprintf(message, strlen(cquery)+50,
"[RODBC] ERROR: Could not SQLExecDirect '%s'", cquery);
geterr(thisHandle);
errlistAppend(thisHandle, message);
(void)SQLFreeHandle(SQL_HANDLE_STMT, thisHandle->hStmt);
thisHandle->hStmt = NULL;
stat = -1;
} else
stat = cachenbind(thisHandle, nRows);
}
return Rf_ScalarInteger(stat);
}
#define success_or_failure(message) \
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {\
geterr(thisHandle);\
(void)SQLFreeHandle(SQL_HANDLE_STMT, thisHandle->hStmt);\
thisHandle->hStmt = NULL;\
errlistAppend(thisHandle, message);\
stat = -1;\
} else stat = cachenbind(thisHandle, 1);
/****************************************************
*
* get primary key
*
* *************************************************/
SEXP RODBCPrimaryKeys(SEXP chan, SEXP table, SEXP cat, SEXP schem)
{
int stat = 1;
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
SQLRETURN res;
const char *catalog = NULL, *schema = NULL;
SQLSMALLINT len1 = 0, len2 = 0;
clearresults(thisHandle);
res = SQLAllocHandle(SQL_HANDLE_STMT, thisHandle->hDbc, &thisHandle->hStmt);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
errlistAppend(thisHandle, err_SQLAllocStmt);
stat = -1;
} else {
if(TYPEOF(cat) == STRSXP && LENGTH(cat)) {
catalog = Rf_translateChar(STRING_ELT(cat, 0));
len1 = (SQLSMALLINT) strlen(catalog);
}
if(TYPEOF(schem) == STRSXP && LENGTH(schem)) {
schema = Rf_translateChar(STRING_ELT(schem, 0));
len2 = (SQLSMALLINT) strlen(schema);
}
/* another case of a missing 'const' */
res = SQLPrimaryKeys( thisHandle->hStmt,
(SQLCHAR *) catalog, len1,
(SQLCHAR *) schema, len2,
(SQLCHAR *) Rf_translateChar(STRING_ELT(table, 0)),
SQL_NTS);
success_or_failure(_("[RODBC] ERROR: Failure in SQLPrimary keys"));
}
return Rf_ScalarInteger(stat);
}
/********************************************
*
* Get column data
*
* ********************************/
SEXP RODBCColumns(SEXP chan, SEXP table, SEXP cat, SEXP schem, SEXP sLiteral)
{
int stat = 1;
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
SQLRETURN res;
const char *catalog = NULL, *schema = NULL;
int literal;
SQLSMALLINT len1 = 0, len2 = 0;
clearresults(thisHandle);
res = SQLAllocHandle(SQL_HANDLE_STMT, thisHandle->hDbc, &thisHandle->hStmt);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
errlistAppend(thisHandle, err_SQLAllocStmt);
stat = -1;
} else {
if(TYPEOF(cat) == STRSXP && LENGTH(cat)) {
catalog = Rf_translateChar(STRING_ELT(cat, 0));
len1 = (SQLSMALLINT) strlen(catalog);
}
if(TYPEOF(schem) == STRSXP && LENGTH(schem)) {
schema = Rf_translateChar(STRING_ELT(schem, 0));
len2 = (SQLSMALLINT) strlen(schema);
}
literal = Rf_asLogical(sLiteral);
if(literal == NA_LOGICAL) literal = 0;
if(literal)
res = SQLSetStmtAttr(thisHandle->hStmt, SQL_ATTR_METADATA_ID,
(SQLPOINTER) SQL_TRUE, SQL_IS_UINTEGER);
/* another case of a missing 'const' */
res = SQLColumns( thisHandle->hStmt,
(SQLCHAR *) catalog, len1,
(SQLCHAR *) schema, len2,
(SQLCHAR *) Rf_translateChar(STRING_ELT(table, 0)),
SQL_NTS, NULL, 0);
success_or_failure(_("[RODBC] ERROR: Failure in SQLColumns"));
}
return Rf_ScalarInteger(stat);
}
SEXP RODBCSpecialColumns(SEXP chan, SEXP table, SEXP cat, SEXP schem)
{
int stat = 1;
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
SQLRETURN res;
const char *catalog = NULL, *schema = NULL;
SQLSMALLINT len1 = 0, len2 = 0;
clearresults(thisHandle);
res = SQLAllocHandle(SQL_HANDLE_STMT, thisHandle->hDbc, &thisHandle->hStmt);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
errlistAppend(thisHandle, err_SQLAllocStmt);
stat = -1;
} else {
if(TYPEOF(cat) == STRSXP && LENGTH(cat)) {
catalog = Rf_translateChar(STRING_ELT(cat, 0));
len1 = (SQLSMALLINT) strlen(catalog);
}
if(TYPEOF(schem) == STRSXP && LENGTH(schem)) {
schema = Rf_translateChar(STRING_ELT(schem, 0));
len2 = (SQLSMALLINT) strlen(schema);
}
/* another case of a missing 'const' */
res = SQLSpecialColumns( thisHandle->hStmt, SQL_BEST_ROWID,
(SQLCHAR *) catalog, len1,
(SQLCHAR *) schema, len2,
(SQLCHAR *) Rf_translateChar(STRING_ELT(table, 0)),
SQL_NTS,
SQL_SCOPE_TRANSACTION, SQL_NULLABLE);
success_or_failure(_("[RODBC] ERROR: Failure in SQLSpecialColumns"));
}
return Rf_ScalarInteger(stat);
}
/*****************************************************
*
* get Table data
*
* ***************************************/
SEXP RODBCTables(SEXP chan, SEXP cat, SEXP schem, SEXP name, SEXP type,
SEXP sLiteral)
{
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
SQLRETURN res;
const char *catalog = NULL, *schema = NULL, *tName = NULL, *tType = NULL;
int stat = 1, literal;
SQLSMALLINT len1 = 0, len2 = 0, len3 = 0, len4 = 0;
clearresults(thisHandle);
res = SQLAllocHandle(SQL_HANDLE_STMT, thisHandle->hDbc, &thisHandle->hStmt);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
errlistAppend(thisHandle, err_SQLAllocStmt);
stat = -1;
} else {
if(TYPEOF(cat) == STRSXP && LENGTH(cat)) {
catalog = Rf_translateChar(STRING_ELT(cat, 0));
len1 = (SQLSMALLINT) strlen(catalog);
}
if(TYPEOF(schem) == STRSXP && LENGTH(schem)) {
schema = Rf_translateChar(STRING_ELT(schem, 0));
len2 = (SQLSMALLINT) strlen(schema);
}
if(TYPEOF(name) == STRSXP && LENGTH(name)) {
tName = Rf_translateChar(STRING_ELT(name, 0));
len3 = (SQLSMALLINT) strlen(tName);
}
if(TYPEOF(type) == STRSXP && LENGTH(type)) {
tType = Rf_translateChar(STRING_ELT(type, 0));
len4 = (SQLSMALLINT) strlen(tType);
}
literal = Rf_asLogical(sLiteral);
if(literal == NA_LOGICAL) literal = 0;
if(literal)
res = SQLSetStmtAttr(thisHandle->hStmt, SQL_ATTR_METADATA_ID,
(SQLPOINTER) SQL_TRUE, SQL_IS_UINTEGER);
res = SQLTables(thisHandle->hStmt,
(SQLCHAR *) catalog, len1,
(SQLCHAR *) schema, len2,
(SQLCHAR *) tName, len3,
(SQLCHAR *) tType, len4);
success_or_failure(_("[RODBC] ERROR: SQLTables failed"));
}
return Rf_ScalarInteger(stat);
}
/*****************************************************
*
* get Type Info
*
* ***************************************/
SEXP RODBCTypeInfo(SEXP chan, SEXP ptype)
{
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
short type;
SQLRETURN res;
int stat = TRUE;
clearresults(thisHandle);
res = SQLAllocHandle(SQL_HANDLE_STMT, thisHandle->hDbc, &thisHandle->hStmt);
if( res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO ) {
errlistAppend(thisHandle, err_SQLAllocStmt);
stat = FALSE;
} else {
switch(Rf_asInteger(ptype)){
case 0: type = SQL_ALL_TYPES; break; /* all */
case 1: type = SQL_CHAR; break;
case 2: type = SQL_VARCHAR; break;
case 3: type = SQL_REAL; break;
case 4: type = SQL_DOUBLE; break;
case 5: type = SQL_INTEGER; break;
case 6: type = SQL_SMALLINT; break;
case 7: type = SQL_TYPE_TIMESTAMP; break;
case 8: type = SQL_FLOAT; break;
case 9: type = SQL_BIT; break;
case 10: type = SQL_WCHAR; break;
case 11: type = SQL_WVARCHAR; break;
case 12: type = SQL_DATE; break;
case 13: type = SQL_TIME; break;
case 14: type = SQL_BINARY; break;
case 15: type = SQL_VARBINARY; break;
case 16:
case 17:
type = SQL_LONGVARBINARY; break;
default: type = SQL_ALL_TYPES;
}
res = SQLGetTypeInfo(thisHandle->hStmt, type);
success_or_failure(_("[RODBC] ERROR: SQLTables failed"));
}
return Rf_ScalarLogical(stat);
}
SEXP RODBCGetInfo(SEXP chan)
{
SEXP ans;
int i;
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
char buf[1000];
SQLSMALLINT nbytes;
SQLRETURN retval;
SQLSMALLINT InfoTypes[] =
{SQL_DBMS_NAME, SQL_DBMS_VER, SQL_DRIVER_ODBC_VER,
SQL_DATA_SOURCE_NAME, SQL_DRIVER_NAME, SQL_DRIVER_VER,
SQL_ODBC_VER, SQL_SERVER_NAME};
/* Rprintf("using (%p, %p)\n", chan, thisHandle); */
PROTECT(ans = Rf_allocVector(STRSXP, 8));
for (i = 0; i < LENGTH(ans); i++) {
retval = SQLGetInfo(thisHandle->hDbc,
InfoTypes[i], buf, (SQLSMALLINT)1000, &nbytes);
if( retval != SQL_SUCCESS && retval != SQL_SUCCESS_WITH_INFO ) {
geterr(thisHandle);
SET_STRING_ELT(ans, i, Rf_mkChar("error"));
break;
} else
SET_STRING_ELT(ans, i, Rf_mkChar(buf));
}
UNPROTECT(1);
return ans;
}
static void cachenbind_free(pRODBCHandle thisHandle)
{
SQLUSMALLINT i;
if(thisHandle->ColData) {
for (i = 0; i < thisHandle->nAllocated; i++)
if(thisHandle->ColData[i].pData)
R_Free(thisHandle->ColData[i].pData);
R_Free(thisHandle->ColData);
thisHandle->ColData = NULL; /* to be sure */
}
}
#define BIND(type, buf, size) \
retval = SQLBindCol(thisHandle->hStmt, i+1, type,\
thisHandle->ColData[i].buf, size,\
thisHandle->ColData[i].IndPtr);\
break;
/* *******************************************
*
* Common column cache and bind for query-like routines
* This is used to bind the columns for all queries that
* produce a result set, which is uses by RODBCFetchRows.
*
* *******************************************/
/* returns 1 for success, -1 for failure */
static int cachenbind(pRODBCHandle thisHandle, int nRows)
{
SQLUSMALLINT i;
SQLRETURN retval;
/* Now cache the number of columns, rows */
retval = SQLNumResultCols(thisHandle->hStmt, &NCOLS);
if( retval != SQL_SUCCESS && retval != SQL_SUCCESS_WITH_INFO ) {
/* assume this is not an error but that no rows found */
NROWS = 0;
return 1 ;
}
retval = SQLRowCount(thisHandle->hStmt, &NROWS);
if( retval != SQL_SUCCESS && retval != SQL_SUCCESS_WITH_INFO ) {
geterr(thisHandle);
errlistAppend(thisHandle, _("[RODBC] ERROR: SQLRowCount failed"));
goto error;
}
/* Allocate storage for ColData array,
first freeing what was there before */
cachenbind_free(thisHandle);
thisHandle->ColData = R_Calloc(NCOLS, COLUMNS);
/* this allocates Data as zero */
thisHandle->nAllocated = NCOLS;
/* attempt to set the row array size */
thisHandle->rowArraySize = my_min(nRows, MAX_ROWS_FETCH);
/* passing unsigned integer values via casts is a bad idea.
But here double casting works because long and a pointer
are the same size on all relevant platforms (since
Win64 is not relevant -- but now is). */
retval = SQLSetStmtAttr(thisHandle->hStmt, SQL_ATTR_ROW_ARRAY_SIZE,
#ifdef _WIN64
(SQLPOINTER) (unsigned long long) thisHandle->rowArraySize,
#else
(SQLPOINTER) (unsigned long) thisHandle->rowArraySize,
#endif
0 );
if (retval != SQL_SUCCESS) thisHandle->rowArraySize = 1;
thisHandle->rowsUsed = 0;
/* Set pointer to report number of rows fetched
*/
if (thisHandle->rowArraySize != 1) {
retval = SQLSetStmtAttr(thisHandle->hStmt,
SQL_ATTR_ROWS_FETCHED_PTR,
&thisHandle->rowsFetched, 0);
if (retval != SQL_SUCCESS) {
thisHandle->rowArraySize = 1;
SQLSetStmtAttr(thisHandle->hStmt, SQL_ATTR_ROW_ARRAY_SIZE,
(SQLPOINTER) 1, 0 );
}
}
nRows = thisHandle->rowArraySize;
/* step through each col and cache metadata: cols are numbered from 1!
*/
for (i = 0; i < NCOLS; i++) {
retval = SQLDescribeCol(thisHandle->hStmt, i+1,
thisHandle->ColData[i].ColName, 256,
&thisHandle->ColData[i].NameLength,
&thisHandle->ColData[i].DataType,
&thisHandle->ColData[i].ColSize,
&thisHandle->ColData[i].DecimalDigits,
&thisHandle->ColData[i].Nullable);
if( retval != SQL_SUCCESS && retval != SQL_SUCCESS_WITH_INFO ) {
geterr(thisHandle);
errlistAppend(thisHandle,
_("[RODBC] ERROR: SQLDescribeCol failed"));
goto error;
}
/* now bind the col to its data buffer */
/* MSDN say the BufferLength is ignored for fixed-size
types, but this is not so for UnixODBC */
/* We could add other types here, in particular
SQL_C_USHORT
SQL_C_ULONG (map to double)
SQL_C_BIT
SQL_C_WCHAR (map to UTF-8)
*/
switch(thisHandle->ColData[i].DataType) {
case SQL_DOUBLE:
BIND(SQL_C_DOUBLE, RData, sizeof(double));
case SQL_REAL:
BIND(SQL_C_FLOAT, R4Data, sizeof(float));
case SQL_INTEGER:
BIND(SQL_C_SLONG, IData, sizeof(int));
case SQL_SMALLINT:
BIND(SQL_C_SSHORT, I2Data, sizeof(short));
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
{
/* should really use SQLCHAR (unsigned) */
SQLLEN datalen = thisHandle->ColData[i].ColSize;
thisHandle->ColData[i].datalen = datalen;
thisHandle->ColData[i].pData =
R_Calloc(nRows * (datalen + 1), char);
BIND(SQL_C_BINARY, pData, datalen);
}
default:
{
SQLLEN datalen = thisHandle->ColData[i].ColSize;
if (datalen <= 0 || datalen < COLMAX) datalen = COLMAX;
/* sanity check as the reports are sometimes unreliable */
if (datalen > 65535) datalen = 65535;
thisHandle->ColData[i].pData =
R_Calloc(nRows * (datalen + 1), char);
thisHandle->ColData[i].datalen = datalen;
BIND(SQL_C_CHAR, pData, datalen);
}
}
if( retval != SQL_SUCCESS && retval != SQL_SUCCESS_WITH_INFO ) {
geterr(thisHandle);
errlistAppend(thisHandle, _("[RODBC] ERROR: SQLBindCol failed"));
goto error;
}
}
return 1;
error:
(void)SQLFreeStmt(thisHandle->hStmt, SQL_CLOSE);
(void)SQLFreeHandle(SQL_HANDLE_STMT, thisHandle->hStmt);
thisHandle->hStmt = NULL;
return -1;
}
/***************************************/
SEXP RODBCNumCols(SEXP chan)
{
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
if(NCOLS == -1)
errlistAppend(thisHandle, _("[RODBC] No results available"));
return Rf_ScalarInteger((int) NCOLS);
}
#define ROWSNA (SQLLEN) -1
static SEXP mkRaw(char *ptr, unsigned int len)
{
SEXP ans = Rf_allocVector(RAWSXP, len);
memcpy(RAW(ans), ptr, len);
return ans;
}
SEXP RODBCFetchRows(SEXP chan, SEXP max, SEXP bs, SEXP nas, SEXP believeNRows)
{
int stat = 1, i, j, blksize, nc, n, row;
int maximum = Rf_asInteger(max);
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
int useNRows = Rf_asLogical(believeNRows) != 0;
int buffsize = Rf_asInteger(bs);
SEXP data, names, ans;
SQLRETURN retval;
nc = NCOLS;
PROTECT(ans = Rf_allocVector(VECSXP, 2)); /* create answer [0] = data, [1]=stat */
if(!useNRows || !thisHandle->useNRows) NROWS = ROWSNA;
if(nc == 0) stat = -2;
if(nc == -1) {
errlistAppend(thisHandle, _("[RODBC] No results available"));
stat = -1;
}
if(stat < 0 || nc == 0) {
if(NROWS == 0)
errlistAppend(thisHandle, _("No Data"));
PROTECT(data = Rf_allocVector(VECSXP, 0));
} else { /* NCOLS > 0 */
PROTECT(data = Rf_allocVector(VECSXP, nc));
if(NROWS == ROWSNA) {
if(maximum) blksize = maximum;
else {
maximum = INT_MAX;
blksize = (buffsize < 100) ? 100: buffsize;
}
} else {
if(!maximum || maximum > NROWS) maximum = (int) NROWS;
blksize = maximum;
}
for(i = 0; i < nc; i++) {
switch(thisHandle->ColData[i].DataType) {
case SQL_DOUBLE:
case SQL_REAL:
SET_VECTOR_ELT(data, i, Rf_allocVector(REALSXP, blksize));
break;
case SQL_INTEGER:
case SQL_SMALLINT:
SET_VECTOR_ELT(data, i, Rf_allocVector(INTSXP, blksize));
break;
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
SET_VECTOR_ELT(data, i, Rf_allocVector(VECSXP, blksize));
break;
default:
SET_VECTOR_ELT(data, i, Rf_allocVector(STRSXP, blksize));
}
}
for(j = 1; j <= maximum; ) {
if(j > blksize) {
blksize *= 2;
for (i = 0; i < nc; i++)
SET_VECTOR_ELT(data, i,
Rf_lengthgets(VECTOR_ELT(data, i), blksize));
}
if(thisHandle->rowsUsed == 0L ||
thisHandle->rowsUsed >= thisHandle->rowsFetched) {
if (thisHandle->rowArraySize == 1) {
retval = SQLFetch(thisHandle->hStmt);
thisHandle->rowsFetched = 1;
} else
/* this will update thisHandle->rowsFetched */
retval = SQLFetchScroll(thisHandle->hStmt, SQL_FETCH_NEXT,
0);
if(retval != SQL_SUCCESS && retval != SQL_SUCCESS_WITH_INFO)
break;
thisHandle->rowsUsed = 0;
/* SQL_SUCCESS_WITH_INFO if char column(s) truncated */
if(retval == SQL_SUCCESS_WITH_INFO) {
SQLCHAR sqlstate[6], msg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER NativeError;
SQLSMALLINT MsgLen;
if(SQLError(hEnv, thisHandle->hDbc,
thisHandle->hStmt, sqlstate, &NativeError,
msg, (SQLSMALLINT)sizeof(msg), &MsgLen)
== SQL_SUCCESS) {
if(strcmp((char *)sqlstate, "O1004") == 0)
Rf_warning(_("character data truncated in column '%s'"),
(char *)thisHandle->ColData[i].ColName);
}
}
}
for(row = thisHandle->rowsUsed;
row < thisHandle->rowsFetched && j <= maximum;
j++, row++)
{
thisHandle->rowsUsed++;
if(j > blksize) {
blksize *= 2;
for (i = 0; i < nc; i++)
SET_VECTOR_ELT(data, i,
Rf_lengthgets(VECTOR_ELT(data, i), blksize));
}
for (i = 0; i < nc; i++) {
SQLLEN len = thisHandle->ColData[i].IndPtr[row];
switch(thisHandle->ColData[i].DataType) {
case SQL_DOUBLE:
REAL(VECTOR_ELT(data, i))[j-1] =
len == SQL_NULL_DATA ? NA_REAL :
thisHandle->ColData[i].RData[row];
break;
case SQL_REAL:
REAL(VECTOR_ELT(data, i))[j-1] =
len == SQL_NULL_DATA ? NA_REAL :
(double) thisHandle->ColData[i].R4Data[row];
break;
case SQL_INTEGER:
INTEGER(VECTOR_ELT(data, i))[j-1] =
len == SQL_NULL_DATA ? NA_INTEGER :
thisHandle->ColData[i].IData[row];
break;
case SQL_SMALLINT:
INTEGER(VECTOR_ELT(data, i))[j-1] =
len == SQL_NULL_DATA ? NA_INTEGER :
(int) thisHandle->ColData[i].I2Data[row];
break;
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
{
SEXP this = (len == SQL_NULL_DATA) ?
Rf_allocVector(RAWSXP, 0) :
mkRaw(thisHandle->ColData[i].pData +
(thisHandle->ColData[i].datalen * row),
(unsigned int) len);
SET_VECTOR_ELT(VECTOR_ELT(data, i), j-1, this);
break;
}
default:
SET_STRING_ELT(VECTOR_ELT(data, i), j-1,
len == SQL_NULL_DATA ?
STRING_ELT(nas, 0) :
Rf_mkChar(thisHandle->ColData[i].pData +
(thisHandle->ColData[i].datalen * row)));
}
}
}
}
n = --j;
if (n > 0 && !(maximum && n >= maximum)) {
/* means 'no further results available' */
NCOLS = -1;
thisHandle->rowsUsed = 0; /* safety */
/* so we can free the buffers */
cachenbind_free(thisHandle);
}
if (n < blksize) { /* need to trim vectors */
for (i = 0; i < nc; i++)
SET_VECTOR_ELT(data, i,
Rf_lengthgets(VECTOR_ELT(data, i), n));
}
}
SET_VECTOR_ELT(ans, 0, data);
SET_VECTOR_ELT(ans, 1, Rf_ScalarInteger(stat));
PROTECT(names = Rf_allocVector(STRSXP, 2));
SET_STRING_ELT(names, 0, Rf_mkChar("data"));
SET_STRING_ELT(names, 1, Rf_mkChar("stat"));
Rf_setAttrib(ans, R_NamesSymbol, names);
// SET_NAMES(ans, names);
UNPROTECT(3); /* ans data names */
return ans;
}
/**********************************************************************/
SEXP RODBCColData(SEXP chan)
{
SEXP ans, names, type, ansnames;
pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
int i, nc;
PROTECT(ans = Rf_allocVector(VECSXP, 2));
if(NCOLS == -1)
errlistAppend(thisHandle, _("[RODBC] No results available"));
nc = NCOLS;
if(nc < 0) nc = 0;
SET_VECTOR_ELT(ans, 0, names = Rf_allocVector(STRSXP, nc));
SET_VECTOR_ELT(ans, 1, type = Rf_allocVector(STRSXP, nc));
PROTECT(ansnames = Rf_allocVector(STRSXP, 2));
SET_STRING_ELT(ansnames, 0, Rf_mkChar("names"));
SET_STRING_ELT(ansnames, 1, Rf_mkChar("type"));
Rf_setAttrib(ans, R_NamesSymbol, ansnames);
for (i = 0; i < nc; i++) {
SET_STRING_ELT(names, i,
Rf_mkChar((char *)thisHandle->ColData[i].ColName));
/* at the moment we only need to know if it is
a date, datetime or other */
switch(thisHandle->ColData[i].DataType) {
case SQL_CHAR: SET_STRING_ELT(type, i, Rf_mkChar("char")); break;
case SQL_NUMERIC: SET_STRING_ELT(type, i, Rf_mkChar("numeric")); break;
case SQL_DECIMAL: SET_STRING_ELT(type, i, Rf_mkChar("decimal")); break;
case SQL_INTEGER: SET_STRING_ELT(type, i, Rf_mkChar("int")); break;
case SQL_SMALLINT: SET_STRING_ELT(type, i, Rf_mkChar("smallint")); break;
case SQL_FLOAT: SET_STRING_ELT(type, i, Rf_mkChar("float")); break;