Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 76 additions & 9 deletions datasette/filters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import math
import re
from typing import ClassVar

from datasette import hookimpl
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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):
Expand All @@ -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))}"
Expand All @@ -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",
Expand Down Expand Up @@ -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):
Expand Down
11 changes: 11 additions & 0 deletions datasette/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
[
Expand Down
17 changes: 15 additions & 2 deletions datasette/views/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 2 additions & 0 deletions docs/json_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading