filters¶
SQLAlchemy filter constructs for advanced query operations.
This module provides a comprehensive collection of filter datastructures designed to enhance SQLAlchemy query construction. It implements type-safe, reusable filter patterns for common database query operations.
- Features:
Type-safe filter construction, datetime range filtering, collection-based filtering, pagination support, search operations, and customizable ordering.
Note
All filter classes implement the StatementFilter
ABC, ensuring consistent
interface across different filter types.
See also
sqlalchemy.sql.expression.Select
: Core SQLAlchemy select expressionsqlalchemy.orm.Query
: SQLAlchemy ORM query interfaceadvanced_alchemy.base
: Base model definitions
- class advanced_alchemy.filters.BeforeAfter[source]¶
Bases:
StatementFilter
DateTime range filter with exclusive bounds.
This filter creates date/time range conditions using < and > operators, excluding the boundary values.
If either before or after is None, that boundary condition is not applied.
See Also:¶
OnBeforeAfter
: Inclusive datetime range filtering- append_to_statement(statement, model)[source]¶
Apply datetime range conditions to statement.
- __init__(field_name, before, after)¶
- class advanced_alchemy.filters.CollectionFilter[source]¶
Bases:
InAnyFilter
,Generic
[T
]Data required to construct a WHERE … IN (…) clause.
This filter restricts records based on a field’s presence in a collection of values.
The filter supports both
IN
andANY
operators for collection membership testing. Useprefer_any=True
inappend_to_statement
to use theANY
operator.-
values:
Optional
[Collection
[TypeVar
(T
)]]¶ Values for the
IN
clause. If this is None, no filter is applied. An empty list will force an empty result set (WHERE 1=-1)
- append_to_statement(statement, model, prefer_any=False)[source]¶
Apply a WHERE … IN or WHERE … ANY (…) clause to the statement.
- Parameters:
- Return type:
TypeVar
(StatementTypeT
, bound=Union
[ReturningDelete
,ReturningUpdate
,Select
,Update
,Delete
])
- __init__(field_name, values)¶
-
values:
- class advanced_alchemy.filters.ComparisonFilter[source]¶
Bases:
StatementFilter
Simple comparison filter for equality and inequality operations.
This filter applies basic comparison operators (=, !=, >, >=, <, <=) to a field. It provides a generic way to perform common comparison operations.
- append_to_statement(statement, model)[source]¶
Apply a comparison operation to the statement.
- Parameters:
- Returns:
Modified statement with the comparison condition
- Return type:
- __init__(field_name, operator, value)¶
- class advanced_alchemy.filters.ExistsFilter[source]¶
Bases:
StatementFilter
Filter for EXISTS subqueries.
This filter creates an EXISTS condition using a list of column expressions. The expressions can be combined using either AND or OR logic. The filter applies a correlated subquery that returns only the rows from the main query that match the specified conditions.
For example, if searching movies with Movie.genre == “Action”, only rows where the genre is “Action” will be returned.
- Parameters:
values¶ (list[ColumnElement[bool]]) – values: List of SQLAlchemy column expressions to use in the EXISTS clause
operator¶ (Literal["and", "or"], optional) – operator: If “and”, combines conditions with AND, otherwise uses OR. Defaults to “and”.
Example¶
--------¶ –
Basic usage with AND conditions:
from sqlalchemy import select from advanced_alchemy.filters import ExistsFilter filter = ExistsFilter( values=[User.email.like("%@example.com%")], ) statement = filter.append_to_statement( select(Organization), Organization )
This will return only organizations where the user’s email contains “@example.com”.
Using OR conditions:
filter = ExistsFilter( values=[User.role == "admin", User.role == "owner"], operator="or", )
This will return organizations where the user’s role is either “admin” OR “owner”.
Also¶ (See)
--------¶ –
NotExistsFilter
: The inverse of this filtersqlalchemy.sql.expression.exists()
: SQLAlchemy EXISTS expression
-
values:
list
[ColumnElement
[bool
]]¶ List of SQLAlchemy column expressions to use in the EXISTS clause.
-
operator:
Literal
['and'
,'or'
] = 'and'¶ If “and”, combines conditions with the AND operator, otherwise uses OR.
- __init__(values, operator='and')¶
- append_to_statement(statement, model)[source]¶
Append EXISTS condition to the statement.
- Parameters:
statement¶ (
TypeVar
(StatementTypeT
, bound=Union
[ReturningDelete
,ReturningUpdate
,Select
,Update
,Delete
])) – StatementTypeT The SQLAlchemy statement to modifymodel¶ (
type
[TypeVar
(ModelT
, bound=ModelProtocol
)]) – type[ModelT]class (The _sphinx_paramlinks_advanced_alchemy.filters.ExistsFilter.append_to_statement.SQLAlchemy model)
- Returns:
Modified statement with EXISTS condition
- Return type:
- class advanced_alchemy.filters.FilterGroup[source]¶
Bases:
StatementFilter
A group of filters combined with a logical operator.
This class combines multiple filters with a logical operator (AND/OR). It provides a way to create complex nested filter conditions.
- __init__(logical_operator, filters)¶
-
logical_operator:
Callable
[...
,ColumnElement
[bool
]]¶ Logical operator to combine the filters.
-
filters:
list
[StatementFilter
]¶ List of filters to combine.
- class advanced_alchemy.filters.FilterMap[source]¶
Bases:
TypedDict
- before_after: type[BeforeAfter]¶
- on_before_after: type[OnBeforeAfter]¶
- collection: type[CollectionFilter[Any]]¶
- not_in_collection: type[NotInCollectionFilter[Any]]¶
- limit_offset: type[LimitOffset]¶
- order_by: type[OrderBy]¶
- search: type[SearchFilter]¶
- not_in_search: type[NotInSearchFilter]¶
- comparison: type[ComparisonFilter]¶
- exists: type[ExistsFilter]¶
- not_exists: type[NotExistsFilter]¶
- filter_group: type[FilterGroup]¶
- advanced_alchemy.filters.FilterTypes: TypeAlias = 'Union[BeforeAfter, OnBeforeAfter, CollectionFilter[Any], LimitOffset, OrderBy, SearchFilter, NotInCollectionFilter[Any], NotInSearchFilter, ExistsFilter, NotExistsFilter, ComparisonFilter, MultiFilter, FilterGroup]'¶
Aggregate type alias of the types supported for collection filtering.
- class advanced_alchemy.filters.InAnyFilter[source]¶
Bases:
StatementFilter
,ABC
Base class for filters using IN or ANY operators.
This abstract class provides common functionality for filters that check membership in a collection using either the SQL IN operator or the ANY operator.
- class advanced_alchemy.filters.LimitOffset[source]¶
Bases:
PaginationFilter
Limit and offset pagination filter.
Implements traditional pagination using SQL LIMIT and OFFSET clauses. Only applies to SELECT statements; other statement types are returned unmodified.
Note
This filter only modifies SELECT statements. For other statement types (UPDATE, DELETE), the statement is returned unchanged.
See also
sqlalchemy.sql.expression.Select.limit()
: SQLAlchemy LIMIT clausesqlalchemy.sql.expression.Select.offset()
: SQLAlchemy OFFSET clause
- append_to_statement(statement, model)[source]¶
Apply LIMIT/OFFSET pagination to the statement.
- Parameters:
- Returns:
Modified statement with limit and offset applied
- Return type:
Note
Only modifies SELECT statements. Other statement types are returned as-is.
See also
sqlalchemy.sql.expression.Select
: SQLAlchemy SELECT statement
- __init__(limit, offset)¶
- class advanced_alchemy.filters.LogicalOperatorMap[source]¶
Bases:
TypedDict
-
and_:
Callable
[...
,ColumnElement
[bool
]]¶
-
or_:
Callable
[...
,ColumnElement
[bool
]]¶
-
and_:
- class advanced_alchemy.filters.MultiFilter[source]¶
Bases:
StatementFilter
Apply multiple filters to a query based on a JSON/dict input.
This filter provides a way to construct complex filter trees from a structured dictionary input, supporting nested logical groups and various filter types.
- __init__(filters)¶
- class advanced_alchemy.filters.NotExistsFilter[source]¶
Bases:
StatementFilter
Filter for NOT EXISTS subqueries.
This filter creates a NOT EXISTS condition using a list of column expressions. The expressions can be combined using either AND or OR logic. The filter applies a correlated subquery that returns only the rows from the main query that DO NOT match the specified conditions.
For example, if searching movies with Movie.genre == “Action”, only rows where the genre is NOT “Action” will be returned.
- Parameters:
values¶ (list[ColumnElement[bool]]) – values: List of SQLAlchemy column expressions to use in the NOT EXISTS clause
operator¶ (Literal["and", "or"], optional) – operator: If “and”, combines conditions with AND, otherwise uses OR. Defaults to “and”.
Example¶
--------¶ –
Basic usage with AND conditions:
from sqlalchemy import select from advanced_alchemy.filters import NotExistsFilter filter = NotExistsFilter( values=[User.email.like("%@example.com%")], ) statement = filter.append_to_statement( select(Organization), Organization )
This will return only organizations where the user’s email does NOT contain “@example.com”.
Using OR conditions:
filter = NotExistsFilter( values=[User.role == "admin", User.role == "owner"], operator="or", )
This will return organizations where the user’s role is NEITHER “admin” NOR “owner”.
Also¶ (See)
--------¶ –
ExistsFilter
: The inverse of this filtersqlalchemy.sql.expression.not_()
: SQLAlchemy NOT operatorsqlalchemy.sql.expression.exists()
: SQLAlchemy EXISTS expression
- __init__(values, operator='and')¶
-
values:
list
[ColumnElement
[bool
]]¶ List of SQLAlchemy column expressions to use in the NOT EXISTS clause.
-
operator:
Literal
['and'
,'or'
] = 'and'¶ If “and”, combines conditions with the AND operator, otherwise uses OR.
- class advanced_alchemy.filters.NotInCollectionFilter[source]¶
Bases:
InAnyFilter
,Generic
[T
]Data required to construct a WHERE … NOT IN (…) clause.
This filter restricts records based on a field’s absence in a collection of values.
The filter supports both
NOT IN
and!= ANY
operators for collection exclusion. Useprefer_any=True
inappend_to_statement
to use theANY
operator.- Parameters:
-
values:
Optional
[Collection
[TypeVar
(T
)]]¶ Values for the
NOT IN
clause. If None or empty, no filter is applied.
- append_to_statement(statement, model, prefer_any=False)[source]¶
Apply a WHERE … NOT IN or WHERE … != ANY(…) clause to the statement.
- Parameters:
- Return type:
TypeVar
(StatementTypeT
, bound=Union
[ReturningDelete
,ReturningUpdate
,Select
,Update
,Delete
])
- __init__(field_name, values)¶
- class advanced_alchemy.filters.NotInSearchFilter[source]¶
Bases:
SearchFilter
Filter for excluding records that match a substring.
Implements negative text search using SQL NOT LIKE or NOT ILIKE operators. Can exclude across multiple fields using AND conditions.
- Parameters:
Note
Uses AND for multiple fields, meaning records matching any field will be excluded.
See also
SearchFilter
: Opposite filter using LIKE/ILIKEsqlalchemy.sql.expression.ColumnOperators.notlike()
: NOT LIKE operatorsqlalchemy.sql.expression.ColumnOperators.notilike()
: NOT ILIKE operator
- __init__(field_name, value, ignore_case=False)¶
- class advanced_alchemy.filters.OnBeforeAfter[source]¶
Bases:
StatementFilter
DateTime range filter with inclusive bounds.
This filter creates date/time range conditions using <= and >= operators, including the boundary values.
If either on_or_before or on_or_after is None, that boundary condition is not applied.
See Also:¶
BeforeAfter
: Exclusive datetime range filtering- append_to_statement(statement, model)[source]¶
Apply inclusive datetime range conditions to statement.
- __init__(field_name, on_or_before, on_or_after)¶
- class advanced_alchemy.filters.OrderBy[source]¶
Bases:
StatementFilter
Order by a specific field.
Appends an ORDER BY clause to SELECT statements, sorting records by the specified field in ascending or descending order.
Note
This filter only modifies SELECT statements. For other statement types, the statement is returned unchanged.
See also
sqlalchemy.sql.expression.Select.order_by()
: SQLAlchemy ORDER BY clausesqlalchemy.sql.expression.ColumnElement.asc()
: Ascending ordersqlalchemy.sql.expression.ColumnElement.desc()
: Descending order
- append_to_statement(statement, model)[source]¶
Append an ORDER BY clause to the statement.
- Parameters:
- Returns:
Modified statement with an ORDER BY clause
- Return type:
Note
Only modifies SELECT statements. Other statement types are returned as-is.
See also
sqlalchemy.sql.expression.Select.order_by()
: SQLAlchemy ORDER BY
- __init__(field_name, sort_order='asc')¶
- class advanced_alchemy.filters.PaginationFilter[source]¶
Bases:
StatementFilter
,ABC
Abstract base class for pagination filters.
Subclasses should implement pagination logic, such as limit/offset or cursor-based pagination.
- class advanced_alchemy.filters.SearchFilter[source]¶
Bases:
StatementFilter
Case-sensitive or case-insensitive substring matching filter.
Implements text search using SQL LIKE or ILIKE operators. Can search across multiple fields using OR conditions.
Note
The search pattern automatically adds wildcards before and after the search value, equivalent to SQL pattern ‘%value%’.
See also
NotInSearchFilter
: Opposite filter using NOT LIKE/ILIKEsqlalchemy.sql.expression.ColumnOperators.like()
: Case-sensitive LIKEsqlalchemy.sql.expression.ColumnOperators.ilike()
: Case-insensitive LIKE
- get_search_clauses(model)[source]¶
Generate the LIKE/ILIKE clauses for all specified fields.
- Parameters:
model¶ (
type
[TypeVar
(ModelT
, bound=ModelProtocol
)]) – The SQLAlchemy model class- Returns:
List of text matching expressions
- Return type:
See also
sqlalchemy.sql.expression.BinaryExpression
: SQLAlchemy expression
- append_to_statement(statement, model)[source]¶
Append a LIKE/ILIKE clause to the statement.
- Parameters:
- Returns:
Modified statement with text search clauses
- Return type:
See also
sqlalchemy.sql.expression.Select.where()
: SQLAlchemy WHERE clause
- __init__(field_name, value, ignore_case=False)¶
- class advanced_alchemy.filters.StatementFilter[source]¶
Bases:
ABC
Abstract base class for SQLAlchemy statement filters.
This class defines the interface for all filter types in the system. Each filter implementation must provide a method to append its filtering logic to an existing SQLAlchemy statement.
- abstractmethod append_to_statement(statement, model, *args, **kwargs)[source]¶
Append filter conditions to a SQLAlchemy statement.
- Parameters:
- Returns:
Modified SQLAlchemy statement with filter conditions applied
- Return type:
- Raises:
NotImplementedError – If the concrete class doesn’t implement this method
Note
This method must be implemented by all concrete filter classes.
See also
sqlalchemy.sql.expression.Select.where()
: SQLAlchemy where clause