From 2c0e1e09bc833c5939c20b937a2ce8ef997c5f5a Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sat, 21 Mar 2020 16:57:37 -0700 Subject: [PATCH] Show sort arrow on primary key by default Closes #677. Refs #702. --- datasette/views/table.py | 21 +++++++++++++++++---- tests/test_html.py | 11 ++++++++++- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/datasette/views/table.py b/datasette/views/table.py index 800cfa5b..b28d6060 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -403,19 +403,21 @@ class TableView(RowTableShared): # Allow for custom sort order sort = special_args.get("_sort") + sort_desc = special_args.get("_sort_desc") + + if sort and sort_desc: + raise DatasetteError("Cannot use _sort and _sort_desc at the same time") + if sort: if sort not in sortable_columns: raise DatasetteError("Cannot sort table by {}".format(sort)) order_by = escape_sqlite(sort) - sort_desc = special_args.get("_sort_desc") + if sort_desc: if sort_desc not in sortable_columns: raise DatasetteError("Cannot sort table by {}".format(sort_desc)) - if sort: - raise DatasetteError("Cannot use _sort and _sort_desc at the same time") - order_by = "{} desc".format(escape_sqlite(sort_desc)) from_sql = "from {table_name} {where}".format( @@ -703,6 +705,8 @@ class TableView(RowTableShared): ) async def extra_template(): + nonlocal sort + display_columns, display_rows = await self.display_columns_and_rows( database, table, @@ -725,6 +729,15 @@ class TableView(RowTableShared): if request.args.get("_where"): for where_text in request.args["_where"]: form_hidden_args.append(("_where", where_text)) + + # if no sort specified AND table has a single primary key, + # set sort to that so arrow is displayed + if not sort and not sort_desc: + if 1 == len(pks): + sort = pks[0] + elif use_rowid: + sort = "rowid" + return { "supports_search": bool(fts_table), "search": search or "", diff --git a/tests/test_html.py b/tests/test_html.py index 823d7c9a..86880cfd 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -462,7 +462,7 @@ def test_table_html_simple_primary_key(app_client): table = Soup(response.body, "html.parser").find("table") assert table["class"] == ["rows-and-columns"] ths = table.findAll("th") - assert "id" == ths[0].find("a").string.strip() + assert "id\xa0▼" == ths[0].find("a").string.strip() for expected_col, th in zip(("content",), ths[1:]): a = th.find("a") assert expected_col == a.string @@ -582,6 +582,15 @@ def test_table_html_no_primary_key(app_client): ] +def test_rowid_sortable_no_primary_key(app_client): + response = app_client.get("/fixtures/no_primary_key") + assert response.status == 200 + table = Soup(response.body, "html.parser").find("table") + assert table["class"] == ["rows-and-columns"] + ths = table.findAll("th") + assert "rowid\xa0▼" == ths[1].find("a").string.strip() + + def test_row_html_no_primary_key(app_client): response = app_client.get("/fixtures/no_primary_key/1") assert response.status == 200