Package tlib :: Package base :: Module MysqlConnector |
[hide private]
[frames] | no frames]

# Source Code for Module tlib.base.MysqlConnector

      1  # @author dumitru.fostic@ypg.com
      2  # @date   May , 2014
      3  import MySQLdb
      4  import warnings
      5  from tlib.base.ExceptionHelper import TLibException
      6  from MySQLdb.cursors import DictCursor, Cursor, SSCursor, SSDictCursor
      7
      8
      9 -class ConnectionError(TLibException):
     10 -    def __init__(self, err_code, err_description):
     11          self.code, self.description = err_code, err_description
     12 -    def __str__(self):
     13          return 'Connection to DB FAILURE with error(/code: description/) /%d: %s/' % (self.code, self.description)
     14
     15
     16 -class AutoCommitError(TLibException):
     17 -    def __init__(self, value):
     18          self.value = value
     19 -    def __str__(self):
     20          return "Wrong argument '%s' passed in <get_autocommit_status> function. Valid args are str: 'local', 'global' or 'session'." % self.value
     21
     22
     23 -class QueryError(TLibException):
     24 -    def __init__(self, err_code, err_description):
     25          self.code, self.description = err_code, err_description
     26 -    def __str__(self):
     27          return 'query function FAILURE with error(/code: description/) /%d: %s/' % (self.code, self.description)
     28
     29
     30 -class ExecuteError(TLibException):
     31 -    def __init__(self, err_code, err_description):
     32          self.code, self.description = err_code, err_description
     33 -    def __str__(self):
     34          return 'execute function FAILURE with error (/code: description/) /%d: %s/' % (self.code, self.description)
     35
     36
     37 -class MysqlConnector(object):
     38      """
     39      Connects to MySQL DB, executes queries
     40      Autocommit is disabled by default, commit is done with commit function
     41      Warnings are turned into exceptions
     42      """
     43 -    def __init__(self, config_data, cursor_class=None):
     44          """
     45          Initialize DB connection. Turning warning into exceptions
     46          :param cursor_class: Cursor type to use. See MySQLdb for more info
     47          :type cursor_class: DictCursor|Cursor|SSCursor|SSDictCursor
     48          """
     49          if cursor_class is None:
     50              cursor_class = DictCursor
     51
     52          self.db = None
     53          warnings.filterwarnings('error', category=MySQLdb.Warning)  # turns warnings into exceptions
     54          try:
     55              self.db = MySQLdb.connect(**config_data)
     56              self.cursor = self.db.cursor(cursor_class)
     57              self.db.autocommit(False)   # in case of autocommit will change by default to ON in future
     58          except MySQLdb.Error, err:
     59              raise ConnectionError(err.args[0], err.args[1])
     60
     61 -    def get_autocommit_status(self, var_type='local'):
     62          """
     63          returns Autocommit status
     64          This is an alias to get_autocommit()
     65          """
     66          return self.get_autocommit(var_type)
     67
     68 -    def get_autocommit(self, var_type='local'):
     69          """
     70          returns Autocommit status
     71          @return: bool
     72          """
     73          if not var_type in ['local', 'global', 'session']:
     74              raise AutoCommitError(var_type)
     75
     76          status_query = "show %s variables where variable_name = 'autocommit'" % var_type
     77          query_result = self.query_select(status_query)
     78
     79          return query_result[0]["Value"] == 'ON'
     80
     81 -    def set_autocommit(self, value):
     82          """
     83          returns tuple Autocommit status i.e. ({'Value': 'ON', 'Variable_name':'autocommit'},)
     84          @type value: bool
     85          """
     86          self.db.autocommit(value)
     87
     88 -    def query_select(self, query, *params):
     89          """
     90          Send/execute SELECT queries, returns data from DB
     91          :param: str MySQL query
     92          :return: tuple with arguments dictionaries, each dictionary is a row of DB i.e. ({row_first}, {row_second}, ... ,{row_last})
     93          """
     94          try:
     95              self.cursor.execute(query, params)
     96              return self.cursor.fetchall()
     97          except MySQLdb.Error, err:
     98              raise QueryError(err.args[0], err.args[1])
     99
    100 -    def query_execute(self, query):
    101          """
    102          Sends query to DB. Can be DELETE, UPDATE
    103          :param: str query
    104          :return: dict {DictCursor}
    105          """
    106          try:
    107              self.cursor.execute(query)
    108              return self.cursor
    109          except MySQLdb.Error, err:
    110              raise ExecuteError(err.args[0], err.args[1])
    111
    112 -    def commit(self):
    113          """
    114          Commits all changes, returns Exception in case of failure
    115          """
    116          self.db.commit()
    117
    118 -    def rollback(self):
    119          """
    120          Rolls back all commits, returns exception in case of failure
    121          """
    122          self.db.rollback()
    123
    124 -    def close_cursor(self):
    125          """
    126          Close cursor. Connection to DB is still open, new cursor can be created
    127          """
    128          self.cursor.close()
    129          self.cursor = None
    130
    131 -    def close_db(self):
    132          """
    133          Close DB connection. All uncommitted changes are lost
    134          """
    135          self.db.close()
    136          self.db = None
    137
    138 -    def __del__(self):
    139          if self.cursor is not None: self.cursor.close()
    140          if self.db is not None: self.db.close()
    141