5151from .plugins import DEFAULT_PLUGINS , get_plugins , pm
5252from .renderer import json_renderer
5353from .resources import DatabaseResource , TableResource
54+ from .rows import connection_row_factory
5455from .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 }
0 commit comments