Session variables
A jed session can carry named string settings — PostgreSQL’s GUC model, scoped to the session.
The host sets them through the API; SQL reads them with current_setting(). They are a clean way
to thread per-request context (a tenant id, a request id, a feature flag) into the queries a session
runs, without weaving it through every statement’s parameters.
Setting and reading
A variable is a string → string pair (PostgreSQL settings are all text). A custom variable must be namespaced — a dotted name like myapp.tenant — to stay distinct from built-in settings; a
non-dotted name is rejected with 42704. Names are case-insensitive; values are kept verbatim.
use jed::{CreateOptions, Database, SessionOptions};
fn main() -> jed::Result<()> {
let db = Database::create(CreateOptions { path: Some("app.jed".into()), ..Default::default() })?;
// Session variables are PostgreSQL's GUC model — they live on a SESSION, so mint one from the
// database rather than using the bare handle. A custom variable must be NAMESPACED — a dotted name
// like `myapp.tenant`; a non-dotted name is 42704.
let mut s = db.session(SessionOptions::default());
s.set_var("myapp.tenant", "acme")?;
// Read it back through the host API — the name is case-insensitive; an unset name is None.
assert_eq!(s.var("myapp.tenant"), Some("acme".to_string()));
// ... or in SQL with current_setting(): `SELECT current_setting('myapp.tenant')` -> "acme".
let _rows = s.query("SELECT current_setting('myapp.tenant')", &[])?;
// An unset name is 42704, unless the two-arg form passes missing_ok = true, which returns NULL:
// SELECT current_setting('myapp.unset') -- 42704
// SELECT current_setting('myapp.unset', true) -- NULL
// Variables are SESSION state, not data — they do NOT roll back with a transaction. reset_var
// clears one by name.
s.reset_var("myapp.tenant")?;
// The built-in session time zone (UTC by default) decides how a timestamptz renders as text. A
// query returns a zone-free value; render it through the session to show it in the session zone.
s.set_time_zone("+05:00")?; // a fixed offset uses the POSIX sign: "+05:00" is UTC-5
let at = s.query("SELECT timestamptz '2024-01-15 12:00:00+00'", &[])?.next().unwrap()?[0].clone();
assert_eq!(s.render(&at)?, "2024-01-15 07:00:00-05");
assert_eq!(at.render(), "2024-01-15 12:00:00+00"); // a Value's own render is always UTC
s.close();
Ok(())
}
package main
import (
"context"
"fmt"
"log"
jed "github.com/jackc/jed/impl/go"
)
func main() {
db, err := jed.CreateDatabase(jed.CreateOptions{Path: "app.jed"})
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
// Session variables are PostgreSQL's GUC model — they live on a SESSION, so mint one from the
// database rather than using the bare handle. A custom variable must be NAMESPACED — a dotted name
// like myapp.tenant; a non-dotted name is 42704.
s, err := db.Session(jed.SessionOptions{})
if err != nil {
log.Fatal(err)
}
defer s.Close()
if err := s.SetVar("myapp.tenant", "acme"); err != nil {
log.Fatal(err)
}
// Read it back through the host API — the name is case-insensitive; ok is false if it is unset.
if v, ok := s.Var("myapp.tenant"); ok {
fmt.Println("tenant:", v) // acme
}
// ... or in SQL with current_setting(): SELECT current_setting('myapp.tenant') -> "acme".
if _, err := s.Exec(ctx, "SELECT current_setting('myapp.tenant')"); err != nil {
log.Fatal(err)
}
// An unset name is 42704, unless the two-arg form passes missing_ok = true, which returns NULL:
// SELECT current_setting('myapp.unset') -- 42704
// SELECT current_setting('myapp.unset', true) -- NULL
// Variables are SESSION state, not data — they do NOT roll back with a transaction. ResetVar
// clears one by name.
if err := s.ResetVar("myapp.tenant"); err != nil {
log.Fatal(err)
}
// The built-in session time zone (UTC by default) decides how a timestamptz renders as text. A
// query returns a zone-free value; render it through the session to show it in the session zone.
if err := s.SetTimeZone("+05:00"); err != nil { // a fixed offset uses the POSIX sign: UTC-5
log.Fatal(err)
}
rows, err := s.Query(ctx, "SELECT timestamptz '2024-01-15 12:00:00+00'")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
if rows.Next() {
at := rows.Value(0)
text, err := s.Render(at)
if err != nil {
log.Fatal(err)
}
fmt.Println(text) // 2024-01-15 07:00:00-05
fmt.Println(at.Render()) // 2024-01-15 12:00:00+00 — a Value's own render is always UTC
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
import { createDatabase } from 'jed-ts';
const db = await createDatabase({ path: 'app.jed' });
try {
const session = await db.session();
try {
// Namespaced custom variables belong to this worker-owned session and survive
// transaction rollback. Setters also return promises.
await session.setVar('myapp.tenant', 'acme');
const row = await session.get("SELECT current_setting('myapp.tenant') AS tenant");
console.log('tenant:', row?.tenant);
// Missing variables raise 42704; missing_ok=true returns SQL NULL instead.
console.log(await session.get("SELECT current_setting('myapp.unset', true) AS missing"));
await session.resetVar('myapp.tenant');
console.log(await session.get("SELECT current_setting('myapp.tenant', true) AS cleared"));
// Cast to text inside SQL to render in the session's time zone. Raw timestamp
// values retain their exact, zone-free bigint instant across the worker wire.
await session.configure({ timeZone: '+05:00' }); // POSIX sign: UTC-5
const at = await session.get("SELECT timestamptz '2024-01-15 12:00:00+00'::text AS at");
console.log(at?.at); // 2024-01-15 07:00:00-05
} finally {
await session.close();
}
} finally {
await db.close();
}
Reading a variable in SQL
current_setting('name') returns the variable’s value as text:
- An unset name raises
42704(unrecognized configuration parameter). - The two-argument form
current_setting('name', true)passesmissing_ok— an unset name returns NULL instead of raising. current_settingis stable and null-propagating, so it composes in ordinary expressions.
They are session state, not data
Session variables live on the session, not in the database:
- They are not stored in the file, and they do not roll back when a transaction rolls back
(PostgreSQL’s
SET SESSIONbehavior). - Each session has its own independent set — a variable on one session is invisible to another.
- Rust’s
reset_var(name), Go’sResetVar(name), and TypeScript’sawait session.resetVar(name)clear one variable by name (case-insensitive). Resetting an unset custom variable is a no-op; other variables are preserved. Initialize them withawait session.setVar(name, value)orawait session.configure({ vars: { 'myapp.tenant': 'acme' } }).
The session time zone
The one built-in setting is the session time zone, UTC by default. Set it with set_time_zone (Rust), SetTimeZone (Go), or await session.configure({ timeZone: "UTC" }) (TypeScript) to UTC, a fixed offset
such as +05:30 (POSIX sign: +05:30 is UTC−5:30), or a named zone from a loaded time-zone
database; an unknown zone raises 22023. The zone decides how a timestamptz is read without an
offset, how date_trunc, EXTRACT, and the datetime casts decompose it, and how it renders as text.
A query returns a timestamptz as a zone-free value. To show it the way PostgreSQL would, render it
through the session: session.render(&value) (Rust), session.Render(value) (Go), or
a SQL cast to text on the TypeScript session. This renders every timestamptz in the value — including one
inside an array, composite, or range — in the session’s current zone, for example 2024-01-15 07:00:00-05. A Value’s own render is always UTC (2024-01-15 12:00:00+00). Both
spellings carry the offset, so either one reads back as the same instant.
Scope. This is the v1 surface — the host API plus the
current_setting()read. The SQLSET/RESET/SHOWgrammar (includingSET TIME ZONE) and transaction-scopedSET LOCALvariables are planned follow-ons.