Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions datasette/views/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -2487,8 +2487,11 @@ async def table_view_data(
where_clauses.extend(
_next_where_clauses(_next, sort, sort_desc, pks, use_rowid, params)
)
if sort or sort_desc:
order_by = f"{order_by}, {order_by_pks}"

# The first page needs this tie-breaker too: the ?_next= cursor assumes that
# rows with the same sort value come back in primary key order
if (sort or sort_desc) and not is_view:
order_by = f"{order_by}, {order_by_pks}"

where_clause = ""
if where_clauses:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_table_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1667,6 +1667,42 @@ async def test_sort_excluded_column_rowid_table(query_string, expected_order):
assert [row["c"] for row in fetched] == [f"c{i:02d}" for i in expected_order]


@pytest.mark.asyncio
@pytest.mark.parametrize(
"create_table",
(
"create table items (id text primary key, status text)",
"create table items (id text, status text, primary key (id, status))",
),
)
@pytest.mark.parametrize("sort_arg", ("_sort", "_sort_desc"))
async def test_sort_ties_paginate_without_skips_or_repeats(create_table, sort_arg):
# Rows are inserted out of primary key order, so SQLite returns ties on the
# sort column in a different order unless the query breaks them by primary key
rows = [("z", "a"), ("m", "a"), ("c", "a"), ("q", "b"), ("a", "b"), ("y", "b")]
ds = Datasette(settings={"default_page_size": 2, "max_returned_rows": 1000})
db = ds.add_memory_database("sort_ties")
await db.execute_write(create_table)
await db.execute_write_many("insert into items (id, status) values (?, ?)", rows)
await ds.invoke_startup()

fetched = []
path = f"/sort_ties/items.json?_shape=objects&{sort_arg}=status"
for _ in range(100):
response = await ds.client.get(path)
assert response.status_code == 200, response.text
data = response.json()
fetched.extend(row["id"] for row in data["rows"])
path = data["next_url"]
if not path:
break
path = path.replace("http://localhost", "")
else:
assert False, "pagination did not terminate"

assert sorted(fetched) == sorted(row[0] for row in rows)


@pytest.mark.asyncio
@pytest.mark.parametrize(
"path",
Expand Down
Loading