cuckcoding.pro
Menu

Paginate a SQLite feed with a stable two-column cursor

You finish the first page of a feed, someone publishes a post, and the first item on page two looks suspiciously familiar. A page number counts positions in a moving list. For a feed ordered newest first, carry forward the values of the last row the reader actually saw.

Before you start
Python 3 with sqlite3 backed by SQLite 3.15 or newer. Use one empty directory.
What to verify
Walk through the original five posts exactly once despite tied dates and a newer insert between pages.

Build a feed with deliberate ties

Save fixture.py. Posts 3 and 4 share a day, as do 1 and 2. The exercise stores dates in one fixed-width ISO format, so ordering these strings also orders these dates. Each ID is unique. The index follows the same two columns as the listing.

fixture.py
def prepare(db):
    db.execute("CREATE TABLE posts (id INTEGER PRIMARY KEY, day TEXT NOT NULL)")
    db.executemany("INSERT INTO posts VALUES (?, ?)", [
        (1, "2026-03-10"), (2, "2026-03-10"),
        (3, "2026-03-11"), (4, "2026-03-11"), (5, "2026-03-12"),
    ])
    db.execute("CREATE INDEX by_day_id ON posts(day DESC, id DESC)")

Using a different day for every post hides the bug in a date-only cursor. Keep at least one pair with the same day across a page boundary.

Return the sorting values with each row

Save feed.py. Order by day and ID, both descending. The first page needs no filter. For the following page, take the final pair from the previous result and request smaller pairs. SQLite compares the day first, then uses the ID when the days match.

feed.py
def page(db, cursor=None):
    if cursor is None:
        return db.execute(
            "SELECT day, id FROM posts ORDER BY day DESC, id DESC LIMIT 2"
        ).fetchall()
    return db.execute(
        "SELECT day, id FROM posts WHERE (day, id) < (?, ?) "
        "ORDER BY day DESC, id DESC LIMIT 2", cursor
    ).fetchall()

The SELECT returns day followed by ID. Keep exactly that order when binding the cursor. The strict comparison excludes the last row already displayed.

Insert a post while the reader is between pages

Save the checker. It reads the first two rows, then inserts tomorrow’s post. OFFSET 2 now starts at ID 4, which was already displayed. The cursor advances from the old boundary instead. Compare both outputs against the original sequence so a skipped item is caught too.

check_feed.py
import sqlite3
from feed import page
from fixture import prepare

with sqlite3.connect(":memory:") as db:
    prepare(db)
    first = page(db)
    db.execute("INSERT INTO posts VALUES (?, ?)", (6, "2026-03-13"))
    shifted = db.execute(
        "SELECT id FROM posts ORDER BY day DESC, id DESC LIMIT 2 OFFSET 2"
    ).fetchall()
    second = page(db, first[-1])
    third = page(db, second[-1])
    assert shifted == [(4,), (3,)]
    assert [i for _, i in first + second + third] == [5, 4, 3, 2, 1]
    assert page(db, third[-1]) == []
    assert page(db)[0][1] == 6
    print(first, second, third, sep="\n")

The final empty page matters. It tells the client to stop requesting more. Starting a fresh walk deliberately shows the newly added post.

Use the failing variant to review the AI’s SQL

Run the checker. It prints pages with IDs 5 and 4, then 3 and 2, then 1. Temporarily replace the next-page filter with just day < ? and bind only the day. Now the second post from March 11 falls through the gap and the checker fails. Restore the two-part cursor.

Terminal
python3 check_feed.py

This design assumes a stable ordering key. If existing records can change publication day, decide separately whether readers need a snapshot of the original list.

Try this prompt with your agent

Prompt
Design the next-page query for this feed. Include a tie at the page boundary and a newer insert between two reads. Show the complete walk including the empty page, and explain what happens if a previously displayed record changes day.

A trap worth catching

Sorting by both columns while storing only the date still loses rows. The cursor must remember every ordering value needed to identify its boundary, including the unique tie-breaker.

Official documentation