-
Notifications
You must be signed in to change notification settings - Fork 564
/
params.cpp
1902 lines (1665 loc) · 64.2 KB
/
params.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
// https://msdn.microsoft.com/en-us/library/ms711014(v=vs.85).aspx
//
// "The length of both the data buffer and the data it contains is measured in bytes, as
// opposed to characters."
//
// https://msdn.microsoft.com/en-us/library/ms711786(v=vs.85).aspx
//
// Column Size: "For character types, this is the length in characters of the data"
// NOTE: I have not ported the "fast executemany" code from 4.x to 5.x yet. Once 5.0 is
// complete, I'll port it in 5.1. My goal is to ensure it uses the exact same binding code
// between both code paths. I'll probably also rename the feature to something that describes
// it more precisely like "array binding".
#include "pyodbc.h"
#include "wrapper.h"
#include "textenc.h"
#include "pyodbcmodule.h"
#include "cursor.h"
#include "params.h"
#include "connection.h"
#include "errors.h"
#include "dbspecific.h"
#include "row.h"
#include <datetime.h>
inline Connection* GetConnection(Cursor* cursor)
{
return (Connection*)cursor->cnxn;
}
struct DAEParam
{
PyObject *cell;
SQLLEN maxlen;
};
static int DetectCType(PyObject *cell, ParamInfo *pi)
{
// Detects and sets the appropriate C type to use for binding the specified Python object.
// Also sets the buffer length to use. Returns false if unsuccessful.
//
// We're setting the pi ParameterType and BufferLength. These are based on the Python
// value if not None or binary. For those, the *existing* ParameterType is used. This
// could be from a previous row or could have been initialized from SQLDescribeParam.
PyObject* cls = 0;
if (PyBool_Check(cell))
{
Type_Bool:
pi->ValueType = SQL_C_BIT;
pi->BufferLength = 1;
}
else if (PyLong_Check(cell))
{
Type_Long:
if (pi->ParameterType == SQL_NUMERIC ||
pi->ParameterType == SQL_DECIMAL)
{
pi->ValueType = SQL_C_NUMERIC;
pi->BufferLength = sizeof(SQL_NUMERIC_STRUCT);
}
else
{
pi->ValueType = SQL_C_SBIGINT;
pi->BufferLength = sizeof(long long);
}
}
else if (PyFloat_Check(cell))
{
Type_Float:
pi->ValueType = SQL_C_DOUBLE;
pi->BufferLength = sizeof(double);
}
else if (PyBytes_Check(cell))
{
Type_Bytes:
// Assume the SQL type is also character (2.x) or binary (3.x).
// If it is a max-type (ColumnSize == 0), use DAE.
pi->ValueType = SQL_C_BINARY;
pi->BufferLength = pi->ColumnSize ? pi->ColumnSize : sizeof(DAEParam);
}
else if (PyUnicode_Check(cell))
{
Type_Unicode:
// Assume the SQL type is also wide character.
// If it is a max-type (ColumnSize == 0), use DAE.
pi->ValueType = SQL_C_WCHAR;
pi->BufferLength = pi->ColumnSize ? pi->ColumnSize * sizeof(SQLWCHAR) : sizeof(DAEParam);
}
else if (PyDateTime_Check(cell))
{
Type_DateTime:
pi->ValueType = SQL_C_TYPE_TIMESTAMP;
pi->BufferLength = sizeof(SQL_TIMESTAMP_STRUCT);
}
else if (PyDate_Check(cell))
{
Type_Date:
pi->ValueType = SQL_C_TYPE_DATE;
pi->BufferLength = sizeof(SQL_DATE_STRUCT);
}
else if (PyTime_Check(cell))
{
Type_Time:
if (pi->ParameterType == SQL_SS_TIME2)
{
pi->ValueType = SQL_C_BINARY;
pi->BufferLength = sizeof(SQL_SS_TIME2_STRUCT);
}
else
{
pi->ValueType = SQL_C_TYPE_TIME;
pi->BufferLength = sizeof(SQL_TIME_STRUCT);
}
}
else if (PyByteArray_Check(cell))
{
// Type_ByteArray:
pi->ValueType = SQL_C_BINARY;
pi->BufferLength = pi->ColumnSize ? pi->ColumnSize : sizeof(DAEParam);
}
else if (cell == Py_None || cell == null_binary)
{
// Use the SQL type to guess what Nones should be inserted as here.
switch (pi->ParameterType)
{
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_LONGVARCHAR:
goto Type_Bytes;
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
goto Type_Unicode;
case SQL_DECIMAL:
case SQL_NUMERIC:
goto Type_Decimal;
case SQL_BIGINT:
goto Type_Long;
case SQL_SMALLINT:
case SQL_INTEGER:
case SQL_TINYINT:
goto Type_Long;
case SQL_REAL:
case SQL_FLOAT:
case SQL_DOUBLE:
goto Type_Float;
case SQL_BIT:
goto Type_Bool;
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
// TODO: Shouldn't this be bytes?
// goto Type_ByteArray;
goto Type_Bytes;
case SQL_TYPE_DATE:
goto Type_Date;
case SQL_SS_TIME2:
case SQL_TYPE_TIME:
goto Type_Time;
case SQL_TYPE_TIMESTAMP:
goto Type_DateTime;
case SQL_GUID:
goto Type_UUID;
default:
goto Type_Bytes;
}
}
else if (IsInstanceForThread(cell, "uuid", "UUID", &cls) && cls)
{
Type_UUID:
// UUID
pi->ValueType = SQL_C_GUID;
pi->BufferLength = 16;
}
else if (IsInstanceForThread(cell, "decimal", "Decimal", &cls) && cls)
{
Type_Decimal:
pi->ValueType = SQL_C_NUMERIC;
pi->BufferLength = sizeof(SQL_NUMERIC_STRUCT);
}
else
{
RaiseErrorV(0, ProgrammingError, "Unknown object type %s during describe", cell->ob_type->tp_name);
return false;
}
return true;
}
#define WRITEOUT(type, ptr, val, indv) { *(type*)(*ptr) = (val); *ptr += sizeof(type); indv = sizeof(type); }
// Convert Python object into C data for binding.
// Output pointer is written to with data, indicator, and updated.
// Returns false if object could not be converted.
static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamInfo *pi)
{
PyObject *cls = 0;
// TODO: Any way to make this a switch (O(1)) or similar instead of if-else chain?
// TODO: Otherwise, rearrange these cases in order of frequency...
SQLLEN ind;
if (PyBool_Check(cell))
{
if (pi->ValueType != SQL_C_BIT)
return false;
WRITEOUT(char, outbuf, cell == Py_True, ind);
}
else if (PyLong_Check(cell))
{
if (pi->ValueType == SQL_C_SBIGINT)
{
WRITEOUT(long long, outbuf, PyLong_AsLongLong(cell), ind);
}
else if (pi->ValueType == SQL_C_NUMERIC)
{
// Convert a PyLong into a SQL_NUMERIC_STRUCT, without losing precision
// or taking an unnecessary trip through character strings.
SQL_NUMERIC_STRUCT *pNum = (SQL_NUMERIC_STRUCT*)*outbuf;
PyObject *absVal = PyNumber_Absolute(cell);
if (pi->DecimalDigits)
{
static PyObject *scaler_table[38];
static PyObject *tenObject;
// Need to scale by 10**pi->DecimalDigits
if (pi->DecimalDigits > 38)
{
NumericOverflow:
RaiseErrorV(0, ProgrammingError, "Numeric overflow");
Py_XDECREF(absVal);
return false;
}
if (!scaler_table[pi->DecimalDigits - 1])
{
if (!tenObject)
tenObject = PyLong_FromLong(10);
PyObject *scaleObj = PyLong_FromLong(pi->DecimalDigits);
scaler_table[pi->DecimalDigits - 1] = PyNumber_Power(tenObject, scaleObj, Py_None);
Py_XDECREF(scaleObj);
}
PyObject *scaledVal = PyNumber_Multiply(absVal, scaler_table[pi->DecimalDigits - 1]);
Py_XDECREF(absVal);
absVal = scaledVal;
}
pNum->precision = (SQLCHAR)pi->ColumnSize;
pNum->scale = (SQLCHAR)pi->DecimalDigits;
pNum->sign = _PyLong_Sign(cell) >= 0;
#if PY_VERSION_HEX < 0x030D0000
if (_PyLong_AsByteArray((PyLongObject*)absVal, pNum->val, sizeof(pNum->val), 1, 0)) {
#else
if (_PyLong_AsByteArray((PyLongObject*)absVal, pNum->val, sizeof(pNum->val), 1, 0, 1)) {
#endif
goto NumericOverflow;
}
Py_XDECREF(absVal);
*outbuf += pi->BufferLength;
ind = sizeof(SQL_NUMERIC_STRUCT);
}
else
return false;
}
else if (PyFloat_Check(cell))
{
if (pi->ValueType != SQL_C_DOUBLE)
return false;
WRITEOUT(double, outbuf, PyFloat_AS_DOUBLE(cell), ind);
}
else if (PyBytes_Check(cell))
{
if (pi->ValueType != SQL_C_BINARY)
return false;
Py_ssize_t len = PyBytes_GET_SIZE(cell);
if (!pi->ColumnSize) // DAE
{
DAEParam *pParam = (DAEParam*)*outbuf;
Py_INCREF(cell);
pParam->cell = cell;
pParam->maxlen = cur->cnxn->GetMaxLength(pi->ValueType);
*outbuf += sizeof(DAEParam);
ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)len) : SQL_DATA_AT_EXEC;
}
else
{
if (len > pi->BufferLength)
{
RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %u buffer %u", len, pi->BufferLength);
return false;
}
memcpy(*outbuf, PyBytes_AS_STRING(cell), len);
*outbuf += pi->BufferLength;
ind = len;
}
}
else if (PyUnicode_Check(cell))
{
if (pi->ValueType != SQL_C_WCHAR)
return false;
const TextEnc& enc = cur->cnxn->unicode_enc;
Object encoded(PyCodec_Encode(cell, enc.name, "strict"));
if (!encoded)
return false;
if (enc.optenc == OPTENC_NONE && !PyBytes_CheckExact(encoded))
{
PyErr_Format(PyExc_TypeError, "Unicode write encoding '%s' returned unexpected data type: %s",
enc.name, encoded.Get()->ob_type->tp_name);
return false;
}
Py_ssize_t len = PyBytes_GET_SIZE(encoded);
if (!pi->ColumnSize)
{
// DAE
DAEParam *pParam = (DAEParam*)*outbuf;
pParam->cell = encoded.Detach();
pParam->maxlen = cur->cnxn->GetMaxLength(pi->ValueType);
*outbuf += sizeof(DAEParam);
ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)len) : SQL_DATA_AT_EXEC;
}
else
{
if (len > pi->BufferLength)
{
RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %u buffer %u", len, pi->BufferLength);
return false;
}
memcpy(*outbuf, PyBytes_AS_STRING((PyObject*)encoded), len);
*outbuf += pi->BufferLength;
ind = len;
}
}
else if (PyDateTime_Check(cell))
{
if (pi->ValueType != SQL_C_TYPE_TIMESTAMP)
return false;
SQL_TIMESTAMP_STRUCT *pts = (SQL_TIMESTAMP_STRUCT*)*outbuf;
pts->year = PyDateTime_GET_YEAR(cell);
pts->month = PyDateTime_GET_MONTH(cell);
pts->day = PyDateTime_GET_DAY(cell);
pts->hour = PyDateTime_DATE_GET_HOUR(cell);
pts->minute = PyDateTime_DATE_GET_MINUTE(cell);
pts->second = PyDateTime_DATE_GET_SECOND(cell);
// Truncate the fraction according to precision
size_t digits = min(9, pi->DecimalDigits);
long fast_pow10[] = {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
SQLUINTEGER milliseconds = PyDateTime_DATE_GET_MICROSECOND(cell) * 1000;
pts->fraction = milliseconds - (milliseconds % fast_pow10[9 - digits]);
*outbuf += sizeof(SQL_TIMESTAMP_STRUCT);
ind = sizeof(SQL_TIMESTAMP_STRUCT);
}
else if (PyDate_Check(cell))
{
if (pi->ValueType != SQL_C_TYPE_DATE)
return false;
SQL_DATE_STRUCT *pds = (SQL_DATE_STRUCT*)*outbuf;
pds->year = PyDateTime_GET_YEAR(cell);
pds->month = PyDateTime_GET_MONTH(cell);
pds->day = PyDateTime_GET_DAY(cell);
*outbuf += sizeof(SQL_DATE_STRUCT);
ind = sizeof(SQL_DATE_STRUCT);
}
else if (PyTime_Check(cell))
{
if (pi->ParameterType == SQL_SS_TIME2)
{
if (pi->ValueType != SQL_C_BINARY)
return false;
SQL_SS_TIME2_STRUCT *pt2s = (SQL_SS_TIME2_STRUCT*)*outbuf;
pt2s->hour = PyDateTime_TIME_GET_HOUR(cell);
pt2s->minute = PyDateTime_TIME_GET_MINUTE(cell);
pt2s->second = PyDateTime_TIME_GET_SECOND(cell);
// This is in units of nanoseconds.
pt2s->fraction = PyDateTime_TIME_GET_MICROSECOND(cell)*1000;
*outbuf += sizeof(SQL_SS_TIME2_STRUCT);
ind = sizeof(SQL_SS_TIME2_STRUCT);
}
else
{
if (pi->ValueType != SQL_C_TYPE_TIME)
return false;
SQL_TIME_STRUCT *pts = (SQL_TIME_STRUCT*)*outbuf;
pts->hour = PyDateTime_TIME_GET_HOUR(cell);
pts->minute = PyDateTime_TIME_GET_MINUTE(cell);
pts->second = PyDateTime_TIME_GET_SECOND(cell);
*outbuf += sizeof(SQL_TIME_STRUCT);
ind = sizeof(SQL_TIME_STRUCT);
}
}
else if (PyByteArray_Check(cell))
{
if (pi->ValueType != SQL_C_BINARY)
return false;
Py_ssize_t len = PyByteArray_GET_SIZE(cell);
if (!pi->ColumnSize) // DAE
{
DAEParam *pParam = (DAEParam*)*outbuf;
Py_INCREF(cell);
pParam->cell = cell;
pParam->maxlen = cur->cnxn->GetMaxLength(pi->ValueType);
*outbuf += sizeof(DAEParam);
ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)len) : SQL_DATA_AT_EXEC;
}
else
{
if (len > pi->BufferLength)
{
RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %u buffer %u", len, pi->BufferLength);
return false;
}
memcpy(*outbuf, PyByteArray_AS_STRING(cell), len);
*outbuf += pi->BufferLength;
ind = len;
}
}
else if (IsInstanceForThread(cell, "uuid", "UUID", &cls) && cls)
{
if (pi->ValueType != SQL_C_GUID)
return false;
pi->BufferLength = 16;
// Do we need to use "bytes" on a big endian machine?
Object b(PyObject_GetAttrString(cell, "bytes_le"));
if (!b)
return false;
memcpy(*outbuf, PyBytes_AS_STRING(b.Get()), sizeof(SQLGUID));
*outbuf += pi->BufferLength;
ind = 16;
}
else if (IsInstanceForThread(cell, "decimal", "Decimal", &cls) && cls)
{
if (pi->ValueType != SQL_C_NUMERIC)
return false;
// Normalise, then get sign, exponent, and digits.
PyObject *normCell = PyObject_CallMethod(cell, "normalize", 0);
if (!normCell)
return false;
PyObject *cellParts = PyObject_CallMethod(normCell, "as_tuple", 0);
if (!cellParts)
return false;
Py_XDECREF(normCell);
SQL_NUMERIC_STRUCT *pNum = (SQL_NUMERIC_STRUCT*)*outbuf;
pNum->sign = !PyLong_AsLong(PyTuple_GET_ITEM(cellParts, 0));
PyObject* digits = PyTuple_GET_ITEM(cellParts, 1);
long exp = PyLong_AsLong(PyTuple_GET_ITEM(cellParts, 2));
Py_ssize_t numDigits = PyTuple_GET_SIZE(digits);
// PyDecimal is digits * 10**exp = digits / 10**-exp
// SQL_NUMERIC_STRUCT is val / 10**scale
Py_ssize_t scaleDiff = pi->DecimalDigits + exp;
if (scaleDiff < 0)
{
RaiseErrorV(0, ProgrammingError, "Converting decimal loses precision");
return false;
}
// Append '0's to the end of the digits to effect the scaling.
PyObject *newDigits = PyTuple_New(numDigits + scaleDiff);
for (Py_ssize_t i = 0; i < numDigits; i++)
{
PyTuple_SET_ITEM(newDigits, i, PyLong_FromLong(PyNumber_AsSsize_t(PyTuple_GET_ITEM(digits, i), 0)));
}
for (Py_ssize_t i = numDigits; i < scaleDiff + numDigits; i++)
{
PyTuple_SET_ITEM(newDigits, i, PyLong_FromLong(0));
}
PyObject *args = Py_BuildValue("((iOi))", 0, newDigits, 0);
PyObject *scaledDecimal = PyObject_CallObject((PyObject*)cell->ob_type, args);
PyObject *digitLong = PyNumber_Long(scaledDecimal);
Py_XDECREF(args);
Py_XDECREF(scaledDecimal);
Py_XDECREF(newDigits);
Py_XDECREF(cellParts);
pNum->precision = (SQLCHAR)pi->ColumnSize;
pNum->scale = (SQLCHAR)pi->DecimalDigits;
#if PY_VERSION_HEX < 0x030D0000
int ret = _PyLong_AsByteArray((PyLongObject*)digitLong, pNum->val, sizeof(pNum->val), 1, 0);
#else
int ret = _PyLong_AsByteArray((PyLongObject*)digitLong, pNum->val, sizeof(pNum->val), 1, 0, 1);
#endif
Py_XDECREF(digitLong);
if (ret)
{
PyErr_Clear();
RaiseErrorV(0, ProgrammingError, "Numeric overflow");
return false;
}
*outbuf += pi->BufferLength;
ind = sizeof(SQL_NUMERIC_STRUCT);
}
else if (cell == Py_None || cell == null_binary)
{
// REVIEW: Theoretically we could eliminate the initial call to SQLDescribeParam for
// all columns if we had a special value for "unknown" and called SQLDescribeParam only
// here when we hit it. Even then, only if we don't already have previous Python
// objects!
*outbuf += pi->BufferLength;
ind = SQL_NULL_DATA;
}
else
{
RaiseErrorV(0, ProgrammingError, "Unknown object type: %s",cell->ob_type->tp_name);
return false;
}
*(SQLLEN*)(*outbuf) = ind;
*outbuf += sizeof(SQLLEN);
return true;
}
static bool GetParamType(Cursor* cur, Py_ssize_t iParam, SQLSMALLINT& type);
static void FreeInfos(ParamInfo* a, Py_ssize_t count)
{
for (Py_ssize_t i = 0; i < count; i++)
{
if (a[i].allocated)
PyMem_Free(a[i].ParameterValuePtr);
if (a[i].ParameterType == SQL_SS_TABLE && a[i].nested)
FreeInfos(a[i].nested, a[i].maxlength);
Py_XDECREF(a[i].pObject);
}
PyMem_Free(a);
}
static bool GetNullInfo(Cursor* cur, Py_ssize_t index, ParamInfo& info)
{
if (!GetParamType(cur, index, info.ParameterType))
return false;
info.ValueType = SQL_C_DEFAULT;
info.ColumnSize = 1;
info.StrLen_or_Ind = SQL_NULL_DATA;
return true;
}
static bool GetNullBinaryInfo(Cursor* cur, Py_ssize_t index, ParamInfo& info)
{
info.ValueType = SQL_C_BINARY;
info.ParameterType = SQL_BINARY;
info.ColumnSize = 1;
info.ParameterValuePtr = 0;
info.StrLen_or_Ind = SQL_NULL_DATA;
return true;
}
static bool GetBytesInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, bool isTVP)
{
// The Python 3 version that writes bytes as binary data.
Py_ssize_t cb = PyBytes_GET_SIZE(param);
info.ValueType = SQL_C_BINARY;
info.ColumnSize = isTVP ? 0 : (SQLUINTEGER)max(cb, 1);
SQLLEN maxlength = cur->cnxn->GetMaxLength(info.ValueType);
if (maxlength == 0 || cb <= maxlength || isTVP)
{
info.ParameterType = SQL_VARBINARY;
info.StrLen_or_Ind = cb;
info.BufferLength = (SQLLEN)info.ColumnSize;
info.ParameterValuePtr = PyBytes_AS_STRING(param);
}
else
{
// Too long to pass all at once, so we'll provide the data at execute.
info.ParameterType = SQL_LONGVARBINARY;
info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)cb) : SQL_DATA_AT_EXEC;
info.ParameterValuePtr = &info;
info.BufferLength = sizeof(ParamInfo*);
info.pObject = param;
Py_INCREF(info.pObject);
info.maxlength = maxlength;
}
return true;
}
static bool GetUnicodeInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, bool isTVP)
{
const TextEnc& enc = cur->cnxn->unicode_enc;
info.ValueType = enc.ctype;
Object encoded(PyCodec_Encode(param, enc.name, "strict"));
if (!encoded)
return false;
if (enc.optenc == OPTENC_NONE && !PyBytes_CheckExact(encoded))
{
PyErr_Format(PyExc_TypeError, "Unicode write encoding '%s' returned unexpected data type: %s",
enc.name, encoded.Get()->ob_type->tp_name);
return false;
}
Py_ssize_t cb = PyBytes_GET_SIZE(encoded);
int denom = 1;
if (enc.optenc == OPTENC_UTF16)
{
denom = 2;
}
else if (enc.optenc == OPTENC_UTF32)
{
denom = 4;
}
info.ColumnSize = isTVP ? 0 : (SQLUINTEGER)max(cb / denom, 1);
info.pObject = encoded.Detach();
SQLLEN maxlength = cur->cnxn->GetMaxLength(enc.ctype);
if (maxlength == 0 || cb <= maxlength || isTVP)
{
info.ParameterType = (enc.ctype == SQL_C_CHAR) ? SQL_VARCHAR : SQL_WVARCHAR;
info.ParameterValuePtr = PyBytes_AS_STRING(info.pObject);
info.BufferLength = (SQLINTEGER)cb;
info.StrLen_or_Ind = (SQLINTEGER)cb;
}
else
{
// Too long to pass all at once, so we'll provide the data at execute.
info.ParameterType = (enc.ctype == SQL_C_CHAR) ? SQL_LONGVARCHAR : SQL_WLONGVARCHAR;
info.ParameterValuePtr = &info;
info.BufferLength = sizeof(ParamInfo*);
info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLINTEGER)cb) : SQL_DATA_AT_EXEC;
info.maxlength = maxlength;
}
return true;
}
static bool GetBooleanInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
info.ValueType = SQL_C_BIT;
info.ParameterType = SQL_BIT;
info.StrLen_or_Ind = 1;
info.Data.ch = (unsigned char)(param == Py_True ? 1 : 0);
info.ParameterValuePtr = &info.Data.ch;
return true;
}
static bool GetDateTimeInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
info.Data.timestamp.year = (SQLSMALLINT) PyDateTime_GET_YEAR(param);
info.Data.timestamp.month = (SQLUSMALLINT)PyDateTime_GET_MONTH(param);
info.Data.timestamp.day = (SQLUSMALLINT)PyDateTime_GET_DAY(param);
info.Data.timestamp.hour = (SQLUSMALLINT)PyDateTime_DATE_GET_HOUR(param);
info.Data.timestamp.minute = (SQLUSMALLINT)PyDateTime_DATE_GET_MINUTE(param);
info.Data.timestamp.second = (SQLUSMALLINT)PyDateTime_DATE_GET_SECOND(param);
// SQL Server chokes if the fraction has more data than the database supports. We expect other databases to be the
// same, so we reduce the value to what the database supports. http://support.microsoft.com/kb/263872
int precision = ((Connection*)cur->cnxn)->datetime_precision - 20; // (20 includes a separating period)
if (precision <= 0)
{
info.Data.timestamp.fraction = 0;
}
else
{
info.Data.timestamp.fraction = (SQLUINTEGER)(PyDateTime_DATE_GET_MICROSECOND(param) * 1000); // 1000 == micro -> nano
// (How many leading digits do we want to keep? With SQL Server 2005, this should be 3: 123000000)
int keep = (int)pow(10.0, 9-min(9, precision));
info.Data.timestamp.fraction = info.Data.timestamp.fraction / keep * keep;
info.DecimalDigits = (SQLSMALLINT)precision;
}
info.ValueType = SQL_C_TIMESTAMP;
info.ParameterType = SQL_TIMESTAMP;
info.ColumnSize = (SQLUINTEGER)((Connection*)cur->cnxn)->datetime_precision;
info.StrLen_or_Ind = sizeof(TIMESTAMP_STRUCT);
info.ParameterValuePtr = &info.Data.timestamp;
return true;
}
static bool GetDateInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
info.Data.date.year = (SQLSMALLINT) PyDateTime_GET_YEAR(param);
info.Data.date.month = (SQLUSMALLINT)PyDateTime_GET_MONTH(param);
info.Data.date.day = (SQLUSMALLINT)PyDateTime_GET_DAY(param);
info.ValueType = SQL_C_TYPE_DATE;
info.ParameterType = SQL_TYPE_DATE;
info.ColumnSize = 10;
info.ParameterValuePtr = &info.Data.date;
info.StrLen_or_Ind = sizeof(DATE_STRUCT);
return true;
}
static bool GetTimeInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
info.Data.time.hour = (SQLUSMALLINT)PyDateTime_TIME_GET_HOUR(param);
info.Data.time.minute = (SQLUSMALLINT)PyDateTime_TIME_GET_MINUTE(param);
info.Data.time.second = (SQLUSMALLINT)PyDateTime_TIME_GET_SECOND(param);
info.ValueType = SQL_C_TYPE_TIME;
info.ParameterType = SQL_TYPE_TIME;
info.ColumnSize = 8;
info.ParameterValuePtr = &info.Data.time;
info.StrLen_or_Ind = sizeof(TIME_STRUCT);
return true;
}
inline bool NeedsBigInt(long long ll)
{
// NOTE: Smallest 32-bit int should be -214748368 but the MS compiler v.1900 AMD64
// says that (10 < -2147483648). Perhaps I miscalculated the minimum?
return ll < -2147483647 || ll > 2147483647;
}
static bool GetLongInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, bool isTVP)
{
// Since some drivers like Access don't support BIGINT, we use INTEGER when possible.
// Unfortunately this may mean that we end up with two execution plans for the same SQL.
// We could use SQLDescribeParam but that's kind of expensive.
long long value = PyLong_AsLongLong(param);
if (PyErr_Occurred())
return false;
if (isTVP || NeedsBigInt(value))
{
info.Data.i64 = (INT64)value;
info.ValueType = SQL_C_SBIGINT;
info.ParameterType = SQL_BIGINT;
info.ParameterValuePtr = &info.Data.i64;
info.StrLen_or_Ind = 8;
}
else
{
info.Data.i32 = (int)value;
info.ValueType = SQL_C_LONG;
info.ParameterType = SQL_INTEGER;
info.ParameterValuePtr = &info.Data.i32;
info.StrLen_or_Ind = 4;
}
return true;
}
static bool GetFloatInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
// Python floats are usually numeric values, but can also be "Infinity" or "NaN".
// https://docs.python.org/3/library/functions.html#float
// PyFloat_AsDouble() does not generate an error for Infinity/NaN, and it is not
// easy to check for those values. Typically, the database will reject them.
double value = PyFloat_AsDouble(param);
if (PyErr_Occurred())
return false;
info.Data.dbl = value;
info.ValueType = SQL_C_DOUBLE;
info.ParameterType = SQL_DOUBLE;
info.ParameterValuePtr = &info.Data.dbl;
info.ColumnSize = 15;
info.StrLen_or_Ind = sizeof(double);
return true;
}
static char* CreateDecimalString(long sign, PyObject* digits, long exp)
{
// Allocate an ASCII string containing the given decimal.
long count = (long)PyTuple_GET_SIZE(digits);
char* pch;
long len;
if (exp >= 0)
{
// (1 2 3) exp = 2 --> '12300'
len = sign + count + exp + 1; // 1: NULL
pch = (char*)PyMem_Malloc((size_t)len);
if (pch)
{
char* p = pch;
if (sign)
*p++ = '-';
for (long i = 0; i < count; i++)
*p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i)));
for (long i = 0; i < exp; i++)
*p++ = '0';
*p = 0;
}
}
else if (-exp < count)
{
// (1 2 3) exp = -2 --> 1.23 : prec = 3, scale = 2
len = sign + count + 2; // 2: decimal + NULL
pch = (char*)PyMem_Malloc((size_t)len);
if (pch)
{
char* p = pch;
if (sign)
*p++ = '-';
int i = 0;
for (; i < (count + exp); i++)
*p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i)));
*p++ = '.';
for (; i < count; i++)
*p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i)));
*p++ = 0;
}
}
else
{
// (1 2 3) exp = -5 --> 0.00123 : prec = 5, scale = 5
len = sign + -exp + 3; // 3: leading zero + decimal + NULL
pch = (char*)PyMem_Malloc((size_t)len);
if (pch)
{
char* p = pch;
if (sign)
*p++ = '-';
*p++ = '0';
*p++ = '.';
for (int i = 0; i < -(exp + count); i++)
*p++ = '0';
for (int i = 0; i < count; i++)
*p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i)));
*p++ = 0;
}
}
assert(pch == 0 || (int)(strlen(pch) + 1) == len);
return pch;
}
static bool GetUUIDInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, PyObject* uuid_type)
{
// uuid_type: This is a new reference that we are responsible for freeing.
Object tmp(uuid_type);
info.ValueType = SQL_C_GUID;
info.ParameterType = SQL_GUID;
info.ColumnSize = 16;
info.allocated = true;
info.ParameterValuePtr = PyMem_Malloc(sizeof(SQLGUID));
if (!info.ParameterValuePtr)
{
PyErr_NoMemory();
return false;
}
// Do we need to use "bytes" on a big endian machine?
Object b(PyObject_GetAttrString(param, "bytes_le"));
if (!b)
return false;
memcpy(info.ParameterValuePtr, PyBytes_AS_STRING(b.Get()), sizeof(SQLGUID));
info.StrLen_or_Ind = sizeof(SQLGUID);
return true;
}
static bool GetDecimalInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, PyObject* decimal_type)
{
// decimal_type: This is a new reference that we are responsible for freeing.
Object tmp(decimal_type);
// The NUMERIC structure never works right with SQL Server and probably a lot of other drivers. We'll bind as a
// string. Unfortunately, the Decimal class doesn't seem to have a way to force it to return a string without
// exponents, so we'll have to build it ourselves.
Object t(PyObject_CallMethod(param, "as_tuple", 0));
if (!t)
return false;
long sign = PyLong_AsLong(PyTuple_GET_ITEM(t.Get(), 0));
PyObject* digits = PyTuple_GET_ITEM(t.Get(), 1);
long exp = PyLong_AsLong(PyTuple_GET_ITEM(t.Get(), 2));
Py_ssize_t count = PyTuple_GET_SIZE(digits);
info.ValueType = SQL_C_CHAR;
info.ParameterType = SQL_NUMERIC;
if (exp >= 0)
{
// (1 2 3) exp = 2 --> '12300'
info.ColumnSize = (SQLUINTEGER)count + exp;
info.DecimalDigits = 0;
}
else if (-exp <= count)
{
// (1 2 3) exp = -2 --> 1.23 : prec = 3, scale = 2
info.ColumnSize = (SQLUINTEGER)count;
info.DecimalDigits = (SQLSMALLINT)-exp;
}
else
{
// (1 2 3) exp = -5 --> 0.00123 : prec = 5, scale = 5
info.ColumnSize = (SQLUINTEGER)(-exp);
info.DecimalDigits = (SQLSMALLINT)info.ColumnSize;
}
assert(info.ColumnSize >= (SQLULEN)info.DecimalDigits);
info.ParameterValuePtr = CreateDecimalString(sign, digits, exp);
if (!info.ParameterValuePtr)
{
PyErr_NoMemory();
return false;
}
info.allocated = true;
info.StrLen_or_Ind = (SQLINTEGER)strlen((char*)info.ParameterValuePtr);
return true;
}
static bool GetByteArrayInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, bool isTVP)
{
info.ValueType = SQL_C_BINARY;
Py_ssize_t cb = PyByteArray_Size(param);
SQLLEN maxlength = cur->cnxn->GetMaxLength(info.ValueType);
if (maxlength == 0 || cb <= maxlength || isTVP)
{
info.ParameterType = SQL_VARBINARY;
info.ParameterValuePtr = (SQLPOINTER)PyByteArray_AsString(param);
info.BufferLength = (SQLINTEGER)cb;
info.ColumnSize = isTVP?0:(SQLUINTEGER)max(cb, 1);
info.StrLen_or_Ind = (SQLINTEGER)cb;
}
else
{
info.ParameterType = SQL_LONGVARBINARY;
info.ParameterValuePtr = &info;
info.BufferLength = sizeof(ParamInfo*);
info.ColumnSize = (SQLUINTEGER)cb;
info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)cb) : SQL_DATA_AT_EXEC;
info.pObject = param;
Py_INCREF(info.pObject);
info.maxlength = maxlength;
}
return true;
}
// TVP
static bool GetTableInfo(Cursor *cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
// This is used for SQL Server's "table valued parameters" or TVPs.
int nskip = 0;
Py_ssize_t nrows = PySequence_Size(param);
if (nrows > 0)
{
PyObject *cell0 = PySequence_GetItem(param, 0);
if (cell0 == NULL)
{
return false;
}
if (PyBytes_Check(cell0) || PyUnicode_Check(cell0))
{
nskip++;
if (nrows > 1)
{
PyObject *cell1 = PySequence_GetItem(param, 1);
nskip += (PyBytes_Check(cell1) || PyUnicode_Check(cell1));
Py_XDECREF(cell1);
}
}
Py_XDECREF(cell0);
}
nrows -= nskip;
if (!nskip)
{
// Need to describe in order to fill in IPD with the TVP's type name, because user has
// not provided it