---
title: ctx.db
description: Every method of Table and SingleRow, the where operators, and the options and results of find, search, nearest and groupBy.
related:
  - /data/read-and-write-rows
  - /sdk/table
  - /data/run-sql
---

`ctx.db` holds one object per table in the luna's schema: a `Table`, or a `SingleRow` for a table declared with `singleRow: true`.

```ts luna/lunas/list.ts
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`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `find(opts?)` | `(opts?: FindOptions) => Row[]` | - | The rows that match, in order. |
| `first(opts?)` | `(opts?: FindOptions without limit) => Row \| undefined` | - | The first row that matches. |
| `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. |
| `count(opts?)` | `(opts?: { where?: Where }) => number` | - | How many rows match. |
| `groupBy(by, opts?)` | `(by: string[], opts?: GroupOptions) => GroupRow[]` | - | One row per group of equal values in the by columns, the largest group first. |
| `insert(row)` | `(row: Insert) => number` | - | Adds a row and returns its rowid, which is the value of its t.id() column. |
| `insertMany(rows)` | `(rows: Insert[]) => void` | - | Adds each row in turn. |
| `upsert(row)` | `(row: Insert) => void` | - | Adds the row, or updates the columns given on the row with the same primary key. |
| `update(opts)` | `(opts: { where?: Where; set: Partial<Row> }) => number` | - | Sets columns on the rows that match and returns how many changed. |
| `delete(opts?)` | `(opts?: { where?: Where }) => number` | - | Deletes the rows that match and returns how many went. |
| `search(query, opts?)` | `(query: string, opts?: SearchOptions) => SearchHit[]` | - | Rows that match a full-text query, best first. Needs the table's search option. |
| `nearest(column, to, opts?)` | `(column: string, to: Float32Array \| number[], opts?: NearestOptions) => NearestHit[]` | - | The rows whose vector column is nearest to, nearest first. |
| `within(box, opts?)` | `(box: Box, opts?: { where?: Where; limit?: number }) => Row[]` | - | Rows whose point is inside the box, edges included. Needs the spatial option. |
| `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. |
| `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. |
| `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. |

### SingleRow

| Prop | Type | Default | Description |
| - | - | - | - |
| `get()` | `() => Row \| undefined` | - | The row, if it has been set. |
| `set(row)` | `(row: Insert) => void` | - | Writes the whole row. A column left out takes its default, or null. |
| `update(set)` | `(set: Partial<Row>) => boolean` | - | Changes some columns of the row. False if there was no row. |
| `clear()` | `() => void` | - | Deletes the row. |

### 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.

| Prop | Type | Default | Description |
| - | - | - | - |
| `eq?` | `V` | - | Equal to. null means the column is null. |
| `ne?` | `V` | - | Not equal to. null means the column is not null. |
| `gt?` | `V` | - | Greater than. |
| `gte?` | `V` | - | Greater than or equal to. |
| `lt?` | `V` | - | Less than. |
| `lte?` | `V` | - | Less than or equal to. |
| `in?` | `V[]` | - | One of these values. An empty list matches no rows. |
| `like?` | `string` | - | Matches an SQL LIKE pattern, with % for any text and _ for one character. |
| `isNull?` | `boolean` | - | true for null, false for not null. |

### FindOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `where?` | `Where` | - | Only rows that match. |
| `orderBy?` | `string \| Record<string, "asc" \| "desc">` | - | A column to sort by, smallest first, or an object of columns and directions. |
| `limit?` | `number` | - | The most rows to return. |
| `offset?` | `number` | `0` | How many rows to skip first. |
| `startAfter?` | `unknown[]` | - | Only rows after this position, one value for each orderBy column. |

### SearchOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `where?` | `Where` | - | Other conditions the rows must meet. |
| `limit?` | `number` | `20` | The most hits to return. |
| `offset?` | `number` | `0` | How many hits to skip first. |
| `match?` | `"all" \| "any" \| "phrase" \| "raw"` | `"all"` | Every word, any word, the words together in order, or a raw SQLite FTS5 query. |
| `prefix?` | `boolean` | `false` | The last word also matches as the start of a word, for search as you type. |
| `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. |

### NearestOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `k?` | `number` | `10` | How many rows, at most 1,000. |
| `where?` | `Where` | - | Other conditions the rows must meet. |
| `exact?` | `boolean` | `false` | Compares against every row even when the column has an index. |

### GroupOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `where?` | `Where` | - | Only rows that match. |
| `sum?` | `string[]` | - | Columns to add up in each group. |
| `min?` | `string[]` | - | Columns to take the smallest value of. |
| `max?` | `string[]` | - | Columns to take the largest value of. |
| `limit?` | `number` | - | The most groups, the largest first. |

### Results

| Prop | Type | Default | Description |
| - | - | - | - |
| `Row` | `{ [column]: value }` | - | A row as read, each column as its t builder's TypeScript type. |
| `Insert` | `Row with some columns optional` | - | A row as written. Optional columns, columns with a default and t.id() columns may be left out. |
| `SearchHit` | `{ row: Row; score: number; snippet?: string }` | - | A match. A higher score is a better match. |
| `NearestHit` | `{ row: Row; distance: number }` | - | A row and its distance by the column's metric. Smaller is nearer. |
| `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. |

## 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.

:::warning
`update()` and `delete()` without `where` change every row of the table. `SingleRow.set()` replaces the whole row, so read the row first to keep columns you do not set.
:::

## Examples

### Page through rows

```ts luna/lunas/list.ts
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

```ts luna/lunas/list.ts
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

```ts luna/lunas/list.ts
progress: h({ query: true }, (ctx) => ctx.db.items.groupBy(["done"])),
```

### Insert or update by primary key

```ts luna/lunas/list.ts
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

```ts luna/lunas/list.ts
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

```ts luna/lunas/list.ts
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

```ts luna/lunas/list.ts
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 })),
),
```
