Cursor Pagination#
Keyset pagination filters, ordering keys, and the token codec hook. See
Filtering and Pagination for usage and Schema Conversion & Pagination for the
CursorPagination response container.
Filter#
- class advanced_alchemy.filters.CursorFilter(
- keys,
- limit,
- cursor=None,
- secret=None,
- *,
- ttl=None,
- encrypted=False,
Bases:
PaginationFilterKeyset (cursor) pagination.
Pages by comparing the ordering keys of the last row a client saw instead of skipping rows with
OFFSET, so deep pages cost the same as the first and concurrent inserts do not shift later pages. The model’s primary key is appended as the final key, in the direction of the last declared key, so every row has a unique position.The filter owns ordering and limits: it replaces any
ORDER BY,LIMIT, andOFFSETon the statement and fetcheslimit + 1rows to learn whether another page exists. Build the response withto_schema(..., pagination_type="cursor")orbuild_page(), which drop the extra row.- Parameters:
keys (tuple[CursorKey, ...]) – Ordering keys; see
CursorKeys. An empty sequence pages by primary key.limit (int) – Page size.
cursor (str | None) – Token from a previous page, or
Nonefor the first page.secret (str | bytes | None) – Key used to sign tokens, or to encrypt them when
encryptedis set.ttl (float | timedelta | None) – Token lifetime in seconds or as a
timedelta.encrypted (bool) – Encrypt tokens so clients cannot read the key values.
- Raises:
ValueError – The keys, limit, secret, or ttl are invalid.
InvalidCursorError –
cursoris malformed, tampered with, expired, or issued for a different ordering.
- limit: int#
Page size.
- cursor: str | None#
Token this page continues from.
- ttl: float | timedelta | None#
Lifetime of issued tokens.
- encrypted: bool#
Whether issued tokens are encrypted.
- property backward: bool#
Whether this page is fetched backward from
cursor.
- build_page(rows, *, model=None)#
Drop the extra row, restore declared order, and mint adjacent-page tokens.
- Parameters:
rows (Sequence[Any]) – Rows returned by the statement this filter was applied to.
model (Any | None) – Mapped model the rows belong to. Defaults to the model the filter was last applied with.
- Returns:
The page with
next_cursorandprevious_cursorset when such pages exist.- Raises:
ImproperConfigurationError – No model is known or a row lacks an ordering key.
- Return type:
CursorPagination[Any]
Ordering Keys#
- class advanced_alchemy.filters.CursorKey(field_name, sort_order='asc', nulls=None)#
Bases:
objectOne ordering key for
CursorFilter.- Parameters:
field_name (Any) – Mapped column attribute name or instrumented attribute.
sort_order ('asc' | 'desc') – Ascending or descending traversal.
nulls ('first' | 'last' | None) – Where NULLs sort. Nullable columns left as
Nonesort NULLs last.
- Raises:
ValueError – The name, direction, or NULL placement is invalid.
- property name: str#
Attribute name used in tokens and fingerprints.
- advanced_alchemy.filters.CursorKeys#
- advanced_alchemy.filters.normalize_cursor_keys(keys)#
Normalize cursor ordering keys.
- Parameters:
keys (str | InstrumentedAttribute[Any] | CursorKey | Sequence[str | InstrumentedAttribute[Any] | CursorKey | tuple[FilterFieldName, _SortOrder]]) – A name, attribute,
CursorKey, or a sequence of names, attributes,(name, direction)pairs, andCursorKeyobjects.- Returns:
Cursor keys in declared order.
- Raises:
TypeError – A key has an unsupported type.
ValueError – A key is invalid or declared twice.
- Return type:
tuple[CursorKey, …]
Token Codec#
- advanced_alchemy.filters.register_cursor_type(value_type, tag, encoder, decoder)#
Teach the cursor codec a sort-key value type.
Call once at application start-up, before any cursor is issued.
- Parameters:
value_type (type) – Python type to encode.
tag (str) – Unique lowercase wire tag, up to 16 characters.
encoder (Callable[[Any], str]) – Converts a value to text.
decoder (Callable[[str], Any]) – Restores a value from text.
- Raises:
ValueError – The type or tag is already registered, reserved, or invalid.
Framework Settings#
Options the Litestar and FastAPI filter dependencies resolve for each request. See Cursor Pagination for how the secret is configured.
- class advanced_alchemy.utils.dependencies.CursorSettings(
- allowed_fields,
- default_field,
- default_order,
- nulls,
- secret,
- ttl,
- encrypted,
Bases:
objectCursor pagination settings resolved from
FilterConfigonce, when dependencies are built.- token_options(defaults=None, *, require_secret=False)[source]#
Resolve the secret, lifetime, and encryption flag for issued and accepted tokens.
Each option comes from the filter configuration, then
defaults. The secret then falls back to theCURSOR_SECRET_ENV_VARSenvironment variables. Tokens are keyed with a value derived from the secret, so the secret itself never signs a token.- Parameters:
defaults (CursorDefaults | None) – Application-wide options.
require_secret (bool) – Refuse to issue or accept unsigned tokens.
- Returns:
The token key, lifetime, and encryption flag.
- Raises:
ImproperConfigurationError – No secret is configured and one is required or encryption is enabled.
- Return type:
tuple[bytes | None, float | timedelta | None, bool]
- build(
- *,
- cursor,
- page_size,
- order_by=None,
- sort_order=None,
- defaults=None,
- require_secret=False,
Build the cursor filter for one request.
- Parameters:
cursor (str | None) – Token from the request, or
Nonefor the first page.page_size (int) – Validated page size.
order_by (str | Sequence[str] | None) – Requested ordering tokens;
-namesorts descending.sort_order ('asc' | 'desc' | None) – Direction for a single unprefixed
order_bytoken.defaults (CursorDefaults | None) – Application-wide token options.
require_secret (bool) – Refuse to issue or accept unsigned tokens.
- Returns:
The request’s cursor filter.
- Raises:
ValueError – The ordering is not allowed or the token is invalid (
InvalidCursorError).ImproperConfigurationError – A secret is required and none is configured.
- Return type:
- advanced_alchemy.utils.dependencies.resolve_cursor_settings(config, model=None)[source]#
Validate cursor options in
configand resolve them for per-request use.- Parameters:
config (FilterConfig) – Filter configuration with
pagination_type="cursor".model (type[Any] | None) – Mapped model, used to validate
sort_fieldswhen known.
- Returns:
Resolved settings.
- Raises:
ImproperConfigurationError – A sort path crosses a relationship, or the secret or TTL is invalid.
- Return type:
- class advanced_alchemy.utils.dependencies.CursorDefaults(secret=None, ttl=None, encrypted=None)[source]#
Bases:
objectApplication-wide cursor token options, used where a filter configuration sets none.
- advanced_alchemy.utils.dependencies.resolve_cursor_defaults(configs)[source]#
Resolve application-wide cursor token options from an application’s SQLAlchemy configurations.
- Parameters:
configs (Iterable[Any]) – Configurations carrying
pagination_cursor_secret,pagination_cursor_ttl, andpagination_cursor_encrypted.- Returns:
The options the configurations set.
- Raises:
ImproperConfigurationError – A secret is empty, a TTL is not a positive finite duration, or two configurations set different values for one option.
- Return type:
- advanced_alchemy.utils.dependencies.CURSOR_SECRET_ENV_VARS: Final = ('ADVANCED_ALCHEMY_PAGINATION_CURSOR_SECRET', 'SECRET_KEY')#
Environment variables read, in order, for a cursor secret no configuration provides.