sqlspec

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SQLSpec Skill

SQLSpec 技能

SQLSpec is a type-safe SQL query mapper for Python -- NOT an ORM. It provides flexible connectivity with consistent interfaces across 15+ database adapters. Write raw SQL, use the builder API, or load SQL from files. All statements pass through a sqlglot-powered AST pipeline for validation and dialect conversion.
SQLSpec 是一款适用于Python的类型安全SQL查询映射工具——而非ORM。它提供灵活的连接能力,在15+种数据库适配器间拥有一致的接口。你可以编写原生SQL、使用构建器API,或从文件加载SQL。所有语句都会经过sqlglot驱动的AST管道进行验证和方言转换。

Match-Your-Framework — read first

适配你的框架 — 请先阅读

sqlspec ships first-party extensions for four web frameworks. If your project uses one of these, jump directly to the matching integration guide and skip the others:
  • Litestar
    SQLSpecPlugin
    with full DI, CLI, observability. The rest of this SKILL.md covers Litestar by default; also see
    references/extensions.md
    .
  • FastAPI
    references/fastapi-integration.md
    Depends(plugin.provide_session())
    DI,
    Annotated[...]
    handlers, filter providers.
  • Flask
    references/flask-integration.md
    plugin.init_app(app)
    , pull-based
    plugin.get_session()
    , async-via-portal.
  • Starlette
    references/starlette-integration.md
    request.state
    -based session access, lifespan wrapping, middleware variants.
sqlspec has no first-party Sanic integration — other frameworks are not supported out-of-the-box.
Shared topics that apply to every framework live in
references/commit-modes.md
(autocommit / manual middleware) and
references/multi-database.md
(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.
sqlspec 为四款Web框架提供官方扩展。如果你的项目使用其中之一,请直接跳转到对应的集成指南,忽略其他内容
  • Litestar
    SQLSpecPlugin
    支持完整的依赖注入(DI)、CLI和可观测性。本SKILL.md默认以Litestar为例;也可查看
    references/extensions.md
  • FastAPI
    references/fastapi-integration.md
    — 支持
    Depends(plugin.provide_session())
    依赖注入、
    Annotated[...]
    处理器、过滤器提供者。
  • Flask
    references/flask-integration.md
    — 支持
    plugin.init_app(app)
    初始化、基于拉取的
    plugin.get_session()
    、通过portal实现异步。
  • Starlette
    references/starlette-integration.md
    — 基于
    request.state
    的会话访问、生命周期包装、中间件变体。
sqlspec 无官方Sanic集成——其他框架无开箱即用支持。
适用于所有框架的通用主题请查看
references/commit-modes.md
(自动提交/手动中间件)和
references/multi-database.md
(多配置注册中心)。请先阅读框架指南,再查看这些文档获取详细信息。
本SKILL.md剩余部分介绍框架无关的主题:适配器设置、查询构建器、驱动方法、过滤器、可观测性、迁移、ADK扩展和数据字典自省。

Code Style Rules

代码风格规则

  • from __future__ import annotations
    rule
    — SQLSpec adapter config modules and driver definitions avoid
    from __future__ import annotations
    because configs are introspected at runtime. Consumer application modules (handlers, services, tests that use a configured driver) MAY and typically SHOULD use it — canonical Litestar apps use it in 100+ files.
  • from __future__ import annotations
    规则
    — SQLSpec适配器配置模块和驱动定义避免使用
    from __future__ import annotations
    ,因为配置会在运行时被自省。消费应用模块(处理器、服务、使用已配置驱动的测试)可以且通常应该使用它——标准Litestar应用在100+个文件中使用该语句。

Quick Reference

快速参考

Adapter Pattern

适配器模式

python
from sqlspec.adapters.asyncpg import AsyncpgConfig, AsyncpgDriver
python
from sqlspec.adapters.asyncpg import AsyncpgConfig, AsyncpgDriver

Configure the adapter with connection details

使用连接详情配置适配器

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

Use the driver as a context manager for connection lifecycle

使用驱动作为上下文管理器管理连接生命周期

async with config.create_driver() as db: users = await db.select_many( "SELECT * FROM users WHERE active = $1", [True], schema_type=User, )
undefined
async with config.create_driver() as db: users = await db.select_many( "SELECT * FROM users WHERE active = $1", [True], schema_type=User, )
undefined

Query Builder Essentials

查询构建器基础

python
from sqlspec import sql
python
from sqlspec import sql

SELECT with filters

带过滤器的SELECT语句

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() )
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

INSERT语句

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

MERGE / upsert

MERGE / 插入更新

stmt = ( sql.merge_("inventory") .using("updates", on="inventory.product_id = updates.product_id") .when_matched().do_update(qty="updates.qty") .when_not_matched().do_insert(product_id="updates.product_id", qty="updates.qty") .to_statement() )
undefined
stmt = ( sql.merge_("inventory") .using("updates", on="inventory.product_id = updates.product_id") .when_matched().do_update(qty="updates.qty") .when_not_matched().do_insert(product_id="updates.product_id", qty="updates.qty") .to_statement() )
undefined

Driver Method Summary

驱动方法汇总

MethodReturnsUse Case
select_value()
Single scalar
COUNT(*)
,
MAX()
, existence checks
select_one()
One row (strict)Get-by-ID, raises
NotFoundError
select_one_or_none()
One row or
None
Optional lookup
select_many()
List of rowsFiltered queries, listing
select_to_arrow()
pyarrow.Table
Bulk data export, analytics
execute()
Row countINSERT/UPDATE/DELETE
execute_many()
Row countBatch operations
方法返回值使用场景
select_value()
单个标量值
COUNT(*)
,
MAX()
、存在性检查
select_one()
单行数据(严格模式)通过ID查询,未找到时抛出
NotFoundError
select_one_or_none()
单行数据或
None
可选查询
select_many()
多行数据列表过滤查询、列表查询
select_to_arrow()
pyarrow.Table
批量数据导出、分析场景
execute()
受影响行数INSERT/UPDATE/DELETE操作
execute_many()
受影响行数批量操作

Arrow Integration Basics

Arrow集成基础

python
undefined
python
undefined

Zero-copy on DuckDB, ADBC adapters; conversion on others

DuckDB、ADBC适配器支持零拷贝;其他适配器会进行转换

arrow_table = await db.select_to_arrow( "SELECT * FROM large_dataset WHERE region = $1", [region] )
arrow_table = await db.select_to_arrow( "SELECT * FROM large_dataset WHERE region = $1", [region] )

Bulk load from Arrow

从Arrow批量加载数据

await db.copy_from_arrow(arrow_table, target_table="users")

<workflow>
await db.copy_from_arrow(arrow_table, target_table="users")

<workflow>

Workflow

工作流程

Step 1: Choose Adapter and Pattern

步骤1:选择适配器和模式

NeedAdapterKey Feature
PostgreSQL async
asyncpg
,
psycopg
Async, NUMERIC/PYFORMAT params
PostgreSQL sync
psycopg
Sync+async, PYFORMAT params
SQLite
sqlite
,
aiosqlite
QMARK params, local dev
DuckDB analytics
duckdb
Arrow-native, zero-copy
MySQL async
asyncmy
PYFORMAT params
Oracle
oracledb
NAMED_COLON params, sync+async
BigQuery / Spanner
bigquery
,
spanner
NAMED_AT params
Raw SQL stringsDriver methods
select_many()
,
execute()
Dynamic queriesQuery builder
sql.select()...to_statement()
SQL from files
SQLFileLoader
Metadata directives, caching
需求适配器核心特性
PostgreSQL异步
asyncpg
,
psycopg
异步、NUMERIC/PYFORMAT参数风格
PostgreSQL同步
psycopg
同步+异步、PYFORMAT参数风格
SQLite
sqlite
,
aiosqlite
QMARK参数风格、本地开发
DuckDB分析
duckdb
原生支持Arrow、零拷贝
MySQL异步
asyncmy
PYFORMAT参数风格
Oracle
oracledb
NAMED_COLON参数风格、同步+异步
BigQuery / Spanner
bigquery
,
spanner
NAMED_AT参数风格
原生SQL字符串驱动方法
select_many()
,
execute()
动态查询查询构建器
sql.select()...to_statement()
从文件加载SQL
SQLFileLoader
元数据指令、缓存

Step 2: Implement

步骤2:实现

  1. Configure the adapter with connection details and pool settings
  2. Use
    create_driver()
    context manager for connection lifecycle
  3. Choose the appropriate driver method for your query shape
  4. Use
    schema_type
    parameter for typed results (Pydantic or msgspec models)
  5. Apply filters with
    LimitOffsetFilter
    ,
    OrderByFilter
    ,
    SearchFilter
  1. 使用连接详情和连接池设置配置适配器
  2. 使用
    create_driver()
    上下文管理器管理连接生命周期
  3. 根据查询类型选择合适的驱动方法
  4. 使用
    schema_type
    参数获取类型化结果(Pydantic或msgspec模型)
  5. 使用
    LimitOffsetFilter
    OrderByFilter
    SearchFilter
    应用过滤器

Step 3: Validate

步骤3:验证

Run through the validation checkpoint below before considering the work complete.
</workflow> <guardrails>
在完成工作前,请通过以下验证检查点。
</workflow> <guardrails>

Guardrails

约束规则

  • Always use typed adapters: import the specific adapter config, not generic base classes
  • Always use
    schema_type
    for query results -- get typed objects, not raw dicts
  • Always use context managers for driver lifecycle --
    async with config.create_driver() as db:
  • Prefer the query builder for complex dynamic queries -- avoids string concatenation, handles dialect conversion
  • Prefer
    SQLFileLoader
    for static queries -- keeps SQL out of Python, enables caching
  • Never concatenate SQL strings -- use parameterized queries or the query builder
  • Never hold connections outside context managers -- connection leaks exhaust the pool
  • Match parameter style to adapter:
    $1
    for asyncpg,
    %s
    for psycopg,
    ?
    for sqlite,
    :name
    for oracledb
  • Adapter config / driver modules avoid
    from __future__ import annotations
    . Consumer app modules MAY use it.
</guardrails> <validation>
  • 始终使用类型化适配器:导入特定的适配器配置,而非通用基类
  • **始终使用
    schema_type
    **处理查询结果——获取类型化对象,而非原始字典
  • 始终使用上下文管理器管理驱动生命周期——
    async with config.create_driver() as db:
  • 复杂动态查询优先使用查询构建器——避免字符串拼接,支持方言转换
  • 静态查询优先使用
    SQLFileLoader
    ——将SQL与Python代码分离,支持缓存
  • 切勿拼接SQL字符串——使用参数化查询或查询构建器
  • 切勿在上下文管理器外持有连接——连接泄漏会耗尽连接池
  • 参数风格与适配器匹配:asyncpg使用
    $1
    ,psycopg使用
    %s
    ,sqlite使用
    ?
    ,oracledb使用
    :name
  • 适配器配置/驱动模块避免使用
    from __future__ import annotations
    。消费应用模块可以使用该语句。
</guardrails> <validation>

Validation Checkpoint

验证检查点

Before delivering SQLSpec code, verify:
  • Adapter config uses the correct import path (
    sqlspec.adapters.<name>
    )
  • Connection lifecycle uses
    create_driver()
    context manager
  • Parameter style matches the adapter (see adapter registry table)
  • Query results use
    schema_type
    for type-safe mapping
  • Complex dynamic queries use the builder API, not string concatenation
  • Filters use SQLSpec filter objects (
    LimitOffsetFilter
    , etc.) not manual LIMIT/OFFSET
</validation> <example>
交付SQLSpec代码前,请验证:
  • 适配器配置使用正确的导入路径(
    sqlspec.adapters.<name>
  • 连接生命周期使用
    create_driver()
    上下文管理器
  • 参数风格与适配器匹配(查看适配器注册表)
  • 查询结果使用
    schema_type
    进行类型安全映射
  • 复杂动态查询使用构建器API,而非字符串拼接
  • 过滤器使用SQLSpec过滤器对象(
    LimitOffsetFilter
    等),而非手动编写LIMIT/OFFSET
</validation> <example>

Example

示例

Task: "Set up an asyncpg adapter, define a typed model, and execute a parameterized query with pagination."
python
from dataclasses import dataclass
from sqlspec.adapters.asyncpg import AsyncpgConfig
from sqlspec.core.filters import LimitOffsetFilter, OrderByFilter
任务: "设置asyncpg适配器,定义类型化模型,并执行带分页的参数化查询。"
python
from dataclasses import dataclass
from sqlspec.adapters.asyncpg import AsyncpgConfig
from sqlspec.core.filters import LimitOffsetFilter, OrderByFilter

--- Typed model ---

--- 类型化模型 ---

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

--- Adapter setup ---

--- 适配器设置 ---

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

--- Query execution ---

--- 查询执行 ---

async def list_active_users(page: int = 1, page_size: int = 25) -> list[User]: filters = [ OrderByFilter(columns=[("name", "asc")]), LimitOffsetFilter(limit=page_size, offset=(page - 1) * page_size), ]
async with config.create_driver() as db:
    users = await db.select_many(
        "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 config.create_driver() as db: count = await db.select_value( "SELECT COUNT(*) FROM users WHERE active = $1", [True] ) return count

</example>
async def list_active_users(page: int = 1, page_size: int = 25) -> list[User]: filters = [ OrderByFilter(columns=[("name", "asc")]), LimitOffsetFilter(limit=page_size, offset=(page - 1) * page_size), ]
async with config.create_driver() as db:
    users = await db.select_many(
        "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 config.create_driver() as db: count = await db.select_value( "SELECT COUNT(*) FROM users WHERE active = $1", [True] ) return count

</example>

Query Builder

查询构建器

The
sql
factory provides a fluent builder API with full method chaining. All builders terminate with
.to_statement()
and pass through sqlglot for validation and dialect conversion.
BuilderEntry PointKey Methods
SELECT
sql.select(*cols)
.from_()
,
.where()
,
.where_eq()
,
.join()
,
.order_by()
,
.limit()
,
.offset()
INSERT
sql.insert_into(table)
.columns()
,
.values()
,
.returning()
UPDATE
sql.update(table)
.set_()
,
.where()
,
.returning()
DELETE
sql.delete_from(table)
.where()
,
.returning()
MERGE
sql.merge_(target)
.using()
,
.when_matched()
,
.when_not_matched()
CREATE TABLE
sql.create_table(name)
.column()
,
.primary_key()
,
.if_not_exists()
DROP TABLE
sql.drop_table(name)
.if_exists()
,
.cascade()
sql
工厂提供流畅的链式调用构建器API。所有构建器都以
.to_statement()
结束,并通过sqlglot进行验证和方言转换。
构建器入口方法核心方法
SELECT
sql.select(*cols)
.from_()
,
.where()
,
.where_eq()
,
.join()
,
.order_by()
,
.limit()
,
.offset()
INSERT
sql.insert_into(table)
.columns()
,
.values()
,
.returning()
UPDATE
sql.update(table)
.set_()
,
.where()
,
.returning()
DELETE
sql.delete_from(table)
.where()
,
.returning()
MERGE
sql.merge_(target)
.using()
,
.when_matched()
,
.when_not_matched()
CREATE TABLE
sql.create_table(name)
.column()
,
.primary_key()
,
.if_not_exists()
DROP TABLE
sql.drop_table(name)
.if_exists()
,
.cascade()

ArrowResult

ArrowResult

select_to_arrow()
returns an Apache Arrow
Table
for bulk and analytical workloads:
  • Zero-copy on DuckDB and ADBC-native adapters — no serialization overhead
  • Conversion path on other adapters — rows are materialized into an Arrow schema
  • Returned tables are compatible with Polars, Pandas, and PyArrow directly
  • Use
    copy_from_arrow(table, target_table)
    for bulk loads back into the database
select_to_arrow()
返回Apache Arrow
Table
,适用于批量和分析工作负载:
  • 零拷贝:DuckDB和ADBC原生适配器支持零拷贝——无序列化开销
  • 转换路径:其他适配器会将行数据转换为Arrow schema
  • 返回的表格可直接与Polars、Pandas和PyArrow兼容
  • 使用
    copy_from_arrow(table, target_table)
    将批量数据加载回数据库

Filters

过滤器

SQLSpec filter objects are passed directly to driver methods alongside the SQL string. They modify the statement before execution.
FilterPurposeExample Use
BeforeAfterFilter
Date range bounds (
before
,
after
)
Audit log queries, time-range pagination
InCollectionFilter
SQL
IN (...)
clause
Filter by a set of IDs or enum values
LimitOffsetFilter
Page-based pagination
limit=25, offset=50
OrderByFilter
Dynamic sort columns and directionUser-supplied sort fields
SearchFilter
Text search (
ILIKE
/
LIKE
)
Full-text style search on string columns
Filters are composable — pass multiple to a single
select_many()
call and they are applied in order.
SQLSpec过滤器对象可与SQL字符串一起直接传递给驱动方法,它们会在执行前修改语句。
过滤器用途使用示例
BeforeAfterFilter
日期范围边界(
before
,
after
审计日志查询、时间范围分页
InCollectionFilter
SQL
IN (...)
子句
通过ID集合或枚举值过滤
LimitOffsetFilter
基于页码的分页
limit=25, offset=50
OrderByFilter
动态排序列和方向用户自定义排序字段
SearchFilter
文本搜索(
ILIKE
/
LIKE
类全文搜索的字符串列查询
过滤器可组合使用——向单个
select_many()
调用传递多个过滤器,它们会按顺序应用。

Framework Integrations

框架集成

FrameworkIntegrationKey Feature
Litestar
SQLSpecPlugin
Dependency injection of typed driver; auto session lifecycle
FastAPI / StarletteMiddlewareRequest-scoped connection; injects driver into route dependencies
FlaskExtension
init_app()
pattern; driver available via
g
or
current_app
SQLSpecPlugin
for Litestar registers the driver as a DI provider — inject it into route handlers via type annotation without manual context management.
框架集成方式核心特性
Litestar
SQLSpecPlugin
类型化驱动的依赖注入;自动会话生命周期管理
FastAPI / Starlette中间件请求作用域的连接;将驱动注入路由依赖
Flask扩展
init_app()
模式;驱动可通过
g
current_app
获取
Litestar的
SQLSpecPlugin
将驱动注册为DI提供者——无需手动管理上下文,通过类型注解即可将其注入路由处理器。

Event Channels

事件通道

For databases that support server-side pub/sub (e.g., PostgreSQL
LISTEN
/
NOTIFY
):
  • Use
    AsyncEventChannel
    to subscribe to named channels
  • Publish with
    NOTIFY channel, payload
    from SQL or from the
    publish()
    method
  • Handlers receive
    EventMessage
    objects with channel name, payload, and PID
  • Useful for real-time cache invalidation, cross-process coordination, and background job triggers
对于支持服务器端发布/订阅的数据库(如PostgreSQL
LISTEN
/
NOTIFY
):
  • 使用
    AsyncEventChannel
    订阅命名通道
  • 通过SQL或
    publish()
    方法发布
    NOTIFY channel, payload
    消息
  • 处理器接收包含通道名称、负载和PID的
    EventMessage
    对象
  • 适用于实时缓存失效、跨进程协调和后台任务触发

Key Design Principles

核心设计原则

  1. Single Source of Truth: The
    SQL
    object holds all state for a given statement
  2. Immutability: All operations on a
    SQL
    object return new instances
  3. Type Safety: Parameters carry type information through the processing pipeline
  4. Protocol-Based Design: Uses Python protocols for runtime type checking instead of inheritance
  5. Single-Pass Processing: Parse once, transform once, validate once
  1. 单一数据源
    SQL
    对象持有给定语句的所有状态
  2. 不可变性:对
    SQL
    对象的所有操作都会返回新实例
  3. 类型安全:参数在处理管道中携带类型信息
  4. 基于协议的设计:使用Python协议进行运行时类型检查,而非继承
  5. 单遍处理:仅解析一次、转换一次、验证一次

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, 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
../advanced-alchemy/SKILL.md
for the ORM path.
For detailed instructions, patterns, and API guides, refer to the following documents:
选择
sqlspec
还是
advanced-alchemy
advanced-alchemy
提供带
UUIDAuditBase
、生命周期钩子、仓库/服务/Alembic集成和
OffsetPagination[T]
的ORM服务层——当你需要完整的CRUD功能、属性式行访问,且乐于使用SQLAlchemy生态时,请选择它。
sqlspec
提供直接的SQL控制、15+种驱动适配器(asyncpg、oracledb、DuckDB、BigQuery、SQLite等)、面向分析的Arrow原生结果流,以及按需使用的构建器API——当你需要显式SQL、异构数据库后端或Arrow集成时,请选择它。两者都通过官方插件与Litestar集成;ORM相关内容请查看
../advanced-alchemy/SKILL.md
如需详细说明、模式和API指南,请参考以下文档:

Standards & Style

标准与风格

  • Code Quality & Mypyc -- Type annotation rules, import standards, test structure.
  • 代码质量与Mypyc -- 类型注解规则、导入标准、测试结构。

Core Utilities

核心工具

  • SQLglot Best Practices -- v30+ guardrails, AST manipulation,
    copy=False
    pattern.
  • SQLglot最佳实践 -- v30+约束规则、AST操作、
    copy=False
    模式。

Architecture & Performance

架构与性能

  • Architecture & Caching -- Core data flow, NamespacedCache system, Mypyc compilation.
  • Data Dictionary -- Dialect feature flags, runtime introspection (
    get_tables
    ,
    get_columns
    ,
    get_indexes
    ), driver-side metadata API.
  • 架构与缓存 -- 核心数据流、NamespacedCache系统、Mypyc编译。
  • 数据字典 -- 方言特性标记、运行时自省(
    get_tables
    ,
    get_columns
    ,
    get_indexes
    )、驱动端元数据API。

Query Building & Execution

查询构建与执行

  • Query Builder API --
    sql
    factory: select, insert, update, delete, merge.
  • Driver Method Reference --
    select_value()
    ,
    select_one()
    ,
    select_many()
    ,
    select_to_arrow()
    .
  • Filter & Pagination System --
    LimitOffsetFilter
    ,
    OrderByFilter
    ,
    SearchFilter
    .
  • 查询构建器API --
    sql
    工厂:select、insert、update、delete、merge。
  • 驱动方法参考 --
    select_value()
    ,
    select_one()
    ,
    select_many()
    ,
    select_to_arrow()
  • 过滤器与分页系统 --
    LimitOffsetFilter
    ,
    OrderByFilter
    ,
    SearchFilter

Data Integration

数据集成

  • Arrow & ADBC Integration --
    select_to_arrow()
    zero-copy,
    copy_from_arrow()
    bulk loading.
  • SQL File Loading --
    SQLFileLoader
    with search paths, metadata directives.
  • Arrow与ADBC集成 --
    select_to_arrow()
    零拷贝、
    copy_from_arrow()
    批量加载。
  • SQL文件加载 --
    SQLFileLoader
    支持搜索路径、元数据指令。

Adapters & Drivers

适配器与驱动

  • Adapter & Driver Registry -- Full 15-adapter registry with dialects and parameter styles.
  • 适配器与驱动注册表 -- 完整的15种适配器注册表,包含方言和参数风格。

Framework & Storage Integrations

框架与存储集成

  • Framework Extensions -- Litestar plugin, FastAPI/Starlette integration.
  • Storage Integration -- ADK store, Litestar session stores, event channel backends.
  • Event Channels (Pub/Sub) --
    AsyncEventChannel
    , subscribe/publish patterns.
  • ADK Extension --
    SQLSpecSessionService
    ,
    SQLSpecMemoryService
    ,
    SQLSpecArtifactService
    , per-adapter ADK stores.
  • 框架扩展 -- Litestar插件、FastAPI/Starlette集成。
  • 存储集成 -- ADK存储、Litestar会话存储、事件通道后端。
  • 事件通道(发布/订阅) --
    AsyncEventChannel
    、订阅/发布模式。
  • ADK扩展 --
    SQLSpecSessionService
    ,
    SQLSpecMemoryService
    ,
    SQLSpecArtifactService
    , 适配各适配器的ADK存储。

Migrations & Schema

迁移与Schema

  • Native Migration Runner --
    sqlspec database
    CLI, timestamp versioning,
    ddl_migrations
    tracker, extension migrations, Litestar
    litestar db
    integration.
  • 原生迁移运行器 --
    sqlspec database
    CLI、时间戳版本控制、
    ddl_migrations
    跟踪器、扩展迁移、Litestar
    litestar db
    集成。

Observability

可观测性

  • Observability & Tracing -- Telemetry semantics, correlation extraction.
  • 可观测性与追踪 -- 遥测语义、关联提取。

Advanced Patterns

高级模式

  • Design Patterns -- Service layer, batch operations, upsert, AST tenant filters.
  • Service Patterns -- SQLSpecAsyncService base, named SQL templates via db_manager.get_sql, direct driver API (select_value / select_one / execute), variadic filter composition, create_filter_dependencies() wiring.
  • Dishka Integration -- FromDishka as Inject alias, multi-provider pattern (REQUEST-scoped domain services, REQUEST-scoped driver, APP-scoped singletons), handler injection.
  • Vector Search — Oracle VECTOR_DISTANCE cosine similarity, Vertex AI embedding generation, SHA256-keyed embedding cache, intent classification via exemplar similarity, pgvector cross-reference.
  • 设计模式 -- 服务层、批量操作、插入更新、AST租户过滤器。
  • 服务模式 -- SQLSpecAsyncService基类、通过db_manager.get_sql获取命名SQL模板、直接驱动API(select_value / select_one / execute)、可变过滤器组合、create_filter_dependencies() wiring。
  • Dishka集成 -- FromDishka作为Inject别名、多提供者模式(REQUEST作用域的领域服务、REQUEST作用域的驱动、APP作用域的单例)、处理器注入。
  • 向量搜索 — Oracle VECTOR_DISTANCE余弦相似度、Vertex AI嵌入生成、SHA256键控嵌入缓存、基于示例相似度的意图分类、pgvector交叉引用。

Key Resources

核心资源

Official References

官方参考

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.
  • 使用共享风格指南处理通用语言/框架规则,减少本技能文档中的重复内容。
  • 通用原则
  • Python
  • Litestar
  • 本技能文档聚焦于工具特定的工作流、边缘案例和集成细节。