pypi datasette 1.0a44

41 minutes ago

This alpha settles a great deal of the outstanding JSON and internal APIs needed prior to the stable 1.0 release - see the 1.0 milestone for current progress.

Queries now return datasette.Row objects in place of sqlite3.Row. The path_with_*() helpers have been replaced by a new datasette.urls.modify() method. Datasette now handles null primary keys (allowed by SQLite) correctly.

The upgrade guide describes how to update plugins for the backwards incompatible changes in this release.

Security fixes

  • Fixed a security issue where the /-/config introspection endpoint showed anonymous visitors the allow blocks, the names of private tables and the name and SQL of private stored queries defined in configuration, on an instance that was otherwise public. Backwards incompatible: the endpoint now requires the permissions-debug permission, which by default is only granted to the root user. It previously needed only view-instance.
  • Fixed a security issue where a SQL parameter returned by a permission_resources_sql() plugin could be replaced by a value from Datasette, or from another plugin, that used the same parameter name. A plugin with a parameter called :database, :q, :pattern, :allowed_dbs or :limit had it overwritten on the homepage and database page, which could list the names, columns and row counts of tables the visitor was not allowed to view. Row data was not exposed. Datasette now renames the parameters of each PermissionSQL before combining them, so plugins no longer need to choose names that are unique.
  • Fixed a security issue where a stored query could be given a name ending in a newline, such as "dogs\n", which got past the check that a query name does not conflict with a table or view. Those names are now rejected.

Features

  • Datasette now handles rows with a primary key that is null, an empty string or a binary value, and primary key columns with no declared type. (#2145, #2805, #2419, #3112)
    • A row with an empty string primary key has a row page at /database/table/$empty, with working edit and delete buttons.
    • A row with a binary primary key has a row page at a URL such as /database/table/b:0102. Binary keys are displayed as binary 0102.
    • In a primary key column with no declared type the integer 1 and the text "1" are different rows. They now have different URLs, /database/table/i:1 and /database/table/1, where previously the integer row could not be reached.
    • A row with a null primary key cannot be told apart from other rows, so it no longer has a link, a row page or edit and delete buttons. It previously linked to /database/table/None, where the delete button could delete a different row with the text None as its key.
    • Pagination now works for tables with any of these keys. Following next_url through a table with a binary primary key previously returned the same page for ever.
    • Foreign key links to these rows, and the links in the edit row dialog, use the same row URLs. The autocomplete API returns a new "path" key for each row, the last part of the URL to its row page, or null for a row with a null primary key.
    • New primary_key_edge_cases, compound_primary_key_edge_cases and primary_key_edge_case_references tables in the fixtures database demonstrate these.
  • New datasette.urls.modify(target, add=, replace=, remove=, format=) method for building links that change the query string of the current page or of any other path. It applies base_url for you and is available in templates as urls.modify(). See datasette.urls.modify(target, *, add=None, replace=None, remove=None, format=None). (#1342)
  • datasette.urls.row() and datasette.urls.row_blob() now accept a list or tuple of primary key values, which are tilde-encoded and joined with commas. A string is still used exactly as it is given. See datasette.urls. (#1048)
  • The following datasette.utils functions and classes are now documented and considered stable for use by plugins: escape_sqlite(), escape_fts(), to_css_class(), modify_query_string(), actor_matches_allow(), add_cors_headers(), StartupError, BadMetadataError, MultiParams, PrefixedUrlString, PaginatedResources and the sqlite3 module. (#1630)
  • The custom_time_limit= argument to db.execute() can now set a time limit that is longer than the sql_time_limit_ms setting. Previously a longer limit was ignored. The ?_timelimit= query string argument can still only shorten the limit, and facet_time_limit_ms and facet_suggest_time_limit_ms are still capped by sql_time_limit_ms. Plugins can apply the same cap using the new datasette.capped_time_limit_ms() method.
  • The ?_context=1 template debug page, enabled by the template_debug setting, now shows each variable passed to the template with its documentation, its current value and the {{ variable }}syntax for using it, with a copy button. Functions are shown with their arguments and docstring. Variables are grouped into those documented for the page, undocumented variables, variables added by plugins and variables available on every page.
  • The template context documentation now covers the stored query pages, the execute write SQL page, the schema pages, the create token page, the API explorer, the logout page, the error pages and the pages that display JSON such as /-/versions, in addition to the homepage, database, table, row and query pages. Each of these is now rendered using a documented dataclass. The variables for the permission and other debugging tools are documented as well, in a separate section that is not covered by the promise of stability.
  • New DatasetteModal.alert() JavaScript method for showing a message using an in-page dialog, returning a promise that resolves when it is dismissed. Datasette now uses this in place of the browser's alert(), which embedded browsers can dismiss without displaying. See Alert dialogs.
  • The tabs for panels added by JavaScript plugins using makeAboveTablePanelConfigs() now show which panel is currently selected. They are also now accessible tabs: the selected state is exposed to assistive technology and the arrow, Home and End keys move between them. (#2253)
  • ?_stream=1 now fetches rows in pages of max_returned_rows, 1,000 by default, instead of the default page size of 100. This makes streaming every row of a large table several times faster. A ?_size= in the URL is still respected. If a page of that size takes longer than sql_time_limit_ms, it is fetched again using the default page size, which is then used for the rest of the stream. (#3070, #3092)
  • The "Export data" dialog now groups plugin formats that can stream with TSV and CSV, so its "Include all rows" option applies to those formats too.
  • Datasette now remembers the columns, primary keys, foreign keys, label column and full-text search table of each table until the schema of its database changes. Loading a table page previously looked up the columns of that table nine times. (#3102)
  • The query page now repeats its notice that the results have been truncated below the table of results, where previously it was only shown above the SQL editor.
  • The link to download a SQLite database from the database page is now a button showing the size of the file.
  • File sizes shown on the database page and in the tooltips for binary values now use decimal units, where 1 MB is 1,000,000 bytes, matching the sizes already shown on the homepage. They previously used 1 MB to mean 1,048,576 bytes, so a 5,242,880 byte database that was displayed as 5.0 MB is now displayed as 5.2 MB.
  • CSV, TSV, JSON and other exports of a custom SQL query or a stored query now include a Datasette-Truncated: true or Datasette-Truncated: false HTTP header, so code paging through the results of a query can tell whether rows were left out because of max_returned_rows. Truncated responses also include a Datasette-Max-Returned-Rows header with the limit that was applied. Both headers are listed in Access-Control-Expose-Headers for --cors. See Truncated query results. (#1553)

Rows and columns

  • Backwards incompatible: rows returned by db.execute() are now datasette.Row objects instead of sqlite3.Row objects. So are rows fetched from the connection passed to a db.execute_fn() or db.execute_write_fn() function. Row is designed to work for database backends other than SQLite. See the upgrade guide for how to update plugins. row["name"], row[0], row.keys(), dict(row), tuple(row) and iterating over a row all continue to work. Code will need to change if it uses isinstance(row, sqlite3.Row), looks up columns using a different case from the one in the query, or catches IndexError for a missing column name - that is now a KeyError. (#1973)
  • Backwards incompatible: results.columns is now a Columns object describing each column, shared by every row as row.columns. Use results.columns.names for the column names. On table and row pages each Column includes the details of that column in its table, such as the type it was declared with.
  • Backwards incompatible: db.table_column_details() now returns a Columns object of datasette.Column objects, the same class used for the columns of a row. It previously returned a list of datasette.utils.Column named tuples, and that class has been removed. The columns can no longer be unpacked or indexed as tuples. is_pk is now pk_position, type is None and not an empty string for a column declared without a type, hidden is a boolean with generated columns described by a new generated attribute, and cid has been removed. See the upgrade guide. (#3100)
  • Backwards incompatible: the render_cell() plugin hook, and the render_cell() method of column types, are now always passed the value stored in the database. Previously the value for a foreign key column was sometimes a {"value": ..., "label": ...} dictionary, depending on the page, the query string and the data. The row passed to the hook is now a datasette.Row on every page, where previously it was either a sqlite3.Row or an undocumented CustomRow. Labels for foreign keys are available in the new row.labels dictionary. If a column is a foreign key and also has a column type assigned, the column type now renders the cell. Previously the cell showed a link to the referenced row, because the column type was passed the label dictionary and did not recognize it. (#1973)
  • Backwards incompatible: the rows passed to output renderers are datasette.Row objects. With ?_labels=on they previously contained {"value": ..., "label": ...} dictionaries - the labels are now in row.labels. The row_actions() and top_row() hooks are passed a datasette.Row too.
  • Backwards incompatible: the row passed to render_cell() on the row page now has its values in the same order as on the table page. Previously the primary key columns were moved to the start, so row[0] could mean something different on the two pages. The row page still displays primary keys first.
  • Backwards incompatible: ?_labels=on no longer expands a foreign key that refers to a table with no label column. These were previously returned as {"value": 1, "label": "1"}, repeating the value as its own label, and are now returned as the plain value. The column is no longer listed in expanded_columns or given a column_label column in CSV exports. The HTML table still links the value to the row it refers to.
  • Backwards incompatible: datasette.utils.CustomRow has been removed.

Breaking changes

  • Backwards incompatible: optional arguments to many of the documented internal methods are now keyword-only, so they can no longer be passed positionally. See the upgrade guide. (#1822) The affected signatures are:

    • Datasette(files=None, *, ...) - every argument other than files is keyword-only.
    • datasette.render_template(templates, context=None, *, request=None, view_name=None)
    • datasette.execute(db_name, sql, params=None, *, ...) and db.execute(sql, params=None, *,...)
    • db.execute_write(sql, params=None, *, ...), db.execute_write_script(sql, *, ...), db.execute_write_many(sql, params_seq, *, ...) and db.execute_write_fn(fn, *, ...)
    • datasette.get_database(name=None, *, route=None), datasette.add_database(db, name=None,*, route=None) and datasette.add_memory_database(memory_name, name=None, *, route=None)
    • Database(ds, path=None, *, ...) - every argument after path is keyword-only. The documentation for this constructor previously left out its mode argument, so passing is_temp_disk by position following that documentation set mode instead. (#2942)
    • datasette.plugin_config(plugin_name, *, database=None, table=None, fallback=True)
    • datasette.set_actor_cookie(response, actor, *, expire_after=None)
    • datasette.client.get(path, *, skip_permission_checks=False, **kwargs) and the other datasette.client methods.
    • datasette.urls.instance(), .path(), .database(), .database_query(), .table(), .query()and .row() now require format= as a keyword.
    • Request.fake(path_with_query_string, *, method="GET", scheme="http", url_vars=None)
    • Response(body=None, *, status=200, headers=None, content_type="text/plain")
    • Response.html(), .text(), .json(), .stream(), .error() and .redirect() still accept status as a second positional argument - Response.json(data, 400) continues to work - but headers, default and content_type are keyword-only.
    • response.set_cookie(key, value="", *, max_age=None, ...)
  • Backwards incompatible: datasette.utils.path_with_added_args(), path_with_removed_args(), path_with_replaced_args(), path_with_format(), path_without_format() and append_querystring() have been removed. Plugins should use datasette.urls.modify() instead: path_with_added_args(request, {"_facet": "x"}) becomes datasette.urls.modify(request,add={"_facet": "x"}) and path_with_format(request=request, format="json", extra_qs={"_shape": "array"}) becomes datasette.urls.modify(request, format="json", add={"_shape":"array"}). path_without_format(request, include_query_string=True) becomes datasette.urls.modify(request, format=False). Note that modify() applies base_url, so its result should not have the prefix added again. See the upgrade guide. (#1342)

  • Backwards incompatible: the path_with_replaced_args, fix_path and append_querystringfunctions are no longer passed to the table and query templates. Custom templates should use urls.modify(): fix_path(path_with_replaced_args(request, {"_sort": "x"})) becomes urls.modify(request, replace={"_sort": "x"}) and append_querystring(url, "_shape=array")becomes urls.modify(url, add={"_shape": "array"}). fix_path(path) is the same as urls.path(path).

  • Backwards incompatible: the format_bytes() function is no longer available in templates, and datasette.utils.format_bytes() has been removed. Custom templates that call {{format_bytes(size) }} should use Jinja's built-in filesizeformat filter instead: {{size|filesizeformat }}. See the upgrade guide. (#1841)

  • Backwards incompatible: the undocumented datasette.utils.testing module, which held the TestClient and TestResponse classes, has been removed. Tests should use datasette.clientinstead, as described in Testing plugins. See the upgrade guide. (#3074)

  • Datasette no longer depends on asgiref. A plugin that imports it should list it as a dependency of its own. (#3074)

  • Backwards incompatible: the homepage JSON at /.json now returns the same searchable catalog of tables, views and stored queries as the HTML homepage, and accepts the same ?q=, ?database= and ?page= parameters. It previously returned up to five tables for each database in a format left over from the old homepage design, ignored those parameters and could take several seconds for instances with thousands of tables. Each database in databases now has name, private, tables, views, url and size keys - url replaces path - and tables and views are listed in a new items key, paginated using next_url. This endpoint is still marked as unstable. (#1674)

  • Backwards incompatible: ?_shape=object now returns a 400 error for a table with rows that have a null primary key, since those rows have no key to file them under. They were previously merged into one entry. The keys of the object are now the row paths used in row URLs, so in a primary key column with no declared type the integer 5 has the key "i:5". Tables with ordinary primary keys are not affected.

  • Backwards incompatible: the primary_key_values variable passed to the row page template now holds the values decoded from the URL. A binary key is bytes, and a number in a primary key column with no declared type is an int or float. They were previously always strings. Use the new key_value_display template filter to display one: {{ value|key_value_display }}. See the upgrade guide.

  • Backwards incompatible: the JSON that ?_context=1 previously returned has moved to ?_context_json=1.

  • Backwards incompatible: removed template variables that were documented but not used by any of Datasette's default templates, so that they are not frozen by the template context promise of stability. (#3088) Custom templates that use them should switch to the alternatives listed here:

    • ok on the table, row, stored query list, save query, edit query and error pages. On the save query and edit query pages use analysis_error instead, which is None if the SQL was analyzed without an error.
    • path, editable and queries_more on the database page. Use urls.database(database) for the path. editable was always true. queries_count is the number of stored queries, which can be compared to the length of queries.
    • page_size on the homepage, which was always 30.
    • limit, show_private_note, show_trusted_note and show_database on the stored query list. show_database was the same as database is none.
    • parameters on the save query and edit query pages.

    The url_csv, count_sql, rows, columns, next and base_url variables are also not used by the default templates, but have been kept because custom templates and plugins rely on them. The JSON API is unchanged, except that /-/queries.json and /<database>/-/queries.json no longer return the show_private_note and show_trusted_note keys.

Bug fixes

  • A URL with a format extension that Datasette does not recognize, such as /database/table.blahor /database/-/query.blah, now returns a 404. These previously returned a 500 error. (#1914)
  • PUT, PATCH and DELETE requests to a table URL now return a 405 error. They were previously handled as if they were a GET.
  • 405 and 403 errors now decide whether to respond with JSON in the same way as other errors: for a .json URL, an Accept: application/json header or a JSON Content-Type header, including one with a charset parameter. A 403 for a .csv or .tsv URL is now plain text, not an HTML page.
  • ?column__in= and ?column__notin= now return a 400 error if their JSON array is not valid JSON, or contains a nested list or object, an integer too large for SQLite or text that cannot be encoded as UTF-8. These previously returned a 500 error. Thanks, goranai. (#3090, #3091)
  • datasette.urls.database_query(database, sql, format="json") and datasette.urls.path(path,format=...) now put the format extension before the query string. They previously added it to the end of the ?sql= value.
  • Fixed a bug where filtering a view by a column calculated using an expression, such as count(*) or sum(amount), returned no rows for a number: ?total=5 did not match rows where total was 5. Facet links for those columns led to empty pages for the same reason. The __exact, __not, __inand __notin filters now compare a value that looks like a number as both a number and text, for columns that have no declared type. This also applies to table columns declared without a type, where ?column=1 now matches the number 1 as well as the text "1". (#1671, #2073, #2713)
  • Fixed a bug where the foreign keys of a table could be reported as empty for a table that had just been created or altered by another connection, which hid foreign key links and labels for that table until the schema next changed. This was also the cause of intermittent failures in the write API tests. (#2356, #1919)
  • Fixed a bug where the search box on the table page was empty after running a search, instead of showing the current ?_search= term. The term is now available to the table template as search.
  • Fixed a bug where sort, facet and filter-removal links on the table page dropped query string arguments with blank values, so sorting /db/table?name= lost the filter for rows where name is the empty string.
  • The "View and edit SQL" link on the table page now links straight to /database/-/query, instead of to a URL that redirects there.
  • ?_context_json=1 no longer returns a 500 error for pages such as /-/queries that have a value in their context which cannot be represented as JSON.
  • A read query that fails part way through now has its cursor closed immediately. On Python 3.11 the open cursor could keep a named in-memory database alive after its Datasette instance was closed.
  • Tables created using the create table API now have NOT NULL primary key columns, so they can no longer hold rows with a null primary key. This applies to text and compound primary keys, for tables created from columns and from example rows. Inserting a row without a value for one of those keys now returns a 400 error. A single integer primary key is unchanged, since SQLite never allows it to be null. Thanks, Pranav Mishra. (#2807, #2826)
  • datasette publish and datasette package no longer fail on Windows when removing their temporary directory. (#1479)
  • Datasette's test suite now runs on Windows in CI. (#1627)
  • Fixed a bug where a custom SQL query or stored query returned one row more than max_returned_rows if that setting was the same as default_page_size. Thanks, kokokoXUY, who spotted this in #2963.
  • Datasette no longer runs count(*) against SpatiaLite KNN and KNN2 virtual tables. That query could run for minutes, ignoring the time limit. Those tables are now shown as having 0 rows. (#1611)
  • The insert API can now return the rows it inserted into a WITHOUT ROWID table. Inserting using "row", or using "rows" with "return": true, previously failed with a no such column: rowiderror. (#1873, #3081)
  • Rows returned by the insert API for a table with no primary key now include the rowid of each row, matching the upsert API.
  • The column menu on a view page now offers "Facet by this" for the first column, which was previously left out. Thanks, Sebastian Cao. (#2045, #2810)

Don't miss a new datasette release

NewReleases is sending notifications on new releases.