2020-11-29 21:36:16 +01:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from sqlalchemy import engine, create_engine
|
2020-12-14 19:51:25 +01:00
|
|
|
from sqlalchemy.orm import Session, sessionmaker
|
2020-11-29 21:36:16 +01:00
|
|
|
|
2020-12-10 18:11:05 +01:00
|
|
|
from sh_edraft.database.connection.base.database_connection_base import DatabaseConnectionBase
|
2020-11-29 21:36:16 +01:00
|
|
|
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-11-29 21:36:16 +01:00
|
|
|
|
|
|
|
|
|
|
|
class DatabaseConnection(DatabaseConnectionBase):
|
|
|
|
|
|
|
|
def __init__(self, database_settings: DatabaseSettings):
|
|
|
|
DatabaseConnectionBase.__init__(self)
|
|
|
|
|
|
|
|
self._db_settings = database_settings
|
|
|
|
|
|
|
|
self._engine: Optional[engine] = None
|
2020-12-14 19:51:25 +01:00
|
|
|
self._session: Optional[Session] = None
|
2020-11-29 21:36:16 +01:00
|
|
|
self._credentials: Optional[str] = None
|
|
|
|
|
2020-12-11 19:42:09 +01:00
|
|
|
@property
|
|
|
|
def engine(self) -> engine:
|
|
|
|
return self._engine
|
|
|
|
|
|
|
|
@property
|
2020-12-14 19:51:25 +01:00
|
|
|
def session(self) -> Session:
|
2020-12-11 19:42:09 +01:00
|
|
|
return self._session
|
|
|
|
|
|
|
|
def connect(self, connection_string: str):
|
2020-11-29 21:48:17 +01:00
|
|
|
try:
|
2020-12-10 18:11:05 +01:00
|
|
|
self._engine = create_engine(connection_string)
|
2020-11-29 21:36:16 +01:00
|
|
|
|
2020-11-29 21:48:17 +01:00
|
|
|
if self._db_settings.encoding is not None:
|
|
|
|
self._engine.encoding = self._db_settings.encoding
|
2020-11-29 21:36:16 +01:00
|
|
|
|
2020-11-29 21:48:17 +01:00
|
|
|
if self._db_settings.case_sensitive is not None:
|
|
|
|
self._engine.case_sensitive = self._db_settings.case_sensitive
|
2020-11-29 21:36:16 +01:00
|
|
|
|
2020-11-29 21:48:17 +01:00
|
|
|
if self._db_settings.echo is not None:
|
|
|
|
self._engine.echo = self._db_settings.echo
|
2020-11-29 21:36:16 +01:00
|
|
|
|
2020-11-29 21:48:17 +01:00
|
|
|
self._engine.connect()
|
|
|
|
|
|
|
|
db_session = sessionmaker(bind=self._engine)
|
|
|
|
self._session = db_session()
|
2020-12-14 21:10:26 +01:00
|
|
|
Console.set_foreground_color(ForegroundColor.green)
|
|
|
|
Console.write_line(f'[{__name__}] Connected to database')
|
|
|
|
Console.set_foreground_color(ForegroundColor.default)
|
2020-11-29 21:48:17 +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__}] Database connection failed -> {e}')
|
|
|
|
Console.set_foreground_color(ForegroundColor.default)
|
2020-11-29 21:48:17 +01:00
|
|
|
exit()
|
2020-11-29 21:36:16 +01:00
|
|
|
|