first commit
This commit is contained in:
68
app/core/database.py
Normal file
68
app/core/database.py
Normal file
@@ -0,0 +1,68 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from contextlib import contextmanager
|
||||
from typing import Optional
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
class DatabaseConnector:
|
||||
"""Управление подключениями к базам данных"""
|
||||
|
||||
def __init__(self):
|
||||
self._src_engine: Optional[Engine] = None
|
||||
self._dst_engine: Optional[Engine] = None
|
||||
self.dst_session = None
|
||||
self.schedule_session = None
|
||||
|
||||
@property
|
||||
def src_engine(self) -> Engine:
|
||||
"""Подключение к MSSQL"""
|
||||
if not self._src_engine:
|
||||
self._src_engine = create_engine(
|
||||
settings.MSSQL_CONNECTION_STRING,
|
||||
pool_pre_ping=True,
|
||||
echo=settings.DEBUG
|
||||
)
|
||||
return self._src_engine
|
||||
|
||||
@property
|
||||
def dst_engine(self) -> Engine:
|
||||
"""Подключение к PostgreSQL (основная БД)"""
|
||||
if not self._dst_engine:
|
||||
self._dst_engine = create_engine(
|
||||
settings.POSTGRES_CONNECTION_STRING,
|
||||
pool_pre_ping=True,
|
||||
echo=settings.DEBUG
|
||||
)
|
||||
self.dst_session = sessionmaker(bind=self._dst_engine)
|
||||
return self._dst_engine
|
||||
|
||||
@contextmanager
|
||||
def src_connection(self):
|
||||
"""Контекстный менеджер для MSSQL соединения"""
|
||||
conn = self.src_engine.connect()
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@contextmanager
|
||||
def dst_connection(self):
|
||||
"""Контекстный менеджер для PostgreSQL соединения"""
|
||||
conn = self.dst_engine.connect()
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def dispose_engines(self):
|
||||
"""Закрытие всех соединений"""
|
||||
if self._src_engine:
|
||||
self._src_engine.dispose()
|
||||
if self._dst_engine:
|
||||
self._dst_engine.dispose()
|
||||
|
||||
|
||||
# Глобальный экземпляр подключений
|
||||
db_connector = DatabaseConnector()
|
||||
Reference in New Issue
Block a user