Metadata-Version: 2.4
Name: hawkapi-sqlalchemy
Version: 0.2.0
Summary: SQLAlchemy integration for HawkAPI — async sessions, multi-database routing, Alembic helpers, pytest fixtures
Project-URL: Homepage, https://pypi.org/project/hawkapi-sqlalchemy/
Project-URL: Repository, https://github.com/ashimov/hawkapi-sqlalchemy
Project-URL: Issues, https://github.com/ashimov/hawkapi-sqlalchemy/issues
Author-email: HawkAPI Contributors <hawkapi@users.noreply.github.com>
License: MIT License
        
        Copyright (c) 2026 HawkAPI Contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: alembic,async,database,hawkapi,mysql,postgres,sqlalchemy
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Database :: Front-Ends
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: aiosqlite>=0.20
Requires-Dist: alembic>=1.13
Requires-Dist: hawkapi>=0.1.7
Requires-Dist: sqlalchemy[asyncio]>=2.0
Provides-Extra: dev
Requires-Dist: pyright>=1.1; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Provides-Extra: mysql
Requires-Dist: aiomysql>=0.2; extra == 'mysql'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29; extra == 'postgres'
Description-Content-Type: text/markdown

# hawkapi-sqlalchemy

SQLAlchemy integration for [HawkAPI](https://github.com/ashimov/HawkAPI). Async sessions, multi-database routing (primary/replica/shards), Alembic helpers, and pytest fixtures.

## Install

```bash
pip install hawkapi-sqlalchemy                     # SQLite included
pip install 'hawkapi-sqlalchemy[postgres]'         # + asyncpg
pip install 'hawkapi-sqlalchemy[mysql]'            # + aiomysql
```

## Quickstart

```python
from hawkapi import Depends, HawkAPI
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column

from hawkapi_sqlalchemy import Base, TimestampMixin, get_session, init_database


class User(Base, TimestampMixin):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    email: Mapped[str] = mapped_column(unique=True)


app = HawkAPI()
init_database(app, url="postgresql+asyncpg://user:pw@localhost/app")


@app.post("/users")
async def create(email: str, sess: AsyncSession = Depends(get_session)):
    sess.add(User(email=email))
    await sess.flush()
    return {"ok": True}
```

The `get_session` dependency opens a fresh session per request, **commits on success**, and **rolls back on exception** — no boilerplate.

## Multiple databases

```python
from hawkapi_sqlalchemy import DatabaseConfig, init_database, session_for

init_database(
    app,
    databases={
        "primary": DatabaseConfig(url="postgresql+asyncpg://…/primary"),
        "replica": DatabaseConfig(url="postgresql+asyncpg://…/replica"),
        "analytics": DatabaseConfig(url="postgresql+asyncpg://…/analytics"),
    },
)

# DI helpers:
from hawkapi_sqlalchemy import get_session, get_replica_session

get_analytics = session_for("analytics", commit=False)


@app.get("/report")
async def report(sess: AsyncSession = Depends(get_analytics)):
    ...
```

`get_replica_session` falls back to `primary` if no replica is registered, so you can switch on without changing handlers.

## Mixins

```python
from hawkapi_sqlalchemy import Base, TimestampMixin, UUIDMixin


class Doc(Base, UUIDMixin, TimestampMixin):
    __tablename__ = "docs"
    title: Mapped[str] = mapped_column()
```

- `TimestampMixin` — `created_at` / `updated_at` with DB-side defaults + Python `onupdate`.
- `UUIDMixin` — string `id` column with a `uuid4()` default.
- Prefer `DataclassBase` over `Base` to get SQLAlchemy 2.0's dataclass-style declarative.

## Alembic

In your `alembic/env.py`:

```python
from hawkapi_sqlalchemy.alembic import run_migrations
from myapp.db import Base, settings  # your Base + URL

run_migrations(target_metadata=Base.metadata, url=settings.database_url)
```

That's it — handles both online (live connection) and offline (`--sql`) modes; uses `NullPool` for migrations; enables `render_as_batch=True` automatically for SQLite.

## Healthchecks

```python
from hawkapi_sqlalchemy import all_healthy


@app.get("/healthz")
async def healthz():
    return await all_healthy(app.state.db)
```

Returns `{"primary": True, "replica": True, ...}`.

## Testing

```python
import pytest
from hawkapi_sqlalchemy import Base, temporary_database


@pytest.fixture
async def db():
    async with temporary_database(Base.metadata) as database:
        yield database


async def test_something(db):
    async with db.session() as sess:
        ...
```

`temporary_database` creates an in-memory SQLite engine, calls `Base.metadata.create_all`, yields, then drops the schema and disposes.

## DatabaseConfig

```python
DatabaseConfig(
    url="postgresql+asyncpg://…",
    echo=False,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30.0,
    pool_recycle=3600,
    pool_pre_ping=True,
    connect_args={"server_settings": {"jit": "off"}},
    engine_kwargs={...},     # forwarded to create_async_engine
    session_kwargs={...},    # forwarded to async_sessionmaker
)
```

## Development

```bash
git clone https://github.com/ashimov/hawkapi-sqlalchemy.git
cd hawkapi-sqlalchemy
uv sync --extra dev
uv run pytest -q
uv run ruff check . && uv run ruff format --check .
uv run pyright src/
```

## License

MIT.
