litestar-databases
Databases
Use this skill when persistence architecture and ORM integration are core to the task, especially SQLAlchemy plugin wiring or Piccolo DTO-based API flows.
Execution Workflow
- Choose ORM path (
SQLAlchemyorPiccolo) based on ecosystem and project constraints. - For SQLAlchemy, choose plugin strategy first (
SQLAlchemyPluginvsSQLAlchemyInitPlugin+ optionalSQLAlchemySerializationPlugin). - Configure engine + session factory centrally at app initialization (async or sync).
- Define model/repository/service boundaries and keep transaction ownership explicit.
- Integrate dependency injection so handlers receive a scoped session/unit-of-work.
- Define DTO and serialization boundaries at API edges (never leak raw ORM internals unintentionally).
- Validate lifecycle behavior: startup initialization, request cleanup/rollback, and lazy-loading behavior in hot paths.
Implementation Rules
- Keep transactions explicit and short-lived; commit where business operations complete, rollback on failure paths.
- Keep repositories/services free of HTTP transport concerns.
- Keep session ownership deterministic; handlers should not guess who closes/rolls back a session.
- Prefer async SQLAlchemy for IO-heavy API workloads unless sync architecture is a deliberate requirement.
- Avoid returning ORM entities blindly when relationships/lazy attributes can trigger unexpected DB access.
- Use DTO shaping for both inbound and outbound payloads to protect private/internal fields.
SQLAlchemy: Decision Guide
- Use
SQLAlchemyPluginfor most applications that need both app/session tooling and SQLAlchemy model serialization support. - Use
SQLAlchemyInitPluginonly when you need engine/session injection and lifecycle management but do not want automatic SQLAlchemy DTO serialization. - Add
SQLAlchemySerializationPluginwhen you want automatic SQLAlchemy DTO generation for handlerdataand return annotations. - Use separate init + serialization plugins when you need explicit composition control; otherwise prefer the combined
SQLAlchemyPlugin.
SQLAlchemy: Models and Repository Patterns
Litestar SQLAlchemy support includes built-in repository utilities and base model patterns:
- Repository classes:
SQLAlchemyAsyncRepositoryfor async session workflows.- Generic repository support for CRUD plus filtering, sorting, pagination, and bulk operations.
- Base model options include UUID and BigInt primary-key variants with optional audit columns:
UUIDBase,UUIDAuditBaseBigIntBase,BigIntAuditBase
Implementation expectations:
- Choose one base strategy early (UUID vs BigInt) and keep it consistent.
- Keep query logic in repositories/services, not route handlers.
- Use repository filtering/pagination primitives in list endpoints rather than ad-hoc SQL in handlers.
- Treat relationship loading strategy as part of API design to avoid N+1 regressions.
SQLAlchemy: Plugin Configuration Patterns
Pattern 1: Combined plugin (recommended)
from litestar import Litestar
from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyPlugin
config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///app.sqlite",
create_all=True,
metadata=Base.metadata,
)
sqlalchemy = SQLAlchemyPlugin(config=config)
app = Litestar(route_handlers=[...], plugins=[sqlalchemy])
Pattern 2: Split init + serialization plugins
from litestar import Litestar
from litestar.plugins.sqlalchemy import (
SQLAlchemyAsyncConfig,
SQLAlchemyInitPlugin,
SQLAlchemySerializationPlugin,
)
config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///app.sqlite")
app = Litestar(
route_handlers=[...],
plugins=[SQLAlchemyInitPlugin(config=config), SQLAlchemySerializationPlugin()],
)
Pattern 3: Sync configuration
from litestar.plugins.sqlalchemy import SQLAlchemyPlugin, SQLAlchemySyncConfig
config = SQLAlchemySyncConfig(connection_string="sqlite:///app.sqlite")
plugin = SQLAlchemyPlugin(config=config)
SQLAlchemy: Dependency Injection and Lifecycle
SQLAlchemyInitPlugin provides:
- Engine and session availability via dependency injection.
- Engine and session factory stored on app state.
- A
before_sendhandler for request-lifecycle cleanup behavior. - Signature namespace support for SQLAlchemy-annotated handler dependencies.
Design guidance:
- Inject session dependencies into handlers/services instead of constructing sessions ad hoc.
- Keep one clear per-request unit-of-work path.
- Validate rollback and cleanup behavior during exception paths.
SQLAlchemy: Serialization and DTO Boundaries
SQLAlchemySerializationPlugin automatically creates SQLAlchemy DTO types for handler data and return annotations that use SQLAlchemy models (including collections), unless an explicit DTO is already provided.
Practical guidance:
- Use automatic serialization for straightforward CRUD APIs.
- Use explicit DTO classes when fields, nesting, or security requirements need tighter control.
- Mark model fields (for example via DTO field controls) to prevent exposing private data.
- Verify generated OpenAPI schemas and serialized payloads after model changes.
Piccolo ORM Guidance
Litestar supports Piccolo-centric API flows via PiccoloDTO.
Core pattern:
- Define Piccolo
Tablemodels. - Use
PiccoloDTO[Model]for request/response shaping. - Use custom DTO subclasses with
DTOConfigfor partial updates and field exclusions.
Example:
from litestar.contrib.piccolo import PiccoloDTO
from litestar.dto import DTOConfig
class PatchDTO(PiccoloDTO[Task]):
config = DTOConfig(exclude={"id"}, partial=True)
Piccolo implementation guidance:
- Keep table definitions and DB config centralized.
- Use DTO-level controls for patch semantics and hidden/internal columns.
- Keep query and persistence logic out of transport handlers where possible.
Validation Checklist
- Confirm selected plugin strategy matches requirements (combined vs split plugins).
- Confirm async/sync config matches deployed runtime and DB driver.
- Confirm migrations/model metadata align with runtime models.
- Confirm session injection works and per-request cleanup runs reliably.
- Confirm rollback behavior on exceptions is tested.
- Confirm DTO boundaries prevent internal/private field leakage.
- Confirm N+1 and lazy-loading pitfalls are addressed in hot paths.
- Confirm list endpoints enforce deterministic filtering/sorting/pagination.
Cross-Skill Handoffs
- Use
litestar-dependency-injectionfor session provisioning patterns. - Use
litestar-dtoandlitestar-responsesfor safe transport shaping. - Use
litestar-testingfor transactional test isolation. - Use
litestar-openapito verify schema output after DTO/plugin changes.
Litestar References
- https://docs.litestar.dev/2/usage/databases/sqlalchemy/models_and_repository.html
- https://docs.litestar.dev/2/usage/databases/sqlalchemy/plugins/index.html
- https://docs.litestar.dev/2/usage/databases/sqlalchemy/plugins/sqlalchemy_plugin.html
- https://docs.litestar.dev/2/usage/databases/sqlalchemy/plugins/sqlalchemy_init_plugin.html
- https://docs.litestar.dev/2/usage/databases/sqlalchemy/plugins/sqlalchemy_serialization_plugin.html
- https://docs.litestar.dev/2/usage/databases/piccolo.html
More from alti3/litestar-skills
litestar-responses
Build Litestar responses with typed return values, explicit Response containers, layered response classes, headers, cookies, status-code control, redirects, files, streams, server-sent events, ASGI app returns, and background tasks. Use when shaping outbound HTTP behavior, correcting response contracts, or choosing the right Litestar response primitive. Do not use for request parsing, validation, or authentication policy design.
22litestar-logging
Configure Litestar logging with `LoggingConfig`, `queue_listener`, exception logging policy, selective stack-trace suppression, standard logging, picologging, Structlog, and custom logging config subclasses. Use when establishing or refactoring application logging behavior, request-level logs, or production-safe error logging in Litestar. Do not use for metrics/tracing instrumentation or exception-response contract design.
22litestar-authentication
Implement Litestar authentication with custom authentication middleware, built-in security backends, JWT and session flows, route inclusion and exclusion rules, and typed auth context on `Request` / `ASGIConnection`. Use when establishing identity, issuing or validating credentials, or attaching authenticated user context in Litestar. Do not use for generic request parsing, broad security audits, or unrelated transport concerns.
22litestar-middleware
Design and apply Litestar middleware for cross-cutting concerns such as CORS, CSRF, allowed-host checks, compression, rate limiting, logging, sessions, request enrichment, policy enforcement, and custom ASGI pipeline control. Use when behavior must wrap broad route sets consistently across the ASGI stack. Do not use for route-specific business rules, simple response mutation better handled by lifecycle hooks, or auth/guard policy work that belongs in security-focused skills.
20litestar-routing
Design and implement Litestar routing with app/router/controller composition, handler decorators, path and parameter modeling, route indexing/reverse lookups, ASGI mounting, and layered route metadata. Use when creating or refactoring endpoint topology and URL contracts. Do not use for purely internal service logic unrelated to HTTP route structure.
18litestar-dto
Configure Litestar DTO behavior for inbound parsing and outbound serialization, including layer-scoped `dto`/`return_dto`, `DTOConfig` policies, `DTOData` update workflows, and custom `AbstractDTO` implementations. Use when API payload contracts differ from internal model structures. Do not use when internal models can be exposed safely without transformation.
18