PaginationCursor

class safir.database.PaginationCursor(previous)

Bases: Generic[E]

Generic pagnination cursor for keyset pagination.

The generic type parameter is the Pydantic model into which each row will be converted, not the ORM model.

Parameters:

previous (bool)

Methods Summary

apply_cursor(stmt)

Apply the restrictions from the cursor to a select statement.

apply_order(stmt, *[, reverse])

Apply the sort order of the cursor to a select statement.

from_entry(entry, *[, reverse])

Construct a cursor with an entry as a bound.

from_str(cursor)

Build cursor from the string serialization form.

invert()

Return the inverted cursor (going the opposite direction).

Methods Documentation

abstract apply_cursor(stmt)

Apply the restrictions from the cursor to a select statement.

Forward cursors (the default) must include the entry the cursor was based on. Reverse cursors must exclude that entry and return data beginning with the entry immediately previous.

Parameters:

stmt (Select) – Select statement to modify.

Returns:

Modified select statement.

Return type:

sqlalchemy.sql.expression.Select

abstract classmethod apply_order(stmt, *, reverse=False)

Apply the sort order of the cursor to a select statement.

This is independent of the cursor and only needs to know the underlying ORM fields, so it is available as a class method on the cursor class, allowing it to be used without a cursor (such as for the initial query). This does, however, mean that the caller has to explicitly say whether to reverse the order, which is required when using a previous cursor.

Parameters:
  • stmt (Select) – SQL select statement.

  • reverse (bool, default: False) – Whether to reverse the sort order.

Returns:

The same select statement but sorted in the order expected by the cursor.

Return type:

sqlalchemy.sql.expression.Select

abstract classmethod from_entry(entry, *, reverse=False)

Construct a cursor with an entry as a bound.

Builds a cursor to get the entries after the provided entry, or before the provided entry if reverse is set to True. When the cursor is later applied with apply_cursor, forward cursors (the default) must include the entry the cursor was based on. Reverse cursors must exclude the given entry and return data starting with the entry immediately previous.

Parameters:
  • entry (TypeVar(E, bound= BaseModel)) – Basis of the cursor.

  • reverse (bool, default: False) – Whether to create a previous cursor.

Returns:

Requested cursor.

Return type:

PaginationCursor

abstract classmethod from_str(cursor)

Build cursor from the string serialization form.

Parameters:

cursor (str) – Serialized form of the cursor.

Returns:

The cursor represented as an object.

Return type:

PaginationCursor

Raises:

ValueError – Raised if the cursor is invalid.

abstract invert()

Return the inverted cursor (going the opposite direction).

Parameters:

cursor – Cursor to invert.

Returns:

The inverted cursor.

Return type:

PaginationCursor