advanced-alchemy
Skill19 starsChanged 10 days agoMITView on GitHub
Use when working with advanced_alchemy, alembic/, SQLAlchemyAsyncRepositoryService, SQLAlchemyAsyncConfig, ServiceGroup, FilterSet, CursorFilter, RelationshipFilter, filters, or storage. Not for raw SQLAlchemy — use sqlspec.
- Reads credentials
In this repository20 other files it gives its agents.
- AGENTS.mdAGENTS.md
- litestar-autowireSkill
- litestar-buildSkill
- litestar-deploymentSkill
- litestar-docsSkill
- litestar-emailSkill
- litestar-granianSkill
- litestar-htmxSkill
- litestar-mcpSkill
- litestar-queuesSkill
- litestar-saqSkill
- litestar-securitySkill
- litestarSkill
- litestar-styleguideSkill
- litestar-testingSkill
- litestar-viteSkill
- msgspecSkill
- polyfactorySkill
- pytest-databasesSkill
- sqlspecSkill
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 6 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 10
Use Mapped[...] for columns and T | None for optional fields.
- Distinctive: line 11
Keep business transformations in service lifecycle hooks.
- Very specific: line 12
Prefer SQLAlchemyAsyncRepositoryService[Model] (infers a default repo) or SQLAlchemyAsyncRepositoryService[Model, CustomRepo] (types custom …
- Very specific: line 13
Use from __future__ import annotations when it matches the project.
- Very specific: line 114
Use SQLAlchemyPlugin (composite of SQLAlchemyInitPlugin + SQLAlchemySerializationPlugin) for full integration:
- Very specific: line 134
Create a repository class with model_type set to your model.
- Very specific: line 138
Create a service class with an inner Repo class.
- Distinctive: line 142
Use the framework plugin (Litestar, FastAPI, Flask, Sanic) to inject sessions and register the service as a dependency.
- Distinctive: line 178
Before delivering code, verify:
- Distinctive: line 267
Read/write routing, RoutingConfig, engine groups, RoundRobinSelector/RandomSelector, sticky-after-write consistency, context managers for …
- Distinctive: line 287
Use shared styleguides for generic language/framework rules to reduce duplication in this skill.
- Distinctive: line 291
Keep this skill focused on tool-specific workflows, edge cases, and integration details.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Advanced Alchemy
Code Style Rules
- Use
Mapped[...]for columns andT | Nonefor optional fields. - Keep business transformations in service lifecycle hooks.
- Prefer
SQLAlchemyAsyncRepositoryService[Model](infers a default repo) orSQLAlchemyAsyncRepositoryService[Model, CustomRepo](types custom repo methods) andadvanced_alchemy.*imports. - Use
from __future__ import annotationswhen it matches the project; 1.12+ supports it in model modules.
Match-Your-Framework — read first
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:
- Litestar —
SQLAlchemyPluginwith full DI, session store, CLI. The rest of this SKILL.md covers Litestar by default; also seereferences/litestar_plugin.md. - FastAPI →
references/fastapi-integration.md—AdvancedAlchemy(config=..., app=app),Depends(alchemy.provide_session())DI,provide_service()/provide_filters(), Alembic CLI viaassign_cli_group. - Flask →
references/flask-integration.md—AdvancedAlchemy(config=..., app=app)orinit_app()factory, pull-basedalchemy.get_sync_session(), async-via-portal. - Sanic →
references/sanic-integration.md—AdvancedAlchemy(sqlalchemy_config=..., sanic_app=app)(note:sqlalchemy_config=kwarg, notconfig=), sanic-ext DI,request.ctxsessions. - Starlette →
references/starlette-integration.md—AdvancedAlchemy(config=..., app=app),request.statesession 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.
Overview
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:
- Base models with automatic
id,created_at,updated_atfields - Repository pattern for type-safe async CRUD
- Service layer with lifecycle hooks (
to_model_on_create,to_model_on_update,to_model_on_upsert,to_model_on_delete) - Framework plugins for automatic session/transaction management
- Custom types:
EncryptedString,EncryptedText,PasswordHash,FileObject,StoredObject,DateTimeUTC,GUID,Bool,JsonB,Vector,TOTPSecret,OneTimeCode - Alembic integration for migrations via CLI
Quick Reference
Base Classes
| 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 / UUIDv7Base | UUID v7 | created_at, updated_at / None | Time-ordered IDs when uuid-utils is installed or Python supplies UUIDv7 |
UUIDv6AuditBase / UUIDv6Base | UUID v6 | created_at, updated_at / None | Time-ordered UUIDv6 IDs |
BigIntAuditBase / BigIntBase | BigInt auto-increment | created_at, updated_at / None | Legacy systems, integer PKs |
NanoIDAuditBase / NanoIDBase | NanoID string | created_at, updated_at / None | URL-friendly short IDs |
IdentityAuditBase / IdentityBase | database identity | created_at, updated_at / None | Native IDENTITY columns |
DefaultBase | None (define yourself) | None | Custom or composite primary keys with AA table naming |
SQLQuery | None | None | Custom mapped read-only SQL query projections |
Repository Pattern
| Repository | Purpose |
SQLAlchemyAsyncRepository[Model] / SQLAlchemySyncRepository[Model] | Standard async/sync CRUD |
SQLAlchemyAsyncSlugRepository[Model] / SQLAlchemySyncSlugRepository[Model] | CRUD + slug generation helpers |
SQLAlchemyAsyncQueryRepository / SQLAlchemySyncQueryRepository | Complex read-only queries (no model_type) |
Service Layer
| Service | Purpose |
SQLAlchemyAsyncRepositoryService[Model] / SQLAlchemySyncRepositoryService[Model] | Full CRUD with lifecycle hooks (optional 2nd type arg [Model, Repo] types custom repo methods) |
SQLAlchemyAsyncRepositoryReadService[Model] / SQLAlchemySyncRepositoryReadService[Model] | Read-only (get_many, get, get_or_none, count, exists) |
SQLAlchemyAsyncQueryService / SQLAlchemySyncQueryService | Service wrapper around arbitrary SQL queries |
ServiceGroup | Coordinates multiple services on one shared SQLAlchemy session (ServiceGroup.new(config=...)) |
Key lifecycle hooks: to_model_on_create, to_model_on_update, to_model_on_upsert, to_model_on_delete.
Custom Types
| Type | Purpose | Notes |
FileObject / StoredObject | Object storage with lifecycle hooks | Tracks file state across session; auto-deletes on row delete via StoredObject tracker; use FileObjectList for multi-file JSON arrays |
PasswordHash | Hashed password storage | Supports Argon2 (Argon2Hasher), Bcrypt (BcryptHasher via [bcrypt]), Passlib, and Pwdlib backends; returns HashedPassword with .verify() and .verify_and_update() |
EncryptedString / EncryptedText | Transparent encryption at rest | Supports FernetBackend (client-side) and PGCryptoBackend (server-side, exported from advanced_alchemy.types); pass a stable key explicitly |
GUID | Cross-dialect UUID column | Native UUID on PostgreSQL/DuckDB/CockroachDB, RAW(16) or CHAR(32) (binary=False) on Oracle; pair with UUIDv7AuditBase / UUIDv6AuditBase for time-sortable UUIDs |
DateTimeUTC | Timezone-aware UTC datetime | Stores as UTC; accepts opt-in fsp=0..6 for MySQL/MariaDB DATETIME(fsp) and Oracle TIMESTAMP WITH TIME ZONE |
Bool | Dialect-aware boolean | Uses Oracle 23ai native BOOLEAN when SQLAlchemy exposes it; falls back to stock SQLAlchemy Boolean |
JsonB / ORA_JSONB | Dialect-aware JSON / JSONB | Uses JSONB on PostgreSQL/CockroachDB, JSON elsewhere, native oracle.JSON (21c+ / SQLAlchemy 2.1+) or BLOB (ORA_JSONB(use_blob=True)) on Oracle |
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 and returns TOTPProvider; OneTimeCode hashes codes with TTL/attempt tracking and returns HashedOneTimeCode |
Repository Service Layer
SQLAlchemyAsyncRepositoryService is the primary service base class. Key behaviors:
- Partial update hydration & single-query
update():Service.update()usespartial_model_from_dictfor generated/SQLModel__init__models so omitted fields stay unset, andService.update(data, item_id=...)delegates directly toRepository.updatewithout a duplicateSELECT;get_or_none(...)returnsNoneinstead of raisingNotFoundError. - Bulk operations:
create_many(data),update_many(data),upsert_many(data, match_fields=..., no_merge=False, chunk_size=None),delete_many(item_ids)— batched in a single transaction;upsert_many()dispatches to native dialect primitives (ON CONFLICT,ON DUPLICATE KEY UPDATE,MERGE, SpannerINSERT OR UPDATE) viaresolve_upsert_strategy()when uniqueness is provable, anddelete_many()accepts raw primary keys, composite-key tuples/dicts, model instances, or mixed lists - Lifecycle hooks:
to_model_on_create,to_model_on_update,to_model_on_upsert— override to transform input data, hash passwords, normalize strings, etc.
Mixins
| 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 |
Litestar Integration
Use SQLAlchemyPlugin (composite of SQLAlchemyInitPlugin + SQLAlchemySerializationPlugin) for full integration:
SQLAlchemyPlugin: registers engine/session providers, a Litestarbefore_sendhook, and ORM type encoders in one callSQLAlchemyDTO: generates Litestar DTOs directly from ORM models withinclude/excludefield control- Type encoders: automatic serialization of
datetime,UUID,Decimal,Enum, and custom column types - Exception handling:
set_default_exception_handler=True(the default) registersRepositoryError: exception_to_http_responseon the app unless aRepositoryErrorsubclass handler is already registered (1.13+ registers it even when integer status-code handlers such as500or404are present) - Typed submodule re-exports:
advanced_alchemy.extensions.litestar.{base,exceptions,filters,mixins,operations,repository,service,types,utils}lazily re-export core symbols alongside Litestar helpers - OpenTelemetry instrumentation: engines resolve
create_engine/create_async_enginelazily, so callingSQLAlchemyInstrumentor().instrument()before app startup instruments default and routing engines automatically
<workflow>Workflow
Step 1: Define the Model
Choose the appropriate base class from the quick reference table. Use UUIDAuditBase unless you have a specific reason not to. Define columns with Mapped[] typing.
Step 2: Create the Repository
Create a repository class with model_type set to your model. Use SQLAlchemyAsyncRepository for standard CRUD, SQLAlchemyAsyncSlugRepository if the model uses SlugKey.
Step 3: Build the Service
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.
Step 4: Wire into Framework
Use the framework plugin (Litestar, FastAPI, Flask, Sanic) to inject sessions and register the service as a dependency.
Step 5: Generate Migration
With Litestar, run litestar database make-migrations -m "description" and
then litestar database upgrade. With the standalone CLI, configure [tool.advanced-alchemy] config = "path.to:config" in pyproject.toml (or ALCHEMY_CONFIG), validate with alchemy --validate-config show-config, or pass --config / -c before or after the subcommand:
alchemy -c path.to:config make-migrations -m "description".
</workflow><guardrails>Guardrails
- Always use the service layer for business logic — never put validation, hashing, or transformation logic directly in route handlers or repositories
- Repositories are for data access only — no business rules, no side effects beyond database operations
- Never bypass the service layer to call repository methods directly from handlers
- Always set
match_fieldson services that useupsert()to avoid duplicate-key errors - Use
schema_dump()/schema_dump_configfor explicit dump behavior — services already convert Pydantic/msgspec/attrs/dataclass inputs during model conversion - Prefer
UUIDAuditBaseas default base class — only deviate when you have a concrete reason - Use
advanced_alchemy.*imports — the oldlitestar.plugins.sqlalchemypaths are deprecated - Pass stable keys to
EncryptedStringandEncryptedText. Omittingkey=emits a 1.11 deprecation warning and produces data that cannot survive a process restart. - Use
get_many()andget_many_and_count().list()andlist_and_count()are deprecated until 2.0. - Use canonical
*Filternames (LimitOffsetFilter,OrderByFilter,BeforeAfterFilter,OnBeforeAfterFilter,InCollectionFilter). The short aliases (LimitOffset,OrderBy,BeforeAfter,OnBeforeAfter,CollectionFilter) are deprecated in 1.13 and removed in 2.0. - Supply
pagination_cursor_secretfor cursor pagination providers and install[cryptography]for encrypted cursors. Litestar and FastAPI cursor providers require a secret (pagination_cursor_secret,ADVANCED_ALCHEMY_PAGINATION_CURSOR_SECRET, orSECRET_KEY);encrypted=True/pagination_cursor_encrypted=Trueuses AES-256-GCM fromadvanced-alchemy[cryptography]. - Specify
fsponDateTimeUTCfor MySQL/MariaDB and Oracle. Omittingfspemits a 1.13 deprecation warning on those dialects (defaults to whole seconds in 1.x; will default to6in 2.0).
</guardrails><validation>Validation Checkpoint
Before delivering code, verify:
- Model inherits from an Advanced Alchemy base class (not raw
DeclarativeBasefrom SQLAlchemy) - All columns use
Mapped[]type annotations - Service has an inner
Repoclass withmodel_typeset - Business logic lives in service lifecycle hooks, not in route handlers
- Imports come from
advanced_alchemy.*, not deprecated paths - Encrypted columns receive a stable explicit key
- New code uses
get_many()/get_many_and_count()and*Filternames (LimitOffsetFilter,OrderByFilter,InCollectionFilter,CursorFilter), not deprecated 1.x aliases
</validation><example>Example
A 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</example>References Index
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/:
- Models Base classes, mixins, special types, relationships, PII tracking, and deferred loading.
- Repositories Async repository variants, configuration, slug repos, and query repos.
- Services
Service layer, lifecycle hooks,
ServiceGroupshared-session composition, filtering,get_or_none(), and pagination. - Litestar Plugin
SQLAlchemy plugin config, DTOs,
DependencyDefaults(prefix=...), scoped filters, session management, andSQLAlchemyStore.delete_expired(). - Migrations
Alembic integration,
pyproject.toml/ALCHEMY_CONFIGCLI discovery,alembic_postgresql_enumdetection, metadata registry, and multi-database support. - Types
Complete catalog of custom column types:
EncryptedString,FileObject,DateTimeUTC(fsp=...),GUID,PasswordHash(BcryptHasher,Argon2Hasher),Bool,ORA_JSONB(use_blob=...),Vector,TOTPSecret,OneTimeCode. - Base Classes Declarative base classes, UUID/BigInt/Nanoid variants, audit mixins, SlugKey, UniqueMixin, metadata registry, and custom base creation.
- Filters
Filter system,
CursorFilter&CursorPagination,FilterSet[Model],RelationshipFilter,pagination_max_size,SearchFilter,InCollectionFilter,BeforeAfterFilter,OrderByFilter,LimitOffsetFilter, and frontend integration patterns. - Framework Integrations FastAPI, Flask, Starlette, and Sanic plugin setup, session management, and feature comparison across frameworks.
- Caching Dogpile.cache integration, CacheConfig, CacheManager API, automatic cache invalidation via session events, version-based list cache keys, singleflight stampede protection, and serialization.
- Read Replicas Read/write routing, RoutingConfig, engine groups, RoundRobinSelector/RandomSelector, sticky-after-write consistency, context managers for explicit routing, and RoutingAsyncSessionMaker.
- Storage (obstore) FileObject and StoredObject types, ObstoreBackend and FSSpecBackend configuration (S3, GCS, Azure, local), StorageRegistry, presigned URL generation, automatic file lifecycle via session tracker, and Pydantic integration.
- Operations, Listeners, Serialization
OnConflictUpsert(single-row + bulkcreate_upsert_many/create_merge_many/create_insert_or_update_many),MergeStatement(PostgreSQL 15+ / Oracle / MSSQL),resolve_upsert_strategy, session event listeners (FileObject, cache invalidation,touch_updated_timestamp), and the msgspec-firstencode_json/decode_jsonused across the library.
Official References
- https://advanced-alchemy.litestar.dev/latest/
- https://pypi.org/project/advanced-alchemy/1.13.0b3/
- https://github.com/litestar-org/advanced-alchemy/blob/main/docs/changelog.rst
- https://github.com/litestar-org/advanced-alchemy/tree/v1.12.0/advanced_alchemy
- https://github.com/litestar-org/advanced-alchemy/tree/v1.12.0/docs/usage
- https://docs.litestar.dev/2/release-notes/changelog.html
- https://docs.sqlalchemy.org/en/20/orm/quickstart.html
Shared Styleguide Baseline
- Use shared styleguides for generic language/framework rules to reduce duplication in this skill.
- General Principles
- Python
- Litestar
- Keep this skill focused on tool-specific workflows, edge cases, and integration details.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

