diff --git a/datasette/app.py b/datasette/app.py index b643c102..919a0a51 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -316,7 +316,7 @@ class Datasette: } ) - def prepare_connection(self, conn): + def prepare_connection(self, conn, database): conn.row_factory = sqlite3.Row conn.text_factory = lambda x: str(x, "utf-8", "replace") for name, num_args, func in self.sqlite_functions: @@ -328,7 +328,7 @@ class Datasette: if self.config("cache_size_kb"): conn.execute("PRAGMA cache_size=-{}".format(self.config("cache_size_kb"))) # pylint: disable=no-member - pm.hook.prepare_connection(conn=conn) + pm.hook.prepare_connection(conn=conn, database=database, datasette=self) async def execute( self, @@ -412,7 +412,7 @@ class Datasette: def versions(self): conn = sqlite3.connect(":memory:") - self.prepare_connection(conn) + self.prepare_connection(conn, ":memory:") sqlite_version = conn.execute("select sqlite_version()").fetchone()[0] sqlite_extensions = {} for extension, testsql, hasversion in ( diff --git a/datasette/cli.py b/datasette/cli.py index 8d724c42..5b8a05c5 100644 --- a/datasette/cli.py +++ b/datasette/cli.py @@ -392,5 +392,7 @@ async def check_databases(ds): ) except ConnectionProblem as e: raise click.UsageError( - "Connection to {} failed check: {}".format(database.path, str(e.args[0])) + "Connection to {} failed check: {}".format( + database.path, str(e.args[0]) + ) ) diff --git a/datasette/database.py b/datasette/database.py index 8d19bd74..b34ecd18 100644 --- a/datasette/database.py +++ b/datasette/database.py @@ -58,7 +58,7 @@ class Database: conn = getattr(connections, self.name, None) if not conn: conn = self.connect() - self.ds.prepare_connection(conn) + self.ds.prepare_connection(conn, self.name) setattr(connections, self.name, conn) return fn(conn) diff --git a/datasette/hookspecs.py b/datasette/hookspecs.py index 3c6726b7..c2fc0126 100644 --- a/datasette/hookspecs.py +++ b/datasette/hookspecs.py @@ -11,7 +11,7 @@ def asgi_wrapper(datasette): @hookspec -def prepare_connection(conn): +def prepare_connection(conn, database, datasette): "Modify SQLite connection in some way e.g. register custom SQL functions" diff --git a/docs/plugins.rst b/docs/plugins.rst index 37871503..108a8aab 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -340,12 +340,18 @@ The full list of available plugin hooks is as follows. .. _plugin_hook_prepare_connection: -prepare_connection(conn) -~~~~~~~~~~~~~~~~~~~~~~~~ +prepare_connection(conn, database, datasette) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``conn`` - sqlite3 connection object The connection that is being opened +``database`` - string + The name of the database + +``datasette`` - :ref:`datasette` + You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)`` + This hook is called when a new SQLite database connection is created. You can use it to `register custom SQL functions `_, aggregates and collations. For example: