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.
Imports
-
create_engine from sqlalchemyConfigures 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.ormsessionmakercreates a configurable factory forSessionobjects, managing database conversations.declarative_baseprovides a base class for ORM model definitions. -
settings from app.core.configProvides application-wide configuration values, including the database connection string and debug flags. This centralizes environment-specific parameters.
Variables
-
engineThe SQLAlchemy engine instance, configured with connection details and pooling. It manages the database connection pool and executes SQL statements for the application.
-
SessionLocalA factory for creating new SQLAlchemy
Sessionobjects. It ensures consistent session configuration, including transaction management and binding to the database engine. -
BaseThe 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.
def get_db():
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.
- Instantiate a new database session by calling
SessionLocal(), assigning the result todb. - Begin a
tryblock to manage the session's lifecycle. - Inside the
tryblock,yieldthedbsession object to the caller, making it available for database operations. - Execute a
finallyblock, ensuringdb.close()is called regardless of whether an exception occurred during the session's use or not.
Usage Tips
-
Utilize this
get_dbfunction 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. Thefinallyblock inget_dbautomatically handles session closure, preventing common resource leak issues effectively.
Additional Notes
-
The
SessionLocalobject 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=Trueensures 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_dbfunction 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 |