From prod instance

This commit is contained in:
Kumi 2022-09-23 15:50:09 +00:00
parent 6d77822af1
commit 8e3a910597
Signed by: kumi
GPG key ID: ECBCC9082395383F
2 changed files with 23 additions and 11 deletions

View file

@ -4,8 +4,11 @@ import MySQLdb.cursors
from typing import Union, Optional
from .connection import Connection
from .logger import Logger
logger = Logger()
class Database:
"""Class wrapping MySQL database connection
"""
@ -17,9 +20,7 @@ class Database:
self._con = None
self._ssh = None
self._connect()
def _execute(self, query: str, parameters: Optional[tuple] = None, ctype: Optional[MySQLdb.cursors.BaseCursor] = None) -> None:
def _execute(self, query: str, parameters: Optional[tuple] = None, ctype: Optional[MySQLdb.cursors.BaseCursor] = None, retry: bool = True):
"""Execute a query on the database
Args:
@ -27,12 +28,22 @@ class Database:
parameters (tuple, optional): Parameters to use to replace
placeholders in the query, if any. Defaults to None.
"""
cur = self.getCursor(ctype)
cur.execute(query, parameters)
self.commit() # Instantly commit after every (potential) write action
return cur.fetchall()
try:
cur = self.getCursor(ctype)
cur.execute(query, parameters)
self.commit() # Instantly commit after every (potential) write action
return cur.fetchall()
except (AttributeError, MySQLdb.OperationalError):
if retry:
self._connect()
return self._execute(query, parameters, ctype, False)
raise
except MySQLdb.ProgrammingError:
logger.error(f"Error in query: {query}")
logger.error(f"Parameters: {str(parameters)}")
raise
def _connect(self):
def _connect(self) -> None:
if self.vessel.ssh:
self._ssh = Connection(self.vessel)
port = self._ssh.forward_tcp(3306)
@ -64,5 +75,5 @@ class Database:
def __del__(self):
"""Close database connection on removal of the Database object
"""
self._con.close()
if self._con:
self._con.close()

View file

@ -2,4 +2,5 @@ import logging
class Logger(logging.Logger):
name = "ReportMonster"
def __init__(self, name="ReportMonster", *args, **kwargs):
super().__init__(name, *args, **kwargs)