ibm-db /IBM_DB/ibm_db/ibm_db_dbi.py

Language Python Lines 1506
MD5 Hash 7bfa25d02b524dbe4ca46aecc24c021a
Repository http://ibm-db.googlecode.com/svn/trunk/ View Raw File
   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
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
# +--------------------------------------------------------------------------+
# |  Licensed Materials - Property of IBM                                    |
# |                                                                          |
# | (C) Copyright IBM Corporation 2007-2009                                  |
# +--------------------------------------------------------------------------+
# | This module complies with SQLAlchemy 0.4 and is                          |
# | Licensed under the Apache License, Version 2.0 (the "License");          |
# | you may not use this file except in compliance with the License.         |
# | You may obtain a copy of the License at                                  |
# | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable |
# | law or agreed to in writing, software distributed under the License is   |
# | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
# | KIND, either express or implied. See the License for the specific        |
# | language governing permissions and limitations under the License.        |
# +--------------------------------------------------------------------------+
# | Authors: Swetha Patel, Abhigyan Agrawal, Tarun Pasrija, Rahul Priyadarshi|
# +--------------------------------------------------------------------------+

"""
This module implements the Python DB API Specification v2.0 for DB2 database.
"""

import types, string, time, datetime, decimal, sys

if sys.version_info >= (3, ):
   buffer = memoryview
if sys.version_info < (3, ):
   import exceptions
   exception = exceptions.StandardError
else:
   exception = Exception
   
import ibm_db
__version__ = ibm_db.__version__

# Constants for specifying database connection options.
SQL_ATTR_AUTOCOMMIT = ibm_db.SQL_ATTR_AUTOCOMMIT
SQL_ATTR_CURRENT_SCHEMA = ibm_db.SQL_ATTR_CURRENT_SCHEMA
SQL_AUTOCOMMIT_OFF = ibm_db.SQL_AUTOCOMMIT_OFF
SQL_AUTOCOMMIT_ON = ibm_db.SQL_AUTOCOMMIT_ON
ATTR_CASE = ibm_db.ATTR_CASE
CASE_NATURAL = ibm_db.CASE_NATURAL
CASE_LOWER = ibm_db.CASE_LOWER
CASE_UPPER = ibm_db.CASE_UPPER
SQL_FALSE = ibm_db.SQL_FALSE
SQL_TRUE = ibm_db.SQL_TRUE
SQL_TABLE_STAT = ibm_db.SQL_TABLE_STAT
SQL_INDEX_CLUSTERED = ibm_db.SQL_INDEX_CLUSTERED
SQL_INDEX_OTHER = ibm_db.SQL_INDEX_OTHER
SQL_DBMS_VER = ibm_db.SQL_DBMS_VER
SQL_DBMS_NAME = ibm_db.SQL_DBMS_NAME

# Module globals
apilevel = '2.0'
threadsafety = 0
paramstyle = 'qmark'


class Error(exception):
    """This is the base class of all other exception thrown by this
    module.  It can be use to catch all exceptions with a single except
    statement.
    
    """
    def __init__(self, message):
        """This is the constructor which take one string argument."""
        self._message = message
    def __str__(self):
        """Converts the message to a string."""
        return 'ibm_db_dbi::'+str(self.__class__.__name__)+': '+str(self._message)


class Warning(exception):
    """This exception is used to inform the user about important 
    warnings such as data truncations.

    """
    def __init__(self, message):
        """This is the constructor which take one string argument."""
        self._message = message
    def __str__(self):
        """Converts the message to a string."""
        return 'ibm_db_dbi::'+str(self.__class__.__name__)+': '+str(self._message)


class InterfaceError(Error):
    """This exception is raised when the module interface is being
    used incorrectly.

    """
    pass


class DatabaseError(Error):
    """This exception is raised for errors related to database."""
    pass


class InternalError(DatabaseError):
    """This exception is raised when internal database error occurs,
    such as cursor is not valid anymore.

    """
    pass


class OperationalError(DatabaseError):
    """This exception is raised when database operation errors that are
    not under the programmer control occur, such as unexpected
    disconnect.

    """ 
    pass


class ProgrammingError(DatabaseError):
    """This exception is raised for programming errors, such as table 
    not found.

    """
    pass

class IntegrityError(DatabaseError):
    """This exception is thrown when errors occur when the relational
    integrity of database fails, such as foreign key check fails. 

    """
    pass


class  DataError(DatabaseError):
    """This exception is raised when errors due to data processing,
    occur, such as divide by zero. 

    """
    pass


class NotSupportedError(DatabaseError):
    """This exception is thrown when a method in this module or an 
    database API is not supported.

    """
    pass


def Date(year, month, day):
    """This method can be used to get date object from integers, for 
    inserting it into a DATE column in the database.

    """
    return datetime.date(year, month, day)

def Time(hour, minute, second):
    """This method can be used to get time object from integers, for 
    inserting it into a TIME column in the database.

    """
    return datetime.time(hour, minute, second)

def Timestamp(year, month, day, hour, minute, second):
    """This method can be used to get timestamp object from integers, 
    for inserting it into a TIMESTAMP column in the database.

    """
    return datetime.datetime(year, month, day, hour, minute, second)

def DateFromTicks(ticks):
    """This method can be used to get date object from ticks seconds,
    for inserting it into a DATE column in the database.

    """
    time_tuple = time.localtime(ticks)
    return datetime.date(time_tuple[0], time_tuple[1], time_tuple[2])

def TimeFromTicks(ticks):
    """This method can be used to get time object from ticks seconds,
    for inserting it into a TIME column in the database.

    """
    time_tuple = time.localtime(ticks)
    return datetime.time(time_tuple[3], time_tuple[4], time_tuple[5])

def TimestampFromTicks(ticks):
    """This method can be used to get timestamp object from ticks  
    seconds, for inserting it into a TIMESTAMP column in the database.

    """
    time_tuple = time.localtime(ticks)
    return datetime.datetime(time_tuple[0], time_tuple[1], time_tuple[2], 
                                time_tuple[3], time_tuple[4], time_tuple[5])

def Binary(string):
    """This method can be used to store binary information, for 
    inserting it into a binary type column in the database.

    """
    if not isinstance( string, types.StringType):
        raise InterfaceError("Binary function expects type string argument.")
    return buffer(string)


class DBAPITypeObject(frozenset):
    """Class used for creating objects that can be used to compare
    in order to determine the python type to provide in parameter 
    sequence argument of the execute method.

    """
    def __new__(cls, col_types):
        return frozenset.__new__(cls, col_types)
        
    def __init__(self, col_types):
        """Constructor for DBAPITypeObject.  It takes a tuple of 
        database column type as an argument.
        """
        self.col_types = col_types

    def __cmp__(self, cmp):
        """This method checks if the string compared with is in the 
        tuple provided to the constructor of this object.  It takes 
        string as an argument. 
 
        """
        if cmp in self.col_types:
            return 0
        if cmp < self.col_types:
            return 1
        else:
            return -1

# The user can use these objects to compare the database column types
# with in order to determine the python type to provide in the 
# parameter sequence argument of the execute method.
STRING = DBAPITypeObject(("CHARACTER", "CHAR", "VARCHAR", 
                          "CHARACTER VARYING", "CHAR VARYING", "STRING",))

TEXT = DBAPITypeObject(("CLOB", "CHARACTER LARGE OBJECT", "CHAR LARGE OBJECT",))

XML = DBAPITypeObject(("XML",))

BINARY = DBAPITypeObject(("BLOB", "BINARY LARGE OBJECT",))

NUMBER = DBAPITypeObject(("INTEGER", "INT", "SMALLINT",))

BIGINT = DBAPITypeObject(("BIGINT",))

FLOAT = DBAPITypeObject(("FLOAT", "REAL", "DOUBLE", "DECFLOAT"))

DECIMAL = DBAPITypeObject(("DECIMAL", "DEC", "NUMERIC", "NUM",))

DATE = DBAPITypeObject(("DATE",))

TIME = DBAPITypeObject(("TIME",))

DATETIME = DBAPITypeObject(("TIMESTAMP",))

ROWID = DBAPITypeObject(())

# This method is used to determine the type of error that was 
# generated.  It takes an exception instance as an argument, and 
# returns exception object of the appropriate type.
def _get_exception(inst):
    # These tuple are used to determine the type of exceptions that are
    # thrown by the database.  They store the SQLSTATE code and the
    # SQLSTATE class code(the 2 digit prefix of the SQLSTATE code)  
    warning_error_tuple = ('01', )
    data_error_tuple = ('02', '22', '10601', '10603', '10605', '10901', '10902', 
                                                               '38552', '54')

    operational_error_tuple = ( '08', '09', '10502', '10000', '10611', '38501', 
                          '38503', '38553', '38H01', '38H02', '38H03', '38H04',
                                   '38H05', '38H06', '38H07', '38H09', '38H0A')

    integrity_error_tuple = ('23', )

    internal_error_tuple = ('24', '25', '26', '2D', '51', '57')

    programming_error_tuple = ('08002', '07', 'OD', 'OF','OK','ON','10', '27',
                               '28', '2E', '34', '36', '38', '39', '56', '42',
                               '3B', '40', '44', '53', '55', '58', '5U', '21')

    not_supported_error_tuple = ('0A', '10509')

    # These tuple are used to determine the type of exceptions that are
    # thrown from the driver module. 
    interface_exceptions = (                  "Supplied parameter is invalid",
                                        "ATTR_CASE attribute must be one of "
                                    "CASE_LOWER, CASE_UPPER, or CASE_NATURAL",
                          "Connection or statement handle must be passed in.",
                                                       "Param is not a tuple")

    programming_exceptions = (                     "Connection is not active", 
                                                 "qualifier must be a string",
                                                   "unique must be a boolean",
                                                       "Parameters not bound",
                                                     "owner must be a string",
                                                "table_name must be a string",
                                                "table type must be a string", 
                                               "column_name must be a string", 
                                                "Column ordinal out of range", 
                                            "procedure name must be a string",
                              "Requested row number must be a positive value", 
                                     "Options Array must have string indexes")

    database_exceptions = (                                   "Binding Error", 
                                   "Column information cannot be retrieved: ", 
                                            "Column binding cannot be done: ",
                                             "Failed to Determine XML Size: ")

    statement_exceptions = (                     "Statement Execute Failed: ",
                                                    "Describe Param Failed: ",
                                                      "Sending data failed: ",
                                                            "Fetch Failure: ",
                                                  "SQLNumResultCols failed: ",
                                                       "SQLRowCount failed: ",
                                                   "SQLGetDiagField failed: ",
                                                 "Statement prepare Failed: ")

    operational_exceptions = (          "Connection Resource cannot be found", 
                                                  "Failed to Allocate Memory",
                                                    "Describe Param Failed: ",
                                                 "Statement Execute Failed: ",
                                                      "Sending data failed: ", 
                                     "Failed to Allocate Memory for XML Data",
                                     "Failed to Allocate Memory for LOB Data")

    # First check if the exception is from the database.  If it is 
    # determine the SQLSTATE code which is used further to determine 
    # the exception type.  If not check if the exception is thrown by 
    # by the driver and return the appropriate exception type.  If it 
    # is not possible to determine the type of exception generated 
    # return the generic Error exception.
    if inst is not None:
        message = repr(inst)
        if message.startswith("Exception('") and message.endswith("',)"):
            message = message[11:]
            message = message[:len(message)-3]

        index = message.find('SQLSTATE=')
        if( message != '') & (index != -1):
            error_code = message[(index+9):(index+14)]
            prefix_code = error_code[:2]
        else:
            for key in interface_exceptions:
                if message.find(key) != -1:
                    return InterfaceError(message)
            for key in programming_exceptions:
                if message.find(key) != -1:
                    return ProgrammingError(message)
            for key in operational_exceptions:
                if message.find(key) != -1:
                    return OperationalError(message)
            for key in database_exceptions:
                if message.find(key) != -1:
                    return DatabaseError(message)  
            for key in statement_exceptions:
                if message.find(key) != -1:
                    return DatabaseError(message)
            return Error(message)
    else:
        return Error('An error has occured')

    # First check if the SQLSTATE is in the tuples, if not check
    # if the SQLSTATE class code is in the tuples to determine the
    # exception type. 
    if ( error_code in warning_error_tuple or 
         prefix_code in warning_error_tuple ):
        return Warning(message)
    if ( error_code in data_error_tuple or 
         prefix_code in data_error_tuple ):
        return DataError(message)
    if ( error_code in operational_error_tuple or 
         prefix_code in operational_error_tuple ):
        return OperationalError(message)
    if ( error_code in integrity_error_tuple or 
         prefix_code in integrity_error_tuple ):
        return IntegrityError(message)
    if ( error_code in internal_error_tuple or
         prefix_code in internal_error_tuple ):
        return InternalError(message)
    if ( error_code in programming_error_tuple or
         prefix_code in programming_error_tuple ):
        return ProgrammingError(message)
    if ( error_code in not_supported_error_tuple or
         prefix_code in not_supported_error_tuple ):
        return NotSupportedError(message)
    return DatabaseError(message)

def _server_connect(dsn, user='', password='', host=''):
    """This method create connection with server
    """
    
    if dsn is None:
        raise InterfaceError("dsn value should not be None")
    
    if (not isinstance(dsn, basestring)) | \
       (not isinstance(user, basestring)) | \
       (not isinstance(password, basestring)) | \
       (not isinstance(host, basestring)):
        raise InterfaceError("Arguments should be of type string or unicode")
    
    # If the dsn does not contain port and protocal adding database
    # and hostname is no good.  Add these when required, that is,
    # if there is a '=' in the dsn.  Else the dsn string is taken to be
    # a DSN entry.
    if dsn.find('=') != -1:
        if dsn[len(dsn) - 1] != ';':
            dsn = dsn + ";"
        if host != '' and dsn.find('HOSTNAME=') == -1:
            dsn = dsn + "HOSTNAME=" + host + ";"
    else:
        dsn = "DSN=" + dsn + ";"

    if dsn.find('attach=') == -1:
        dsn = dsn + "attach=true;"
    if user != '' and dsn.find('UID=') == -1:
        dsn = dsn + "UID=" + user + ";"
    if password != '' and dsn.find('PWD=') == -1:
        dsn = dsn + "PWD=" + password + ";"
    try:    
        conn = ibm_db.connect(dsn, '', '')
    except Exception, inst:
        raise _get_exception(inst)
    
    return conn
    
def createdb(database, dsn, user='', password='', host='', codeset='', mode=''):
    """This method creates a database by using the specified database name, code set, and mode
    """
    
    if database is None:
        raise InterfaceError("createdb expects a not None database name value")
    if (not isinstance(database, basestring)) | \
       (not isinstance(codeset, basestring)) | \
       (not isinstance(mode, basestring)):
        raise InterfaceError("Arguments sould be string or unicode")
        
    conn = _server_connect(dsn, user=user, password=password, host=host)
    try:
        return_value = ibm_db.createdb(conn, database, codeset, mode)
    except Exception, inst:
        raise _get_exception(inst)
    finally:
        try:
            ibm_db.close(conn)
        except Exception, inst:
            raise _get_exception(inst)
        
    return return_value
    
def dropdb(database, dsn, user='', password='', host=''):
    """This method drops the specified database
    """
    
    if database is None:
        raise InterfaceError("dropdb expects a not None database name value")
    if (not isinstance(database, basestring)):
        raise InterfaceError("Arguments sould be string or unicode")
        
    conn = _server_connect(dsn, user=user, password=password, host=host)
    try:
        return_value = ibm_db.dropdb(conn, database)
    except Exception, inst:
        raise _get_exception(inst)
    finally:
        try:
            ibm_db.close(conn)
        except Exception, inst:
            raise _get_exception(inst)
        
    return return_value
    
def recreatedb(database, dsn, user='', password='', host='', codeset='', mode=''):
    """This method drops and then recreate the database by using the specified database name, code set, and mode
    """
    
    if database is None:
        raise InterfaceError("recreatedb expects a not None database name value")
    if (not isinstance(database, basestring)) | \
       (not isinstance(codeset, basestring)) | \
       (not isinstance(mode, basestring)):
        raise InterfaceError("Arguments sould be string or unicode")
        
    conn = _server_connect(dsn, user=user, password=password, host=host)
    try:
        return_value = ibm_db.recreatedb(conn, database, codeset, mode)
    except Exception, inst:
        raise _get_exception(inst)
    finally:
        try:
            ibm_db.close(conn)
        except Exception, inst:
            raise _get_exception(inst)
        
    return return_value
    
def createdbNX(database, dsn, user='', password='', host='', codeset='', mode=''):
    """This method creates a database if it not exist by using the specified database name, code set, and mode
    """
    
    if database is None:
        raise InterfaceError("createdbNX expects a not None database name value")
    if (not isinstance(database, basestring)) | \
       (not isinstance(codeset, basestring)) | \
       (not isinstance(mode, basestring)):
        raise InterfaceError("Arguments sould be string or unicode")
        
    conn = _server_connect(dsn, user=user, password=password, host=host)
    try:
        return_value = ibm_db.createdbNX(conn, database, codeset, mode)
    except Exception, inst:
        raise _get_exception(inst)
    finally:
        try:
            ibm_db.close(conn)
        except Exception, inst:
            raise _get_exception(inst)
        
    return return_value
    
def connect(dsn, user='', password='', host='', database='', conn_options=None):
    """This method creates a non persistent connection to the database. It returns
        a ibm_db_dbi.Connection object.
    """
    
    if dsn is None:
        raise InterfaceError("connect expects a not None dsn value") 
    
    if (not isinstance(dsn, basestring)) | \
       (not isinstance(user, basestring)) | \
       (not isinstance(password, basestring)) | \
       (not isinstance(host, basestring)) | \
       (not isinstance(database, basestring)):
        raise InterfaceError("connect expects the first five arguments to"
                                                      " be of type string or unicode")
    if conn_options is not None:
        if not isinstance(conn_options, dict):
            raise InterfaceError("connect expects the sixth argument"
                                 " (conn_options) to be of type dict")
        if not SQL_ATTR_AUTOCOMMIT in conn_options:
            conn_options[SQL_ATTR_AUTOCOMMIT] = SQL_AUTOCOMMIT_OFF
    else:
        conn_options = {SQL_ATTR_AUTOCOMMIT : SQL_AUTOCOMMIT_OFF}

    # If the dsn does not contain port and protocal adding database
    # and hostname is no good.  Add these when required, that is,
    # if there is a '=' in the dsn.  Else the dsn string is taken to be
    # a DSN entry.
    if dsn.find('=') != -1:
        if dsn[len(dsn) - 1] != ';':
            dsn = dsn + ";"
        if database != '' and dsn.find('DATABASE=') == -1:
            dsn = dsn + "DATABASE=" + database + ";"
        if host != '' and dsn.find('HOSTNAME=') == -1:
            dsn = dsn + "HOSTNAME=" + host + ";"
    else:
        dsn = "DSN=" + dsn + ";"

    if user != '' and dsn.find('UID=') == -1:
        dsn = dsn + "UID=" + user + ";"
    if password != '' and dsn.find('PWD=') == -1:
        dsn = dsn + "PWD=" + password + ";"
    try:    
        conn = ibm_db.connect(dsn, '', '', conn_options)
        ibm_db.set_option(conn, {SQL_ATTR_CURRENT_SCHEMA : user}, 1)
    except Exception, inst:
        raise _get_exception(inst)

    return Connection(conn)

def pconnect(dsn, user='', password='', host='', database='', conn_options=None):
    """This method creates persistent connection to the database. It returns
        a ibm_db_dbi.Connection object.
    """
    
    if dsn is None:
        raise InterfaceError("connect expects a not None dsn value") 
    
    if (not isinstance(dsn, basestring)) | \
       (not isinstance(user, basestring)) | \
       (not isinstance(password, basestring)) | \
       (not isinstance(host, basestring)) | \
       (not isinstance(database, basestring)):
        raise InterfaceError("connect expects the first five arguments to"
                                                      " be of type string or unicode")
    if conn_options is not None:
        if not isinstance(conn_options, dict):
            raise InterfaceError("connect expects the sixth argument"
                                 " (conn_options) to be of type dict")
        if not SQL_ATTR_AUTOCOMMIT in conn_options:
            conn_options[SQL_ATTR_AUTOCOMMIT] = SQL_AUTOCOMMIT_OFF
    else:
        conn_options = {SQL_ATTR_AUTOCOMMIT : SQL_AUTOCOMMIT_OFF}

    # If the dsn does not contain port and protocal adding database
    # and hostname is no good.  Add these when required, that is,
    # if there is a '=' in the dsn.  Else the dsn string is taken to be
    # a DSN entry.
    if dsn.find('=') != -1:
        if dsn[len(dsn) - 1] != ';':
            dsn = dsn + ";"
        if database != '' and dsn.find('DATABASE=') == -1:
            dsn = dsn + "DATABASE=" + database + ";"
        if host != '' and dsn.find('HOSTNAME=') == -1:
            dsn = dsn + "HOSTNAME=" + host + ";"
    else:
        dsn = "DSN=" + dsn + ";"

    if user != '' and dsn.find('UID=') == -1:
        dsn = dsn + "UID=" + user + ";"
    if password != '' and dsn.find('PWD=') == -1:
        dsn = dsn + "PWD=" + password + ";"
    try:    
        conn = ibm_db.pconnect(dsn, '', '', conn_options)
        ibm_db.set_option(conn, {SQL_ATTR_CURRENT_SCHEMA : user}, 1)
    except Exception, inst:
        raise _get_exception(inst)

    return Connection(conn)

class Connection(object):
    """This class object represents a connection between the database 
    and the application.

    """
    def __init__(self, conn_handler):
        """Constructor for Connection object. It takes ibm_db 
        connection handler as an argument. 

        """
        self.conn_handler = conn_handler

        # Used to identify close cursors for generating exceptions 
        # after the connection is closed.
        self._cursor_list = []
        self.__dbms_name = ibm_db.get_db_info(conn_handler, SQL_DBMS_NAME)
        self.__dbms_ver = ibm_db.get_db_info(conn_handler, SQL_DBMS_VER)

    # This method is used to get the DBMS_NAME 
    def __get_dbms_name( self ):
        return self.__dbms_name

    # This attribute specifies the DBMS_NAME
    # It is a read only attribute. 
    dbms_name = property(__get_dbms_name, None, None, "")

    # This method is used to get the DBMS_ver 
    def __get_dbms_ver( self ):
        return self.__dbms_ver

    # This attribute specifies the DBMS_ver
    # It is a read only attribute. 
    dbms_ver = property(__get_dbms_ver, None, None, "")

    def close(self):
        """This method closes the Database connection associated with
        the Connection object.  It takes no arguments.

        """
        self.rollback()
        try:
            if self.conn_handler is None:
                raise ProgrammingError("Connection cannot be closed; "
                                     "connection is no longer active.")
            else:
                return_value = ibm_db.close(self.conn_handler)
        except Exception, inst:
            raise _get_exception(inst)
        self.conn_handler = None
        for index in range(len(self._cursor_list)):
            self._cursor_list[index].conn_handler = None
            self._cursor_list[index].stmt_handler = None
            self._cursor_list[index]._all_stmt_handlers = None
        return return_value

    def commit(self):
        """This method commits the transaction associated with the
        Connection object.  It takes no arguments.

        """
        try:
            return_value = ibm_db.commit(self.conn_handler)
        except Exception, inst:
            raise _get_exception(inst)
        return return_value

    def rollback(self):
        """This method rollbacks the transaction associated with the
        Connection object.  It takes no arguments.

        """
        try:
            return_value = ibm_db.rollback(self.conn_handler)
        except Exception, inst:
            raise _get_exception(inst)
        return return_value

    def cursor(self):
        """This method returns a Cursor object associated with the 
        Connection.  It takes no arguments.

        """
        if self.conn_handler is None:
            raise ProgrammingError("Cursor cannot be returned; "
                               "connection is no longer active.")
        cursor = Cursor(self.conn_handler, self)
        self._cursor_list.append(cursor)
        return cursor

    # Sets connection attribute values
    def set_option(self, attr_dict):
        """Input: connection attribute dictionary
           Return: True on success or False on failure
        """
        return ibm_db.set_option(self.conn_handler, attr_dict, 1)

    # Retrieves connection attributes values
    def get_option(self, attr_key):
        """Input: connection attribute key
           Return: current setting of the resource attribute requested
        """
        return ibm_db.get_option(self.conn_handler, attr_key, 1)

    # Sets connection AUTOCOMMIT attribute
    def set_autocommit(self, is_on):
        """Input: connection attribute: true if AUTOCOMMIT ON, false otherwise (i.e. OFF)
           Return: True on success or False on failure
        """
        try:
          if is_on:
            is_set = ibm_db.set_option(self.conn_handler, {SQL_ATTR_AUTOCOMMIT : SQL_AUTOCOMMIT_ON}, 1)
          else:
            is_set = ibm_db.set_option(self.conn_handler, {SQL_ATTR_AUTOCOMMIT : SQL_AUTOCOMMIT_OFF}, 1)
        except Exception, inst:
          raise _get_exception(inst)
        return is_set

    # Sets connection attribute values
    def set_current_schema(self, schema_name):
        """Input: connection attribute dictionary
           Return: True on success or False on failure
        """
        self.current_schema = schema_name
        try:
          is_set = ibm_db.set_option(self.conn_handler, {SQL_ATTR_CURRENT_SCHEMA : schema_name}, 1)
        except Exception, inst:
          raise _get_exception(inst)
        return is_set

    # Retrieves connection attributes values
    def get_current_schema(self):
        """Return: current setting of the schema attribute
        """
        try:
          conn_schema = ibm_db.get_option(self.conn_handler, SQL_ATTR_CURRENT_SCHEMA, 1)
          if conn_schema is not None and conn_schema != '':
            self.current_schema = conn_schema
        except Exception, inst:
          raise _get_exception(inst)
        return self.current_schema

    # Retrieves the IBM Data Server version for a given Connection object
    def server_info(self):
        """Return: tuple (DBMS_NAME, DBMS_VER)
        """
        try:
          server_info = []
          server_info.append(self.dbms_name)
          server_info.append(self.dbms_ver)
        except Exception, inst:
          raise _get_exception(inst)
        return tuple(server_info)
    
    def set_case(self, server_type, str_value):
        return str_value.upper()

    # Retrieves the tables for a specified schema (and/or given table name)
    def tables(self, schema_name=None, table_name=None):
        """Input: connection - ibm_db.IBM_DBConnection object
           Return: sequence of table metadata dicts for the specified schema
        """
            
        result = []
        if schema_name is not None:
            schema_name = self.set_case("DB2_LUW", schema_name)
        if table_name is not None:
            table_name = self.set_case("DB2_LUW", table_name)

        try:      
          stmt = ibm_db.tables(self.conn_handler, None, schema_name, table_name)
          row = ibm_db.fetch_assoc(stmt)
          i = 0
          while (row):
              result.append( row )
              i += 1    
              row = ibm_db.fetch_assoc(stmt)
          ibm_db.free_result(stmt)
        except Exception, inst:
          raise _get_exception(inst)

        return result

    # Retrieves metadata pertaining to index for specified schema (and/or table name)
    def indexes(self, unique=True, schema_name=None, table_name=None):
        """Input: connection - ibm_db.IBM_DBConnection object
           Return: sequence of index metadata dicts for the specified table
        Example:
           Index metadata retrieved from schema 'PYTHONIC.TEST_TABLE' table
           {
           'TABLE_SCHEM':       'PYTHONIC',              'TABLE_CAT':          None, 
           'TABLE_NAME':        'ENGINE_USERS',          'PAGES':              None, 
           'COLUMN_NAME':       'USER_ID'                'FILTER_CONDITION':   None, 
           'INDEX_NAME':        'SQL071201150750170',    'CARDINALITY':        None,
           'ORDINAL_POSITION':   1,                      'INDEX_QUALIFIER':   'SYSIBM', 
           'TYPE':               3, 
           'NON_UNIQUE':         0, 
           'ASC_OR_DESC':       'A'
           }
        """
        result = []
        if schema_name is not None:
            schema_name = self.set_case("DB2_LUW", schema_name)
        if table_name is not None:
            table_name = self.set_case("DB2_LUW", table_name)

        try:
          stmt = ibm_db.statistics(self.conn_handler, None, schema_name, table_name, unique)
          row = ibm_db.fetch_assoc(stmt)
          i = 0
          while (row):
              if row['TYPE'] == SQL_INDEX_OTHER:
                  result.append( row )
              i += 1    
              row = ibm_db.fetch_assoc(stmt)
          ibm_db.free_result(stmt)
        except Exception, inst:
          raise _get_exception(inst)

        return result        

    # Retrieves metadata pertaining to primary keys for specified schema (and/or table name)
    def primary_keys(self, unique=True, schema_name=None, table_name=None):
        """Input: connection - ibm_db.IBM_DBConnection object
           Return: sequence of PK metadata dicts for the specified table
        Example:
           PK metadata retrieved from 'PYTHONIC.ORDERS' table
           {  
           'TABLE_SCHEM':  'PYTHONIC',                 'TABLE_CAT': None, 
           'TABLE_NAME':   'ORDERS', 
           'COLUMN_NAME':  'ORDER_ID'
           'PK_NAME':      'SQL071128122038680', 
           'KEY_SEQ':       1
           }
        """
        result = []
        if schema_name is not None:
            schema_name = self.set_case("DB2_LUW", schema_name)
        if table_name is not None:
            table_name = self.set_case("DB2_LUW", table_name)

        try:
          stmt = ibm_db.primary_keys(self.conn_handler, None, schema_name, table_name)
          row = ibm_db.fetch_assoc(stmt)
          i = 0
          while (row):
              result.append( row )
              i += 1    
              row = ibm_db.fetch_assoc(stmt)
          ibm_db.free_result(stmt)
        except Exception, inst:
          raise _get_exception(inst)

        return result        

    # Retrieves metadata pertaining to foreign keys for specified schema (and/or table name)
    def foreign_keys(self, unique=True, schema_name=None, table_name=None):
        """Input: connection - ibm_db.IBM_DBConnection object
           Return: sequence of FK metadata dicts for the specified table
        Example:
           FK metadata retrieved from 'PYTHONIC.ENGINE_EMAIL_ADDRESSES' table
           {  
           'PKTABLE_SCHEM': 'PYTHONIC',                 'PKTABLE_CAT':    None, 
           'PKTABLE_NAME':  'ENGINE_USERS',             'FKTABLE_CAT':    None,
           'PKCOLUMN_NAME': 'USER_ID',                  'UPDATE_RULE':    3,
           'PK_NAME':       'SQL071205090958680',       'DELETE_RULE':    3
           'KEY_SEQ':        1,                         'DEFERRABILITY':  7, 
           'FK_NAME':       'SQL071205091000160', 
           'FKCOLUMN_NAME': 'REMOTE_USER_ID', 
           'FKTABLE_NAME':  'ENGINE_EMAIL_ADDRESSES', 
           'FKTABLE_SCHEM': 'PYTHONIC' 
           }
        """
        result = []
        if schema_name is not None:
            schema_name = self.set_case("DB2_LUW", schema_name)
        if table_name is not None:
            table_name = self.set_case("DB2_LUW", table_name)

        try:
          stmt = ibm_db.foreign_keys(self.conn_handler, None, None, None, None, schema_name, table_name)
          row = ibm_db.fetch_assoc(stmt)
          i = 0
          while (row):
              result.append( row )
              i += 1    
              row = ibm_db.fetch_assoc(stmt)
          ibm_db.free_result(stmt)
        except Exception, inst:
          raise _get_exception(inst)

        return result        
    
    # Retrieves the columns for a specified schema (and/or table name and column name)
    def columns(self, schema_name=None, table_name=None, column_names=None):
        """Input: connection - ibm_db.IBM_DBConnection object
           Return: sequence of column metadata dicts for the specified schema
        Example:
           Column metadata retrieved from schema 'PYTHONIC.FOO' table, column 'A'
           {
           'TABLE_NAME':        'FOO',        'NULLABLE':           1, 
           'ORDINAL_POSITION':   2L,          'REMARKS':            None, 
           'COLUMN_NAME':       'A',          'BUFFER_LENGTH':      30L, 
           'TYPE_NAME':         'VARCHAR',    'SQL_DATETIME_SUB':   None, 
           'COLUMN_DEF':         None,        'DATA_TYPE':          12, 
           'IS_NULLABLE':       'YES',        'SQL_DATA_TYPE':      12, 
           'COLUMN_SIZE':        30L,         'TABLE_CAT':          None, 
           'CHAR_OCTET_LENGTH':  30L,         'TABLE_SCHEM':       'PYTHONIC',
           'NUM_PREC_RADIX':     None,
           'DECIMAL_DIGITS':     None
           }
        """
        result = []
        if schema_name is not None:
          schema_name = self.set_case("DB2_LUW", schema_name)
        if table_name is not None:
          table_name = self.set_case("DB2_LUW", table_name)

        try:
          stmt = ibm_db.columns(self.conn_handler, None, schema_name, table_name)
          row = ibm_db.fetch_assoc(stmt)
          i = 0
          while (row):
            result.append( row )
            i += 1    
            row = ibm_db.fetch_assoc(stmt)
          ibm_db.free_result(stmt)

          col_names_lower = []
          if column_names is not None:
            for name in column_names:
              col_names_lower.append(name.lower())
            include_columns = []
            if column_names and column_names != '':
              for column in result:
                if column['COLUMN_NAME'].lower() in col_names_lower:
                  column['COLUMN_NAME'] = column['COLUMN_NAME'].lower()
                  include_columns.append(column)
              result = include_columns
        except Exception, inst:
          raise _get_exception(inst)

        return result


# Defines a cursor for the driver connection
class Cursor(object):
    """This class represents a cursor of the connection.  It can be
    used to process an SQL statement.
    """
    
    # This method is used to get the description attribute.
    def __get_description(self):
        """ If this method has already been called, after executing a select statement,
            return the stored information in the self.__description.
        """
        if self.__description is not None:
            return self.__description 

        if self.stmt_handler is None:
            return None
        self.__description = []
        
        try:
            num_columns = ibm_db.num_fields(self.stmt_handler)
            """ If the execute statement did not produce a result set return None.
            """
            if num_columns == False:
                self.__description = None
                return None
            for column_index in range(num_columns):
                column_desc = []
                column_desc.append(ibm_db.field_name(self.stmt_handler,
                                                          column_index))
                type = ibm_db.field_type(self.stmt_handler, column_index)
                type = type.upper()
                if STRING.__cmp__(type) == 0:
                    column_desc.append(STRING)
                elif TEXT.__cmp__(type) == 0:
                    column_desc.append(TEXT)
                elif XML.__cmp__(type) == 0:
                    column_desc.append(XML)
                elif BINARY.__cmp__(type) == 0:
                    column_desc.append(BINARY)
                elif NUMBER.__cmp__(type) == 0:
                    column_desc.append(NUMBER)
                elif BIGINT.__cmp__(type) == 0:
                    column_desc.append(BIGINT) 
                elif FLOAT.__cmp__(type) == 0:
                    column_desc.append(FLOAT)                
                elif DECIMAL.__cmp__(type) == 0:
                    column_desc.append(DECIMAL)
                elif DATE.__cmp__(type) == 0:
                    column_desc.append(DATE)
                elif TIME.__cmp__(type) == 0:
                    column_desc.append(TIME)
                elif DATETIME.__cmp__(type) == 0:
                    column_desc.append(DATETIME)
                elif ROWID.__cmp__(type) == 0:
                    column_desc.append(ROWID)

                column_desc.append(ibm_db.field_display_size(
                                             self.stmt_handler, column_index))

                column_desc.append(ibm_db.field_display_size(
                                             self.stmt_handler, column_index))
                
                column_desc.append(ibm_db.field_precision(
                                             self.stmt_handler, column_index))

                column_desc.append(ibm_db.field_scale(self.stmt_handler,
                                                                column_index))

                column_desc.append(None)
                self.__description.append(column_desc)
        except Exception, inst:
            self.messages.append(_get_exception(inst))
            raise self.messages[len(self.messages) - 1]

        return self.__description

    # This attribute provides the metadata information of the columns  
    # in the result set produced by the last execute function.  It is
    # a read only attribute.
    description = property(fget = __get_description)

    # This method is used to get the rowcount attribute. 
    def __get_rowcount( self ):
        return self.__rowcount

    # This attribute specifies the number of rows the last executeXXX()
    # produced or affected.  It is a read only attribute. 
    rowcount = property(__get_rowcount, None, None, "")
    
    # This method is used to get the Connection object
    def __get_connection( self ):
        return self.__connection
    
    # This attribute specifies the connection object.
    # It is a read only attribute. 
    connection = property(__get_connection, None, None, "")

    def __init__(self, conn_handler, conn_object=None):
        """Constructor for Cursor object. It takes ibm_db connection
        handler as an argument.
        """
        
        # This attribute is used to determine the fetch size for fetchmany
        # operation. It is a read/write attribute
        self.arraysize = 1
        self.__rowcount = -1
        self._result_set_produced = False
        self.__description = None
        self.conn_handler = conn_handler
        self.stmt_handler = None
        self._is_scrollable_cursor = False
        self.__connection = conn_object
        self.messages = []
    
    # This method closes the statemente associated with the cursor object.
    # It takes no argument.
    def close(self):
        """This method closes the cursor object.  After this method is 
        called the cursor object is no longer usable.  It takes no
        arguments.

        """
        messages = []
        if self.conn_handler is None:
            self.messages.append(ProgrammingError("Cursor cannot be closed; connection is no longer active."))
            raise self.messages[len(self.messages) - 1]
        try:
            return_value = ibm_db.free_stmt(self.stmt_handler)
        except Exception, inst:
            self.messages.append(_get_exception(inst))
            raise self.messages[len(self.messages) - 1]
        self.stmt_handler = None
        self.conn_handler = None
        self._all_stmt_handlers = None
        if self.__connection is not None:
            try:
                self.__connection._cursor_list.remove(self)
            except:
                pass
        return return_value

    # helper for calling procedure
    def _callproc_helper(self, procname, parameters=None):
        if parameters is not None:
            buff = []
            CONVERT_STR = (datetime.datetime, datetime.date, datetime.time, buffer)
            # Convert date/time and binary objects to string for 
            # inserting into the database. 
            for param in parameters:
                if isinstance(param, CONVERT_STR):
                    param = str(param)
                buff.append(param)
            parameters = tuple(buff)
            
            try:
                result = ibm_db.callproc(self.conn_handler, procname,parameters)
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                raise self.messages[len(self.messages) - 1]
        else:
            try:
                result = ibm_db.callproc(self.conn_handler, procname)
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                raise self.messages[len(self.messages) - 1]
        return result
       

    def callproc(self, procname, parameters=None):
        """This method can be used to execute a stored procedure.  
        It takes the name of the stored procedure and the parameters to
        the stored procedure as arguments. 

        """
        self.messages = []
        if not isinstance(procname, basestring):
            self.messages.append(InterfaceError("callproc expects the first argument to be of type String or Unicode."))
            raise self.messages[len(self.messages) - 1]
        if parameters is not None:
            if not isinstance(parameters, (types.ListType, types.TupleType)):
                self.messages.append(InterfaceError("callproc expects the second argument to be of type list or tuple."))
                raise self.messages[len(self.messages) - 1]
        result = self._callproc_helper(procname, parameters)
        return_value = None
        self.__description = None
        self._all_stmt_handlers = []
        if isinstance(result, types.TupleType):
            self.stmt_handler = result[0]
            return_value = result[1:]
        else:
            self.stmt_handler = result
        self._result_set_produced = True
        return return_value

    # Helper for preparing an SQL statement. 
    def _prepare_helper(self, operation, parameters=None):
        try:
            ibm_db.free_stmt(self.stmt_handler)
        except:
            pass

        try:
            self.stmt_handler = ibm_db.prepare(self.conn_handler, operation)
        except Exception, inst:
            self.messages.append(_get_exception(inst))
            raise self.messages[len(self.messages) - 1]

    # Helper for preparing an SQL statement.
    def _set_cursor_helper(self):
        if (ibm_db.get_option(self.stmt_handler, ibm_db.SQL_ATTR_CURSOR_TYPE, 0) != ibm_db.SQL_CURSOR_FORWARD_ONLY):
            self._is_scrollable_cursor = True
        else:
            self._is_scrollable_cursor = False
        self._result_set_produced = False
        try:
            num_columns = ibm_db.num_fields(self.stmt_handler)
        except Exception, inst:
            self.messages.append(_get_exception(inst))
            raise self.messages[len(self.messages) - 1]
        if not num_columns:
            return True
        self._result_set_produced = True

        return True

    # Helper for executing an SQL statement.
    def _execute_helper(self, parameters=None):
        if parameters is not None:
            buff = []
            CONVERT_STR = (datetime.datetime, datetime.date, datetime.time, buffer)
            # Convert date/time and binary objects to string for 
            # inserting into the database. 
            for param in parameters:
                if isinstance(param, CONVERT_STR):
                    param = str(param)
                buff.append(param)
            parameters = tuple(buff)
            try:                
                return_value = ibm_db.execute(self.stmt_handler, parameters)
                if not return_value:
                    if ibm_db.conn_errormsg() is not None:
                        self.messages.append(Error(str(ibm_db.conn_errormsg())))
                        raise self.messages[len(self.messages) - 1]
                    if ibm_db.stmt_errormsg() is not None:
                        self.messages.append(Error(str(ibm_db.stmt_errormsg())))
                        raise self.messages[len(self.messages) - 1]
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                raise self.messages[len(self.messages) - 1]
        else:
            try:
                return_value = ibm_db.execute(self.stmt_handler)
                if not return_value:
                    if ibm_db.conn_errormsg() is not None:
                        self.messages.append(Error(str(ibm_db.conn_errormsg())))
                        raise self.messages[len(self.messages) - 1]
                    if ibm_db.stmt_errormsg() is not None:
                        self.messages.append(Error(str(ibm_db.stmt_errormsg())))
                        raise self.messages[len(self.messages) - 1]
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                raise self.messages[len(self.messages) - 1]
        return return_value

    # This method is used to set the rowcount after executing an SQL 
    # statement. 
    def _set_rowcount(self):
        self.__rowcount = -1
        if not self._result_set_produced:
            try:
                counter = ibm_db.num_rows(self.stmt_handler)
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                raise self.messages[len(self.messages) - 1]
            self.__rowcount = counter
        elif self._is_scrollable_cursor:
            try:
                counter = ibm_db.get_num_result(self.stmt_handler)
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                raise self.messages[len(self.messages) - 1]
            if counter >= 0:
                self.__rowcount = counter
        return True

    # Retrieves the last generated identity value from the DB2 catalog
    def _get_last_identity_val(self):
        """
        The result of the IDENTITY_VAL_LOCAL function is not affected by the following:
         - A single row INSERT statement with a VALUES clause for a table without an
        identity column
         - A multiple row INSERT statement with a VALUES clause
         - An INSERT statement with a fullselect

        """
        operation = 'SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1'
        try:
            stmt_handler = ibm_db.prepare(self.conn_handler, operation)
            if ibm_db.execute(stmt_handler):
                row = ibm_db.fetch_assoc(stmt_handler)
                if row['1'] is not None:
                  identity_val = int(row['1'])
                else:
                  identity_val = None
            else:
                if ibm_db.conn_errormsg() is not None:
                    self.messages.append(Error(str(ibm_db.conn_errormsg())))
                    raise self.messages[len(self.messages) - 1]
                if ibm_db.stmt_errormsg() is not None:
                    self.messages.append(Error(str(ibm_db.stmt_errormsg())))
                    raise self.messages[len(self.messages) - 1]
        except Exception, inst:
            self.messages.append(_get_exception(inst))
            raise self.messages[len(self.messages) - 1]
        return identity_val
    last_identity_val = property(_get_last_identity_val, None, None, "")

    def execute(self, operation, parameters=None):
        """
        This method can be used to prepare and execute an SQL 
        statement.  It takes the SQL statement(operation) and a 
        sequence of values to substitute for the parameter markers in  
        the SQL statement as arguments.
        """
        self.messages = []
        if not isinstance(operation, basestring):
            self.messages.append(InterfaceError("execute expects the first argument [%s] to be of type String or Unicode." % operation ))
            raise self.messages[len(self.messages) - 1]
        if parameters is not None:
            if not isinstance(parameters, (types.ListType, types.TupleType, types.DictType)):
                self.messages.append(InterfaceError("execute parameters argument should be sequence."))
                raise self.messages[len(self.messages) - 1]
        self.__description = None
        self._all_stmt_handlers = []
        self._prepare_helper(operation)
        self._set_cursor_helper()
        self._execute_helper(parameters)
        return self._set_rowcount()

    def executemany(self, operation, seq_parameters):
        """
        This method can be used to prepare, and then execute an SQL 
        statement many times.  It takes the SQL statement(operation) 
        and sequence of sequence of values to substitute for the 
        parameter markers in the SQL statement as its argument.
        """
        self.messages = []
        if not isinstance(operation, basestring):
            self.messages.append(InterfaceError("executemany expects the first argument to be of type String or Unicode."))
            raise self.messages[len(self.messages) - 1]
        if seq_parameters is None:
            self.messages.append(InterfaceError("executemany expects a not None seq_parameters value"))
            raise self.messages[len(self.messages) - 1]

        if not isinstance(seq_parameters, (types.ListType, types.TupleType)):
            self.messages.append(InterfaceError("executemany expects the second argument to be of type list or tuple of sequence."))
            raise self.messages[len(self.messages) - 1]
        
        CONVERT_STR = (datetime.datetime, datetime.date, datetime.time, buffer)
        # Convert date/time and binary objects to string for
        # inserting into the database.
        buff = []
        seq_buff = []
        for index in range(len(seq_parameters)):
            buff = []
            for param in seq_parameters[index]:
                if isinstance(param, CONVERT_STR):
                    param = str(param)
                buff.append(param)
            seq_buff.append(tuple(buff))
        seq_parameters = tuple(seq_buff)
        self.__description = None
        self._all_stmt_handlers = []
        self.__rowcount = -1
        self._prepare_helper(operation)
        try:
            autocommit = ibm_db.autocommit(self.conn_handler)
            if autocommit !=  0:
                ibm_db.autocommit(self.conn_handler, 0)
            self.__rowcount = ibm_db.execute_many(self.stmt_handler, seq_parameters)
            if autocommit != 0:
                ibm_db.commit(self.conn_handler)
                ibm_db.autocommit(self.conn_handler, autocommit)
            if self.__rowcount == -1:
                if ibm_db.conn_errormsg() is not None:
                    self.messages.append(Error(str(ibm_db.conn_errormsg())))
                    raise self.messages[len(self.messages) - 1]
                if ibm_db.stmt_errormsg() is not None:
                    self.messages.append(Error(str(ibm_db.stmt_errormsg())))
                    raise self.messages[len(self.messages) - 1]   
        except Exception, inst:
            self._set_rowcount()
            self.messages.append(Error(inst))
            raise self.messages[len(self.messages) - 1]
        return True

    def _fetch_helper(self, fetch_size=-1):
        """
        This method is a helper function for fetching fetch_size number of 
        rows, after executing an SQL statement which produces a result set.
        It takes the number of rows to fetch as an argument.
        If this is not provided it fetches all the remaining rows.
        """
        if self.stmt_handler is None:
            self.messages.append(ProgrammingError("Please execute an SQL statement in order to get a row from result set."))
            raise self.messages[len(self.messages) - 1]
        if self._result_set_produced == False:
            self.messages.append(ProgrammingError("The last call to execute did not produce any result set."))
            raise  self.messages[len(self.messages) - 1]
        row_list = []
        rows_fetched = 0
        while (fetch_size == -1) or \
              (fetch_size != -1 and rows_fetched < fetch_size):
            try:
                row = ibm_db.fetch_tuple(self.stmt_handler)
            except Exception, inst:
                self.messages.append(_get_exception(inst))
                if len(row_list) == 0:
                    raise self.messages[len(self.messages) - 1]
                else:
                    return row_list
            
            if row != False:
                row_list.append(self._fix_return_data_type(row))
            else:
                return row_list
            rows_fetched = rows_fetched + 1
        return row_list

    def fetchone(self):
        """This method fetches one row from the database, after 
        executing an SQL statement which produces a result set.
        
        """
        row_list = self._fetch_helper(1)
        if len(row_list) == 0:
            return None
        else:
            return row_list[0]

    def fetchmany(self, size=0):
        """This method fetches size number of rows from the database,
        after executing an SQL statement which produces a result set.
        It takes the number of rows to fetch as an argument.  If this 
        is not provided it fetches self.arraysize number of rows. 
        """
        if not isinstance(size, (int, long)):
            self.messages.append(InterfaceError( "fetchmany expects argument type int or long."))
            raise self.messages[len(self.messages) - 1]
        if size == 0:
            size = self.arraysize
        if size < -1:
            self.messages.append(ProgrammingError("fetchmany argument size expected to be positive."))
            raise self.messages[len(self.messages) - 1]

        return self._fetch_helper(size)

    def fetchall(self):
        """This method fetches all remaining rows from the database,
        after executing an SQL statement which produces a result set.
        """
        return self._fetch_helper()

    def nextset(self):
        """This method can be used to get the next result set after 
        executing a stored procedure, which produces multiple result sets.
        """
        self.messages = []
        if self.stmt_handler is None:
            self.messages.append(ProgrammingError("Please execute an SQL statement in order to get result sets."))
            raise self.messages[len(self.messages) - 1]
        if self._result_set_produced == False:
            self.messages.append(ProgrammingError("The last call to execute did not produce any result set."))
            raise self.messages[len(self.messages) - 1]
        try:
            # Store all the stmt handler that were created.  The 
            # handler was the one created by the execute method.  It 
            # should be used to get next result set. 
            self.__description = None
            self._all_stmt_handlers.append(self.stmt_handler)
            self.stmt_handler = ibm_db.next_result(self._all_stmt_handlers[0])
        except Exception, inst:
            self.messages.append(_get_exception(inst))
            raise self.messages[len(self.messages) - 1]

        if self.stmt_handler == False:
            self.stmt_handler = None
        if self.stmt_handler == None:
            return None 
        return True

    def setinputsizes(self, sizes):
        """This method currently does nothing."""
        pass

    def setoutputsize(self, size, column=-1):
        """This method currently does nothing."""
        pass

    #To change formate date/time string to date/time object
    def _str_to_datetime(self, date_string, format):
        return datetime.datetime(*(time.strptime(date_string, format)[0:6]))

    # This method is used to convert a string representing date/time 
    # and binary data in a row tuple fetched from the database 
    # to date/time and binary objects, for returning it to the user.
    def _fix_return_data_type(self, row):
        row = list(row)
        for index in range(len(row)):
            if row[index] is not None:
                type = ibm_db.field_type(self.stmt_handler, index)
                type = type.upper()

                try:
                    if type == 'TIMESTAMP':
                        # strptime() method does not support 
                        # microsecond format. 
                        microsec = 0
                        if row[index][20:] != '':
                            microsec = int(row[index][20:])
                            row[index] = row[index][:19]
                        row[index] = self._str_to_datetime(row[index],
                                                          '%Y-%m-%d %H:%M:%S')
                        row[index] = row[index].replace(
                                                       microsecond = microsec)
                    elif type == 'DATE':
                        row[index] = self._str_to_datetime(row[index], 
                                                            '%Y-%m-%d').date()
                    elif type == 'TIME':
                        row[index] = self._str_to_datetime(row[index],
                                                            '%H:%M:%S').time()
                    elif type == 'BLOB':
                        row[index] = buffer(row[index])

                    elif type == 'DECIMAL':
                        row[index] = decimal.Decimal(str(row[index]).replace(",", "."))    

                except Exception, inst:
                    self.messages.append(DataError("Data type format error: "+ str(inst)))
                    raise self.messages[len(self.messages) - 1]
        return tuple(row)
Back to Top