simonw / sqlite-utils

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

Mechanism for de-registering registered SQL functions #589

Open simonw opened 10 months ago

simonw commented 10 months ago

I used a custom SQL function in a migration script and then realized that it should be de-registered before the end of the script to avoid leaking into the calling code.

simonw commented 10 months ago

For that particular case I realized I'd quite like to have a mechanism for applying functions for a block of code and then de-registering them at the end - a context manager.

I played with this idea a bit:

with db.register_functions(md5, md5_random):
    db.query(...)
simonw commented 10 months ago

Normally in Python/sqlite3 you de-register a function by passing None to it.

You can't do that with db.register_function() at the moment because a fn of None does something else:

https://github.com/simonw/sqlite-utils/blob/1260bdc7bfe31c36c272572c6389125f8de6ef71/sqlite_utils/db.py#L461-L464

simonw commented 10 months ago

Here's a prototype: https://github.com/simonw/sqlite-utils/commit/62f673835c4a66f87cf6f949eaff43c8b014619b

Still needs tests and documentation (and some more thought to make sure it's doing the right thing).