Sqlspec

From litestar-org/litestar-skills · View interactive version

Sqlspec is an AI agent skill from the GitHub repository litestar-org/litestar-skills. Use when working with sqlspec, SQLSpec, SQLFileLoader, drivers, query builders, named SQL, filters, pagination, read replicas, tenant isolation, Arrow, framework extensions, ADK stores, or observers. Not for ORM repositories — use advanced-alchemy.

How to use this skill

Skill file

SQLSpec Skill

SQLSpec is a type-safe SQL query mapper for Python -- NOT an ORM. It provides flexible connectivity with consistent interfaces across its database adapter packages. Write raw SQL, use the builder API, or load SQL from files. Statements pass through a sqlglot-powered AST pipeline for validation, parameter handling, and dialect conversion.

Match-Your-Framework — read first

sqlspec 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:

Shared topics that apply to every framework live in CODE0 (autocommit / manual middleware) and CODE1 (multi-config registry). Read the framework guide first, then those for depth.

The rest of this SKILL.md covers framework-agnostic topics: adapter setup, query builder, driver methods, filters, observability, migrations, the ADK extension, and data-dictionary introspection.

Code Style Rules

Quick Reference

Adapter Pattern

from sqlspec import SQLSpec
from sqlspec.adapters.asyncpg import AsyncpgConfig

config = AsyncpgConfig(
    connection_config={
        "dsn": "postgresql://user:pass@localhost:5432/mydb",
        "min_size": 2,
        "max_size": 10,
    },
)
db_manager = SQLSpec()
db_manager.add_config(config)

async with db_manager.provide_session(config) as db:
    users = await db.select(
        "SELECT * FROM users WHERE active = $1",
        True,
        schema_type=User,
    )

Query Builder Essentials

from sqlspec import sql

stmt = (
    sql.select("id", "name", "email")
    .from_("users")
    .where_eq("status", "active")
    .where("created_at > :since", since=cutoff_date)
    .order_by("created_at", desc=True)
    .limit(50)
    .to_statement()
)

insert_stmt = (
    sql.insert("users").columns("name", "email").values(name="Alice", email="alice@example.com").to_statement()
)

merge_stmt = (
    sql.merge("inventory", dialect="postgres")
    .using("updates")
    .on("inventory.product_id = updates.product_id")
    .when_matched_then_update(qty=sql.col("qty", "updates"))
    .when_not_matched_then_insert(
        product_id=sql.col("product_id", "updates"),
        qty=sql.col("qty", "updates"),
    )
    .to_statement()
)

Driver Method Summary

| Method | Returns | Use Case |

| --- | --- | --- |

| select() / fetch() | List of rows | Filtered queries, listing |

| select_value() | Single scalar | COUNT(*), MAX(), existence checks |

| select_value_or_none() | Scalar or None | Optional scalar lookup |

| select_one() | One row (strict) | Get-by-ID, raises NotFoundError |

| select_one_or_none() | One row or None | Optional lookup |

| select_with_total() | Rows plus total | Pagination |

| select_stream() / fetch_stream() | Context-managed row stream | Bounded row iteration where adapter supports native streaming |

| select_to_arrow() / fetch_to_arrow() | ArrowResult | Bulk data export, analytics |

| select_to_storage() | StorageBridgeJob | Export query results to local or cloud storage |

| execute() | SQLResult | INSERT/UPDATE/DELETE metadata |

| execute_many() | SQLResult | Batch operation metadata |

| execute_script() | SQLResult | Multi-statement SQL script execution |

| execute_stack() | tuple[StackResult, ...] | Ordered statement-stack execution |

| load_from_arrow() | StorageBridgeJob | Adapter-supported Arrow ingest |

| load_from_storage() | StorageBridgeJob | Adapter-supported staged-file ingest |

| load_from_records() | StorageBridgeJob | Records normalized through the Arrow ingest path |

| transaction() | Context manager | Atomic transaction or savepoint scope on a driver |

Arrow Integration Basics

arrow_result = await db.select_to_arrow(
    "SELECT * FROM large_dataset WHERE region = $1",
    region,
    return_format="reader",
    batch_size=10_000,
)

await db.load_from_arrow("users", arrow_result)
await db.load_from_records("users", [{"id": 1, "name": "Ada"}])

<workflow>

Workflow

Step 1: Choose Adapter and Pattern

| Need | Adapter | Key Feature |

| --- | --- | --- |

| PostgreSQL async | asyncpg, psycopg | Async, NUMERIC/PYFORMAT params, auto-probed pgvector / pg_textsearch / paradedb |

| PostgreSQL sync | psycopg | Sync+async, PYFORMAT params |

| SQLite | sqlite, aiosqlite | QMARK params, local dev |

| DuckDB analytics | duckdb | Arrow-native OLAP, extension load/install lifecycle, direct object-store transfer |

| Arrow / multi-engine ETL | adbc | Arrow-native ingest/export across DuckDB, PostgreSQL, BigQuery, Flight SQL, GizmoSQL, Quack, Oracle, and Db2 |

| MySQL async | asyncmy | PYFORMAT params |

| Oracle | oracledb | NAMED_COLON params, sync+async |

| IBM Db2 | db2 | QMARK params, sync+async via ibm_db, SYSCAT catalog reflection |

| SQL Server / Sybase / SQL Anywhere | mssql_python, pymssql, sybase, sqlanywhere | T-SQL (tsql), Sybase ASE (sybase), and SAP SQL Anywhere (sqlanywhere) dialects |

| BigQuery / Spanner / Snowflake / Teradata | bigquery, spanner, snowflake, teradata | NAMED_AT / PYFORMAT / QMARK params, cloud job/session controls, Spanner sync+async & Property Graph/Vector AST, Snowflake (snowflake), Teradata (vantage) |

| Read Replicas & Routing | ReplicaGroup, ReplicaSpec | Primary/replica pools across all 24 adapters, read-after-write primary pinning, provide_replica_session() / provide_routing_session() |

| Tenant Isolation | TenantContext, SQLSpecTenantMiddleware | Request-scoped tenant_id session variables, RLS/bind routing, tenant_bypass() |

| Raw SQL strings | Driver methods | select(), execute() |

| Dynamic queries | Query builder | sql.select()...to_statement(), sql.func(), sql.col() / sql.c, sql.var(), sql.update()...from_(), sql.upsert() |

| SQL from files | SQLFileLoader | Metadata directives, -- param:, -- fragment:, /* include: */, /* slot: */, caching |

| High-volume ingest/export | Storage bridge | Check the adapter matrix before selecting load_from_arrow(), load_from_storage(), load_from_records(), or select_to_storage() |

Step 2: Implement

  1. Configure the adapter with connection details (standardized aliases like dsn/url/conninfo, database/dbname, user/username normalize automatically) and pool settings
  2. Register the config with SQLSpec.add_config() and use SQLSpec.provide_session(config) or config-backed SQLSpecAsyncService(config=..., loader=...) for connection lifecycle
  3. Choose the appropriate driver method for your query shape
  4. Use schema_type parameter for typed results (msgspec Structs, dataclasses, or Pydantic models)
  5. Apply filters with LimitOffsetFilter, CursorFilter, OrderByFilter, SearchFilter, BeforeAfterFilter, or InCollectionFilter
  6. Use select_stream(..., native_only=True) when bounded-memory streaming is mandatory
  7. Check adapter ingest capabilities, then use load_from_records(), load_from_arrow(), load_from_storage(), or select_to_storage() for high-volume data movement

Step 3: Validate

Run through the validation checkpoint below before considering the work complete.

</workflow>

<guardrails>

Guardrails

</guardrails>

<validation>

Validation Checkpoint

Before delivering SQLSpec code, verify:

</validation>

<example>

Example

Task: "Set up an asyncpg adapter, define a typed model, and execute a parameterized query with pagination."

from dataclasses import dataclass
from sqlspec import SQLSpec
from sqlspec.adapters.asyncpg import AsyncpgConfig
from sqlspec.core.filters import LimitOffsetFilter, OrderByFilter


@dataclass
class User:
    id: int
    name: str
    email: str
    active: bool


config = AsyncpgConfig(
    connection_config={
        "dsn": "postgresql://user:pass@localhost:5432/mydb",
        "min_size": 2,
        "max_size": 10,
    },
)
db_manager = SQLSpec()
db_manager.add_config(config)


async def list_active_users(page: int = 1, page_size: int = 25) -> list[User]:
    filters = [
        OrderByFilter(field_name="name", sort_order="asc"),
        LimitOffsetFilter(limit=page_size, offset=(page - 1) * page_size),
    ]

    async with db_manager.provide_session(config) as db:
        users = await db.select(
            "SELECT id, name, email, active FROM users WHERE active = $1",
            True,
            *filters,
            schema_type=User,
        )
        return users


async def get_user_count() -> int:
    async with db_manager.provide_session(config) as db:
        count = await db.select_value("SELECT COUNT(*) FROM users WHERE active = $1", True)
        return count

</example>

References Index

Choosing between sqlspec and advanced-alchemy: advanced-alchemy gives you an opinionated ORM service layer with UUIDAuditBase, lifecycle hooks, repository / service / Alembic integration, and OffsetPagination[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. sqlspec gives you direct SQL control, first-party database adapter packages (asyncpg, oracledb, Db2, Sybase ASE, SQL Anywhere, DuckDB, BigQuery, Spanner, SQLite, and more), Arrow result paths 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 CODE6 for the ORM path.

For detailed instructions, patterns, and API guides, refer to the following documents:

Standards & Style

Core Utilities

Architecture & Performance

Query Building & Execution

Data Integration

Adapters & Drivers

Framework & Storage Integrations

Migrations & Schema

Observability

Advanced Patterns

Key Resources

Official References

Shared Styleguide Baseline

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.