bookmyservice-ams / app /core /sql_config.py
MukeshKapoor25's picture
refactor(database): improve database configuration handling
6eda67d
import logging
import databases
import sqlalchemy
from app.core.config import DATABASE_URL
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
# Database URL is constructed in app.core.config via build_database_uri
# Initialize the database connection and metadata
try:
# Create database connection
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
logger.info("Database connection initialized successfully.")
except Exception as e:
logger.error("Failed to initialize database connection: %s", e)
raise
# Helper function to initialize database
async def connect_to_database():
"""
Connects to the database when the application starts.
"""
try:
await database.connect()
logger.info("Successfully connected to the database.")
except Exception as e:
logger.error("Error connecting to the database: %s", e)
raise
# Helper function to disconnect database
async def disconnect_from_database():
"""
Disconnects from the database when the application shuts down.
"""
try:
await database.disconnect()
logger.info("Successfully disconnected from the database.")
except Exception as e:
logger.error("Error disconnecting from the database: %s", e)
raise