Keyset Pagination Cursor
Paginate ordered rows by a keyset cursor instead of offset, keeping page cost stable as data grows.
Code
from dataclasses import dataclass
import base64
import json
from typing import Optional
@dataclass(frozen=True)
class Cursor:
created_at: str
row_id: int
def encode(cursor: Optional[Cursor]) -> Optional[str]:
if cursor is None:
return None
raw = json.dumps({'c': cursor.created_at, 'i': cursor.row_id}).encode('utf-8')
return base64.urlsafe_b64encode(raw).decode('ascii')
def decode(token: Optional[str]) -> Optional[Cursor]:
if not token:
return None
try:
data = json.loads(base64.urlsafe_b64decode(token.encode('ascii')))
return Cursor(created_at=str(data['c']), row_id=int(data['i']))
except (ValueError, KeyError, TypeError):
raise ValueError('invalid pagination cursor')
def fetch_page(conn, cursor: Optional[Cursor], limit: int = 20):
if cursor is None:
rows = conn.execute(
'SELECT id, created_at FROM items ORDER BY created_at, id LIMIT ?', (limit + 1,)).fetchall()
else:
rows = conn.execute(
'SELECT id, created_at FROM items WHERE (created_at, id) > (?, ?) '
'ORDER BY created_at, id LIMIT ?', (cursor.created_at, cursor.row_id, limit + 1)).fetchall()
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = Cursor(page[-1][1], page[-1][0]) if has_more and page else None
return page, encode(next_cursor)Inside the snippet
Everything happens inside the classes import and Cursor and the functions encode, decode and fetch_page.
Reach for base64 and what you get is dataclass, Optional — that is the whole API contact area. ValueError appears at a raise inside an except handler — it fires only while that failure type is already being handled.
Points of care
- External dependency:
base64— install it before running the snippet.
Putting it to use
The main signature reads def encode(cursor: Optional[Cursor]) -> Optional[str]
encode is the public entry point; everything else in the file exists to support it.
Core lines
def encode(cursor: Optional[Cursor]) -> Optional[str]:
if cursor is None:
return None
raw = json.dumps({'c': cursor.created_at, 'i': cursor.row_id}).encode('utf-8')
return base64.urlsafe_b64encode(raw).decode('ascii')
except (ValueError, KeyError, TypeError):
raise ValueError('invalid pagination cursor')
if cursor is None:
rows = conn.execute(
'SELECT id, created_at FROM items ORDER BY created_at, id LIMIT ?', (limit + 1,)).fetchall()
Interactive Tools for This Topic
DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- When is the exception raised?
- Inside an `except` handler — the `ValueError` fires only while that failure type is already being handled, not on its own trigger.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `dataclasses`, `base64`, `json`. The file defines `encode`, `decode`, `fetch_page` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.