Custom drivers (agent plugins)
Plug any Python database driver into the agent — DuckDB, Oracle, MongoDB, SAP HANA, …
PyCorner ships hosted drivers for Postgres and MySQL. Everything else — DuckDB, Oracle, MongoDB, SAP HANA, an internal protocol, your own ORM, anything you can pip-install — you wire up as a driver plugin on your tunnel agent. From the Pyodide app’s perspective the API is identical: pycorner.connect("name").execute(sql). The dispatch just happens on your machine instead of ours.
You get to control:
- Which Python driver and version (the agent’s environment is yours).
- Where the credentials live (the agent only — they never need to round-trip through PyCorner).
- License-restricted clients (Oracle Instant Client, etc.) stay on your network.
The contract
A driver plugin is a single Python file under pycorner-agent/drivers/. It imports register_driver from the agent module and decorates a callable:
# drivers/mything.py
from pycorner_agent import register_driver
@register_driver("mything")
def execute(config: dict, sql: str, params):
# `config` is whatever JSON dict you put in the resource's "Plugin
# config" textarea. `sql` and `params` come from the user's app.
# Return a JSON-serializable dict in this exact shape:
return {
"columns": ["a", "b"], # column names
"rows": [[1, 2], [3, 4]], # list of lists, JSON-safe values
"row_count": 2,
"truncated": False, # set True if you clipped
}
The handler is invoked on a worker thread, so blocking calls are fine — you don’t have to make your driver async. Anything you raise becomes an error message back to the client.
Working example — DuckDB
The agent bundle already ships drivers/duckdb.py:
from pycorner_agent import register_driver
MAX_ROWS = 10_000
@register_driver("duckdb")
def execute(config, sql, params):
import duckdb
path = config.get("path", ":memory:")
read_only = bool(config.get("read_only", True)) and path != ":memory:"
conn = duckdb.connect(path, read_only=read_only)
try:
cur = conn.execute(sql, params or [])
cols = [d[0] for d in cur.description] if cur.description else []
rows = cur.fetchmany(MAX_ROWS)
return {
"columns": cols,
"rows": [list(r) for r in rows],
"row_count": len(rows),
"truncated": len(rows) >= MAX_ROWS,
}
finally:
conn.close()
To make it work end-to-end:
1. Install the driver on the agent
The bundle’s pixi.toml defines a duckdb feature env. Start the agent with it:
cd pycorner-agent
pixi run -e duckdb start
You’ll see [INFO] registered driver plugin: duckdb in the log. The agent now advertises sql in its capabilities list at handshake.
2. Put a DuckDB file somewhere the agent can read
python -c "
import duckdb
con = duckdb.connect('/tmp/sales.duckdb')
con.execute('CREATE TABLE orders (id INT, total NUMERIC, status VARCHAR)')
con.execute(\"INSERT INTO orders VALUES (1, 19.99, 'paid'), (2, 5.00, 'pending')\")
con.close()
"
3. Create the Resource in PyCorner
Resources → Databases → New Database:
- Driver:
Custom (agent plugin) - Agent: your tunnel agent
- Driver name:
duckdb - Plugin config (JSON):
{"path": "/tmp/sales.duckdb", "read_only": true}
Name the resource — say, sales-duckdb — and save.
4. Query it from a Stlite app
import pycorner
import streamlit as st
db = pycorner.connect("sales-duckdb")
rows = db.execute("SELECT * FROM orders WHERE status = 'paid'").fetchall()
st.table(rows)
That’s it. The path from db.execute(...) is:
Pyodide → PyCorner backend → tunnel WS → your agent
→ drivers/duckdb.py:execute(config, sql, params)
→ duckdb.connect(path).execute(sql).fetchmany()
→ back through the tunnel as JSON
Building your own driver
Drop a file in pycorner-agent/drivers/. The skeleton:
from pycorner_agent import register_driver
@register_driver("<your-name>")
def execute(config: dict, sql: str, params):
import yourdriver
conn = yourdriver.connect(**conn_kwargs_from(config))
try:
cur = conn.cursor()
cur.execute(sql, params or ())
cols = [d[0] for d in cur.description] if cur.description else []
rows = list(cur.fetchall())
return {
"columns": cols,
"rows": [list(r) for r in rows],
"row_count": len(rows),
}
finally:
conn.close()
A few practical notes:
- Make rows JSON-safe. Datetimes, UUIDs, Decimals — convert them to strings or floats before returning. The result has to survive
json.dumps. - Cap row counts. Big result sets blow through your tunnel and your customer’s memory. We use 10k as a reasonable default; do the same.
- Don’t trust upstream params. Always use the driver’s parameterized API (
%s,?, named placeholders) so you don’t introduce a SQL injection your customer didn’t have before. - Use
config.get(...)defensively. The plugin config is opaque to PyCorner; it’s whatever JSON the resource was created with. Validate it, raise a clear error on missing keys.
What gets shipped over the wire
Per query, the server sends the agent a single encrypted message:
{"type": "request",
"request_id": "<uuid>",
"request_type": "sql",
"payload": {
"driver_name": "duckdb",
"sql": "SELECT ...",
"params": [...],
"config": {... your resource config minus driver/driver_name/agent_id ...}
}}
The agent’s response goes back as:
{"type": "response",
"request_id": "<uuid>",
"data": {"columns": [...], "rows": [...], "row_count": ..., "truncated": ...}}
Errors raised by the plugin are converted to:
{"type": "error", "request_id": "<uuid>", "error": "PluginError: ..."}
When to NOT write a plugin
If you’re reaching a common cloud SQL database (Postgres-as-a-Service, MySQL-as-a-Service), the hosted driver is simpler and faster. You only get the plugin benefits when:
- The driver doesn’t exist (or isn’t free) for PyCorner to host.
- You need version-pinned compatibility with your DB.
- You want zero credentials reaching PyCorner’s infrastructure.
- The DB isn’t reachable from PyCorner anyway.
Otherwise, Databases covers the same UX with no install required.