Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

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.

PropType
find(opts?)(opts?: FindOptions) => Row[]

The rows that match, in order.

Type(opts?: FindOptions) => Row[]
first(opts?)(opts?: FindOptions without limit) => Row | undefined

The first row that matches.

Type(opts?: FindOptions without limit) => Row | undefined
get(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.

Type(key: unknown) => Row | undefined
count(opts?)(opts?: { where?: Where }) => number

How many rows match.

Type(opts?: { where?: Where }) => number
groupBy(by, opts?)(by: string[], opts?: GroupOptions) => GroupRow[]

One row per group of equal values in the by columns, the largest group first.

Type(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.

Type(row: Insert) => number
insertMany(rows)(rows: Insert[]) => void

Adds each row in turn.

Type(rows: Insert[]) => void
upsert(row)(row: Insert) => void

Adds the row, or updates the columns given on the row with the same primary key.

Type(row: Insert) => void
update(opts)(opts: { where?: Where; set: Partial<Row> }) => number

Sets columns on the rows that match and returns how many changed.

Type(opts: { where?: Where; set: Partial<Row> }) => number
delete(opts?)(opts?: { where?: Where }) => number

Deletes the rows that match and returns how many went.

Type(opts?: { where?: Where }) => number
search(query, opts?)(query: string, opts?: SearchOptions) => SearchHit[]

Rows that match a full-text query, best first. Needs the table's search option.

Type(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.

Type(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.

Type(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.

Type(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.

Type(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.

Type(from: unknown, to: unknown, opts?: { maxDepth?: number; direction?: "out" | "both" }) => unknown[] | null

SingleRow

PropType
get()() => Row | undefined

The row, if it has been set.

Type() => Row | undefined
set(row)(row: Insert) => void

Writes the whole row. A column left out takes its default, or null.

Type(row: Insert) => void
update(set)(set: Partial<Row>) => boolean

Changes some columns of the row. False if there was no row.

Type(set: Partial<Row>) => boolean
clear()() => void

Deletes the row.

Type() => void

Where

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.

PropType
eq?V

Equal to. null means the column is null.

TypeV
ne?V

Not equal to. null means the column is not null.

TypeV
gt?V

Greater than.

TypeV
gte?V

Greater than or equal to.

TypeV
lt?V

Less than.

TypeV
lte?V

Less than or equal to.

TypeV
in?V[]

One of these values. An empty list matches no rows.

TypeV[]
like?string

Matches an SQL LIKE pattern, with % for any text and _ for one character.

Typestring
isNull?boolean

true for null, false for not null.

Typeboolean

FindOptions

PropType
where?Where

Only rows that match.

TypeWhere
orderBy?string | Record<string, "asc" | "desc">

A column to sort by, smallest first, or an object of columns and directions.

Typestring | Record<string, "asc" | "desc">
limit?number

The most rows to return.

Typenumber
offset?number

How many rows to skip first.

Typenumber
Default0
startAfter?unknown[]

Only rows after this position, one value for each orderBy column.

Typeunknown[]

SearchOptions

PropType
where?Where

Other conditions the rows must meet.

TypeWhere
limit?number

The most hits to return.

Typenumber
Default20
offset?number

How many hits to skip first.

Typenumber
Default0
match?"all" | "any" | "phrase" | "raw"

Every word, any word, the words together in order, or a raw SQLite FTS5 query.

Type"all" | "any" | "phrase" | "raw"
Default"all"
prefix?boolean

The last word also matches as the start of a word, for search as you type.

Typeboolean
Defaultfalse
snippet?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.

Typestring | { column: string; open?: string; close?: string; tokens?: number }

NearestOptions

PropType
k?number

How many rows, at most 1,000.

Typenumber
Default10
where?Where

Other conditions the rows must meet.

TypeWhere
exact?boolean

Compares against every row even when the column has an index.

Typeboolean
Defaultfalse

GroupOptions

PropType
where?Where

Only rows that match.

TypeWhere
sum?string[]

Columns to add up in each group.

Typestring[]
min?string[]

Columns to take the smallest value of.

Typestring[]
max?string[]

Columns to take the largest value of.

Typestring[]
limit?number

The most groups, the largest first.

Typenumber

Results

PropType
Row{ [column]: value }

A row as read, each column as its t builder's TypeScript type.

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.

TypeRow with some columns optional
SearchHit{ row: Row; score: number; snippet?: string }

A match. A higher score is a better match.

Type{ row: Row; score: number; snippet?: string }
NearestHit{ row: Row; distance: number }

A row and its distance by the column's metric. Smaller is nearer.

Type{ 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.

Type{ [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() and get() need a primary key. startAfter needs one value for each orderBy column. Both throw otherwise.
  • On a t.json() column, an object in where is 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. With where, it checks a larger set of near rows, and compares against every row when too few of them match.
  • For a geo table, nearby() measures distance in metres. traverse() goes 10 edges deep by default, at most 100, and returns up to 1,000 nodes unless limit says 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 })),
),

Was this page helpful?