2018-05-13 12:58:28 +00:00
|
|
|
import sqlite3
|
|
|
|
import urllib
|
|
|
|
|
|
|
|
import jinja2
|
2018-05-13 12:44:22 +00:00
|
|
|
from sanic.exceptions import NotFound
|
2018-05-13 12:58:28 +00:00
|
|
|
from sanic.request import RequestParameters
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
from datasette.utils import (
|
|
|
|
Filters,
|
2018-05-18 06:07:45 +00:00
|
|
|
InterruptedError,
|
2018-05-13 12:44:22 +00:00
|
|
|
compound_keys_after_sql,
|
|
|
|
escape_sqlite,
|
|
|
|
filters_should_redirect,
|
|
|
|
is_url,
|
|
|
|
path_from_row_pks,
|
|
|
|
path_with_added_args,
|
2018-05-14 20:42:10 +00:00
|
|
|
path_with_removed_args,
|
2018-05-15 09:34:45 +00:00
|
|
|
path_with_replaced_args,
|
2018-05-13 12:44:22 +00:00
|
|
|
to_css_class,
|
2018-05-18 06:07:45 +00:00
|
|
|
urlsafe_components,
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
2018-05-13 12:58:28 +00:00
|
|
|
|
|
|
|
from .base import BaseView, DatasetteError, ureg
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RowTableShared(BaseView):
|
2018-05-13 12:55:15 +00:00
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
def sortable_columns_for_table(self, name, table, use_rowid):
|
|
|
|
table_metadata = self.table_metadata(name, table)
|
2018-05-13 12:55:15 +00:00
|
|
|
if "sortable_columns" in table_metadata:
|
|
|
|
sortable_columns = set(table_metadata["sortable_columns"])
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
2018-05-13 12:55:15 +00:00
|
|
|
table_info = self.ds.inspect()[name]["tables"].get(table) or {}
|
|
|
|
sortable_columns = set(table_info.get("columns", []))
|
2018-05-13 12:44:22 +00:00
|
|
|
if use_rowid:
|
2018-05-13 12:55:15 +00:00
|
|
|
sortable_columns.add("rowid")
|
2018-05-13 12:44:22 +00:00
|
|
|
return sortable_columns
|
|
|
|
|
2018-05-15 15:52:02 +00:00
|
|
|
async def expand_foreign_keys(self, database, table, column, values):
|
|
|
|
"Returns dict mapping (column, value) -> label"
|
|
|
|
labeled_fks = {}
|
|
|
|
tables_info = self.ds.inspect()[database]["tables"]
|
|
|
|
table_info = tables_info.get(table) or {}
|
|
|
|
if not table_info:
|
|
|
|
return {}
|
|
|
|
foreign_keys = table_info["foreign_keys"]["outgoing"]
|
|
|
|
# Find the foreign_key for this column
|
|
|
|
try:
|
|
|
|
fk = [
|
|
|
|
foreign_key for foreign_key in foreign_keys
|
|
|
|
if foreign_key["column"] == column
|
|
|
|
][0]
|
|
|
|
except IndexError:
|
|
|
|
return {}
|
|
|
|
label_column = (
|
|
|
|
# First look in metadata.json for this foreign key table:
|
|
|
|
self.table_metadata(
|
|
|
|
database, fk["other_table"]
|
|
|
|
).get("label_column")
|
|
|
|
or tables_info.get(fk["other_table"], {}).get("label_column")
|
|
|
|
)
|
|
|
|
if not label_column:
|
|
|
|
return {}
|
|
|
|
labeled_fks = {}
|
|
|
|
sql = '''
|
|
|
|
select {other_column}, {label_column}
|
|
|
|
from {other_table}
|
|
|
|
where {other_column} in ({placeholders})
|
|
|
|
'''.format(
|
|
|
|
other_column=escape_sqlite(fk["other_column"]),
|
|
|
|
label_column=escape_sqlite(label_column),
|
|
|
|
other_table=escape_sqlite(fk["other_table"]),
|
|
|
|
placeholders=", ".join(["?"] * len(set(values))),
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
results = await self.execute(
|
|
|
|
database, sql, list(set(values))
|
|
|
|
)
|
2018-05-18 06:07:45 +00:00
|
|
|
except InterruptedError:
|
2018-05-15 15:52:02 +00:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
for id, value in results:
|
|
|
|
labeled_fks[(fk["column"], id)] = value
|
|
|
|
return labeled_fks
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
async def display_columns_and_rows(
|
|
|
|
self,
|
|
|
|
database,
|
|
|
|
table,
|
|
|
|
description,
|
|
|
|
rows,
|
|
|
|
link_column=False,
|
|
|
|
expand_foreign_keys=True,
|
|
|
|
):
|
2018-05-13 12:44:22 +00:00
|
|
|
"Returns columns, rows for specified table - including fancy foreign key treatment"
|
|
|
|
table_metadata = self.table_metadata(database, table)
|
|
|
|
info = self.ds.inspect()[database]
|
|
|
|
sortable_columns = self.sortable_columns_for_table(database, table, True)
|
2018-05-13 12:55:15 +00:00
|
|
|
columns = [
|
|
|
|
{"name": r[0], "sortable": r[0] in sortable_columns} for r in description
|
|
|
|
]
|
|
|
|
tables = info["tables"]
|
2018-05-13 12:44:22 +00:00
|
|
|
table_info = tables.get(table) or {}
|
2018-05-13 12:55:15 +00:00
|
|
|
pks = table_info.get("primary_keys") or []
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
# Prefetch foreign key resolutions for later expansion:
|
|
|
|
fks = {}
|
|
|
|
labeled_fks = {}
|
|
|
|
if table_info and expand_foreign_keys:
|
2018-05-13 12:55:15 +00:00
|
|
|
foreign_keys = table_info["foreign_keys"]["outgoing"]
|
2018-05-13 12:44:22 +00:00
|
|
|
for fk in foreign_keys:
|
|
|
|
label_column = (
|
|
|
|
# First look in metadata.json definition for this foreign key table:
|
2018-05-13 12:55:15 +00:00
|
|
|
self.table_metadata(database, fk["other_table"]).get("label_column")
|
2018-05-13 12:44:22 +00:00
|
|
|
# Fall back to label_column from .inspect() detection:
|
2018-05-13 12:55:15 +00:00
|
|
|
or tables.get(fk["other_table"], {}).get("label_column")
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
if not label_column:
|
|
|
|
# No label for this FK
|
2018-05-13 12:55:15 +00:00
|
|
|
fks[fk["column"]] = fk["other_table"]
|
2018-05-13 12:44:22 +00:00
|
|
|
continue
|
2018-05-13 12:55:15 +00:00
|
|
|
|
|
|
|
ids_to_lookup = set([row[fk["column"]] for row in rows])
|
2018-05-15 15:00:39 +00:00
|
|
|
sql = '''
|
|
|
|
select {other_column}, {label_column}
|
|
|
|
from {other_table}
|
|
|
|
where {other_column} in ({placeholders})
|
|
|
|
'''.format(
|
|
|
|
other_column=escape_sqlite(fk["other_column"]),
|
|
|
|
label_column=escape_sqlite(label_column),
|
2018-05-13 12:55:15 +00:00
|
|
|
other_table=escape_sqlite(fk["other_table"]),
|
|
|
|
placeholders=", ".join(["?"] * len(ids_to_lookup)),
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
try:
|
2018-05-13 12:55:15 +00:00
|
|
|
results = await self.execute(
|
|
|
|
database, sql, list(set(ids_to_lookup))
|
|
|
|
)
|
2018-05-18 06:07:45 +00:00
|
|
|
except InterruptedError:
|
2018-05-13 12:44:22 +00:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
for id, value in results:
|
2018-05-13 12:55:15 +00:00
|
|
|
labeled_fks[(fk["column"], id)] = (fk["other_table"], value)
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
cell_rows = []
|
|
|
|
for row in rows:
|
|
|
|
cells = []
|
|
|
|
# Unless we are a view, the first column is a link - either to the rowid
|
|
|
|
# or to the simple or compound primary key
|
|
|
|
if link_column:
|
2018-05-13 12:55:15 +00:00
|
|
|
cells.append(
|
|
|
|
{
|
|
|
|
"column": pks[0] if len(pks) == 1 else "Link",
|
|
|
|
"value": jinja2.Markup(
|
|
|
|
'<a href="/{database}/{table}/{flat_pks_quoted}">{flat_pks}</a>'.format(
|
|
|
|
database=database,
|
|
|
|
table=urllib.parse.quote_plus(table),
|
|
|
|
flat_pks=str(
|
|
|
|
jinja2.escape(
|
|
|
|
path_from_row_pks(row, pks, not pks, False)
|
|
|
|
)
|
|
|
|
),
|
|
|
|
flat_pks_quoted=path_from_row_pks(row, pks, not pks),
|
|
|
|
)
|
|
|
|
),
|
|
|
|
}
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
for value, column_dict in zip(row, columns):
|
2018-05-13 12:55:15 +00:00
|
|
|
column = column_dict["name"]
|
2018-05-13 12:44:22 +00:00
|
|
|
if link_column and len(pks) == 1 and column == pks[0]:
|
|
|
|
# If there's a simple primary key, don't repeat the value as it's
|
|
|
|
# already shown in the link column.
|
|
|
|
continue
|
2018-05-13 12:55:15 +00:00
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
if (column, value) in labeled_fks:
|
|
|
|
other_table, label = labeled_fks[(column, value)]
|
|
|
|
display_value = jinja2.Markup(
|
|
|
|
'<a href="/{database}/{table}/{link_id}">{label}</a> <em>{id}</em>'.format(
|
|
|
|
database=database,
|
|
|
|
table=urllib.parse.quote_plus(other_table),
|
|
|
|
link_id=urllib.parse.quote_plus(str(value)),
|
|
|
|
id=str(jinja2.escape(value)),
|
|
|
|
label=str(jinja2.escape(label)),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
elif column in fks:
|
|
|
|
display_value = jinja2.Markup(
|
|
|
|
'<a href="/{database}/{table}/{link_id}">{id}</a>'.format(
|
|
|
|
database=database,
|
|
|
|
table=urllib.parse.quote_plus(fks[column]),
|
|
|
|
link_id=urllib.parse.quote_plus(str(value)),
|
2018-05-13 12:55:15 +00:00
|
|
|
id=str(jinja2.escape(value)),
|
|
|
|
)
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
elif value is None:
|
2018-05-13 12:55:15 +00:00
|
|
|
display_value = jinja2.Markup(" ")
|
2018-05-13 12:44:22 +00:00
|
|
|
elif is_url(str(value).strip()):
|
|
|
|
display_value = jinja2.Markup(
|
|
|
|
'<a href="{url}">{url}</a>'.format(
|
|
|
|
url=jinja2.escape(value.strip())
|
|
|
|
)
|
|
|
|
)
|
2018-05-13 12:55:15 +00:00
|
|
|
elif column in table_metadata.get("units", {}) and value != "":
|
2018-05-13 12:44:22 +00:00
|
|
|
# Interpret units using pint
|
2018-05-13 12:55:15 +00:00
|
|
|
value = value * ureg(table_metadata["units"][column])
|
2018-05-13 12:44:22 +00:00
|
|
|
# Pint uses floating point which sometimes introduces errors in the compact
|
|
|
|
# representation, which we have to round off to avoid ugliness. In the vast
|
|
|
|
# majority of cases this rounding will be inconsequential. I hope.
|
|
|
|
value = round(value.to_compact(), 6)
|
2018-05-13 12:55:15 +00:00
|
|
|
display_value = jinja2.Markup(
|
|
|
|
"{:~P}".format(value).replace(" ", " ")
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
display_value = str(value)
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
cells.append({"column": column, "value": display_value})
|
2018-05-13 12:44:22 +00:00
|
|
|
cell_rows.append(cells)
|
|
|
|
|
|
|
|
if link_column:
|
|
|
|
# Add the link column header.
|
|
|
|
# If it's a simple primary key, we have to remove and re-add that column name at
|
|
|
|
# the beginning of the header row.
|
|
|
|
if len(pks) == 1:
|
2018-05-13 12:55:15 +00:00
|
|
|
columns = [col for col in columns if col["name"] != pks[0]]
|
2018-05-13 12:44:22 +00:00
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
columns = [
|
|
|
|
{"name": pks[0] if len(pks) == 1 else "Link", "sortable": len(pks) == 1}
|
|
|
|
] + columns
|
2018-05-13 12:44:22 +00:00
|
|
|
return columns, cell_rows
|
|
|
|
|
|
|
|
|
|
|
|
class TableView(RowTableShared):
|
2018-05-13 12:55:15 +00:00
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
async def data(self, request, name, hash, table):
|
|
|
|
table = urllib.parse.unquote_plus(table)
|
|
|
|
canned_query = self.ds.get_canned_query(name, table)
|
|
|
|
if canned_query is not None:
|
2018-05-13 12:55:15 +00:00
|
|
|
return await self.custom_sql(
|
|
|
|
request,
|
|
|
|
name,
|
|
|
|
hash,
|
|
|
|
canned_query["sql"],
|
|
|
|
editable=False,
|
|
|
|
canned_query=table,
|
|
|
|
)
|
|
|
|
|
|
|
|
is_view = bool(
|
|
|
|
list(
|
|
|
|
await self.execute(
|
|
|
|
name,
|
|
|
|
"SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n",
|
|
|
|
{"n": table},
|
|
|
|
)
|
2018-05-15 13:23:20 +00:00
|
|
|
)[0][0]
|
2018-05-13 12:55:15 +00:00
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
view_definition = None
|
|
|
|
table_definition = None
|
|
|
|
if is_view:
|
2018-05-13 12:55:15 +00:00
|
|
|
view_definition = list(
|
|
|
|
await self.execute(
|
|
|
|
name,
|
|
|
|
'select sql from sqlite_master where name = :n and type="view"',
|
|
|
|
{"n": table},
|
|
|
|
)
|
2018-05-15 13:23:20 +00:00
|
|
|
)[0][0]
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
2018-05-13 12:55:15 +00:00
|
|
|
table_definition_rows = list(
|
|
|
|
await self.execute(
|
|
|
|
name,
|
|
|
|
'select sql from sqlite_master where name = :n and type="table"',
|
|
|
|
{"n": table},
|
|
|
|
)
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
if not table_definition_rows:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise NotFound("Table not found: {}".format(table))
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
table_definition = table_definition_rows[0][0]
|
|
|
|
info = self.ds.inspect()
|
2018-05-13 12:55:15 +00:00
|
|
|
table_info = info[name]["tables"].get(table) or {}
|
|
|
|
pks = table_info.get("primary_keys") or []
|
2018-05-13 12:44:22 +00:00
|
|
|
use_rowid = not pks and not is_view
|
|
|
|
if use_rowid:
|
2018-05-13 12:55:15 +00:00
|
|
|
select = "rowid, *"
|
|
|
|
order_by = "rowid"
|
|
|
|
order_by_pks = "rowid"
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
2018-05-13 12:55:15 +00:00
|
|
|
select = "*"
|
|
|
|
order_by_pks = ", ".join([escape_sqlite(pk) for pk in pks])
|
2018-05-13 12:44:22 +00:00
|
|
|
order_by = order_by_pks
|
|
|
|
|
|
|
|
if is_view:
|
2018-05-13 12:55:15 +00:00
|
|
|
order_by = ""
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
# We roll our own query_string decoder because by default Sanic
|
|
|
|
# drops anything with an empty value e.g. ?name__exact=
|
|
|
|
args = RequestParameters(
|
|
|
|
urllib.parse.parse_qs(request.query_string, keep_blank_values=True)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Special args start with _ and do not contain a __
|
|
|
|
# That's so if there is a column that starts with _
|
|
|
|
# it can still be queried using ?_col__exact=blah
|
|
|
|
special_args = {}
|
|
|
|
special_args_lists = {}
|
|
|
|
other_args = {}
|
|
|
|
for key, value in args.items():
|
2018-05-13 12:55:15 +00:00
|
|
|
if key.startswith("_") and "__" not in key:
|
2018-05-13 12:44:22 +00:00
|
|
|
special_args[key] = value[0]
|
|
|
|
special_args_lists[key] = value
|
|
|
|
else:
|
|
|
|
other_args[key] = value[0]
|
|
|
|
|
|
|
|
# Handle ?_filter_column and redirect, if present
|
|
|
|
redirect_params = filters_should_redirect(special_args)
|
|
|
|
if redirect_params:
|
|
|
|
return self.redirect(
|
|
|
|
request,
|
|
|
|
path_with_added_args(request, redirect_params),
|
2018-05-13 12:55:15 +00:00
|
|
|
forward_querystring=False,
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# Spot ?_sort_by_desc and redirect to _sort_desc=(_sort)
|
2018-05-13 12:55:15 +00:00
|
|
|
if "_sort_by_desc" in special_args:
|
2018-05-13 12:44:22 +00:00
|
|
|
return self.redirect(
|
|
|
|
request,
|
2018-05-13 12:55:15 +00:00
|
|
|
path_with_added_args(
|
|
|
|
request,
|
|
|
|
{
|
|
|
|
"_sort_desc": special_args.get("_sort"),
|
|
|
|
"_sort_by_desc": None,
|
|
|
|
"_sort": None,
|
|
|
|
},
|
|
|
|
),
|
|
|
|
forward_querystring=False,
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
table_metadata = self.table_metadata(name, table)
|
2018-05-13 12:55:15 +00:00
|
|
|
units = table_metadata.get("units", {})
|
2018-05-13 12:44:22 +00:00
|
|
|
filters = Filters(sorted(other_args.items()), units, ureg)
|
|
|
|
where_clauses, params = filters.build_where_clauses()
|
|
|
|
|
|
|
|
# _search support:
|
2018-05-13 12:55:15 +00:00
|
|
|
fts_table = info[name]["tables"].get(table, {}).get("fts_table")
|
2018-05-13 12:44:22 +00:00
|
|
|
search_args = dict(
|
2018-05-13 12:55:15 +00:00
|
|
|
pair for pair in special_args.items() if pair[0].startswith("_search")
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
search_descriptions = []
|
2018-05-13 12:55:15 +00:00
|
|
|
search = ""
|
2018-05-13 12:44:22 +00:00
|
|
|
if fts_table and search_args:
|
2018-05-13 12:55:15 +00:00
|
|
|
if "_search" in search_args:
|
2018-05-13 12:44:22 +00:00
|
|
|
# Simple ?_search=xxx
|
2018-05-13 12:55:15 +00:00
|
|
|
search = search_args["_search"]
|
2018-05-13 12:44:22 +00:00
|
|
|
where_clauses.append(
|
2018-05-15 15:00:39 +00:00
|
|
|
"rowid in (select rowid from {fts_table} where {fts_table} match :search)".format(
|
|
|
|
fts_table=escape_sqlite(fts_table),
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
search_descriptions.append('search matches "{}"'.format(search))
|
2018-05-13 12:55:15 +00:00
|
|
|
params["search"] = search
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
# More complex: search against specific columns
|
2018-05-13 12:55:15 +00:00
|
|
|
valid_columns = set(info[name]["tables"][fts_table]["columns"])
|
2018-05-13 12:44:22 +00:00
|
|
|
for i, (key, search_text) in enumerate(search_args.items()):
|
2018-05-13 12:55:15 +00:00
|
|
|
search_col = key.split("_search_", 1)[1]
|
2018-05-13 12:44:22 +00:00
|
|
|
if search_col not in valid_columns:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise DatasetteError("Cannot search by that column", status=400)
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
where_clauses.append(
|
2018-05-15 15:00:39 +00:00
|
|
|
"rowid in (select rowid from {fts_table} where {search_col} match :search_{i})".format(
|
|
|
|
fts_table=escape_sqlite(fts_table),
|
|
|
|
search_col=escape_sqlite(search_col),
|
|
|
|
i=i
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
search_descriptions.append(
|
2018-05-13 12:55:15 +00:00
|
|
|
'search column "{}" matches "{}"'.format(
|
|
|
|
search_col, search_text
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
2018-05-13 12:55:15 +00:00
|
|
|
params["search_{}".format(i)] = search_text
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
table_rows_count = None
|
|
|
|
sortable_columns = set()
|
|
|
|
if not is_view:
|
2018-05-13 12:55:15 +00:00
|
|
|
table_rows_count = table_info["count"]
|
2018-05-13 12:44:22 +00:00
|
|
|
sortable_columns = self.sortable_columns_for_table(name, table, use_rowid)
|
|
|
|
|
|
|
|
# Allow for custom sort order
|
2018-05-13 12:55:15 +00:00
|
|
|
sort = special_args.get("_sort")
|
2018-05-13 12:44:22 +00:00
|
|
|
if sort:
|
|
|
|
if sort not in sortable_columns:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise DatasetteError("Cannot sort table by {}".format(sort))
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
order_by = escape_sqlite(sort)
|
2018-05-13 12:55:15 +00:00
|
|
|
sort_desc = special_args.get("_sort_desc")
|
2018-05-13 12:44:22 +00:00
|
|
|
if sort_desc:
|
|
|
|
if sort_desc not in sortable_columns:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise DatasetteError("Cannot sort table by {}".format(sort_desc))
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
if sort:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise DatasetteError("Cannot use _sort and _sort_desc at the same time")
|
|
|
|
|
|
|
|
order_by = "{} desc".format(escape_sqlite(sort_desc))
|
2018-05-13 12:44:22 +00:00
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
from_sql = "from {table_name} {where}".format(
|
2018-05-13 12:44:22 +00:00
|
|
|
table_name=escape_sqlite(table),
|
|
|
|
where=(
|
2018-05-13 12:55:15 +00:00
|
|
|
"where {} ".format(" and ".join(where_clauses))
|
|
|
|
) if where_clauses else "",
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
2018-05-18 06:07:45 +00:00
|
|
|
# Store current params and where_clauses for later:
|
|
|
|
from_sql_params = dict(**params)
|
|
|
|
from_sql_where_clauses = where_clauses[:]
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
count_sql = "select count(*) {}".format(from_sql)
|
2018-05-13 12:44:22 +00:00
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
_next = special_args.get("_next")
|
|
|
|
offset = ""
|
2018-05-13 12:44:22 +00:00
|
|
|
if _next:
|
|
|
|
if is_view:
|
|
|
|
# _next is an offset
|
2018-05-13 12:55:15 +00:00
|
|
|
offset = " offset {}".format(int(_next))
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
components = urlsafe_components(_next)
|
|
|
|
# If a sort order is applied, the first of these is the sort value
|
|
|
|
if sort or sort_desc:
|
|
|
|
sort_value = components[0]
|
|
|
|
# Special case for if non-urlencoded first token was $null
|
2018-05-13 12:55:15 +00:00
|
|
|
if _next.split(",")[0] == "$null":
|
2018-05-13 12:44:22 +00:00
|
|
|
sort_value = None
|
|
|
|
components = components[1:]
|
|
|
|
|
|
|
|
# Figure out the SQL for next-based-on-primary-key first
|
|
|
|
next_by_pk_clauses = []
|
|
|
|
if use_rowid:
|
2018-05-13 12:55:15 +00:00
|
|
|
next_by_pk_clauses.append("rowid > :p{}".format(len(params)))
|
|
|
|
params["p{}".format(len(params))] = components[0]
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
# Apply the tie-breaker based on primary keys
|
|
|
|
if len(components) == len(pks):
|
|
|
|
param_len = len(params)
|
2018-05-13 12:55:15 +00:00
|
|
|
next_by_pk_clauses.append(
|
|
|
|
compound_keys_after_sql(pks, param_len)
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
for i, pk_value in enumerate(components):
|
2018-05-13 12:55:15 +00:00
|
|
|
params["p{}".format(param_len + i)] = pk_value
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
# Now add the sort SQL, which may incorporate next_by_pk_clauses
|
|
|
|
if sort or sort_desc:
|
|
|
|
if sort_value is None:
|
|
|
|
if sort_desc:
|
|
|
|
# Just items where column is null ordered by pk
|
|
|
|
where_clauses.append(
|
2018-05-13 12:55:15 +00:00
|
|
|
"({column} is null and {next_clauses})".format(
|
2018-05-13 12:44:22 +00:00
|
|
|
column=escape_sqlite(sort_desc),
|
2018-05-13 12:55:15 +00:00
|
|
|
next_clauses=" and ".join(next_by_pk_clauses),
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
where_clauses.append(
|
2018-05-13 12:55:15 +00:00
|
|
|
"({column} is not null or ({column} is null and {next_clauses}))".format(
|
2018-05-13 12:44:22 +00:00
|
|
|
column=escape_sqlite(sort),
|
2018-05-13 12:55:15 +00:00
|
|
|
next_clauses=" and ".join(next_by_pk_clauses),
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
where_clauses.append(
|
2018-05-13 12:55:15 +00:00
|
|
|
"({column} {op} :p{p}{extra_desc_only} or ({column} = :p{p} and {next_clauses}))".format(
|
2018-05-13 12:44:22 +00:00
|
|
|
column=escape_sqlite(sort or sort_desc),
|
2018-05-13 12:55:15 +00:00
|
|
|
op=">" if sort else "<",
|
2018-05-13 12:44:22 +00:00
|
|
|
p=len(params),
|
2018-05-13 12:55:15 +00:00
|
|
|
extra_desc_only="" if sort else " or {column2} is null".format(
|
|
|
|
column2=escape_sqlite(sort or sort_desc)
|
2018-05-13 12:44:22 +00:00
|
|
|
),
|
2018-05-13 12:55:15 +00:00
|
|
|
next_clauses=" and ".join(next_by_pk_clauses),
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
)
|
2018-05-13 12:55:15 +00:00
|
|
|
params["p{}".format(len(params))] = sort_value
|
|
|
|
order_by = "{}, {}".format(order_by, order_by_pks)
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
where_clauses.extend(next_by_pk_clauses)
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
where_clause = ""
|
2018-05-13 12:44:22 +00:00
|
|
|
if where_clauses:
|
2018-05-13 12:55:15 +00:00
|
|
|
where_clause = "where {} ".format(" and ".join(where_clauses))
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
if order_by:
|
2018-05-13 12:55:15 +00:00
|
|
|
order_by = "order by {} ".format(order_by)
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
# _group_count=col1&_group_count=col2
|
2018-05-13 12:55:15 +00:00
|
|
|
group_count = special_args_lists.get("_group_count") or []
|
2018-05-13 12:44:22 +00:00
|
|
|
if group_count:
|
|
|
|
sql = 'select {group_cols}, count(*) as "count" from {table_name} {where} group by {group_cols} order by "count" desc limit 100'.format(
|
2018-05-13 12:55:15 +00:00
|
|
|
group_cols=", ".join(
|
|
|
|
'"{}"'.format(group_count_col) for group_count_col in group_count
|
|
|
|
),
|
2018-05-13 12:44:22 +00:00
|
|
|
table_name=escape_sqlite(table),
|
|
|
|
where=where_clause,
|
|
|
|
)
|
|
|
|
return await self.custom_sql(request, name, hash, sql, editable=True)
|
|
|
|
|
|
|
|
extra_args = {}
|
2018-05-20 17:01:49 +00:00
|
|
|
# Handle ?_size=500
|
2018-05-13 12:55:15 +00:00
|
|
|
page_size = request.raw_args.get("_size")
|
2018-05-13 12:44:22 +00:00
|
|
|
if page_size:
|
2018-05-13 12:55:15 +00:00
|
|
|
if page_size == "max":
|
2018-05-13 12:44:22 +00:00
|
|
|
page_size = self.max_returned_rows
|
|
|
|
try:
|
|
|
|
page_size = int(page_size)
|
|
|
|
if page_size < 0:
|
|
|
|
raise ValueError
|
2018-05-13 12:55:15 +00:00
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
except ValueError:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise DatasetteError("_size must be a positive integer", status=400)
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
if page_size > self.max_returned_rows:
|
|
|
|
raise DatasetteError(
|
2018-05-13 12:55:15 +00:00
|
|
|
"_size must be <= {}".format(self.max_returned_rows), status=400
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
2018-05-13 12:55:15 +00:00
|
|
|
|
|
|
|
extra_args["page_size"] = page_size
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
page_size = self.page_size
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
sql = "select {select} from {table_name} {where}{order_by}limit {limit}{offset}".format(
|
2018-05-13 12:44:22 +00:00
|
|
|
select=select,
|
|
|
|
table_name=escape_sqlite(table),
|
|
|
|
where=where_clause,
|
|
|
|
order_by=order_by,
|
|
|
|
limit=page_size + 1,
|
|
|
|
offset=offset,
|
|
|
|
)
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
if request.raw_args.get("_timelimit"):
|
|
|
|
extra_args["custom_time_limit"] = int(request.raw_args["_timelimit"])
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
rows, truncated, description = await self.execute(
|
|
|
|
name, sql, params, truncate=True, **extra_args
|
|
|
|
)
|
|
|
|
|
|
|
|
# facets support
|
2018-05-20 17:01:49 +00:00
|
|
|
facet_size = self.ds.config["default_facet_size"]
|
2018-05-16 15:15:23 +00:00
|
|
|
metadata_facets = table_metadata.get("facets", [])
|
|
|
|
facets = metadata_facets[:]
|
2018-05-13 12:44:22 +00:00
|
|
|
try:
|
2018-05-16 15:15:23 +00:00
|
|
|
facets.extend(request.args["_facet"])
|
2018-05-13 12:44:22 +00:00
|
|
|
except KeyError:
|
2018-05-16 15:15:23 +00:00
|
|
|
pass
|
2018-05-13 12:44:22 +00:00
|
|
|
facet_results = {}
|
2018-05-18 06:07:45 +00:00
|
|
|
facets_timed_out = []
|
2018-05-13 12:44:22 +00:00
|
|
|
for column in facets:
|
2018-05-13 12:55:15 +00:00
|
|
|
facet_sql = """
|
2018-05-13 12:44:22 +00:00
|
|
|
select {col} as value, count(*) as count
|
2018-05-14 22:19:43 +00:00
|
|
|
{from_sql} {and_or_where} {col} is not null
|
2018-05-15 09:50:27 +00:00
|
|
|
group by {col} order by count desc limit {limit}
|
2018-05-13 12:55:15 +00:00
|
|
|
""".format(
|
2018-05-14 22:19:43 +00:00
|
|
|
col=escape_sqlite(column),
|
|
|
|
from_sql=from_sql,
|
2018-05-18 06:07:45 +00:00
|
|
|
and_or_where='and' if where_clause else 'where',
|
2018-05-18 05:08:26 +00:00
|
|
|
limit=facet_size+1,
|
2018-05-13 12:55:15 +00:00
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
try:
|
|
|
|
facet_rows = await self.execute(
|
2018-05-16 05:06:05 +00:00
|
|
|
name, facet_sql, params,
|
2018-05-18 05:08:26 +00:00
|
|
|
truncate=False,
|
2018-05-20 17:01:49 +00:00
|
|
|
custom_time_limit=self.ds.config["facet_time_limit_ms"],
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
2018-05-16 05:06:05 +00:00
|
|
|
facet_results_values = []
|
2018-05-15 09:50:27 +00:00
|
|
|
facet_results[column] = {
|
|
|
|
"name": column,
|
2018-05-16 05:06:05 +00:00
|
|
|
"results": facet_results_values,
|
2018-05-18 05:08:26 +00:00
|
|
|
"truncated": len(facet_rows) > facet_size,
|
2018-05-15 09:50:27 +00:00
|
|
|
}
|
2018-05-18 05:08:26 +00:00
|
|
|
facet_rows = facet_rows[:facet_size]
|
2018-05-15 15:52:02 +00:00
|
|
|
# Attempt to expand foreign keys into labels
|
|
|
|
values = [row["value"] for row in facet_rows]
|
2018-05-16 05:06:05 +00:00
|
|
|
expanded = (await self.expand_foreign_keys(
|
|
|
|
name, table, column, values
|
|
|
|
))
|
2018-05-15 15:52:02 +00:00
|
|
|
for row in facet_rows:
|
2018-05-14 21:33:24 +00:00
|
|
|
selected = str(other_args.get(column)) == str(row["value"])
|
2018-05-14 20:42:10 +00:00
|
|
|
if selected:
|
|
|
|
toggle_path = path_with_removed_args(
|
2018-05-15 10:19:09 +00:00
|
|
|
request, {column: str(row["value"])}
|
2018-05-14 20:42:10 +00:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
toggle_path = path_with_added_args(
|
|
|
|
request, {column: row["value"]}
|
|
|
|
)
|
2018-05-16 05:06:05 +00:00
|
|
|
facet_results_values.append({
|
2018-05-13 12:55:15 +00:00
|
|
|
"value": row["value"],
|
2018-05-15 15:52:02 +00:00
|
|
|
"label": expanded.get(
|
|
|
|
(column, row["value"]),
|
|
|
|
row["value"]
|
|
|
|
),
|
2018-05-13 12:55:15 +00:00
|
|
|
"count": row["count"],
|
|
|
|
"toggle_url": urllib.parse.urljoin(
|
2018-05-14 20:42:10 +00:00
|
|
|
request.url, toggle_path
|
2018-05-13 12:55:15 +00:00
|
|
|
),
|
2018-05-14 20:42:10 +00:00
|
|
|
"selected": selected,
|
|
|
|
})
|
2018-05-18 06:07:45 +00:00
|
|
|
except InterruptedError:
|
|
|
|
facets_timed_out.append(column)
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
columns = [r[0] for r in description]
|
|
|
|
rows = list(rows)
|
|
|
|
|
|
|
|
filter_columns = columns[:]
|
2018-05-13 12:55:15 +00:00
|
|
|
if use_rowid and filter_columns[0] == "rowid":
|
2018-05-13 12:44:22 +00:00
|
|
|
filter_columns = filter_columns[1:]
|
|
|
|
|
|
|
|
# Pagination next link
|
|
|
|
next_value = None
|
|
|
|
next_url = None
|
|
|
|
if len(rows) > page_size and page_size > 0:
|
|
|
|
if is_view:
|
|
|
|
next_value = int(_next or 0) + page_size
|
|
|
|
else:
|
|
|
|
next_value = path_from_row_pks(rows[-2], pks, use_rowid)
|
|
|
|
# If there's a sort or sort_desc, add that value as a prefix
|
|
|
|
if (sort or sort_desc) and not is_view:
|
|
|
|
prefix = rows[-2][sort or sort_desc]
|
|
|
|
if prefix is None:
|
2018-05-13 12:55:15 +00:00
|
|
|
prefix = "$null"
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
|
|
|
prefix = urllib.parse.quote_plus(str(prefix))
|
2018-05-13 12:55:15 +00:00
|
|
|
next_value = "{},{}".format(prefix, next_value)
|
|
|
|
added_args = {"_next": next_value}
|
2018-05-13 12:44:22 +00:00
|
|
|
if sort:
|
2018-05-13 12:55:15 +00:00
|
|
|
added_args["_sort"] = sort
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
2018-05-13 12:55:15 +00:00
|
|
|
added_args["_sort_desc"] = sort_desc
|
2018-05-13 12:44:22 +00:00
|
|
|
else:
|
2018-05-13 12:55:15 +00:00
|
|
|
added_args = {"_next": next_value}
|
|
|
|
next_url = urllib.parse.urljoin(
|
2018-05-15 09:34:45 +00:00
|
|
|
request.url, path_with_replaced_args(request, added_args)
|
2018-05-13 12:55:15 +00:00
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
rows = rows[:page_size]
|
|
|
|
|
|
|
|
# Number of filtered rows in whole set:
|
|
|
|
filtered_table_rows_count = None
|
|
|
|
if count_sql:
|
|
|
|
try:
|
2018-05-18 06:07:45 +00:00
|
|
|
count_rows = list(await self.execute(
|
|
|
|
name, count_sql, from_sql_params
|
|
|
|
))
|
2018-05-13 12:44:22 +00:00
|
|
|
filtered_table_rows_count = count_rows[0][0]
|
2018-05-18 06:07:45 +00:00
|
|
|
except InterruptedError:
|
2018-05-13 12:44:22 +00:00
|
|
|
pass
|
|
|
|
|
2018-05-14 22:09:42 +00:00
|
|
|
# Detect suggested facets
|
|
|
|
suggested_facets = []
|
|
|
|
for facet_column in columns:
|
|
|
|
if facet_column in facets:
|
|
|
|
continue
|
2018-05-14 22:19:43 +00:00
|
|
|
suggested_facet_sql = '''
|
|
|
|
select distinct {column} {from_sql}
|
|
|
|
{and_or_where} {column} is not null
|
|
|
|
limit {limit}
|
|
|
|
'''.format(
|
2018-05-14 22:09:42 +00:00
|
|
|
column=escape_sqlite(facet_column),
|
|
|
|
from_sql=from_sql,
|
2018-05-18 06:07:45 +00:00
|
|
|
and_or_where='and' if from_sql_where_clauses else 'where',
|
2018-05-18 05:08:26 +00:00
|
|
|
limit=facet_size+1
|
2018-05-14 22:09:42 +00:00
|
|
|
)
|
|
|
|
distinct_values = None
|
|
|
|
try:
|
|
|
|
distinct_values = await self.execute(
|
2018-05-18 06:07:45 +00:00
|
|
|
name, suggested_facet_sql, from_sql_params,
|
2018-05-18 05:08:26 +00:00
|
|
|
truncate=False,
|
2018-05-20 17:01:49 +00:00
|
|
|
custom_time_limit=self.ds.config["facet_suggest_time_limit_ms"],
|
2018-05-14 22:09:42 +00:00
|
|
|
)
|
2018-05-15 03:05:10 +00:00
|
|
|
num_distinct_values = len(distinct_values)
|
2018-05-14 22:09:42 +00:00
|
|
|
if (
|
2018-05-15 03:05:10 +00:00
|
|
|
num_distinct_values and
|
|
|
|
num_distinct_values > 1 and
|
2018-05-18 05:08:26 +00:00
|
|
|
num_distinct_values <= facet_size and
|
2018-05-15 03:05:10 +00:00
|
|
|
num_distinct_values < filtered_table_rows_count
|
2018-05-14 22:09:42 +00:00
|
|
|
):
|
|
|
|
suggested_facets.append({
|
|
|
|
'name': facet_column,
|
|
|
|
'toggle_url': path_with_added_args(
|
|
|
|
request, {'_facet': facet_column}
|
|
|
|
),
|
|
|
|
})
|
2018-05-18 06:07:45 +00:00
|
|
|
except InterruptedError:
|
2018-05-14 22:09:42 +00:00
|
|
|
pass
|
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
# human_description_en combines filters AND search, if provided
|
|
|
|
human_description_en = filters.human_description_en(extra=search_descriptions)
|
|
|
|
|
|
|
|
if sort or sort_desc:
|
2018-05-13 12:55:15 +00:00
|
|
|
sorted_by = "sorted by {}{}".format(
|
|
|
|
(sort or sort_desc), " descending" if sort_desc else ""
|
|
|
|
)
|
|
|
|
human_description_en = " ".join(
|
|
|
|
[b for b in [human_description_en, sorted_by] if b]
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
async def extra_template():
|
|
|
|
display_columns, display_rows = await self.display_columns_and_rows(
|
2018-05-13 12:55:15 +00:00
|
|
|
name,
|
|
|
|
table,
|
|
|
|
description,
|
|
|
|
rows,
|
|
|
|
link_column=not is_view,
|
|
|
|
expand_foreign_keys=True,
|
|
|
|
)
|
|
|
|
metadata = self.ds.metadata.get("databases", {}).get(name, {}).get(
|
|
|
|
"tables", {}
|
|
|
|
).get(
|
|
|
|
table, {}
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
self.ds.update_with_inherited_metadata(metadata)
|
|
|
|
return {
|
2018-05-13 12:55:15 +00:00
|
|
|
"database_hash": hash,
|
|
|
|
"supports_search": bool(fts_table),
|
|
|
|
"search": search or "",
|
|
|
|
"use_rowid": use_rowid,
|
|
|
|
"filters": filters,
|
|
|
|
"display_columns": display_columns,
|
|
|
|
"filter_columns": filter_columns,
|
|
|
|
"display_rows": display_rows,
|
2018-05-18 06:07:45 +00:00
|
|
|
"facets_timed_out": facets_timed_out,
|
2018-05-16 05:06:05 +00:00
|
|
|
"sorted_facet_results": sorted(
|
|
|
|
facet_results.values(),
|
2018-05-16 14:43:13 +00:00
|
|
|
key=lambda f: (len(f["results"]), f["name"]),
|
2018-05-16 05:06:05 +00:00
|
|
|
reverse=True
|
|
|
|
),
|
2018-05-16 15:15:23 +00:00
|
|
|
"facet_hideable": lambda facet: facet not in metadata_facets,
|
2018-05-13 12:55:15 +00:00
|
|
|
"is_sortable": any(c["sortable"] for c in display_columns),
|
2018-05-15 09:34:45 +00:00
|
|
|
"path_with_replaced_args": path_with_replaced_args,
|
2018-05-15 10:11:52 +00:00
|
|
|
"path_with_removed_args": path_with_removed_args,
|
2018-05-13 12:55:15 +00:00
|
|
|
"request": request,
|
|
|
|
"sort": sort,
|
|
|
|
"sort_desc": sort_desc,
|
|
|
|
"disable_sort": is_view,
|
|
|
|
"custom_rows_and_columns_templates": [
|
|
|
|
"_rows_and_columns-{}-{}.html".format(
|
|
|
|
to_css_class(name), to_css_class(table)
|
|
|
|
),
|
|
|
|
"_rows_and_columns-table-{}-{}.html".format(
|
|
|
|
to_css_class(name), to_css_class(table)
|
|
|
|
),
|
|
|
|
"_rows_and_columns.html",
|
2018-05-13 12:44:22 +00:00
|
|
|
],
|
2018-05-13 12:55:15 +00:00
|
|
|
"metadata": metadata,
|
2018-05-13 12:44:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2018-05-13 12:55:15 +00:00
|
|
|
"database": name,
|
|
|
|
"table": table,
|
|
|
|
"is_view": is_view,
|
|
|
|
"view_definition": view_definition,
|
|
|
|
"table_definition": table_definition,
|
|
|
|
"human_description_en": human_description_en,
|
|
|
|
"rows": rows[:page_size],
|
|
|
|
"truncated": truncated,
|
|
|
|
"table_rows_count": table_rows_count,
|
|
|
|
"filtered_table_rows_count": filtered_table_rows_count,
|
|
|
|
"columns": columns,
|
|
|
|
"primary_keys": pks,
|
|
|
|
"units": units,
|
|
|
|
"query": {"sql": sql, "params": params},
|
|
|
|
"facet_results": facet_results,
|
2018-05-14 22:09:42 +00:00
|
|
|
"suggested_facets": suggested_facets,
|
2018-05-13 12:55:15 +00:00
|
|
|
"next": next_value and str(next_value) or None,
|
|
|
|
"next_url": next_url,
|
2018-05-13 12:44:22 +00:00
|
|
|
}, extra_template, (
|
2018-05-13 12:55:15 +00:00
|
|
|
"table-{}-{}.html".format(to_css_class(name), to_css_class(table)),
|
|
|
|
"table.html",
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class RowView(RowTableShared):
|
2018-05-13 12:55:15 +00:00
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
async def data(self, request, name, hash, table, pk_path):
|
|
|
|
table = urllib.parse.unquote_plus(table)
|
|
|
|
pk_values = urlsafe_components(pk_path)
|
|
|
|
info = self.ds.inspect()[name]
|
2018-05-13 12:55:15 +00:00
|
|
|
table_info = info["tables"].get(table) or {}
|
|
|
|
pks = table_info.get("primary_keys") or []
|
2018-05-13 12:44:22 +00:00
|
|
|
use_rowid = not pks
|
2018-05-13 12:55:15 +00:00
|
|
|
select = "*"
|
2018-05-13 12:44:22 +00:00
|
|
|
if use_rowid:
|
2018-05-13 12:55:15 +00:00
|
|
|
select = "rowid, *"
|
|
|
|
pks = ["rowid"]
|
|
|
|
wheres = ['"{}"=:p{}'.format(pk, i) for i, pk in enumerate(pks)]
|
|
|
|
sql = 'select {} from "{}" where {}'.format(select, table, " AND ".join(wheres))
|
2018-05-13 12:44:22 +00:00
|
|
|
params = {}
|
|
|
|
for i, pk_value in enumerate(pk_values):
|
2018-05-13 12:55:15 +00:00
|
|
|
params["p{}".format(i)] = pk_value
|
2018-05-13 12:44:22 +00:00
|
|
|
# rows, truncated, description = await self.execute(name, sql, params, truncate=True)
|
2018-05-13 12:55:15 +00:00
|
|
|
rows, truncated, description = await self.execute(
|
|
|
|
name, sql, params, truncate=True
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
columns = [r[0] for r in description]
|
|
|
|
rows = list(rows)
|
|
|
|
if not rows:
|
2018-05-13 12:55:15 +00:00
|
|
|
raise NotFound("Record not found: {}".format(pk_values))
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
async def template_data():
|
|
|
|
display_columns, display_rows = await self.display_columns_and_rows(
|
2018-05-13 12:55:15 +00:00
|
|
|
name,
|
|
|
|
table,
|
|
|
|
description,
|
|
|
|
rows,
|
|
|
|
link_column=False,
|
|
|
|
expand_foreign_keys=True,
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
for column in display_columns:
|
2018-05-13 12:55:15 +00:00
|
|
|
column["sortable"] = False
|
2018-05-13 12:44:22 +00:00
|
|
|
return {
|
2018-05-13 12:55:15 +00:00
|
|
|
"database_hash": hash,
|
|
|
|
"foreign_key_tables": await self.foreign_key_tables(
|
|
|
|
name, table, pk_values
|
|
|
|
),
|
|
|
|
"display_columns": display_columns,
|
|
|
|
"display_rows": display_rows,
|
|
|
|
"custom_rows_and_columns_templates": [
|
|
|
|
"_rows_and_columns-{}-{}.html".format(
|
|
|
|
to_css_class(name), to_css_class(table)
|
|
|
|
),
|
|
|
|
"_rows_and_columns-row-{}-{}.html".format(
|
|
|
|
to_css_class(name), to_css_class(table)
|
|
|
|
),
|
|
|
|
"_rows_and_columns.html",
|
2018-05-13 12:44:22 +00:00
|
|
|
],
|
2018-05-13 12:55:15 +00:00
|
|
|
"metadata": self.ds.metadata.get("databases", {}).get(name, {}).get(
|
|
|
|
"tables", {}
|
|
|
|
).get(
|
|
|
|
table, {}
|
|
|
|
),
|
2018-05-13 12:44:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
data = {
|
2018-05-13 12:55:15 +00:00
|
|
|
"database": name,
|
|
|
|
"table": table,
|
|
|
|
"rows": rows,
|
|
|
|
"columns": columns,
|
|
|
|
"primary_keys": pks,
|
|
|
|
"primary_key_values": pk_values,
|
|
|
|
"units": self.table_metadata(name, table).get("units", {}),
|
2018-05-13 12:44:22 +00:00
|
|
|
}
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
if "foreign_key_tables" in (request.raw_args.get("_extras") or "").split(","):
|
|
|
|
data["foreign_key_tables"] = await self.foreign_key_tables(
|
|
|
|
name, table, pk_values
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
|
|
|
|
return data, template_data, (
|
2018-05-13 12:55:15 +00:00
|
|
|
"row-{}-{}.html".format(to_css_class(name), to_css_class(table)), "row.html"
|
2018-05-13 12:44:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
async def foreign_key_tables(self, name, table, pk_values):
|
|
|
|
if len(pk_values) != 1:
|
|
|
|
return []
|
2018-05-13 12:55:15 +00:00
|
|
|
|
|
|
|
table_info = self.ds.inspect()[name]["tables"].get(table)
|
2018-05-13 12:44:22 +00:00
|
|
|
if not table_info:
|
|
|
|
return []
|
2018-05-13 12:55:15 +00:00
|
|
|
|
|
|
|
foreign_keys = table_info["foreign_keys"]["incoming"]
|
2018-05-13 12:44:22 +00:00
|
|
|
if len(foreign_keys) == 0:
|
|
|
|
return []
|
|
|
|
|
2018-05-13 12:55:15 +00:00
|
|
|
sql = "select " + ", ".join(
|
|
|
|
[
|
2018-05-15 15:00:39 +00:00
|
|
|
'(select count(*) from {table} where {column}=:id)'.format(
|
|
|
|
table=escape_sqlite(fk["other_table"]),
|
|
|
|
column=escape_sqlite(fk["other_column"]),
|
2018-05-13 12:55:15 +00:00
|
|
|
)
|
|
|
|
for fk in foreign_keys
|
|
|
|
]
|
|
|
|
)
|
2018-05-13 12:44:22 +00:00
|
|
|
try:
|
2018-05-13 12:55:15 +00:00
|
|
|
rows = list(await self.execute(name, sql, {"id": pk_values[0]}))
|
2018-05-13 12:44:22 +00:00
|
|
|
except sqlite3.OperationalError:
|
|
|
|
# Almost certainly hit the timeout
|
|
|
|
return []
|
2018-05-13 12:55:15 +00:00
|
|
|
|
2018-05-13 12:44:22 +00:00
|
|
|
foreign_table_counts = dict(
|
|
|
|
zip(
|
2018-05-13 12:55:15 +00:00
|
|
|
[(fk["other_table"], fk["other_column"]) for fk in foreign_keys],
|
2018-05-13 12:44:22 +00:00
|
|
|
list(rows[0]),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
foreign_key_tables = []
|
|
|
|
for fk in foreign_keys:
|
2018-05-13 12:55:15 +00:00
|
|
|
count = foreign_table_counts.get(
|
|
|
|
(fk["other_table"], fk["other_column"])
|
|
|
|
) or 0
|
|
|
|
foreign_key_tables.append({**fk, **{"count": count}})
|
2018-05-13 12:44:22 +00:00
|
|
|
return foreign_key_tables
|