-
Notifications
You must be signed in to change notification settings - Fork 566
/
Copy pathcursor.cpp
2548 lines (2078 loc) · 82.7 KB
/
cursor.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
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Note: This project has gone from C++ (when it was ported from pypgdb) to C, back to C++ (where it will stay). If
// you are making modifications, feel free to move variable declarations from the top of functions to where they are
// actually used.
#include "pyodbc.h"
#include "wrapper.h"
#include "textenc.h"
#include "cursor.h"
#include "pyodbcmodule.h"
#include "connection.h"
#include "row.h"
#include "params.h"
#include "errors.h"
#include "getdata.h"
#include "dbspecific.h"
#include <datetime.h>
enum
{
CURSOR_REQUIRE_CNXN = 0x00000001,
CURSOR_REQUIRE_OPEN = 0x00000003, // includes _CNXN
CURSOR_REQUIRE_RESULTS = 0x00000007, // includes _OPEN
CURSOR_RAISE_ERROR = 0x00000010,
};
inline bool StatementIsValid(Cursor* cursor)
{
return cursor->cnxn != 0 && ((Connection*)cursor->cnxn)->hdbc != SQL_NULL_HANDLE && cursor->hstmt != SQL_NULL_HANDLE;
}
extern PyTypeObject CursorType;
inline bool Cursor_Check(PyObject* o)
{
return o != 0 && Py_TYPE(o) == &CursorType;
}
static Cursor* Cursor_Validate(PyObject* obj, DWORD flags)
{
// Validates that a PyObject is a Cursor (like Cursor_Check) and optionally some other requirements controlled by
// `flags`. If valid and all requirements (from the flags) are met, the cursor is returned, cast to Cursor*.
// Otherwise zero is returned.
//
// Designed to be used at the top of methods to convert the PyObject pointer and perform necessary checks.
//
// Valid flags are from the CURSOR_ enum above. Note that unless CURSOR_RAISE_ERROR is supplied, an exception
// will not be set. (When deallocating, we really don't want an exception.)
Connection* cnxn = 0;
Cursor* cursor = 0;
if (!Cursor_Check(obj))
{
if (flags & CURSOR_RAISE_ERROR)
PyErr_SetString(ProgrammingError, "Invalid cursor object.");
return 0;
}
cursor = (Cursor*)obj;
cnxn = (Connection*)cursor->cnxn;
if (cnxn == 0)
{
if (flags & CURSOR_RAISE_ERROR)
PyErr_SetString(ProgrammingError, "Attempt to use a closed cursor.");
return 0;
}
if (IsSet(flags, CURSOR_REQUIRE_OPEN))
{
if (cursor->hstmt == SQL_NULL_HANDLE)
{
if (flags & CURSOR_RAISE_ERROR)
PyErr_SetString(ProgrammingError, "Attempt to use a closed cursor.");
return 0;
}
if (cnxn->hdbc == SQL_NULL_HANDLE)
{
if (flags & CURSOR_RAISE_ERROR)
PyErr_SetString(ProgrammingError, "The cursor's connection has been closed.");
return 0;
}
}
if (IsSet(flags, CURSOR_REQUIRE_RESULTS) && cursor->colinfos == 0)
{
if (flags & CURSOR_RAISE_ERROR)
PyErr_SetString(ProgrammingError, "No results. Previous SQL was not a query.");
return 0;
}
return cursor;
}
inline bool IsNumericType(SQLSMALLINT sqltype)
{
switch (sqltype)
{
case SQL_DECIMAL:
case SQL_NUMERIC:
case SQL_REAL:
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_SMALLINT:
case SQL_INTEGER:
case SQL_TINYINT:
case SQL_BIGINT:
return true;
}
return false;
}
static bool create_name_map(Cursor* cur, SQLSMALLINT field_count, bool lower)
{
// Called after an execute to construct the map shared by rows.
bool success = false;
PyObject *desc = 0, *colmap = 0, *colinfo = 0, *type = 0, *index = 0, *nullable_obj=0;
SQLSMALLINT nameLen = 300;
uint16_t *szName = NULL;
SQLRETURN ret;
assert(cur->hstmt != SQL_NULL_HANDLE && cur->colinfos != 0);
// These are the values we expect after free_results. If this function fails, we do not modify any members, so
// they should be set to something Cursor_close can deal with.
assert(cur->description == Py_None);
assert(cur->map_name_to_index == 0);
if (cur->cnxn->hdbc == SQL_NULL_HANDLE)
{
RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
return false;
}
desc = PyTuple_New((Py_ssize_t)field_count);
colmap = PyDict_New();
szName = (uint16_t*) PyMem_Malloc((nameLen + 1) * sizeof(uint16_t));
if (!desc || !colmap || !szName)
goto done;
for (int i = 0; i < field_count; i++)
{
SQLSMALLINT cchName;
SQLSMALLINT nDataType;
SQLULEN nColSize; // precision
SQLSMALLINT cDecimalDigits; // scale
SQLSMALLINT nullable;
retry:
Py_BEGIN_ALLOW_THREADS
ret = SQLDescribeColW(cur->hstmt, (SQLUSMALLINT)(i + 1), (SQLWCHAR*)szName, nameLen, &cchName, &nDataType, &nColSize, &cDecimalDigits, &nullable);
Py_END_ALLOW_THREADS
if (cur->cnxn->hdbc == SQL_NULL_HANDLE)
{
// The connection was closed by another thread in the ALLOW_THREADS block above.
RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
goto done;
}
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cur->cnxn, "SQLDescribeCol", cur->cnxn->hdbc, cur->hstmt);
goto done;
}
// If needed, allocate a bigger column name message buffer and retry.
if (cchName > nameLen - 1) {
nameLen = cchName + 1;
if (!PyMem_Realloc((BYTE**) &szName, (nameLen + 1) * sizeof(uint16_t))) {
PyErr_NoMemory();
goto done;
}
goto retry;
}
const TextEnc& enc = cur->cnxn->metadata_enc;
// HACK: I don't know the exact issue, but iODBC + Teradata results in either UCS4 data
// or 4-byte SQLWCHAR. I'm going to use UTF-32 as an indication that's what we have.
Py_ssize_t cbName = cchName;
switch (enc.optenc)
{
case OPTENC_UTF32:
case OPTENC_UTF32LE:
case OPTENC_UTF32BE:
cbName *= 4;
break;
default:
if (enc.ctype == SQL_C_WCHAR)
cbName *= 2;
break;
}
TRACE("Col %d: type=%s (%d) colsize=%d\n", (i+1), SqlTypeName(nDataType), (int)nDataType, (int)nColSize);
Object name(TextBufferToObject(enc, (byte*)szName, cbName));
if (!name)
goto done;
if (lower)
{
PyObject* l = PyObject_CallMethod(name, "lower", 0);
if (!l)
goto done;
name.Attach(l);
}
type = PythonTypeFromSqlType(cur, nDataType);
if (!type)
goto done;
switch (nullable)
{
case SQL_NO_NULLS:
nullable_obj = Py_False;
break;
case SQL_NULLABLE:
nullable_obj = Py_True;
break;
case SQL_NULLABLE_UNKNOWN:
default:
nullable_obj = Py_None;
break;
}
// The Oracle ODBC driver has a bug (I call it) that it returns a data size of 0 when a numeric value is
// retrieved from a UNION: http://support.microsoft.com/?scid=kb%3Ben-us%3B236786&x=13&y=6
//
// Unfortunately, I don't have a test system for this yet, so I'm *trying* something. (Not a good sign.) If
// the size is zero and it appears to be a numeric type, we'll try to come up with our own length using any
// other data we can get.
if (nColSize == 0 && IsNumericType(nDataType))
{
// I'm not sure how
if (cDecimalDigits != 0)
{
nColSize = (SQLUINTEGER)(cDecimalDigits + 3);
}
else
{
// I'm not sure if this is a good idea, but ...
nColSize = 42;
}
}
colinfo = Py_BuildValue("(OOOiiiO)",
name.Get(),
type, // type_code
Py_None, // display size
(int)nColSize, // internal_size
(int)nColSize, // precision
(int)cDecimalDigits, // scale
nullable_obj); // null_ok
if (!colinfo)
goto done;
nullable_obj = 0;
index = PyLong_FromLong(i);
if (!index)
goto done;
PyDict_SetItem(colmap, name.Get(), index);
Py_DECREF(index); // SetItemString increments
index = 0;
PyTuple_SET_ITEM(desc, i, colinfo);
colinfo = 0; // reference stolen by SET_ITEM
}
Py_XDECREF(cur->description);
cur->description = desc;
desc = 0;
cur->map_name_to_index = colmap;
colmap = 0;
success = true;
done:
Py_XDECREF(nullable_obj);
Py_XDECREF(desc);
Py_XDECREF(colmap);
Py_XDECREF(index);
Py_XDECREF(colinfo);
PyMem_Free(szName);
return success;
}
enum free_results_flags
{
FREE_STATEMENT = 0x01,
KEEP_STATEMENT = 0x02,
FREE_PREPARED = 0x04,
KEEP_PREPARED = 0x08,
KEEP_MESSAGES = 0x10,
STATEMENT_MASK = 0x03,
PREPARED_MASK = 0x0C
};
static bool free_results(Cursor* self, int flags)
{
// Internal function called any time we need to free the memory associated with query results. It is safe to call
// this even when a query has not been executed.
// If we ran out of memory, it is possible that we have a cursor but colinfos is zero. However, we should be
// deleting this object, so the cursor will be freed when the HSTMT is destroyed. */
assert((flags & STATEMENT_MASK) != 0);
assert((flags & PREPARED_MASK) != 0);
if ((flags & PREPARED_MASK) == FREE_PREPARED)
{
Py_XDECREF(self->pPreparedSQL);
self->pPreparedSQL = 0;
}
if (self->colinfos)
{
PyMem_Free(self->colinfos);
self->colinfos = 0;
}
if (StatementIsValid(self))
{
if ((flags & STATEMENT_MASK) == FREE_STATEMENT)
{
Py_BEGIN_ALLOW_THREADS
SQLFreeStmt(self->hstmt, SQL_CLOSE);
Py_END_ALLOW_THREADS;
}
else
{
Py_BEGIN_ALLOW_THREADS
SQLFreeStmt(self->hstmt, SQL_UNBIND);
SQLFreeStmt(self->hstmt, SQL_RESET_PARAMS);
Py_END_ALLOW_THREADS;
}
if (self->cnxn->hdbc == SQL_NULL_HANDLE)
{
// The connection was closed by another thread in the ALLOW_THREADS block above.
RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
return false;
}
}
if (self->description != Py_None)
{
Py_DECREF(self->description);
self->description = Py_None;
Py_INCREF(Py_None);
}
if (self->map_name_to_index)
{
Py_DECREF(self->map_name_to_index);
self->map_name_to_index = 0;
}
if ((flags & KEEP_MESSAGES) == 0)
{
Py_XDECREF(self->messages);
self->messages = PyList_New(0);
}
self->rowcount = -1;
return true;
}
static void closeimpl(Cursor* cur)
{
// An internal function for the shared 'closing' code used by Cursor_close and Cursor_dealloc.
//
// This method releases the GIL lock while closing, so verify the HDBC still exists if you use it.
free_results(cur, FREE_STATEMENT | FREE_PREPARED);
FreeParameterData(cur);
FreeParameterInfo(cur);
if (StatementIsValid(cur))
{
HSTMT hstmt = cur->hstmt;
cur->hstmt = SQL_NULL_HANDLE;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
Py_END_ALLOW_THREADS
// If there is already an exception, don't overwrite it.
if (!SQL_SUCCEEDED(ret) && !PyErr_Occurred())
RaiseErrorFromHandle(cur->cnxn, "SQLFreeHandle", cur->cnxn->hdbc, SQL_NULL_HANDLE);
}
Py_XDECREF(cur->pPreparedSQL);
Py_XDECREF(cur->description);
Py_XDECREF(cur->map_name_to_index);
Py_XDECREF(cur->cnxn);
Py_XDECREF(cur->messages);
cur->pPreparedSQL = 0;
cur->description = 0;
cur->map_name_to_index = 0;
cur->cnxn = 0;
cur->messages = 0;
}
static char close_doc[] =
"Close the cursor now (rather than whenever __del__ is called). The cursor will\n"
"be unusable from this point forward; a ProgrammingError exception will be\n"
"raised if any operation is attempted with the cursor.";
static PyObject* Cursor_close(PyObject* self, PyObject* args)
{
UNUSED(args);
Cursor* cursor = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR);
if (!cursor)
return 0;
closeimpl(cursor);
if (PyErr_Occurred())
return 0;
Py_INCREF(Py_None);
return Py_None;
}
static void Cursor_dealloc(Cursor* cursor)
{
if (Cursor_Validate((PyObject*)cursor, CURSOR_REQUIRE_CNXN))
{
closeimpl(cursor);
}
Py_XDECREF(cursor->inputsizes);
PyObject_Del(cursor);
}
bool InitColumnInfo(Cursor* cursor, SQLUSMALLINT iCol, ColumnInfo* pinfo)
{
// Initializes ColumnInfo from result set metadata.
SQLRETURN ret;
// REVIEW: This line fails on OS/X with the FileMaker driver : http://www.filemaker.com/support/updaters/xdbc_odbc_mac.html
//
// I suspect the problem is that it doesn't allow NULLs in some of the parameters, so I'm going to supply them all
// to see what happens.
SQLCHAR ColumnName[200];
SQLSMALLINT BufferLength = _countof(ColumnName);
SQLSMALLINT NameLength = 0;
SQLSMALLINT DataType = 0;
SQLULEN ColumnSize = 0;
SQLSMALLINT DecimalDigits = 0;
SQLSMALLINT Nullable = 0;
Py_BEGIN_ALLOW_THREADS
ret = SQLDescribeCol(cursor->hstmt, iCol,
ColumnName,
BufferLength,
&NameLength,
&DataType,
&ColumnSize,
&DecimalDigits,
&Nullable);
Py_END_ALLOW_THREADS
pinfo->sql_type = DataType;
pinfo->column_size = ColumnSize;
if (cursor->cnxn->hdbc == SQL_NULL_HANDLE)
{
// The connection was closed by another thread in the ALLOW_THREADS block above.
RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
return false;
}
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cursor->cnxn, "SQLDescribeCol", cursor->cnxn->hdbc, cursor->hstmt);
return false;
}
// If it is an integer type, determine if it is signed or unsigned. The buffer size is the same but we'll need to
// know when we convert to a Python integer.
switch (pinfo->sql_type)
{
case SQL_TINYINT:
case SQL_SMALLINT:
case SQL_INTEGER:
case SQL_BIGINT:
{
SQLLEN f;
Py_BEGIN_ALLOW_THREADS
ret = SQLColAttribute(cursor->hstmt, iCol, SQL_DESC_UNSIGNED, 0, 0, 0, &f);
Py_END_ALLOW_THREADS
if (cursor->cnxn->hdbc == SQL_NULL_HANDLE)
{
// The connection was closed by another thread in the ALLOW_THREADS block above.
RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
return false;
}
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cursor->cnxn, "SQLColAttribute", cursor->cnxn->hdbc, cursor->hstmt);
return false;
}
pinfo->is_unsigned = (f == SQL_TRUE);
break;
}
default:
pinfo->is_unsigned = false;
}
return true;
}
static bool PrepareResults(Cursor* cur, int cCols)
{
// Called after a SELECT has been executed to perform pre-fetch work.
//
// Allocates the ColumnInfo structures describing the returned data.
int i;
assert(cur->colinfos == 0);
cur->colinfos = (ColumnInfo*)PyMem_Malloc(sizeof(ColumnInfo) * cCols);
if (cur->colinfos == 0)
{
PyErr_NoMemory();
return false;
}
for (i = 0; i < cCols; i++)
{
if (!InitColumnInfo(cur, (SQLUSMALLINT)(i + 1), &cur->colinfos[i]))
{
PyMem_Free(cur->colinfos);
cur->colinfos = 0;
return false;
}
}
return true;
}
int GetDiagRecs(Cursor* cur)
{
// Retrieves all diagnostic records from the cursor and assigns them to the "messages" attribute.
PyObject* msg_list; // the "messages" as a Python list of diagnostic records
SQLSMALLINT iRecNumber = 1; // the index of the diagnostic records (1-based)
uint16_t cSQLState[6]; // five-character SQLSTATE code (plus terminating NULL)
SQLINTEGER iNativeError;
SQLSMALLINT iMessageLen = 1023;
uint16_t *cMessageText = (uint16_t*) PyMem_Malloc((iMessageLen + 1) * sizeof(uint16_t));
SQLSMALLINT iTextLength;
SQLRETURN ret;
char sqlstate_ascii[6] = ""; // ASCII version of the SQLState
if (!cMessageText) {
PyErr_NoMemory();
return 0;
}
msg_list = PyList_New(0);
if (!msg_list)
return 0;
for (;;)
{
cSQLState[0] = 0;
iNativeError = 0;
cMessageText[0] = 0;
iTextLength = 0;
Py_BEGIN_ALLOW_THREADS
ret = SQLGetDiagRecW(
SQL_HANDLE_STMT, cur->hstmt, iRecNumber, (SQLWCHAR*)cSQLState, &iNativeError,
(SQLWCHAR*)cMessageText, iMessageLen, &iTextLength
);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
break;
// If needed, allocate a bigger error message buffer and retry.
if (iTextLength > iMessageLen - 1) {
iMessageLen = iTextLength + 1;
if (!PyMem_Realloc((BYTE**) &cMessageText, (iMessageLen + 1) * sizeof(uint16_t))) {
PyMem_Free(cMessageText);
PyErr_NoMemory();
return 0;
}
Py_BEGIN_ALLOW_THREADS
ret = SQLGetDiagRecW(
SQL_HANDLE_STMT, cur->hstmt, iRecNumber, (SQLWCHAR*)cSQLState, &iNativeError,
(SQLWCHAR*)cMessageText, iMessageLen, &iTextLength
);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
break;
}
cSQLState[5] = 0; // Not always NULL terminated (MS Access)
CopySqlState(cSQLState, sqlstate_ascii);
PyObject* msg_class = PyUnicode_FromFormat("[%s] (%ld)", sqlstate_ascii, (long)iNativeError);
// Default to UTF-16, which may not work if the driver/manager is using some other encoding
const char *unicode_enc = cur->cnxn ? cur->cnxn->metadata_enc.name : ENCSTR_UTF16NE;
PyObject* msg_value = PyUnicode_Decode(
(char*)cMessageText, iTextLength * sizeof(uint16_t), unicode_enc, "strict"
);
if (!msg_value)
{
// If the char cannot be decoded, return something rather than nothing.
Py_XDECREF(msg_value);
msg_value = PyBytes_FromStringAndSize((char*)cMessageText, iTextLength * sizeof(uint16_t));
}
PyObject* msg_tuple = PyTuple_New(2); // the message as a Python tuple of class and value
if (msg_class && msg_value && msg_tuple)
{
PyTuple_SetItem(msg_tuple, 0, msg_class); // msg_tuple now owns the msg_class reference
PyTuple_SetItem(msg_tuple, 1, msg_value); // msg_tuple now owns the msg_value reference
PyList_Append(msg_list, msg_tuple);
Py_XDECREF(msg_tuple); // whether PyList_Append succeeds or not
}
else
{
Py_XDECREF(msg_class);
Py_XDECREF(msg_value);
Py_XDECREF(msg_tuple);
}
iRecNumber++;
}
PyMem_Free(cMessageText);
Py_XDECREF(cur->messages);
cur->messages = msg_list; // cur->messages now owns the msg_list reference
return 0;
}
static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool skip_first)
{
// Internal function to execute SQL, called by .execute and .executemany.
//
// pSql
// A PyString, PyUnicode, or derived object containing the SQL.
//
// params
// Pointer to an optional sequence of parameters, and possibly the SQL statement (see skip_first):
// (SQL, param1, param2) or (param1, param2).
//
// skip_first
// If true, the first element in `params` is ignored. (It will be the SQL statement and `params` will be the
// entire tuple passed to Cursor.execute.) Otherwise all of the params are used. (This case occurs when called
// from Cursor.executemany, in which case the sequences do not contain the SQL statement.) Ignored if params is
// zero.
if (params)
{
if (!PyTuple_Check(params) && !PyList_Check(params) && !Row_Check(params))
return RaiseErrorV(0, PyExc_TypeError, "Params must be in a list, tuple, or Row");
}
// Normalize the parameter variables.
int params_offset = skip_first ? 1 : 0;
Py_ssize_t cParams = params == 0 ? 0 : PySequence_Length(params) - params_offset;
SQLRETURN ret = 0;
free_results(cur, FREE_STATEMENT | KEEP_PREPARED);
const char* szLastFunction = "";
if (cParams > 0)
{
// There are parameters, so we'll need to prepare the SQL statement and bind the parameters. (We need to
// prepare the statement because we can't bind a NULL (None) object without knowing the target datatype. There
// is no one data type that always maps to the others (no, not even varchar)).
if (!PrepareAndBind(cur, pSql, params, skip_first))
return 0;
szLastFunction = "SQLExecute";
Py_BEGIN_ALLOW_THREADS
ret = SQLExecute(cur->hstmt);
Py_END_ALLOW_THREADS
}
else
{
// REVIEW: Why don't we always prepare? It is highly unlikely that a user would need to execute the same SQL
// repeatedly if it did not have parameters, so we are not losing performance, but it would simplify the code.
Py_XDECREF(cur->pPreparedSQL);
cur->pPreparedSQL = 0;
szLastFunction = "SQLExecDirect";
const TextEnc* penc = 0;
penc = &cur->cnxn->unicode_enc;
Object query(penc->Encode(pSql));
if (!query)
return 0;
bool isWide = (penc->ctype == SQL_C_WCHAR);
const char* pch = PyBytes_AS_STRING(query.Get());
SQLINTEGER cch = (SQLINTEGER)(PyBytes_GET_SIZE(query.Get()) / (isWide ? sizeof(uint16_t) : 1));
Py_BEGIN_ALLOW_THREADS
if (isWide)
ret = SQLExecDirectW(cur->hstmt, (SQLWCHAR*)pch, cch);
else
ret = SQLExecDirect(cur->hstmt, (SQLCHAR*)pch, cch);
Py_END_ALLOW_THREADS
}
if (cur->cnxn->hdbc == SQL_NULL_HANDLE)
{
// The connection was closed by another thread in the ALLOW_THREADS block above.
FreeParameterData(cur);
return RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
}
if (!SQL_SUCCEEDED(ret) && ret != SQL_NEED_DATA && ret != SQL_NO_DATA)
{
// We could try dropping through the while and if below, but if there is an error, we need to raise it before
// FreeParameterData calls more ODBC functions.
RaiseErrorFromHandle(cur->cnxn, "SQLExecDirectW", cur->cnxn->hdbc, cur->hstmt);
FreeParameterData(cur);
return 0;
}
if (ret == SQL_SUCCESS_WITH_INFO)
{
GetDiagRecs(cur);
}
while (ret == SQL_NEED_DATA)
{
// One or more parameters were too long to bind normally so we set the
// length to SQL_LEN_DATA_AT_EXEC. ODBC will return SQL_NEED_DATA for
// each of the parameters we did this for.
//
// For each one we set a pointer to the ParamInfo as the "parameter
// data" we can access with SQLParamData. We've stashed everything we
// need in there.
szLastFunction = "SQLParamData";
ParamInfo* pInfo;
Py_BEGIN_ALLOW_THREADS
ret = SQLParamData(cur->hstmt, (SQLPOINTER*)&pInfo);
Py_END_ALLOW_THREADS
if (ret != SQL_NEED_DATA && ret != SQL_NO_DATA && !SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, "SQLParamData", cur->cnxn->hdbc, cur->hstmt);
TRACE("SQLParamData() --> %d\n", ret);
if (ret == SQL_NEED_DATA)
{
szLastFunction = "SQLPutData";
if (pInfo->pObject && (PyBytes_Check(pInfo->pObject) || PyByteArray_Check(pInfo->pObject)
))
{
char *(*pGetPtr)(PyObject*);
Py_ssize_t (*pGetLen)(PyObject*);
if (PyByteArray_Check(pInfo->pObject))
{
pGetPtr = PyByteArray_AsString;
pGetLen = PyByteArray_Size;
}
else
{
pGetPtr = PyBytes_AsString;
pGetLen = PyBytes_Size;
}
const char* p = pGetPtr(pInfo->pObject);
SQLLEN cb = (SQLLEN)pGetLen(pInfo->pObject);
SQLLEN offset = 0;
do
{
SQLLEN remaining = pInfo->maxlength ? min(pInfo->maxlength, cb - offset) : cb;
TRACE("SQLPutData [%d] (%d) %.10s\n", offset, remaining, &p[offset]);
Py_BEGIN_ALLOW_THREADS
ret = SQLPutData(cur->hstmt, (SQLPOINTER)&p[offset], remaining);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt);
offset += remaining;
}
while (offset < cb);
}
else if (pInfo->ParameterType == SQL_SS_TABLE)
{
// TVP
// Need to convert its columns into the bound row buffers
int hasTvpRows = 0;
if (pInfo->curTvpRow < PySequence_Length(pInfo->pObject))
{
PyObject *tvpRow = PySequence_GetItem(pInfo->pObject, pInfo->curTvpRow);
Py_XDECREF(tvpRow);
for (Py_ssize_t i = 0; i < PySequence_Size(tvpRow); i++)
{
struct ParamInfo newParam;
struct ParamInfo *prevParam = pInfo->nested + i;
PyObject *cell = PySequence_GetItem(tvpRow, i);
Py_XDECREF(cell);
memset(&newParam, 0, sizeof(newParam));
if (!GetParameterInfo(cur, i, cell, newParam, true))
{
// Error converting object
FreeParameterData(cur);
return NULL;
}
if((newParam.ValueType != SQL_C_DEFAULT && prevParam->ValueType != SQL_C_DEFAULT) &&
(newParam.ValueType != prevParam->ValueType ||
newParam.ParameterType != prevParam->ParameterType))
{
FreeParameterData(cur);
return RaiseErrorV(0, ProgrammingError, "Type mismatch between TVP row values");
}
if (prevParam->allocated)
PyMem_Free(prevParam->ParameterValuePtr);
Py_XDECREF(prevParam->pObject);
newParam.BufferLength = newParam.StrLen_or_Ind;
newParam.StrLen_or_Ind = SQL_DATA_AT_EXEC;
*prevParam = newParam;
if(prevParam->ParameterValuePtr == &newParam.Data)
{
prevParam->ParameterValuePtr = &prevParam->Data;
}
}
pInfo->curTvpRow++;
hasTvpRows = 1;
}
Py_BEGIN_ALLOW_THREADS
ret = SQLPutData(cur->hstmt, hasTvpRows ? (SQLPOINTER)1 : 0, hasTvpRows);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt);
}
else
{
// TVP column sent as DAE
Py_BEGIN_ALLOW_THREADS
ret = SQLPutData(cur->hstmt, pInfo->ParameterValuePtr, pInfo->BufferLength);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt);
}
ret = SQL_NEED_DATA;
}
}
FreeParameterData(cur);
if (ret == SQL_NO_DATA)
{
// Example: A delete statement that did not delete anything.
cur->rowcount = 0;
Py_INCREF(cur);
return (PyObject*)cur;
}
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, szLastFunction, cur->cnxn->hdbc, cur->hstmt);
SQLLEN cRows = -1;
Py_BEGIN_ALLOW_THREADS
ret = SQLRowCount(cur->hstmt, &cRows);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, "SQLRowCount", cur->cnxn->hdbc, cur->hstmt);
cur->rowcount = (int)cRows;
TRACE("SQLRowCount: %d\n", cRows);
SQLSMALLINT cCols = 0;
Py_BEGIN_ALLOW_THREADS
ret = SQLNumResultCols(cur->hstmt, &cCols);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
// Note: The SQL Server driver sometimes returns HY007 here if multiple statements (separated by ;) were
// submitted. This is not documented, but I've seen it with multiple successful inserts.
return RaiseErrorFromHandle(cur->cnxn, "SQLNumResultCols", cur->cnxn->hdbc, cur->hstmt);
}
TRACE("SQLNumResultCols: %d\n", cCols);
if (cur->cnxn->hdbc == SQL_NULL_HANDLE)
{
// The connection was closed by another thread in the ALLOW_THREADS block above.
return RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed.");
}
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cur->cnxn, "SQLRowCount", cur->cnxn->hdbc, cur->hstmt);
if (cCols != 0)
{
// A result set was created.
if (!PrepareResults(cur, cCols))
return 0;
if (!create_name_map(cur, cCols, lowercase()))
return 0;
}
Py_INCREF(cur);
return (PyObject*)cur;
}
inline bool IsSequence(PyObject* p)
{
// Used to determine if the first parameter of execute is a collection of SQL parameters or is a SQL parameter
// itself. If the first parameter is a list, tuple, or Row object, then we consider it a collection. Anything
// else, including other sequences (e.g. bytearray), are considered SQL parameters.
return PyList_Check(p) || PyTuple_Check(p) || Row_Check(p);
}
static char execute_doc[] =
"C.execute(sql, [params]) --> Cursor\n"
"\n"
"Prepare and execute a database query or command.\n"
"\n"
"Parameters may be provided as a sequence (as specified by the DB API) or\n"
"simply passed in one after another (non-standard):\n"
"\n"
" cursor.execute(sql, (param1, param2))\n"
"\n"
" or\n"
"\n"
" cursor.execute(sql, param1, param2)\n";
PyObject* Cursor_execute(PyObject* self, PyObject* args)
{
Py_ssize_t cParams = PyTuple_Size(args) - 1;
Cursor* cursor = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR);
if (!cursor)
return 0;
if (cParams < 0)
{