From 3bc7e7517a56af2e266c1ae17f09d6dc25e84cc9 Mon Sep 17 00:00:00 2001 From: feiiiiii5 Date: Tue, 29 Sep 2026 00:42:01 +0800 Subject: [PATCH 1/4] Keep an empty-string keyset pagination cursor, closes #2967 path_from_row_pks() returns "" for a row whose only primary key value is the empty string, and "" is a legitimate _next= cursor. Both the site that emits the token and the site that reads it back tested it for truthiness, so the token was discarded. Emitting: "next": next_value and str(next_value) or None turns "" into None, while next_url is still built a few lines earlier and stays non-null. docs/json_api.rst:99 says both are null on the final page, so the response contradicted its own documentation. Reading back, "if _next:" then ignored the cursor and the query returned page 1 again, so a client following next_url looped on the first row forever. CREATE TABLE t (id TEXT PRIMARY KEY); INSERT INTO t (id) VALUES ('a'), (''), ('c'), ('d'), 'e'); /d/t.json?_size=1 rows [''] next=None next_url=...&_next= following it rows [''] next=None next_url=...&_next= None is the no-cursor sentinel: it is initialised to None at table.py:2508 and nothing assigns "" to it deliberately. The same function already asks this correctly at table.py:2536 ("if prefix is None: prefix = '\'"). A bare ?_next= with no value now means "rows after the empty primary key" rather than being ignored, which is the only coherent reading of an empty cursor. _next=a and _next=zzz are unchanged. No docs change: json_api.rst already describes the fixed behaviour. Test: tests/test_table_api.py::test_paginate_table_with_empty_string_primary_key walks the pages and fails on cec5e6b2 with assert '_next=None' in '...?_size=1&_next=' pytest -n auto -m 'not serial' 2782 passed, pytest -m serial 40 passed. black, ruff, cog --check and codespell clean. --- datasette/views/table.py | 6 +++--- tests/test_table_api.py | 43 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/datasette/views/table.py b/datasette/views/table.py index 0a908c69af..7d085bf857 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -2140,10 +2140,10 @@ 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") offset = "" - if _next: + if _next is not None: sort_value = None if is_view: # _next is an offset @@ -2397,7 +2397,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( diff --git a/tests/test_table_api.py b/tests/test_table_api.py index 58a5ddc3ed..483d42f172 100644 --- a/tests/test_table_api.py +++ b/tests/test_table_api.py @@ -366,6 +366,49 @@ async def test_page_size_zero(ds_client): assert None is response.json()["next_url"] +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. + with make_app_client( + memory=True, + extra_databases={ + "empty_pk": ( + "CREATE TABLE t (id TEXT PRIMARY KEY);" + "INSERT INTO t (id) VALUES ('a'), (''), ('c'), ('d'), ('e');" + ) + }, + ) as client: + fetched = [] + path = "/empty_pk/t.json?_size=1" + page = 0 + while path: + page += 1 + response = client.get(path) + assert response.status == 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 = client.get("/empty_pk/t.json?_size=100").json + assert None is last["next"] + assert None is last["next_url"] + + @pytest.mark.asyncio async def test_paginate_compound_keys(ds_client): fetched = [] From f7c7dac9a3a57e14f63f970c05db5bc3782caa90 Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:50:12 +0800 Subject: [PATCH 2/4] Views treat an empty _next as the first page, not int("") The empty-string cursor change made `if _next is not None` apply to views as well. Views paginate by integer offset, and their first page arrives as `?_next=`, so `int("")` raised ValueError and returned 500. An empty cursor now stays "no cursor" for views, while a table still reads it as a real cursor for an empty primary key. Refs #2967, #2968 Test: tests/test_table_api.py::test_view_ignores_an_empty_next_cursor returns 500 before this change and passes after it. The same test passes against origin/main's table.py, so this restores base behaviour. tests/test_table_api.py: 129 passed, 8 xpassed; tests/test_html.py -k view: 6 passed; black and ruff check clean. --- datasette/views/table.py | 5 +++++ tests/test_table_api.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/datasette/views/table.py b/datasette/views/table.py index 7d085bf857..52cd13f4cb 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -2142,6 +2142,11 @@ async def table_view_data( # Handle pagination driven by ?_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 is not None: sort_value = None diff --git a/tests/test_table_api.py b/tests/test_table_api.py index 483d42f172..061feb7902 100644 --- a/tests/test_table_api.py +++ b/tests/test_table_api.py @@ -409,6 +409,29 @@ def test_paginate_table_with_empty_string_primary_key(): assert None is last["next_url"] +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". + with make_app_client( + memory=True, + extra_databases={ + "view_db": ( + "CREATE TABLE items (id TEXT PRIMARY KEY);" + "INSERT INTO items (id) VALUES ('a'), ('b'), ('c');" + "CREATE VIEW v AS SELECT id FROM items;" + ) + }, + ) as client: + response = client.get("/view_db/v.json?_size=1&_sort=id&_next=") + assert response.status == 200 + assert [row["id"] for row in response.json["rows"]] == ["a"] + + response = client.get("/view_db/v.json?_size=1&_sort=id&_next=1") + assert response.status == 200 + assert [row["id"] for row in response.json["rows"]] == ["b"] + + @pytest.mark.asyncio async def test_paginate_compound_keys(ds_client): fetched = [] From 75c9815e5b76e6db80f1ee9ede5998aa2164ecaa Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:00:17 +0800 Subject: [PATCH 3/4] Merge branch 'main' of github.com:simonw/datasette into fix/next-token-empty-pk --- AGENTS.md | 5 + README.md | 2 +- datasette/app.py | 187 +- datasette/cli.py | 28 +- datasette/csv_renderer.py | 160 ++ datasette/database.py | 7 + datasette/default_jump_items.py | 9 +- datasette/facets.py | 103 +- datasette/filters.py | 31 +- datasette/fixtures.py | 19 +- datasette/handle_exception.py | 15 +- datasette/homepage.py | 402 ++++ datasette/plugins.py | 1 + datasette/publish/cloudrun.py | 65 + datasette/publish/heroku.py | 14 +- datasette/renderer.py | 166 +- datasette/static/app.css | 1763 ++++++++++++++--- datasette/static/catalog-cards.js | 19 + datasette/static/column-stats.js | 133 +- datasette/static/copy-button.js | 185 ++ datasette/static/datasette-manager.js | 27 +- datasette/static/edit-tools.js | 125 +- datasette/static/homepage.js | 298 +++ datasette/static/modal.js | 91 +- datasette/static/navigation-search.js | 84 +- datasette/static/recent.js | 107 + datasette/static/row-fields.js | 196 ++ datasette/static/table-layout.js | 25 +- datasette/static/table.js | 7 +- datasette/stored_queries.py | 14 +- datasette/telemetry.py | 9 +- datasette/template_contexts.py | 5 +- datasette/templates/_catalog_cards.html | 51 + datasette/templates/_export_dialog.html | 6 +- datasette/templates/_facet_results.html | 2 +- datasette/templates/_homepage_fragment.html | 5 + datasette/templates/_homepage_results.html | 101 + datasette/templates/_homepage_summary.html | 9 + datasette/templates/_query_list_fragment.html | 4 + datasette/templates/_query_list_results.html | 67 + datasette/templates/_query_list_summary.html | 4 + datasette/templates/_recent_item.html | 1 + datasette/templates/_row_fields.html | 39 + datasette/templates/_suggested_facets.html | 2 +- datasette/templates/_table.html | 4 +- datasette/templates/base.html | 6 +- datasette/templates/database.html | 109 +- datasette/templates/index.html | 52 +- datasette/templates/query.html | 5 + datasette/templates/query_list.html | 290 +-- datasette/templates/row.html | 32 +- datasette/templates/schema.html | 5 +- datasette/templates/table.html | 65 +- datasette/tracer.py | 4 +- datasette/url_builder.py | 11 +- datasette/utils/__init__.py | 141 +- datasette/utils/asgi.py | 78 +- datasette/utils/internal_db.py | 21 +- datasette/utils/testing.py | 175 -- datasette/version.py | 2 +- datasette/views/base.py | 322 ++- datasette/views/database.py | 129 +- datasette/views/index.py | 254 ++- datasette/views/row.py | 58 +- datasette/views/special.py | 57 +- datasette/views/stored_queries.py | 71 +- datasette/views/table.py | 262 +-- datasette/views/table_extras.py | 59 +- docs/authentication.rst | 6 +- docs/binary_data.rst | 4 +- docs/changelog.rst | 167 ++ docs/cli-reference.rst | 14 +- docs/contributing.rst | 21 +- docs/csv_export.rst | 19 +- docs/custom_templates.rst | 20 +- docs/deploying.rst | 2 +- docs/facets.rst | 4 +- docs/full_text_search.rst | 26 +- docs/getting_started.rst | 2 +- docs/images/copy-button-example.webp | Bin 0 -> 7242 bytes docs/index.rst | 2 +- docs/internals.rst | 83 +- docs/introspection.rst | 47 +- docs/javascript_plugins.rst | 183 +- docs/json_api.rst | 79 +- docs/pages.rst | 54 +- docs/plugin_hooks.rst | 111 +- docs/plugins.rst | 12 +- docs/publish.rst | 33 + docs/settings.rst | 58 +- docs/shots.yml | 18 +- docs/shots/copy-button-example.js | 18 + docs/spatialite.rst | 2 +- docs/sql_queries.rst | 2 +- docs/template_context.rst | 71 +- docs/upgrade-1.0a20.md | 5 +- docs/upgrade_guide.md | 69 + pyproject.toml | 3 +- pytest.ini | 3 +- tests/conftest.py | 92 +- tests/fixtures.py | 195 +- tests/plugins/messages_output_renderer.py | 4 +- tests/plugins/register_output_renderer.py | 47 +- tests/test_actions_sql.py | 7 - tests/test_actor_restriction_bug.py | 4 - tests/test_allowed_many.py | 21 - tests/test_allowed_resources.py | 16 - tests/test_api.py | 451 +++-- tests/test_api_write.py | 53 - tests/test_auth.py | 99 +- tests/test_autocomplete.py | 9 - tests/test_background_tasks.py | 9 - tests/test_base_view.py | 4 - tests/test_cli.py | 43 +- tests/test_cli_serve_get.py | 5 +- tests/test_column_types.py | 226 +-- tests/test_config_dir.py | 66 +- tests/test_config_permission_rules.py | 9 - tests/test_crossdb.py | 20 +- tests/test_csrf_middleware.py | 73 +- tests/test_csv.py | 118 +- tests/test_custom_pages.py | 130 +- tests/test_debug_autocomplete.py | 4 - tests/test_default_deny.py | 7 - tests/test_docs.py | 3 - tests/test_docs_plugins.py | 2 - tests/test_error_shape.py | 124 +- tests/test_extras.py | 2 - tests/test_facets.py | 335 +++- tests/test_fd_leak.py | 8 +- tests/test_filters.py | 5 +- tests/test_fts_permissions.py | 7 - tests/test_homepage.py | 451 +++++ tests/test_html.py | 828 ++++---- tests/test_http_span.py | 137 +- tests/test_internal_db.py | 108 +- tests/test_internals_database.py | 154 +- tests/test_internals_datasette.py | 24 +- tests/test_internals_datasette_client.py | 19 - tests/test_internals_request.py | 52 +- tests/test_internals_response.py | 225 ++- tests/test_internals_urls.py | 83 +- tests/test_jump.py | 107 +- tests/test_label_column_for_table.py | 1 - tests/test_lifespan.py | 10 - tests/test_load_extensions.py | 3 - tests/test_messages.py | 4 +- tests/test_multipart.py | 1736 ++++++++-------- tests/test_numeric_filter_values.py | 32 + tests/test_package.py | 9 +- tests/test_permission_endpoints.py | 14 - tests/test_permissions.py | 496 ++--- tests/test_playwright.py | 943 ++++++++- tests/test_plugins.py | 619 +++--- tests/test_pr76_fts_policy.py | 1 - tests/test_pr76_statistics_policy.py | 3 - tests/test_publish_cloudrun.py | 106 +- tests/test_publish_heroku.py | 9 +- tests/test_queries.py | 345 ++-- tests/test_renderer_extras.py | 283 +++ tests/test_renderer_streaming.py | 299 +++ tests/test_restriction_sql.py | 9 - tests/test_routes.py | 48 +- tests/test_schema_endpoints.py | 43 +- tests/test_search_tables.py | 7 - tests/test_setting_aliases.py | 181 ++ tests/test_shutdown.py | 7 - tests/test_spatialite.py | 1 - tests/test_stored_queries.py | 285 +-- tests/test_success_envelope.py | 10 - tests/test_table_api.py | 614 +++--- tests/test_table_count.py | 9 - tests/test_table_html.py | 544 +++-- tests/test_table_pagination.py | 308 ++- tests/test_table_resource_identity.py | 7 - tests/test_tasks_endpoint.py | 3 - tests/test_telemetry.py | 37 - tests/test_telemetry_metrics.py | 16 - tests/test_telemetry_registry.py | 9 - tests/test_template_context.py | 3 +- tests/test_token_handler.py | 17 - tests/test_tracer.py | 80 +- tests/test_utils.py | 160 +- tests/test_utils_permissions.py | 10 - tests/test_utils_sql_analysis.py | 198 +- tests/test_write_wrapper.py | 22 - tests/utils.py | 20 +- 187 files changed, 13665 insertions(+), 6225 deletions(-) create mode 100644 AGENTS.md create mode 100644 datasette/csv_renderer.py create mode 100644 datasette/homepage.py create mode 100644 datasette/static/catalog-cards.js create mode 100644 datasette/static/copy-button.js create mode 100644 datasette/static/homepage.js create mode 100644 datasette/static/recent.js create mode 100644 datasette/static/row-fields.js create mode 100644 datasette/templates/_catalog_cards.html create mode 100644 datasette/templates/_homepage_fragment.html create mode 100644 datasette/templates/_homepage_results.html create mode 100644 datasette/templates/_homepage_summary.html create mode 100644 datasette/templates/_query_list_fragment.html create mode 100644 datasette/templates/_query_list_results.html create mode 100644 datasette/templates/_query_list_summary.html create mode 100644 datasette/templates/_recent_item.html create mode 100644 datasette/templates/_row_fields.html delete mode 100644 datasette/utils/testing.py create mode 100644 docs/images/copy-button-example.webp create mode 100644 docs/shots/copy-button-example.js create mode 100644 tests/test_homepage.py create mode 100644 tests/test_renderer_extras.py create mode 100644 tests/test_renderer_streaming.py create mode 100644 tests/test_setting_aliases.py diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..ec356707ae --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,5 @@ +# Notes for coding agents + +## JavaScript + +- Never use the browser's native `alert()`, `confirm()` or `prompt()` dialogs. Browsers embedded in other applications can dismiss them without showing anything, so a button that depends on one silently does nothing. Ask with `DatasetteModal.confirm()` from `datasette/static/modal.js`, or with a step inside the dialog that is already open, and show errors in the page. diff --git a/README.md b/README.md index 6d7b727651..2ef3bf9239 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ The license and source information will be displayed on the index page and in th ## datasette publish -If you have [Heroku](https://heroku.com/) or [Google Cloud Run](https://cloud.google.com/run/) configured, Datasette can deploy one or more SQLite databases to the internet with a single command: +If you have [Heroku](https://www.heroku.com/) or [Google Cloud Run](https://cloud.google.com/run/) configured, Datasette can deploy one or more SQLite databases to the internet with a single command: datasette publish heroku database.db diff --git a/datasette/app.py b/datasette/app.py index 9c1cc32801..14a0139812 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -24,6 +24,7 @@ import time import types import urllib.parse +import warnings from concurrent import futures from pathlib import Path @@ -77,7 +78,6 @@ escape_css_string, escape_sqlite, find_spatialite, - format_bytes, module_from_path, move_plugins_and_allow, move_table_config, @@ -222,7 +222,7 @@ class PermissionCheck: ), Setting( "max_post_body_bytes", - 2 * 1024 * 1024, + 10 * 1024 * 1024, "Maximum size in bytes for a POST body read into memory, e.g. JSON API requests - set 0 to disable this limit", ), Setting( @@ -241,12 +241,12 @@ class PermissionCheck: "Time limit for calculating a suggested facet", ), Setting( - "allow_facet", + "default_allow_facet", True, "Allow users to specify columns to facet using ?_facet= parameter", ), Setting( - "allow_download", + "default_allow_download", True, "Allow users to download the original SQLite database files", ), @@ -273,14 +273,14 @@ class PermissionCheck: ), Setting("cache_size_kb", 0, "SQLite cache size in KB (0 == use SQLite default)"), Setting( - "allow_csv_stream", + "default_allow_stream", True, - "Allow .csv?_stream=1 to download all rows (ignoring max_returned_rows)", + "Allow ?_stream=1 to export all rows (ignoring max_returned_rows)", ), Setting( - "max_csv_mb", + "max_stream_mb", 100, - "Maximum size allowed for CSV export in MB - set 0 to disable this limit", + "Maximum size allowed for a streamed export in MB - set 0 to disable this limit", ), Setting( "truncate_cells_html", @@ -304,12 +304,63 @@ class PermissionCheck: ), Setting("base_url", "/", "Datasette URLs should use this base path"), ) -_HASH_URLS_REMOVED = "The hash_urls setting has been removed, try the datasette-hashed-urls plugin instead" -OBSOLETE_SETTINGS = { - "hash_urls": _HASH_URLS_REMOVED, - "default_cache_ttl_hashed": _HASH_URLS_REMOVED, -} DEFAULT_SETTINGS = {option.name: option.default for option in SETTINGS} +# Previous names of settings that have been renamed, mapped to their new +# names. The old names are not documented but still work everywhere a +# setting can be set or read. +SETTING_ALIASES = { + "allow_facet": "default_allow_facet", + "allow_download": "default_allow_download", + "allow_csv_stream": "default_allow_stream", + "max_csv_mb": "max_stream_mb", +} + + +# Arguments that output renderer render functions should no longer accept, +# mapped to what to use instead +DEPRECATED_RENDER_ARGUMENTS = { + "data": "Declare the extras it needs and use the page argument instead", + "args": "Use request.args instead", +} + + +def _warn_deprecated_render_argument(render, extension, argument, replacement): + message = ( + f"Output renderer '{extension}' accepts the {argument} argument, which is " + f"deprecated and will be removed before Datasette 1.0. {replacement}: " + "https://docs.datasette.io/en/latest/plugin_hooks.html" + "#register-output-renderer-datasette" + ) + code = getattr(render, "__code__", None) + if code is None: + warnings.warn(message, DeprecationWarning, stacklevel=2) + else: + # Report the warning against the render function itself, so the + # plugin author can see which code needs to change + warnings.warn_explicit( + message, + DeprecationWarning, + filename=code.co_filename, + lineno=code.co_firstlineno, + # module must be a string or some warnings are silently dropped + module=getattr(render, "__module__", None) or "datasette", + ) + + +def resolve_setting_aliases(settings, source): + """ + Return a copy of the settings dictionary with any old setting names + replaced by their new names. source says where the settings came from, + for the error raised if a setting is given under both of its names. + """ + for old_name, name in SETTING_ALIASES.items(): + if old_name in settings and name in settings: + raise StartupError( + f"Setting '{name}' and its previous name '{old_name}' " + f"are both set in {source}" + ) + return {SETTING_ALIASES.get(key, key): value for key, value in settings.items()} + FAVICON_PATH = app_root / "datasette" / "static" / "favicon.png" @@ -392,7 +443,6 @@ def _resolve_static_asset_path(root_path, path): "show_logout": "True if the logout link should be shown in the navigation menu", "zip": "Python's ``zip()`` builtin, made available to template logic", "body_scripts": 'List of JavaScript snippets contributed by plugins using :ref:`plugin_hook_extra_body_script`. Each item is a dictionary with ``script`` containing JavaScript source and ``module`` indicating whether Datasette will wrap it in `` diff --git a/datasette/templates/_row_fields.html b/datasette/templates/_row_fields.html new file mode 100644 index 0000000000..5803b9ee44 --- /dev/null +++ b/datasette/templates/_row_fields.html @@ -0,0 +1,39 @@ + +
+{% if display_columns and display_rows %} +{% set row = display_rows[0] %} +
+ {% for column, cell in zip(display_columns, row) %} + {% set raw = cell.raw %} + {% set is_text = raw is string %} + {% set is_empty = raw is none or (is_text and raw == "") %} + {% set copyable = not is_empty and (is_text or raw is number) %} + {% set is_long = is_text and (raw|length > 400 or raw.count("\n") > 6) %} + {% set expand_label = "Show all {:,} characters".format(raw|length) if is_long else "" %} +
+
+ {#- after underscores lets long snake_case names wrap between words #} + {{ (column.name|e)|replace("_", "_"|safe) }} + {% if column.description %}{{ column.description }}{% endif %} +
+
+ {#- Labels are CSS generated content so copying a section of the page leaves them out #} + {% if raw is none %} + {% elif is_text and raw == "" %} + {% elif is_long %}
{{ cell.value }}
+ {% else %}
{{ cell.value }}
+ {% endif %} + {% if copyable %} + {#- row-fields.js adds a JSON pretty-print toggle here for JSON values #} +
+ +
+ {% endif %} +
+
+ {% endfor %} +
+{% endif %} +{% if not display_rows %} +

0 records

+{% endif %} diff --git a/datasette/templates/_suggested_facets.html b/datasette/templates/_suggested_facets.html index 3fb3e47b8b..bbbec54ff0 100644 --- a/datasette/templates/_suggested_facets.html +++ b/datasette/templates/_suggested_facets.html @@ -2,7 +2,7 @@ Suggested facets