38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
from database.models import Base
|
|
import logging.config
|
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
|
from sqlalchemy import event
|
|
from config import DATABASE_URL
|
|
|
|
from logger_helper.logger_helper import LOGGING_CONFIG
|
|
|
|
logging.config.dictConfig(LOGGING_CONFIG)
|
|
logger = logging.getLogger("database")
|
|
|
|
|
|
async_engine = create_async_engine(
|
|
DATABASE_URL,
|
|
echo=False,
|
|
connect_args={"check_same_thread": False}
|
|
)
|
|
|
|
@event.listens_for(async_engine.sync_engine, "connect")
|
|
def _enable_foreign_keys(dbapi_connection, connection_record):
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA foreign_keys=ON")
|
|
cursor.close()
|
|
|
|
async_session = async_sessionmaker(
|
|
async_engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False
|
|
)
|
|
|
|
async def init_db():
|
|
try:
|
|
async with async_engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
logger.info("Database initialized.")
|
|
except Exception as e:
|
|
logger.error("Database initialization failed: %s", e, exc_info=True)
|