Skip to content

API Reference

Public API

pyrsql

Public package interface for pyrsql.

ValueConverter module-attribute

ValueConverter = Callable[[str], object]

DEFAULT_JSON_OPTIONS module-attribute

DEFAULT_JSON_OPTIONS = JSONOptions()

Query dataclass

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 BoundComparison | BoundLogical

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
) -> BoundComparison | BoundLogical

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
BoundComparison | BoundLogical

The bound logical query IR.

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 dataclass

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 BoundSort | None

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
) -> BoundSort | None

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
BoundSort | None

The bound logical sort IR, or None when no fields were parsed.

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.

bound_page property

bound_page: BoundPage

The logical pagination IR for this request.

Returns:

Type Description
BoundPage

The bound pagination IR for this request.

__post_init__

__post_init__() -> None

Validates pagination invariants.

Raises:

Type Description
ValueError

If the page number is negative or the page size is not positive.

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 dataclass

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.

SortOptions dataclass

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.

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 configured SQL function names.

Raises:

Type Description
TypeError

If sort_field_types is not a mapping.

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

Validates path segments.

Raises:

Type Description
ValueError

If any segment is empty or padded with whitespace.

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.

__post_init__

__post_init__() -> None

Validates logical JSON comparison invariants.

Raises:

Type Description
ValueError

If the operator name is empty or padded.

from_raw_arguments classmethod

from_raw_arguments(
    *,
    path: JSONPath,
    operator_name: str,
    raw_arguments: tuple[tuple[str, bool], ...],
    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 a custom predicate independently of any orm.

FieldPolicySet dataclass

ORM-neutral field mapping and access-policy configuration.

Attributes:

Name Type Description
field_mapping Mapping[str, str]

Global selector-to-field mapping.

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 active restrictions.

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 dataclass

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.

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.

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 dataclass

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: type[Any], 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: str, target_type: type[Any] | None
) -> object

Converts a raw string into the requested target type.

Returns:

Type Description
object

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

object

provided.

Raises:

Type Description
ValueConversionError

If conversion fails or the target type is unsupported.

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 an ORM-specific compiled query object.

Attributes:

Name Type Description
orm_name str

Name of the ORM used to produce the compilation.

compiled_query CompiledQuery

ORM-specific compiled query payload.

__post_init__

__post_init__() -> None

Validates compilation result invariants.

apply

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

Applies the compiled query 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

Returns:

Type Description
_TargetT

The value returned by the compiled query 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.ir - Logical intermediate representation
  • pyrsql.parsing - Lexer, parser, operators, limits
  • pyrsql.selector - Selector syntax
  • pyrsql.semantic - Semantic binding
  • pyrsql.sorting - Sort syntax and binding