Fixed database connection handling by reconnecting
This commit is contained in:
@@ -15,7 +15,7 @@ __title__ = 'cpl_core.database.context'
|
||||
__author__ = 'Sven Heidemann'
|
||||
__license__ = 'MIT'
|
||||
__copyright__ = 'Copyright (c) 2020 - 2022 sh-edraft.de'
|
||||
__version__ = '2022.7.0.post4'
|
||||
__version__ = '2022.7.0.post5'
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
@@ -25,4 +25,4 @@ from .database_context import DatabaseContext
|
||||
from .database_context_abc import DatabaseContextABC
|
||||
|
||||
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
|
||||
version_info = VersionInfo(major='2022', minor='7', micro='0.post4')
|
||||
version_info = VersionInfo(major='2022', minor='7', micro='0.post5')
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import mysql
|
||||
|
||||
from cpl_core.database.connection.database_connection import DatabaseConnection
|
||||
from cpl_core.database.connection.database_connection_abc import \
|
||||
DatabaseConnectionABC
|
||||
@@ -23,12 +25,25 @@ class DatabaseContext(DatabaseContextABC):
|
||||
|
||||
self._db: DatabaseConnectionABC = DatabaseConnection()
|
||||
self._tables: list[TableABC] = TableABC.__subclasses__()
|
||||
self._settings: Optional[DatabaseSettings] = None
|
||||
|
||||
@property
|
||||
def cursor(self) -> MySQLCursorBuffered:
|
||||
self._ping_and_reconnect()
|
||||
return self._db.cursor
|
||||
|
||||
|
||||
def _ping_and_reconnect(self):
|
||||
try:
|
||||
self._db.server.ping(reconnect=True, attempts=3, delay=5)
|
||||
except mysql.connector.Error as err:
|
||||
# reconnect your cursor as you did in __init__ or wherever
|
||||
if self._settings is None:
|
||||
raise Exception('Call DatabaseContext.connect first')
|
||||
self.connect(self._settings)
|
||||
|
||||
def connect(self, database_settings: DatabaseSettings):
|
||||
if self._settings is None:
|
||||
self._settings = database_settings
|
||||
self._db.connect(database_settings)
|
||||
for table in self._tables:
|
||||
self._db.cursor.execute(table.get_create_string())
|
||||
@@ -36,8 +51,10 @@ class DatabaseContext(DatabaseContextABC):
|
||||
self.save_changes()
|
||||
|
||||
def save_changes(self):
|
||||
self._ping_and_reconnect()
|
||||
self._db.server.commit()
|
||||
|
||||
def select(self, statement: str) -> list[tuple]:
|
||||
self._ping_and_reconnect()
|
||||
self._db.cursor.execute(statement)
|
||||
return self._db.cursor.fetchall()
|
||||
|
||||
@@ -12,8 +12,8 @@ class DatabaseContextABC(ABC):
|
||||
pass
|
||||
|
||||
@property
|
||||
def cursor(self) -> MySQLCursorBuffered:
|
||||
return self._cursor
|
||||
@abstractmethod
|
||||
def cursor(self) -> MySQLCursorBuffered: pass
|
||||
|
||||
@abstractmethod
|
||||
def connect(self, database_settings: DatabaseSettings):
|
||||
|
||||
Reference in New Issue
Block a user