Skip to content
19 changes: 14 additions & 5 deletions datasette/views/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1575,7 +1575,11 @@ async def count(self, request):
self.ds, request, resolved.db.name, resolved.table
)
_next = request.args.get("_next")
if request.args.get("_count") == "before" and _next:
if (
request.args.get("_count") == "before"
and _next is not None
and not (resolved.is_view and _next == "")
):
return await self.count_before(
request, resolved, _next, where_clauses, params
)
Expand Down Expand Up @@ -2294,7 +2298,7 @@ def _next_where_clauses(_next, sort, sort_desc, pks, use_rowid, params):
def _page_position(datasette, request, is_view, sort, sort_desc, pks, use_rowid):
"""Context for the "you are not on the first page" strip, or None on page 1."""
_next = request.args.get("_next")
if not _next:
if _next is None or (is_view and _next == ""):
return None
route_path = request.scope.get("route_path")
position = {
Expand Down Expand Up @@ -2475,10 +2479,15 @@ async def table_view_data(
count_sql = f"select count(*) {from_sql}"

# Handle pagination driven by ?_next=
_next = _next or request.args.get("_next")
_next = _next if _next is not None else request.args.get("_next")

# A view paginates by integer offset, so the first page arrives as an empty
# ?_next=; a table's empty _next is a real cursor for an empty primary key.
if is_view and _next == "":
_next = None

offset = ""
if _next:
if _next is not None:
if is_view:
# _next is an offset
offset = f" offset {int(_next)}"
Expand Down Expand Up @@ -2694,7 +2703,7 @@ async def table_view_data(

data = {
"ok": True,
"next": next_value and str(next_value) or None,
"next": None if next_value is None else str(next_value),
"next_url": next_url,
}
data.update(
Expand Down
65 changes: 65 additions & 0 deletions tests/test_table_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,71 @@ async def test_page_size_zero(ds_client):
assert None is response.json()["next_url"]


async def test_paginate_table_with_empty_string_primary_key():
# path_from_row_pks() returns "" for a row whose only primary key
# value is the empty string, and "" is a legitimate _next= cursor.
# The "next" key and the _next= handling both used a truthiness
# check, so the token was dropped and pagination never advanced.
ds = Datasette(memory=True)
db = ds.add_memory_database("empty_pk")
await db.execute_write("CREATE TABLE t (id TEXT PRIMARY KEY)")
await db.execute_write_many(
"INSERT INTO t (id) VALUES (?)",
[("a",), ("",), ("c",), ("d",), ("e",)],
)
await ds.invoke_startup()

fetched = []
path = "/empty_pk/t.json?_size=1"
page = 0
while path:
page += 1
response = await ds.client.get(path)
assert response.status_code == 200
data = response.json()
fetched.extend(row["id"] for row in data["rows"])
if data["next_url"]:
# next_url and next agree, per docs/json_api.rst
assert urllib.parse.urlencode({"_next": data["next"]}) in data["next_url"]
path = data["next_url"]
if path:
path = path.replace("http://localhost", "")
assert page < 30, "Possible infinite loop detected"

# Every row exactly once
assert 5 == len(fetched)
assert ["", "a", "c", "d", "e"] == sorted(fetched)
assert 5 == page
# And the final page has both keys null, as documented
last = (await ds.client.get("/empty_pk/t.json?_size=100")).json()
assert None is last["next"]
assert None is last["next_url"]


async def test_view_ignores_an_empty_next_cursor():
# Views paginate by integer offset, not by a keyset cursor, so the
# first page arrives as ?_next= (empty). Feeding that to int() raises
# ValueError and returns 500; an empty cursor must mean "first page".
ds = Datasette(memory=True)
db = ds.add_memory_database("view_db")
await db.execute_write("CREATE TABLE items (id TEXT PRIMARY KEY)")
await db.execute_write_many(
"INSERT INTO items (id) VALUES (?)",
[("a",), ("b",), ("c",)],
)
await db.execute_write("CREATE VIEW v AS SELECT id FROM items")
await ds.invoke_startup()

response = await ds.client.get("/view_db/v.json?_size=1&_sort=id&_next=")
assert response.status_code == 200
assert [row["id"] for row in response.json()["rows"]] == ["a"]

response = await ds.client.get("/view_db/v.json?_size=1&_sort=id&_next=1")
assert response.status_code == 200
assert [row["id"] for row in response.json()["rows"]] == ["b"]


@pytest.mark.asyncio
async def test_paginate_compound_keys(ds_client):
fetched = []
path = "/fixtures/compound_three_primary_keys.json?_shape=objects"
Expand Down
30 changes: 30 additions & 0 deletions tests/test_table_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,33 @@ def test_count_before_uses_primary_key_index(pks, use_rowid, next_value):
)
)
assert plan.startswith("SEARCH"), plan


@pytest.mark.asyncio
async def test_empty_primary_key_cursor_position(tmp_path):
ds = Datasette([tmp_path / "empty.db"])
try:
await ds.get_database().execute_write_script("""
create table items (id text primary key);
insert into items values (''), ('a'), ('b');
create view items_view as select id from items;
""")
response = await ds.client.get("/empty/items?_size=1&_next=")
soup = BeautifulSoup(response.text, "html.parser")
assert "Back to first page" in soup.get_text()
response = await ds.client.post("/empty/items/-/count?_next=&_count=before")
assert response.status_code == 200
assert response.json()["count"] == 1
response = await ds.client.get("/empty/items_view?_size=1&_next=")
assert response.status_code == 200
assert (
"Back to first page"
not in BeautifulSoup(response.text, "html.parser").get_text()
)
response = await ds.client.post(
"/empty/items_view/-/count?_next=&_count=before"
)
assert response.status_code == 200
assert response.json()["count"] == 3
finally:
ds.close()
Loading