Skip to content

API Reference

Public API

pyrsql

Public package interface for pyrsql.

ValueConverter module-attribute

ValueConverter: TypeAlias = Callable[
    [RawValue], ConvertedValue
]

DEFAULT_JSON_OPTIONS module-attribute

DEFAULT_JSON_OPTIONS = JSONOptions()

Query

Bases: Struct

Represents a parsed ORM-neutral query request.

The query preserves the raw text, the parsed expression tree, and the bound logical representation used by later compilation stages.

Attributes:

Name Type Description
text str

Raw RSQL text that produced the query.

options QueryOptions

Normalized query configuration used during parsing.

expression Expression

Parsed syntax tree, if parsing succeeded.

bound_expression Expression

Bound logical expression tree.

parse classmethod

parse(
    query_text: str, *, options: QueryOptions | None = None
) -> Query

Parses raw RSQL text into a query object.

Parameters:

Name Type Description Default
query_text str

Raw RSQL text to parse.

required
options QueryOptions | None

Optional query configuration.

None

Returns:

Type Description
Query

A parsed query object.

parse_expression staticmethod

parse_expression(
    query_text: str, *, options: QueryOptions
) -> Expression

Parses raw RSQL text into a syntax tree.

Parameters:

Name Type Description Default
query_text str

Raw RSQL text to parse.

required
options QueryOptions

Query configuration used by the parser.

required

Returns:

Type Description
Expression

The parsed syntax tree.

bind_expression staticmethod

bind_expression(
    expression: Expression, *, options: QueryOptions
) -> Expression

Binds a syntax tree into logical query IR.

Parameters:

Name Type Description Default
expression Expression

Parsed syntax tree to bind.

required
options QueryOptions

Query configuration used by semantic binding.

required

Returns:

Type Description
Expression

The semantically validated expression tree.

compile

compile(*, orm: ORM) -> CompilationResult

Compiles the query using the provided ORM.

Parameters:

Name Type Description Default
orm ORM

ORM adapter used to compile the query.

required

Returns:

Type Description
CompilationResult

The ORM-specific compilation result.

apply

apply(
    target: _TargetT, model: type[_ModelT], *, orm: ORM
) -> _TargetT

Compiles and applies the query using the provided ORM.

Parameters:

Name Type Description Default
target _TargetT

ORM-specific target to mutate.

required
model type[_ModelT]

ORM model class used to resolve the query.

required
orm ORM

ORM adapter used to compile the query.

required

Returns:

Type Description
_TargetT

The value returned by the ORM-specific apply operation.

Sort

Bases: Struct

Represents an ORM-neutral parsed sort request.

Attributes:

Name Type Description
text str | None

Raw sort text used to build the request.

options SortOptions

Normalized sort configuration used during parsing.

fields tuple[SortField, ...]

Parsed sort fields, if parsing succeeded.

bound_sort tuple[SortField, ...]

Bound logical sort IR when fields are present.

parse classmethod

parse(
    sort_text: str | None,
    *,
    options: SortOptions | None = None,
) -> Sort

Parses raw sort text into a sort object.

Parameters:

Name Type Description Default
sort_text str | None

Raw sort text to parse.

required
options SortOptions | None

Optional sort configuration.

None

Returns:

Type Description
Sort

A parsed sort object.

parse_fields staticmethod

parse_fields(
    sort_text: str | None, *, options: SortOptions
) -> tuple[SortField, ...]

Parses raw sort text into sort fields.

Parameters:

Name Type Description Default
sort_text str | None

Raw sort text to parse.

required
options SortOptions

Sort configuration used by the parser.

required

Returns:

Type Description
tuple[SortField, ...]

The parsed sort fields.

bind_fields staticmethod

bind_fields(
    fields: tuple[SortField, ...], *, options: SortOptions
) -> tuple[SortField, ...]

Binds parsed sort fields into logical sort IR.

Parameters:

Name Type Description Default
fields tuple[SortField, ...]

Parsed sort fields to bind.

required
options SortOptions

Sort configuration used by semantic binding.

required

Returns:

Type Description
tuple[SortField, ...]

The semantically validated sort fields.

compile

compile(*, orm: ORM) -> SortCompilationResult

Compiles the sort using the provided ORM.

Parameters:

Name Type Description Default
orm ORM

ORM adapter used to compile the sort.

required

Returns:

Type Description
SortCompilationResult

The ORM-specific sort compilation result.

apply

apply(
    target: _TargetT, model: type[_ModelT], *, orm: ORM
) -> _TargetT

Compiles and applies the sort using the provided ORM.

Parameters:

Name Type Description Default
target _TargetT

ORM-specific target to mutate.

required
model type[_ModelT]

ORM model class used to resolve the sort.

required
orm ORM

ORM adapter used to compile the sort.

required

Returns:

Type Description
_TargetT

The value returned by the ORM-specific apply operation.

PageRequest

Bases: Struct

Represents an ORM-neutral pagination request.

Attributes:

Name Type Description
page_number int

Zero-based page number.

page_size int

Number of rows requested per page.

offset property

offset: int

The zero-based row offset for this request.

Returns:

Type Description
int

The zero-based row offset.

limit property

limit: int

The maximum number of rows for this request.

Returns:

Type Description
int

The maximum number of rows to fetch.

__post_init__

__post_init__() -> None

Validates pagination invariants.

of classmethod

of(page_number: int, page_size: int) -> PageRequest

Builds a pagination request from page number and page size.

Parameters:

Name Type Description Default
page_number int

Zero-based page number.

required
page_size int

Number of rows requested per page.

required

Returns:

Type Description
PageRequest

A validated pagination request.

from_offset classmethod

from_offset(*, offset: int, limit: int) -> PageRequest

Builds a pagination request from offset and limit.

Parameters:

Name Type Description Default
offset int

Zero-based row offset.

required
limit int

Maximum number of rows requested.

required

Returns:

Type Description
PageRequest

A validated pagination request.

Raises:

Type Description
ValueError

If the offset or limit is invalid, or if the offset does not align with the limit.

compile

compile(*, orm: ORM) -> PageCompilationResult

Compiles the page request using the provided ORM.

Parameters:

Name Type Description Default
orm ORM

ORM adapter used to compile the page request.

required

Returns:

Type Description
PageCompilationResult

The ORM-specific page compilation result.

apply

apply(
    target: _TargetT, model: type[_ModelT], *, orm: ORM
) -> _TargetT

Compiles and applies the page request using the ORM.

Parameters:

Name Type Description Default
target _TargetT

ORM-specific target to mutate.

required
model type[_ModelT]

ORM model class used to resolve the page request.

required
orm ORM

ORM adapter used to compile the page request.

required

Returns:

Type Description
_TargetT

The value returned by the ORM-specific apply operation.

QueryOptions

Bases: Struct

ORM-neutral configuration for parsing and compiling queries.

The options bundle parser limits, operator registries, field policies, custom predicates, value converters, and JSON behavior in one immutable object.

field_policy property

field_policy: FieldPolicySet

The normalized field mapping and access configuration.

Returns:

Type Description
FieldPolicySet

The compiled field policy for this query configuration.

field_converter_set property

field_converter_set: FieldValueConverterSet

The normalized field-scoped converter configuration.

Returns:

Type Description
FieldValueConverterSet

The compiled field converter set for this query configuration.

procedure_policy property

procedure_policy: ProcedureAccessPolicy

The compiled procedure access policy.

Returns:

Type Description
ProcedureAccessPolicy

The compiled procedure access policy for this query configuration.

__post_init__

__post_init__() -> None

Normalizes option containers into immutable representations.

with_field_whitelist

with_field_whitelist(
    field_whitelist: frozenset[str],
) -> QueryOptions

Returns one copy with only the global field whitelist replaced.

Returns:

Type Description
QueryOptions

A query options copy with the provided field whitelist.

SortOptions

Bases: Struct

ORM-neutral sort options.

field_policy property

field_policy: FieldPolicySet

Returns the normalized field mapping and access configuration.

Returns:

Type Description
FieldPolicySet

The compiled field policy for this sort configuration.

procedure_policy property

procedure_policy: ProcedureAccessPolicy

Returns the compiled procedure access policy.

Returns:

Type Description
ProcedureAccessPolicy

The compiled procedure access policy for this sort configuration.

__post_init__

__post_init__() -> None

Normalizes option containers into immutable representations.

with_field_whitelist

with_field_whitelist(
    field_whitelist: frozenset[str],
) -> SortOptions

Returns one copy with only the global field whitelist replaced.

Returns:

Type Description
SortOptions

A sort options copy with the provided field whitelist.

JSONOptions

Bases: Struct

ORM-neutral JSON behavior flags.

Attributes:

Name Type Description
path_exists_function str

SQL function used for JSON path existence.

path_exists_tz_function str

SQL function used for timezone-aware JSON path existence checks.

use_datetime bool

Whether JSON values should be interpreted as datetimes when possible.

__post_init__

__post_init__() -> None

Validates and normalizes configured JSON options.

JSONSortScalarType

Bases: str, Enum

Supported scalar cast strategies for JSON sort expressions.

JSONPath

Bases: Struct

Represents an ORM-neutral JSON path.

Attributes:

Name Type Description
segments tuple[str, ...]

Ordered path segments from the JSON root to the target.

is_root property

is_root: bool

Whether the path targets the root JSON value.

Returns:

Type Description
bool

True when the path has no segments.

__post_init__

__post_init__() -> None

Materializes derived cached path representations.

to_dot_path

to_dot_path() -> str

The path rendered as a dotted string.

Returns:

Type Description
str

The cached dotted representation of the JSON path.

to_postgresql_jsonpath

to_postgresql_jsonpath() -> str

The path rendered as a PostgreSQL jsonpath root expression.

Returns:

Type Description
str

The cached PostgreSQL jsonpath representation.

JSONPathComparison

Bases: Struct

Represents one JSON path comparison after semantic normalization.

from_raw_arguments classmethod

from_raw_arguments(
    *,
    path: JSONPath,
    operator_name: str,
    raw_arguments: tuple[RawJSONArgument, ...],
    normalizer: JSONScalarNormalizer | None = None,
) -> JSONPathComparison

Builds a normalized JSON comparison from raw RSQL arguments.

Returns:

Type Description
JSONPathComparison

One normalized JSON path comparison.

JSONScalarNormalizer

Normalizes raw RSQL arguments to JSON-aware values.

normalize

normalize(
    raw_value: str, *, quoted: bool
) -> JSONScalarValue

Builds one JSON value from a raw RSQL argument.

Returns:

Type Description
JSONScalarValue

One normalized JSON scalar or structured value.

JSONScalarValue

Bases: Struct

Represents one normalized JSON scalar or structured value.

CustomPredicateDefinition

Bases: Struct

Defines one ORM-neutral custom predicate contract.

Attributes:

Name Type Description
operator ComparisonOperator

The query-language operator exposed to users.

argument_type ArgumentType

Runtime type used to coerce raw predicate arguments before backend-specific lowering.

FieldPolicySet

Bases: Struct

ORM-neutral runtime field access and model-mapping configuration.

Attributes:

Name Type Description
field_whitelist frozenset[str]

Globally allowed field paths.

field_blacklist frozenset[str]

Globally blocked field paths.

model_field_mapping Mapping[type[Any], Mapping[str, str]]

Model-specific selector-to-field mappings.

model_field_whitelist Mapping[type[Any], frozenset[str]]

Model-specific allowed field names.

model_field_blacklist Mapping[type[Any], frozenset[str]]

Model-specific blocked field names.

is_empty property

is_empty: bool

Whether the policy carries no runtime mapping or access rules.

__post_init__

__post_init__() -> None

Normalizes policy containers into immutable views.

map_model_field

map_model_field(model: type[Any], selector: str) -> str

Maps one selector segment for a specific model when configured.

Parameters:

Name Type Description Default
model type[Any]

ORM model used to look up a model-specific mapping.

required
selector str

Raw selector segment to map.

required

Returns:

Type Description
str

The mapped selector segment, or the original value when no mapping

str

is configured.

validate_global_field_access

validate_global_field_access(field_path: str) -> None

Validates global whitelist and blacklist rules.

Parameters:

Name Type Description Default
field_path str

Dotted field path to validate.

required

Raises:

Type Description
ValueError

If the field path is not allowed or is blocked.

validate_model_field_access

validate_model_field_access(
    model: type[Any], field_name: str
) -> None

Validates model-specific whitelist and blacklist rules.

Parameters:

Name Type Description Default
model type[Any]

ORM model used to look up model-specific rules.

required
field_name str

Field name to validate.

required

Raises:

Type Description
ValueError

If the field name is not allowed or is blocked.

FieldValueConverterSet

Bases: Struct

Immutable field-scoped value converter configuration.

__post_init__

__post_init__() -> None

Normalizes nested converter mappings into immutable views.

resolve

resolve(
    *,
    model: type[Any] | None,
    field_name: str | None,
    field_path: str | None,
) -> ValueConverter | None

Resolves the most specific converter configured for a field.

Returns:

Type Description
ValueConverter | None

The most specific configured converter, or None.

Resolution precedence
  1. model-scoped converter by model + field_name
  2. global field-path converter by field_path

ProcedureAccessPolicy

Bases: Struct

Regex-based access policy for selector procedures.

The policy stores compiled whitelist and blacklist patterns used to check whether a procedure name is allowed.

Attributes:

Name Type Description
whitelist_patterns tuple[Pattern[str], ...]

Compiled whitelist regular expressions.

blacklist_patterns tuple[Pattern[str], ...]

Compiled blacklist regular expressions.

__post_init__

__post_init__() -> None

Normalizes and validates compiled regex patterns.

from_patterns classmethod

from_patterns(
    whitelist: tuple[str, ...], blacklist: tuple[str, ...]
) -> ProcedureAccessPolicy

Builds a policy from raw regex pattern strings.

Parameters:

Name Type Description Default
whitelist tuple[str, ...]

Raw regular expressions that allow procedures.

required
blacklist tuple[str, ...]

Raw regular expressions that deny procedures.

required

Returns:

Type Description
ProcedureAccessPolicy

A compiled procedure access policy.

is_whitelisted

is_whitelisted(procedure_name: str) -> bool

Whether the procedure matches the whitelist.

Returns:

Type Description
bool

True when the procedure matches at least one whitelist pattern.

is_blacklisted

is_blacklisted(procedure_name: str) -> bool

Whether the procedure matches the blacklist.

Returns:

Type Description
bool

True when the procedure matches at least one blacklist pattern.

ValueConverterRegistry

Bases: Struct

Immutable registry of orm-neutral string-to-type converters.

__post_init__

__post_init__() -> None

Normalizes the converter mapping into an immutable view.

with_converter

with_converter(
    target_type: TargetType, converter: ValueConverter
) -> ValueConverterRegistry

Returns a new registry with one additional converter.

Returns:

Type Description
ValueConverterRegistry

A new registry containing the additional converter.

convert

convert(
    raw_value: RawValue, target_type: TargetType | None
) -> ConvertedValue

Converts a raw string into the requested target type.

Returns:

Type Description
ConvertedValue

The converted value, or the raw string when no target type is

ConvertedValue

provided.

ORM

Bases: ABC

Abstract ORM contract used by the pyrsql public API.

name abstractmethod property

name: str

The stable ORM name.

Returns:

Type Description
str

The ORM's stable identifier.

compile_query abstractmethod

compile_query(query: Query) -> CompiledQuery

Compiles a high-level query into an ORM-specific form.

Parameters:

Name Type Description Default
query Query

High-level query to compile.

required

Returns:

Type Description
CompiledQuery

A compiled query object for this ORM.

compile_sort abstractmethod

compile_sort(sort: Sort) -> CompiledSort

Compiles a high-level sort into an ORM-specific form.

Parameters:

Name Type Description Default
sort Sort

High-level sort request to compile.

required

Returns:

Type Description
CompiledSort

A compiled sort object for this ORM.

compile_page_request abstractmethod

compile_page_request(
    page_request: PageRequest,
) -> CompiledPageRequest

Compiles a pagination request into an ORM-specific form.

Parameters:

Name Type Description Default
page_request PageRequest

Pagination request to compile.

required

Returns:

Type Description
CompiledPageRequest

A compiled page request object for this ORM.

CompilationResult

Bases: Struct

Wraps one ORM-specific compiled artifact.

Attributes:

Name Type Description
orm_name str

Name of the ORM used to produce the compilation.

compiled CompiledArtifact

ORM-specific compiled payload implementing apply.

apply

apply(target: _TargetT, model: type[_ModelT]) -> _TargetT

Applies the compiled artifact to an ORM-specific target.

Parameters:

Name Type Description Default
target _TargetT

ORM-specific target to mutate.

required
model type[_ModelT]

ORM model class used to resolve the compilation.

required

Returns:

Type Description
_TargetT

The value returned by the compiled artifact application.

parse

parse(
    query_text: str, *, options: QueryOptions | None = None
) -> Query

Parses raw RSQL text into a query object.

Parameters:

Name Type Description Default
query_text str

Raw RSQL text to parse.

required
options QueryOptions | None

Optional query configuration.

None

Returns:

Type Description
Query

A parsed query object.

compile

compile(
    query_text: str,
    *,
    orm: ORM,
    options: QueryOptions | None = None,
) -> CompilationResult

Compiles raw RSQL text using the provided ORM.

Parameters:

Name Type Description Default
query_text str

Raw RSQL text to compile.

required
orm ORM

ORM adapter used to compile the query.

required
options QueryOptions | None

Optional query configuration.

None

Returns:

Type Description
CompilationResult

The ORM-specific compilation result.

apply

apply(
    target: _TargetT,
    model: type[_ModelT],
    query_text: str,
    *,
    orm: ORM,
    options: QueryOptions | None = None,
) -> _TargetT

Applies raw RSQL text to an ORM-specific target.

Parameters:

Name Type Description Default
target _TargetT

ORM-specific target to mutate.

required
model type[_ModelT]

ORM model class used to resolve the query.

required
query_text str

Raw RSQL text to apply.

required
orm ORM

ORM adapter used to compile the query.

required
options QueryOptions | None

Optional query configuration.

None

Returns:

Type Description
_TargetT

The value returned by the ORM-specific apply operation.

Subpackages

  • pyrsql.adapters.fastapi - FastAPI adapter (FastAPICriteriaConfig, RequestCriteria, CriteriaDependency)
  • pyrsql.integrations.fastapi - FastAPI + SQLAlchemy (FastAPISQLAlchemyIntegration, FastAPISQLAlchemyResource)
  • pyrsql.orms.sqlalchemy - SQLAlchemy backend (SQLAlchemyORM)
  • pyrsql.core - ORM-neutral core types and options
  • pyrsql.parsing - Lexer, parser, operators, limits
  • pyrsql.selector - Selector syntax
  • pyrsql.semantic - Semantic binding
  • pyrsql.sorting - Sort syntax and binding