From f81d9d0cd9f567e73a1a54be34b653db8ae2c1cf Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Fri, 17 Dec 2021 18:42:29 -0800 Subject: [PATCH] Trace write SQL queries in addition to read ones, closes #1568 --- datasette/database.py | 4 +++- tests/test_api.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/datasette/database.py b/datasette/database.py index 0a0c104a..468e9360 100644 --- a/datasette/database.py +++ b/datasette/database.py @@ -99,7 +99,9 @@ class Database: with conn: return conn.execute(sql, params or []) - return await self.execute_write_fn(_inner, block=block) + with trace("sql", database=self.name, sql=sql.strip(), params=params): + results = await self.execute_write_fn(_inner, block=block) + return results async def execute_write_fn(self, fn, block=False): task_id = uuid.uuid5(uuid.NAMESPACE_DNS, "datasette.io") diff --git a/tests/test_api.py b/tests/test_api.py index df9e0fc4..9ad7d569 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -939,6 +939,19 @@ def test_trace(trace_debug): assert isinstance(trace["sql"], str) assert isinstance(trace["params"], (list, dict, None.__class__)) + sqls = [trace["sql"] for trace in trace_info["traces"] if "sql" in trace] + # There should be a mix of different types of SQL statement + expected = ( + "CREATE TABLE ", + "PRAGMA ", + "INSERT OR REPLACE INTO ", + "DELETE FROM ", + "INSERT INTO", + "select ", + ) + for prefix in expected: + assert any(sql.startswith(prefix) for sql in sqls) + @pytest.mark.parametrize( "path,status_code",