FennecQL

The query language you use to create collections, write documents and search them by vector, by text or by filter.

FennecQL is a small language: one statement reads or writes a collection of documents, and the same text runs in the browser, in an app, in the shell and over HTTP. This page is a tour of it and the grammar; the reference is a page for each family of statements, listed below the tour. Jump to the grammar.

An example of the reference with tabs shows the same statement written with each language's query builder, db a client of the server or the database in an app, and the statement that code sends. Each tab's code is run by that language's tests, as shown, and held to the statement.

A tour

One database, built in the shell a step at a time. Each step is a few statements as written with the shell's answer under them; the timings are from one run, and yours differ. To follow along, open a file with fennec books.fennec (Install has the download, and The shell the first steps) and type each line at the prompt. A write ends at a ;.

Make a collection and write to it

A collection has typed fields. put writes documents, and the database gives each an id.

fennec> create collection books (title text, year int, author int, copies int);
collection `books` created
fennec> put books [{title: "Desert Dunes", year: 2019, author: 1, copies: 3}, {title: "Night Oasis", year: 2024, author: 2, copies: 1}, {title: "Fennec Ears", year: 2021, author: 1, copies: 0}, {title: "Oasis Maps", year: 2016, author: 2, copies: 5}];
4 records (132.88µs)

More in Writing data.

Read it back

get with nothing after it is every row.

fennec> get books
id  title         year  author  copies
--  ------------  ----  ------  ------
1   Desert Dunes  2019  1       3
2   Night Oasis   2024  2       1
3   Fennec Ears   2021  1       0
4   Oasis Maps    2016  2       5
(4 rows, 102.58µs)

More in Reading data.

Filter and order

select names the fields to return, where keeps the rows, order sorts them and limit takes a page.

fennec> get books select title, year where year >= 2020 order year desc
title        year
-----------  ----
Night Oasis  2024
Fennec Ears  2021
(2 rows, 147.79µs)
fennec> get books select title, copies where copies > 0 order year limit 2
title         copies
------------  ------
Oasis Maps    5
Desert Dunes  3
(2 rows, 157.21µs)

More in Reading data.

Change it

A set can read the row it writes, and require 1 refuses the statement unless exactly one row changed. insert … returning id answers the id it made.

fennec> set books {copies: copies + 2} where title = "Fennec Ears" require 1;
1 records (156.21µs)
fennec> insert books {title: "Salt Roads", year: 2022, author: 1, copies: 4} returning id;
id
--
5
(1 rows, 110.04µs)

More in Writing data.

Index it

A filter works without an index, by reading the rows; an index makes one kind of question fast. explain runs a query and says how it ran: here the ordered index is walked and stops at the page.

fennec> create index on books (year) @sorted;
index built on `books.year`
fennec> explain get books where year >= 2020 order year desc limit 2
plan
----------------------------------------------------
order: walked the ordered index on year desc, 2 rows
rows: 2
(2 rows, 250.79µs)

More in Indexes.

A @text index lets match rank rows by how well their words match. fuzzy finds a word typed wrong, and highlight() says where in the text the words are.

fennec> create index on books (title) @text;
index built on `books.title`
fennec> get books select title match title "oasis"
title        _score
-----------  ------
Night Oasis  0.8755
Oasis Maps   0.8755
(2 rows, 258.04µs)
fennec> get books select title, highlight(title) match title "oasys" fuzzy
title        highlight(title)  _score
-----------  ----------------  ------
Night Oasis  [[6, 11]]         0.8755
Oasis Maps   [[0, 5]]          0.8755
(2 rows, 404.92µs)

More in Text search.

Follow a key into another collection

lookup attaches another collection's rows to each row, by a key that collection indexes. The shell prints them as joined rows; over JSON they nest under books.

fennec> create collection authors (name text, country text);
collection `authors` created
fennec> put authors [{name: "Ada", country: "UK"}, {name: "Bo", country: "TR"}];
2 records (92.46µs)
fennec> create index on books (author) @hash;
index built on `books.author`
fennec> get authors select name lookup books on author select title order year
name  books.title
----  ------------
Ada   Desert Dunes
Ada   Fennec Ears
Ada   Salt Roads
Bo    Oasis Maps
Bo    Night Oasis
(5 rows, 181.67µs)

More in Lookup and subqueries.

Count and group

An aggregate in the select list folds rows into one, and group makes one row per key.

fennec> get books select author, count(*) as books, sum(copies) as copies group author order books desc
author  books  copies
------  -----  ------
1       3      9
2       2      6
(2 rows, 154.25µs)

More in Aggregates and grouping.

Not in the tour: vector search, which finds the rows whose embedding is closest to one you pass, and types such as json, timestamp and geo.

The reference pages

A page for each family of statements: what it is for, a run you can repeat, then every rule, with the measurements and the internals folded under a line that says what is inside.

  • Reading data

    get, where, order, limit; pages by parameters, columns worked out, explain.

  • Writing data

    put, insert, set, del; upserts, require, returning, writes that pick their rows.

  • Collections and types

    json fields and paths, points, time, collation, nocase, alter collection.

  • Indexes

    Hash, ordered and unique indexes, indexes over several fields, rows that expire.

  • Lookup and subqueries

    Attach another collection's rows to each row, or filter by them.

  • Aggregates and grouping

    count, sum, group, having, bucket and time zones.

  • Text search

    match, typos, highlights, facets and hybrid search.

  • Vector search

    near, quantized indexes and sparse vectors.

Statements

FennecQL is a small language with vectors in the core. It is not SQL and does not try to be, but it reads SQL's everyday spellings as the statements they mean — select … from, CREATE TABLE, INSERT INTO … VALUES, UPDATE … SET a = …, JOIN as a lookup, IN (…), EXISTS, DISTINCT, BETWEEN, LIKE, ON CONFLICT — and refuses the rest saying what to write: see From SQL. These are all its statements.

create collection [if not exists] <name> ( <field> <type> [required] [collate und|tr] [nocase] [@index], ...
                                         [, @sorted(<field> [desc], ...) | @unique(<field>, ...)] )
drop collection [if exists] <name>
create index [if not exists] on <name> (<field> | <path>) @index
create index [if not exists] on <name> (<field> [desc], <field> [desc], ...) @sorted | @unique
drop index [if exists] on <name> (<field>, <field>, ...)
alter collection <name> add field <field> <type> [collate und|tr] [nocase] [@index]
alter collection <name> drop field <field>
alter collection <name> rename field <field> to <new name>
alter collection <name> alter field <field> @ttl(<duration>) | @sorted

put <name> { field: value, ... }              -- or [ {...}, {...} ]
insert [into] <name> { field: value, ... }     -- as put, refusing an id that is taken
put <name> { field: value, ... } if absent     -- a held id or @unique value passed over, and not counted
put <name> { ... } if absent else set { n: n + new.n }   -- an upsert: the row holding it set, new.f the document's
put <name> $1 [if absent ...]                -- the documents a parameter holds: an object, or a list of them
insert into <name> (a, b) values (1, 'x'), ... [on conflict do nothing | do update set a = ...]  -- SQL's spelling
update <name> set a = <expr>, b = <expr> [where ...]   -- SQL's spelling of set
get <name> [select a, b] [where <expr>]
           [near <field> <vector> [ef N] [exact]]
           [match <field> <text> [fuzzy [N]] [prefix]] [rerank <field> <vector> [candidates N]]
           [fuse [k N] [candidates N]]             -- match and near, both ranking
           [order <key> [collate und|tr] [asc|desc], ...] [limit N] [offset N]   -- N or a parameter, $2
                                                   -- a key: a field, or an expression, distance(loc, $1)
           [facet <field> [top N | ranges [..]] [disjunctive], ...]   -- value counts over every matched row
           [lookup <name> on <child> [= <parent>] [required] <clauses...>]...
           [lookup <name> on (<child>, ...) = (<parent>, ...) ...]   -- a key over several fields
get <name> select a, highlight(f [, pre, post]), snippet(f, N [, ellipsis [, pre, post]])
           match <field> <text> ...           -- where the words matched
get <name> where <field> in (get <name> select <field> ...)  -- a subquery's list
get <name> [where <expr>] count               -- number of matching rows
get <name> select [<key>,] count(*), count(distinct e), sum(e), avg(e), min(e), max(e),
           first(e [by k]), last(e [by k]), approx_count_distinct(e),
           hll_accumulate(e), hll_combine(sketch) [as <name>], ... [where <expr>]
           [group <key>, ... [having <expr>] [order <column> [desc]] [limit N] [offset N] [count]]
get <name> select a, <expr> as <name> ...     -- a column worked out over each row
explain get <name> ...                         -- the path the query took
select a, b from <name> [where ...]           -- the classic SQL order works too
set <name> { field: value, path: value } [where <expr>]  -- a value may read the row: {n: n + 1}
del <name> [where <expr>]
<set | del ...> [order <key> [desc], ...] [limit N] [returning * | a, b]   -- the page a get answers, written and answered
<put | insert ...> [returning * | a, b]       -- the rows written, ids and all, in the documents' order
<put | insert | set | del ...> require N [else '<reason>']   -- refused, and its batch put back, unless it wrote N rows
get <name> ... require N [else '<reason>'] [lookup ...]      -- refused, and its batch put back, unless it answered N rows; the reason is said

collections | describe <name> | compact [<name>]

-- a path, meta.source.rank, reads into a json field wherever a field is read
  • Every document gets an id on its own. Give one in a put and it writes over the document with that id.
  • insert never writes over. If an id is taken, the whole statement is refused; put … if absent passes over it instead, and the answer counts what was written; put … if absent else set {n: n + new.n} sets the row holding it instead, an upsert in one statement, new.f the document's field.
  • A set can read the row it writes. set hits {n: n + 1} where key = "ip1" is an increment, made under the write lock — see Writes that read the row.
  • A set or a del can pick its rows and answer them. order and limit write the page a get with them would answer, and returning hands it back: a job queue's claim in one statement — see Writes that pick their rows. A put or an insert answers the rows it wrote with returning, the ids it made among them.
  • A page's numbers take a parameter. limit $2 offset $3, and a facet's top $4: every page of a list is one statement, which a server parses once — see Pages by parameters.
  • require N makes a count a condition. A write that does not write exactly N rows, or a get that does not answer exactly N, is refused, and the batch it is in is put back whole — see Writes that must find their rows. else '<reason>' after the count says why, a text written in the statement (never a parameter, at most 200 bytes, no backtick), which a caller reads back as reason — see A reason for the refusal.
  • alter collection rewrites no document. A field added reads null in the documents already there; a field's type does not change — see Changing a collection.
  • A statement ends where the next one begins, or at a ;. No separator is needed, and a statement may run over several lines: the parser reads where each ends. A ; ends the statement before it, so no clause goes on past one — del notes; where id = 3 is refused, not read as one statement, and so is a ; inside brackets, in (get … ;). A clause that is a statement too begins one after it: get a lookup b on k; select z is two statements, the second a read of z. A query string's select=, group= and facet= take a ; after their list as they always did. How the shell runs statements written over lines is in The shell.

Named statements

A named statement is a statement, or a block of them, defined once in a database and called by name with typed arguments, running with its own text's authority — PostgreSQL's function used as an API, with FennecQL for its body. The server's token defines one, as it makes any schema change; a scoped token calls only what its policy grants it (Calling a named statement). A definition is a record of its database's file, kept by every compact, sent to its replicas and read back by every open, which checks that its text still reads as the statement it was; a schema change taking away a field, a collection or an index one reads is refused naming it.

create [or replace] statement <name>($p <type> [= <literal>], ...)
       [claims (<c> <type> [from "<claim>"], ...)] [public] [scans] [comment '<text>'] [check <expr>]
       as <statement> | as begin <statement>; ... end   -- $p and $jwt.<c> in the body
drop statement [if exists] <name> | statements | describe statement <name>
call <name> [{p: value, ...} | $1] [as {c: value, ...}]   -- SQL's CALL <name>(v, ..., p => v)

A body holds get, insert, and set and del with a where or a pick, and its last statement names the fields it answers; a put, a parameter's documents, a schema change, a call or a collection whose name starts with _ is refused as the definition is read. Defining a statement also checks that each field a body writes or filters on is one its collection holds, and that a writing body reads its rows through an index (an equality, an in or a range over id or an indexed field, a pick an ordered index walks, near, match, fuse) unless the definition says scans: a call holds the write lock while it walks. A $name outside a definition is refused: a statement sent alone numbers its parameters, $1.

A call runs through POST /_call/<name> — its arguments the body's params, answered as /query answers the call — through /query and /batch, the shell and the native library. One whose body writes is one block under the write lock: its writes land together or not at all, a read in it sees the writes before it, and an Idempotency-Key makes it once. One whose body only reads is a read: it runs beside the other reads, takes no write lock and keeps no key — on a pinned snapshot with no lock held where it reads many rows — so a read-only server, a replica and a request marked Fennec-Read: replica answer it (read replicas), and a query across tenants merges it. They refuse one whose body writes (403), once its grant, claims and arguments were asked. Either way the answer is its last statement's, as /query would give it, with the change it stands at in Fennec-Seq. Fennec-Wait holds a call whose body sets or deletes until it writes, as it holds those statements sent alone (Holding a write); one whose body inserts is refused. /_stats/statements counts every call as call <name> $1, however its arguments were written, and never its body's statements apart. The arguments are a document, a parameter's object or SQL's list, by name or by place, and the signature types them: one missing, extra, null where the parameter has no default, or of another type is a 400 naming it. A check that is false is a 400. The claims a statement declares come from the token, or from as {…} for the server's token alone; one the caller lacks — missing, null, "", an empty list or of another type — is a 403, and nothing runs; so is a list claim of more than 1 000 values, never cut to them. A require … else '…' that is not met puts the block back, a 412 carrying its reason. A broken statement, whose text no longer reads — a number written past its range that an earlier version clamped, say — or whose collection, field or index the schema lacks, is a 409 saying why, once its claims, arguments and check were asked. A call examines at most --call-max-rows rows, 100 000, counted however its statements read them — a scan, an index, an ordered walk, near, match and a lookup's children alike: past it the block is put back and the call is a 400 naming the bound, never answered from the rows it reached.

statements lists them and describe statement describes one, its text and what it depends on included, to the server's token; a scoped token is told what it may call by /_whoami. A schema declared in code — a schema.fennecql a server or the native library applies — may hold create statements after the collections they read: the plan compares each with the database's by what it means, never its text, and applying a planned definition defines it. The browser module reads none of these forms, refusing them as named statements are a server's; a file holding them opens in every build, the module's included, which keeps them as they came.

A tenant's schema may declare them at the router as at a node (Tenants). Before a primary defines the first one, every reader of its file runs a release that knows them — its archivers, replicas and standbys, the nodes a move or a restore may put it on, and the routers: a binary from before refuses the record a definition writes, and stops there (Replication).

Every SDK has a call method, Dart's callStatement, which sends call transfer $1 with the arguments as the one parameter — a value is never text, and the name is checked against the rule above — and the claims after them, as $2, for the server's token. Each call below is what an SDK sends for the statement beside it:

call transfer {from: 1, to: 2, amount: 300}
call history {account: 1} as {sub: "alice"}
import { connect } from '@fennecdb/web/client'
await db.call('transfer', { from: 1, to: 2, amount: 300 });

await db.call('history', { account: 1 }, { claims: { sub: 'alice' } });
from fennecdb import Client
db.call("transfer", {"from": 1, "to": 2, "amount": 300})

db.call("history", {"account": 1}, claims={"sub": "alice"})
import fennecdb "github.com/fennec-db/fennecdb/integrations/go"
db.Call(
	ctx,
	"transfer",
	fennecdb.Params{"from": 1, "to": 2, "amount": 300},
)

db.Call(
	ctx,
	"history",
	fennecdb.Params{"account": 1},
	fennecdb.Claims(fennecdb.Params{"sub": "alice"}),
)
using FennecDb;
await db.CallAsync(
    "transfer",
    new Dictionary<string, object?> { ["from"] = 1, ["to"] = 2, ["amount"] = 300 }
);

await db.CallAsync(
    "history",
    new Dictionary<string, object?> { ["account"] = 1 },
    claims: new Dictionary<string, object?> { ["sub"] = "alice" }
);
import FennecDB
try await db.call(
    "transfer",
    ["from": 1, "to": 2, "amount": 300] as Value
)

try await db.call(
    "history",
    ["account": 1] as Value,
    claims: ["sub": "alice"] as Value
)
import com.fennecdb.*
db.call("transfer", mapOf("from" to 1, "to" to 2, "amount" to 300))

db.call(
    "history",
    mapOf("account" to 1),
    claims = mapOf("sub" to "alice")
)
import 'package:fennecdb/fennecdb.dart';
await db.callStatement(
    'transfer',
    args: {'from': 1, 'to': 2, 'amount': 300}
);

await db.callStatement(
    'history',
    args: {'account': 1},
    claims: {'sub': 'alice'}
);
sends
call transfer $1
-- [{"from": 1, "to": 2, "amount": 300}]
call history $1 as $2
-- [{"account": 1}, {"sub": "alice"}]

A read option marks a statement that only reads, which a client reading near has answered by a read replica (a statement that writes is refused there, 403, never landed); without it a call goes home. A refusal is the SDK's error with the call's status and, for a require … else '…', its reason (Your language, Mobile). An agent calls each statement its token may call as an MCP tool of its own, call_transfer, typed by the signature (MCP); fennec studio lists them in its schema view and calls one from a form; the shell's .help gives the forms above. A sync replica refuses call, create statement and drop statement: its app calls the server through its HTTP client.

Statements bound to writes

A named statement may be bound to the writes of one collection instead of being called: it runs in the block of the write that woke it, once for each row that write made, wrote over or took out, with that row as new. and old. — a ledger line, a counter, a denormalized field kept with the write that made them, in the record that holds it. A crash, a replica and a subscriber see the write and what it woke together, or neither.

create [or replace] statement <name>
       after insert | set | del [or ...] <collection> [where <condition>]
       [comment '<text>'] [scans]
       as <statement> | as begin <statement>; ... end   -- new.<field> and old.<field> in the body
create statement paid_ledger
  after set orders where new.status = 'paid' and old.status = 'open'
as begin
  get accounts select id where id = new.account limit 1 require 1 else 'no such account';
  insert ledger {order: new.id, account: new.account, amount: new.total, at: now()};
  set accounts {balance: balance - new.total} where id = new.account
end

An event is what happened to a row, whatever statement did it: insert a row made — by insert, by a put of an id not held, or of one whose row is past its @ttl time, which every read already saw gone; set a live row written over — by set, a put naming its id or an upsert's else set; del a row taken out by del. SQL's update and delete read as set and del. new. is the row as the write leaves it and old. the row as it stood: an insert binding reads new. alone, a del binding old. alone, a set binding both. The where reads new., old. and now(), each field compared in its collation and case fold as a get compares it. The body is a callable statement's, its values the row's: no parameters, claims, check or public, a get only with require (a guard), no returning.

The bindings run after the statement's own rows, hooks and require, before its block lands: row by row in the order the statement wrote them, and on each row the bindings it passed in name order. Each condition is asked as its row is written, and only a row passing one is kept; now() is read once for the whole write, condition and bodies alike. A write waking more than 10 000 rows is refused (400), and the bodies one statement runs examine at most --call-max-rows rows together — a call's own budget when the write is in a call's body: past either, nothing lands, never a part. A binding's error is its writer's — a guard's require is a 412 with its reason, a unique value taken a 409 — and the block is put back whole, a /batch's statements before it included. Under Fennec-Wait a binding's 412 is answered at once, never held: the wait is for the writer's own rows. A set held on a derived collection, set ledger {...} where ..., is answered by the write whose binding inserted the row it waits for.

Depth one: a binding's own writes wake nothing, so one writing the collection it is bound to, one writing a collection another statement is bound to and one bound to a collection another binding writes are each refused as they are defined, as is one bound to or writing a collection whose name starts with _, the database's own (_idempotency, _consumers). A collection is bound by at most 16 statements; after del is refused on a collection whose rows expire (@ttl), and @ttl under one, since no binding sees a row expire. A binding is never called (400). A replacement keeps the collection and events it is bound to and each collection and kind of write it makes; anything else is a drop and a create. A broken binding — a dependency gone, a text that no longer reads — refuses every write it binds (409) until it is defined again or dropped: a write never lands without its rows.

The server's token defines one and its writes wake it at every way in — /query, /batch, the REST routes, MCP's write, a held write, a call's body, the shell and the native library, and a schema declared in code may declare it, a tenant's at the router too, after the collections it binds and writes (Tenants). A scoped token's write, or call, wakes one only where the policy's wake line grants it (Waking a bound statement): its writes are then the statement's own, judged by no rule of the token's, and otherwise the write is refused (403) before anything runs — a binding never runs on a token's behalf without one, and never skips. A write waking none — a row its condition does not pass, an event it is not bound to — is a token's as ever. What copies or loads rows wakes nothing, its derived rows made elsewhere or by its operator: a replica's apply and a restore, which take the bound rows from the record, fennec import, --follow's mirror, a declared schema's migrations, a sync replica's apply of its streams, and the @ttl sweep. The browser module runs none: it refuses the writes a binding binds, write it through a server. Before a primary defines the first one, every reader of its file runs a release that knows them: a binary from before refuses the record and stops there, in words (Replication).

A binding's refusal is told to the server's token with the binding's name: the error carries binding beside the engine's words, which begin bound statement `voided`, after `set` on `orders`, refused this write: . It does on /query, keyed with an Idempotency-Key or not, on /_call, on the REST routes and on /batch, whose stop body also holds at, completed and the guard's reason (Refusals and their statuses). The native library answers {"kind":"error","message":"bound statement `voided`, after `set` on `orders`, refused this write: unmet: ...","reason":"no ledger line","binding":"voided","at":1}, its at only for a text of several, and the shell prints error: bound statement `voided`, after `set` on `orders`, refused this write: ...: an app and the shell hold their file's authority. A scoped token is told its status and reason alone, never the binding's name. Every SDK reads it from its error as it reads reason: JavaScript's and Python's FennecError.binding, Go's Error.Binding, .NET's FennecException.Binding, Swift's FennecError.binding and Kotlin's and Dart's FennecException.binding, the last three from the native library too (Languages). fennec studio lists a collection's bindings in its schema view, each opened in the query editor as create or replace statement ... and none given a call form, and the shell's .help gives the form.

statements has an after column, ["orders","set"] for a binding's collection and events and null for a statement that is called, and describe statement adds condition, the where as written (new.status = 'paid' and old.status = 'open') or null; both are the server's token's. GET /_schema lists each collection's bindings beside it, "bindings":[{"name":"paid", "events":"set","text":"create statement paid after set orders ..."}], and ?as=fennecql writes each definition after the collections. Either reads back through POST /_schema/plan and /_schema/apply, which plan the bindings listed: a binding's text says what it binds, and one listed with events its text does not bind is refused. A scoped token sees no binding there, no name and no text (HTTP reference).

How often a binding ran, how long it took and what it refused are counted in /_stats/statements (the shape after paid_ledger) and in /_metrics, named in the slow-statement line, given a span each and written to the audit log when it is defined, dropped or refuses a scoped writer.

Scheduled statements

A named statement may run by the clock instead of being called: every quarter of an hour, at 03:00 in Berlin, on the first of the month — a purge, a hold lapsed once its time is up, a monthly reset. The server that writes its file runs it, each run and the mark of the slot it ran for landing as one block: a crash, a replica and a subscriber see the run and its mark together or neither, and no slot runs twice.

create [or replace] statement <name>
       every <interval> | at '<cron>' [in '<zone>']
       [comment '<text>'] [scans]
       as <statement> | as begin <statement>; ... end   -- now() and slot() in the body
create statement lapse_holds
  every 1m
  comment 'Lapses each hold whose time is up, a thousand a minute'
as set holds {state: 'lapsed', lapsed_at: now()}
   where state = 'held' and until < now() order until limit 1000

create statement monthly_reset
  at '0 0 1 * *' in 'Europe/Berlin'
  scans
as set plans {used: 0, period: slot()} where used > 0

every <interval> runs at the edges bucket cuts — a whole number of minutes, hours, days or weeks counted from the epoch, a week from a Monday, or calendar months (mo, y) — so every 15m runs at :00, :15, :30 and :45, never a quarter of an hour after its definition. at '<cron>' takes cron's five fields, minute, hour, day of the month, month and day of the week, each *, a number, a range, a list or a step, Sunday 0 or 7, and the three-letter English names. in '<zone>' names the clock it reads, one of IANA's zones or a fixed offset, UTC without it: a time the clock skips the night summer time starts runs at the instant it jumps past it, once, and a time it shows twice runs once, at the first; every 1h runs twice in the hour shown twice, as bucket(at, 1h, 'Europe/Berlin') has two of it. A minute is the finest period. Refused as the definition is read, each naming the form to write: a period under a minute or not of whole minutes, cron's sixth field (Quartz's seconds), ?, L, W, # and the @hourly macros, a day of the month and a day of the week both written (0 0 13 * 5, which cron runs on every Friday and every 13th), an expression that never runs (0 0 30 2 *), and a zone the binary's table does not hold. The body is a called statement's with nothing to call it with: no parameters, claims, check or public, no new. or old., no returning, a get only with require (a guard), and a body of guards alone is refused. A database holds at most 16, and a statement runs by the clock or after a write, never both.

now() is the run's start, read once a run — the time @ttl reads too, so a late run leaves out the rows every read already left out — and slot() the instant of the slot it ran for: monthly_reset's period is the month's first midnight in Berlin even when a restart ran it at 00:40. slot() is a constant of the run, so where period = slot() reads through an index on period as where period = $1 would, and needs no scans. slot() outside a scheduled statement is refused. A definition starts its schedule at its own landing: one made at 02:59 every 1h runs at 03:00, one made at 03:01 at 04:00. A server down for a day, or a clock stepped forward, finds the slots it missed and runs the latest once, the others counted as passed over — never a day of runs at once. A clock stepped back behind the last run waits for it, an hour at most; a run's mark further ahead than that is taken for a wrong clock's, and the schedule goes on from the clock — as it does from a definition a clock that far ahead made: the latest slot runs once, and each after it as it comes. A replacement starts its schedule again from its own landing.

Who refused decides whether a slot is spent. A refusal the statement makes — a guard's require unmet, a broken statement, a unique value taken, --call-max-rows, a statement bound to its writes refusing them — spends the slot, its status and the guard's reason noted, and the next slot runs as due. A refusal the server's state makes — a tenant's quota, a storage error — leaves the slot due, tried again as the data or the limit changes, at most once a minute, and otherwise after a wait that doubles from a minute to fifteen; the next slot takes its place. A run that finds nothing to do writes nothing: no record, no fsync, no send to a replica, its mark kept in memory until the next write lands. A run is a write as any other: its writes wake the statements bound to them, in its block, and a held write reading what it wrote, and they reach a replica, an archive and /_changes as any write does; under --sync always it is fsynced, and its replicas sent it, before the next run. A run examines at most --call-max-rows rows, each run a fresh budget, and is no one's request: no rate is charged for it.

A server that may write runs them, from one thread that sleeps while no schedule is held: a fennec-server <file> primary, a replica from its promotion, which runs a slot then due at once, and a tenant node, which opens a closed tenant as its slot comes and closes it after its run (Scheduled statements on a node). Should that thread fail outside a run, the server stops through its usual shutdown rather than answer with its schedules unrun. A replica runs none — its primary's runs come to it with their marks — nor does a server under --http-read-only, which says how many it holds unrun at its start and again as its primary's reach it, nor one whose storage failed. The shell, the native library and the browser module run none and take no definition, since nothing of theirs would run it; a file they hold keeps its schedules, and the server that next writes it runs each slot due, once, the latest.

The server's token defines one, as it makes any schema change; the audit log's schema line names its schedule beside the statement's shape. The server's token may call one to run it now — an operator's test — which runs the body, answers its last statement and spends no slot, its slot() the latest slot at or before the call: the slot that has come, under its label. To a scoped token a scheduled statement is the 404 a missing statement is, at /query, /batch and POST /_call/<name>, whatever its policy's call lines say — the server logs such a line as granting nothing — and an agent gets no MCP tool for it. statements lists it to the server's token, its after null. A refused or held run is written to the server's log with an id of the run's own; a run's mark found ahead of the clock is written there, once, and to the audit log as a clock line. A sync replica refuses the definition, as it refuses every create statement: what a run writes reaches it through its shapes' streams. Before a primary defines the first one, every reader of its file runs a release that knows them: a binary from before refuses the record and stops there, in words (Replication).

Where a schedule stands is in the listings, to the server's token alone (a scoped token's statements is 403 and describe statement 404): four columns follow after. schedule is the clause as the text writes it (every 15m in 'Europe/Berlin'). next is the slot due now — shown past, overdue, where the scheduler holds it back or nothing runs it yet — else the first slot after now. last is the last slot's mark, pending or landed: {outcome, reason, skipped, slot, status}, outcome "ran" or "refused", and null before the first run. held is a due slot the state holds back — the tenant's quota, a lapsed lease, a storage error — as {since, slot, status}, else null. It is the scheduler's memory, not the file's: after a restart the slot is found due and held again. All four are null for a statement that is called or bound. Two more follow held, hook and armed, which a webhook consumer fills and these leave null.

{"name":"reset","version":[0,4],"signature":"()","writes":true,"comment":null,"broken":null,"after":null,"schedule":"every 15m","next":"2026-05-04T12:15:00Z","last":null,"held":{"since":"2026-05-04T12:16:00Z","slot":"2026-05-04T12:15:00Z","status":507},"hook":null,"armed":null}

A refused run's last holds the status and the guard's reason: {"outcome":"refused","reason":"no hold to look at","skipped":0,"slot":"2026-05-04T12:15:00Z","status":412}. GET /_schema lists the same beside the collections, as schedules, and ?as=fennecql writes each definition after them (HTTP reference). How often a schedule ran, how late, and what it refused are counted in /_metrics and /_stats/statements (the shape schedule lapse_holds), named in the slow-statement line and given a trace a run.

Every SDK reads the listing into types of its own — db.statements(), Go's Statements, .NET's StatementsAsync, each row a NamedStatement with its LastRun and HeldSlot, the times in the language's own (every SDK's). fennec studio lists a scheduled statement among the named statements by its schedule, with its next slot, last run and held slot, runs one now — call lapse_holds, marking no slot — and opens its definition as create or replace statement ...; its editor colours every, slot and the at before a cron text. The shell's .help gives the form, which a server defines and runs.

Webhook consumers

A named statement may take another service's events instead of being called: Stripe's payments, GitHub's pushes, the events of any sender signing as Standard Webhooks does, sent to POST /_hooks/<hook> on a file's server given a hooks file (--hooks). The server verifies each event's signature before it reads anything of it, binds its values to the statement's typed parameters, and takes it once by its key: the statements' writes and the key's row in _hook_events land as one block, and the sender is told 2xx once that block is on disk, whatever --sync says. Webhooks from Stripe and GitHub has the setup of each sender, the hooks file and every answer.

create [or replace] statement <name>
       ($p <type> from event.<path> | event | hook.id | hook.at | hook.event, ...)
       on hook <hook> [where <condition>]
       [comment '<text>'] [check <expr>] [scans]
       as <statement> | as begin <statement>; ... end
create statement stripe_paid(
    $intent text from event.data.object.id,
    $order  text from event.data.object.metadata.order)
  on hook stripe
  where event.type = 'payment_intent.succeeded' and event.livemode = true
as set orders {status: 'paid', intent: $intent}
   where ref = $order and (status = 'open' or intent = $intent)
   require 1 else 'no open order for this payment yet'

Every parameter names where it is read from: a path into the event's body (from event.data.object.id; a key that is no word quoted, event.metadata."order-id"; a key of digits a list's place, event.items."0".sku), the whole body for a json parameter (from event), or the delivery's own hook.id (its key), hook.at (the time its signature covers, a timestamp) and hook.event (GitHub's X-GitHub-Event). A value is typed with no cast: a string where an int is declared is refused 400, naming the parameter and its path, and a timestamp read from a number takes it as milliseconds — Stripe's created, in seconds, is read as an int and written $created * 1000. The condition reads the event, hook.event and literals alone; an event no condition takes is answered 200, {"taken":0}, and writes nothing. A hook's statements take an event together, in their names' order, in one block under one --call-max-rows, now() one instant for all; a refusal by any is the event's answer, its writes and the key put back.

The server's token defines one, and may call one with an event as its argument to try it — run as an event would be, keeping no key. To a scoped token a hook's statement is the 404 a missing statement is, whatever its policy's call lines say, and an agent gets no MCP tool for it. Each tenant of a node takes its own at /t/<tenant>/_hooks/<name>, its secrets set through the admin routes. A replica, a server under --http-read-only, a sync replica, the shell, the native library and the browser module take none: each refuses the definition, and a file holding one keeps it. Before a primary defines the first one, every reader of its file runs a release that knows them: a binary from before refuses the record and stops there, in words (Replication).

Where a hook stands is in the listings, to the server's token alone (a scoped token's statements is 403 and describe statement 404): two columns follow held. hook is the hook the statement takes, from its record, else null. armed is whether this server holds a secret for that hook: on a file's server, a line of its hooks file names it; on a tenant node, the tenant's set holds it. It is asked as the listing is written, so a PUT or DELETE through the router changes it while the tenant is open. false is no secret held, and the hook's events are answered 401, or a tenant's hook kept from 0.2.0 with key delivery, its verified events answered 409 until it is set again (Webhooks); null is a statement that takes no hook. The shell and the native library take no event, and say false for a statement that takes a hook.

{"name":"stripe_paid","version":[0,4],"signature":"($intent text from event.data.object.id, $order text from event.data.object.metadata.order)","writes":true,"comment":null,"broken":null,"after":null,"schedule":null,"next":null,"last":null,"held":null,"hook":"stripe","armed":true}

describe statement of a webhook consumer shows its condition as its text writes it (event.type = 'payment_intent.succeeded' and event.livemode = true), and its signature names what each parameter reads: a path into the body ($intent text from event.data.object.id), from event for the whole of it, or from hook.id, from hook.at and from hook.event. A quoted key is shown as the event's JSON names it, event.metadata.order-id. GET /_schema lists a hook after the scheduled statements, as hooks ([{"name", "hook", "text", "armed"}], never a secret), and ?as=fennecql writes each definition after the scheduled ones (HTTP reference). Events are counted by outcome in /_metrics and by statement in /_stats/statements (the shape hook stripe_paid); a slow event is named in the slow-statement line, and each statement it ran is a span. Webhooks from Stripe and GitHub gathers them, with the Datadog monitors.

Every SDK's NamedStatement carries the two columns, hook and armed (every SDK's), and its call sends a webhook consumer a test event, the event its one argument. fennec studio lists a webhook consumer among the named statements by its hook, armed or not, sends it a test event begun from the paths its parameters read and the values its condition compares, and opens its definition as create or replace statement ...; its editor colours hook and the event of event.<path>. The shell's .help gives the form, which a server defines and takes events for.

How insert and put treat an id

The id field is automatic. Supplying id inside a put turns it into an upsert. insert makes documents and never writes over one: a document naming an id that is taken refuses the statement, and nothing of it is written — 409 over HTTP, as PostgreSQL's INSERT refuses a taken key. Without an id the two are the same. A retried write that must not be made twice either way sends an Idempotency-Key.

Reference

Types, indexes, operators and functions at a glance.

Typesbool int float text bytes timestamp vector<N[, f16]> sparse<N> [type] json geo (a point, [lon, lat] — see Points)
Caseemail text nocase compares by its case fold wherever it is compared — =, its indexes, order, group — and keeps what was written — see Case-insensitive text
Pathsmeta.source.rank reads into a json field in where, select, order and set, and takes @hash, @unique and @sorted — see Objects and paths
Indexes@sorted(owner, created desc) and @unique(org, slug) over several fields (see Indexes over several fields), @hash, @unique, @sorted, @ttl(30m) (a timestamp field's rows expire — see Rows that expire), @text(k1=.., b=.., prefix=.., chars, accents), @hnsw(metric, m=.., ef_construction=.., ef_search=.., quant=int8|bit), @inverted (a sparse<N> field's), @geo (a geo field's)
Defaults@hnsw(cosine, m=16, ef_construction=200, ef_search=100); ef_search=200 with quant=bit; m is 2 to 32 767, ef_construction from 4 (pgvector's floor) and ef_search from 1, each refused past its range (Limits)
Metricscosine l2 dot
Operators= != (or <>) < <= > >=, ~ text contains (case-insensitive), has list contains, in [..] (or in (..)), in $1 (a parameter holding the list — see A list in one parameter), in (get …) — see Subqueries, is null, between a and b, like and ilike with % and _, not in, not like, not between — see From SQL
Arithmetic+ - * / on numbers, a timestamp moved by milliseconds, and + (or ||) joining two texts — in a set's values and in where; see Writes that read the row
Logicand or not — and binds tighter
Parameters$1, $2, … as in PostgreSQL, wherever a value goes, and as limit, offset and a facet's top — see Pages by parameters; a list in one, where id in $1 — see A list in one parameter
Functionslower upper len coalesce greatest least now expired (rows past their @ttl) timestamp bucket(at, 15m [, zone]) cosine l2 dot norm normalize distance(loc, p) within(loc, box) (Points), case when … then … else … end, plus plugins — see Functions over a row
Orderingorder year desc, title asc — a tie on the first key is decided by the second; a null comes first ascending, and a float's NaN last, above every number, as in PostgreSQL (see Collections and types); values of two kinds — a json field's, an expression's — order by kind, every number (a time among them) below every text, and order timestamp(meta.at) orders ISO texts as times (see Two kinds); id can be ordered too; a key may be any expression over the row, order distance(loc, $1), order price * qty desc (see Ordering by an expression); order name collate und puts text in Unicode's order for every language and collate tr in Turkish order, and a field declared name text collate und is in it wherever it compares — see Collation
Pickingset … order run_at limit 10 returning * writes the rows a get with the clauses answers and hands them back, as written; del … returning as they were; insert … returning id the rows it made — see Writes that pick their rows
Explainexplain get ... runs the query and returns the path it took, one row a step — see Explain
Typosmatch body $1 fuzzy matches each word within the edits its length allows, a word as typed ranking first; prefix matches the last word as the start of one, as a search box is typed into — see Typos and words begun
Highlightshighlight(body) and snippet(body, 20) in the select list mark the words a match found, as UTF-16 offsets or between tags you pass — see Highlights and snippets
Facetsfacet brand, color top 10 counts each value over every row the query matches, beside the page — see Facets
Countingcount returns one row with one column; it does not combine with select, near, order, limit or offset, and beside match counts every row it finds — see Matches in another order, and counted
Aggregatescount(*) count(…) (the rows it is not null in) count(distinct …) sum avg min max first(… by …) last(… by …) approx_count_distinct hll_accumulate hll_combine over fields, paths or expressions, whole or per group of one key or several, the groups kept by having — see Aggregates and the analytics and market-data recipes
Columnsselect px * qty as notional: an expression over the row, named with as — see Columns worked out
Ceilingsnear, match and fuse rankings at most 10 000 rows (limit + offset, a parameter's as a number written; a match beside order, count or an aggregate ranks nothing and has none), rerank at most 10 000 candidates, fuse 10 000 a side; a word of a fuzzy or prefix match 10 000 words of the index; expression depth 512 levels; a json value 64 levels deep, a path 64 keys; in (get …) 100 000 values and 4 levels — see Limits