Repository navigation
1.0a44
Pre-releaseThis 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
allowblocks, 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 thepermissions-debugpermission, which by default is only granted to the root user. It previously needed onlyview-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_dbsor:limithad 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 eachPermissionSQLbefore 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 asbinary 0102. - In a primary key column with no declared type the integer
1and the text"1"are different rows. They now have different URLs,/database/table/i:1and/database/table/1, where previously the integer row could not be reached. - A row with a
nullprimary 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 textNoneas its key. - Pagination now works for tables with any of these keys. Following
next_urlthrough 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, ornullfor a row with a null primary key. - New
primary_key_edge_cases,compound_primary_key_edge_casesandprimary_key_edge_case_referencestables in the fixtures database demonstrate these.
- A row with an empty string primary key has a row page at
- 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 appliesbase_urlfor you and is available in templates asurls.modify(). See datasette.urls.modify(target, *, add=None, replace=None, remove=None, format=None). (#1342) datasette.urls.row()anddatasette.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.utilsfunctions 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,PaginatedResourcesand thesqlite3module. (#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 bysql_time_limit_ms. Plugins can apply the same cap using the new datasette.capped_time_limit_ms() method. - The
?_context=1template 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'salert(), 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,
HomeandEndkeys move between them. (#2253) ?_stream=1now 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 MBis now displayed as5.2 MB. - CSV, TSV, JSON and other exports of a custom SQL query or a stored query now include a
Datasette-Truncated: trueorDatasette-Truncated: falseHTTP 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 aDatasette-Max-Returned-Rowsheader with the limit that was applied. Both headers are listed inAccess-Control-Expose-Headersfor--cors. See Truncated query results. (#1553)
Rows and columns
- Backwards incompatible: rows returned by db.execute() are now datasette.Row objects instead of
sqlite3.Rowobjects. So are rows fetched from the connection passed to a db.execute_fn() or db.execute_write_fn() function.Rowis 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 usesisinstance(row, sqlite3.Row), looks up columns using a different case from the one in the query, or catchesIndexErrorfor a missing column name - that is now aKeyError. (#1973) - Backwards incompatible:
results.columnsis now a Columns object describing each column, shared by every row asrow.columns. Useresults.columns.namesfor the column names. On table and row pages eachColumnincludes 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.Columnobjects, the same class used for the columns of a row. It previously returned a list ofdatasette.utils.Columnnamed tuples, and that class has been removed. The columns can no longer be unpacked or indexed as tuples.is_pkis nowpk_position,typeisNoneand not an empty string for a column declared without a type,hiddenis a boolean with generated columns described by a newgeneratedattribute, andcidhas 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 thevaluefor a foreign key column was sometimes a{"value": ..., "label": ...}dictionary, depending on the page, the query string and the data. Therowpassed to the hook is now adatasette.Rowon every page, where previously it was either asqlite3.Rowor an undocumentedCustomRow. Labels for foreign keys are available in the newrow.labelsdictionary. 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
rowspassed to output renderers aredatasette.Rowobjects. With?_labels=onthey previously contained{"value": ..., "label": ...}dictionaries - the labels are now inrow.labels. The row_actions() and top_row() hooks are passed adatasette.Rowtoo. - Backwards incompatible: the
rowpassed torender_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, sorow[0]could mean something different on the two pages. The row page still displays primary keys first. - Backwards incompatible:
?_labels=onno 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 inexpanded_columnsor given acolumn_labelcolumn in CSV exports. The HTML table still links the value to the row it refers to. - Backwards incompatible:
datasette.utils.CustomRowhas 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 thanfilesis keyword-only.datasette.render_template(templates, context=None, *, request=None, view_name=None)datasette.execute(db_name, sql, params=None, *, ...)anddb.execute(sql, params=None, *,...)db.execute_write(sql, params=None, *, ...),db.execute_write_script(sql, *, ...),db.execute_write_many(sql, params_seq, *, ...)anddb.execute_write_fn(fn, *, ...)datasette.get_database(name=None, *, route=None),datasette.add_database(db, name=None,*, route=None)anddatasette.add_memory_database(memory_name, name=None, *, route=None)Database(ds, path=None, *, ...)- every argument afterpathis keyword-only. The documentation for this constructor previously left out itsmodeargument, so passingis_temp_diskby position following that documentation setmodeinstead. (#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 otherdatasette.clientmethods.datasette.urls.instance(),.path(),.database(),.database_query(),.table(),.query()and.row()now requireformat=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 acceptstatusas a second positional argument -Response.json(data, 400)continues to work - butheaders,defaultandcontent_typeare 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()andappend_querystring()have been removed. Plugins should usedatasette.urls.modify()instead:path_with_added_args(request, {"_facet": "x"})becomesdatasette.urls.modify(request,add={"_facet": "x"})andpath_with_format(request=request, format="json", extra_qs={"_shape": "array"})becomesdatasette.urls.modify(request, format="json", add={"_shape":"array"}).path_without_format(request, include_query_string=True)becomesdatasette.urls.modify(request, format=False). Note thatmodify()appliesbase_url, so its result should not have the prefix added again. See the upgrade guide. (#1342) -
Backwards incompatible: the
path_with_replaced_args,fix_pathandappend_querystringfunctions are no longer passed to the table and query templates. Custom templates should useurls.modify():fix_path(path_with_replaced_args(request, {"_sort": "x"}))becomesurls.modify(request, replace={"_sort": "x"})andappend_querystring(url, "_shape=array")becomesurls.modify(url, add={"_shape": "array"}).fix_path(path)is the same asurls.path(path). -
Backwards incompatible: the
format_bytes()function is no longer available in templates, anddatasette.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.testingmodule, which held theTestClientandTestResponseclasses, 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
/.jsonnow 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 indatabasesnow hasname,private,tables,views,urlandsizekeys -urlreplacespath- and tables and views are listed in a newitemskey, paginated usingnext_url. This endpoint is still marked as unstable. (#1674) -
Backwards incompatible:
?_shape=objectnow returns a 400 error for a table with rows that have anullprimary 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 integer5has the key"i:5". Tables with ordinary primary keys are not affected. -
Backwards incompatible: the
primary_key_valuesvariable passed to the row page template now holds the values decoded from the URL. A binary key isbytes, and a number in a primary key column with no declared type is anintorfloat. They were previously always strings. Use the newkey_value_displaytemplate filter to display one:{{ value|key_value_display }}. See the upgrade guide. -
Backwards incompatible: the JSON that
?_context=1previously 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:
okon the table, row, stored query list, save query, edit query and error pages. On the save query and edit query pages useanalysis_errorinstead, which isNoneif the SQL was analyzed without an error.path,editableandqueries_moreon the database page. Useurls.database(database)for the path.editablewas always true.queries_countis the number of stored queries, which can be compared to the length ofqueries.page_sizeon the homepage, which was always 30.limit,show_private_note,show_trusted_noteandshow_databaseon the stored query list.show_databasewas the same asdatabase is none.parameterson the save query and edit query pages.
The
url_csv,count_sql,rows,columns,nextandbase_urlvariables 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.jsonand/<database>/-/queries.jsonno longer return theshow_private_noteandshow_trusted_notekeys.
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,PATCHandDELETErequests to a table URL now return a 405 error. They were previously handled as if they were aGET.405and403errors now decide whether to respond with JSON in the same way as other errors: for a.jsonURL, anAccept: application/jsonheader or a JSONContent-Typeheader, including one with acharsetparameter. A403for a.csvor.tsvURL 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")anddatasette.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(*)orsum(amount), returned no rows for a number:?total=5did not match rows wheretotalwas5. Facet links for those columns led to empty pages for the same reason. The__exact,__not,__inand__notinfilters 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=1now matches the number1as 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 assearch. - 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 wherenameis 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=1no longer returns a 500 error for pages such as/-/queriesthat 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
Datasetteinstance was closed. - Tables created using the create table API now have
NOT NULLprimary 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 fromcolumnsand from examplerows. 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 publishanddatasette packageno 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 SpatiaLiteKNNandKNN2virtual 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 ROWIDtable. Inserting using"row", or using"rows"with"return": true, previously failed with ano such column: rowiderror. (#1873, #3081) - Rows returned by the insert API for a table with no primary key now include the
rowidof 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)