service ¶
Database Service for Tux Bot.
This module provides a clean, maintainable database service for async PostgreSQL operations.
Key Principles: - Async-first design - Connection pooling with retry logic - Type-safe interfaces - Automatic reconnection handling
Classes:
-
DatabaseService–Async database service for PostgreSQL.
Classes¶
DatabaseService ¶
DatabaseService(echo: bool = False)
Async database service for PostgreSQL.
Provides connection management, session handling, query execution with retry logic, and health checks for the PostgreSQL database.
Attributes:
-
_engine(AsyncEngine | None) –SQLAlchemy async engine for database connections.
-
_session_factory(async_sessionmaker[AsyncSession] | None) –Factory for creating database sessions.
-
_echo(bool) –Whether to log SQL queries (useful for debugging).
Initialize the database service.
Parameters:
-
echo(bool, default:False) –Whether to enable SQL query logging (default is False).
-
afk ClassesAfkController Attributesdb_service -
base ClassesBaseController Attributesdb_service -
base_controller ClassesBaseController Attributesdb_service -
case ClassesCaseController Attributesdb_service -
controllers Classes-
AfkController Attributesdb_service -
BaseController Attributesdb_service -
CaseController Attributesdb_service -
GuildConfigController Attributesdb_service -
GuildController Attributesdb_service -
LevelsController Attributesdb_service -
PermissionAssignmentController Attributesdb_service -
PermissionCommandController Attributesdb_service -
PermissionRankController Attributesdb_service -
ReminderController Attributesdb_service -
SnippetController Attributesdb_service -
StarboardController Attributesdb_service -
StarboardMessageController Attributesdb_service
-
-
guild ClassesGuildController Attributesdb_service -
guild_config ClassesGuildConfigController Attributesdb_service -
levels ClassesLevelsController Attributesdb_service -
permissions Classes -
reminder ClassesReminderController Attributesdb_service -
snippet ClassesSnippetController Attributesdb_service -
starboard Classes -
utils Functionsget_db_service_from
-
afk ClassesAfkController -
base ClassesBaseController -
base_controller ClassesBaseController -
bulk ClassesBulkOperationsController -
case ClassesCaseController -
controllers Classes -
crud ClassesCrudController -
database_setup ClassesDatabaseSetupService -
guild ClassesGuildController -
guild_config ClassesGuildConfigController -
levels ClassesLevelsController -
pagination ClassesPaginationController -
performance ClassesPerformanceController -
permission_setup ClassesPermissionSetupService -
permissions Classes -
query ClassesQueryController -
reminder ClassesReminderController -
snippet ClassesSnippetController -
starboard Classes -
transaction ClassesTransactionController -
upsert ClassesUpsertController
Methods:
-
connect–Connect to the PostgreSQL database.
-
disconnect–Disconnect from the database and dispose of the connection pool.
-
is_connected–Check if database is currently connected.
-
test_connection–Test database connectivity with a simple query.
-
session–Get a database session context manager.
-
execute_transaction–Execute a callback inside a database transaction.
-
execute_query–Execute database operation with automatic retry logic.
-
health_check–Perform database health check.
-
validate_schema–Validate that the database schema matches the current model definitions.
Attributes¶
engine property ¶
engine: AsyncEngine | None
Get the database engine.
Returns:
-
AsyncEngine | None–The SQLAlchemy async engine, or None if not connected.
Notes
Primarily used for testing and advanced operations.
Functions¶
connect async ¶
disconnect async ¶
disconnect() -> None
Disconnect from the database and dispose of the connection pool.
test_connection async ¶
test_connection() -> None
Test database connectivity with a simple query.
Raises:
-
Exception–If the database connection fails or the test query fails.
session async ¶
session() -> AsyncGenerator[AsyncSession]
Get a database session context manager.
Automatically handles connection, commit, and rollback.
Yields:
-
AsyncSession–An active database session.
Examples:
>>> async with db.session() as session:
... result = await session.execute(select(User))
... users = result.scalars().all()
execute_transaction async ¶
execute_query async ¶
execute_query(operation: Callable[[AsyncSession], Awaitable[T]], span_desc: str) -> T
Execute database operation with automatic retry logic.
Parameters:
-
operation(Callable[[AsyncSession], Awaitable[T]]) –Async function that performs database operations.
-
span_desc(str) –Description for Sentry performance monitoring.
Returns:
-
T–Result of the operation.
Notes
Retries the operation automatically on transient failures.
_execute_with_retry async ¶
_execute_with_retry(
operation: Callable[[AsyncSession], Awaitable[T]],
span_desc: str,
max_retries: int = 3,
backoff_factor: float = 0.5,
) -> T
Execute database operation with exponential backoff retry logic.
Parameters:
-
operation(Callable[[AsyncSession], Awaitable[T]]) –Database operation to execute.
-
span_desc(str) –Description for monitoring/logging.
-
max_retries(int, default:3) –Maximum number of retry attempts (default is 3).
-
backoff_factor(float, default:0.5) –Multiplier for exponential backoff (default is 0.5).
Returns:
-
T–Result of the operation.
Raises:
-
TimeoutError–If the operation times out after all retries.
-
DisconnectionError–If database disconnection occurs after all retries.
-
OperationalError–If database operational error occurs after all retries.
-
RuntimeError–If the retry loop completes unexpectedly without return or exception.
health_check async ¶
Perform database health check.
Returns:
-
dict[str, Any]–Health check result with status and optional error message. Status can be: "healthy", "unhealthy", or "disconnected".
Examples:
>>> result = await db.health_check()
>>> print(result)
{'status': 'healthy', 'mode': 'async'}
validate_schema async ¶
Validate that the database schema matches the current model definitions.
Uses SQLAlchemy's metadata reflection to compare the actual database schema with the defined model metadata. Much more efficient and accurate than manual queries.
Returns:
-
dict[str, Any]–Schema validation result with status and optional error message. Status can be: "valid", "invalid", or "error".
Examples:
>>> result = await db.validate_schema()
>>> print(result)
{'status': 'valid', 'mode': 'async'}