WMGZON/controllers/database/database.py

62 lines
1.5 KiB
Python

from abc import ABC, abstractmethod
from typing import Mapping, Any
import sqlite3
import os
class DatabaseController(ABC):
__data_dir = "./data/"
__db_name = "wmgzon.db"
# Use test file if necessary
if os.environ.get("ENVIRON") == "test":
__db_name = "test_" + __db_name
__sqlitefile = __data_dir + __db_name
def __init__(self):
self._conn = None
try:
# Creates a connection and specifies a flag to parse all types
# back down into Python declared types e.g. date & time
self._conn = sqlite3.connect(
self.__sqlitefile, detect_types=sqlite3.PARSE_DECLTYPES)
except sqlite3.Error as e:
# Close the connection if still open
if self._conn:
self._conn.close()
print(e)
def __del__(self):
if self._conn is not None:
self._conn.close()
""" Takes a dictionary of fields and returns the object
with those fields populated """
def new_instance(self, of: type, with_fields: Mapping[str, Any]):
obj = of.__new__(of)
for attr, value in with_fields.items():
setattr(obj, attr, value)
return obj
"""
Set of CRUD methods to allow for Data manipulation on the backend
"""
@abstractmethod
def create(self):
pass
@abstractmethod
def read(self):
pass
@abstractmethod
def update(self):
pass
@abstractmethod
def delete(self):
pass