Skip to content

Commit 1ad8e36

Browse files
authored
datasette.Row replaces sqlite3.Row and CustomRow
Merge pull request #3099
2 parents 29bfe85 + 45f0860 commit 1ad8e36

26 files changed

Lines changed: 1615 additions & 219 deletions

‎datasette/__init__.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22
from datasette.version import __version_info__, __version__ # noqa
33
from datasette.events import Event # noqa
44
from datasette.background_tasks import BackgroundTask, BackgroundTaskSupervisor # noqa
5+
from datasette.rows import ( # noqa
6+
Column,
7+
Columns,
8+
ForeignKey,
9+
Row,
10+
)
511
from datasette.tokens import TokenHandler, TokenInvalid, TokenRestrictions # noqa
612
from datasette.utils.asgi import ( # noqa
713
Forbidden,

‎datasette/app.py‎

Lines changed: 69 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
from .plugins import DEFAULT_PLUGINS, get_plugins, pm
5252
from .renderer import json_renderer
5353
from .resources import DatabaseResource, TableResource
54+
from .rows import connection_row_factory
5455
from .telemetry import (
5556
TelemetryMiddleware,
5657
_in_datasette_client,
@@ -1613,7 +1614,7 @@ def static(self, path, plugin=None, mount=None):
16131614
return url + separator + urllib.parse.urlencode({"_hash": hash_value})
16141615

16151616
def _prepare_connection(self, conn, database):
1616-
conn.row_factory = sqlite3.Row
1617+
conn.row_factory = connection_row_factory()
16171618
conn.text_factory = lambda x: str(x, "utf-8", "replace")
16181619
if self.sqlite_extensions and database != INTERNAL_DB_NAME:
16191620
# Extension loading is only enabled for as long as it takes to
@@ -1763,7 +1764,7 @@ def resource_for_action(self, action: str, parent: str | None, child: str | None
17631764

17641765
async def check_visibility(
17651766
self,
1766-
actor: dict,
1767+
actor: dict | None,
17671768
action: str,
17681769
resource: Resource | None = None,
17691770
):
@@ -2343,9 +2344,14 @@ async def execute(
23432344
log_sql_errors=log_sql_errors,
23442345
)
23452346

2346-
async def expand_foreign_keys(self, actor, database, table, column, values):
2347-
"""Returns dict mapping (column, value) -> label"""
2348-
labeled_fks = {}
2347+
async def _foreign_key_target(
2348+
self, actor: dict | None, database: str, table: str, column: str
2349+
) -> tuple[str, str] | None:
2350+
"""
2351+
Returns ``(other_table, other_column)`` for the row that the foreign
2352+
key in ``column`` refers to, or ``None`` if there is no foreign key
2353+
there that this actor can follow.
2354+
"""
23492355
db = self.databases[database]
23502356
foreign_keys = await db.foreign_keys_for_table(table)
23512357
# Find the foreign_key for this column
@@ -2358,7 +2364,7 @@ async def expand_foreign_keys(self, actor, database, table, column, values):
23582364
None,
23592365
)
23602366
if fk is None:
2361-
return {}
2367+
return None
23622368
# Ensure user has permission to view the referenced table
23632369
from datasette.resources import TableResource
23642370

@@ -2373,25 +2379,51 @@ async def expand_foreign_keys(self, actor, database, table, column, values):
23732379
if target_table is None:
23742380
# SQLite accepts a foreign key to a table that does not exist, and
23752381
# linking to it would only lead to a 404
2376-
return {}
2382+
return None
23772383
other_table = target_table[0]
23782384
other_column = fk["other_column"]
23792385
if other_column is None:
23802386
other_pks = await db.primary_keys(other_table)
23812387
if len(other_pks) != 1:
2382-
return {}
2388+
return None
23832389
other_column = other_pks[0]
23842390
visible, _ = await self.check_visibility(
23852391
actor,
23862392
action="view-table",
23872393
resource=TableResource(database=database, table=other_table),
23882394
)
23892395
if not visible:
2390-
return {}
2396+
return None
2397+
return other_table, other_column
2398+
2399+
async def foreign_key_labels(
2400+
self,
2401+
actor: dict | None,
2402+
database: str,
2403+
table: str,
2404+
column: str,
2405+
values: Iterable[Any],
2406+
) -> tuple[str, dict[Any, Any] | None] | None:
2407+
"""
2408+
Looks up labels for the rows that the foreign key in ``column`` refers to.
2409+
2410+
Returns ``None`` if the column is not a foreign key this actor can
2411+
follow. Otherwise returns ``(other_table, labels)``. ``labels`` is a
2412+
``{value: label}`` dictionary for each of the ``values`` that matched
2413+
a row, or ``None`` if the other table has no label column.
2414+
"""
2415+
target = await self._foreign_key_target(actor, database, table, column)
2416+
if target is None:
2417+
return None
2418+
other_table, other_column = target
2419+
db = self.databases[database]
23912420
label_column = await db.label_column_for_table(other_table)
23922421
if not label_column:
2393-
return {(fk["column"], value): str(value) for value in values}
2394-
labeled_fks = {}
2422+
return other_table, None
2423+
labels: dict[Any, Any] = {}
2424+
distinct_values = list({value for value in values if value is not None})
2425+
if not distinct_values:
2426+
return other_table, labels
23952427
sql = """
23962428
select {other_column}, {label_column}
23972429
from {other_table}
@@ -2400,16 +2432,36 @@ async def expand_foreign_keys(self, actor, database, table, column, values):
24002432
other_column=escape_sqlite(other_column),
24012433
label_column=escape_sqlite(label_column),
24022434
other_table=escape_sqlite(other_table),
2403-
placeholders=", ".join(["?"] * len(set(values))),
2435+
placeholders=", ".join(["?"] * len(distinct_values)),
24042436
)
24052437
try:
2406-
results = await self.execute(database, sql, list(set(values)))
2438+
results = await self.execute(database, sql, distinct_values)
24072439
except QueryInterrupted:
24082440
pass
24092441
else:
2410-
for id, value in results:
2411-
labeled_fks[(fk["column"], id)] = value
2412-
return labeled_fks
2442+
for id, label in results:
2443+
labels[id] = label
2444+
return other_table, labels
2445+
2446+
async def expand_foreign_keys(
2447+
self,
2448+
actor: dict | None,
2449+
database: str,
2450+
table: str,
2451+
column: str,
2452+
values: Iterable[Any],
2453+
) -> dict[tuple[str, Any], Any]:
2454+
"""Returns dict mapping (column, value) -> label"""
2455+
# values is used twice below, so it must not be a one-shot iterator
2456+
values = list(values)
2457+
expanded = await self.foreign_key_labels(actor, database, table, column, values)
2458+
if expanded is None:
2459+
return {}
2460+
_, labels = expanded
2461+
if labels is None:
2462+
# No label column, so each value is its own label
2463+
return {(column, value): str(value) for value in values}
2464+
return {(column, value): label for value, label in labels.items()}
24132465

24142466
def absolute_url(self, request, path):
24152467
url = urllib.parse.urljoin(request.url, path)
@@ -2695,7 +2747,7 @@ async def render_template(
26952747
context_class = type(context) if isinstance(context, Context) else None
26962748
if dataclasses.is_dataclass(context):
26972749
# Shallow conversion - asdict() would deep-copy values, which
2698-
# is wasteful and fails on values like sqlite3.Row
2750+
# is wasteful for values such as lists of rows
26992751
context = {
27002752
f.name: getattr(context, f.name) for f in dataclasses.fields(context)
27012753
}

‎datasette/context_debug.py‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
from markupsafe import Markup, escape
1616

17+
from datasette.rows import Row
18+
1719
# Values that fit in this many characters are shown on a single line
1820
COMPACT_LENGTH = 200
1921
# Values longer than this many lines start out collapsed
@@ -53,7 +55,7 @@ def replace(match):
5355
def _json_default(value):
5456
if dataclasses.is_dataclass(value) and not isinstance(value, type):
5557
return {f.name: getattr(value, f.name) for f in dataclasses.fields(value)}
56-
if isinstance(value, sqlite3.Row):
58+
if isinstance(value, (Row, sqlite3.Row)):
5759
# Iterating over a Row gives its values, not its keys
5860
return {key: value[key] for key in value.keys()} # noqa: SIM118
5961
if isinstance(value, (set, frozenset, tuple)):
@@ -124,7 +126,20 @@ def _is_data(value):
124126
"Is this a value we display as JSON, rather than as an object with members?"
125127
if value is None or isinstance(
126128
value,
127-
(str, bytes, int, float, bool, dict, list, tuple, set, frozenset, sqlite3.Row),
129+
(
130+
str,
131+
bytes,
132+
int,
133+
float,
134+
bool,
135+
dict,
136+
list,
137+
tuple,
138+
set,
139+
frozenset,
140+
Row,
141+
sqlite3.Row,
142+
),
128143
):
129144
return True
130145
return dataclasses.is_dataclass(value) and not isinstance(value, type)

‎datasette/csv_renderer.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ def render_delimited(
6363
headings.append(f"{column}_label")
6464

6565
def cells(row):
66+
labels = getattr(row, "labels", {})
6667
for column, cell in zip(columns, row):
6768
if isinstance(cell, bytes):
6869
cell = _blob_url(
@@ -81,10 +82,9 @@ def cells(row):
8182
elif cell is None:
8283
yield ""
8384
yield ""
84-
elif isinstance(cell, dict):
85-
# {"value": ..., "label": ...}
86-
yield cell["value"]
87-
yield cell["label"]
85+
elif column in labels:
86+
yield cell
87+
yield labels[column]
8888
else:
8989
yield cell
9090
yield ""

0 commit comments

Comments
 (0)