implement ABC classes getting rid of duplicate code

This commit is contained in:
Xevion
2021-01-27 09:14:51 -06:00
parent 6bb302d2fc
commit 7410dbb01d

View File

@@ -2,6 +2,7 @@ import logging
import os import os
import sqlite3 import sqlite3
import threading import threading
import abc
import constants import constants
@@ -11,11 +12,13 @@ logger.setLevel(logging.DEBUG)
lock = threading.Lock() lock = threading.Lock()
class Database(object): class Database(abc.ABC):
def __init__(self, database: str): def __init__(self, database: str):
logger.debug(f"Connected to './{os.path.basename(database)}'") logger.debug(f"Connected to './{os.path.basename(database)}'")
self.conn = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES) self.conn = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES)
self.__isClosed = False self.__isClosed = False
self.__table = None
self.construct()
@property @property
def is_closed(self) -> bool: def is_closed(self) -> bool:
@@ -32,55 +35,51 @@ class Database(object):
self.__isClosed = True self.__isClosed = True
def construct(self) -> None: def construct(self) -> None:
raise NotImplementedError with lock:
cur = self.conn.cursor()
try:
cur.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name = ?;''', [self.__table])
if cur.fetchone() is None:
self._construct()
logger.info(f"'{self.__table}' table created.")
finally:
cur.close()
@abc.abstractmethod
def _construct(self) -> None:
pass
class ClientDatabase(Database): class ClientDatabase(Database):
def __init__(self): def __init__(self):
super().__init__(constants.CLIENT_DATABASE) super().__init__(constants.CLIENT_DATABASE)
self.__table = 'connection'
def construct(self) -> None: def _construct(self) -> None:
with lock: self.conn.execute('''CREATE TABLE connection
cur = self.conn.cursor() (id INTEGER PRIMARY KEY,
try: address TEXT NOT NULL,
cur.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name = '?';''', 'connection') port INTEGER NOT NULL,
if cur.fetchone() is None: nickname TEXT NOT NULL,
self.conn.execute('''CREATE TABLE connection password TEXT,
(id INTEGER PRIMARY KEY, connections INTEGER DEFAULT 1,
address TEXT NOT NULL, favorite BOOLEAN DEFAULT FALSE,
port INTEGER NOT NULL, initial_time TIMESTAMP NOT NULL,
nickname TEXT NOT NULL, latest_time TIMESTAMP NOT NULL);''')
password TEXT,
connections INTEGER DEFAULT 1,
favorite BOOLEAN DEFAULT FALSE,
initial_time TIMESTAMP NOT NULL,
latest_time TIMESTAMP NOT NULL);''')
finally:
cur.close()
class ServerDatabase(Database): class ServerDatabase(Database):
def __init__(self): def __init__(self):
super().__init__(constants.SERVER_DATABASE) super().__init__(constants.SERVER_DATABASE)
def construct(self): def _construct(self):
with lock: self.conn.execute('''CREATE TABLE message
cur = self.conn.cursor() (id INTEGER PRIMARY KEY,
try: nickname TEXT NOT NULL,
# check if the table exists connection_hash TEXT NOT NULL,
cur.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name='?';''', 'message') color TEXT DEFAULT '#000000',
# if it doesn't exist, create the table and report it message TEXT DEFAULT '',
if cur.fetchone() is None: timestamp INTEGER NOT NULL)''')
self.conn.execute('''CREATE TABLE message
(id INTEGER PRIMARY KEY,
nickname TEXT NOT NULL,
connection_hash TEXT NOT NULL,
color TEXT DEFAULT '#000000',
message TEXT DEFAULT '',
timestamp INTEGER NOT NULL)''')
logger.debug("'message' table created.")
finally:
cur.close()
def add_message(self, nickname: str, user_hash: str, color: str, message: str, timestamp: int) -> int: def add_message(self, nickname: str, user_hash: str, color: str, message: str, timestamp: int) -> int:
""" """