diff --git a/datasette/filters.py b/datasette/filters.py index d1c27821e3..5530b7e7ab 100644 --- a/datasette/filters.py +++ b/datasette/filters.py @@ -1,5 +1,6 @@ import json import math +import re from typing import ClassVar from datasette import hookimpl @@ -223,6 +224,33 @@ def _coerce_numeric_filter_value(value): return converted if math.isfinite(converted) else value +# Values that SQLite would convert to a number when comparing them to a +# column with INTEGER, REAL or NUMERIC affinity +_numeric_literal_re = re.compile(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?") + + +def looks_numeric(value): + # fullmatch(), because "$" would also match before a trailing newline + return isinstance(value, str) and bool(_numeric_literal_re.fullmatch(value)) + + +def column_type_has_no_affinity(column_type): + """ + True if a column with this declared type has no type affinity (which + SQLite calls BLOB affinity), following the rules in + https://www.sqlite.org/datatype3.html#determination_of_column_affinity + + This is the case for expression columns in views, such as + ``count(*) as n``, and for table columns declared without a type. + """ + column_type = (column_type or "").upper() + if "INT" in column_type: + return False + if any(text in column_type for text in ("CHAR", "CLOB", "TEXT")): + return False + return not column_type or "BLOB" in column_type + + class TemplatedFilter(Filter): def __init__( self, @@ -233,10 +261,18 @@ def __init__( format="{}", numeric=False, no_argument=False, + no_affinity_sql_template=None, ): self.key = key self.display = display self.sql_template = sql_template + # Alternative SQL for comparing a numeric-looking value against a + # column that has no type affinity, see #1671. This should use + # "in (:p, cast(:p as numeric))" rather than "= cast(:p as numeric)": + # the "=" form applies numeric affinity to the column as well, so + # ?col=1 would also match the text values '1.0' and '01', and it + # stops SQLite from using an index on the column + self.no_affinity_sql_template = no_affinity_sql_template self.human_template = human_template self.format = format self.numeric = numeric @@ -257,6 +293,16 @@ def where_clause(self, table, column, value, param_counter): } return self.sql_template.format(**kwargs), converted + def where_clause_no_affinity(self, table, column, value, param_counter): + if not self.no_affinity_sql_template or not looks_numeric(value): + return self.where_clause(table, column, value, param_counter) + return ( + self.no_affinity_sql_template.format( + c=_quote_sqlite_identifier(column), p=f"p{param_counter}" + ), + value, + ) + def human_clause(self, column, value): if callable(self.human_template): template = self.human_template(column, value) @@ -302,10 +348,24 @@ def split_value(self, value): else: return [v.strip() for v in value.split(",")] + operator = "in" + def where_clause(self, table, column, value, param_counter): values = self.split_value(value) params = [f":p{param_counter + i}" for i in range(len(values))] - sql = f"{escape_sqlite(column)} in ({', '.join(params)})" + sql = f"{escape_sqlite(column)} {self.operator} ({', '.join(params)})" + return sql, values + + def where_clause_no_affinity(self, table, column, value, param_counter): + # Numeric-looking values are compared as both text and numbers + values = self.split_value(value) + params = [] + for i, individual_value in enumerate(values): + param = f":p{param_counter + i}" + params.append(param) + if looks_numeric(individual_value): + params.append(f"cast({param} as numeric)") + sql = f"{escape_sqlite(column)} {self.operator} ({', '.join(params)})" return sql, values def human_clause(self, column, value): @@ -315,12 +375,7 @@ def human_clause(self, column, value): class NotInFilter(InFilter): key = "notin" display = "not in" - - def where_clause(self, table, column, value, param_counter): - values = self.split_value(value) - params = [f":p{param_counter + i}" for i in range(len(values))] - sql = f"{escape_sqlite(column)} not in ({', '.join(params)})" - return sql, values + operator = "not in" def human_clause(self, column, value): return f"{column} not in {json.dumps(self.split_value(value))}" @@ -335,12 +390,14 @@ class Filters: "=", "{c} = :{p}", lambda c, v: "{c} = {v}" if v.isdigit() else '{c} = "{v}"', + no_affinity_sql_template="{c} in (:{p}, cast(:{p} as numeric))", ), TemplatedFilter( "not", "!=", "{c} != :{p}", lambda c, v: "{c} != {v}" if v.isdigit() else '{c} != "{v}"', + no_affinity_sql_template="{c} not in (:{p}, cast(:{p} as numeric))", ), TemplatedFilter( "contains", @@ -475,14 +532,24 @@ def selections(self): def has_selections(self): return bool(self.pairs) - def build_where_clauses(self, table): + def build_where_clauses(self, table, no_affinity_columns=None): + # no_affinity_columns is the set of columns that have no type + # affinity, such as expression columns in views. SQLite will not + # convert the text values from the query string to numbers when + # comparing against those, so we have to do that ourselves - see #1671 + no_affinity_columns = no_affinity_columns or () sql_bits = [] params = {} i = 0 for column, lookup, value in self.selections(): filter = self._filters_by_key.get(lookup, None) if filter: - sql_bit, param = filter.where_clause(table, column, value, i) + where_clause = filter.where_clause + if column in no_affinity_columns: + where_clause = getattr( + filter, "where_clause_no_affinity", where_clause + ) + sql_bit, param = where_clause(table, column, value, i) sql_bits.append(sql_bit) if param is not None: if not isinstance(param, list): diff --git a/datasette/fixtures.py b/datasette/fixtures.py index bbb14798b6..7d2debddc7 100644 --- a/datasette/fixtures.py +++ b/datasette/fixtures.py @@ -339,6 +339,17 @@ def generate_sortable_rows(num): CREATE VIEW binary_data_view AS SELECT data FROM binary_data; +-- A view with columns calculated by aggregate functions. These have no +-- declared type, see #1671 +CREATE VIEW facetable_by_state AS + SELECT + state, + count(*) AS row_count, + sum(planet_int) AS planet_total, + avg(on_earth) AS avg_on_earth + FROM facetable + GROUP BY state; + """ + "\n".join( [ diff --git a/datasette/views/table.py b/datasette/views/table.py index 91b7ccc284..2ff56f01fb 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -21,7 +21,7 @@ UpsertRowsEvent, ) from datasette.extras import ExtraScope, extra_names_from_request -from datasette.filters import Filters +from datasette.filters import Filters, column_type_has_no_affinity from datasette.plugins import pm from datasette.renderer import apply_column_type_transforms, row_as_dict from datasette.resources import DatabaseResource, TableResource @@ -2341,7 +2341,20 @@ async def _table_filters(datasette, request, database_name, table_name): # Build where clauses from query string arguments filters = Filters(sorted(filter_args)) - where_clauses, params = filters.build_where_clauses(table_name) + no_affinity_columns = set() + if filter_args: + # Expression columns in views (and untyped table columns) have no + # type affinity, so need numeric values to be handled differently + no_affinity_columns = { + column.name + for column in await datasette.get_database( + database_name + ).table_column_details(table_name) + if column_type_has_no_affinity(column.type) + } + where_clauses, params = filters.build_where_clauses( + table_name, no_affinity_columns=no_affinity_columns + ) # Execute filters_from_request plugin hooks - including the default # ones that live in datasette/filters.py diff --git a/docs/changelog.rst b/docs/changelog.rst index 7d92849ac1..4a1c60f102 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -64,6 +64,7 @@ Unreleased - **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. (:issue:`1342`) - **Backwards incompatible:** the ``path_with_replaced_args``, ``fix_path`` and ``append_querystring`` functions 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)``. - ``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``, ``__in`` and ``__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"``. (:issue:`1671`, :issue:`2073`, :issue:`2713`) .. _v1_0_a43: diff --git a/docs/json_api.rst b/docs/json_api.rst index 50ebb6f127..6a2e2963b2 100644 --- a/docs/json_api.rst +++ b/docs/json_api.rst @@ -1444,6 +1444,8 @@ You can filter the data returned by the table based on column values using a que ``?column__exact=value`` or ``?_column=value`` Returns rows where the specified column exactly matches the value. + A value that looks like a number matches numbers as well as text if the column has no declared type, which is the case for a column in a view that is calculated by an expression such as ``count(*)`` or ``sum(amount)``. ``?total=5`` returns rows where ``total`` is the number ``5`` or the text ``"5"``. The same applies to ``__not``, ``__in`` and ``__notin``. + ``?column__not=value`` Returns rows where the column does not match the value. diff --git a/tests/test_filters.py b/tests/test_filters.py index b0a524d195..298992db84 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -1,6 +1,13 @@ import pytest -from datasette.filters import Filters, search_filters, through_filters, where_filters +from datasette.filters import ( + Filters, + column_type_has_no_affinity, + looks_numeric, + search_filters, + through_filters, + where_filters, +) from datasette.utils.asgi import BadRequest, Request @@ -182,6 +189,93 @@ def test_in_filter_invalid_json_array_is_bad_request(lookup, value): filters.build_where_clauses("table") +@pytest.mark.parametrize( + "args,expected_where,expected_params", + [ + # Numeric-looking values are compared as text and as numbers + ( + (("n", "1"),), + ['"n" in (:p0, cast(:p0 as numeric))'], + ["1"], + ), + ( + (("n__not", "1.5"),), + ['"n" not in (:p0, cast(:p0 as numeric))'], + ["1.5"], + ), + ( + (("n__in", "1,dog,-2.5"),), + ["n in (:p0, cast(:p0 as numeric), :p1, :p2, cast(:p2 as numeric))"], + ["1", "dog", "-2.5"], + ), + ( + (("n__notin", "1"),), + ["n not in (:p0, cast(:p0 as numeric))"], + ["1"], + ), + # Other values and other columns are left alone + ((("n", "dog"),), ['"n" = :p0'], ["dog"]), + ((("n", "0x10"),), ['"n" = :p0'], ["0x10"]), + ((("n", "1_000"),), ['"n" = :p0'], ["1_000"]), + ((("n", "nan"),), ['"n" = :p0'], ["nan"]), + ((("other", "1"),), ['"other" = :p0'], ["1"]), + ((("n__contains", "1"),), ['"n" like :p0'], ["%1%"]), + ((("n__gt", "1"),), ['"n" > :p0'], [1]), + ], +) +def test_build_where_no_affinity_columns(args, expected_where, expected_params): + f = Filters(sorted(args)) + sql_bits, actual_params = f.build_where_clauses("table", no_affinity_columns={"n"}) + assert expected_where == sql_bits + assert {f"p{i}": param for i, param in enumerate(expected_params)} == actual_params + + +@pytest.mark.parametrize( + "column_type,expected", + [ + ("", True), + (None, True), + ("BLOB", True), + ("blob", True), + ("INTEGER", False), + ("TEXT", False), + ("VARCHAR(10)", False), + ("REAL", False), + ("NUMERIC", False), + ("DATETIME", False), + ], +) +def test_column_type_has_no_affinity(column_type, expected): + assert column_type_has_no_affinity(column_type) is expected + + +@pytest.mark.parametrize( + "value,expected", + [ + ("5", True), + ("-5", True), + ("+5", True), + ("2.5", True), + (".5", True), + ("5.", True), + ("1e3", True), + ("1.5E-3", True), + ("", False), + ("abc", False), + ("5 ", False), + ("5\n", False), + ("0x10", False), + ("1_000", False), + ("nan", False), + ("inf", False), + (5, False), + (None, False), + ], +) +def test_looks_numeric(value, expected): + assert looks_numeric(value) is expected + + @pytest.mark.asyncio @pytest.mark.parametrize( "qs,expected_status", @@ -195,3 +289,128 @@ def test_in_filter_invalid_json_array_is_bad_request(lookup, value): async def test_in_filter_json_array_status(ds_client, qs, expected_status): response = await ds_client.get("/fixtures/facetable.json?" + qs) assert response.status_code == expected_status + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "qs,expected_states", + [ + # The facetable_by_state view in the fixtures database has three + # columns calculated by aggregate functions, which have no type + # affinity: row_count, planet_total and avg_on_earth. + # Refs #1671, #2073, #2713 + ("row_count=4", ["MI"]), + ("row_count__exact=10", ["CA"]), + ("row_count__not=4", ["CA", "MC"]), + ("row_count__in=1,4", ["MC", "MI"]), + ('row_count__in=["1","4"]', ["MC", "MI"]), + ("row_count__in=[1,4]", ["MC", "MI"]), + ("row_count__notin=10", ["MC", "MI"]), + ("row_count__notin=1,4", ["CA"]), + ("planet_total=2", ["MC"]), + ("planet_total=4&row_count=4", ["MI"]), + # Integers and floating point numbers match each other + ("avg_on_earth=1", ["CA", "MI"]), + ("avg_on_earth=1.0", ["CA", "MI"]), + ("avg_on_earth=0", ["MC"]), + ("avg_on_earth__not=1", ["MC"]), + ("row_count=4.0", ["MI"]), + # A value that is not a number matches nothing + ("row_count=four", []), + # These already worked, because the value is converted in Python + ("row_count__gt=3", ["CA", "MI"]), + ("row_count__lte=4", ["MC", "MI"]), + # state is passed straight through the view and keeps its affinity + ("state=MI", ["MI"]), + ], +) +async def test_filters_against_view_columns_with_no_affinity( + ds_client, qs, expected_states +): + response = await ds_client.get( + "/fixtures/facetable_by_state.json?_sort=state&" + qs + ) + assert response.status_code == 200 + assert [row["state"] for row in response.json()["rows"]] == expected_states + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "column,expected_facet_values", + [ + ("row_count", [(1, 1), (4, 1), (10, 1)]), + ("planet_total", [(2, 1), (4, 1), (10, 1)]), + ("avg_on_earth", [(0.0, 1), (1.0, 2)]), + ], +) +async def test_facet_links_work_for_view_expression_columns( + ds_client, column, expected_facet_values +): + # https://github.com/simonw/datasette/issues/2073 + response = await ds_client.get(f"/fixtures/facetable_by_state.json?_facet={column}") + facet_values = response.json()["facet_results"]["results"][column]["results"] + assert ( + sorted((v["value"], v["count"]) for v in facet_values) == expected_facet_values + ) + for facet_value in facet_values: + path = facet_value["toggle_url"].replace("http://localhost", "") + filtered = (await ds_client.get(path)).json() + assert len(filtered["rows"]) == facet_value["count"] + selected = filtered["facet_results"]["results"][column]["results"] + assert [ + v["selected"] for v in selected if v["value"] == facet_value["value"] + ] == [True] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path,expected_ids", + [ + # Cases the fixtures database has no data for. Expression columns + # in a view can hold numbers that are not whole + ("/data/v.json?score_calc=1.5", [1, 2]), + # ... or text + ("/data/v.json?n_text=1", [2]), + ("/data/v.json?n_text=0", [1, 3]), + ("/data/v.json?label=dog", [3]), + # Text that looks like a different spelling of the same number + # is not matched: '1.0' and '01' are not '1' + ("/data/v.json?code_calc=1", [1]), + ("/data/v.json?code_calc=1.0", [2]), + ("/data/v.json?code_calc=01", [3]), + ("/data/v.json?code_calc__not=1", [2, 3]), + # Table columns declared without a type + ("/data/t.json?untyped=1", [2]), + ("/data/t.json?untyped=dog", [3]), + ("/data/t.json?untyped__not=1", [1, 3]), + ("/data/t.json?untyped_text=1", [1]), + # Table columns with a declared type are not affected + ("/data/t.json?n=1", [2]), + ("/data/t.json?code=1", [1]), + ], +) +async def test_filters_against_untyped_table_columns_and_text(path, expected_ids): + from datasette.app import Datasette + + ds = Datasette() + db = ds.add_memory_database("data") + await db.execute_write_script(""" + create table t ( + id integer primary key, n integer, score real, code text, untyped, + untyped_text + ); + insert into t values (1, 0, 1.5, '1', 0, '1'); + insert into t values (2, 1, 1.5, '2', 1, '1.0'); + insert into t values (3, 0, 2.0, '3', 'dog', '01'); + create view v as select + id, + score * 1 as score_calc, + '' || n as n_text, + '' || untyped_text as code_calc, + case when id = 3 then 'dog' else n end as label + from t; + """) + await ds.invoke_startup() + response = await ds.client.get(path) + assert response.status_code == 200 + assert [row["id"] for row in response.json()["rows"]] == expected_ids diff --git a/tests/test_html.py b/tests/test_html.py index f0e2bbe757..0431c84031 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -279,6 +279,7 @@ async def test_database_page(ds_client): if "catalog-item-view" in li["class"] ) == [ ("/fixtures/binary_data_view", "binary_data_view"), + ("/fixtures/facetable_by_state", "facetable_by_state"), ("/fixtures/paginated_view", "paginated_view"), ("/fixtures/searchable_view", "searchable_view"), ( diff --git a/tests/test_internals_database.py b/tests/test_internals_database.py index bb1634d126..575742b40f 100644 --- a/tests/test_internals_database.py +++ b/tests/test_internals_database.py @@ -481,6 +481,7 @@ async def test_view_names(db): "searchable_view", "searchable_view_configured_by_metadata", "binary_data_view", + "facetable_by_state", ] diff --git a/tests/test_permissions.py b/tests/test_permissions.py index 6efb7b92d3..1b291e85e6 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -178,14 +178,16 @@ async def test_database_list_respects_view_table(): ">names 🔒", ">v 🔒", ] - anon_response_text = (await ds.client.get("/")).text + # ?database=data keeps this to one page of the homepage catalog, however + # many tables and views the fixtures database has + anon_response_text = (await ds.client.get("/?database=data")).text assert "/data/names" not in homepage_item_links(anon_response_text) assert "/data/v" not in homepage_item_links(anon_response_text) for html_fragment in html_fragments: assert html_fragment not in anon_response_text auth_response_text = ( await ds.client.get( - "/", + "/?database=data", cookies={"ds_actor": ds.client.actor_cookie({"id": "root"})}, ) ).text