-
Notifications
You must be signed in to change notification settings - Fork 566
/
Copy pathconnection.cpp
1447 lines (1215 loc) · 44.5 KB
/
connection.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.
#include "pyodbc.h"
#include "wrapper.h"
#include "textenc.h"
#include "connection.h"
#include "cursor.h"
#include "pyodbcmodule.h"
#include "errors.h"
#include "cnxninfo.h"
static char connection_doc[] =
"Connection objects manage connections to the database.\n"
"\n"
"Each manages a single ODBC HDBC.";
static Connection* Connection_Validate(PyObject* self)
{
Connection* cnxn;
if (self == 0 || !Connection_Check(self))
{
PyErr_SetString(PyExc_TypeError, "Connection object required");
return 0;
}
cnxn = (Connection*)self;
if (cnxn->hdbc == SQL_NULL_HANDLE)
{
PyErr_SetString(ProgrammingError, "Attempt to use a closed connection.");
return 0;
}
return cnxn;
}
static char* StrDup(const char* text) {
// Like StrDup but uses PyMem_Malloc for the memory. This is only used for internal
// encodings which are known to be ASCII.
size_t cb = strlen(text) + 1;
char* pb = (char*)PyMem_Malloc(cb);
if (!pb) {
PyErr_NoMemory();
return 0;
}
memcpy(pb, text, cb);
return pb;
}
static bool Connect(PyObject* pConnectString, HDBC hdbc, long timeout, PyObject* encoding)
{
assert(PyUnicode_Check(pConnectString));
SQLRETURN ret;
if (timeout > 0)
{
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttrW(hdbc, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER)(uintptr_t)timeout, SQL_IS_UINTEGER);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
RaiseErrorFromHandle(0, "SQLSetConnectAttr(SQL_ATTR_LOGIN_TIMEOUT)", hdbc, SQL_NULL_HANDLE);
}
const char* szEncoding = 0;
Object encBytes;
if (encoding)
{
if (PyUnicode_Check(encoding))
{
szEncoding = PyUnicode_AsUTF8(encoding);
}
}
SQLWChar cstring(pConnectString, szEncoding ? szEncoding : ENCSTR_UTF16NE);
if (!cstring.isValid())
return false;
Py_BEGIN_ALLOW_THREADS
ret = SQLDriverConnectW(hdbc, 0, cstring, SQL_NTS, 0, 0, 0, SQL_DRIVER_NOPROMPT);
Py_END_ALLOW_THREADS
if (SQL_SUCCEEDED(ret))
return true;
RaiseErrorFromHandle(0, "SQLDriverConnect", hdbc, SQL_NULL_HANDLE);
return false;
}
static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char *strencoding)
{
SQLRETURN ret;
SQLPOINTER ivalue = 0;
SQLINTEGER vallen = 0;
SQLWChar sqlchar;
if (PyLong_Check(value))
{
if (_PyLong_Sign(value) >= 0)
{
ivalue = (SQLPOINTER)PyLong_AsUnsignedLong(value);
vallen = SQL_IS_UINTEGER;
} else
{
ivalue = (SQLPOINTER)PyLong_AsLong(value);
vallen = SQL_IS_INTEGER;
}
}
else if (PyByteArray_Check(value))
{
ivalue = (SQLPOINTER)PyByteArray_AsString(value);
vallen = SQL_IS_POINTER;
}
else if (PyBytes_Check(value))
{
ivalue = PyBytes_AsString(value);
vallen = SQL_IS_POINTER;
}
else if (PyUnicode_Check(value))
{
sqlchar.set(value, strencoding ? strencoding : "utf-16le");
ivalue = sqlchar.get();
vallen = SQL_NTS;
}
else if (PySequence_Check(value))
{
// To allow for possibility of setting multiple attributes more than once.
Py_ssize_t len = PySequence_Size(value);
for (Py_ssize_t i = 0; i < len; i++)
{
Object v(PySequence_GetItem(value, i));
if (!ApplyPreconnAttrs(hdbc, ikey, v.Get(), strencoding))
return false;
}
return true;
}
else
{
RaiseErrorV(0, PyExc_TypeError, "Unsupported attrs_before type: %s",
Py_TYPE(value)->tp_name);
return false;
}
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttrW(hdbc, ikey, ivalue, vallen);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(0, "SQLSetConnectAttr", hdbc, SQL_NULL_HANDLE);
Py_BEGIN_ALLOW_THREADS
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
Py_END_ALLOW_THREADS
return false;
}
return true;
}
PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeout, bool fReadOnly,
PyObject* attrs_before, PyObject* encoding)
{
//
// Allocate HDBC and connect
//
Object attrs_before_o(attrs_before);
HDBC hdbc = SQL_NULL_HANDLE;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(0, "SQLAllocHandle", SQL_NULL_HANDLE, SQL_NULL_HANDLE);
//
// Attributes that must be set before connecting.
//
if (attrs_before)
{
Py_ssize_t pos = 0;
PyObject* key = 0;
PyObject* value = 0;
Object encodingholder;
char *strencoding = (encoding != 0) ?
(PyUnicode_Check(encoding) ? PyBytes_AsString(encodingholder = PyCodec_Encode(encoding, "utf-8", "strict")) :
PyBytes_Check(encoding) ? PyBytes_AsString(encoding) : 0) : 0;
while (PyDict_Next(attrs_before, &pos, &key, &value))
{
SQLINTEGER ikey = 0;
if (PyLong_Check(key))
ikey = (int)PyLong_AsLong(key);
if (!ApplyPreconnAttrs(hdbc, ikey, value, strencoding))
{
return 0;
}
}
}
if (!Connect(pConnectString, hdbc, timeout, encoding))
{
// Connect has already set an exception.
Py_BEGIN_ALLOW_THREADS
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
Py_END_ALLOW_THREADS
return 0;
}
//
// Connected, so allocate the Connection object.
//
// Set all variables to something valid, so we don't crash in dealloc if this function fails.
#ifdef _MSC_VER
#pragma warning(disable : 4365)
#endif
Connection* cnxn = PyObject_NEW(Connection, &ConnectionType);
#ifdef _MSC_VER
#pragma warning(default : 4365)
#endif
if (cnxn == 0)
{
Py_BEGIN_ALLOW_THREADS
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
Py_END_ALLOW_THREADS
return 0;
}
cnxn->hdbc = hdbc;
cnxn->nAutoCommit = fAutoCommit ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF;
cnxn->searchescape = 0;
cnxn->maxwrite = 0;
cnxn->timeout = 0;
cnxn->map_sqltype_to_converter = 0;
cnxn->attrs_before = attrs_before_o.Detach();
// This is an inefficient default, but should work all the time. When we are offered
// single-byte text we don't actually know what the encoding is. For example, with SQL
// Server the encoding is based on the database's collation. We ask the driver / DB to
// convert to SQL_C_WCHAR and use the ODBC default of UTF-16LE.
cnxn->sqlchar_enc.optenc = OPTENC_UTF16NE;
cnxn->sqlchar_enc.name = StrDup(ENCSTR_UTF16NE);
cnxn->sqlchar_enc.ctype = SQL_C_WCHAR;
cnxn->sqlwchar_enc.optenc = OPTENC_UTF16NE;
cnxn->sqlwchar_enc.name = StrDup(ENCSTR_UTF16NE);
cnxn->sqlwchar_enc.ctype = SQL_C_WCHAR;
cnxn->metadata_enc.optenc = OPTENC_UTF16NE;
cnxn->metadata_enc.name = StrDup(ENCSTR_UTF16NE);
cnxn->metadata_enc.ctype = SQL_C_WCHAR;
// Note: I attempted to use UTF-8 here too since it can hold any type, but SQL Server fails
// with a data truncation error if we send something encoded in 2 bytes to a column with 1
// character. I don't know if this is a bug in SQL Server's driver or if I'm missing
// something, so we'll stay with the default ODBC conversions.
cnxn->unicode_enc.optenc = OPTENC_UTF16NE;
cnxn->unicode_enc.name = StrDup(ENCSTR_UTF16NE);
cnxn->unicode_enc.ctype = SQL_C_WCHAR;
if (!cnxn->sqlchar_enc.name || !cnxn->sqlwchar_enc.name || !cnxn->metadata_enc.name || !cnxn->unicode_enc.name)
{
PyErr_NoMemory();
Py_DECREF(cnxn);
return 0;
}
//
// Initialize autocommit mode.
//
// The DB API says we have to default to manual-commit, but ODBC defaults to auto-commit. We also provide a
// keyword parameter that allows the user to override the DB API and force us to start in auto-commit (in which
// case we don't have to do anything).
if (fAutoCommit == false)
{
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttr(cnxn->hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)cnxn->nAutoCommit, SQL_IS_UINTEGER);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT)", cnxn->hdbc, SQL_NULL_HANDLE);
Py_DECREF(cnxn);
return 0;
}
}
if (fReadOnly)
{
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttr(cnxn->hdbc, SQL_ATTR_ACCESS_MODE, (SQLPOINTER)SQL_MODE_READ_ONLY, 0);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr(SQL_ATTR_ACCESS_MODE)", cnxn->hdbc, SQL_NULL_HANDLE);
Py_DECREF(cnxn);
return 0;
}
}
//
// Gather connection-level information we'll need later.
//
Object info(GetConnectionInfo(pConnectString, cnxn));
if (!info.IsValid())
{
Py_DECREF(cnxn);
return 0;
}
CnxnInfo* p = (CnxnInfo*)info.Get();
cnxn->odbc_major = p->odbc_major;
cnxn->odbc_minor = p->odbc_minor;
cnxn->supports_describeparam = p->supports_describeparam;
cnxn->datetime_precision = p->datetime_precision;
cnxn->need_long_data_len = p->need_long_data_len;
cnxn->varchar_maxlength = p->varchar_maxlength;
cnxn->wvarchar_maxlength = p->wvarchar_maxlength;
cnxn->binary_maxlength = p->binary_maxlength;
return reinterpret_cast<PyObject*>(cnxn);
}
static char set_attr_doc[] =
"set_attr(attr_id, value) -> None\n\n"
"Calls SQLSetConnectAttr with the given values.\n\n"
"attr_id\n"
" The attribute id (integer) to set. These are ODBC or driver constants.\n\n"
"value\n"
" An integer value.\n\n"
"At this time, only integer values are supported and are always passed as SQLUINTEGER.";
static PyObject* Connection_set_attr(PyObject* self, PyObject* args)
{
int id;
int value;
if (!PyArg_ParseTuple(args, "ii", &id, &value))
return 0;
Connection* cnxn = (Connection*)self;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttr(cnxn->hdbc, id, (SQLPOINTER)(intptr_t)value, SQL_IS_INTEGER);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr", cnxn->hdbc, SQL_NULL_HANDLE);
Py_RETURN_NONE;
}
static char conv_clear_doc[] =
"clear_output_converters() --> None\n\n"
"Remove all output converter functions.";
static PyObject* Connection_conv_clear(PyObject* self, PyObject* args)
{
UNUSED(args);
Connection* cnxn = (Connection*)self;
Py_XDECREF(cnxn->map_sqltype_to_converter);
cnxn->map_sqltype_to_converter = 0;
Py_RETURN_NONE;
}
static int Connection_clear(PyObject* self)
{
// Internal method for closing the connection. (Not called close so it isn't confused with the external close
// method.)
Connection* cnxn = (Connection*)self;
if (cnxn->hdbc != SQL_NULL_HANDLE)
{
TRACE("cnxn.clear cnxn=%p hdbc=%d\n", cnxn, cnxn->hdbc);
HDBC hdbc = cnxn->hdbc;
cnxn->hdbc = SQL_NULL_HANDLE;
Py_BEGIN_ALLOW_THREADS
if (cnxn->nAutoCommit == SQL_AUTOCOMMIT_OFF)
SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_ROLLBACK);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
Py_END_ALLOW_THREADS
}
Py_XDECREF(cnxn->searchescape);
cnxn->searchescape = 0;
PyMem_Free((void*)cnxn->sqlchar_enc.name);
cnxn->sqlchar_enc.name = 0;
PyMem_Free((void*)cnxn->sqlwchar_enc.name);
cnxn->sqlwchar_enc.name = 0;
PyMem_Free((void*)cnxn->metadata_enc.name);
cnxn->metadata_enc.name = 0;
PyMem_Free((void*)cnxn->unicode_enc.name);
cnxn->unicode_enc.name = 0;
Py_XDECREF(cnxn->attrs_before);
cnxn->attrs_before = 0;
Py_XDECREF(cnxn->map_sqltype_to_converter);
cnxn->map_sqltype_to_converter = 0;
return 0;
}
static void Connection_dealloc(PyObject* self)
{
Connection_clear(self);
PyObject_Del(self);
}
static char close_doc[] =
"Close the connection now (rather than whenever __del__ is called).\n"
"\n"
"The connection will be unusable from this point forward and a ProgrammingError\n"
"will be raised if any operation is attempted with the connection. The same\n"
"applies to all cursor objects trying to use the connection.\n"
"\n"
"Note that closing a connection without committing the changes first will cause\n"
"an implicit rollback to be performed.";
static PyObject* Connection_close(PyObject* self, PyObject* args)
{
UNUSED(args);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
Connection_clear(self);
Py_RETURN_NONE;
}
static PyObject* Connection_cursor(PyObject* self, PyObject* args)
{
UNUSED(args);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
return (PyObject*)Cursor_New(cnxn);
}
static PyObject* Connection_execute(PyObject* self, PyObject* args)
{
PyObject* result = 0;
Cursor* cursor;
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
cursor = Cursor_New(cnxn);
if (!cursor)
return 0;
result = Cursor_execute((PyObject*)cursor, args);
Py_DECREF((PyObject*)cursor);
return result;
}
enum
{
GI_YESNO,
GI_STRING,
GI_UINTEGER,
GI_USMALLINT,
};
struct GetInfoType
{
SQLUSMALLINT infotype;
int datatype; // GI_XXX
};
static const GetInfoType aInfoTypes[] = {
// SQL_CONVERT_X
{ SQL_CONVERT_FUNCTIONS, GI_UINTEGER },
{ SQL_CONVERT_BIGINT, GI_UINTEGER },
{ SQL_CONVERT_BINARY, GI_UINTEGER },
{ SQL_CONVERT_BIT, GI_UINTEGER },
{ SQL_CONVERT_CHAR, GI_UINTEGER },
{ SQL_CONVERT_DATE, GI_UINTEGER },
{ SQL_CONVERT_DECIMAL, GI_UINTEGER },
{ SQL_CONVERT_DOUBLE, GI_UINTEGER },
{ SQL_CONVERT_FLOAT, GI_UINTEGER },
{ SQL_CONVERT_INTEGER, GI_UINTEGER },
{ SQL_CONVERT_LONGVARCHAR, GI_UINTEGER },
{ SQL_CONVERT_NUMERIC, GI_UINTEGER },
{ SQL_CONVERT_REAL, GI_UINTEGER },
{ SQL_CONVERT_SMALLINT, GI_UINTEGER },
{ SQL_CONVERT_TIME, GI_UINTEGER },
{ SQL_CONVERT_TIMESTAMP, GI_UINTEGER },
{ SQL_CONVERT_TINYINT, GI_UINTEGER },
{ SQL_CONVERT_VARBINARY, GI_UINTEGER },
{ SQL_CONVERT_VARCHAR, GI_UINTEGER },
{ SQL_CONVERT_LONGVARBINARY, GI_UINTEGER },
{ SQL_CONVERT_WCHAR, GI_UINTEGER },
{ SQL_CONVERT_INTERVAL_DAY_TIME, GI_UINTEGER },
{ SQL_CONVERT_INTERVAL_YEAR_MONTH, GI_UINTEGER },
{ SQL_CONVERT_WLONGVARCHAR, GI_UINTEGER },
{ SQL_CONVERT_WVARCHAR, GI_UINTEGER },
{ SQL_CONVERT_GUID, GI_UINTEGER },
{ SQL_ACCESSIBLE_PROCEDURES, GI_YESNO },
{ SQL_ACCESSIBLE_TABLES, GI_YESNO },
{ SQL_ACTIVE_ENVIRONMENTS, GI_USMALLINT },
{ SQL_AGGREGATE_FUNCTIONS, GI_UINTEGER },
{ SQL_ALTER_DOMAIN, GI_UINTEGER },
{ SQL_ALTER_TABLE, GI_UINTEGER },
{ SQL_ASYNC_MODE, GI_UINTEGER },
{ SQL_BATCH_ROW_COUNT, GI_UINTEGER },
{ SQL_BATCH_SUPPORT, GI_UINTEGER },
{ SQL_BOOKMARK_PERSISTENCE, GI_UINTEGER },
{ SQL_CATALOG_LOCATION, GI_USMALLINT },
{ SQL_CATALOG_NAME, GI_YESNO },
{ SQL_CATALOG_NAME_SEPARATOR, GI_STRING },
{ SQL_CATALOG_TERM, GI_STRING },
{ SQL_CATALOG_USAGE, GI_UINTEGER },
{ SQL_COLLATION_SEQ, GI_STRING },
{ SQL_COLUMN_ALIAS, GI_YESNO },
{ SQL_CONCAT_NULL_BEHAVIOR, GI_USMALLINT },
{ SQL_CORRELATION_NAME, GI_USMALLINT },
{ SQL_CREATE_ASSERTION, GI_UINTEGER },
{ SQL_CREATE_CHARACTER_SET, GI_UINTEGER },
{ SQL_CREATE_COLLATION, GI_UINTEGER },
{ SQL_CREATE_DOMAIN, GI_UINTEGER },
{ SQL_CREATE_SCHEMA, GI_UINTEGER },
{ SQL_CREATE_TABLE, GI_UINTEGER },
{ SQL_CREATE_TRANSLATION, GI_UINTEGER },
{ SQL_CREATE_VIEW, GI_UINTEGER },
{ SQL_CURSOR_COMMIT_BEHAVIOR, GI_USMALLINT },
{ SQL_CURSOR_ROLLBACK_BEHAVIOR, GI_USMALLINT },
{ SQL_DATABASE_NAME, GI_STRING },
{ SQL_DATA_SOURCE_NAME, GI_STRING },
{ SQL_DATA_SOURCE_READ_ONLY, GI_YESNO },
{ SQL_DATETIME_LITERALS, GI_UINTEGER },
{ SQL_DBMS_NAME, GI_STRING },
{ SQL_DBMS_VER, GI_STRING },
{ SQL_DDL_INDEX, GI_UINTEGER },
{ SQL_DEFAULT_TXN_ISOLATION, GI_UINTEGER },
{ SQL_DESCRIBE_PARAMETER, GI_YESNO },
{ SQL_DM_VER, GI_STRING },
{ SQL_DRIVER_NAME, GI_STRING },
{ SQL_DRIVER_ODBC_VER, GI_STRING },
{ SQL_DRIVER_VER, GI_STRING },
{ SQL_DROP_ASSERTION, GI_UINTEGER },
{ SQL_DROP_CHARACTER_SET, GI_UINTEGER },
{ SQL_DROP_COLLATION, GI_UINTEGER },
{ SQL_DROP_DOMAIN, GI_UINTEGER },
{ SQL_DROP_SCHEMA, GI_UINTEGER },
{ SQL_DROP_TABLE, GI_UINTEGER },
{ SQL_DROP_TRANSLATION, GI_UINTEGER },
{ SQL_DROP_VIEW, GI_UINTEGER },
{ SQL_DYNAMIC_CURSOR_ATTRIBUTES1, GI_UINTEGER },
{ SQL_DYNAMIC_CURSOR_ATTRIBUTES2, GI_UINTEGER },
{ SQL_EXPRESSIONS_IN_ORDERBY, GI_YESNO },
{ SQL_FILE_USAGE, GI_USMALLINT },
{ SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1, GI_UINTEGER },
{ SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2, GI_UINTEGER },
{ SQL_GETDATA_EXTENSIONS, GI_UINTEGER },
{ SQL_GROUP_BY, GI_USMALLINT },
{ SQL_IDENTIFIER_CASE, GI_USMALLINT },
{ SQL_IDENTIFIER_QUOTE_CHAR, GI_STRING },
{ SQL_INDEX_KEYWORDS, GI_UINTEGER },
{ SQL_INFO_SCHEMA_VIEWS, GI_UINTEGER },
{ SQL_INSERT_STATEMENT, GI_UINTEGER },
{ SQL_INTEGRITY, GI_YESNO },
{ SQL_KEYSET_CURSOR_ATTRIBUTES1, GI_UINTEGER },
{ SQL_KEYSET_CURSOR_ATTRIBUTES2, GI_UINTEGER },
{ SQL_KEYWORDS, GI_STRING },
{ SQL_LIKE_ESCAPE_CLAUSE, GI_YESNO },
{ SQL_MAX_ASYNC_CONCURRENT_STATEMENTS, GI_UINTEGER },
{ SQL_MAX_BINARY_LITERAL_LEN, GI_UINTEGER },
{ SQL_MAX_CATALOG_NAME_LEN, GI_USMALLINT },
{ SQL_MAX_CHAR_LITERAL_LEN, GI_UINTEGER },
{ SQL_MAX_COLUMNS_IN_GROUP_BY, GI_USMALLINT },
{ SQL_MAX_COLUMNS_IN_INDEX, GI_USMALLINT },
{ SQL_MAX_COLUMNS_IN_ORDER_BY, GI_USMALLINT },
{ SQL_MAX_COLUMNS_IN_SELECT, GI_USMALLINT },
{ SQL_MAX_COLUMNS_IN_TABLE, GI_USMALLINT },
{ SQL_MAX_COLUMN_NAME_LEN, GI_USMALLINT },
{ SQL_MAX_CONCURRENT_ACTIVITIES, GI_USMALLINT },
{ SQL_MAX_CURSOR_NAME_LEN, GI_USMALLINT },
{ SQL_MAX_DRIVER_CONNECTIONS, GI_USMALLINT },
{ SQL_MAX_IDENTIFIER_LEN, GI_USMALLINT },
{ SQL_MAX_INDEX_SIZE, GI_UINTEGER },
{ SQL_MAX_PROCEDURE_NAME_LEN, GI_USMALLINT },
{ SQL_MAX_ROW_SIZE, GI_UINTEGER },
{ SQL_MAX_ROW_SIZE_INCLUDES_LONG, GI_YESNO },
{ SQL_MAX_SCHEMA_NAME_LEN, GI_USMALLINT },
{ SQL_MAX_STATEMENT_LEN, GI_UINTEGER },
{ SQL_MAX_TABLES_IN_SELECT, GI_USMALLINT },
{ SQL_MAX_TABLE_NAME_LEN, GI_USMALLINT },
{ SQL_MAX_USER_NAME_LEN, GI_USMALLINT },
{ SQL_MULTIPLE_ACTIVE_TXN, GI_YESNO },
{ SQL_MULT_RESULT_SETS, GI_YESNO },
{ SQL_NEED_LONG_DATA_LEN, GI_YESNO },
{ SQL_NON_NULLABLE_COLUMNS, GI_USMALLINT },
{ SQL_NULL_COLLATION, GI_USMALLINT },
{ SQL_NUMERIC_FUNCTIONS, GI_UINTEGER },
{ SQL_ODBC_INTERFACE_CONFORMANCE, GI_UINTEGER },
{ SQL_ODBC_VER, GI_STRING },
{ SQL_OJ_CAPABILITIES, GI_UINTEGER },
{ SQL_ORDER_BY_COLUMNS_IN_SELECT, GI_YESNO },
{ SQL_PARAM_ARRAY_ROW_COUNTS, GI_UINTEGER },
{ SQL_PARAM_ARRAY_SELECTS, GI_UINTEGER },
{ SQL_PROCEDURES, GI_YESNO },
{ SQL_PROCEDURE_TERM, GI_STRING },
{ SQL_QUOTED_IDENTIFIER_CASE, GI_USMALLINT },
{ SQL_ROW_UPDATES, GI_YESNO },
{ SQL_SCHEMA_TERM, GI_STRING },
{ SQL_SCHEMA_USAGE, GI_UINTEGER },
{ SQL_SCROLL_OPTIONS, GI_UINTEGER },
{ SQL_SEARCH_PATTERN_ESCAPE, GI_STRING },
{ SQL_SERVER_NAME, GI_STRING },
{ SQL_SPECIAL_CHARACTERS, GI_STRING },
{ SQL_SQL92_DATETIME_FUNCTIONS, GI_UINTEGER },
{ SQL_SQL92_FOREIGN_KEY_DELETE_RULE, GI_UINTEGER },
{ SQL_SQL92_FOREIGN_KEY_UPDATE_RULE, GI_UINTEGER },
{ SQL_SQL92_GRANT, GI_UINTEGER },
{ SQL_SQL92_NUMERIC_VALUE_FUNCTIONS, GI_UINTEGER },
{ SQL_SQL92_PREDICATES, GI_UINTEGER },
{ SQL_SQL92_RELATIONAL_JOIN_OPERATORS, GI_UINTEGER },
{ SQL_SQL92_REVOKE, GI_UINTEGER },
{ SQL_SQL92_ROW_VALUE_CONSTRUCTOR, GI_UINTEGER },
{ SQL_SQL92_STRING_FUNCTIONS, GI_UINTEGER },
{ SQL_SQL92_VALUE_EXPRESSIONS, GI_UINTEGER },
{ SQL_SQL_CONFORMANCE, GI_UINTEGER },
{ SQL_STANDARD_CLI_CONFORMANCE, GI_UINTEGER },
{ SQL_STATIC_CURSOR_ATTRIBUTES1, GI_UINTEGER },
{ SQL_STATIC_CURSOR_ATTRIBUTES2, GI_UINTEGER },
{ SQL_STRING_FUNCTIONS, GI_UINTEGER },
{ SQL_SUBQUERIES, GI_UINTEGER },
{ SQL_SYSTEM_FUNCTIONS, GI_UINTEGER },
{ SQL_TABLE_TERM, GI_STRING },
{ SQL_TIMEDATE_ADD_INTERVALS, GI_UINTEGER },
{ SQL_TIMEDATE_DIFF_INTERVALS, GI_UINTEGER },
{ SQL_TIMEDATE_FUNCTIONS, GI_UINTEGER },
{ SQL_TXN_CAPABLE, GI_USMALLINT },
{ SQL_TXN_ISOLATION_OPTION, GI_UINTEGER },
{ SQL_UNION, GI_UINTEGER },
{ SQL_USER_NAME, GI_STRING },
{ SQL_XOPEN_CLI_YEAR, GI_STRING },
};
static PyObject* Connection_getinfo(PyObject* self, PyObject* args)
{
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
unsigned long infotype;
if (!PyArg_ParseTuple(args, "k", &infotype))
return 0;
unsigned int i = 0;
for (; i < _countof(aInfoTypes); i++)
{
if (aInfoTypes[i].infotype == infotype)
break;
}
if (i == _countof(aInfoTypes))
return RaiseErrorV(0, ProgrammingError, "Unsupported getinfo value: %d", infotype);
char szBuffer[0x1000];
SQLSMALLINT cch = 0;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLGetInfo(cnxn->hdbc, (SQLUSMALLINT)infotype, szBuffer, sizeof(szBuffer), &cch);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cnxn, "SQLGetInfo", cnxn->hdbc, SQL_NULL_HANDLE);
return 0;
}
PyObject* result = 0;
switch (aInfoTypes[i].datatype)
{
case GI_YESNO:
result = (szBuffer[0] == 'Y') ? Py_True : Py_False;
Py_INCREF(result);
break;
case GI_STRING:
result = PyUnicode_FromStringAndSize(szBuffer, (Py_ssize_t)cch);
break;
case GI_UINTEGER:
{
SQLUINTEGER n = *(SQLUINTEGER*)szBuffer; // Does this work on PPC or do we need a union?
result = PyLong_FromLong((long)n);
break;
}
case GI_USMALLINT:
result = PyLong_FromLong(*(SQLUSMALLINT*)szBuffer);
break;
}
return result;
}
PyObject* Connection_endtrans(Connection* cnxn, SQLSMALLINT type)
{
// If called from Cursor.commit, it is possible that `cnxn` is deleted by another thread when we release them
// below. (The cursor has had its reference incremented by the method it is calling, but nothing has incremented
// the connections count. We could, but we really only need the HDBC.)
HDBC hdbc = cnxn->hdbc;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLEndTran(SQL_HANDLE_DBC, hdbc, type);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cnxn, "SQLEndTran", hdbc, SQL_NULL_HANDLE);
return 0;
}
Py_RETURN_NONE;
}
static PyObject* Connection_commit(PyObject* self, PyObject* args)
{
UNUSED(args);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
TRACE("commit: cnxn=%p hdbc=%d\n", cnxn, cnxn->hdbc);
return Connection_endtrans(cnxn, SQL_COMMIT);
}
static PyObject* Connection_rollback(PyObject* self, PyObject* args)
{
UNUSED(args);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
TRACE("rollback: cnxn=%p hdbc=%d\n", cnxn, cnxn->hdbc);
return Connection_endtrans(cnxn, SQL_ROLLBACK);
}
static char cursor_doc[] =
"Return a new Cursor object using the connection.";
static char execute_doc[] =
"execute(sql, [params]) --> Cursor\n"
"\n"
"Create a new Cursor object, call its execute method, and return it. See\n"
"Cursor.execute for more details.\n"
"\n"
"This is a convenience method that is not part of the DB API. Since a new\n"
"Cursor is allocated by each call, this should not be used if more than one SQL\n"
"statement needs to be executed.";
static char commit_doc[] =
"Commit any pending transaction to the database.";
static char rollback_doc[] =
"Causes the the database to roll back to the start of any pending transaction.";
static char getinfo_doc[] =
"getinfo(type) --> str | int | bool\n"
"\n"
"Calls SQLGetInfo, passing `type`, and returns the result formatted as a Python object.";
PyObject* Connection_getautocommit(PyObject* self, void* closure)
{
UNUSED(closure);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
PyObject* result = (cnxn->nAutoCommit == SQL_AUTOCOMMIT_ON) ? Py_True : Py_False;
Py_INCREF(result);
return result;
}
static int Connection_setautocommit(PyObject* self, PyObject* value, void* closure)
{
UNUSED(closure);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return -1;
if (value == 0)
{
PyErr_SetString(PyExc_TypeError, "Cannot delete the autocommit attribute.");
return -1;
}
uintptr_t nAutoCommit = PyObject_IsTrue(value) ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttr(cnxn->hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)nAutoCommit, SQL_IS_UINTEGER);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr", cnxn->hdbc, SQL_NULL_HANDLE);
return -1;
}
cnxn->nAutoCommit = nAutoCommit;
return 0;
}
static PyObject* Connection_getclosed(PyObject* self, void* closure)
{
UNUSED(closure);
Connection* cnxn;
if (self == 0 || !Connection_Check(self))
{
PyErr_SetString(PyExc_TypeError, "Connection object required");
return 0;
}
cnxn = (Connection*)self;
if (cnxn->hdbc == SQL_NULL_HANDLE)
{
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject* Connection_getsearchescape(PyObject* self, void* closure)
{
UNUSED(closure);
Connection* cnxn = (Connection*)self;
if (!cnxn->searchescape)
{
char sz[8] = { 0 };
SQLSMALLINT cch = 0;
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLGetInfo(cnxn->hdbc, SQL_SEARCH_PATTERN_ESCAPE, &sz, _countof(sz), &cch);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
return RaiseErrorFromHandle(cnxn, "SQLGetInfo", cnxn->hdbc, SQL_NULL_HANDLE);
cnxn->searchescape = PyUnicode_FromStringAndSize(sz, (Py_ssize_t)cch);
}
Py_INCREF(cnxn->searchescape);
return cnxn->searchescape;
}
static PyObject* Connection_getmaxwrite(PyObject* self, void* closure)
{
UNUSED(closure);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
return PyLong_FromSsize_t(cnxn->maxwrite);
}
static int Connection_setmaxwrite(PyObject* self, PyObject* value, void* closure)
{
UNUSED(closure);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return -1;
if (value == 0)
{
PyErr_SetString(PyExc_TypeError, "Cannot delete the maxwrite attribute.");
return -1;
}
long maxwrite = PyLong_AsLong(value);
if (PyErr_Occurred())
return -1;
Py_ssize_t minval = 255;
if (maxwrite != 0 && maxwrite < minval)
{
PyErr_Format(PyExc_ValueError, "Cannot set maxwrite less than %d unless setting to 0.", (int)minval);
return -1;
}
cnxn->maxwrite = maxwrite;
return 0;
}
static PyObject* Connection_gettimeout(PyObject* self, void* closure)
{
UNUSED(closure);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return 0;
return PyLong_FromLong(cnxn->timeout);
}
static int Connection_settimeout(PyObject* self, PyObject* value, void* closure)
{
UNUSED(closure);
Connection* cnxn = Connection_Validate(self);
if (!cnxn)
return -1;
if (value == 0)
{
PyErr_SetString(PyExc_TypeError, "Cannot delete the timeout attribute.");
return -1;
}
long timeout = PyLong_AsLong(value);
if (timeout == -1 && PyErr_Occurred())
return -1;
if (timeout < 0)
{
PyErr_SetString(PyExc_ValueError, "Cannot set a negative timeout.");
return -1;
}
SQLRETURN ret;
Py_BEGIN_ALLOW_THREADS
ret = SQLSetConnectAttr(cnxn->hdbc, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER)(uintptr_t)timeout, SQL_IS_UINTEGER);
Py_END_ALLOW_THREADS
if (!SQL_SUCCEEDED(ret))
{
RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr", cnxn->hdbc, SQL_NULL_HANDLE);
return -1;
}
cnxn->timeout = timeout;
return 0;
}
static bool _remove_converter(PyObject* self, SQLSMALLINT sqltype)
{
Connection* cnxn = (Connection*)self;
if (!cnxn->map_sqltype_to_converter)
{
// There are no converters, so nothing to remove.