2020-12-11 21:48:46 +01:00
|
|
|
from sqlalchemy import engine, Table
|
2020-12-14 19:51:25 +01:00
|
|
|
from sqlalchemy.orm import Session
|
2020-12-11 21:48:46 +01:00
|
|
|
|
|
|
|
from sh_edraft.database.connection.database_connection import DatabaseConnection
|
|
|
|
from sh_edraft.database.connection.base.database_connection_base import DatabaseConnectionBase
|
|
|
|
from sh_edraft.database.context.base.database_context_base import DatabaseContextBase
|
|
|
|
from sh_edraft.database.model.dbmodel import DBModel
|
|
|
|
from sh_edraft.database.model.database_settings import DatabaseSettings
|
2020-12-15 16:53:15 +01:00
|
|
|
from sh_edraft.console.console import Console
|
|
|
|
from sh_edraft.console.model.foreground_color import ForegroundColor
|
2020-12-11 21:48:46 +01:00
|
|
|
|
|
|
|
|
|
|
|
class DatabaseContext(DatabaseContextBase):
|
|
|
|
|
|
|
|
def __init__(self, database_settings: DatabaseSettings):
|
|
|
|
DatabaseContextBase.__init__(self)
|
|
|
|
|
|
|
|
self._db: DatabaseConnectionBase = DatabaseConnection(database_settings)
|
|
|
|
self._tables: list[Table] = []
|
|
|
|
|
|
|
|
@property
|
|
|
|
def engine(self) -> engine:
|
|
|
|
return self._db.engine
|
|
|
|
|
|
|
|
@property
|
2020-12-14 19:51:25 +01:00
|
|
|
def session(self) -> Session:
|
2020-12-11 21:48:46 +01:00
|
|
|
return self._db.session
|
|
|
|
|
|
|
|
def create(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def connect(self, connection_string: str):
|
|
|
|
self._db.connect(connection_string)
|
|
|
|
self._create_tables()
|
|
|
|
|
|
|
|
def _create_tables(self):
|
|
|
|
try:
|
|
|
|
for subclass in DBModel.__subclasses__():
|
|
|
|
self._tables.append(subclass.__table__)
|
|
|
|
|
|
|
|
DBModel.metadata.drop_all(self._db.engine, self._tables)
|
|
|
|
DBModel.metadata.create_all(self._db.engine, self._tables, checkfirst=True)
|
2020-12-14 21:10:26 +01:00
|
|
|
Console.set_foreground_color(ForegroundColor.green)
|
|
|
|
Console.write_line(f'[{__name__}] Created tables')
|
|
|
|
Console.set_foreground_color(ForegroundColor.default)
|
2020-12-11 21:48:46 +01:00
|
|
|
except Exception as e:
|
2020-12-14 21:10:26 +01:00
|
|
|
Console.set_foreground_color(ForegroundColor.red)
|
|
|
|
Console.write_line(f'[{__name__}] Creating tables failed -> {e}')
|
|
|
|
Console.set_foreground_color(ForegroundColor.default)
|
2020-12-11 21:48:46 +01:00
|
|
|
exit()
|