Skip to content

Commit 45f0860

Browse files
simonwclaude
andcommitted
execute_fn() and execute_write_fn() connections return datasette.Row
Connections that Datasette prepares now use a row factory that builds datasette.Row objects, so rows fetched from a raw connection are the same type as rows returned by db.execute(). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 991f5d8 commit 45f0860

7 files changed

Lines changed: 97 additions & 6 deletions

File tree

‎datasette/app.py‎

Lines changed: 2 additions & 1 deletion
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

‎datasette/database.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1281,7 +1281,9 @@ def from_cursor(
12811281
cursor.close()
12821282
if description is not None and not return_all and truncated:
12831283
rowcount = -1
1284-
if rows:
1284+
if rows and not isinstance(rows[0], Row):
1285+
# Connections Datasette opens return Row objects already, but a
1286+
# plugin may have set a different row_factory on this one
12851287
columns = Columns(d[0] for d in description)
12861288
rows = [Row(tuple(row), columns) for row in rows]
12871289
return cls(rowcount, lastrowid, description, rows, truncated)

‎datasette/rows.py‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
from __future__ import annotations
1515

16-
from collections.abc import Iterable, Iterator, Mapping
16+
from collections.abc import Callable, Iterable, Iterator, Mapping
1717
from dataclasses import dataclass
1818
from types import MappingProxyType
1919
from typing import Any, overload
@@ -278,3 +278,28 @@ def label_rows(
278278
continue
279279
labeled.append(Row(row._values, row._columns, {**row.labels, **row_labels}))
280280
return labeled
281+
282+
283+
def connection_row_factory() -> Callable[[Any, tuple[Any, ...]], Row]:
284+
"""
285+
Returns a ``row_factory`` for a SQLite connection that builds
286+
:class:`Row` objects, sharing one :class:`Columns` between the rows of
287+
each query.
288+
289+
Each connection needs its own factory, because the factory remembers the
290+
columns of the query that connection is currently reading.
291+
"""
292+
last_description = None
293+
last_columns = Columns()
294+
295+
def row_factory(cursor: Any, values: tuple[Any, ...]) -> Row:
296+
nonlocal last_description, last_columns
297+
# cursor.description is the same object for every row of a query,
298+
# and a new object each time the cursor executes something else
299+
description = cursor.description
300+
if description is not last_description:
301+
last_columns = Columns([d[0] for d in description])
302+
last_description = description
303+
return Row(values, last_columns)
304+
305+
return row_factory

‎docs/changelog.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Changelog
99
Unreleased
1010
----------
1111

12-
- **Backwards incompatible:** rows returned by :ref:`db.execute() <database_execute>` are now :ref:`datasette.Row <internals_row>` objects instead of ``sqlite3.Row`` objects. ``Row`` is designed to work for database backends other than SQLite. See the :ref:`upgrade guide <upgrade_guide_v1_rows>` for how to update plugins. ``row["name"]``, ``row[0]``, ``row.keys()``, ``dict(row)``, ``tuple(row)`` and iterating over a row all continue to work. Code will need to change if it uses ``isinstance(row, sqlite3.Row)``, looks up columns using a different case from the one in the query, or catches ``IndexError`` for a missing column name - that is now a ``KeyError``. (:issue:`1973`)
12+
- **Backwards incompatible:** rows returned by :ref:`db.execute() <database_execute>` are now :ref:`datasette.Row <internals_row>` objects instead of ``sqlite3.Row`` objects. So are rows fetched from the connection passed to a :ref:`db.execute_fn() <database_execute_fn>` or :ref:`db.execute_write_fn() <database_execute_write_fn>` function. ``Row`` is designed to work for database backends other than SQLite. See the :ref:`upgrade guide <upgrade_guide_v1_rows>` for how to update plugins. ``row["name"]``, ``row[0]``, ``row.keys()``, ``dict(row)``, ``tuple(row)`` and iterating over a row all continue to work. Code will need to change if it uses ``isinstance(row, sqlite3.Row)``, looks up columns using a different case from the one in the query, or catches ``IndexError`` for a missing column name - that is now a ``KeyError``. (:issue:`1973`)
1313
- **Backwards incompatible:** ``results.columns`` is now a :ref:`Columns <internals_row_columns>` object describing each column, shared by every row as ``row.columns``. Use ``results.columns.names`` for the column names. On table and row pages each ``Column`` includes the type the column was declared with, as a string, and any foreign key. The new :ref:`db.describe_columns() <database_describe_columns>` method returns the same information for any table.
1414
- **Backwards incompatible:** the :ref:`render_cell() <plugin_hook_render_cell>` plugin hook, and the ``render_cell()`` method of :ref:`column types <datasette_column_types>`, are now always passed the value stored in the database. Previously the ``value`` for a foreign key column was sometimes a ``{"value": ..., "label": ...}`` dictionary, depending on the page, the query string and the data. The ``row`` passed to the hook is now a ``datasette.Row`` on every page, where previously it was either a ``sqlite3.Row`` or an undocumented ``CustomRow``. Labels for foreign keys are available in the new ``row.labels`` dictionary. If a column is a foreign key and also has a column type assigned, the column type now renders the cell. Previously the cell showed a link to the referenced row, because the column type was passed the label dictionary and did not recognize it. (:issue:`1973`)
1515
- **Backwards incompatible:** the ``rows`` passed to :ref:`output renderers <plugin_register_output_renderer>` are ``datasette.Row`` objects. With ``?_labels=on`` they previously contained ``{"value": ..., "label": ...}`` dictionaries - the labels are now in ``row.labels``. The :ref:`row_actions() <plugin_hook_row_actions>` and :ref:`top_row() <plugin_hook_top_row>` hooks are passed a ``datasette.Row`` too.

‎docs/internals.rst‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2358,6 +2358,8 @@ Example usage:
23582358
23592359
version = await db.execute_fn(get_version)
23602360
2361+
Rows fetched from this connection are :ref:`Row <internals_row>` objects, the same as those returned by ``db.execute()``.
2362+
23612363
The call is traced as a ``db.query`` OpenTelemetry span carrying ``datasette.callback`` (the function's qualified name) rather than ``db.query.text``, since the SQL is whatever the function chooses to run - see :ref:`internals_telemetry`. Passing a named function gives the span a readable identity; a lambda reports ``<lambda>``.
23622364

23632365
.. _database_execute_write:
@@ -2443,6 +2445,8 @@ This method works like ``.execute_write()``, but instead of a SQL statement you
24432445

24442446
The function can then perform multiple actions, safe in the knowledge that it has exclusive access to the single writable connection for as long as it is executing.
24452447

2448+
Rows fetched from this connection are :ref:`Row <internals_row>` objects.
2449+
24462450
Like ``execute_fn()``, the call is traced as a ``db.query`` OpenTelemetry span carrying ``datasette.callback`` rather than ``db.query.text``, above the write-queue spans - see :ref:`internals_telemetry`. A named function gives the span a readable identity; a lambda reports ``<lambda>``.
24472451

24482452
.. warning::
@@ -2530,7 +2534,7 @@ await db.execute_isolated_fn(fn)
25302534

25312535
This method works is similar to :ref:`execute_write_fn() <database_execute_write_fn>` but executes the provided function in an entirely isolated SQLite connection, which is opened, used and then closed again in a single call to this method.
25322536

2533-
The :ref:`prepare_connection() <plugin_hook_prepare_connection>` plugin hook is not executed against this connection.
2537+
The :ref:`prepare_connection() <plugin_hook_prepare_connection>` plugin hook is not executed against this connection, and Datasette does not configure it in any other way. Rows fetched from it are plain tuples, not :ref:`Row <internals_row>` objects.
25342538

25352539
This allows plugins to execute database operations that might conflict with how database connections are usually configured. For example, running a ``VACUUM`` operation while bypassing any restrictions placed by the `datasette-sqlite-authorizer <https://github.com/datasette/datasette-sqlite-authorizer>`__ plugin.
25362540

‎docs/upgrade_guide.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ The dictionary returned by `register_output_renderer()` itself must use the `"re
103103

104104
The rows returned by {ref}`db.execute() <database_execute>` are now {ref}`datasette.Row <internals_row>` objects. They were previously `sqlite3.Row` objects. The rows passed to the `render_cell()`, `row_actions()` and `top_row()` plugin hooks and to output renderers are `datasette.Row` objects too.
105105

106+
The same is true for rows your own code fetches from the connection passed to a {ref}`db.execute_fn() <database_execute_fn>` or {ref}`db.execute_write_fn() <database_execute_write_fn>` function.
107+
106108
`Row` is not tied to SQLite, so that Datasette can support other databases in the future.
107109

108110
Most code does not need to change. These all work as before:
@@ -139,7 +141,7 @@ Check your code for the following, each of which behaves differently:
139141

140142
You can also check `"optional_column" in row.columns`.
141143

142-
Functions passed to {ref}`db.execute_fn() <database_execute_fn>` and {ref}`db.execute_write_fn() <database_execute_write_fn>` are given a SQLite connection and run their own queries, so the rows they fetch are still `sqlite3.Row` objects.
144+
The connection passed to a {ref}`db.execute_isolated_fn() <database_execute_isolated_fn>` function is not configured by Datasette, so its rows are plain tuples. That has not changed.
143145

144146
(upgrade_guide_v1_results_columns)=
145147
#### `results.columns` is no longer a list of strings

‎tests/test_rows.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import copy
22
import json
33
import pickle
4+
import sqlite3
45

56
import pytest
67

@@ -545,3 +546,59 @@ async def test_labels_in_json_and_csv(ds_with_dogs):
545546
"1,1,Natalie,3",
546547
"2,99,,3",
547548
]
549+
550+
551+
@pytest.mark.asyncio
552+
@pytest.mark.parametrize("method", ("execute_fn", "execute_write_fn"))
553+
async def test_raw_connections_return_rows(method):
554+
ds = Datasette(memory=True)
555+
db = ds.add_memory_database(f"test_raw_connections_{method}")
556+
await db.execute_write_script("""
557+
create table dogs (id integer primary key, name text);
558+
insert into dogs values (1, 'Cleo'), (2, 'Pancakes');
559+
""")
560+
561+
def fetch(conn):
562+
return conn.execute("select id, name from dogs order by id").fetchall()
563+
564+
rows = await getattr(db, method)(fetch)
565+
assert all(type(row) is Row for row in rows)
566+
assert rows[0]["name"] == "Cleo"
567+
assert rows[1][0] == 2
568+
assert rows[0].keys() == ["id", "name"]
569+
# The rows of one query share their columns
570+
assert rows[0].columns is rows[1].columns
571+
572+
def reuse_cursor(conn):
573+
cursor = conn.cursor()
574+
first = cursor.execute("select 1 as a").fetchone()
575+
second = cursor.execute("select 2 as b, 3 as c").fetchone()
576+
return first, second
577+
578+
first, second = await getattr(db, method)(reuse_cursor)
579+
assert first.keys() == ["a"]
580+
assert second.keys() == ["b", "c"]
581+
assert dict(second) == {"b": 2, "c": 3}
582+
583+
def interleave(conn):
584+
ids = conn.execute("select id from dogs order by id")
585+
names = conn.execute("select name from dogs order by id")
586+
return [(ids.fetchone(), names.fetchone()) for _ in range(2)]
587+
588+
pairs = await getattr(db, method)(interleave)
589+
assert [(dict(id_), dict(name)) for id_, name in pairs] == [
590+
({"id": 1}, {"name": "Cleo"}),
591+
({"id": 2}, {"name": "Pancakes"}),
592+
]
593+
594+
595+
@pytest.mark.asyncio
596+
async def test_execute_isolated_fn_connection_is_not_configured(tmp_path):
597+
path = str(tmp_path / "isolated.db")
598+
sqlite3.connect(path).execute("vacuum")
599+
ds = Datasette([path])
600+
db = ds.get_database("isolated")
601+
row = await db.execute_isolated_fn(
602+
lambda conn: conn.execute("select 1 as a").fetchone()
603+
)
604+
assert type(row) is tuple

0 commit comments

Comments
 (0)