Host functions
jed’s built-in function catalog is pure and side-effect-free — that is what makes an untrusted query safe to run. But an embedding host often has domain logic the engine will never ship: a pricing rule, a scoring formula, a company-specific transform. You register those as host scalar functions — your own code, callable from SQL by name, resolved and evaluated beside the built-in catalog.
A host registers functions on an environment builder, builds the Environment, and passes it
in the create/open options. An environment is immutable — it also carries the loaded Unicode and
time-zone data and the random and clock sources — so the set of functions is fixed for the handle’s
lifetime and shared into every session. One environment can serve many databases. Registering code never mutates
schema, and the function itself is never written to the file: a reopening host brings its own. Only
an index or CHECK that uses a host function records which implementation it was built against
(below).
For TypeScript, register functions in a module that exports configure(builder), as shown below.
Registration runs inside the database’s worker. Node loads the module from the trusted file URL
passed as extensionModule to await createDatabase(...) or await openDatabase(...).
Browser applications import it into a custom worker, using the public helper shown below.
Application closures and Environment instances cannot cross the worker boundary.
use jed::{CreateOptions, Database, Environment, HostFunction, ScalarType, Value, Volatility};
fn main() -> jed::Result<()> {
// A host registers its own SCALAR FUNCTIONS over the built-in types on an environment builder,
// then hands the built Environment to create/open — it is frozen once built and shared by every
// session of the handle. It is never written to the file (a reopening host brings its own).
let env = Environment::builder()
// discount(cents, pct) -> the price after a whole-percent discount. STRICT — a NULL argument
// short-circuits to NULL before the kernel runs, so the closure never sees one — and reached by
// an EXACT (i64, i64) signature (no implicit promotion; a built-in of the same signature would
// win). `.cost(2)` is charged once per call and gated against a session's max_cost, so the
// function stays inside the untrusted-query bound.
.register_function(
HostFunction::new(
"discount",
vec![ScalarType::Int64, ScalarType::Int64],
ScalarType::Int64,
Box::new(|args: &[Value]| -> jed::Result<Value> {
let (Value::Int(cents), Value::Int(pct)) = (&args[0], &args[1]) else {
unreachable!("strict + resolved (i64, i64) args")
};
Ok(Value::Int(cents - cents * pct / 100))
}),
)
.volatility(Volatility::Immutable) // same inputs ⇒ same output
.cross_core(true) // results are byte-identical on every core
.cost(2)
.component_id("com.example/discount") // a stable identity for index-backing
.semantic_version(1), // bump when a formula change would invalidate stored index keys
)?
// with_tax(cents) -> cents plus 8% tax, as a BATCH kernel: it receives a whole column of rows per
// call (args[0][i] is row i's argument) and appends one result per row to `out`. jed calls it
// once per chunk where it already holds the rows, and one row at a time elsewhere — same rows,
// cost, and errors either way.
.register_function(
HostFunction::batched(
"with_tax",
vec![ScalarType::Int64],
ScalarType::Int64,
Box::new(|args: &[Vec<Value>], out: &mut Vec<Value>| -> jed::Result<()> {
for v in &args[0] {
let Value::Int(cents) = v else { unreachable!("strict + resolved i64 arg") };
out.push(Value::Int(cents + cents * 8 / 100));
}
Ok(())
}),
)
.volatility(Volatility::Immutable),
)?
.build();
let db = Database::create(CreateOptions { environment: env, ..Default::default() })?;
db.execute("CREATE TABLE product (id i32 PRIMARY KEY, name text, price_cents i64)", &[])?;
db.execute("INSERT INTO product VALUES (1, 'Mug', 1250), (2, 'Notebook', 400)", &[])?;
// Because discount is IMMUTABLE and carries a component identity, it can back a persisted index.
// On reopen, if the environment supplies a different component/version, the index is skipped for
// reads (a correct heap scan) and refused for writes — never a silently stale result.
db.execute("CREATE INDEX ON product (discount(price_cents, 10))", &[])?;
// Call it by name from SQL, exactly like a built-in.
let sql = "SELECT name, discount(price_cents, 15) AS sale, with_tax(price_cents) AS total \
FROM product ORDER BY id";
for row in db.query(sql, &[])? {
let row = row?; // a read can fail part-way; each row is a Result
// Mug -> 1063 / 1350, Notebook -> 340 / 432
println!("{} -> {} / {}", row[0].render(), row[1].render(), row[2].render());
}
Ok(())
}
package main
import (
"context"
"fmt"
"log"
jed "github.com/jackc/jed/impl/go"
)
func main() {
// A host registers its own SCALAR FUNCTIONS over the built-in types on an EnvironmentBuilder,
// builds the (immutable) Environment, and hands it to Create/Open — every session of the handle
// shares it. It is never written to the file (a reopening host brings its own).
builder := jed.NewEnvironmentBuilder()
// discount(cents, pct) -> the price after a whole-percent discount. STRICT — a NULL argument
// short-circuits to NULL before the kernel runs, so the closure never sees one — and reached by an
// EXACT (i64, i64) signature (no implicit promotion; a built-in of the same signature would win).
// WithCost(2) is charged once per call and gated against a session's MaxCost, so the function stays
// inside the untrusted-query bound.
err := builder.RegisterFunction(
jed.NewHostFunction("discount", []string{"i64", "i64"}, "i64",
func(args []jed.Value) (jed.Value, error) {
cents, pct := args[0].Int, args[1].Int
return jed.IntValue(cents - cents*pct/100), nil
}).
WithVolatility(jed.VolatilityImmutable). // same inputs ⇒ same output
WithCrossCore(true). // results are byte-identical on every core
WithCost(2). //
WithComponentID("com.example/discount"). // a stable identity for index-backing
WithSemanticVersion(1)) // bump when a formula change invalidates keys
if err != nil {
log.Fatal(err)
}
// with_tax(cents) -> cents plus 8% tax, as a BATCH kernel: it receives a whole column of rows per
// call (args[0][i] is row i's argument) and appends one result per row to out. jed calls it once
// per chunk where it already holds the rows, and one row at a time elsewhere — same rows, cost, and
// errors either way.
err = builder.RegisterFunction(
jed.NewHostBatchFunction("with_tax", []string{"i64"}, "i64",
func(args [][]jed.Value, out []jed.Value) ([]jed.Value, error) {
for _, v := range args[0] {
out = append(out, jed.IntValue(v.Int+v.Int*8/100))
}
return out, nil
}).
WithVolatility(jed.VolatilityImmutable))
if err != nil {
log.Fatal(err)
}
db, err := jed.CreateDatabase(jed.CreateOptions{Environment: builder.Build()})
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
mustExec(db, "CREATE TABLE product (id i32 PRIMARY KEY, name text, price_cents i64)")
mustExec(db, "INSERT INTO product VALUES (1, 'Mug', 1250), (2, 'Notebook', 400)")
// Because discount is IMMUTABLE and carries a component identity, it can back a persisted index.
// On reopen, if the environment supplies a different component/version, the index is skipped for
// reads (a correct heap scan) and refused for writes — never a silently stale result.
mustExec(db, "CREATE INDEX ON product (discount(price_cents, 10))")
// Call it by name from SQL, exactly like a built-in.
rows, err := db.Query(ctx,
"SELECT name, discount(price_cents, 15) AS sale, with_tax(price_cents) AS total FROM product ORDER BY id")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
r := rows.Row()
// Mug -> 1063 / 1350, Notebook -> 340 / 432
fmt.Printf("%s -> %s / %s\n", r[0].Render(), r[1].Render(), r[2].Render())
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
func mustExec(db *jed.Database, sql string) {
if _, err := db.Exec(context.Background(), sql); err != nil {
log.Fatal(err)
}
}
// discount.ts — shared registration code, imported inside the database worker.
// The public worker entry point is browser-safe and can also be imported on Node.
import { intValue, type EnvironmentBuilder } from 'jed-ts/browser/worker';
export function configure(builder: EnvironmentBuilder): void {
// discount(cents, pct) -> the price after a whole-percent discount. STRICT — a NULL argument
// short-circuits to NULL before the kernel runs, so the closure never sees one — and reached by an
// EXACT (i64, i64) signature (no implicit promotion; a built-in of the same signature would win).
// `cost: 2n` is charged once per call and gated against a session's maxCost before the kernel runs.
// The host remains responsible for the kernel's actual work and memory use.
builder.registerFunction({
name: 'discount',
argTypes: ['i64', 'i64'],
result: 'i64',
volatility: 'immutable', // same inputs ⇒ same output
crossCore: true, // results are byte-identical on every core
cost: 2n,
componentId: 'com.example/discount', // a stable identity for index-backing
semanticVersion: 1, // bump when a formula change would invalidate stored index keys
kernel: (args) => {
// strict + resolved (i64, i64), so both args are non-null ints
const cents = args[0] as { kind: 'int'; int: bigint };
const pct = args[1] as { kind: 'int'; int: bigint };
return intValue(cents.int - (cents.int * pct.int) / 100n);
}
});
// with_tax(cents) -> cents plus 8% tax, as a BATCH kernel: it receives a whole column of rows per
// call (args[0][i] is row i's argument) and pushes one result per row to `out`. jed calls it once
// per chunk where it already holds the rows, and one row at a time elsewhere — same rows, cost, and
// errors either way.
builder.registerFunction({
name: 'with_tax',
argTypes: ['i64'],
result: 'i64',
volatility: 'immutable',
batchKernel: (args, out) => {
for (const v of args[0]) {
const cents = (v as { kind: 'int'; int: bigint }).int;
out.push(intValue(cents + (cents * 8n) / 100n));
}
}
});
}
// In a separate Node application module:
// const db = await createDatabase({
// path: 'shop.jed',
// extensionModule: new URL('./discount.ts', import.meta.url).href
// });
// await db.get('SELECT discount(1250, 15) AS sale'); // { sale: 1063n }
// await db.close();
//
// In database-worker.ts for the browser:
// import { startDatabaseWorker } from 'jed-ts/browser/worker';
// import { configure } from './discount.ts';
// startDatabaseWorker({ configure });
//
// In the browser application:
// import { createDatabase } from 'jed-ts/browser';
// const db = await createDatabase({
// path: 'shop.jed',
// workerFactory: () =>
// new Worker(new URL('./database-worker.ts', import.meta.url), { type: 'module' })
// });
// await db.get('SELECT discount(1250, 15) AS sale'); // { sale: 1063n }
// await db.close();
Browser registration
Import your registration module into a worker and call the startup helper at the module’s top level:
// database-worker.ts
import { startDatabaseWorker } from 'jed-ts/browser/worker';
import { configure } from './discount.ts';
startDatabaseWorker({ configure }); Supply a factory when creating or opening the database. Keep new Worker(new URL(...)) directly
in the factory so your bundler can discover the worker entry point:
import { createDatabase, openDatabase } from 'jed-ts/browser';
const workerFactory = () =>
new Worker(new URL('./database-worker.ts', import.meta.url), { type: 'module' });
const db = await createDatabase({ path: 'shop.jed', workerFactory });
try {
console.log(await db.get('SELECT discount(1250, 15) AS sale')); // { sale: 1063n }
} finally {
await db.close();
}
// Bring the same registrations when reopening the file.
const reopened = await openDatabase('shop.jed', { workerFactory });
await reopened.close(); The factory must create a fresh dedicated worker for each database handle. Jed owns it,
terminates it after close or initialization failure, and rejects reuse with PROTOCOL.
Omitting workerFactory uses the ordinary package worker with no custom functions.
Call startDatabaseWorker once, synchronously. It installs the message listener immediately and
awaits configure(builder) before building the environment and opening storage. Configuration
can load data asynchronously; scalar and batch SQL kernels remain synchronous. A configuration
error rejects createDatabase or openDatabase and releases the worker.
The jed-ts/browser/worker entry point exports EnvironmentBuilder, HostFunctionSpec, HostKernel, HostBatchKernel, Value, intValue, and Decimal for registration code. A module
using these imports can also serve Node’s extensionModule, provided its other imports support
both hosts. Importing the entry point alone does not start a worker.
Functions can capture variables in their worker module. They cannot capture variables from the application thread, and changing an application variable does not change worker state. Pass changing inputs as SQL parameters. Calls run directly in the worker, without a callback to the application thread.
A function’s shape
Each registered function carries a name, an exact scalar argument signature, a scalar result type, a kernel, and three declarations:
cost— a non-negative static weight, charged once per call. This is the load-bearing one: it is guarded against a session’smax_cost, so a heavy host function aborts54P01before its kernel runs. This admits the declared work under the cost ceiling; the host remains responsible for the kernel’s actual work and memory use. (Defaults to1.)volatility—immutable/stable/volatile(PostgreSQL’s notion). Animmutablefunction may back a persisted index (below);stable/volatilemay not. Defaults tovolatile(the safe assumption).cross_core— whether the function’s results are byte-identical on every core. Recorded for the determinism ledger; not yet enforced. Defaults tofalse.
Two behaviors are guaranteed and free:
- Strict. A NULL argument short-circuits to a NULL result before the kernel runs — the kernel never sees a NULL, so it can read its arguments as concrete typed values.
- Result-type checked. A kernel that returns a value not matching its declared result type is
caught (
22000), so a misbehaving host function cannot leak a wrong-typed value into jed’s strict type system. An integer result must also fit its declared width: a function declared to returni32that returns2^40raises22003(value out of range for type i32) on that row.
Batch kernels
A kernel can take one row at a time, as above, or a whole column of rows per call. A batch
kernel receives its arguments column-major — args[j][i] is argument j of row i, never
NULL — and appends one result per row, in order, to an output column. To fail, it stops at the
failing row and raises; the results it already appended mark which row that was, so the error is
reported for exactly the row a one-row kernel would have failed on.
Both forms behave identically from SQL — same rows, same cost, same errors in the same order. The
difference is how often your code is entered: jed calls a non-volatile batch kernel once per chunk
of rows, then replays the row-by-row evaluation against those results. It does this
- in a projection over a filtered, joined, grouped, or sorted result, up to 1,024 rows at a time;
- in a streaming primary-key scan —
SELECT f(x) FROM t ORDER BY id, a key range, or a keyINlist — for both the projection and theWHEREclause (jed reads up to 64 rows ahead of the scan to form the chunk); - in the output of a streaming sort (
ORDER BYa non-key column), also up to 64 rows at a time.
A call is batched when it is a projection item or WHERE predicate itself, or sits beneath only
casts, arithmetic, comparisons, unary minus, NOT, or IS [NOT] NULL — f(x) + 1 and WHERE f(x) > 10 batch — and its arguments are columns, constants, or parameters. A call under CASE, COALESCE, AND/OR, or another function’s arguments is called one row at a time. That
matters most when a call crosses a language boundary — a binding that wraps jed in another language
pays the crossing once per chunk instead of once per row. A single-row kernel is always called one row
at a time, exactly on the rows the query evaluates — batching it would save nothing — and so is a volatile batch kernel, so its calls happen exactly as a one-row kernel’s would. So is a function
with no arguments: its batch kernel receives no columns to learn a row count from, so jed always
hands it exactly one row, and it appends exactly one result.
Because jed may compute a chunk ahead of the rows it emits, a batch kernel can run on rows a query
never returns — the tail of a chunk after a LIMIT is satisfied, a row the WHERE clause rejects,
or a row after an earlier error. Your kernel must be a plain per-row map: result i depends only on
row i’s arguments; an error it raises for a row the query never evaluates is discarded. With a LIMIT, the read-ahead never goes past the rows the limit can still return. On a session with a
cost ceiling, the chunk is capped at what the remaining budget could pay for at the declared cost,
so the speculation stays bounded.
Resolution: built-ins win
A host name — or a host overload of a built-in name over a new argument signature — resolves after the built-in catalog. So a built-in always wins an exact-signature collision (registering a
host abs(i64) is accepted but never reached), and overloading is by signature: discount(i64, i64) and discount(text, text) are two different functions under one name.
A call that matches no signature exactly goes through the same implicit argument coercion built-ins use. jed picks the host function (or built-in) whose arguments need the cheapest conversions:
- an integer widens to a wider integer (
i16 → i32 → i64), the nearest width first; - an integer becomes
numeric(cost more than any integer widening); - a number literal can become a float; an integer or
numericcolumn never does; - an
f32widens tof64.
So a host discount(i64, i64) also takes i32 columns, and a host scale_by(numeric) takes scale_by(3). Your kernel always receives values of the types it declared: jed converts the
arguments first. A built-in wins a tie, two host functions that tie are 42725, and a call no
conversion can reach is 42883, exactly as an unknown built-in. A bare NULL or $1 never matches
a host signature.
The registered name is used exactly as given. SQL folds a bare name to lowercase, so register names
in lowercase: a function registered as discount is called as discount(…) or DISCOUNT(…), but
one registered as Discount can only be called with quotes, as "Discount"(…).
Registration itself rejects three mistakes up front: a negative cost is 22023, an unknown
type name is 42704 (Go and TypeScript name argument types by string), and a second function
with an identical (name, arg-types) signature is 42723.
Backing an index
An immutable host function may be the key (or partial-WHERE predicate) of an index — CREATE INDEX ON t (geo_hash(location)) — so a derived value is indexed without any extra machinery.
Because the same SQL text re-binds to your code on reopen, an index like this must be able to tell
whether the code still matches. So an index-backing function declares two more things:
component_id— a stable string naming the implementation (e.g."com.example/geo_hash"), independent of the SQL name.semantic_version— a number you bump whenever a change to the results would invalidate keys built from the old code.
The file records that dependency. On reopen, if your environment supplies a different component_id,
a bumped semantic_version, or no such function, the index is treated as unusable:
reads simply skip it (you still get correct rows from a heap scan) and any write that would maintain
it is refused (XX002 on a mismatch, 42883 when the function is missing) — never a silently stale
result. A non-immutable or unversioned host function used in an index is rejected up front with 42P17. To adopt the new version, rebuild the index with REINDEX — REINDEX INDEX geo_idx (or REINDEX TABLE, REINDEX DATABASE) re-resolves the expression against your current functions,
records their new identity, and rebuilds the keys, all or nothing.
In DEFAULT and CHECK
A host function can supply a column default or enforce a check:
CREATE TABLE items (
id i64 PRIMARY KEY DEFAULT next_item_id(),
sku text CHECK (valid_sku(sku))
); The two are treated differently, because they relate differently to stored rows:
- A
DEFAULTruns once, when a row is written, and the value it produces is ordinary data. Changing the function later affects only new rows. So any host function may be a default (any volatility, nocomponent_idneeded), and nothing about it is recorded in the file. A statement calls the function only if it actually uses the default: anINSERTthat supplies the column, or anUPDATEthat doesn’t assignDEFAULT, works even when the host hasn’t registered it. One that needs the default gets42883. - A
CHECKis a promise about every stored row, so a changed function could leave old rows silently violating it. A check’s host function must declare acomponent_id(42P17otherwise), and the file records each one’s identity andsemantic_version, as for an index. Any volatility is allowed. On reopen with a differentcomponent_idor bumpedsemantic_version, every statement that would evaluate the check (INSERT,UPDATE, a foreign-key action that updates the table) is refused withXX002before writing anything. With the function missing, those statements get42883. Reads andDELETEnever evaluate a check, so they keep working.
To adopt a new version, re-add the check in one statement. It re-checks every existing row with the
current code (failing with 23514, and changing nothing, if one no longer passes) and records the
new version:
ALTER TABLE items DROP CONSTRAINT items_sku_check, ADD CONSTRAINT items_sku_check CHECK (valid_sku(sku)); Registration stays a host-API act, never SQL — there is no CREATE FUNCTION statement, so an
untrusted query surface can never register or redefine host code. The environment itself is a host
input a reopening host brings; only the dependency of an index or check on a function is
written to the file.
The boundary
A host kernel is opaque to the engine — it may compute anything, and jed cannot know whether it touches the filesystem, the network, or burns CPU. So host functions are deliberately outside the built-in untrusted-query safety guarantee: a host that exposes them to an adversarial query surface owns that decision. The engine’s one mechanical defense is the cost gate above — and it binds only a function that declared its cost. That is the whole trade: jed gives you a clean, first-class extension seam and a legible line where your code takes over.
The surface is still deliberately narrow — strict, with scalar signatures only. Host types and non-strict functions come later, as does batching at more sites (filters inside joins and blocking scans, aggregate arguments, writes, index builds — today they call a batch kernel with one row).