From 95ac1f0d6786d6f4331cfc8387ef816c1db24618 Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Tue, 20 Feb 2024 00:56:00 +0300 Subject: comletely delete old lws, rewrite vk_sms_checker on python --- include/py/homekit/database/mysql.py | 77 ++++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 25 deletions(-) (limited to 'include/py/homekit/database/mysql.py') diff --git a/include/py/homekit/database/mysql.py b/include/py/homekit/database/mysql.py index fe97cd4..a0b73fa 100644 --- a/include/py/homekit/database/mysql.py +++ b/include/py/homekit/database/mysql.py @@ -1,47 +1,74 @@ import time import logging +from abc import ABC, abstractmethod from mysql.connector import connect, MySQLConnection, Error from typing import Optional -from ..config import config +from ..config import ConfigUnit -link: Optional[MySQLConnection] = None logger = logging.getLogger(__name__) - datetime_fmt = '%Y-%m-%d %H:%M:%S' -def get_mysql() -> MySQLConnection: - global link +class MySQLCredsConfig(ConfigUnit, ABC): + @classmethod + def schema(cls) -> Optional[dict]: + schema = {} + for k in ('host', 'database', 'user', 'password'): + schema[k] = dict(type='string', required=True) + return schema + - if link is not None: - return link +class MySQLHomeCredsConfig(MySQLCredsConfig): + NAME = 'mysql_home_creds' - link = connect( - host=config['mysql']['host'], - user=config['mysql']['user'], - password=config['mysql']['password'], - database=config['mysql']['database'], - ) - link.time_zone = '+01:00' - return link + +class MySQLCloudCredsConfig(MySQLCredsConfig): + NAME = 'mysql_cloud_creds' def mysql_now() -> str: return time.strftime('%Y-%m-%d %H:%M:%S') -class MySQLDatabase: - def __init__(self): - self.db = get_mysql() +class MySQLDatabase(ABC): + _enable_pings: bool + _link: MySQLConnection + _time_zone: Optional[str] + + @abstractmethod + def creds(self) -> MySQLCredsConfig: + pass + + def __init__(self, enable_pings=False, time_zone='+01:00'): + self._enable_pings = enable_pings + self._time_zone = time_zone + self._connect() + + def _connect(self): + c = self.creds() + self._link = connect( + host=c['host'], + user=c['user'], + password=c['password'], + database=c['database'], + ) + if self._time_zone: + self._link.time_zone = self._time_zone def cursor(self, **kwargs): - try: - self.db.ping(reconnect=True, attempts=2) - except Error as e: - logger.exception(e) - self.db = get_mysql() - return self.db.cursor(**kwargs) + if self._enable_pings: + try: + self._link.ping(reconnect=True, attempts=2) + except Error as e: + logger.exception(e) + self._connect() + return self._link.cursor(**kwargs) def commit(self): - self.db.commit() + self._link.commit() + + +class MySQLHomeDatabase(MySQLDatabase): + def creds(self) -> MySQLCredsConfig: + return MySQLHomeCredsConfig() \ No newline at end of file -- cgit v1.2.3