Show sort arrow on primary key by default

Closes #677. Refs #702.
This commit is contained in:
Simon Willison 2020-03-21 16:57:37 -07:00
commit 2c0e1e09bc
2 changed files with 27 additions and 5 deletions

View file

@ -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 "",

View file

@ -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