forked from ibmdb/python-ibmdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ibm_db_dbi.py
1885 lines (1625 loc) · 76.8 KB
/
ibm_db_dbi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# +--------------------------------------------------------------------------+
# | Licensed Materials - Property of IBM |
# | |
# | (C) Copyright IBM Corporation 2007-2015 |
# +--------------------------------------------------------------------------+
# | This module complies with SQLAlchemy 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,
# | Akshay Anand, Saba Kauser
# +--------------------------------------------------------------------------+
"""
This module implements the Python DB API Specification v2.0 for DB2 database.
"""
import types, string, time, datetime, decimal, sys
import weakref
import logging
logger = logging.getLogger(__name__)
log_enabled = False
# Define macros for log levels
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
EXCEPTION = "EXCEPTION"
def debug(option):
global log_enabled
if isinstance(option, bool):
log_enabled = option
if log_enabled:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
elif isinstance(option, str):
log_enabled = True # Set log_enabled to True
if '.' not in option:
option += '.txt'
logging.basicConfig(filename=option, level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s',
filemode='w')
else:
print("Invalid argument in debug. Please give a boolean or a file name in string.")
def LogMsg(log_level, message):
if log_enabled:
if log_level == DEBUG:
logger.debug(message)
elif log_level == INFO:
logger.info(message)
elif log_level == WARNING:
logger.warning(message)
elif log_level == ERROR:
logger.error(message)
elif log_level == EXCEPTION:
logger.exception(message)
PY2 = sys.version_info < (3, )
if not PY2:
buffer = memoryview
if PY2:
import exceptions
exception = exceptions.Exception
else:
exception = Exception
if PY2:
import __builtin__
string_types = __builtin__.unicode, bytes
int_types = __builtin__.long, int
else:
string_types = str
int_types = int
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
USE_WCHAR = ibm_db.USE_WCHAR
WCHAR_YES = ibm_db.WCHAR_YES
WCHAR_NO = ibm_db.WCHAR_NO
FIX_RETURN_TYPE = 1
SQL_ATTR_TXN_ISOLATION = ibm_db.SQL_ATTR_TXN_ISOLATION
SQL_TXN_READ_UNCOMMITTED = ibm_db.SQL_TXN_READ_UNCOMMITTED
SQL_TXN_READ_COMMITTED = ibm_db.SQL_TXN_READ_COMMITTED
SQL_TXN_REPEATABLE_READ = ibm_db.SQL_TXN_REPEATABLE_READ
SQL_TXN_SERIALIZABLE = ibm_db.SQL_TXN_SERIALIZABLE
SQL_TXN_NO_COMMIT = ibm_db.SQL_TXN_NO_COMMIT
# 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
super(Error, self).__init__(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
super(Warning, self).__init__(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, (bytes, memoryview)):
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 sys.version_info < (3,):
if cmp < self.col_types:
return 1
else:
return -1
else:
return 1
def __eq__(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.
"""
return cmp in self.col_types
def __ne__(self, cmp):
"""This method checks if the string compared with is not in the
tuple provided to the constructor of this object. It takes
string as an argument.
"""
return cmp not in self.col_types
def __hash__(self):
return id(self)
# 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", "DBCLOB"))
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(())
BOOLEAN = DBAPITypeObject(("BOOLEAN",))
# 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('"):
if message.endswith("',)"): # python 2
message = message[11:]
message = message[:len(message) - 3]
elif message.endswith("')"): # python 3
message = message[11:]
message = message[:len(message) - 2]
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 _retrieve_current_schema(dsn):
"""This method retrieve the value of ODBC keyword CURRENTSCHEMA from DSN
"""
ODBC_CURRENTSCHEMA_KEYWORD = 'CURRENTSCHEMA='
current_schema_value = None
current_schema_start = dsn.find(ODBC_CURRENTSCHEMA_KEYWORD)
message = f"current_schema_start: {current_schema_start}"
LogMsg(DEBUG, message)
if current_schema_start > -1:
current_schema_end = dsn.find(';', current_schema_start)
message = f"ODBC_CURRENTSCHEMA_KEYWORD: {ODBC_CURRENTSCHEMA_KEYWORD}"
LogMsg(DEBUG, message)
LogMsg(DEBUG, f"current_schema_end: {current_schema_end}")
current_schema_value = dsn[
(current_schema_start + len(ODBC_CURRENTSCHEMA_KEYWORD))
:current_schema_end
]
LogMsg(DEBUG, f"current_schema_value: {current_schema_value}")
return current_schema_value
def _server_connect(dsn, user='', password='', host=''):
"""This method create connection with server
"""
if dsn is None:
LogMsg(ERROR, "dsn value should not be None")
raise InterfaceError("dsn value should not be None")
if (not isinstance(dsn, string_types)) | \
(not isinstance(user, string_types)) | \
(not isinstance(password, string_types)) | \
(not isinstance(host, string_types)):
LogMsg(ERROR, "Arguments should be of type string or unicode")
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 + ";"
# attach = true is not valid against IDS. And attach is not needed for connect currently.
#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 as inst:
message = f"An exception occurred while connecting to server: {inst}"
LogMsg(EXCEPTION, message)
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:
LogMsg(ERROR, "createdb expects a not None database name value")
raise InterfaceError("createdb expects a not None database name value")
if (not isinstance(database, string_types)) | \
(not isinstance(codeset, string_types)) | \
(not isinstance(mode, string_types)):
LogMsg(ERROR, "Arguments should be string or unicode")
raise InterfaceError("Arguments should be string or unicode")
conn = _server_connect(dsn, user=user, password=password, host=host)
try:
return_value = ibm_db.createdb(conn, database, codeset, mode)
LogMsg(DEBUG, f"Return value from ibm_db.createdb: {return_value}")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred during database creation: {inst}")
raise _get_exception(inst)
finally:
try:
ibm_db.close(conn)
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while closing connection: {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:
LogMsg(ERROR, "dropdb expects a not None database name value")
raise InterfaceError("dropdb expects a not None database name value")
if not isinstance(database, string_types):
LogMsg(ERROR, "Arguments should be string or unicode")
raise InterfaceError("Arguments should be string or unicode")
conn = _server_connect(dsn, user=user, password=password, host=host)
try:
return_value = ibm_db.dropdb(conn, database)
LogMsg(DEBUG, f"Return value from ibm_db.dropdb: {return_value}")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred during database droping: {inst}")
raise _get_exception(inst)
finally:
try:
ibm_db.close(conn)
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while closing connection: {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:
LogMsg(ERROR, "recreatedb expects a not None database name value")
raise InterfaceError("recreatedb expects a not None database name value")
if (not isinstance(database, string_types)) | \
(not isinstance(codeset, string_types)) | \
(not isinstance(mode, string_types)):
LogMsg(ERROR, "Arguments should be string or unicode")
raise InterfaceError("Arguments should be string or unicode")
conn = _server_connect(dsn, user=user, password=password, host=host)
try:
return_value = ibm_db.recreatedb(conn, database, codeset, mode)
LogMsg(DEBUG, f"Return value from ibm_db.recreatedb: {return_value}")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred during database recreation: {inst}")
raise _get_exception(inst)
finally:
try:
ibm_db.close(conn)
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while closing connection: {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:
LogMsg(ERROR, "createdbNX expects a not None database name value")
raise InterfaceError("createdbNX expects a not None database name value")
if (not isinstance(database, string_types)) | \
(not isinstance(codeset, string_types)) | \
(not isinstance(mode, string_types)):
LogMsg(ERROR, "Arguments should be string or unicode")
raise InterfaceError("Arguments should be string or unicode")
conn = _server_connect(dsn, user=user, password=password, host=host)
try:
return_value = ibm_db.createdbNX(conn, database, codeset, mode)
LogMsg(DEBUG, f"Return value from ibm_db.createdbNX: {return_value}")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred during database createdbNX: {inst}")
raise _get_exception(inst)
finally:
try:
ibm_db.close(conn)
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while closing connection: {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.
"""
try:
message = f"dsn: {dsn}, user: {user}, host: {host}, database: {database}, conn_options: {conn_options}"
LogMsg(DEBUG, message)
if dsn is None:
LogMsg(ERROR, "connect expects a not None dsn value")
raise InterfaceError("connect expects a not None dsn value")
if (not isinstance(dsn, string_types)) | \
(not isinstance(user, string_types)) | \
(not isinstance(password, string_types)) | \
(not isinstance(host, string_types)) | \
(not isinstance(database, string_types)):
message = "connect expects the first five arguments to be of type string or unicode"
LogMsg(ERROR, message)
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):
message = "connect expects the sixth argument (conn_options) to be of type dict"
LogMsg(ERROR, message)
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 protocol 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 + ";"
LogMsg(DEBUG, f"Connection string: {dsn}")
conn = ibm_db.connect(dsn, '', '', conn_options)
conn_object = Connection(conn)
conn_object.set_current_schema(_retrieve_current_schema(dsn) or user)
LogMsg(INFO, "Connection successful.")
return conn_object
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while connecting: {inst}")
raise _get_exception(inst)
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:
LogMsg(ERROR, "connect expects a not None dsn value")
raise InterfaceError("connect expects a not None dsn value")
if (not isinstance(dsn, string_types)) | \
(not isinstance(user, string_types)) | \
(not isinstance(password, string_types)) | \
(not isinstance(host, string_types)) | \
(not isinstance(database, string_types)):
LogMsg(ERROR, "connect expects the first five arguments to be of type string or unicode")
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):
LogMsg(ERROR, "connect expects the sixth argument (conn_options) to be of type 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:
LogMsg(DEBUG, f"Connecting to database with DSN: {dsn}")
conn = ibm_db.pconnect(dsn, '', '', conn_options)
LogMsg(INFO, "Connection established successfully")
conn_object = Connection(conn)
conn_object.set_current_schema(_retrieve_current_schema(dsn) or user)
return conn_object
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while connecting: {inst}")
raise _get_exception(inst)
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)
self.FIX_RETURN_TYPE = 1
# 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:
LogMsg(ERROR, "Connection cannot be closed; connection is no longer active.")
raise ProgrammingError("Connection cannot be closed; "
"connection is no longer active.")
else:
LogMsg(DEBUG, f"Closing connection: conn_handler={self.conn_handler}")
return_value = ibm_db.close(self.conn_handler)
LogMsg(INFO, "Connection closed.")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while closing connection: {inst}")
raise _get_exception(inst)
self.conn_handler = None
for index in range(len(self._cursor_list)):
if (self._cursor_list[index]() != None):
tmp_cursor = self._cursor_list[index]()
tmp_cursor.conn_handler = None
tmp_cursor.stmt_handler = None
tmp_cursor._all_stmt_handlers = None
self._cursor_list = []
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)
LogMsg(INFO, "Transaction committed.")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while committing transaction: {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)
LogMsg(INFO, "Transaction rolled back.")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while rolling back transaction: {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:
LogMsg(ERROR, "Cursor cannot be returned; connection is no longer active.")
raise ProgrammingError("Cursor cannot be returned; "
"connection is no longer active.")
cursor = Cursor(self.conn_handler, self)
self._cursor_list.append(weakref.ref(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
"""
LogMsg(DEBUG, f"Setting connection options: {attr_dict}")
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
"""
LogMsg(DEBUG, f"Getting connection option: {attr_key}")
return ibm_db.get_option(self.conn_handler, attr_key, 1)
# Sets FIX_RETURN_TYPE. Added for performance improvement
def set_fix_return_type(self, is_on):
try:
LogMsg(DEBUG, f"Setting fix return type to: {is_on}")
if is_on:
self.FIX_RETURN_TYPE = 1
else:
self.FIX_RETURN_TYPE = 0
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while setting fix return type: {inst}")
raise _get_exception(inst)
return self.FIX_RETURN_TYPE
# 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:
LogMsg(DEBUG, f"Setting autocommit to: {is_on}")
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 as inst:
LogMsg(EXCEPTION, f"An exception occurred while setting autocommit: {inst}")
raise _get_exception(inst)
LogMsg(DEBUG, f"set_autocommit returns: {is_set}")
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:
LogMsg(DEBUG, f"Setting current schema to: {schema_name}")
is_set = ibm_db.set_option(self.conn_handler, {SQL_ATTR_CURRENT_SCHEMA: schema_name}, 1)
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred setting current schema: {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
LogMsg(DEBUG, f"Current schema: {self.current_schema}")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while getting current schema: {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)
LogMsg(INFO, f"Server info: {server_info}")
except Exception as inst:
LogMsg(EXCEPTION, f"An exception occurred while getting server info: {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