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 tuple Autocommit status i.e. ({'Value': 'ON', 'Variable_name':'autocommit'},) 64 """ 65 if not var_type in ['local', 'global', 'session']: 66 raise AutoCommitError(var_type) 67 68 status_query = "show %s variables where variable_name = 'autocommit'" % var_type 69 return self.query_select(status_query)
70
71 - def query_select(self, query):
72 """ 73 Send/execute SELECT queries, returns data from DB 74 :param: str MySQL query 75 :return: tuple with arguments dictionaries, each dictionary is a row of DB i.e. ({row_first}, {row_second}, ... ,{row_last}) 76 """ 77 try: 78 self.cursor.execute(query) 79 return self.cursor.fetchall() 80 except MySQLdb.Error, err: 81 raise QueryError(err.args[0], err.args[1])
82
83 - def query_execute(self, query):
84 """ 85 Sends query to DB. Can be DELETE, UPDATE 86 :param: str query 87 :return: dict {DictCursor} 88 """ 89 try: 90 self.cursor.execute(query) 91 return self.cursor 92 except MySQLdb.Error, err: 93 raise ExecuteError(err.args[0], err.args[1])
94
95 - def commit(self):
96 """ 97 Commits all changes, returns Exception in case of failure 98 """ 99 self.db.commit()
100
101 - def rollback(self):
102 """ 103 Rolls back all commits, returns exception in case of failure 104 """ 105 self.db.rollback()
106
107 - def close_cursor(self):
108 """ 109 Close cursor. Connection to DB is still open, new cursor can be created 110 """ 111 self.cursor.close() 112 self.cursor = None
113
114 - def close_db(self):
115 """ 116 Close DB connection. All uncommitted changes are lost 117 """ 118 self.db.close() 119 self.db = None
120
121 - def __del__(self):
122 if self.cursor is not None: self.cursor.close() 123 if self.db is not None: self.db.close()
124