Skip to content

Fall back to rowid when paginating a sort prefix - #2975

Merged
simonw merged 2 commits into
simonw:mainfrom
feiiiiii5:fix/rowid-sort-prefix-fallback
Nov 8, 2026
Merged

simonw merged 2 commits into
simonw:mainfrom
feiiiiii5:fix/rowid-sort-prefix-fallback

Conversation

@feiiiiii5

Copy link
Copy Markdown
Contributor

Fixes #2974.

Sorting a table that has no explicit primary key, by a column excluded from the SELECT with ?_col= or ?_nocol=, returns a 500.

_next_value_and_url() has a fallback that re-reads the sort-column value by primary key when that column is not in the SELECT — added so ?_sort= / ?_sort_desc= work together with ?_col= / ?_nocol= (#1773). For a table with no primary key, pks is [], so the WHERE clause is built from an empty list:

select b from items where

which SQLite rejects with sqlite3.OperationalError: incomplete input.

sqlite3.OperationalError: incomplete input
  rowid, sort col excluded       -> HTTP 500
  rowid, other col excluded      -> HTTP 500
  rowid, sort desc excluded      -> HTTP 500
  rowid, no exclusion (control)  -> ok first_page=c01..c10 next='b10,10'

The rest of the function already treats rowid as the key for such tables — path_from_row_pks(rows[-2], pks, use_rowid), and the use_rowid handling a few lines above. The fallback was the only place still assuming a declared primary key, so the fix is to use the same key there:

            except IndexError:
                # sort/sort_desc column missing from SELECT - look up value by PK instead
                # Tables with no primary key paginate on rowid
                lookup_pks = pks or ["rowid"]

used in both the WHERE clause and the bound parameters.

The next value is the same, not just non-crashing

That is the part worth checking, because a fallback that merely stops raising could still paginate to the wrong place. With the fix, all three excluded-column cases produce byte-identical next tokens to the control that does not exclude anything — 'b10,10' for ascending and 'b16,16' for descending:

  rowid, sort col excluded       -> ok first_page=c01..c10 next='b10,10'
  rowid, other col excluded      -> ok first_page=c01..c10 next='b10,10'
  rowid, sort desc excluded      -> ok first_page=c25..c16 next='b16,16'
  rowid, no exclusion (control)  -> ok first_page=c01..c10 next='b10,10'

The new test walks the whole next_url chain rather than checking one page, and asserts the exact order with no skipped or repeated rows, so a cursor that is merely valid but points somewhere else would still fail. Tables with a primary key are untouched, and a literal $null sort value still round-trips.

Scope

I kept this separate from #2600 even though both sit in the same except IndexError clause. #2600 is a different defect: CustomRow (used with _labels=on) raises KeyError where sqlite3.Row raises IndexError, so that path never reaches this handler at all. Catching KeyError as well would not fix this — here the handler does run and then builds the broken SQL. Happy to combine them if you would rather have one PR.

Checks

gate result
pytest 2709 passed, 107 skipped, 6 xfailed, 15 xpassed, 143 subtests vs 2706 / 107 / 6 / 15 / 143 on cec5e6b2 — +3 new parametrizations, nothing else moved
ruff check clean on both files

The baseline's 15 xpassed are pre-existing, not something this change introduced.

Not run: blacken-docs, codespell and sphinx (not installed here, and no .rst changed), prettier (no JavaScript changed), and the Playwright browser tests (out of scope). No cog block is affected — grep -c cog on both changed files finds nothing but the substring inside "unrecognized token", which is pre-existing — so uv run cog -r docs/*.rst is not needed.

History note: git log -S and git blame on this file need network for the partial clone and time out, so I established the origin with git log --oneline -2000 plus git show df4fd2d7 ("_sort= works even if sort column not selected, closes #1773"), which added the fallback and a test only against sortable — a table that has a primary key.

_next_value_and_url() re-reads the sort column by primary key when that
column is not in the SELECT. For a table with no primary key `pks` is
`[]`, so the WHERE clause came out empty and the lookup SQL was
`select b from items where ` — sqlite3.OperationalError: incomplete
input, and a 500.

Such tables paginate on rowid, which path_from_row_pks() and the
use_rowid handling above already use. Use the same key in the fallback,
so the next value is identical to the one the non-fallback path
produces.

Fixes simonw#2974
@feiiiiii5
feiiiiii5 force-pushed the fix/rowid-sort-prefix-fallback branch from 82faf07 to 0ac8f60 Compare October 8, 2026 06:35
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Hi @simonw — CI has been green here since 09-29 and nothing has changed since, so this is ready for a look whenever you get a chance.

One question that would settle the shape of it: for a table with no explicit primary key sorted by a column excluded with ?_col=/?_nocol=, should pagination fall back to rowid the way this does, or would you rather the request fail with a 400 because the sort column is not in the SELECT? I chose the fallback so existing ?_sort links keep working, and it follows the fallback _next_value_and_url() already has for tables that do have a primary key (#1773). The other option is the smaller change if you consider that combination unsupported.

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Status is unchanged since 09-29 and CI is green. The open question is whether a table with no primary key should fall back to rowid here or return a 400 when the sort column is excluded from the SELECT; I chose rowid so existing ?_sort links keep working. If you would rather reject that combination, I can narrow this to the primary-key case.

@Muguett-DBY Muguett-DBY left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also checked repeated sort values and NULLs across page boundaries. With 25 rows and _size=4, both ascending and descending _sort=b&_nocol=b traversed all 25 distinct row identifiers in the same order as the corresponding query with b included. The base returned 500 for both excluded-column requests.

This exercised the exact base and PR versions of _next_value_and_url through HTTP using an in-memory SQLite database, with the rest of Datasette from b4c280c on Windows/Python 3.12. I did not build or run the full suite at this PR head.

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Thanks for the independent check on repeated sort values and NULLs, and for confirming the base 500 on both excluded-column requests — that matches what the PR is meant to fix.

One note from the sibling PR #2968: after its latest commit, an empty _next= on a view means the first page, not a keyset cursor.

@simonw simonw added the bug label Nov 8, 2026
@simonw

simonw commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Reproduced on https://latest.datasette.io/ using roadside_attraction_characteristics, which has no primary key. _size=2 ensures there is a next page:

Table HTML pages, and JSON with ?_labels=on, expand foreign key labels,
which turns each row into a CustomRow. A CustomRow raises KeyError
rather than IndexError for a missing column, so the rowid fallback never
ran and those pages still returned a 500.

Refs simonw#2974, simonw#2600

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simonw simonw closed this Nov 8, 2026
@simonw simonw reopened this Nov 8, 2026
@simonw
simonw merged commit eead867 into simonw:main Nov 8, 2026
12 of 13 checks passed
@codecov

codecov Bot commented Nov 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 0.00%. Comparing base (cec5e6b) to head (94b0e19).
⚠️ Report is 107 commits behind head on main.

Files with missing lines Patch % Lines
datasette/views/table.py 0.00% 4 Missing ⚠️
Additional details and impacted files
@@          Coverage Diff           @@
##            main   #2975    +/-   ##
======================================
  Coverage   0.00%   0.00%            
======================================
  Files         78      78            
  Lines      13392   13662   +270     
======================================
- Misses     13392   13662   +270     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@simonw

simonw commented Nov 9, 2026

Copy link
Copy Markdown
Owner

These example links now all work, since the fix has been deployed to https://latest.datasette.io/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

500 error when sorting a table with no primary key by a column excluded from the SELECT 500 error if sorted by a column not in the ?_col= list

3 participants