File size: 49,816 Bytes
375a1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
"""adodbapi - A python DB API 2.0 (PEP 249) interface to Microsoft ADO

Copyright (C) 2002 Henrik Ekelund, versions 2.1 and later by Vernon Cole
* http://sourceforge.net/projects/pywin32
* https://github.com/mhammond/pywin32
* http://sourceforge.net/projects/adodbapi

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    django adaptations and refactoring by Adam Vandenberg

DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/

This module source should run correctly in CPython versions 2.7 and later,
or IronPython version 2.7 and later,
or, after running through 2to3.py, CPython 3.4 or later.
"""

__version__ = "2.6.2.0"
version = "adodbapi v" + __version__

import copy
import decimal
import os
import sys
import weakref

from . import ado_consts as adc, apibase as api, process_connect_string

try:
    verbose = int(os.environ["ADODBAPI_VERBOSE"])
except:
    verbose = False
if verbose:
    print(version)

# --- define objects to smooth out IronPython <-> CPython differences
onWin32 = False  # assume the worst
if api.onIronPython:
    from clr import Reference
    from System import (
        Activator,
        Array,
        Byte,
        DateTime,
        DBNull,
        Decimal as SystemDecimal,
        Type,
    )

    def Dispatch(dispatch):
        type = Type.GetTypeFromProgID(dispatch)
        return Activator.CreateInstance(type)

    def getIndexedValue(obj, index):
        return obj.Item[index]

else:  # try pywin32
    try:
        import pythoncom
        import pywintypes
        import win32com.client

        onWin32 = True

        def Dispatch(dispatch):
            return win32com.client.Dispatch(dispatch)

    except ImportError:
        import warnings

        warnings.warn(
            "pywin32 package (or IronPython) required for adodbapi.", ImportWarning
        )

    def getIndexedValue(obj, index):
        return obj(index)


from collections.abc import Mapping

# --- define objects to smooth out Python3000 <-> Python 2.x differences
unicodeType = str
longType = int
StringTypes = str
maxint = sys.maxsize


# -----------------  The .connect method -----------------
def make_COM_connecter():
    try:
        if onWin32:
            pythoncom.CoInitialize()  # v2.1 Paj
        c = Dispatch("ADODB.Connection")  # connect _after_ CoIninialize v2.1.1 adamvan
    except:
        raise api.InterfaceError(
            "Windows COM Error: Dispatch('ADODB.Connection') failed."
        )
    return c


def connect(*args, **kwargs):  # --> a db-api connection object
    """Connect to a database.

    call using:
    :connection_string -- An ADODB formatted connection string, see:
         * http://www.connectionstrings.com
         * http://www.asp101.com/articles/john/connstring/default.asp
    :timeout -- A command timeout value, in seconds (default 30 seconds)
    """
    co = Connection()  # make an empty connection object

    kwargs = process_connect_string.process(args, kwargs, True)

    try:  # connect to the database, using the connection information in kwargs
        co.connect(kwargs)
        return co
    except Exception as e:
        message = 'Error opening connection to "%s"' % co.connection_string
        raise api.OperationalError(e, message)


# so you could use something like:
#   myConnection.paramstyle = 'named'
# The programmer may also change the default.
#   For example, if I were using django, I would say:
#     import adodbapi as Database
#     Database.adodbapi.paramstyle = 'format'

# ------- other module level defaults --------
defaultIsolationLevel = adc.adXactReadCommitted
#  Set defaultIsolationLevel on module level before creating the connection.
#   For example:
#   import adodbapi, ado_consts
#   adodbapi.adodbapi.defaultIsolationLevel=ado_consts.adXactBrowse"
#
#  Set defaultCursorLocation on module level before creating the connection.
# It may be one of the "adUse..." consts.
defaultCursorLocation = adc.adUseClient  # changed from adUseServer as of v 2.3.0

dateconverter = api.pythonDateTimeConverter()  # default


def format_parameters(ADOparameters, show_value=False):
    """Format a collection of ADO Command Parameters.

    Used by error reporting in _execute_command.
    """
    try:
        if show_value:
            desc = [
                'Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %s'
                % (
                    p.Name,
                    adc.directions[p.Direction],
                    adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
                    p.Size,
                    p.Value,
                    p.Precision,
                    p.NumericScale,
                )
                for p in ADOparameters
            ]
        else:
            desc = [
                "Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s"
                % (
                    p.Name,
                    adc.directions[p.Direction],
                    adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
                    p.Size,
                    p.Precision,
                    p.NumericScale,
                )
                for p in ADOparameters
            ]
        return "[" + "\n".join(desc) + "]"
    except:
        return "[]"


def _configure_parameter(p, value, adotype, settings_known):
    """Configure the given ADO Parameter 'p' with the Python 'value'."""

    if adotype in api.adoBinaryTypes:
        p.Size = len(value)
        p.AppendChunk(value)

    elif isinstance(value, StringTypes):  # v2.1 Jevon
        L = len(value)
        if adotype in api.adoStringTypes:  # v2.2.1 Cole
            if settings_known:
                L = min(L, p.Size)  # v2.1 Cole limit data to defined size
            p.Value = value[:L]  # v2.1 Jevon & v2.1 Cole
        else:
            p.Value = value  # dont limit if db column is numeric
        if L > 0:  # v2.1 Cole something does not like p.Size as Zero
            p.Size = L  # v2.1 Jevon

    elif isinstance(value, decimal.Decimal):
        if api.onIronPython:
            s = str(value)
            p.Value = s
            p.Size = len(s)
        else:
            p.Value = value
        exponent = value.as_tuple()[2]
        digit_count = len(value.as_tuple()[1])
        p.Precision = digit_count
        if exponent == 0:
            p.NumericScale = 0
        elif exponent < 0:
            p.NumericScale = -exponent
            if p.Precision < p.NumericScale:
                p.Precision = p.NumericScale
        else:  # exponent > 0:
            p.NumericScale = 0
            p.Precision = digit_count + exponent

    elif type(value) in dateconverter.types:
        if settings_known and adotype in api.adoDateTimeTypes:
            p.Value = dateconverter.COMDate(value)
        else:  # probably a string
            # provide the date as a string in the format 'YYYY-MM-dd'
            s = dateconverter.DateObjectToIsoFormatString(value)
            p.Value = s
            p.Size = len(s)

    elif api.onIronPython and isinstance(value, longType):  # Iron Python Long
        s = str(value)  # feature workaround for IPy 2.0
        p.Value = s

    elif adotype == adc.adEmpty:  # ADO will not let you specify a null column
        p.Type = (
            adc.adInteger
        )  # so we will fake it to be an integer (just to have something)
        p.Value = None  # and pass in a Null *value*

        # For any other type, set the value and let pythoncom do the right thing.
    else:
        p.Value = value


# # # # # ----- the Class that defines a connection ----- # # # # #
class Connection(object):
    # include connection attributes as class attributes required by api definition.
    Warning = api.Warning
    Error = api.Error
    InterfaceError = api.InterfaceError
    DataError = api.DataError
    DatabaseError = api.DatabaseError
    OperationalError = api.OperationalError
    IntegrityError = api.IntegrityError
    InternalError = api.InternalError
    NotSupportedError = api.NotSupportedError
    ProgrammingError = api.ProgrammingError
    FetchFailedError = api.FetchFailedError  # (special for django)
    # ...class attributes... (can be overridden by instance attributes)
    verbose = api.verbose

    @property
    def dbapi(self):  # a proposed db-api version 3 extension.
        "Return a reference to the DBAPI module for this Connection."
        return api

    def __init__(self):  # now define the instance attributes
        self.connector = None
        self.paramstyle = api.paramstyle
        self.supportsTransactions = False
        self.connection_string = ""
        self.cursors = weakref.WeakValueDictionary()
        self.dbms_name = ""
        self.dbms_version = ""
        self.errorhandler = None  # use the standard error handler for this instance
        self.transaction_level = 0  # 0 == Not in a transaction, at the top level
        self._autocommit = False

    def connect(self, kwargs, connection_maker=make_COM_connecter):
        if verbose > 9:
            print("kwargs=", repr(kwargs))
        try:
            self.connection_string = (
                kwargs["connection_string"] % kwargs
            )  # insert keyword arguments
        except Exception as e:
            self._raiseConnectionError(
                KeyError, "Python string format error in connection string->"
            )
        self.timeout = kwargs.get("timeout", 30)
        self.mode = kwargs.get("mode", adc.adModeUnknown)
        self.kwargs = kwargs
        if verbose:
            print('%s attempting: "%s"' % (version, self.connection_string))
        self.connector = connection_maker()
        self.connector.ConnectionTimeout = self.timeout
        self.connector.ConnectionString = self.connection_string
        self.connector.Mode = self.mode

        try:
            self.connector.Open()  # Open the ADO connection
        except api.Error:
            self._raiseConnectionError(
                api.DatabaseError,
                "ADO error trying to Open=%s" % self.connection_string,
            )

        try:  # Stefan Fuchs; support WINCCOLEDBProvider
            if getIndexedValue(self.connector.Properties, "Transaction DDL").Value != 0:
                self.supportsTransactions = True
        except pywintypes.com_error:
            pass  # Stefan Fuchs
        self.dbms_name = getIndexedValue(self.connector.Properties, "DBMS Name").Value
        try:  # Stefan Fuchs
            self.dbms_version = getIndexedValue(
                self.connector.Properties, "DBMS Version"
            ).Value
        except pywintypes.com_error:
            pass  # Stefan Fuchs
        self.connector.CursorLocation = defaultCursorLocation  # v2.1 Rose
        if self.supportsTransactions:
            self.connector.IsolationLevel = defaultIsolationLevel
            self._autocommit = bool(kwargs.get("autocommit", False))
            if not self._autocommit:
                self.transaction_level = (
                    self.connector.BeginTrans()
                )  # Disables autocommit & inits transaction_level
        else:
            self._autocommit = True
        if "paramstyle" in kwargs:
            self.paramstyle = kwargs["paramstyle"]  # let setattr do the error checking
        self.messages = []
        if verbose:
            print("adodbapi New connection at %X" % id(self))

    def _raiseConnectionError(self, errorclass, errorvalue):
        eh = self.errorhandler
        if eh is None:
            eh = api.standardErrorHandler
        eh(self, None, errorclass, errorvalue)

    def _closeAdoConnection(self):  # all v2.1 Rose
        """close the underlying ADO Connection object,
        rolling it back first if it supports transactions."""
        if self.connector is None:
            return
        if not self._autocommit:
            if self.transaction_level:
                try:
                    self.connector.RollbackTrans()
                except:
                    pass
        self.connector.Close()
        if verbose:
            print("adodbapi Closed connection at %X" % id(self))

    def close(self):
        """Close the connection now (rather than whenever __del__ is called).

        The connection will be unusable from this point forward;
        an Error (or subclass) exception will be raised if any operation is attempted with the connection.
        The same applies to all cursor objects trying to use the connection.
        """
        for crsr in list(self.cursors.values())[
            :
        ]:  # copy the list, then close each one
            crsr.close(dont_tell_me=True)  # close without back-link clearing
        self.messages = []
        try:
            self._closeAdoConnection()  # v2.1 Rose
        except Exception as e:
            self._raiseConnectionError(sys.exc_info()[0], sys.exc_info()[1])

        self.connector = None  # v2.4.2.2 fix subtle timeout bug
        # per M.Hammond: "I expect the benefits of uninitializing are probably fairly small,
        #    so never uninitializing will probably not cause any problems."

    def commit(self):
        """Commit any pending transaction to the database.

        Note that if the database supports an auto-commit feature,
        this must be initially off. An interface method may be provided to turn it back on.
        Database modules that do not support transactions should implement this method with void functionality.
        """
        self.messages = []
        if not self.supportsTransactions:
            return

        try:
            self.transaction_level = self.connector.CommitTrans()
            if verbose > 1:
                print("commit done on connection at %X" % id(self))
            if not (
                self._autocommit
                or (self.connector.Attributes & adc.adXactAbortRetaining)
            ):
                # If attributes has adXactCommitRetaining it performs retaining commits that is,
                # calling CommitTrans automatically starts a new transaction. Not all providers support this.
                # If not, we will have to start a new transaction by this command:
                self.transaction_level = self.connector.BeginTrans()
        except Exception as e:
            self._raiseConnectionError(api.ProgrammingError, e)

    def _rollback(self):
        """In case a database does provide transactions this method causes the the database to roll back to
        the start of any pending transaction. Closing a connection without committing the changes first will
        cause an implicit rollback to be performed.

        If the database does not support the functionality required by the method, the interface should
        throw an exception in case the method is used.
        The preferred approach is to not implement the method and thus have Python generate
        an AttributeError in case the method is requested. This allows the programmer to check for database
        capabilities using the standard hasattr() function.

        For some dynamically configured interfaces it may not be appropriate to require dynamically making
        the method available. These interfaces should then raise a NotSupportedError to indicate the
        non-ability to perform the roll back when the method is invoked.
        """
        self.messages = []
        if (
            self.transaction_level
        ):  # trying to roll back with no open transaction causes an error
            try:
                self.transaction_level = self.connector.RollbackTrans()
                if verbose > 1:
                    print("rollback done on connection at %X" % id(self))
                if not self._autocommit and not (
                    self.connector.Attributes & adc.adXactAbortRetaining
                ):
                    # If attributes has adXactAbortRetaining it performs retaining aborts that is,
                    # calling RollbackTrans automatically starts a new transaction. Not all providers support this.
                    # If not, we will have to start a new transaction by this command:
                    if (
                        not self.transaction_level
                    ):  # if self.transaction_level == 0 or self.transaction_level is None:
                        self.transaction_level = self.connector.BeginTrans()
            except Exception as e:
                self._raiseConnectionError(api.ProgrammingError, e)

    def __setattr__(self, name, value):
        if name == "autocommit":  # extension: allow user to turn autocommit on or off
            if self.supportsTransactions:
                object.__setattr__(self, "_autocommit", bool(value))
                try:
                    self._rollback()  # must clear any outstanding transactions
                except:
                    pass
            return
        elif name == "paramstyle":
            if value not in api.accepted_paramstyles:
                self._raiseConnectionError(
                    api.NotSupportedError,
                    'paramstyle="%s" not in:%s'
                    % (value, repr(api.accepted_paramstyles)),
                )
        elif name == "variantConversions":
            value = copy.copy(
                value
            )  # make a new copy -- no changes in the default, please
        object.__setattr__(self, name, value)

    def __getattr__(self, item):
        if (
            item == "rollback"
        ):  # the rollback method only appears if the database supports transactions
            if self.supportsTransactions:
                return (
                    self._rollback
                )  # return the rollback method so the caller can execute it.
            else:
                raise AttributeError("this data provider does not support Rollback")
        elif item == "autocommit":
            return self._autocommit
        else:
            raise AttributeError(
                'no such attribute in ADO connection object as="%s"' % item
            )

    def cursor(self):
        "Return a new Cursor Object using the connection."
        self.messages = []
        c = Cursor(self)
        return c

    def _i_am_here(self, crsr):
        "message from a new cursor proclaiming its existence"
        oid = id(crsr)
        self.cursors[oid] = crsr

    def _i_am_closing(self, crsr):
        "message from a cursor giving connection a chance to clean up"
        try:
            del self.cursors[id(crsr)]
        except:
            pass

    def printADOerrors(self):
        j = self.connector.Errors.Count
        if j:
            print("ADO Errors:(%i)" % j)
        for e in self.connector.Errors:
            print("Description: %s" % e.Description)
            print("Error: %s %s " % (e.Number, adc.adoErrors.get(e.Number, "unknown")))
            if e.Number == adc.ado_error_TIMEOUT:
                print(
                    "Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)"
                )
            print("Source: %s" % e.Source)
            print("NativeError: %s" % e.NativeError)
            print("SQL State: %s" % e.SQLState)

    def _suggest_error_class(self):
        """Introspect the current ADO Errors and determine an appropriate error class.

        Error.SQLState is a SQL-defined error condition, per the SQL specification:
        http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

        The 23000 class of errors are integrity errors.
        Error 40002 is a transactional integrity error.
        """
        if self.connector is not None:
            for e in self.connector.Errors:
                state = str(e.SQLState)
                if state.startswith("23") or state == "40002":
                    return api.IntegrityError
        return api.DatabaseError

    def __del__(self):
        try:
            self._closeAdoConnection()  # v2.1 Rose
        except:
            pass
        self.connector = None

    def __enter__(self):  # Connections are context managers
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self._rollback()  # automatic rollback on errors
        else:
            self.commit()

    def get_table_names(self):
        schema = self.connector.OpenSchema(20)  # constant = adSchemaTables

        tables = []
        while not schema.EOF:
            name = getIndexedValue(schema.Fields, "TABLE_NAME").Value
            tables.append(name)
            schema.MoveNext()
        del schema
        return tables


# # # # # ----- the Class that defines a cursor ----- # # # # #
class Cursor(object):
    ## ** api required attributes:
    ## description...
    ##    This read-only attribute is a sequence of 7-item sequences.
    ##    Each of these sequences contains information describing one result column:
    ##        (name, type_code, display_size, internal_size, precision, scale, null_ok).
    ##    This attribute will be None for operations that do not return rows or if the
    ##    cursor has not had an operation invoked via the executeXXX() method yet.
    ##    The type_code can be interpreted by comparing it to the Type Objects specified in the section below.
    ## rowcount...
    ##    This read-only attribute specifies the number of rows that the last executeXXX() produced
    ##    (for DQL statements like select) or affected (for DML statements like update or insert).
    ##    The attribute is -1 in case no executeXXX() has been performed on the cursor or
    ##    the rowcount of the last operation is not determinable by the interface.[7]
    ## arraysize...
    ##    This read/write attribute specifies the number of rows to fetch at a time with fetchmany().
    ##    It defaults to 1 meaning to fetch a single row at a time.
    ##    Implementations must observe this value with respect to the fetchmany() method,
    ##    but are free to interact with the database a single row at a time.
    ##    It may also be used in the implementation of executemany().
    ## ** extension attributes:
    ## paramstyle...
    ##   allows the programmer to override the connection's default paramstyle
    ## errorhandler...
    ##   allows the programmer to override the connection's default error handler

    def __init__(self, connection):
        self.command = None
        self._ado_prepared = False
        self.messages = []
        self.connection = connection
        self.paramstyle = connection.paramstyle  # used for overriding the paramstyle
        self._parameter_names = []
        self.recordset_is_remote = False
        self.rs = None  # the ADO recordset for this cursor
        self.converters = []  # conversion function for each column
        self.columnNames = {}  # names of columns {lowercase name : number,...}
        self.numberOfColumns = 0
        self._description = None
        self.rowcount = -1
        self.errorhandler = connection.errorhandler
        self.arraysize = 1
        connection._i_am_here(self)
        if verbose:
            print(
                "%s New cursor at %X on conn %X"
                % (version, id(self), id(self.connection))
            )

    def __iter__(self):  # [2.1 Zamarev]
        return iter(self.fetchone, None)  # [2.1 Zamarev]

    def prepare(self, operation):
        self.command = operation
        self._description = None
        self._ado_prepared = "setup"

    def __next__(self):
        r = self.fetchone()
        if r:
            return r
        raise StopIteration

    def __enter__(self):
        "Allow database cursors to be used with context managers."
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        "Allow database cursors to be used with context managers."
        self.close()

    def _raiseCursorError(self, errorclass, errorvalue):
        eh = self.errorhandler
        if eh is None:
            eh = api.standardErrorHandler
        eh(self.connection, self, errorclass, errorvalue)

    def build_column_info(self, recordset):
        self.converters = []  # convertion function for each column
        self.columnNames = {}  # names of columns {lowercase name : number,...}
        self._description = None

        # if EOF and BOF are true at the same time, there are no records in the recordset
        if (recordset is None) or (recordset.State == adc.adStateClosed):
            self.rs = None
            self.numberOfColumns = 0
            return
        self.rs = recordset  # v2.1.1 bkline
        self.recordset_format = api.RS_ARRAY if api.onIronPython else api.RS_WIN_32
        self.numberOfColumns = recordset.Fields.Count
        try:
            varCon = self.connection.variantConversions
        except AttributeError:
            varCon = api.variantConversions
        for i in range(self.numberOfColumns):
            f = getIndexedValue(self.rs.Fields, i)
            try:
                self.converters.append(
                    varCon[f.Type]
                )  # conversion function for this column
            except KeyError:
                self._raiseCursorError(
                    api.InternalError, "Data column of Unknown ADO type=%s" % f.Type
                )
            self.columnNames[f.Name.lower()] = i  # columnNames lookup

    def _makeDescriptionFromRS(self):
        # Abort if closed or no recordset.
        if self.rs is None:
            self._description = None
            return
        desc = []
        for i in range(self.numberOfColumns):
            f = getIndexedValue(self.rs.Fields, i)
            if self.rs.EOF or self.rs.BOF:
                display_size = None
            else:
                display_size = (
                    f.ActualSize
                )  # TODO: Is this the correct defintion according to the DB API 2 Spec ?
            null_ok = bool(f.Attributes & adc.adFldMayBeNull)  # v2.1 Cole
            desc.append(
                (
                    f.Name,
                    f.Type,
                    display_size,
                    f.DefinedSize,
                    f.Precision,
                    f.NumericScale,
                    null_ok,
                )
            )
        self._description = desc

    def get_description(self):
        if not self._description:
            self._makeDescriptionFromRS()
        return self._description

    def __getattr__(self, item):
        if item == "description":
            return self.get_description()
        object.__getattribute__(
            self, item
        )  # may get here on Remote attribute calls for existing attributes

    def format_description(self, d):
        """Format db_api description tuple for printing."""
        if self.description is None:
            self._makeDescriptionFromRS()
        if isinstance(d, int):
            d = self.description[d]
        desc = (
            "Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s"
            % (
                d[0],
                adc.adTypeNames.get(d[1], str(d[1]) + " (unknown type)"),
                d[2],
                d[3],
                d[4],
                d[5],
                d[6],
            )
        )
        return desc

    def close(self, dont_tell_me=False):
        """Close the cursor now (rather than whenever __del__ is called).
        The cursor will be unusable from this point forward; an Error (or subclass)
        exception will be raised if any operation is attempted with the cursor.
        """
        if self.connection is None:
            return
        self.messages = []
        if (
            self.rs and self.rs.State != adc.adStateClosed
        ):  # rs exists and is open      #v2.1 Rose
            self.rs.Close()  # v2.1 Rose
            self.rs = None  # let go of the recordset so ADO will let it be disposed #v2.1 Rose
        if not dont_tell_me:
            self.connection._i_am_closing(
                self
            )  # take me off the connection's cursors list
        self.connection = (
            None  # this will make all future method calls on me throw an exception
        )
        if verbose:
            print("adodbapi Closed cursor at %X" % id(self))

    def __del__(self):
        try:
            self.close()
        except:
            pass

    def _new_command(self, command_type=adc.adCmdText):
        self.cmd = None
        self.messages = []

        if self.connection is None:
            self._raiseCursorError(api.InterfaceError, None)
            return
        try:
            self.cmd = Dispatch("ADODB.Command")
            self.cmd.ActiveConnection = self.connection.connector
            self.cmd.CommandTimeout = self.connection.timeout
            self.cmd.CommandType = command_type
            self.cmd.CommandText = self.commandText
            self.cmd.Prepared = bool(self._ado_prepared)
        except:
            self._raiseCursorError(
                api.DatabaseError,
                'Error creating new ADODB.Command object for "%s"'
                % repr(self.commandText),
            )

    def _execute_command(self):
        # Stored procedures may have an integer return value
        self.return_value = None
        recordset = None
        count = -1  # default value
        if verbose:
            print('Executing command="%s"' % self.commandText)
        try:
            # ----- the actual SQL is executed here ---
            if api.onIronPython:
                ra = Reference[int]()
                recordset = self.cmd.Execute(ra)
                count = ra.Value
            else:  # pywin32
                recordset, count = self.cmd.Execute()
            # ----- ------------------------------- ---
        except Exception as e:
            _message = ""
            if hasattr(e, "args"):
                _message += str(e.args) + "\n"
            _message += "Command:\n%s\nParameters:\n%s" % (
                self.commandText,
                format_parameters(self.cmd.Parameters, True),
            )
            klass = self.connection._suggest_error_class()
            self._raiseCursorError(klass, _message)
        try:
            self.rowcount = recordset.RecordCount
        except:
            self.rowcount = count
        self.build_column_info(recordset)

        # The ADO documentation hints that obtaining the recordcount may be timeconsuming
        #   "If the Recordset object does not support approximate positioning, this property
        #    may be a significant drain on resources # [ekelund]
        # Therefore, COM will not return rowcount for server-side cursors. [Cole]
        # Client-side cursors (the default since v2.8) will force a static
        # cursor, and rowcount will then be set accurately [Cole]

    def get_rowcount(self):
        return self.rowcount

    def get_returned_parameters(self):
        """with some providers, returned parameters and the .return_value are not available until
        after the last recordset has been read.  In that case, you must coll nextset() until it
        returns None, then call this method to get your returned information."""

        retLst = (
            []
        )  # store procedures may return altered parameters, including an added "return value" item
        for p in tuple(self.cmd.Parameters):
            if verbose > 2:
                print(
                    'Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s",'
                    " Precision: %s, NumericScale: %s"
                    % (
                        p.Name,
                        adc.directions[p.Direction],
                        adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
                        p.Size,
                        p.Value,
                        p.Precision,
                        p.NumericScale,
                    )
                )
            pyObject = api.convert_to_python(p.Value, api.variantConversions[p.Type])
            if p.Direction == adc.adParamReturnValue:
                self.returnValue = (
                    pyObject  # also load the undocumented attribute (Vernon's Error!)
                )
                self.return_value = pyObject
            else:
                retLst.append(pyObject)
        return retLst  # return the parameter list to the caller

    def callproc(self, procname, parameters=None):
        """Call a stored database procedure with the given name.
        The sequence of parameters must contain one entry for each
        argument that the sproc expects. The result of the
        call is returned as modified copy of the input
        sequence.  Input parameters are left untouched, output and
        input/output parameters replaced with possibly new values.

        The sproc may also provide a result set as output,
        which is available through the standard .fetch*() methods.
        Extension: A "return_value" property may be set on the
        cursor if the sproc defines an integer return value.
        """
        self._parameter_names = []
        self.commandText = procname
        self._new_command(command_type=adc.adCmdStoredProc)
        self._buildADOparameterList(parameters, sproc=True)
        if verbose > 2:
            print(
                "Calling Stored Proc with Params=",
                format_parameters(self.cmd.Parameters, True),
            )
        self._execute_command()
        return self.get_returned_parameters()

    def _reformat_operation(self, operation, parameters):
        if self.paramstyle in ("format", "pyformat"):  # convert %s to ?
            operation, self._parameter_names = api.changeFormatToQmark(operation)
        elif self.paramstyle == "named" or (
            self.paramstyle == "dynamic" and isinstance(parameters, Mapping)
        ):
            operation, self._parameter_names = api.changeNamedToQmark(
                operation
            )  # convert :name to ?
        return operation

    def _buildADOparameterList(self, parameters, sproc=False):
        self.parameters = parameters
        if parameters is None:
            parameters = []

        # Note: ADO does not preserve the parameter list, even if "Prepared" is True, so we must build every time.
        parameters_known = False
        if sproc:  # needed only if we are calling a stored procedure
            try:  # attempt to use ADO's parameter list
                self.cmd.Parameters.Refresh()
                if verbose > 2:
                    print(
                        "ADO detected Params=",
                        format_parameters(self.cmd.Parameters, True),
                    )
                    print("Program Parameters=", repr(parameters))
                parameters_known = True
            except api.Error:
                if verbose:
                    print("ADO Parameter Refresh failed")
                pass
            else:
                if len(parameters) != self.cmd.Parameters.Count - 1:
                    raise api.ProgrammingError(
                        "You must supply %d parameters for this stored procedure"
                        % (self.cmd.Parameters.Count - 1)
                    )
        if sproc or parameters != []:
            i = 0
            if parameters_known:  # use ado parameter list
                if self._parameter_names:  # named parameters
                    for i, pm_name in enumerate(self._parameter_names):
                        p = getIndexedValue(self.cmd.Parameters, i)
                        try:
                            _configure_parameter(
                                p, parameters[pm_name], p.Type, parameters_known
                            )
                        except Exception as e:
                            _message = (
                                "Error Converting Parameter %s: %s, %s <- %s\n"
                                % (
                                    p.Name,
                                    adc.ado_type_name(p.Type),
                                    p.Value,
                                    repr(parameters[pm_name]),
                                )
                            )
                            self._raiseCursorError(
                                api.DataError, _message + "->" + repr(e.args)
                            )
                else:  # regular sequence of parameters
                    for value in parameters:
                        p = getIndexedValue(self.cmd.Parameters, i)
                        if (
                            p.Direction == adc.adParamReturnValue
                        ):  # this is an extra parameter added by ADO
                            i += 1  # skip the extra
                            p = getIndexedValue(self.cmd.Parameters, i)
                        try:
                            _configure_parameter(p, value, p.Type, parameters_known)
                        except Exception as e:
                            _message = (
                                "Error Converting Parameter %s: %s, %s <- %s\n"
                                % (
                                    p.Name,
                                    adc.ado_type_name(p.Type),
                                    p.Value,
                                    repr(value),
                                )
                            )
                            self._raiseCursorError(
                                api.DataError, _message + "->" + repr(e.args)
                            )
                        i += 1
            else:  # -- build own parameter list
                if (
                    self._parameter_names
                ):  # we expect a dictionary of parameters, this is the list of expected names
                    for parm_name in self._parameter_names:
                        elem = parameters[parm_name]
                        adotype = api.pyTypeToADOType(elem)
                        p = self.cmd.CreateParameter(
                            parm_name, adotype, adc.adParamInput
                        )
                        _configure_parameter(p, elem, adotype, parameters_known)
                        try:
                            self.cmd.Parameters.Append(p)
                        except Exception as e:
                            _message = "Error Building Parameter %s: %s, %s <- %s\n" % (
                                p.Name,
                                adc.ado_type_name(p.Type),
                                p.Value,
                                repr(elem),
                            )
                            self._raiseCursorError(
                                api.DataError, _message + "->" + repr(e.args)
                            )
                else:  # expecting the usual sequence of parameters
                    if sproc:
                        p = self.cmd.CreateParameter(
                            "@RETURN_VALUE", adc.adInteger, adc.adParamReturnValue
                        )
                        self.cmd.Parameters.Append(p)

                    for elem in parameters:
                        name = "p%i" % i
                        adotype = api.pyTypeToADOType(elem)
                        p = self.cmd.CreateParameter(
                            name, adotype, adc.adParamInput
                        )  # Name, Type, Direction, Size, Value
                        _configure_parameter(p, elem, adotype, parameters_known)
                        try:
                            self.cmd.Parameters.Append(p)
                        except Exception as e:
                            _message = "Error Building Parameter %s: %s, %s <- %s\n" % (
                                p.Name,
                                adc.ado_type_name(p.Type),
                                p.Value,
                                repr(elem),
                            )
                            self._raiseCursorError(
                                api.DataError, _message + "->" + repr(e.args)
                            )
                        i += 1
                if self._ado_prepared == "setup":
                    self._ado_prepared = (
                        True  # parameters will be "known" by ADO next loop
                    )

    def execute(self, operation, parameters=None):
        """Prepare and execute a database operation (query or command).

        Parameters may be provided as sequence or mapping and will be bound to variables in the operation.
        Variables are specified in a database-specific notation
        (see the module's paramstyle attribute for details). [5]
        A reference to the operation will be retained by the cursor.
        If the same operation object is passed in again, then the cursor
        can optimize its behavior. This is most effective for algorithms
        where the same operation is used, but different parameters are bound to it (many times).

        For maximum efficiency when reusing an operation, it is best to use
        the setinputsizes() method to specify the parameter types and sizes ahead of time.
        It is legal for a parameter to not match the predefined information;
        the implementation should compensate, possibly with a loss of efficiency.

        The parameters may also be specified as list of tuples to e.g. insert multiple rows in
        a single operation, but this kind of usage is depreciated: executemany() should be used instead.

        Return value is not defined.

        [5] The module will use the __getitem__ method of the parameters object to map either positions
        (integers) or names (strings) to parameter values. This allows for both sequences and mappings
        to be used as input.
        The term "bound" refers to the process of binding an input value to a database execution buffer.
        In practical terms, this means that the input value is directly used as a value in the operation.
        The client should not be required to "escape" the value so that it can be used -- the value
        should be equal to the actual database value."""
        if (
            self.command is not operation
            or self._ado_prepared == "setup"
            or not hasattr(self, "commandText")
        ):
            if self.command is not operation:
                self._ado_prepared = False
                self.command = operation
            self._parameter_names = []
            self.commandText = (
                operation
                if (self.paramstyle == "qmark" or not parameters)
                else self._reformat_operation(operation, parameters)
            )
        self._new_command()
        self._buildADOparameterList(parameters)
        if verbose > 3:
            print("Params=", format_parameters(self.cmd.Parameters, True))
        self._execute_command()

    def executemany(self, operation, seq_of_parameters):
        """Prepare a database operation (query or command)
        and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.

            Return values are not defined.
        """
        self.messages = list()
        total_recordcount = 0

        self.prepare(operation)
        for params in seq_of_parameters:
            self.execute(self.command, params)
            if self.rowcount == -1:
                total_recordcount = -1
            if total_recordcount != -1:
                total_recordcount += self.rowcount
        self.rowcount = total_recordcount

    def _fetch(self, limit=None):
        """Fetch rows from the current recordset.

        limit -- Number of rows to fetch, or None (default) to fetch all rows.
        """
        if self.connection is None or self.rs is None:
            self._raiseCursorError(
                api.FetchFailedError, "fetch() on closed connection or empty query set"
            )
            return

        if self.rs.State == adc.adStateClosed or self.rs.BOF or self.rs.EOF:
            return list()
        if limit:  # limit number of rows retrieved
            ado_results = self.rs.GetRows(limit)
        else:  # get all rows
            ado_results = self.rs.GetRows()
        if (
            self.recordset_format == api.RS_ARRAY
        ):  # result of GetRows is a two-dimension array
            length = (
                len(ado_results) // self.numberOfColumns
            )  # length of first dimension
        else:  # pywin32
            length = len(ado_results[0])  # result of GetRows is tuples in a tuple
        fetchObject = api.SQLrows(
            ado_results, length, self
        )  # new object to hold the results of the fetch
        return fetchObject

    def fetchone(self):
        """Fetch the next row of a query result set, returning a single sequence,
        or None when no more data is available.

        An Error (or subclass) exception is raised if the previous call to executeXXX()
        did not produce any result set or no call was issued yet.
        """
        self.messages = []
        result = self._fetch(1)
        if result:  # return record (not list of records)
            return result[0]
        return None

    def fetchmany(self, size=None):
        """Fetch the next set of rows of a query result, returning a list of tuples. An empty sequence is returned when no more rows are available.

        The number of rows to fetch per call is specified by the parameter.
        If it is not given, the cursor's arraysize determines the number of rows to be fetched.
        The method should try to fetch as many rows as indicated by the size parameter.
        If this is not possible due to the specified number of rows not being available,
        fewer rows may be returned.

        An Error (or subclass) exception is raised if the previous call to executeXXX()
        did not produce any result set or no call was issued yet.

        Note there are performance considerations involved with the size parameter.
        For optimal performance, it is usually best to use the arraysize attribute.
        If the size parameter is used, then it is best for it to retain the same value from
        one fetchmany() call to the next.
        """
        self.messages = []
        if size is None:
            size = self.arraysize
        return self._fetch(size)

    def fetchall(self):
        """Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples).

        Note that the cursor's arraysize attribute
        can affect the performance of this operation.
        An Error (or subclass) exception is raised if the previous call to executeXXX()
        did not produce any result set or no call was issued yet.
        """
        self.messages = []
        return self._fetch()

    def nextset(self):
        """Skip to the next available recordset, discarding any remaining rows from the current recordset.

        If there are no more sets, the method returns None. Otherwise, it returns a true
        value and subsequent calls to the fetch methods will return rows from the next result set.

        An Error (or subclass) exception is raised if the previous call to executeXXX()
        did not produce any result set or no call was issued yet.
        """
        self.messages = []
        if self.connection is None or self.rs is None:
            self._raiseCursorError(
                api.OperationalError,
                ("nextset() on closed connection or empty query set"),
            )
            return None

        if api.onIronPython:
            try:
                recordset = self.rs.NextRecordset()
            except TypeError:
                recordset = None
            except api.Error as exc:
                self._raiseCursorError(api.NotSupportedError, exc.args)
        else:  # pywin32
            try:  # [begin 2.1 ekelund]
                rsTuple = self.rs.NextRecordset()  #
            except pywintypes.com_error as exc:  # return appropriate error
                self._raiseCursorError(
                    api.NotSupportedError, exc.args
                )  # [end 2.1 ekelund]
            recordset = rsTuple[0]
        if recordset is None:
            return None
        self.build_column_info(recordset)
        return True

    def setinputsizes(self, sizes):
        pass

    def setoutputsize(self, size, column=None):
        pass

    def _last_query(self):  # let the programmer see what query we actually used
        try:
            if self.parameters == None:
                ret = self.commandText
            else:
                ret = "%s,parameters=%s" % (self.commandText, repr(self.parameters))
        except:
            ret = None
        return ret

    query = property(_last_query, None, None, "returns the last query executed")


if __name__ == "__main__":
    raise api.ProgrammingError(version + " cannot be run as a main program.")