|
1 | 1 | # db-try |
2 | 2 |
|
3 | | -This library provides retry decorators for sqlalchemy and some helpers |
| 3 | +A Python library providing robust retry mechanisms, connection utilities, and transaction helpers for PostgreSQL and SQLAlchemy applications. |
4 | 4 |
|
5 | | -Default settings are in [./db_try/settings.py](db_try/settings.py). |
6 | | -You can redefine them by environment variables. |
| 5 | +## Features |
| 6 | + |
| 7 | +- **Retry Decorators**: Automatic retry logic for transient database errors |
| 8 | +- **Connection Factories**: Robust connection handling with multi-host support |
| 9 | +- **DSN Utilities**: Flexible Data Source Name parsing and manipulation |
| 10 | +- **Transaction Helpers**: Simplified transaction management with automatic cleanup |
| 11 | + |
| 12 | +## Installation |
| 13 | + |
| 14 | +### Using uv |
| 15 | + |
| 16 | +```bash |
| 17 | +uv add db-try |
| 18 | +``` |
| 19 | + |
| 20 | +### Using pip |
| 21 | + |
| 22 | +```bash |
| 23 | +pip install db-try |
| 24 | +``` |
| 25 | + |
| 26 | +## ORM-Based Usage Examples |
| 27 | + |
| 28 | +### 1. Database Operations with Automatic Retry |
| 29 | + |
| 30 | +Protect your database operations from transient failures using ORM models: |
| 31 | + |
| 32 | +```python |
| 33 | +import asyncio |
| 34 | +import sqlalchemy as sa |
| 35 | +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession |
| 36 | +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column |
| 37 | +from db_try import postgres_retry |
| 38 | + |
| 39 | +class User(DeclarativeBase): |
| 40 | + __tablename__ = "users" |
| 41 | + |
| 42 | + id: Mapped[int] = mapped_column(primary_key=True) |
| 43 | + name: Mapped[str] = mapped_column(sa.String()) |
| 44 | + email: Mapped[str] = mapped_column(sa.String(), index=True) |
| 45 | + |
| 46 | +# Apply retry logic to ORM operations |
| 47 | +@postgres_retry |
| 48 | +async def get_user_by_email(session: AsyncSession, email: str) -> User: |
| 49 | + return await session.scalar( |
| 50 | + sa.select(User).where(User.email == email) |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +async def main(): |
| 55 | + engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/mydb") |
| 56 | + async with AsyncSession(engine) as session: |
| 57 | + # Automatically retries on connection failures or serialization errors |
| 58 | + user = await get_user_by_email(session, "john.doe@example.com") |
| 59 | + if user: |
| 60 | + print(f"Found user: {user.name}") |
| 61 | + |
| 62 | +asyncio.run(main()) |
| 63 | +``` |
| 64 | + |
| 65 | +### 2. High Availability Database Connections |
| 66 | + |
| 67 | +Set up resilient database connections with multiple fallback hosts: |
| 68 | + |
| 69 | +```python |
| 70 | +import sqlalchemy as sa |
| 71 | +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession |
| 72 | +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column |
| 73 | +from db_try import build_connection_factory, build_db_dsn |
| 74 | + |
| 75 | + |
| 76 | +# Configure multiple database hosts for high availability |
| 77 | +multi_host_dsn = ( |
| 78 | + "postgresql://user:password@/" |
| 79 | + "myapp_db?" |
| 80 | + "host=primary-db:5432&" |
| 81 | + "host=secondary-db:5432&" |
| 82 | + "host=backup-db:5432" |
| 83 | +) |
| 84 | + |
| 85 | +# Build production-ready DSN |
| 86 | +dsn = build_db_dsn( |
| 87 | + db_dsn=multi_host_dsn, |
| 88 | + database_name="production_database", |
| 89 | + drivername="postgresql+asyncpg" |
| 90 | +) |
| 91 | + |
| 92 | +# Create connection factory with timeout |
| 93 | +connection_factory = build_connection_factory( |
| 94 | + url=dsn, |
| 95 | + timeout=5.0 # 5 second connection timeout |
| 96 | +) |
| 97 | + |
| 98 | +# Engine will automatically try different hosts on failure |
| 99 | +engine = create_async_engine(dsn, async_creator=connection_factory) |
| 100 | +``` |
| 101 | + |
| 102 | +### 3. Simplified Transaction Management |
| 103 | + |
| 104 | +Handle database transactions with automatic cleanup using ORM: |
| 105 | + |
| 106 | +```python |
| 107 | +import dataclasses |
| 108 | +import datetime |
| 109 | +import typing |
| 110 | + |
| 111 | +from schemas import AnalyticsEventCreate, AnalyticsEvent |
| 112 | +from db_try import Transaction, postgres_retry |
| 113 | + |
| 114 | +from your_service_name.database.tables import EventsTable |
| 115 | +from your_service_name.producers.analytics_service_events_producer import AnalyticsEventsProducer |
| 116 | +from your_service_name.repositories.events_repository import EventsRepository |
| 117 | +from your_service_name.settings import settings |
| 118 | + |
| 119 | + |
| 120 | +@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 121 | +class CreateEventUseCase: |
| 122 | + events_repository: EventsRepository |
| 123 | + transaction: Transaction |
| 124 | + analytics_events_producer: AnalyticsEventsProducer |
| 125 | + |
| 126 | + @postgres_retry |
| 127 | + async def __call__( |
| 128 | + self, |
| 129 | + event_create_data: AnalyticsEventCreate, |
| 130 | + ) -> AnalyticsEvent: |
| 131 | + async with self.transaction: |
| 132 | + model: typing.Final = EventsTable( |
| 133 | + **event_create_data.model_dump(), |
| 134 | + created_at=datetime.datetime.now(tz=settings.common.default_timezone), |
| 135 | + ) |
| 136 | + saved_event: typing.Final[EventsTable] = await self.events_repository.create(model) |
| 137 | + event: typing.Final = AnalyticsEvent.model_validate(saved_event) |
| 138 | + await self.analytics_events_producer.send_message(event) |
| 139 | + await self.transaction.commit() |
| 140 | + return event |
| 141 | + |
| 142 | +``` |
| 143 | + |
| 144 | +### 4. Serializable Transactions for Consistency |
| 145 | + |
| 146 | +Use serializable isolation level to prevent race conditions with ORM: |
| 147 | + |
| 148 | +```python |
| 149 | +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine |
| 150 | +from db_try import Transaction |
| 151 | + |
| 152 | + |
| 153 | +async def main(): |
| 154 | + engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/mydb") |
| 155 | + |
| 156 | + async with AsyncSession(engine) as session: |
| 157 | + strict_transaction = Transaction( |
| 158 | + session=session, |
| 159 | + isolation_level="SERIALIZABLE", |
| 160 | + ) |
| 161 | + # use strict_transaction where needed |
| 162 | +``` |
| 163 | + |
| 164 | +## Configuration |
| 165 | + |
| 166 | +The library can be configured using environment variables: |
| 167 | + |
| 168 | +| Variable | Description | Default | |
| 169 | +|---------------------------|--------------------------------------------------|---------| |
| 170 | +| `DB_UTILS_RETRIES_NUMBER` | Number of retry attempts for database operations | 3 | |
| 171 | + |
| 172 | +Example: |
| 173 | +```bash |
| 174 | +export DB_UTILS_RETRIES_NUMBER=5 |
| 175 | +``` |
| 176 | + |
| 177 | +## API Reference |
| 178 | + |
| 179 | +### Retry Decorator |
| 180 | +- `@postgres_retry` - Decorator for async functions that should retry on database errors |
| 181 | + |
| 182 | +### Connection Utilities |
| 183 | +- `build_connection_factory(url, timeout)` - Creates a connection factory for multi-host setups |
| 184 | +- `build_db_dsn(db_dsn, database_name, use_replica=False, drivername="postgresql")` - Builds a DSN with specified parameters |
| 185 | +- `is_dsn_multihost(db_dsn)` - Checks if a DSN contains multiple hosts |
| 186 | + |
| 187 | +### Transaction Helper |
| 188 | +- `Transaction(session, isolation_level=None)` - Context manager for simplified transaction handling |
| 189 | + |
| 190 | +## Requirements |
| 191 | + |
| 192 | +- Python 3.13+ |
| 193 | +- SQLAlchemy with asyncio support |
| 194 | +- asyncpg PostgreSQL driver |
| 195 | +- tenacity for retry logic |
| 196 | + |
| 197 | +## License |
| 198 | + |
| 199 | +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. |
0 commit comments