ctx.db
Every method of Table and SingleRow, the where operators, and the options and results of find, search, nearest and groupBy.
ctx.db holds one object per table in the luna’s schema: a Table, or a SingleRow for a table declared with singleRow: true.
import { defineLuna, t, table } from "luna";
export const List = defineLuna({
name: "List",
key: { id: t.string() },
schema: {
items: table(
{ id: t.id(), text: t.string(), done: t.bool().default(false), added: t.timestamp(), embedding: t.vector(384).optional() },
{ search: { columns: ["text"] } },
),
tags: table({ name: t.string(), uses: t.int().default(0) }, { primaryKey: ["name"] }),
stats: table({ adds: t.int(), last: t.timestamp() }, { singleRow: true }),
},
handlers: (h) => ({
open: h({ query: true }, (ctx) =>
ctx.db.items.find({ where: { done: false }, orderBy: { added: "desc" }, limit: 50 }),
),
}),
});
Reference
Table
Every method runs at once and returns without await.
find(opts?)(opts?: FindOptions) => Row[]
The rows that match, in order.
(opts?: FindOptions) => Row[]first(opts?)(opts?: FindOptions without limit) => Row | undefined
The first row that matches.
(opts?: FindOptions without limit) => Row | undefinedget(key)(key: unknown) => Row | undefined
The row with this primary key: a value, or for a key of several columns an array in key order or an object.
(key: unknown) => Row | undefinedcount(opts?)(opts?: { where?: Where }) => number
How many rows match.
(opts?: { where?: Where }) => numbergroupBy(by, opts?)(by: string[], opts?: GroupOptions) => GroupRow[]
One row per group of equal values in the by columns, the largest group first.
(by: string[], opts?: GroupOptions) => GroupRow[]insert(row)(row: Insert) => number
Adds a row and returns its rowid, which is the value of its t.id() column.
(row: Insert) => numberinsertMany(rows)(rows: Insert[]) => void
Adds each row in turn.
(rows: Insert[]) => voidupsert(row)(row: Insert) => void
Adds the row, or updates the columns given on the row with the same primary key.
(row: Insert) => voidupdate(opts)(opts: { where?: Where; set: Partial<Row> }) => number
Sets columns on the rows that match and returns how many changed.
(opts: { where?: Where; set: Partial<Row> }) => numberdelete(opts?)(opts?: { where?: Where }) => number
Deletes the rows that match and returns how many went.
(opts?: { where?: Where }) => numbersearch(query, opts?)(query: string, opts?: SearchOptions) => SearchHit[]
Rows that match a full-text query, best first. Needs the table's search option.
(query: string, opts?: SearchOptions) => SearchHit[]nearest(column, to, opts?)(column: string, to: Float32Array | number[], opts?: NearestOptions) => NearestHit[]
The rows whose vector column is nearest to, nearest first.
(column: string, to: Float32Array | number[], opts?: NearestOptions) => NearestHit[]within(box, opts?)(box: Box, opts?: { where?: Where; limit?: number }) => Row[]
Rows whose point is inside the box, edges included. Needs the spatial option.
(box: Box, opts?: { where?: Where; limit?: number }) => Row[]nearby(point, opts?)(point: { x: number; y: number }, opts?: { k?: number; maxDistance?: number; where?: Where }) => { row: Row; distance: number }[]
The k rows nearest a point, nearest first, 10 by default and at most 1,000.
(point: { x: number; y: number }, opts?: { k?: number; maxDistance?: number; where?: Where }) => { row: Row; distance: number }[]traverse(start, opts?)(start: unknown, opts?: { direction?: "out" | "in" | "both"; depth?: number; limit?: number }) => { node: unknown; depth: number }[]
The nodes reachable from start, nearest first. Needs the graph option.
(start: unknown, opts?: { direction?: "out" | "in" | "both"; depth?: number; limit?: number }) => { node: unknown; depth: number }[]path(from, to, opts?)(from: unknown, to: unknown, opts?: { maxDepth?: number; direction?: "out" | "both" }) => unknown[] | null
The nodes of a shortest path, or null if there is none.
(from: unknown, to: unknown, opts?: { maxDepth?: number; direction?: "out" | "both" }) => unknown[] | nullSingleRow
get()() => Row | undefined
The row, if it has been set.
() => Row | undefinedset(row)(row: Insert) => void
Writes the whole row. A column left out takes its default, or null.
(row: Insert) => voidupdate(set)(set: Partial<Row>) => boolean
Changes some columns of the row. False if there was no row.
(set: Partial<Row>) => booleanclear()() => void
Deletes the row.
() => voidWhere
An object with a condition for each column it names. Every condition must hold. A plain value means equal, and null means the column is null.
eq?V
Equal to. null means the column is null.
Vne?V
Not equal to. null means the column is not null.
Vgt?V
Greater than.
Vgte?V
Greater than or equal to.
Vlt?V
Less than.
Vlte?V
Less than or equal to.
Vin?V[]
One of these values. An empty list matches no rows.
V[]like?string
Matches an SQL LIKE pattern, with % for any text and _ for one character.
stringisNull?boolean
true for null, false for not null.
booleanFindOptions
where?Where
Only rows that match.
WhereorderBy?string | Record<string, "asc" | "desc">
A column to sort by, smallest first, or an object of columns and directions.
string | Record<string, "asc" | "desc">limit?number
The most rows to return.
numberoffset?number
How many rows to skip first.
number0startAfter?unknown[]
Only rows after this position, one value for each orderBy column.
unknown[]SearchOptions
where?Where
Other conditions the rows must meet.
Wherelimit?number
The most hits to return.
number20offset?number
How many hits to skip first.
number0match?"all" | "any" | "phrase" | "raw"
Every word, any word, the words together in order, or a raw SQLite FTS5 query.
"all" | "any" | "phrase" | "raw""all"prefix?boolean
The last word also matches as the start of a word, for search as you type.
booleanfalsesnippet?string | { column: string; open?: string; close?: string; tokens?: number }
Returns part of this search column with the matches marked, by <mark> and </mark> and 12 words long unless given.
string | { column: string; open?: string; close?: string; tokens?: number }NearestOptions
k?number
How many rows, at most 1,000.
number10where?Where
Other conditions the rows must meet.
Whereexact?boolean
Compares against every row even when the column has an index.
booleanfalseGroupOptions
where?Where
Only rows that match.
Wheresum?string[]
Columns to add up in each group.
string[]min?string[]
Columns to take the smallest value of.
string[]max?string[]
Columns to take the largest value of.
string[]limit?number
The most groups, the largest first.
numberResults
Row{ [column]: value }
A row as read, each column as its t builder's TypeScript type.
{ [column]: value }InsertRow with some columns optional
A row as written. Optional columns, columns with a default and t.id() columns may be left out.
Row with some columns optionalSearchHit{ row: Row; score: number; snippet?: string }
A match. A higher score is a better match.
{ row: Row; score: number; snippet?: string }NearestHit{ row: Row; distance: number }
A row and its distance by the column's metric. Smaller is nearer.
{ row: Row; distance: number }GroupRow{ [by column]: value; count: number; sum?; min?; max? }
A group's values, its row count, and each of sum, min and max asked for, as an object by column.
{ [by column]: value; count: number; sum?; min?; max? }Good to know
- Writes are kept when the handler returns and undone if it fails. In a query handler, a write fails the call.
upsert()andget()need a primary key.startAfterneeds one value for eachorderBycolumn. Both throw otherwise.- On a
t.json()column, an object inwhereis compared as a whole value, never read as operators. nearest()is exact without an index and below 10,000 rows. Above that, with an index, it is approximate. Withwhere, it checks a larger set of near rows, and compares against every row when too few of them match.- For a
geotable,nearby()measures distance in metres.traverse()goes 10 edges deep by default, at most 100, and returns up to 1,000 nodes unlesslimitsays otherwise.path()looks 6 edges deep by default, at most 12.
Examples
Page through rows
page: h({ args: { after: t.int().optional() }, query: true }, (ctx, { after }) => {
const rows = ctx.db.items.find({ orderBy: "id", limit: 20, startAfter: after ? [after] : undefined });
return { rows, next: rows.length === 20 ? rows[rows.length - 1].id : null };
}),
Match with operators
some: h({ args: { ids: t.array(t.int()) }, query: true }, (ctx, { ids }) =>
ctx.db.items.find({ where: { id: { in: ids }, text: { like: "%milk%" } } }),
),
Count done and open items
progress: h({ query: true }, (ctx) => ctx.db.items.groupBy(["done"])),
Insert or update by primary key
tag: h({ args: { name: t.string() } }, (ctx, { name }) => {
const uses = ctx.db.tags.get(name)?.uses ?? 0;
ctx.db.tags.upsert({ name, uses: uses + 1 });
}),
Keep a counter in a single row
add: h({ args: { text: t.string() } }, (ctx, { text }) => {
const id = ctx.db.items.insert({ text, added: ctx.now() });
const adds = ctx.db.stats.get()?.adds ?? 0;
ctx.db.stats.set({ adds: adds + 1, last: ctx.now() });
return id;
}),
Search as your app’s users type
find: h({ args: { q: t.string() }, query: true }, (ctx, { q }) =>
ctx.db.items.search(q, { prefix: true, snippet: "text", limit: 10, where: { done: false } }),
),
Find similar items
similar: h({ args: { to: t.array(t.float()) }, query: true }, (ctx, { to }) =>
ctx.db.items.nearest("embedding", to, { k: 5 }).map((hit) => ({ text: hit.row.text, distance: hit.distance })),
),