2023-02-14 22:07:16 +00:00
|
|
|
from typing import Optional, Union
|
|
|
|
from enum import Enum
|
|
|
|
from peewee import (
|
|
|
|
SqliteDatabase,
|
|
|
|
MySQLDatabase,
|
|
|
|
PostgresqlDatabase,
|
2022-11-27 14:07:02 +00:00
|
|
|
)
|
2022-10-27 17:53:12 +00:00
|
|
|
|
2023-02-14 22:07:16 +00:00
|
|
|
from . import data_models
|
2023-02-13 16:07:36 +00:00
|
|
|
|
2023-01-30 22:54:21 +00:00
|
|
|
|
2023-02-14 22:07:16 +00:00
|
|
|
class DatabaseType(Enum):
|
|
|
|
SQLITE = "sqlite"
|
|
|
|
POSTGRESQL = "postgresql"
|
|
|
|
MYSQL = "mysql"
|
2022-11-25 17:27:48 +00:00
|
|
|
|
2022-11-06 17:10:00 +00:00
|
|
|
class Database:
|
2023-02-14 22:07:16 +00:00
|
|
|
database: Union[SqliteDatabase, PostgresqlDatabase, MySQLDatabase]
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
db_type: DatabaseType,
|
|
|
|
db_name: str,
|
|
|
|
db_user: Optional[str] = None,
|
|
|
|
db_password: Optional[str] = None,
|
|
|
|
db_host: Optional[str] = None,
|
|
|
|
db_port: Optional[int] = None
|
|
|
|
):
|
|
|
|
self.db_type = db_type
|
|
|
|
self.db_name = db_name
|
|
|
|
self.db_user = db_user
|
|
|
|
self.db_password = db_password
|
|
|
|
self.db_host = db_host
|
|
|
|
self.db_port = db_port
|
|
|
|
|
|
|
|
self.initialize_database()
|
|
|
|
|
|
|
|
def create_database(self) -> Union[SqliteDatabase, PostgresqlDatabase, MySQLDatabase]:
|
|
|
|
"""Create a database instance based on the configured database type and parameters.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The created database instance, or None if an invalid database type was specified.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# SQLITE
|
|
|
|
if self.db_type == DatabaseType.SQLITE:
|
|
|
|
return SqliteDatabase(self.db_name)
|
|
|
|
|
|
|
|
# POSTGRES
|
|
|
|
if self.db_type == DatabaseType.POSTGRESQL:
|
|
|
|
return PostgresqlDatabase(
|
|
|
|
self.db_name,
|
|
|
|
user=self.db_user,
|
|
|
|
password=self.db_password,
|
|
|
|
host=self.db_host,
|
|
|
|
port=self.db_port,
|
2023-01-30 22:54:21 +00:00
|
|
|
)
|
2022-11-25 17:27:48 +00:00
|
|
|
|
2023-02-14 22:07:16 +00:00
|
|
|
# MYSQL
|
|
|
|
if self.db_type == DatabaseType.MYSQL:
|
|
|
|
return MySQLDatabase(
|
|
|
|
self.db_name,
|
|
|
|
user=self.db_user,
|
|
|
|
password=self.db_password,
|
|
|
|
host=self.db_host,
|
|
|
|
port=self.db_port,
|
|
|
|
)
|
2022-10-30 19:30:59 +00:00
|
|
|
|
2023-02-14 22:07:16 +00:00
|
|
|
raise ValueError("define a Valid database type")
|
2023-01-30 22:54:21 +00:00
|
|
|
|
2023-02-14 22:07:16 +00:00
|
|
|
def initialize_database(self):
|
2022-11-06 17:10:00 +00:00
|
|
|
"""
|
2023-02-14 22:07:16 +00:00
|
|
|
Connect to the database
|
|
|
|
initialize the previously defined databases
|
|
|
|
create tables if they don't exist.
|
2023-01-30 22:54:21 +00:00
|
|
|
"""
|
2023-02-14 22:07:16 +00:00
|
|
|
self.database = self.create_database()
|
2022-11-06 17:10:00 +00:00
|
|
|
|
2023-02-14 22:07:16 +00:00
|
|
|
self.database.connect()
|