diff --git a/doc/howto.md b/doc/howto.md index 674e27a6e..de34d723a 100644 --- a/doc/howto.md +++ b/doc/howto.md @@ -63,3 +63,50 @@ FROM penguins.csv GROUP BY species ORDER BY count DESC ``` + +## Register SQLite UDF + +To register a user-defined function (UDF) when using SQLite, you can use [SQLAlchemy's `@event.listens_for`](https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#user-defined-functions) and SQLite's [`create_function`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function): + +### Install JupySQL + +```{code-cell} ipython3 +%pip install jupysql --quiet +``` + +### Create engine and register function + +```{code-cell} ipython3 +from sqlalchemy import create_engine +from sqlalchemy import event + +def mysum(x, y): + return x + y + +engine = create_engine("sqlite://") + +@event.listens_for(engine, "connect") +def connect(conn, rec): + conn.create_function(name="MYSUM", narg=2, func=mysum) +``` + +### Create connection with existing engine + +```{versionadded} 0.5.1 +Pass existing engines to `%sql` +``` + +```{code-cell} ipython3 +%load_ext sql +``` + +```{code-cell} ipython3 +%sql engine +``` + +## Query + +```{code-cell} ipython3 +%%sql +SELECT MYSUM(1, 2) +```