forked from jiangwen365/pypyodbc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pypyodbc.py
2653 lines (2197 loc) · 99 KB
/
pypyodbc.py
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
# -*- coding: utf-8 -*-
# PyPyODBC is develped from RealPyODBC 0.1 beta released in 2004 by Michele Petrazzo. Thanks Michele.
# The MIT License (MIT)
#
# Copyright (c) 2013 Rockallite Wulf <[email protected]>
# Copyright (c) 2013 Henry Zhou <[email protected]> and PyPyODBC contributors
# Copyright (c) 2004 Michele Petrazzo
# 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, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions
# of the Software.
#
# 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.
pooling = True
apilevel = '2.0'
paramstyle = 'qmark'
threadsafety = 1
version = '1.1.5-rkl20130721-3'
lowercase=True
DEBUG = 0
# Comment out all "if DEBUG:" statements like below for production
#if DEBUG:print 'DEBUGGING'
import sys, os, datetime, ctypes, threading
from decimal import Decimal
py_ver = sys.version[:3]
py_v3 = py_ver >= '3.0'
if py_v3:
long = int
unicode = str
str_8b = bytes
buffer = memoryview
BYTE_1 = bytes('1','ascii')
use_unicode = True
else:
str_8b = str
BYTE_1 = '1'
use_unicode = False
if py_ver < '2.6':
bytearray = str
if not hasattr(ctypes, 'c_ssize_t'):
if ctypes.sizeof(ctypes.c_uint) == ctypes.sizeof(ctypes.c_void_p):
ctypes.c_ssize_t = ctypes.c_int
elif ctypes.sizeof(ctypes.c_ulong) == ctypes.sizeof(ctypes.c_void_p):
ctypes.c_ssize_t = ctypes.c_long
elif ctypes.sizeof(ctypes.c_ulonglong) == ctypes.sizeof(ctypes.c_void_p):
ctypes.c_ssize_t = ctypes.c_longlong
lock = threading.Lock()
shared_env_h = None
SQLWCHAR_SIZE = ctypes.sizeof(ctypes.c_wchar)
#determin the size of Py_UNICODE
#sys.maxunicode > 65536 and 'UCS4' or 'UCS2'
UNICODE_SIZE = sys.maxunicode > 65536 and 4 or 2
# Define ODBC constants. They are widly used in ODBC documents and programs
# They are defined in cpp header files: sql.h sqlext.h sqltypes.h sqlucode.h
# and you can get these files from the mingw32-runtime_3.13-1_all.deb package
SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC2, SQL_OV_ODBC3 = 200, 2, 3
SQL_DRIVER_NOPROMPT = 0
SQL_ATTR_CONNECTION_POOLING = 201; SQL_CP_ONE_PER_HENV = 2
SQL_FETCH_NEXT, SQL_FETCH_FIRST, SQL_FETCH_LAST = 0x01, 0x02, 0x04
SQL_NULL_HANDLE, SQL_HANDLE_ENV, SQL_HANDLE_DBC, SQL_HANDLE_STMT = 0, 1, 2, 3
SQL_SUCCESS, SQL_SUCCESS_WITH_INFO = 0, 1
SQL_NO_DATA = 100; SQL_NO_TOTAL = -4
SQL_ATTR_ACCESS_MODE = SQL_ACCESS_MODE = 101
SQL_ATTR_AUTOCOMMIT = SQL_AUTOCOMMIT = 102
SQL_MODE_DEFAULT = SQL_MODE_READ_WRITE = 0; SQL_MODE_READ_ONLY = 1
SQL_AUTOCOMMIT_OFF, SQL_AUTOCOMMIT_ON = 0, 1
SQL_IS_UINTEGER = -5
SQL_ATTR_LOGIN_TIMEOUT = 103; SQL_ATTR_CONNECTION_TIMEOUT = 113
SQL_COMMIT, SQL_ROLLBACK = 0, 1
SQL_INDEX_UNIQUE,SQL_INDEX_ALL = 0,1
SQL_QUICK,SQL_ENSURE = 0,1
SQL_FETCH_NEXT = 1
SQL_COLUMN_DISPLAY_SIZE = 6
SQL_INVALID_HANDLE = -2
SQL_NO_DATA_FOUND = 100; SQL_NULL_DATA = -1; SQL_NTS = -3
SQL_HANDLE_DESCR = 4
SQL_TABLE_NAMES = 3
SQL_PARAM_INPUT = 1; SQL_PARAM_INPUT_OUTPUT = 2
SQL_PARAM_TYPE_UNKNOWN = 0
SQL_RESULT_COL = 3
SQL_PARAM_OUTPUT = 4
SQL_RETURN_VALUE = 5
SQL_PARAM_TYPE_DEFAULT = SQL_PARAM_INPUT_OUTPUT
SQL_RESET_PARAMS = 3
SQL_UNBIND = 2
SQL_CLOSE = 0
# Below defines The constants for sqlgetinfo method, and their coresponding return types
SQL_QUALIFIER_LOCATION = 114
SQL_QUALIFIER_NAME_SEPARATOR = 41
SQL_QUALIFIER_TERM = 42
SQL_QUALIFIER_USAGE = 92
SQL_OWNER_TERM = 39
SQL_OWNER_USAGE = 91
SQL_ACCESSIBLE_PROCEDURES = 20
SQL_ACCESSIBLE_TABLES = 19
SQL_ACTIVE_ENVIRONMENTS = 116
SQL_AGGREGATE_FUNCTIONS = 169
SQL_ALTER_DOMAIN = 117
SQL_ALTER_TABLE = 86
SQL_ASYNC_MODE = 10021
SQL_BATCH_ROW_COUNT = 120
SQL_BATCH_SUPPORT = 121
SQL_BOOKMARK_PERSISTENCE = 82
SQL_CATALOG_LOCATION = SQL_QUALIFIER_LOCATION
SQL_CATALOG_NAME = 10003
SQL_CATALOG_NAME_SEPARATOR = SQL_QUALIFIER_NAME_SEPARATOR
SQL_CATALOG_TERM = SQL_QUALIFIER_TERM
SQL_CATALOG_USAGE = SQL_QUALIFIER_USAGE
SQL_COLLATION_SEQ = 10004
SQL_COLUMN_ALIAS = 87
SQL_CONCAT_NULL_BEHAVIOR = 22
SQL_CONVERT_FUNCTIONS = 48
SQL_CONVERT_VARCHAR = 70
SQL_CORRELATION_NAME = 74
SQL_CREATE_ASSERTION = 127
SQL_CREATE_CHARACTER_SET = 128
SQL_CREATE_COLLATION = 129
SQL_CREATE_DOMAIN = 130
SQL_CREATE_SCHEMA = 131
SQL_CREATE_TABLE = 132
SQL_CREATE_TRANSLATION = 133
SQL_CREATE_VIEW = 134
SQL_CURSOR_COMMIT_BEHAVIOR = 23
SQL_CURSOR_ROLLBACK_BEHAVIOR = 24
SQL_DATABASE_NAME = 16
SQL_DATA_SOURCE_NAME = 2
SQL_DATA_SOURCE_READ_ONLY = 25
SQL_DATETIME_LITERALS = 119
SQL_DBMS_NAME = 17
SQL_DBMS_VER = 18
SQL_DDL_INDEX = 170
SQL_DEFAULT_TXN_ISOLATION = 26
SQL_DESCRIBE_PARAMETER = 10002
SQL_DM_VER = 171
SQL_DRIVER_NAME = 6
SQL_DRIVER_ODBC_VER = 77
SQL_DRIVER_VER = 7
SQL_DROP_ASSERTION = 136
SQL_DROP_CHARACTER_SET = 137
SQL_DROP_COLLATION = 138
SQL_DROP_DOMAIN = 139
SQL_DROP_SCHEMA = 140
SQL_DROP_TABLE = 141
SQL_DROP_TRANSLATION = 142
SQL_DROP_VIEW = 143
SQL_DYNAMIC_CURSOR_ATTRIBUTES1 = 144
SQL_DYNAMIC_CURSOR_ATTRIBUTES2 = 145
SQL_EXPRESSIONS_IN_ORDERBY = 27
SQL_FILE_USAGE = 84
SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 = 146
SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 = 147
SQL_GETDATA_EXTENSIONS = 81
SQL_GROUP_BY = 88
SQL_IDENTIFIER_CASE = 28
SQL_IDENTIFIER_QUOTE_CHAR = 29
SQL_INDEX_KEYWORDS = 148
SQL_INFO_SCHEMA_VIEWS = 149
SQL_INSERT_STATEMENT = 172
SQL_INTEGRITY = 73
SQL_KEYSET_CURSOR_ATTRIBUTES1 = 150
SQL_KEYSET_CURSOR_ATTRIBUTES2 = 151
SQL_KEYWORDS = 89
SQL_LIKE_ESCAPE_CLAUSE = 113
SQL_MAX_ASYNC_CONCURRENT_STATEMENTS = 10022
SQL_MAX_BINARY_LITERAL_LEN = 112
SQL_MAX_CATALOG_NAME_LEN = 34
SQL_MAX_CHAR_LITERAL_LEN = 108
SQL_MAX_COLUMNS_IN_GROUP_BY = 97
SQL_MAX_COLUMNS_IN_INDEX = 98
SQL_MAX_COLUMNS_IN_ORDER_BY = 99
SQL_MAX_COLUMNS_IN_SELECT = 100
SQL_MAX_COLUMNS_IN_TABLE = 101
SQL_MAX_COLUMN_NAME_LEN = 30
SQL_MAX_CONCURRENT_ACTIVITIES = 1
SQL_MAX_CURSOR_NAME_LEN = 31
SQL_MAX_DRIVER_CONNECTIONS = 0
SQL_MAX_IDENTIFIER_LEN = 10005
SQL_MAX_INDEX_SIZE = 102
SQL_MAX_PROCEDURE_NAME_LEN = 33
SQL_MAX_ROW_SIZE = 104
SQL_MAX_ROW_SIZE_INCLUDES_LONG = 103
SQL_MAX_SCHEMA_NAME_LEN = 32
SQL_MAX_STATEMENT_LEN = 105
SQL_MAX_TABLES_IN_SELECT = 106
SQL_MAX_TABLE_NAME_LEN = 35
SQL_MAX_USER_NAME_LEN = 107
SQL_MULTIPLE_ACTIVE_TXN = 37
SQL_MULT_RESULT_SETS = 36
SQL_NEED_LONG_DATA_LEN = 111
SQL_NON_NULLABLE_COLUMNS = 75
SQL_NULL_COLLATION = 85
SQL_NUMERIC_FUNCTIONS = 49
SQL_ODBC_INTERFACE_CONFORMANCE = 152
SQL_ODBC_VER = 10
SQL_OJ_CAPABILITIES = 65003
SQL_ORDER_BY_COLUMNS_IN_SELECT = 90
SQL_PARAM_ARRAY_ROW_COUNTS = 153
SQL_PARAM_ARRAY_SELECTS = 154
SQL_PROCEDURES = 21
SQL_PROCEDURE_TERM = 40
SQL_QUOTED_IDENTIFIER_CASE = 93
SQL_ROW_UPDATES = 11
SQL_SCHEMA_TERM = SQL_OWNER_TERM
SQL_SCHEMA_USAGE = SQL_OWNER_USAGE
SQL_SCROLL_OPTIONS = 44
SQL_SEARCH_PATTERN_ESCAPE = 14
SQL_SERVER_NAME = 13
SQL_SPECIAL_CHARACTERS = 94
SQL_SQL92_DATETIME_FUNCTIONS = 155
SQL_SQL92_FOREIGN_KEY_DELETE_RULE = 156
SQL_SQL92_FOREIGN_KEY_UPDATE_RULE = 157
SQL_SQL92_GRANT = 158
SQL_SQL92_NUMERIC_VALUE_FUNCTIONS = 159
SQL_SQL92_PREDICATES = 160
SQL_SQL92_RELATIONAL_JOIN_OPERATORS = 161
SQL_SQL92_REVOKE = 162
SQL_SQL92_ROW_VALUE_CONSTRUCTOR = 163
SQL_SQL92_STRING_FUNCTIONS = 164
SQL_SQL92_VALUE_EXPRESSIONS = 165
SQL_SQL_CONFORMANCE = 118
SQL_STANDARD_CLI_CONFORMANCE = 166
SQL_STATIC_CURSOR_ATTRIBUTES1 = 167
SQL_STATIC_CURSOR_ATTRIBUTES2 = 168
SQL_STRING_FUNCTIONS = 50
SQL_SUBQUERIES = 95
SQL_SYSTEM_FUNCTIONS = 51
SQL_TABLE_TERM = 45
SQL_TIMEDATE_ADD_INTERVALS = 109
SQL_TIMEDATE_DIFF_INTERVALS = 110
SQL_TIMEDATE_FUNCTIONS = 52
SQL_TXN_CAPABLE = 46
SQL_TXN_ISOLATION_OPTION = 72
SQL_UNION = 96
SQL_USER_NAME = 47
SQL_XOPEN_CLI_YEAR = 10000
aInfoTypes = {
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_CONVERT_FUNCTIONS : 'GI_UINTEGER',SQL_CONVERT_VARCHAR : 'GI_UINTEGER',
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',
}
#Definations for types
BINARY = bytearray
Binary = bytearray
DATETIME = datetime.datetime
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
STRING = str
NUMBER = float
ROWID = int
DateFromTicks = datetime.date.fromtimestamp
TimeFromTicks = lambda x: datetime.datetime.fromtimestamp(x).time()
TimestampFromTicks = datetime.datetime.fromtimestamp
#Define exceptions
class OdbcNoLibrary(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class OdbcLibraryError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class OdbcInvalidHandle(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class OdbcGenericError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Warning(Exception):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class Error(Exception):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class InterfaceError(Error):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class DatabaseError(Error):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class InternalError(DatabaseError):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class ProgrammingError(DatabaseError):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class DataError(DatabaseError):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class IntegrityError(DatabaseError):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class NotSupportedError(Error):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
class OperationalError(DatabaseError):
def __init__(self, error_code, error_desc):
self.value = (error_code, error_desc)
self.args = (error_code, error_desc)
# Get the References of the platform's ODBC functions via ctypes
if sys.platform in ('win32','cli'):
ODBC_API = ctypes.windll.odbc32
# On Windows, the size of SQLWCHAR is hardcoded to 2-bytes.
SQLWCHAR_SIZE = ctypes.sizeof(ctypes.c_ushort)
else:
# Set load the library on linux
try:
# First try direct loading libodbc.so
ODBC_API = ctypes.cdll.LoadLibrary('libodbc.so')
except:
# If direct loading libodbc.so failed
# We try finding the libodbc.so by using find_library
from ctypes.util import find_library
library = find_library('odbc')
if library is None:
# If find_library still can not find the library
# we try finding it manually from where libodbc.so usually appears
lib_paths = ("/usr/lib/libodbc.so","/usr/lib/i386-linux-gnu/libodbc.so","/usr/lib/x86_64-linux-gnu/libodbc.so","/usr/lib/libiodbc.dylib")
lib_paths = [path for path in lib_paths if os.path.exists(path)]
if len(lib_paths) == 0 :
raise OdbcNoLibrary('ODBC Library is not found. Is LD_LIBRARY_PATH set?')
else:
library = lib_paths[0]
# Then we try loading the found libodbc.so again
try:
ODBC_API = ctypes.cdll.LoadLibrary(library)
except:
# If still fail loading, abort.
raise OdbcLibraryError('Error while loading ' + library)
# unixODBC defaults to 2-bytes SQLWCHAR, unless "-DSQL_WCHART_CONVERT" was
# added to CFLAGS, in which case it will be the size of wchar_t.
# Note that using 4-bytes SQLWCHAR will break most ODBC drivers, as driver
# development mostly targets the Windows platform.
if py_v3:
from subprocess import getstatusoutput
else:
from commands import getstatusoutput
status, output = getstatusoutput('odbc_config --cflags')
if status == 0 and 'SQL_WCHART_CONVERT' in output:
SQLWCHAR_SIZE = ctypes.sizeof(ctypes.c_wchar)
else:
SQLWCHAR_SIZE = ctypes.sizeof(ctypes.c_ushort)
create_buffer_u = ctypes.create_unicode_buffer
create_buffer = ctypes.create_string_buffer
wchar_pointer = ctypes.c_wchar_p
ucs2_buf = lambda s: s
def ucs2_dec(buffer):
i = 0
uchars = []
while True:
uchar = buffer.raw[i:i + 2].decode('utf_16')
if uchar == unicode('\x00'):
break
uchars.append(uchar)
i += 2
return ''.join(uchars)
from_buffer_u = lambda buffer: buffer.value
# This is the common case on Linux, which uses wide Python build together with
# the default unixODBC without the "-DSQL_WCHART_CONVERT" CFLAGS.
if sys.platform not in ('win32','cli'):
if UNICODE_SIZE > SQLWCHAR_SIZE:
# We can only use unicode buffer if the size of wchar_t (UNICODE_SIZE) is
# the same as the size expected by the driver manager (SQLWCHAR_SIZE).
create_buffer_u = create_buffer
wchar_pointer = ctypes.c_char_p
def ucs2_buf(s):
return s.encode('utf_16_le')
from_buffer_u = ucs2_dec
# Exoteric case, don't really care.
elif UNICODE_SIZE < SQLWCHAR_SIZE:
raise OdbcLibraryError('Using narrow Python build with ODBC library '
'expecting wide unicode is not supported.')
#################
# Database value to Python data type mappings
SQL_TYPE_NULL = 0
SQL_DECIMAL = 3
SQL_FLOAT = 6
SQL_DATE = 9
SQL_TIME = 10
SQL_TIMESTAMP = 11
SQL_VARCHAR = 12
SQL_LONGVARCHAR = -1
SQL_VARBINARY = -3
SQL_LONGVARBINARY = -4
SQL_BIGINT = -5
SQL_WVARCHAR = -9
SQL_WLONGVARCHAR = -10
SQL_ALL_TYPES = 0
SQL_SIGNED_OFFSET = -20
SQL_SS_VARIANT = -150
SQL_SS_UDT = -151
SQL_SS_XML = -152
SQL_SS_TIME2 = -154
SQL_C_CHAR = SQL_CHAR = 1
SQL_C_NUMERIC = SQL_NUMERIC = 2
SQL_C_LONG = SQL_INTEGER = 4
SQL_C_SLONG = SQL_C_LONG + SQL_SIGNED_OFFSET
SQL_C_SHORT = SQL_SMALLINT = 5
SQL_C_FLOAT = SQL_REAL = 7
SQL_C_DOUBLE = SQL_DOUBLE = 8
SQL_C_TYPE_DATE = SQL_TYPE_DATE = 91
SQL_C_TYPE_TIME = SQL_TYPE_TIME = 92
SQL_C_BINARY = SQL_BINARY = -2
SQL_C_SBIGINT = SQL_BIGINT + SQL_SIGNED_OFFSET
SQL_C_TINYINT = SQL_TINYINT = -6
SQL_C_BIT = SQL_BIT = -7
SQL_C_WCHAR = SQL_WCHAR = -8
SQL_C_GUID = SQL_GUID = -11
SQL_C_TYPE_TIMESTAMP = SQL_TYPE_TIMESTAMP = 93
SQL_C_DEFAULT = 99
SQL_DESC_DISPLAY_SIZE = SQL_COLUMN_DISPLAY_SIZE
def dttm_cvt(x):
if py_v3:
x = x.decode('ascii')
if x == '': return None
else: return datetime.datetime(int(x[0:4]),int(x[5:7]),int(x[8:10]),int(x[10:13]),int(x[14:16]),int(x[17:19]),int(x[20:].ljust(6,'0')))
def tm_cvt(x):
if py_v3:
x = x.decode('ascii')
if x == '': return None
else: return datetime.time(int(x[0:2]),int(x[3:5]),int(x[6:8]),int(x[9:].ljust(6,'0')))
def dt_cvt(x):
if py_v3:
x = x.decode('ascii')
if x == '': return None
else: return datetime.date(int(x[0:4]),int(x[5:7]),int(x[8:10]))
def Decimal_cvt(x):
if py_v3:
x = x.decode('ascii')
return Decimal(x)
bytearray_cvt = bytearray
if sys.platform == 'cli':
bytearray_cvt = lambda x: bytearray(buffer(x))
# Below Datatype mappings referenced the document at
# http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.sdk_12.5.1.aseodbc/html/aseodbc/CACFDIGH.htm
SQL_data_type_dict = { \
#SQL Data TYPE 0.Python Data Type 1.Default Output Converter 2.Buffer Type 3.Buffer Allocator 4.Default Buffer Size
SQL_TYPE_NULL : (None, lambda x: None, SQL_C_CHAR, create_buffer, 2 ),
SQL_CHAR : (str, lambda x: x, SQL_C_CHAR, create_buffer, 2048 ),
SQL_NUMERIC : (Decimal, Decimal_cvt, SQL_C_CHAR, create_buffer, 150 ),
SQL_DECIMAL : (Decimal, Decimal_cvt, SQL_C_CHAR, create_buffer, 150 ),
SQL_INTEGER : (int, int, SQL_C_CHAR, create_buffer, 150 ),
SQL_SMALLINT : (int, int, SQL_C_CHAR, create_buffer, 150 ),
SQL_FLOAT : (float, float, SQL_C_CHAR, create_buffer, 150 ),
SQL_REAL : (float, float, SQL_C_CHAR, create_buffer, 150 ),
SQL_DOUBLE : (float, float, SQL_C_CHAR, create_buffer, 200 ),
SQL_DATE : (datetime.date, dt_cvt, SQL_C_CHAR , create_buffer, 30 ),
SQL_TIME : (datetime.time, tm_cvt, SQL_C_CHAR, create_buffer, 20 ),
SQL_SS_TIME2 : (datetime.time, tm_cvt, SQL_C_CHAR, create_buffer, 20 ),
SQL_TIMESTAMP : (datetime.datetime, dttm_cvt, SQL_C_CHAR, create_buffer, 30 ),
SQL_VARCHAR : (str, lambda x: x, SQL_C_CHAR, create_buffer, 2048 ),
SQL_LONGVARCHAR : (str, lambda x: x, SQL_C_CHAR, create_buffer, 20500 ),
SQL_BINARY : (bytearray, bytearray_cvt, SQL_C_BINARY, create_buffer, 5120 ),
SQL_VARBINARY : (bytearray, bytearray_cvt, SQL_C_BINARY, create_buffer, 5120 ),
SQL_LONGVARBINARY : (bytearray, bytearray_cvt, SQL_C_BINARY, create_buffer, 20500 ),
SQL_BIGINT : (long, long, SQL_C_CHAR, create_buffer, 150 ),
SQL_TINYINT : (int, int, SQL_C_CHAR, create_buffer, 150 ),
SQL_BIT : (bool, lambda x:x == BYTE_1, SQL_C_CHAR, create_buffer, 2 ),
SQL_WCHAR : (unicode, lambda x: x, SQL_C_WCHAR, create_buffer_u, 2048 ),
SQL_WVARCHAR : (unicode, lambda x: x, SQL_C_WCHAR, create_buffer_u, 2048 ),
SQL_GUID : (str, str, SQL_C_CHAR, create_buffer, 50 ),
SQL_WLONGVARCHAR : (unicode, lambda x: x, SQL_C_WCHAR, create_buffer_u, 20500 ),
SQL_TYPE_DATE : (datetime.date, dt_cvt, SQL_C_CHAR, create_buffer, 30 ),
SQL_TYPE_TIME : (datetime.time, tm_cvt, SQL_C_CHAR, create_buffer, 20 ),
SQL_TYPE_TIMESTAMP : (datetime.datetime, dttm_cvt, SQL_C_CHAR, create_buffer, 30 ),
SQL_SS_VARIANT : (str, lambda x: x, SQL_C_CHAR, create_buffer, 2048 ),
SQL_SS_XML : (unicode, lambda x: x, SQL_C_WCHAR, create_buffer_u, 20500 ),
SQL_SS_UDT : (bytearray, bytearray_cvt, SQL_C_BINARY, create_buffer, 5120 ),
}
"""
Types mapping, applicable for 32-bit and 64-bit Linux / Windows / Mac OS X.
SQLPointer -> ctypes.c_void_p
SQLCHAR * -> ctypes.c_char_p
SQLWCHAR * -> ctypes.c_wchar_p on Windows, ctypes.c_char_p with unixODBC
SQLINT -> ctypes.c_int
SQLSMALLINT -> ctypes.c_short
SQMUSMALLINT -> ctypes.c_ushort
SQLLEN -> ctypes.c_ssize_t
SQLULEN -> ctypes.c_size_t
SQLRETURN -> ctypes.c_short
"""
# Define the python return type for ODBC functions with ret result.
funcs_with_ret = [
"SQLAllocHandle",
"SQLBindParameter",
"SQLCloseCursor",
"SQLColAttribute",
"SQLColumns",
"SQLColumnsW",
"SQLConnect",
"SQLConnectW",
"SQLDataSources",
"SQLDataSourcesW",
"SQLDescribeCol",
"SQLDescribeColW",
"SQLDescribeParam",
"SQLDisconnect",
"SQLDriverConnect",
"SQLDriverConnectW",
"SQLDrivers",
"SQLDriversW",
"SQLEndTran",
"SQLExecDirect",
"SQLExecDirectW",
"SQLExecute",
"SQLFetch",
"SQLFetchScroll",
"SQLForeignKeys",
"SQLForeignKeysW",
"SQLFreeHandle",
"SQLFreeStmt",
"SQLGetData",
"SQLGetDiagRec",
"SQLGetDiagRecW",
"SQLGetInfo",
"SQLGetInfoW",
"SQLGetTypeInfo",
"SQLMoreResults",
"SQLNumParams",
"SQLNumResultCols",
"SQLPrepare",
"SQLPrepareW",
"SQLPrimaryKeys",
"SQLPrimaryKeysW",
"SQLProcedureColumns",
"SQLProcedureColumnsW",
"SQLProcedures",
"SQLProceduresW",
"SQLRowCount",
"SQLSetConnectAttr",
"SQLSetEnvAttr",
"SQLStatistics",
"SQLStatisticsW",
"SQLTables",
"SQLTablesW",
]
for func_name in funcs_with_ret:
getattr(ODBC_API, func_name).restype = ctypes.c_short
if sys.platform not in ('cli'):
#Seems like the IronPython can not declare ctypes.POINTER type arguments
ODBC_API.SQLAllocHandle.argtypes = [
ctypes.c_short, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p),
]
ODBC_API.SQLBindParameter.argtypes = [
ctypes.c_void_p, ctypes.c_ushort, ctypes.c_short,
ctypes.c_short, ctypes.c_short, ctypes.c_size_t,
ctypes.c_short, ctypes.c_void_p, ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_ssize_t),
]
ODBC_API.SQLColAttribute.argtypes = [
ctypes.c_void_p, ctypes.c_ushort, ctypes.c_ushort,
ctypes.c_void_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short), ctypes.POINTER(ctypes.c_ssize_t),
]
ODBC_API.SQLDataSources.argtypes = [
ctypes.c_void_p, ctypes.c_ushort, ctypes.c_char_p,
ctypes.c_short, ctypes.POINTER(ctypes.c_short),
ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLDescribeCol.argtypes = [
ctypes.c_void_p, ctypes.c_ushort, ctypes.c_char_p, ctypes.c_short,
ctypes.POINTER(ctypes.c_short), ctypes.POINTER(ctypes.c_short),
ctypes.POINTER(ctypes.c_size_t), ctypes.POINTER(ctypes.c_short), ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLDescribeParam.argtypes = [
ctypes.c_void_p, ctypes.c_ushort,
ctypes.POINTER(ctypes.c_short), ctypes.POINTER(ctypes.c_size_t),
ctypes.POINTER(ctypes.c_short), ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLDriverConnect.argtypes = [
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p,
ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
ctypes.POINTER(ctypes.c_short), ctypes.c_ushort,
]
ODBC_API.SQLDrivers.argtypes = [
ctypes.c_void_p, ctypes.c_ushort,
ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short),
ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLGetData.argtypes = [
ctypes.c_void_p, ctypes.c_ushort, ctypes.c_short,
ctypes.c_void_p, ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_ssize_t),
]
ODBC_API.SQLGetDiagRec.argtypes = [
ctypes.c_short, ctypes.c_void_p, ctypes.c_short,
ctypes.c_char_p, ctypes.POINTER(ctypes.c_int),
ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLGetInfo.argtypes = [
ctypes.c_void_p, ctypes.c_ushort, ctypes.c_void_p,
ctypes.c_short, ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLRowCount.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_ssize_t),
]
ODBC_API.SQLNumParams.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLNumResultCols.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_short),
]
ODBC_API.SQLCloseCursor.argtypes = [ctypes.c_void_p]
ODBC_API.SQLColumns.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p,
ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
ODBC_API.SQLConnect.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
ODBC_API.SQLDisconnect.argtypes = [ctypes.c_void_p]
ODBC_API.SQLEndTran.argtypes = [
ctypes.c_short, ctypes.c_void_p, ctypes.c_short,
]
ODBC_API.SQLExecute.argtypes = [ctypes.c_void_p]
ODBC_API.SQLExecDirect.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int,
]
ODBC_API.SQLFetch.argtypes = [ctypes.c_void_p]
ODBC_API.SQLFetchScroll.argtypes = [
ctypes.c_void_p, ctypes.c_short, ctypes.c_ssize_t,
]
ODBC_API.SQLForeignKeys.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p,
ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
ODBC_API.SQLFreeHandle.argtypes = [
ctypes.c_short, ctypes.c_void_p,
]
ODBC_API.SQLFreeStmt.argtypes = [
ctypes.c_void_p, ctypes.c_ushort,
]
ODBC_API.SQLGetTypeInfo.argtypes = [
ctypes.c_void_p, ctypes.c_short,
]
ODBC_API.SQLMoreResults.argtypes = [ctypes.c_void_p]
ODBC_API.SQLPrepare.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int,
]
ODBC_API.SQLPrimaryKeys.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
ODBC_API.SQLProcedureColumns.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p,
ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
ODBC_API.SQLProcedures.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
ODBC_API.SQLSetConnectAttr.argtypes = [
ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
]
ODBC_API.SQLSetEnvAttr.argtypes = [
ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
]
ODBC_API.SQLStatistics.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p,
ctypes.c_short, ctypes.c_ushort, ctypes.c_ushort,
]
ODBC_API.SQLTables.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_short,
ctypes.c_char_p, ctypes.c_short, ctypes.c_char_p,
ctypes.c_short, ctypes.c_char_p, ctypes.c_short,
]
def to_wchar(argtypes):
if argtypes: # Under IronPython some argtypes are not declared
result = []
for x in argtypes:
if x == ctypes.c_char_p:
result.append(wchar_pointer)
else:
result.append(x)
return result
else:
return argtypes
ODBC_API.SQLColumnsW.argtypes = to_wchar(ODBC_API.SQLColumns.argtypes)
ODBC_API.SQLConnectW.argtypes = to_wchar(ODBC_API.SQLConnect.argtypes)
ODBC_API.SQLDataSourcesW.argtypes = to_wchar(ODBC_API.SQLDataSources.argtypes)
ODBC_API.SQLDescribeColW.argtypes = to_wchar(ODBC_API.SQLDescribeCol.argtypes)
ODBC_API.SQLDriverConnectW.argtypes = to_wchar(ODBC_API.SQLDriverConnect.argtypes)
ODBC_API.SQLDriversW.argtypes = to_wchar(ODBC_API.SQLDrivers.argtypes)
ODBC_API.SQLExecDirectW.argtypes = to_wchar(ODBC_API.SQLExecDirect.argtypes)
ODBC_API.SQLForeignKeysW.argtypes = to_wchar(ODBC_API.SQLForeignKeys.argtypes)
ODBC_API.SQLPrepareW.argtypes = to_wchar(ODBC_API.SQLPrepare.argtypes)
ODBC_API.SQLPrimaryKeysW.argtypes = to_wchar(ODBC_API.SQLPrimaryKeys.argtypes)
ODBC_API.SQLProcedureColumnsW.argtypes = to_wchar(ODBC_API.SQLProcedureColumns.argtypes)
ODBC_API.SQLProceduresW.argtypes = to_wchar(ODBC_API.SQLProcedures.argtypes)
ODBC_API.SQLStatisticsW.argtypes = to_wchar(ODBC_API.SQLStatistics.argtypes)
ODBC_API.SQLTablesW.argtypes = to_wchar(ODBC_API.SQLTables.argtypes)
ODBC_API.SQLGetDiagRecW.argtypes = to_wchar(ODBC_API.SQLGetDiagRec.argtypes)
ODBC_API.SQLGetInfoW.argtypes = to_wchar(ODBC_API.SQLGetInfo.argtypes)
# Set the alias for the ctypes functions for beter code readbility or performance.
ADDR = ctypes.byref
c_short = ctypes.c_short
c_ssize_t = ctypes.c_ssize_t
SQLFetch = ODBC_API.SQLFetch
SQLExecute = ODBC_API.SQLExecute
SQLBindParameter = ODBC_API.SQLBindParameter
SQLGetData = ODBC_API.SQLGetData
SQLRowCount = ODBC_API.SQLRowCount
SQLNumResultCols = ODBC_API.SQLNumResultCols
SQLEndTran = ODBC_API.SQLEndTran
# Set alias for beter code readbility or performance.
NO_FREE_STATEMENT = 0
FREE_STATEMENT = 1
BLANK_BYTE = str_8b()
def ctrl_err(ht, h, val_ret, ansi):
"""Classify type of ODBC error from (type of handle, handle, return value)
, and raise with a list"""
if ansi:
state = create_buffer(22)
Message = create_buffer(1024*10)
ODBC_func = ODBC_API.SQLGetDiagRec
if py_v3:
raw_s = lambda s: bytes(s,'ascii')
else:
raw_s = str_8b
else:
state = create_buffer_u(22)
Message = create_buffer_u(1024*10)
ODBC_func = ODBC_API.SQLGetDiagRecW
raw_s = unicode
NativeError = ctypes.c_int()
Buffer_len = c_short()
err_list = []
number_errors = 1
while 1:
ret = ODBC_func(ht, h, number_errors, state, \
NativeError, Message, len(Message), ADDR(Buffer_len))
if ret == SQL_NO_DATA_FOUND:
#No more data, I can raise
#print(err_list[0][1])
state = err_list[0][0]
err_text = raw_s('[')+state+raw_s('] ')+err_list[0][1]
if state[:2] in (raw_s('24'),raw_s('25'),raw_s('42')):
raise ProgrammingError(state,err_text)
elif state[:2] in (raw_s('22')):
raise DataError(state,err_text)
elif state[:2] in (raw_s('23')) or state == raw_s('40002'):
raise IntegrityError(state,err_text)
elif state == raw_s('0A000'):
raise NotSupportedError(state,err_text)
elif state in (raw_s('HYT00'),raw_s('HYT01')):
raise OperationalError(state,err_text)
elif state[:2] in (raw_s('IM'),raw_s('HY')):
raise Error(state,err_text)
else:
raise DatabaseError(state,err_text)
break
elif ret == SQL_INVALID_HANDLE:
#The handle passed is an invalid handle
raise ProgrammingError('', 'SQL_INVALID_HANDLE')
elif ret == SQL_SUCCESS:
if ansi:
err_list.append((state.value, Message.value, NativeError.value))
else:
err_list.append((from_buffer_u(state), from_buffer_u(Message), NativeError.value))
number_errors += 1
def check_success(ODBC_obj, ret):
""" Validate return value, if not success, raise exceptions based on the handle """
if ret not in (SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_NO_DATA):
if isinstance(ODBC_obj, Cursor):
ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
elif isinstance(ODBC_obj, Connection):
ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi)
else:
ctrl_err(SQL_HANDLE_ENV, ODBC_obj, ret, False)
def AllocateEnv():
if pooling:
ret = ODBC_API.SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, SQL_CP_ONE_PER_HENV, SQL_IS_UINTEGER)
check_success(SQL_NULL_HANDLE, ret)
'''
Allocate an ODBC environment by initializing the handle shared_env_h
ODBC enviroment needed to be created, so connections can be created under it
connections pooling can be shared under one environment
'''
global shared_env_h
shared_env_h = ctypes.c_void_p()
ret = ODBC_API.SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, ADDR(shared_env_h))
check_success(shared_env_h, ret)
# Set the ODBC environment's compatibil leve to ODBC 3.0
ret = ODBC_API.SQLSetEnvAttr(shared_env_h, SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3, 0)
check_success(shared_env_h, ret)
"""
Here, we have a few callables that determine how a result row is returned.
A new one can be added by creating a callable that:
- accepts a cursor as its parameter.
- returns a callable that accepts an iterable containing the row values.
"""
def TupleRow(cursor):
"""Normal tuple with added attribute `cursor_description`, as in pyodbc.
This is the default.
"""
class Row(tuple):
cursor_description = cursor.description
def get(self, field):
if not hasattr(self, 'field_dict'):
self.field_dict = {}
for i,item in enumerate(self):
self.field_dict[self.cursor_description[i][0]] = item
return self.field_dict.get(field)
def __getitem__(self, field):