Metadata-Version: 2.5
Name: alchemic
Version: 0.1.0
Summary: SQLAlchemy 2.0 declarative models that are also Pydantic models, with Mapped[T] typing a type checker actually understands.
Project-URL: Repository, https://github.com/barrenore/alchemic
Project-URL: Issues, https://github.com/barrenore/alchemic/issues
Author: Steppestone
License-Expression: MIT
License-File: LICENSE
Keywords: orm,pydantic,sqlalchemy,typing
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.13
Requires-Dist: pydantic<3,>=2.11
Requires-Dist: sqlalchemy<2.1,>=2.0.31
Provides-Extra: dev
Requires-Dist: aiosqlite>=0.20; extra == 'dev'
Requires-Dist: alembic>=1.13; extra == 'dev'
Requires-Dist: black; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: psycopg[binary]>=3.2; extra == 'dev'
Requires-Dist: pylint; extra == 'dev'
Requires-Dist: pyright; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Requires-Dist: sqlalchemy[asyncio]; extra == 'dev'
Requires-Dist: ty==0.0.84; extra == 'dev'
Description-Content-Type: text/markdown

# alchemic

**alchemic** lets one class be both a SQLAlchemy 2.0 declarative model and a
validating Pydantic v2 model, declared once with `Mapped[T]`, and typed so that
pyright and mypy can tell a column from a value.

```sh
pip install alchemic
```

Requires Python 3.13 or later, SQLAlchemy 2.0.31 or later (not 2.1), and
Pydantic 2.11 or later.

## Quickstart

```python
import uuid

from sqlalchemy import String, create_engine

from alchemic import Mapped, Model, Session, mapped_column


class Character(Model):
    __tablename__ = "characters"
    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
    name: Mapped[str] = mapped_column(String(80))


engine = create_engine("sqlite://")
Model.metadata.create_all(engine)

with Session(engine) as session:
    session.add(Character(name="Rick"))  # validated by Pydantic
    session.commit()
    rick = session.exec(Character.where(Character.name == "Rick")).one()  # a Character
```

`Character.name` is a `TypedAttribute[str]`, an `InstrumentedAttribute` subclass:
queryable, with comparisons typed against `str`. `rick.name` is a `str`.

## Why

SQLModel annotates columns as bare `str` or `UUID`, so a type checker cannot tell
a column from a value. Downstream that means generated stub files, type-checker
suppressions, and `where(Character.name in names)` silently compiling to
`WHERE false`. SQLModel does this because Pydantic cannot build a schema for
`Mapped[str]`. alchemic teaches Pydantic to read `Mapped[T]` as `T`, so both
frameworks read the same annotation, and a type checker sees the difference:

```python
names = ["Rick", "Morty"]
character = Character(name="Rick")

Character.where(Character.name == "Rick")  # accepted: the ergonomic idiom survives
Character.where(Character.name in names)   # type error on both pyright and mypy
Character.where(Character.name == True)    # type error: compared against the column's type
Character(nme="Rick")                      # type error: constructors are checked too
character.update(nme="Rick")               # type error: so are partial updates


class Profile(Model):
    __tablename__ = "profiles"
    id: Mapped[int] = mapped_column(primary_key=True)
    age: Mapped[int] = mapped_column(String(3))  # type error: column type vs. annotation
```

Import `Mapped`, `mapped_column` and `relationship` from `alchemic`, not
`sqlalchemy.orm`. At runtime they are SQLAlchemy's; type checkers see versions
that check comparisons and constructors. `select`, `insert`, `update` and `delete`
are re-exported from SQLAlchemy for convenience.

## Relationships

Relationships are declared once per side, and pair up by themselves:

```python
from sqlalchemy import String

from alchemic import Mapped, Model, Related, link, mapped_column, path, prefetch
from alchemic import references, relationship


class Team(Model):
    __tablename__ = "teams"
    id: Mapped[int] = mapped_column(primary_key=True, init=False)  # set by the database
    name: Mapped[str] = mapped_column(String(40))
    heroes: Related[list["Hero"]] = relationship()


class Hero(Model):
    __tablename__ = "heroes"
    id: Mapped[int] = mapped_column(primary_key=True, init=False)
    name: Mapped[str] = mapped_column(String(80))  # 81 characters is a ValidationError
    team_id: Mapped[int | None] = mapped_column(
        references(Team.id, ondelete="CASCADE"), default=None
    )
    team: Related[Team | None] = relationship()  # without | None: refused, team_id is nullable
    powers: Related[list["Power"]] = relationship()


class Power(Model):
    __tablename__ = "powers"
    id: Mapped[int] = mapped_column(primary_key=True, init=False)
    heroes: Related[list[Hero]] = relationship()


hero_power = link(Hero.powers, Power.heroes)  # the many-to-many table, wired to both sides

session.exec(Team.where(Team.name == "red", prefetch=[path(Team.heroes, Hero.powers)]))
session.get(Hero, 1, options=prefetch(Hero, Hero.team))
path(Team.heroes, Power.heroes)  # type error: Power.heroes does not start at Hero
```

They are SQLAlchemy's own relationships, so `Hero.team` also works in `join()`,
`selectinload()` and `any()`.

`references(Team.id)` is a foreign key checked against the annotation:
`team_id: Mapped[str] = mapped_column(references(Team.id))` is a type error, since
`Team.id` is an `int`. A NOT NULL key that is usually set through its relationship
takes `default=None`, as in
`team_id: Mapped[int] = mapped_column(references(Team.id), default=None)`, so both
`Hero(team=red)` and `Hero(team_id=1)` work.

A many-to-many needs `link()`, which creates the association table: one column
per primary-key column of each side, each a foreign key with `ON DELETE CASCADE`.
`name=` names the table, and `prefixes=` prefixes its columns, which is required
when both sides are the same class. Call it before the first query.

## Construction and validation

Unlike SQLModel's `table=True` models, construction validates: wrong types,
constraint violations and `@field_validator` all apply. Loading a row does not
re-validate, so validation costs nothing on the read path and legacy rows stay
readable.

A constructor argument is optional exactly when its declaration gives a default,
`mapped_column(default=None)` included. A nullable or `server_default` column is
still required without one, the same rule as Pydantic's `x: str | None`.
`init=False` leaves a column out of the constructor, for values the database
sets, such as an autoincrementing primary key.

An instance is a row: it equals only itself, and can go in a `set`. Compare data
with `model_dump()`. Copying an instance raises, since a copy would share the
original's SQLAlchemy state; construct a new instance, or `update` this one.

## Writing

Writes are checked the same way:

```python
hero.update(name="Rick")  # validated, all or nothing
hero.update(patch)        # a Pydantic model or a mapping, for PATCH
session.exec(Hero.assign(name="Rick").where(Hero.id == 1))  # a typed UPDATE
team = await hero.load(Hero.team)  # an async lazy load, typed Team | None
```

## Values the model maintains

Values the model maintains itself are declared on the column. `default=` runs
when the row is inserted and `onupdate=` whenever an `UPDATE` changes it, bulk
ones included. Both take any function, checked against the annotation:

```python
import uuid
from datetime import UTC, date, datetime

from sqlalchemy import Date, DateTime

from alchemic import Mapped, Model, mapped_column


def utcnow() -> datetime:
    return datetime.now(UTC)


class Document(Model):
    __tablename__ = "documents"
    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4, readonly=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), default=utcnow, readonly=True
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), default=utcnow, onupdate=utcnow
    )
    touched_on: Mapped[date] = mapped_column(Date, default=date.today, onupdate=date.today)
    version: Mapped[int] = mapped_column(version=True, init=False)  # optimistic locking
```

`readonly=True` fields are set by the constructor. Changing one later, by
assignment or `update()`, raises a `ValidationError`. Writing back the value it
holds is allowed, and so is filling in a `None`. They are `readOnly` in the JSON
schema.

A `version=True` column is SQLAlchemy's `version_id_col`, starting at 1: a write
based on a stale read raises `StaleDataError`. It is read-only, unless the
application writes the version itself (`version_id_generator=False` in
`__mapper_args__`).

A preset is a plain function, and stays checked:

```python
def updated_at() -> Mapped[datetime]:
    return mapped_column(DateTime(timezone=True), default=utcnow, onupdate=utcnow)
```

## Hooks

For logic across fields, override a hook: `before_insert`, `before_update` or
`before_delete`. It runs inside the flush, under an `AsyncSession` too, so it is
a plain method; an `async def` hook is refused. `has_changed` tells what this
flush changes:

```python
class Task(Model):
    __tablename__ = "tasks"
    id: Mapped[int] = mapped_column(primary_key=True, init=False)
    status: Mapped[str] = mapped_column(String(20))
    completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), default=None)

    def before_update(self) -> None:
        if self.has_changed(Task.status):  # a misspelled attribute is a type error
            self.update(completed_at=utcnow() if self.status == "done" else None)

    def before_delete(self) -> None:
        if self.status != "done":
            raise PermissionError("only finished tasks can be deleted")
```

A bulk `UPDATE` runs no per-object code, so `Task.assign(...)` is refused for a
model with a `before_update` hook or `on_commit` update receivers.
`sqlalchemy.update(Task)` is the escape hatch: it bypasses both.

## Running code after commit

Code that should run once the data is committed, such as a broadcast or a cache
invalidation, is an `on_commit` receiver. It runs after the outermost transaction
commits, never for a rollback or a rolled-back savepoint, and
`await session.commit()` awaits an async one:

```python
from alchemic import Change, Deleted, Inserted, Updated, on_commit


async def publish(message: str) -> None: ...


@on_commit(Task)
async def broadcast(task: Task, change: Change) -> None:
    match change:  # Change = Inserted | Updated | Deleted
        case Inserted() | Deleted():
            await publish(f"task {task.id}")
        case Updated() if change.has_changed(Task.status):
            await publish(f"task {task.id} is {task.status}")


@on_commit(Task, Deleted)  # the receiver is told a Deleted
def forget(task: Task, change: Deleted) -> None: ...
```

The receiver is checked against the model and the kinds: one taking a `Hero`
for `Team`, or an `Updated` where only `Deleted` is registered, is a type error,
and a `match` that misses a kind fails `assert_never`. A receiver on a mixin
hears every model that inherits it. Any SQLAlchemy session runs receivers. If
receivers raise, all of them still run, and `commit()` then raises an
`ExceptionGroup`; the data is committed by then. Receivers are not durable:
work that must happen belongs in a job queue.

## Sessions

`alchemic.Session` and `alchemic.AsyncSession` are SQLAlchemy's, plus `exec`,
which types the result by what the statement selects, for any SQLAlchemy
statement. SQLModel's `exec` does that only for its own `select()`: a plain
`sqlalchemy.select` is typed as tuples but runs as rows. The async session adds
`stream_exec` for large results, and does not expire on commit. Build it with
`alchemic.async_sessionmaker`, which keeps that default.

## Field metadata

Metadata for forms, admin screens or API schemas can be attached to a field in
its `Annotated` type, and read back with `get_field_metadata`:

```python
from typing import Annotated

from alchemic import Extension, FieldExtension, get_field_metadata


class Upload(Model):
    __tablename__ = "uploads"
    id: Mapped[int] = mapped_column(primary_key=True, init=False)
    path: Mapped[Annotated[str, Extension(file_field=True, allow_upload=True)]] = mapped_column()
    owner: Mapped[Annotated[str, FieldExtension(widget="user-picker")]] = mapped_column()


get_field_metadata(Upload, "path")  # {'file_field': True, 'allow_upload': True}
```

`Extension` has typed keys (`editable`, `file_field`, `allow_upload`, and `extra`
for anything else); `FieldExtension` takes any keyword arguments.
`get_field_metadata` merges the column's `info`, then `Annotated` metadata, then
`json_schema_extra`, a later source winning on a shared key.

## Base classes and SQLModel

Every model inherits from `Model`, which has its own registry and `MetaData`. To
use a different one, with SQLModel during a migration for instance, declare a
base:

```python
from sqlalchemy.orm import registry

shared_registry = registry()


class Base(Model):
    __abstract__ = True
    registry = shared_registry  # or: metadata = MetaData() for a separate one
```

`create_model_base(registry=..., metadata=..., name=...)` builds the same class
at runtime, but mypy does not accept a variable as a base class, so declaring it
is the portable form.

`references()` also takes a plain SQLAlchemy model's column. SQLModel declares
its columns as plain values (`Scene.id: UUID`), so a SQLModel column type-checks
there only with stubs that type it as a column; without them, use
`ForeignKey("scenes.id")`.

## What importing alchemic changes

Two things outside alchemic's own classes:

- SQLAlchemy's `Mapped` gets a `__get_pydantic_core_schema__`, so Pydantic
  validates `Mapped[T]` as `T`, unless SQLAlchemy already provides one.
- SQLAlchemy's `Session` gets `after_commit`, `after_soft_rollback` and
  `after_transaction_end` listeners, which is how every session runs `on_commit`
  receivers. They cost a dictionary lookup when nothing is pending.

## Status

Alpha. The core is implemented and tested, but the API may still change, and a
0.x minor release may break it. See
[CHANGELOG.md](https://github.com/barrenore/alchemic/blob/main/CHANGELOG.md) for
release notes and [SPEC.md](https://github.com/barrenore/alchemic/blob/main/SPEC.md)
for the design and its rationale. Report bugs at
[github.com/barrenore/alchemic/issues](https://github.com/barrenore/alchemic/issues).

MIT licensed.
