simonw / datasette-write

Datasette plugin providing a UI for executing SQL writes against the database
https://datasette.io/plugins/datasette-write
10 stars 2 forks source link

Event tracking for Datasette 1.0a8 and higher #13

Open simonw opened 2 months ago

simonw commented 2 months ago

An audit trail of SQL queries run using this plugin feels useful.

simonw commented 2 months ago

Prototype:

diff --git a/datasette_write/__init__.py b/datasette_write/__init__.py
index 5d336a4..f7710eb 100644
--- a/datasette_write/__init__.py
+++ b/datasette_write/__init__.py
@@ -1,4 +1,12 @@
+from dataclasses import dataclass
 from datasette import hookimpl, Forbidden, Response
+
+try:
+    from datasette import Event
+except ImportError:
+    # Only in Datasette >1.0a
+    Event = None
 from datasette.utils import derive_named_parameters
 from urllib.parse import urlencode
 import re
@@ -76,6 +84,15 @@ async def write(request, datasette):
                 )
         except Exception as e:
             message = str(e)
+        if Event is not None:
+            await datasette.track_event(
+                ExecuteWriteEvent(
+                    actor=request.actor,
+                    database=database.name,
+                    sql=sql,
+                    params=params,
+                )
+            )
         datasette.add_message(
             request,
             message,
@@ -281,3 +298,17 @@ def parse_create_alter_drop_sql(sql):
         if match is not None:
             return match.group(1), verb, type
     return None
+
+
+if Event is not None:
+
+    @dataclass
+    class ExecuteWriteEvent(Event):
+        name = "datasette-write-execute-write"
+        database: str
+        sql: str
+        params: dict
+
+    @hookimpl
+    def register_events():
+        return [ExecuteWriteEvent]