> ## Documentation Index
> Fetch the complete documentation index at: https://developers.zite.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Database

> Read and write the workspace database from Start server code with the typed zite client: table methods, bulkCreate as an upsert, findAll's limits, and read-only SQL with zite.sql().

Every app reads and writes the workspace database through the typed `zite` client
from `zitejs/db`. It's generated into `.zite/db.ts` at the workspace root from the database's schema, so it
knows your tables and fields. To persist data, use these tables: a request's context has no `storage`, `db`,
or `cache`.

```typescript theme={"system"}
import { zite } from 'zitejs/db';
```

`zite.*` is server-only. Use it inside a server function's handler, a `*.server.ts` helper, or an
automation, never at a route file's top level or in a component. Pages reach data by calling
[server functions](https://developers.zite.com/framework/overview.md#server-functions).

## Names

Read `.zite/db.ts` before writing code against the database: it has the table types and the methods each
table client has. Each table is a property on `zite`, named by its SDK name in camelCase (`zite.ballRuns`).
Fields are camelCase SDK names too (`runLabel`). SQL takes a different name for the table, in PascalCase
(`"BallRuns"`). See [SQL](#raw-sql).

## Table methods

```typescript theme={"system"}
// src/lib/tickets.server.ts
import { zite } from 'zitejs/db';

const { records, hasMore } = await zite.tickets.findAll({
  filters: { status: 'open' },
  sort: [{ field: 'createdAt', direction: 'desc' }],
  limit: 100,
});

const ticket = await zite.tickets.findOne({ id: ticketId });
const created = await zite.tickets.create({ record: { subject: 'Help', status: 'open' } });
await zite.tickets.update({ id: created.id, record: { status: 'closed' } });
await zite.tickets.delete({ id: created.id });
```

| Method | Arguments | Returns |
| - | - | - |
| `findAll` | `{ limit?, offset?, sort?, filters?, fields? }` | `{ records, hasMore }` |
| `findOne` | `{ id?, filters?, fields? }` | The record, or `undefined` |
| `create` | `{ record }` | The created record |
| `update` | `{ id, record }` | The updated record |
| `delete` | `{ id }` | `{ success, id }` |
| `bulkCreate` | `{ records, matchOn? }` | `{ success, records }` |

Writes always go through these methods, never through SQL.

## findAll returns 500 rows by default

`findAll` returns 500 records unless you pass `limit`, and it does so silently: `hasMore` is the only sign
there were more. `limit` goes up to 2000, and more than that is rejected with a 400.

So an aggregate computed by pulling rows and reducing them in JavaScript quietly produces wrong numbers once
a table grows past that. SQL aggregates in Postgres see every row, whatever the table's size. Reach for
`findAll` only when you need a small, paginated list of full records to display, and use
[`zite.sql()`](#raw-sql) for everything else.

## Filters

Filters are keyed by field SDK name. A bare value means equality, and an object applies an operator:

```typescript theme={"system"}
await zite.tickets.findAll({ filters: { status: 'open' } });
await zite.tickets.findAll({ filters: { priority: { gte: 3 }, subject: { contains: 'refund' } } });
```

| Operator | Meaning |
| - | - |
| *(bare value)* | Equals |
| `contains` | Substring match on text, or "has any of these" on linked records |
| `not` | Not equal. `{ not: null }` means "is set" |
| `in` | Is one of. An empty array matches nothing |
| `notIn` | Is not one of. An empty array applies no filter |
| `gt`, `gte`, `lt`, `lte` | Greater than, at least, less than, at most |

Zite tables have no `ilike`: a filter using it matches no records. For a case-insensitive match, filter with
`contains` and keep the record whose value, lowercased, equals what you're looking for, lowercased.

> [!WARNING]
>
> A filter value of `undefined` is dropped, so `findAll` runs as if that filter weren't there.
> `filters: { createdBy: context.user?.id }` matches every row when nobody is signed in: return early when
> `context.user` is null. A filter key that isn't a field's SDK name matches no column, and the query comes
> back unfiltered too, so check names against `.zite/db.ts`.

## User and linked-record fields

* To record who a row belongs to, put `context.user.id` in a `user` field.
* To filter records by a user field, pass the user's id directly: `filters: { createdBy: context.user.id }`.
  The SDK handles the array matching.
* A `user` or linked-record field reads back as an array of ids, so test it with
  `[row.owner ?? []].flat().includes(context.user.id)`, never `===`.

## bulkCreate

When creating multiple records, use `bulkCreate` instead of calling `create` in a loop. Individual calls are
slower and may hit rate limits:

```typescript theme={"system"}
await zite.items.bulkCreate({ records: items.map(i => ({ name: i.name })) });
```

`bulkCreate` takes at most **100 records per call**. More is rejected with a 400, and nothing chunks for
you, so slice anything unbounded into batches of 100:

```typescript theme={"system"}
for (let i = 0; i < rows.length; i += 100) {
  await zite.contacts.bulkCreate({ records: rows.slice(i, i + 100) });
}
```

### Upserts with matchOn

`bulkCreate` is also the upsert. With `matchOn`, it updates the rows that already match on those fields
(only the fields you pass change) and inserts the rest:

```typescript theme={"system"}
await zite.preferences.bulkCreate({ records: [row], matchOn: ['userId'] });
```

Reach for it whenever a write is "create or update", such as one row per user or syncing a list. A
`findOne` followed by a `create` costs two round trips, and can insert twice when two calls land at once.

A [database trigger](https://developers.zite.com/automations/triggers.md) sees a row an upsert inserts as `created`, a row it
matched as `updated`, and a matched row it left as it was not at all.

## Raw SQL

Default to raw SQL through `zite.sql()` for anything that aggregates, joins, or summarizes data:
dashboards, KPIs, reports, totals, counts, group-bys, top-N lists, anything that touches more than one table
together.

```typescript theme={"system"}
// src/lib/dashboard.functions.ts
import { z } from 'zod';
import { signedInFn } from 'zitejs/start';
import { zite } from 'zitejs/db';

export const ordersByStatus = signedInFn({
  method: 'GET',
  description: 'Counts orders by status since a date',
})
  .validator(z.object({ since: z.string() }))
  .handler(async ({ data }) => {
    const { rows } = await zite.sql({
      query: `
        SELECT "status", COUNT(*) AS "orderCount"
        FROM "Orders"
        WHERE created_at >= $1
        GROUP BY "status"
      `,
      params: [data.since],
    });
    return rows;
  });
```

`zite.sql()` resolves to `{ rows, columns, rowCount, truncated }`. Result columns come back keyed by each
field's SDK name (`rows[0].orderPlacedAt`), and expressions by their alias.

`zite.sql()` is read-only: it accepts `SELECT` statements only, and anything else is rejected at runtime.
Writes go through the table methods (`create`, `update`, `delete`, `bulkCreate`).

### Identifier rules

A wrong name in SQL is a runtime 500, which type-checking can't catch:

| Identifier | Convention | Example |
| - | - | - |
| Table | PascalCase SDK name, double-quoted | `"BallRuns"` |
| Field | camelCase SDK name, double-quoted | `"runLabel"`, not `"Run Label"` |
| System column | lowercase, safe unquoted | `id`, `created_at`, `updated_at` |
| Link table | Both tables' SDK names, concatenated alphabetically, double-quoted | `"BallRuns"` + `"Racers"` → `"BallRunsRacers"` |
| Link table id column | camelCase table name + `Id`, double-quoted | `"ballRunsId"`, `"racersId"` |

* Use the SDK names from `.zite/db.ts`, never display names. The table's accessor in code (`zite.ballRuns`)
  is a different name from the one SQL takes (`"BallRuns"`).
* Double-quote every table and field identifier: Postgres lowercases unquoted ones.
* The `.zite/db.ts` header lists the workspace's link tables.
* Pass runtime values through `params` (`$1`, `$2`, ...), never string interpolation.
* Soft-deleted rows are excluded automatically.

A result holds at most 2000 rows or about 16 MB, whichever comes first. Past that it comes back with
`truncated: true`. See [Dashboards and reports](https://developers.zite.com/recipes/dashboards-sql.md) for paging, linked records,
dates, select and user fields, and worked dashboards.

> [!NOTE]
>
> Try a server function's SQL with `zite.sql()` in `run_one_off_script`, which takes SDK names as server
> functions do. The `execute_sql` data tool takes display names (`"Amount Paid"`) rather than SDK names
> (`amountPaid`), so it fails correct server-function SQL with "column does not exist".
> `run_one_off_script` runs against the live database, so anything it writes is real data.

## The app's users

The client also lists the app's users and updates their profiles, with `zite.auth.findAllUsers` and
`zite.auth.updateUserProfile`. See [Access and sign-in](https://developers.zite.com/framework/access-and-sign-in.md#the-apps-users).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.