simonw / sqlite-utils

Python CLI utility and library for manipulating SQLite databases
https://sqlite-utils.datasette.io
Apache License 2.0
1.62k stars 109 forks source link

`prepare_connection()` plugin hook #574

Closed simonw closed 1 year ago

simonw commented 1 year ago

Splitting off an issue for prepare_connection() since Alex got the PR in seconds before I shipped 3.34!

Originally posted by @simonw in https://github.com/simonw/sqlite-utils/issues/567#issuecomment-1646686424

simonw commented 1 year ago

Alex built this in:

simonw commented 1 year ago

Documentation: https://sqlite-utils.datasette.io/en/latest/plugins.html#prepare-connection-conn

simonw commented 1 year ago

Just tried this out by adding the example from the docs to my sqlite-utils-hello-world plugin and running:

sqlite-utils install -e ../sqlite-utils-hello-world 
Obtaining file:///Users/simon/Dropbox/Development/sqlite-utils-hello-world
...

Then:

sqlite-utils memory "select hello('simon')"
[{"hello('simon')": "Hello, simon!"}]

Also:

>>> import sqlite_utils
>>> db = sqlite_utils.Database(memory=True)
>>> list(db.query("select hello('simon')"))
[{"hello('simon')": 'Hello, simon!'}]
>>> db2 = sqlite_utils.Database(memory=True, execute_plugins=False)
>>> list(db2.query("select hello('simon')"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/simon/Dropbox/Development/sqlite-utils/sqlite_utils/db.py", line 494, in query
    cursor = self.execute(sql, params or tuple())
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/simon/Dropbox/Development/sqlite-utils/sqlite_utils/db.py", line 512, in execute
    return self.conn.execute(sql, parameters)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlean.dbapi2.OperationalError: no such function: hello