-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathodbc.cpp
More file actions
1780 lines (1599 loc) · 59.4 KB
/
odbc.cpp
File metadata and controls
1780 lines (1599 loc) · 59.4 KB
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
/*
odbc.cpp
$Id$
Donated to the Python community by EShop, who can not
support it!
Note that this can be built on non-Windows systems by a C (not C++)
compiler, so should avoid C++ constructs and comments.
*/
/* @doc - this file contains autoduck documentation in the comments. */
#include <math.h>
#include <limits.h>
#include <string.h>
#include "PyWinTypes.h"
#include "PyWinObjects.h"
#include "structmember.h"
#include <sql.h>
#include <sqlext.h>
#include <import.h>
#include <time.h>
#ifndef _cplusplus
#define bool int
#define true 1
#define false 0
#endif
// #ifdef _WIN64
// # define mktime _mktime32
// #endif
static PyObject *datetime_module, *datetime_class;
// Type names
static PyObject *DbiString, *DbiRaw, *DbiNumber, *DbiDate;
// Exceptions
static PyObject *odbcError;
static PyObject *DbiNoError, *DbiOpError, *DbiProgError;
static PyObject *DbiIntegrityError, *DbiDataError, *DbiInternalError;
#define MAX_STR 256
static HENV Env;
typedef struct {
PyObject_HEAD HDBC hdbc;
int connected;
int connect_id;
TCHAR *connectionString;
PyObject *connectionError;
} connectionObject;
static connectionObject *connection(PyObject *o) { return (connectionObject *)o; }
typedef PyObject *(*CopyFcn)(const void *, SQLLEN);
typedef struct _out {
struct _out *next;
SQLLEN rcode;
void *bind_area;
CopyFcn copy_fcn;
bool bGetData;
short vtype;
int pos;
SQLLEN vsize;
} OutputBinding;
typedef struct _in {
struct _in *next;
SQLLEN len;
SQLLEN sqlBytesAvailable;
bool bPutData;
char bind_area[1];
} InputBinding;
typedef struct {
PyObject_HEAD HSTMT hstmt;
OutputBinding *outputVars;
InputBinding *inputVars;
long max_width;
connectionObject *my_conx;
int connect_id;
PyObject *description;
PyObject *cursorError;
int n_columns;
} cursorObject;
static cursorObject *cursor(PyObject *o) { return (cursorObject *)o; }
static void cursorDealloc(PyObject *self);
extern PyMethodDef cursorMethods[];
extern PyMemberDef cursorMembers[];
static PyTypeObject Cursor_Type = {
PYWIN_OBJECT_HEAD "odbccur", /*tp_name */
sizeof(cursorObject), /*tp_basicsize */
0, /*tp_itemsize */
cursorDealloc, /*tp_dealloc */
0, /*tp_print */
0, /*tp_getattr */
0, /*tp_setattr */
0, /*tp_compare */
0, /*tp_repr */
0, /*tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /*tp_str */
PyObject_GenericGetAttr, /* tp_getattro dbiGetAttr */
PyObject_GenericSetAttr, /* tp_setattro */
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
cursorMethods, /* tp_methods */
cursorMembers, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static void connectionDealloc(PyObject *self);
extern PyMethodDef connectionMethods[];
extern PyMemberDef connectionMembers[];
static PyTypeObject Connection_Type = {
PYWIN_OBJECT_HEAD "odbcconn", /*tp_name */
sizeof(connectionObject), /*tp_basicsize */
0, /*tp_itemsize */
connectionDealloc, /*tp_dealloc */
0, /*tp_print */
0, /*tp_getattr */
0, /*tp_setattr */
0, /*tp_compare */
0, /*tp_repr */
0, /*tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /*tp_str */
PyObject_GenericGetAttr, /* tp_getattro dbiGetAttr */
PyObject_GenericSetAttr, /* tp_setattro */
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
connectionMethods, /* tp_methods */
connectionMembers, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static int unsuccessful(RETCODE rc) { return (rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO); }
int connectionDied(const char *sqlState) { return !strcmp(sqlState, "08S01"); }
typedef struct {
const TCHAR *state;
int index;
int connected;
} odbcErrorDesc;
static odbcErrorDesc *lookupError(const TCHAR *sqlState);
static PyObject *dbiErrors[6]; /* 'cause I know about six DBI errors */
static void odbcPrintError(HENV env, connectionObject *conn, HSTMT cur, const TCHAR *action)
{
TCHAR sqlState[256];
long nativeError;
short pcbErrorMsg;
TCHAR errorMsg[1000];
PyObject *error;
if (unsuccessful(SQLError(env, conn ? conn->hdbc : 0, cur, (SQLTCHAR *)sqlState, &nativeError, (SQLTCHAR *)errorMsg,
sizeof(errorMsg) / sizeof(errorMsg[0]), &pcbErrorMsg))) {
error = odbcError;
_tcscpy(errorMsg, _T("Could not find error "));
}
else {
_tcscat(errorMsg, _T(" in "));
_tcscat(errorMsg, action);
odbcErrorDesc *errorType = lookupError(sqlState);
if (conn && errorType && (errorType->connected == 0)) {
SQLDisconnect(conn->hdbc);
conn->connected = 0;
}
/* internal is the default */
int errn = errorType ? errorType->index : 5;
error = dbiErrors[errn];
}
PyErr_SetObject(error, PyWinObject_FromTCHAR(errorMsg));
}
static void connectionError(connectionObject *conn, const TCHAR *action)
{
odbcPrintError(Env, conn, SQL_NULL_HSTMT, action);
}
static void cursorError(cursorObject *cur, const TCHAR *action)
{
odbcPrintError(Env, cur->my_conx, cur->hstmt, action);
}
static int doConnect(connectionObject *conn)
{
RETCODE rc;
short connectionStringLength;
Py_BEGIN_ALLOW_THREADS rc = SQLDriverConnect(conn->hdbc, NULL, (SQLTCHAR *)conn->connectionString, SQL_NTS, NULL, 0,
&connectionStringLength, SQL_DRIVER_NOPROMPT);
Py_END_ALLOW_THREADS if (unsuccessful(rc))
{
odbcPrintError(Env, conn, SQL_NULL_HSTMT, _T("LOGIN"));
return 1;
}
conn->connected = 1;
conn->connect_id++; /* perturb it so cursors know to reconnect */
return 0;
}
static int attemptReconnect(cursorObject *cur)
{
if ((cur->connect_id != cur->my_conx->connect_id) || (cur->my_conx->connected == 0)) {
/* ie the cursor was made on an old connection */
/* Do not need to free HSTMT here, since any statements attached to the connection
are automatically invalidated when SQLDisconnect is called in odbcPrintError.
(only place where connected is set to 0)
SQLFreeStmt(cur->hstmt, SQL_DROP);
*/
cur->hstmt = NULL;
if (cur->my_conx->connected == 0) {
/* ie the db has not been reconnected */
if (doConnect(cur->my_conx)) {
return 1;
}
}
if (unsuccessful(SQLAllocStmt(cur->my_conx->hdbc, &cur->hstmt))) {
connectionError(cur->my_conx, _T("REOPEN"));
return 1;
}
cur->connect_id = cur->my_conx->connect_id;
return 0;
}
return 0;
}
/* @pymethod |connection|setautocommit|Sets the autocommit mode. */
static PyObject *odbcSetAutoCommit(PyObject *self, PyObject *args)
{
int c;
connectionObject *conn;
/* @pyparm int|c||The boolean autocommit mode. */
if (!PyArg_ParseTuple(args, "i", &c))
return NULL;
conn = connection(self);
if (c == 0) {
if (unsuccessful(SQLSetConnectOption(conn->hdbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF))) {
connectionError(conn, _T("SETAUTOCOMMIT"));
return NULL;
}
}
else {
if (unsuccessful(SQLSetConnectOption(conn->hdbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_ON))) {
connectionError(conn, _T("SETAUTOCOMMIT"));
return NULL;
};
}
Py_INCREF(Py_None);
return Py_None;
}
/* @pymethod |connection|commit|Commits a transaction. */
static PyObject *odbcCommit(PyObject *self, PyObject *args)
{
RETCODE rc;
Py_BEGIN_ALLOW_THREADS rc = SQLTransact(Env, connection(self)->hdbc, SQL_COMMIT);
Py_END_ALLOW_THREADS if (unsuccessful(rc))
{
connectionError(connection(self), _T("COMMIT"));
return 0;
}
else
{
Py_INCREF(Py_None);
return Py_None;
}
}
/* @pymethod |connection|rollback|Rollsback a transaction. */
static PyObject *odbcRollback(PyObject *self, PyObject *args)
{
RETCODE rc;
Py_BEGIN_ALLOW_THREADS rc = SQLTransact(Env, connection(self)->hdbc, SQL_ROLLBACK);
Py_END_ALLOW_THREADS if (unsuccessful(rc))
{
connectionError(connection(self), _T("ROLLBACK"));
return 0;
}
else
{
Py_INCREF(Py_None);
return Py_None;
}
}
/* @pymethod |connection|cursor|Creates a <o cursor> object */
static PyObject *odbcCursor(PyObject *self, PyObject *args)
{
connectionObject *conn = connection(self);
if (conn->connected == 0) {
if (doConnect(conn)) {
return 0;
}
}
cursorObject *cur = PyObject_New(cursorObject, &Cursor_Type);
if (cur == NULL)
return NULL;
cur->outputVars = 0;
cur->inputVars = 0;
cur->description = 0;
cur->max_width = 65536L;
cur->my_conx = 0;
cur->hstmt = NULL;
cur->cursorError = odbcError;
Py_INCREF(odbcError);
if (unsuccessful(SQLAllocStmt(conn->hdbc, &cur->hstmt))) {
connectionError(cur->my_conx, _T("OPEN"));
Py_DECREF(cur);
return NULL;
}
cur->my_conx = conn;
cur->connect_id = cur->my_conx->connect_id;
Py_INCREF(self); /* the cursors owns a reference to the connection */
return (PyObject *)cur;
}
/* @pymethod |connection|close|Closes the connection. */
static PyObject *odbcClose(PyObject *self, PyObject *args)
{
Py_INCREF(Py_None);
return Py_None;
}
/* @object connection|An object representing an ODBC connection */
static struct PyMethodDef connectionMethods[] = {
{"setautocommit", odbcSetAutoCommit, 1}, /* @pymeth setautocommit|Sets the autocommit mode. */
{"commit", odbcCommit, 1}, /* @pymeth commit|Commits a transaction. */
{"rollback", odbcRollback, 1}, /* @pymeth rollback|Rollsback a transaction. */
{"cursor", odbcCursor, 1}, /* @pymeth cursor|Creates a <o cursor> object */
{"close", odbcClose, 1}, /* @pymeth close|Closes the connection. */
{0, 0}};
static PyMemberDef connectionMembers[] = {{"error", T_OBJECT, offsetof(connectionObject, connectionError), READONLY},
{NULL}};
static void connectionDealloc(PyObject *self)
{
Py_XDECREF(connection(self)->connectionError);
SQLDisconnect(connection(self)->hdbc);
SQLFreeConnect(connection(self)->hdbc);
if (connection(self)->connectionString) {
free(connection(self)->connectionString);
}
PyObject_Del(self);
}
static void deleteOutput(cursorObject *cur)
{
OutputBinding *ob = cur->outputVars;
while (ob) {
OutputBinding *next = ob->next;
free(ob->bind_area);
free(ob);
ob = next;
}
cur->outputVars = 0;
}
static void deleteInput(cursorObject *cur)
{
InputBinding *ib = cur->inputVars;
while (ib) {
InputBinding *next = ib->next;
/*$ free(ib->bind_area); */
free(ib);
ib = next;
}
cur->inputVars = 0;
}
static void deleteBinding(cursorObject *cur)
{
deleteInput(cur);
deleteOutput(cur);
}
static void cursorDealloc(PyObject *self)
{
cursorObject *cur = cursor(self);
/* Only free HSTMT if database connection hasn't been disconnected */
if (cur->my_conx && cur->my_conx->connected && cur->hstmt)
SQLFreeHandle(SQL_HANDLE_STMT, cur->hstmt);
deleteBinding(cur);
if (cur->my_conx) {
Py_DECREF((PyObject *)cur->my_conx);
}
Py_XDECREF(cur->description);
Py_XDECREF(cur->cursorError);
PyObject_Del(self);
}
/* @pymethod |cursor|close|Closes the cursor */
static PyObject *odbcCurClose(PyObject *self, PyObject *args)
{
/* @comm This method does nothing!! I presume it should!?!?! */
Py_INCREF(Py_None);
return Py_None;
}
static BOOL bindOutputVar(cursorObject *cur, CopyFcn fcn, short vtype, SQLLEN vsize, int pos, bool bUseGet)
{
OutputBinding *ob = (OutputBinding *)malloc(sizeof(OutputBinding));
if (ob == NULL) {
PyErr_NoMemory();
return FALSE;
}
OutputBinding *current = NULL;
ob->bGetData = bUseGet;
ob->pos = pos;
ob->vtype = vtype;
ob->vsize = vsize;
/* Stick the new column on the end of the linked list.
We do this because we call SQLGetData() while walking the linked list.
Some ODBC drivers require all BLOB columns to be at the end of the column list.
So preserve the order our consumer called us with. */
ob->next = NULL;
if (cur->outputVars == NULL) {
cur->outputVars = ob;
}
else {
current = cur->outputVars;
while (current->next != NULL) {
current = current->next;
}
current->next = ob;
}
ob->copy_fcn = fcn;
ob->bind_area = malloc(vsize);
if (ob->bind_area == NULL) {
PyErr_NoMemory();
return FALSE;
}
ob->rcode = vsize;
if (ob->bGetData == false) {
if (unsuccessful(SQLBindCol(cur->hstmt, pos, vtype, ob->bind_area, vsize, &ob->rcode))) {
cursorError(cur, _T("BIND"));
return FALSE;
}
}
return TRUE;
}
static PyObject *wcharCopy(const void *v, SQLLEN sz) { return PyWinObject_FromWCHAR((WCHAR *)v, sz / sizeof(WCHAR)); }
static PyObject *stringCopy(const void *v, SQLLEN sz) { return PyBytes_FromStringAndSize((char *)v, sz); }
static PyObject *longCopy(const void *v, SQLLEN sz) { return PyLong_FromLong(*(unsigned long *)v); }
static PyObject *doubleCopy(const void *v, SQLLEN sz)
{
double d = *(double *)v;
return (d == floor(d)) ? PyLong_FromDouble(d) : PyFloat_FromDouble(d);
}
static PyObject *dateCopy(const void *v, SQLLEN sz)
{
const TIMESTAMP_STRUCT *dt = (const TIMESTAMP_STRUCT *)v;
// Units for fraction is billionths, python datetime uses microseconds
unsigned long usec = dt->fraction / 1000;
return PyObject_CallFunction(datetime_class, "hhhhhhk", dt->year, dt->month, dt->day, dt->hour, dt->minute,
dt->second, usec);
}
static PyObject *rawCopy(const void *v, SQLLEN sz)
{
PyObject *ret = PyBuffer_New(sz);
if (!ret)
return NULL;
// Should not fail, but check anyway
PyWinBufferView pybuf(ret, true);
if (!pybuf.ok()) {
Py_DECREF(ret);
return NULL;
}
memcpy(pybuf.ptr(), v, sz);
return ret;
}
typedef struct {
const TCHAR *ptr;
int parmCount;
int parmIdx;
int isParm;
TCHAR state;
TCHAR prev;
} parseContext;
static void initParseContext(parseContext *ct, const TCHAR *c)
{
ct->state = 0;
ct->ptr = c;
ct->parmCount = 0;
}
static TCHAR doParse(parseContext *ct)
{
ct->isParm = 0;
if (ct->state == *ct->ptr) {
ct->state = 0;
}
else if (ct->state == 0) {
if ((*ct->ptr == '\'') || (*ct->ptr == '"')) {
ct->state = *ct->ptr;
}
else if (*ct->ptr == '?') {
ct->parmIdx = ct->parmCount;
ct->parmCount++;
ct->isParm = 1;
}
else if ((*ct->ptr == ':') && !isalnum(ct->prev)) {
const TCHAR *m = ct->ptr + 1;
int n = 0;
while (isdigit(*m)) {
n *= 10;
n += *m - '0';
m++;
}
if (n) {
ct->parmIdx = n - 1;
ct->parmCount++;
ct->ptr = m;
ct->isParm = 1;
ct->prev = '0';
return '?';
}
}
}
ct->prev = *ct->ptr;
return *ct->ptr++;
}
static SQLLEN NTS = SQL_NTS;
static InputBinding *initInputBinding(cursorObject *cur, Py_ssize_t len)
{
InputBinding *ib = (InputBinding *)malloc(sizeof(InputBinding) + len);
if (ib) {
ib->bPutData = false;
ib->next = cur->inputVars;
cur->inputVars = ib;
ib->len = len;
}
else {
PyErr_NoMemory();
}
return ib;
}
static int ibindInt(cursorObject *cur, int column, PyObject *item)
{
int len = sizeof(long);
long val = PyLong_AsLong(item);
InputBinding *ib = initInputBinding(cur, len);
if (!ib)
return 0;
memcpy(ib->bind_area, &val, len);
if (unsuccessful(SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, len, 0,
ib->bind_area, len, &ib->len))) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindLong(cursorObject *cur, int column, PyObject *item)
{
/* This will always be called in Py3k, so differentiate between an int
that fits in a long, and one that requires a 64=bit datatype. */
int len;
InputBinding *ib;
SQLSMALLINT ParamType = SQL_PARAM_INPUT, CType, SqlType;
long longval = PyLong_AsLong(item);
if (longval != -1 || !PyErr_Occurred()) {
CType = SQL_C_LONG;
SqlType = SQL_INTEGER;
len = sizeof(long);
ib = initInputBinding(cur, len);
if (!ib)
return 0;
memcpy(ib->bind_area, &longval, len);
}
else {
__int64 longlongval = PyLong_AsLongLong(item);
if (longlongval == -1 && PyErr_Occurred())
return 0;
CType = SQL_C_SBIGINT;
SqlType = SQL_BIGINT;
len = sizeof(longlongval);
ib = initInputBinding(cur, len);
if (!ib)
return 0;
memcpy(ib->bind_area, &longlongval, len);
}
if (unsuccessful(
SQLBindParameter(cur->hstmt, column, ParamType, CType, SqlType, len, 0, ib->bind_area, len, &ib->len))) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindNull(cursorObject *cur, int column)
{
static SQLLEN nl;
/* apparently, ODBC does not read the last parameter
until EXEC time, i.e., after this function is
out of scope, hence nl must be static */
nl = SQL_NULL_DATA;
/* I don't know if ODBC resets the value of the parameter.
It shouldn't but god knows... */
if (unsuccessful(SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 0, 0, 0, 0, &nl))) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindDate(cursorObject *cur, int column, PyObject *item)
{
/* Sql server apparently determines the precision and type of date based
on length of input, according to the character size required for column
storage. This is completely bogus when passing a TIMESTAMP_STRUCT, whose
length is always 16. This apparently causes Sql Server to treat it as a
SMALLDATETIME, and truncates seconds as well as fraction of second, and
also limits the range of acceptable dates.
Tell it we have enough room for 3 decimals, since this is all that
SYSTEMTIME affords, and all that Sql Server 2005 will accept.
Sql Server 2008 has a datetime2 with up to 7 decimals.
Might need to use SqlDescribeCol to get length and precision to support this.
*/
SQLLEN len = 23; // length of character storage for yyyy-mm-dd hh:mm:ss.ddd
assert(len >= sizeof(TIMESTAMP_STRUCT));
InputBinding *ib = initInputBinding(cur, len);
if (!ib)
return 0;
TIMESTAMP_STRUCT *dt = (TIMESTAMP_STRUCT *)ib->bind_area;
ZeroMemory(dt, len);
// Accept a datetime object
TmpPyObject timeseq = PyObject_CallMethod(item, "timetuple", NULL);
if (timeseq == NULL)
return 0;
timeseq = PySequence_Tuple(timeseq);
if (timeseq == NULL)
return 0;
// Last 3 items are ignored.
PyObject *obwday, *obyday, *obdst;
if (!PyArg_ParseTuple(timeseq, "hhh|hhhOOO:TIMESTAMP_STRUCT", &dt->year, &dt->month, &dt->day, &dt->hour,
&dt->minute, &dt->second, &obwday, &obyday, &obdst))
return 0;
TmpPyObject usec = PyObject_GetAttrString(item, "microsecond");
if (usec == NULL) {
PyErr_Clear();
}
else {
dt->fraction = PyLong_AsUnsignedLong(usec);
if (dt->fraction == -1 && PyErr_Occurred())
return 0;
// Convert to nanoseconds
dt->fraction *= 1000;
}
if (unsuccessful(SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_TIMESTAMP, SQL_TIMESTAMP, len,
3, // Decimal digits of precision, appears to be ignored for datetime
ib->bind_area, len, &ib->len))) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindRaw(cursorObject *cur, int column, PyObject *item)
{
PyWinBufferView pybuf(item);
if (!pybuf.ok())
return 0;
InputBinding *ib = initInputBinding(cur, pybuf.len());
if (!ib)
return 0;
ib->bPutData = true;
memcpy(ib->bind_area, pybuf.ptr(), pybuf.len());
RETCODE rc = SQL_SUCCESS;
ib->sqlBytesAvailable = SQL_LEN_DATA_AT_EXEC(ib->len);
rc = SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, pybuf.len(), 0,
ib->bind_area, pybuf.len(), &ib->len);
if (unsuccessful(rc)) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindFloat(cursorObject *cur, int column, PyObject *item)
{
double d = PyFloat_AsDouble(item);
InputBinding *ib = initInputBinding(cur, sizeof(double));
if (!ib)
return NULL;
memcpy(ib->bind_area, &d, ib->len);
if (unsuccessful(SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_DOUBLE, 15, 0,
ib->bind_area, sizeof(double), &ib->len))) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindString(cursorObject *cur, int column, PyObject *item)
{
const char *val = PyBytes_AsString(item);
size_t len = strlen(val);
InputBinding *ib = initInputBinding(cur, len);
if (!ib)
return 0;
strcpy(ib->bind_area, val);
int sqlType = SQL_VARCHAR; /* SQL_CHAR can cause padding in some drivers.. */
if (len > 255) /* should remove hardcoded value and actually implement setinputsize method */
{
ib->sqlBytesAvailable = SQL_LEN_DATA_AT_EXEC(ib->len);
sqlType = SQL_LONGVARCHAR;
ib->bPutData = true;
}
else {
ib->sqlBytesAvailable = ib->len;
ib->bPutData = false;
}
RETCODE rc =
SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_CHAR, sqlType, len, 0, ib->bind_area, len, &NTS);
if (unsuccessful(rc)) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int ibindUnicode(cursorObject *cur, int column, PyObject *item)
{
TmpWCHAR wval = item;
if (!wval)
return 0;
Py_ssize_t nchars = wval.length + 1;
Py_ssize_t nbytes = nchars * sizeof(WCHAR);
InputBinding *ib = initInputBinding(cur, nbytes);
if (!ib)
return 0;
memcpy(ib->bind_area, wval, nbytes);
/* See above re SQL_VARCHAR */
int sqlType = SQL_WVARCHAR;
if (nchars > 255) {
ib->sqlBytesAvailable = SQL_LEN_DATA_AT_EXEC(ib->len);
sqlType = SQL_WLONGVARCHAR;
ib->bPutData = true;
}
else {
ib->sqlBytesAvailable = ib->len;
ib->bPutData = false;
}
RETCODE rc = SQLBindParameter(cur->hstmt, column, SQL_PARAM_INPUT, SQL_C_WCHAR, sqlType, nchars, 0, ib->bind_area,
nbytes, &NTS);
if (unsuccessful(rc)) {
cursorError(cur, _T("input-binding"));
return 0;
}
return 1;
}
static int rewriteQuery(TCHAR *out, const TCHAR *in)
{
parseContext ctx;
initParseContext(&ctx, in);
while (*out++ = doParse(&ctx));
return ctx.parmCount;
}
static int bindInput(cursorObject *cur, PyObject *vars, int columns)
{
int i;
PyObject *item;
int rv;
int iCol;
if (columns == 0) {
return 1;
}
for (i = 0; i < PySequence_Length(vars); i++) {
item = PySequence_GetItem(vars, i);
iCol = i + 1;
if (PyLong_Check(item)) {
rv = ibindLong(cur, iCol, item);
}
else if (PyLong_Check(item)) {
rv = ibindInt(cur, iCol, item);
}
else if (PyBytes_Check(item)) {
rv = ibindString(cur, iCol, item);
}
else if (PyUnicode_Check(item)) {
rv = ibindUnicode(cur, iCol, item);
}
else if (item == Py_None) {
rv = ibindNull(cur, iCol);
}
else if (PyFloat_Check(item)) {
rv = ibindFloat(cur, iCol, item);
}
else if (PyWinTime_Check(item)) {
rv = ibindDate(cur, iCol, item);
}
else if (PyObject_CheckBuffer(item)) {
rv = ibindRaw(cur, iCol, item);
}
else {
OutputDebugString(_T("bindInput - using repr conversion for type: '"));
OutputDebugStringA(Py_TYPE(item)->tp_name);
OutputDebugString(_T("'\n"));
PyObject *sitem = PyObject_Str(item);
if (sitem == NULL)
rv = 0;
else if (PyBytes_Check(sitem))
rv = ibindString(cur, iCol, sitem);
else if (PyUnicode_Check(sitem))
rv = ibindUnicode(cur, iCol, sitem);
else { // Just in case some object doesn't follow the rules
PyErr_Format(PyExc_SystemError, "??? Repr for type '%s' returned type '%s' ???", Py_TYPE(item),
Py_TYPE(sitem));
rv = 0;
}
Py_XDECREF(sitem);
}
Py_DECREF(item);
if (rv == 0) {
return 0;
}
}
return 1;
}
static int display_size(short coltype, int collen, const TCHAR *colname)
{
switch (coltype) {
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_DATE:
case SQL_TIMESTAMP:
case SQL_BIT:
return (max(collen, (int)_tcslen(colname)));
case SQL_SMALLINT:
case SQL_INTEGER:
case SQL_TINYINT:
return (max(collen + 1, (int)_tcslen(colname)));
case SQL_DECIMAL:
case SQL_NUMERIC:
return (max(collen + 2, (int)_tcslen(colname)));
case SQL_REAL:
case SQL_FLOAT:
case SQL_DOUBLE:
return (max(20, (int)_tcslen(colname)));
case SQL_BINARY:
case SQL_VARBINARY:
return (max(2 * collen, (int)_tcslen(colname)));
case SQL_LONGVARBINARY:
case SQL_LONGVARCHAR:
default:
return (0);
}
}
static BOOL bindOutput(cursorObject *cur)
{
short vtype;
SQLULEN vsize;
TCHAR name[256];
int pos = 1;
short n_columns;
SQLNumResultCols(cur->hstmt, &n_columns);
cur->n_columns = n_columns;
for (pos = 1; pos <= cur->n_columns; pos++) {
PyObject *typeOf;
long dsize;
unsigned long prec;
short nullok;
short nsize;
short scale = 0;
SQLDescribeCol(cur->hstmt, pos, (SQLTCHAR *)name, sizeof(name) / sizeof(name[0]), &nsize, &vtype,
&vsize, // This is column size in characters
&scale, &nullok);
name[nsize] = 0;
dsize = display_size(vtype, vsize, name);
prec = 0;
switch (vtype) {
case SQL_BIT:
case SQL_SMALLINT:
case SQL_INTEGER:
case SQL_TINYINT:
if (!bindOutputVar(cur, longCopy, SQL_C_LONG, sizeof(unsigned long), pos, false))
return FALSE;
typeOf = DbiNumber;
break;
case SQL_NUMERIC:
case SQL_DECIMAL:
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_REAL:
case SQL_BIGINT:
if (!bindOutputVar(cur, doubleCopy, SQL_C_DOUBLE, sizeof(double), pos, false))
return FALSE;
typeOf = DbiNumber;
prec = vsize;
break;