Skip to content

logicblocks.event.persistence

class TypeRegistryConverter[I, R](
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: Converter[I, R], ABC

Convert items by delegating to a converter registered for their type.

Each item is converted by the converter registered for its exact class. Lookup does not consider base classes, so a converter registered for a class is not used for its subclasses. Registering a converter for a type that already has one replaces it.

Subclasses implement register, typically by calling _register, to narrow the accepted item and converter types.

Parameters:

  • registry (Mapping[type[I], Converter[Any, R]] | None) — An initial mapping from item type to the converter for that type. The mapping is copied, so later changes to it have no effect. Defaults to an empty registry.
def register(item_type: type[I], converter: Converter[I, R]) -> Self

Register the converter to use for items of a type.

Parameters:

  • item_type (type[I]) — The exact class of the items to convert.
  • converter (Converter[I, R]) — The converter to use for items of that class.

Returns:

  • Self — this converter, to allow chaining.
def convert(item: I) -> R

Convert an item using the converter registered for its class.

Parameters:

  • item (I) — The item to convert.

Returns:

  • R — the result of the registered converter.

Raises:

  • ValueError — If no converter is registered for the item’s class.
class ClauseConverter[R: Identifiable, C: query.Clause = query.Clause]

Bases: Converter[C, ResultSetTransformer[R]], ABC

Converts a clause into a transformer over in-memory result sets.

class DelegatingQueryConverter[R: Identifiable](
    function_converter: TypeRegistryFunctionConverter[R] | None = None,
    clause_converter: TypeRegistryClauseConverter[R] | None = None,
    query_converter: TypeRegistryQueryConverter[R] | None = None,
)

Bases: Converter[Query, ResultSetTransformer[R]]

Converts queries into transformers over in-memory result sets.

Holds separate registries for functions, clauses and queries. The registries start empty: call with_default_converters to register converters for all built-in query types, or register custom ones.

Parameters:

def with_default_function_converters() -> Self

Register the converter for Similarity.

def with_default_clause_converters() -> Self

Register converters for the built-in clause types.

def with_default_query_converters() -> Self

Register converters for Search and Lookup.

def with_default_converters() -> Self

Register all built-in function, clause and query converters.

def register_function_converter[F: Function](
    function_type: type[F],
    converter: FunctionConverter[R, F],
) -> Self
def register_clause_converter[C: Clause](
    clause_type: type[C],
    converter: ClauseConverter[R, C],
) -> Self
def register_query_converter[Q: Query](
    query_type: type[Q],
    converter: QueryConverter[R, Q],
) -> Self
def convert_function(item: Function) -> ResultSetTransformer[R]
def convert_clause(item: Clause) -> ResultSetTransformer[R]
def convert_query(item: Query) -> ResultSetTransformer[R]
def convert(item: Query) -> ResultSetTransformer[R]
class FilterClauseConverter[R: Identifiable]

Bases: ClauseConverter[R, FilterClause]

Converts a FilterClause into a transformer that filters results.

Results missing a nested level of the clause’s path never match.

def convert(item: FilterClause) -> ResultSetTransformer[R]
class FunctionConverter[R: Identifiable, F: query.Function = query.Function]

Bases: Converter[F, ResultSetTransformer[R]], ABC

Converts a function into a transformer that adds computed values.

class Identifiable

Bases: Protocol

A record with a string ID, as required for in-memory querying.

property id: str
class KeySetPagingClauseConverter[R: Identifiable]

Bases: ClauseConverter[R, KeySetPagingClause]

Converts a KeySetPagingClause into a transformer selecting a page.

Pages are taken relative to the position of the record with last_id in the current order of the results. If that record is not present, or no last_id is given when paging backwards, the page is empty.

def convert(item: KeySetPagingClause) -> ResultSetTransformer[R]
class LookupQueryConverter[R: Identifiable](
    clause_converter: Converter[Clause, ResultSetTransformer[R]],
)

Bases: QueryConverter[R, Lookup]

Converts a Lookup into a transformer that applies its filters.

Parameters:

def convert(item: Lookup) -> ResultSetTransformer[R]
class OffsetPagingClauseConverter[R: Identifiable]

Bases: ClauseConverter[R, OffsetPagingClause]

Converts an OffsetPagingClause into a transformer selecting a page.

def convert(item: OffsetPagingClause) -> ResultSetTransformer[R]
class QueryConverter[R: Identifiable, Q: query.Query = query.Query]

Bases: Converter[Q, ResultSetTransformer[R]], ABC

Converts a query into a transformer over in-memory result sets.

class ResultSet[T: Identifiable](
    results: Sequence[Result[T]],
    extra: Mapping[str, Any],
)

An immutable, ordered set of results that query transformers act on.

Attributes:

  • results (Sequence[Result[T]]) — The results, in order.
  • extra (Mapping[str, Any]) — Additional values associated with the set as a whole.
results: Sequence[Result[T]]
extra: Mapping[str, Any]
@classmethod
def of(*records: T) -> Self

Create a result set containing the given records, in order.

property records: Sequence[T]

The underlying records, in order.

def with_results(results: Sequence[Result[T]]) -> Self
def with_extra(extra: Mapping[str, Any]) -> Self
type ResultSetTransformer[T: Identifiable] = Callable[[ResultSet[T]], ResultSet[T]]
class SearchQueryConverter[R: Identifiable](
    clause_converter: Converter[Clause, ResultSetTransformer[R]],
)

Bases: QueryConverter[R, Search]

Converts a Search into a transformer over result sets.

The transformer applies the filters, then the sort, then the paging.

Parameters:

def convert(item: Search) -> ResultSetTransformer[R]
class SortClauseConverter[R: Identifiable](
    function_converter: Converter[Function, ResultSetTransformer[R]],
)

Bases: ClauseConverter[R, SortClause]

Converts a SortClause into a transformer that sorts results.

Any functions among the sort fields are evaluated before sorting.

Parameters:

def convert(item: SortClause) -> ResultSetTransformer[R]
class TypeRegistryClauseConverter[R: Identifiable](
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: TypeRegistryConverter[Clause, ResultSetTransformer[R]]

Converts clauses using the converter registered for their type.

def register[C: Clause](
    item_type: type[C],
    converter: Converter[C, ResultSetTransformer[R]],
) -> Self
class TypeRegistryFunctionConverter[R: Identifiable](
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: TypeRegistryConverter[Function, ResultSetTransformer[R]]

Converts functions using the converter registered for their type.

def register[F: Function](
    item_type: type[F],
    converter: Converter[F, ResultSetTransformer[R]],
) -> Self
class TypeRegistryQueryConverter[R: Identifiable](
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: TypeRegistryConverter[Query, ResultSetTransformer[R]]

Converts queries using the converter registered for their type.

def register[Q: Query](
    item_type: type[Q],
    converter: Converter[Q, ResultSetTransformer[R]],
) -> Self
class Cast(*, expression: Expression, typename: str)

Bases: Expression

A CAST(expression AS typename) expression.

Attributes:

  • expression (Expression) — The expression to cast.
  • typename (str) — The type to cast to, quoted as an identifier.
expression: Expression
typename: str
def to_fragment() -> ParameterisedQueryFragment
class ColumnReference(
    *,
    schema: str | None = None,
    table: str | None = None,
    field: str,
)

Bases: Expression

A reference to a column, optionally qualified by table and schema.

Attributes:

  • schema (str | None) — The schema of the table. Requires table to be set.
  • table (str | None) — The table containing the column.
  • field (str) — The name of the column.
schema: str | None = None
table: str | None = None
field: str
def to_fragment() -> ParameterisedQueryFragment
class Condition(
    left: ConditionOperand | None = None,
    right: ConditionOperand | None = None,
    operator: Operator | None = None,
)

Bases: Expression

A binary condition, built fluently, for use in a WHERE clause.

Each operand may be an expression, a sequence of expressions (rendered as a row, for row comparisons) or a query (rendered as a subquery). Builder methods return a new condition rather than modifying this one.

Parameters:

  • left (ConditionOperand | None) — The left-hand operand.
  • right (ConditionOperand | None) — The right-hand operand.
  • operator (Operator | None) — The comparison operator.
def left(left: ConditionOperand) -> Self
def right(right: ConditionOperand) -> Self
def operator(operator: Operator) -> Self
def equals() -> Self
def not_equals() -> Self
def greater_than() -> Self
def greater_than_or_equal_to() -> Self
def less_than() -> Self
def less_than_or_equal_to() -> Self
def regex_matches()
def not_regex_matches()
def to_fragment() -> ParameterisedQueryFragment
class ConnectionSettings(
    *,
    host: str,
    port: int,
    dbname: str,
    user: str,
    password: str,
)

Settings for connecting to a Postgres database.

The password is masked in the repr.

Attributes:

  • host (str) — The hostname or address of the database server.
  • port (int) — The port on which the database server listens.
  • dbname (str) — The name of the database to connect to.
  • user (str) — The user to connect as.
  • password (str) — The password for the user.
host: str
port: int
dbname: str
user: str
password: str
def to_connection_string() -> str

Build a postgresql:// connection URI from these settings.

The user and password are included without URL encoding.

Returns:

  • str — the connection URI, including the password.
type ConnectionSource = ConnectionSettings | AsyncConnectionPool[AsyncConnection]

Settings from which to open connections, or an existing pool to use.

class FunctionApplication(
    *,
    function_name: str,
    arguments: Sequence[Expression] = (),
)

Bases: Expression

A call to a SQL function, such as to_jsonb(...).

Attributes:

  • function_name (str) — The name of the function, quoted as an identifier.
  • arguments (Sequence[Expression]) — The arguments to pass to the function.
function_name: str
arguments: Sequence[Expression] = ()
def to_fragment() -> ParameterisedQueryFragment
class Operator

Bases: StrEnum

SQL comparison operators, with values as they appear in SQL.

EQUALS = '='
NOT_EQUALS = '!='
GREATER_THAN = '>'
GREATER_THAN_OR_EQUAL = '>='
LESS_THAN = '<'
LESS_THAN_OR_EQUAL = '<='
IN = 'IN'
CONTAINS = '@>'
REGEX_MATCHES = '~'
NOT_REGEX_MATCHES = '!~'
IS_NULL = 'IS NULL'
IS_NOT_NULL = 'IS NOT NULL'
property comparison_type: ComparisonType

How nested values are compared by this operator.

Regular expression and null checks compare text; all other operators compare JSONB.

def has_value() -> bool

Return whether the operator takes a right-hand operand.

type ParameterisedQuery = tuple[abc.Query, Sequence[Any]]

A SQL query paired with the parameters to bind into it.

type ParameterisedQueryFragment = tuple[SqlFragment, Sequence[Any]]

A SQL fragment, possibly empty, paired with its parameters.

class Query(
    *,
    common_table_expressions: Sequence[tuple[Self, str]] | None = None,
    unions: tuple[Sequence[Self], SetQuantifier] | None = None,
    select_target_list: Sequence[ResultTarget | Star] | None = None,
    from_tables: Sequence[str] | None = None,
    from_subqueries: Sequence[tuple[Self, str]] | None = None,
    where_conditions: Sequence[Condition] | None = None,
    sortby_list: Sequence[SortBy] | None = None,
    limit_value: int | None = None,
    offset_value: int | None = None,
)

An immutable, fluent builder for SQL SELECT queries.

Each builder method returns a new query rather than modifying this one. Call build to render the query and its parameters for execution.

common_table_expressions: Sequence[tuple[Self, str]]
unions: tuple[Sequence[Self], SetQuantifier] | None
select_target_list: Sequence[ResultTarget | Star]
from_tables: Sequence[str]
from_subqueries: Sequence[tuple[Self, str]]
where_conditions: Sequence[Condition]
sortby_list: Sequence[SortBy]
limit_value: int | None
offset_value: int | None
@staticmethod
def union(
    query1: Query,
    query2: Query,
    *more_queries: Query,
    mode: SetQuantifier = SetQuantifier.DISTINCT,
) -> Query

Combine two or more queries with UNION.

Parameters:

  • query1 (Query) — The first query.
  • query2 (Query) — The second query.
  • *more_queries (Query) — Any further queries.
  • mode (SetQuantifier) — Whether to keep or remove duplicate rows. Defaults to removing them.

Returns:

  • Query — a query over the union of the given queries.
def clone(**kwargs: Unpack[QueryParams]) -> Self

Return a copy of this query with the given parts replaced.

def with_query(query: Self, name: str) -> Self

Add a common table expression, rendered as WITH name AS (...).

def select(*target_list: str | Expression | ResultTarget) -> Self
def select_all() -> Self
def from_table(table: str) -> Self
def from_subquery(subquery: Self, alias: str) -> Self
def where(*conditions: Condition) -> Self
def replace_order_by(*sortby_list: str | SortBy) -> Self

Replace any existing ORDER BY terms with the given terms.

def order_by(*sortby_list: str | SortBy) -> Self

Append the given ORDER BY terms; strings name columns.

def limit(limit: int | None) -> Self
def offset(offset: int | None) -> Self
def to_fragment() -> ParameterisedQueryFragment
def build() -> ParameterisedQuery

Render the query for execution.

Returns:

class QueryApplier

Bases: Applier[Query], ABC

Transforms a query, for example by adding a clause to it.

class QueryConverter(
    table_settings: TableSettings,
    function_converter: TypeRegistryFunctionConverter | None = None,
    clause_converter: TypeRegistryClauseConverter | None = None,
    query_converter: TypeRegistryQueryConverter | None = None,
)

Bases: Converter[genericquery.Query, ParameterisedQuery]

Converts queries into parameterised SQL queries against a table.

Holds separate registries for functions, clauses and queries. The registries start empty: call with_default_converters to register converters for all built-in query types, or register custom ones.

Parameters:

  • table_settings (TableSettings) — The table that queries select from.
  • function_converter (TypeRegistryFunctionConverter | None) — The registry of function converters. Defaults to an empty registry.
  • clause_converter (TypeRegistryClauseConverter | None) — The registry of clause converters. Defaults to an empty registry.
  • query_converter (TypeRegistryQueryConverter | None) — The registry of query converters. Defaults to an empty registry.
def with_default_function_converters() -> Self

Register the converter for Similarity.

def with_default_clause_converters() -> Self

Register converters for the built-in clause types.

def with_default_query_converters() -> Self

Register converters for Search and Lookup.

def with_default_converters()

Register all built-in function, clause and query converters.

def register_function_converter[F: genericquery.Function](
    function_type: type[F],
    converter: FunctionConverter[F],
) -> Self
def register_clause_converter[C: genericquery.Clause](
    clause_type: type[C],
    converter: ClauseConverter[C],
) -> Self
def register_query_converter[Q: genericquery.Query](
    query_type: type[Q],
    converter: QueryConverter[Q],
) -> Self
def apply_clause(
    clause: genericquery.Clause,
    query_builder: postgresquery.Query,
) -> postgresquery.Query

Convert a clause and apply it to a query under construction.

Parameters:

  • clause (genericquery.Clause) — The clause to convert.
  • query_builder (postgresquery.Query) — The query to apply the clause to.

Returns:

  • postgresquery.Query — the query with the clause applied.
def convert_query(item: genericquery.Query) -> postgresquery.ParameterisedQuery
def convert(item: genericquery.Query) -> postgresquery.ParameterisedQuery
class ResultTarget(expression: Expression, label: str | None = None)

Bases: Node

An entry in a select list, optionally labelled with AS.

Attributes:

  • expression (Expression) — The expression to select.
  • label (str | None) — The name to give the selected value, if any.
expression: Expression
label: str | None = None
def to_fragment() -> ParameterisedQueryFragment
class SetQuantifier

Bases: StrEnum

Whether a UNION keeps (ALL) or removes (DISTINCT) duplicates.

ALL = 'ALL'
DISTINCT = 'DISTINCT'
class SortBy(expression: Expression, direction: SortDirection | None = None)

Bases: Node

A single ORDER BY term.

Attributes:

  • expression (Expression) — The expression to sort by.
  • direction (SortDirection | None) — The direction to sort in. If None, no direction is rendered, so the database default of ascending applies.
expression: Expression
direction: SortDirection | None = None
def is_ascending()

Return whether the term sorts ascending, including by default.

def is_descending()
def reverse()

Return this term with its direction reversed, if it has one.

def to_fragment() -> ParameterisedQueryFragment
class SortDirection

Bases: StrEnum

Direction of an ORDER BY term.

ASC = 'ASC'
DESC = 'DESC'
def reverse() -> SortDirection

Return the opposite direction.

type SqlFragment = sql.Composable | None
class Star(schema: str | None = None, table: str | None = None)

Bases: Expression

A * select target, optionally qualified by table and schema.

Attributes:

  • schema (str | None) — The schema of the table. Requires table to be set.
  • table (str | None) — The table whose columns to select.
schema: str | None = None
table: str | None = None
def to_fragment() -> ParameterisedQueryFragment
class TableSettings(table_name: str)

Settings for the Postgres table that an adapter reads and writes.

Attributes:

  • table_name (str) — The name of the table.
table_name: str
class Constant(value: Any)

Bases: Expression

A value passed to the query as a bound parameter.

Attributes:

  • value (Any) — The value to bind.
value: Any
def to_fragment() -> ParameterisedQueryFragment

logicblocks.event.persistence.postgres.converters

Section titled “logicblocks.event.persistence.postgres.converters”
class FilterClauseConverter(
    operators: Mapping[genericquery.Operator, postgresquery.Operator] | None = None,
)

Bases: ClauseConverter[genericquery.FilterClause]

Converts a FilterClause into a FilterClauseQueryApplier.

Parameters:

  • operators (Mapping[genericquery.Operator, postgresquery.Operator] | None) — The mapping from query operators to SQL operators. Defaults to a mapping covering every Operator.
def convert(item: genericquery.FilterClause) -> QueryApplier
class KeySetPagingClauseConverter(table_settings: TableSettings)

Bases: ClauseConverter[genericquery.KeySetPagingClause]

Converts a KeySetPagingClause into a key-set paging applier.

Parameters:

  • table_settings (TableSettings) — The table holding the records being paged.
def convert(item: genericquery.KeySetPagingClause) -> QueryApplier
class LookupQueryConverter(
    clause_converter: Converter[genericquery.Clause, QueryApplier],
    table_settings: TableSettings,
)

Bases: QueryConverter[genericquery.Lookup]

Converts a Lookup into a filtered SELECT over a table.

Parameters:

def convert(item: genericquery.Lookup) -> ParameterisedQuery
class OffsetPagingClauseConverter

Bases: ClauseConverter[genericquery.OffsetPagingClause]

Converts an OffsetPagingClause into an offset paging applier.

def convert(item: genericquery.OffsetPagingClause) -> QueryApplier
class SearchQueryConverter(
    clause_converter: Converter[genericquery.Clause, QueryApplier],
    table_settings: TableSettings,
)

Bases: QueryConverter[genericquery.Search]

Converts a Search into a SELECT over a table.

The filters are applied, then the sort, then the paging.

Parameters:

def convert(item: genericquery.Search) -> ParameterisedQuery
class SortClauseConverter(
    function_converter: Converter[genericquery.Function, QueryApplier],
)

Bases: ClauseConverter[genericquery.SortClause]

Converts a SortClause into an applier that sorts the query.

Any functions among the sort fields are added to the select list first.

Parameters:

def convert(item: genericquery.SortClause) -> QueryApplier
class TypeRegistryClauseConverter(
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: TypeRegistryConverter[genericquery.Clause, QueryApplier]

Converts clauses using the converter registered for their type.

def register[C: genericquery.Clause](
    item_type: type[C],
    converter: Converter[C, QueryApplier],
) -> Self
class TypeRegistryQueryConverter(
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: TypeRegistryConverter[genericquery.Query, ParameterisedQuery]

Converts queries using the converter registered for their type.

def register[Q: genericquery.Query](
    item_type: type[Q],
    converter: Converter[Q, ParameterisedQuery],
) -> Self