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