Skip to content

database.py

This file establishes the core database engine and session management for the application. It configures SQLAlchemy for efficient connection pooling and provides a dependency injection function for transactional database sessions, centralizing data access.

Scope

  • Configures the SQLAlchemy database engine with connection pooling.

  • Establishes a session factory for managing database interactions.

  • Provides a dependency injection function for database sessions.

  • Manages database connection lifecycle and resource cleanup.

  • Defines the base class for declarative ORM models.

File diagram - "database.py" /app/core/database.pyFile diagram - "database.py"  GlobalImportscreate_enginesessionmakerdeclarative_basesettings/app/core/database.pyengineSessionLocalBaseget_db()create_engine()sessionmaker()declarative_base()get_dbdbSessionLocal()db.close()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
File diagram - "database.py" /app/core/database.pyFile diagram - "database.py"  GlobalImportscreate_enginesessionmakerdeclarative_basesettings/app/core/database.pyengineSessionLocalBaseget_db()create_engine()sessionmaker()declarative_base()get_dbdbSessionLocal()db.close()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Imports

  • create_engine from sqlalchemy

    Configures the database connection pool and dialect, serving as the primary interface to the relational database. This engine manages connections efficiently for application requests.

  • sessionmaker, declarative_base from sqlalchemy.orm

    sessionmaker creates a configurable factory for Session objects, managing database conversations. declarative_base provides a base class for ORM model definitions.

  • settings from app.core.config

    Provides application-wide configuration values, including the database connection string and debug flags. This centralizes environment-specific parameters.

Variables

  • engine

    The SQLAlchemy engine instance, configured with connection details and pooling. It manages the database connection pool and executes SQL statements for the application.

  • SessionLocal

    A factory for creating new SQLAlchemy Session objects. It ensures consistent session configuration, including transaction management and binding to the database engine.

  • Base

    The declarative base class for SQLAlchemy ORM models. It allows defining database tables and their relationships using Python classes for object-relational mapping.

Global Code

This code initializes the SQLAlchemy database engine, establishing connection parameters, pooling settings, and debug logging. It prepares the core interface for all database interactions. This code creates a local session factory, configuring it for non-autocommit and non-autoflush behavior. It binds the session factory to the previously initialized database engine. This code initializes the declarative base class for SQLAlchemy ORM models. It serves as the foundation for defining all database tables and their corresponding Python object mappings.

Functions

get_db

public

This generator function provides a database session for dependency injection, ensuring proper resource management. It creates a new `SessionLocal` instance, yields it for use, and guarantees the session is closed afterward, preventing connection leaks.
=== " "

Activity Diagram - "get_db" /app/core/database.pyActivity Diagram - "get_db"  Initialize database session (SessionLocal)Try Block: Provide Database SessionExecution pauses here until caller finishes or an exception occurs in caller's context.Yield database session to callerexception occurred in caller's context?yesnoCapture exceptionSet exception_occurred = trueCaller finished normallySet exception_occurred = falseCatch Block: Handle Exceptions (None Explicitly Handled by get_db)exception_occurred is true?yesnoget_db does not catch exceptions; they are re-raised after finally.Propagate exception to callerNo exception to handleFinally Block: Always Close Database SessionClose database session (db.close())   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "get_db" /app/core/database.pyActivity Diagram - "get_db"  Initialize database session (SessionLocal)Try Block: Provide Database SessionExecution pauses here until caller finishes or an exception occurs in caller's context.Yield database session to callerexception occurred in caller's context?yesnoCapture exceptionSet exception_occurred = trueCaller finished normallySet exception_occurred = falseCatch Block: Handle Exceptions (None Explicitly Handled by get_db)exception_occurred is true?yesnoget_db does not catch exceptions; they are re-raised after finally.Propagate exception to callerNo exception to handleFinally Block: Always Close Database SessionClose database session (db.close())   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "get_db" /app/core/database.pyMethod diagram - "get_db"  get_dbdbSessionLocal()db.close()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "get_db" /app/core/database.pyMethod diagram - "get_db"  get_dbdbSessionLocal()db.close()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "get_db" Sequence Diagram - "get_db"  get_dbSessionLocalDatabaseSessionCallerget_dbSessionLocalDatabaseSessionCallerCallerget_dbget_dbSessionLocalSessionLocalDatabaseSessionDatabaseSessionget_dbSessionLocalDatabaseSessionFunction Callget_db()Session InitializationSessionLocal()db_instanceDatabase Session Usagetryyield db_instanceCaller uses the database sessionCaller finishes using sessionSession Cleanupfinallyclose()session_closedGenerator finished/app/core/database.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "get_db" Sequence Diagram - "get_db"  get_dbSessionLocalDatabaseSessionCallerget_dbSessionLocalDatabaseSessionCallerCallerget_dbget_dbSessionLocalSessionLocalDatabaseSessionDatabaseSessionget_dbSessionLocalDatabaseSessionFunction Callget_db()Session InitializationSessionLocal()db_instanceDatabase Session Usagetryyield db_instanceCaller uses the database sessionCaller finishes using sessionSession Cleanupfinallyclose()session_closedGenerator finished/app/core/database.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def get_db():

Output / Return Values

  • db_session (Session)

    This function yields an active SQLAlchemy database session object. It provides a transactional scope for database operations, ensuring consistency and proper resource handling. The session is automatically closed after use, preventing resource leaks.

Logic / Execution Flow

  • Instantiate a new database session by calling SessionLocal(), assigning the result to db.
  • Begin a try block to manage the session's lifecycle.
  • Inside the try block, yield the db session object to the caller, making it available for database operations.
  • Execute a finally block, ensuring db.close() is called regardless of whether an exception occurred during the session's use or not.

Usage Tips

  • Utilize this get_db function as a FastAPI dependency to inject a database session into route handlers. This pattern ensures each request receives a fresh, isolated session, promoting clean resource management effectively.

  • Avoid directly calling db.close() within your route handlers when using this dependency. The finally block in get_db automatically handles session closure, preventing common resource leak issues effectively.

Additional Notes

  • The SessionLocal object is typically configured to be thread-local, ensuring each request or thread gets its own database session. This prevents concurrency issues and maintains data isolation effectively across the application.

  • This pattern is crucial for maintaining database connection pool health and preventing resource exhaustion in high-concurrency environments. It ensures connections are returned to the pool promptly after each request.

FAQs

Why is autocommit=False and autoflush=False used in SessionLocal?

These settings ensure explicit transaction control, preventing premature commits or flushes. This allows developers to manage transaction boundaries manually, enhancing data integrity and consistency across operations.

What is the benefit of configuring pool_pre_ping=True for the database engine?

pool_pre_ping=True ensures that database connections in the pool are still alive before being used. This prevents errors from stale connections, improving application reliability and stability significantly.

How does the get_db function facilitate database access in the application?

The get_db function provides a dependency injection pattern, yielding a database session for each request. It ensures proper session lifecycle management, including automatic closing, promoting resource efficiency and clean code.

Insights

Metric Score Level
Complexity 0.15 Simple
Security 0.90 Secure
Performance 0.90 Optimised