From litestar
Provides an opinionated service/repository layer on top of SQLAlchemy 2.0+ with base models, automatic audit fields, and framework plugins for Litestar, FastAPI, Flask, Starlette, and Sanic.
How this skill is triggered — by the user, by Claude, or both
Slash command
/litestar:advanced-alchemyThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
- Use `Mapped[...]` for columns and `T | None` for optional fields.
references/bases.mdreferences/caching.mdreferences/commit-modes.mdreferences/fastapi-integration.mdreferences/filters.mdreferences/flask-integration.mdreferences/frameworks.mdreferences/litestar_plugin.mdreferences/migrations.mdreferences/models.mdreferences/multi-database.mdreferences/operations.mdreferences/replicas.mdreferences/repositories.mdreferences/sanic-integration.mdreferences/services.mdreferences/starlette-integration.mdreferences/storage.mdreferences/types.mdMapped[...] for columns and T | None for optional fields.Repo service pattern and advanced_alchemy.* imports.from __future__ import annotations when it matches the project; 1.11
supports it in model modules.advanced-alchemy ships first-party extensions for five web frameworks. If your project uses one of these, jump directly to the matching integration guide and skip the others:
SQLAlchemyPlugin with full DI, session store, CLI. The rest of this SKILL.md covers Litestar by default; also see references/litestar_plugin.md.references/fastapi-integration.md — AdvancedAlchemy(config=..., app=app), Depends(alchemy.provide_session()) DI, provide_service()/provide_filters(), Alembic CLI via assign_cli_group.references/flask-integration.md — AdvancedAlchemy(config=..., app=app) or init_app() factory, pull-based alchemy.get_sync_session(), async-via-portal.references/sanic-integration.md — AdvancedAlchemy(sqlalchemy_config=..., sanic_app=app) (note: sqlalchemy_config= kwarg, not config=), sanic-ext DI, request.ctx sessions.references/starlette-integration.md — AdvancedAlchemy(config=..., app=app), request.state session access, lifespan wrapping.Transaction configuration is framework-specific. Litestar uses
before_send_handler; FastAPI, Flask, Starlette, and Sanic use
commit_mode="manual", "autocommit", or
"autocommit_include_redirect". Read the matching framework guide, then
references/commit-modes.md and
references/multi-database.md.
The rest of this SKILL.md covers framework-agnostic topics: base classes, repositories, services, filters, custom types, caching, replicas, operations, and Alembic migrations.
Advanced Alchemy is NOT a raw ORM — it is a service/repository layer built on top of SQLAlchemy 2.0+ with opinionated base classes, audit mixins, and deep framework integrations (Litestar, FastAPI, Flask, Starlette, Sanic). It provides:
id, created_at, updated_at fieldsto_model_on_create, to_model_on_update)EncryptedString, FileObject, DateTimeUTC, GUID, Bool, Vector, TOTPSecret, OneTimeCode| Base Class | PK Type | Audit Columns | When to Use |
|---|---|---|---|
UUIDAuditBase | UUID v4 | created_at, updated_at | Default choice for most models |
UUIDBase | UUID v4 | None | Lookup tables, tags, no audit needed |
UUIDv7AuditBase | UUID v7 | created_at, updated_at | Time-sortable IDs (preferred over v6) |
BigIntAuditBase | BigInt auto-increment | created_at, updated_at | Legacy systems, integer PKs |
NanoIDAuditBase | NanoID string | created_at, updated_at | URL-friendly short IDs |
IdentityAuditBase | database identity | created_at, updated_at | Native IDENTITY columns |
DefaultBase | None (define yourself) | None | Custom primary keys with AA table naming |
| Repository | Purpose |
|---|---|
SQLAlchemyAsyncRepository[Model] | Standard async CRUD |
SQLAlchemyAsyncSlugRepository[Model] | CRUD + automatic slug generation |
SQLAlchemyAsyncQueryRepository | Complex read-only queries (no model_type) |
| Service | Purpose |
|---|---|
SQLAlchemyAsyncRepositoryService[Model] | Full CRUD with lifecycle hooks |
SQLAlchemyAsyncRepositoryReadService[Model] | Read-only (get_many, get, count, exists) |
Key lifecycle hooks: to_model_on_create, to_model_on_update, to_model_on_upsert.
| Type | Purpose | Notes |
|---|---|---|
FileObject | Object storage with lifecycle hooks | Tracks file state across session; auto-deletes on row delete via StoredObject tracker |
PasswordHash | Hashed password storage | Supports Argon2, Passlib, and Pwdlib backends; hashes on assignment |
EncryptedString | Transparent encryption at rest | Pass a stable key explicitly; the random default is deprecated |
UUID6 / UUID7 | Time-sortable UUID variants | UUID7 preferred for standardized timestamp-ordered identifiers |
DateTimeUTC | Timezone-aware UTC datetime | Stores as UTC; raises on naive datetimes |
Bool | Dialect-aware boolean | Uses Oracle 23c native BOOLEAN when SQLAlchemy exposes it; falls back to stock SQLAlchemy Boolean |
Vector | Dialect-aware vector storage and distance operators | Oracle 23ai VECTOR, PostgreSQL/CockroachDB pgvector, JSON fallback without distance operators |
TOTPSecret / OneTimeCode | MFA and single-use code storage | TOTPSecret encrypts shared secrets; OneTimeCode hashes codes and requires an explicit hashing backend |
SQLAlchemyAsyncRepositoryService is the primary service base class. Key behaviors:
dict to create(), update(), upsert() — the service converts via to_model_on_create / to_model_on_update lifecycle hooks before persistencecreate_many(data), update_many(data), upsert_many(data), delete_many(item_ids) — batched in a single transaction; delete_many() accepts raw primary keys, composite-key tuples/dicts, model instances, or mixed liststo_model_on_create, to_model_on_update, to_model_on_upsert — override to transform input data, hash passwords, normalize strings, etc.| Mixin | Fields Added | When to Use |
|---|---|---|
AuditColumns | created_at, updated_at | Add timestamps to a model with a custom primary key |
SlugKey | unique slug column | Pair with a slug repository; the mixin does not generate values |
UniqueMixin | as_unique_async() / as_unique_sync() | Session-cached select-or-create after defining unique_hash() and unique_filter() |
SentinelMixin | hidden sa_orm_sentinel column | Deterministic ordering for SQLAlchemy bulk inserts; not optimistic locking |
Use SQLAlchemyPlugin (composite of SQLAlchemyInitPlugin + SQLAlchemySerializationPlugin) for full integration:
SQLAlchemyPlugin: registers engine/session providers, a Litestar
before_send hook, and ORM type encoders in one callSQLAlchemyDTO: generates Litestar DTOs directly from ORM models with include/exclude field controldatetime, UUID, Decimal, Enum, and custom column typesset_default_exception_handler=True (the default)
registers RepositoryError handling through the pluginChoose the appropriate base class from the quick reference table. Use UUIDAuditBase unless you have a specific reason not to. Define columns with Mapped[] typing.
Create a repository class with model_type set to your model. Use SQLAlchemyAsyncRepository for standard CRUD, SQLAlchemyAsyncSlugRepository if the model uses SlugKey.
Create a service class with an inner Repo class. Set match_fields for upsert logic. Add lifecycle hooks (to_model_on_create, to_model_on_update) for business logic transformations.
Use the framework plugin (Litestar, FastAPI, Flask, Sanic) to inject sessions and register the service as a dependency.
With Litestar, run litestar database make-migrations -m "description" and
then litestar database upgrade. With the standalone CLI, put the required
config option before the command:
alchemy --config path.to.config make-migrations -m "description".
match_fields on services that use upsert() to avoid duplicate-key errorsschema_dump() / schema_dump_config for explicit dump behavior — services already convert Pydantic/msgspec/attrs/dataclass inputs during model conversionUUIDAuditBase as default base class — only deviate when you have a concrete reasonadvanced_alchemy.* imports — the old litestar.plugins.sqlalchemy paths are deprecatedEncryptedString and EncryptedText. Omitting
key= emits a 1.11 deprecation warning and produces data that cannot survive
a process restart.get_many() and get_many_and_count(). list() and
list_and_count() are deprecated until 2.0.Before delivering code, verify:
DeclarativeBase from SQLAlchemy)Mapped[] type annotationsRepo class with model_type setadvanced_alchemy.*, not deprecated pathsget_many() / get_many_and_count(), not deprecated list aliasesA complete Tag entity with model, repository, and service:
"""Tag domain — model, repository, and service."""
from advanced_alchemy.base import UUIDAuditBase
from advanced_alchemy.repository import SQLAlchemyAsyncRepository
from advanced_alchemy.service import ModelDictT, SQLAlchemyAsyncRepositoryService
from sqlalchemy.orm import Mapped, mapped_column
class Tag(UUIDAuditBase):
"""Tag model with audit trail."""
__tablename__ = "tag"
name: Mapped[str] = mapped_column(unique=True)
description: Mapped[str | None] = mapped_column(default=None)
class TagRepository(SQLAlchemyAsyncRepository[Tag]):
"""Data access for tags."""
model_type = Tag
class TagService(SQLAlchemyAsyncRepositoryService[Tag]):
"""Business logic for tags."""
class Repo(SQLAlchemyAsyncRepository[Tag]):
model_type = Tag
repository_type = Repo
match_fields = ["name"]
async def to_model_on_create(self, data: ModelDictT[Tag]) -> ModelDictT[Tag]:
"""Normalize tag name before creation."""
if isinstance(data, dict) and "name" in data:
data["name"] = data["name"].strip().lower()
return data
Choosing between
advanced-alchemyandsqlspec:advanced-alchemy(this skill) gives you an opinionated ORM service layer withUUIDAuditBase, lifecycle hooks, repository / service / Alembic integration, andOffsetPagination[T]out of the box — pick it when you want a complete CRUD surface with attribute-style row access and you're happy inside the SQLAlchemy ecosystem.sqlspecgives you direct SQL control, 15+ driver adapters (asyncpg, oracledb, DuckDB, BigQuery, SQLite, and more), Arrow-native result streams for analytics, and a builder API when you need it — pick it when you want explicit SQL, heterogeneous database backends, or Arrow integration. Both skills integrate with Litestar via first-party plugins; see../sqlspec/SKILL.mdfor the raw-SQL / multi-adapter path.
For detailed guides and code examples, refer to the following documents in references/:
OnConflictUpsert / MergeStatement dialect-aware upsert building blocks, session event listeners (FileObject, cache invalidation, touch_updated_timestamp), and the msgspec-first encode_json / decode_json used across the library.npx claudepluginhub litestar-org/litestar-skills --plugin litestarGuides completion of development work by verifying tests, detecting environment, and presenting structured options for merge, PR, or cleanup.
Enforces test-driven development: write failing test first, then minimal code to pass. Use when implementing features or bugfixes.
Guides creation and editing of skills using test-driven development with pressure scenarios and subagents to verify agent compliance.