---
id: database/table-resource
title: Table resource
summary: Describe one database table once (its fields, columns, ownership, search and sort) so its owner feature reads and writes it through a scoped handle.
keywords: database, defaultTo, defineTableResource, lockVersionField, lookup, owns, ownership, resource, system, table, workspace_or_shared
requires: @jskit-ai/resource-core
---

# Table resource

## Use when

Use this pattern for every table an application owns, whether or not it is
served over HTTP. The table resource is the table's one description; the
feature that owns the table lists it in `owns`, and every read and write goes
through the handle setup receives
([data access](https://mobily-enterprises.github.io/jskit-ai/guide/framework/data-access)).

## Do not use when

Do not describe a table twice, and do not describe another feature's table:
ask its owner. A table with standard screens over HTTP adds a CRUD contract on
this resource (`crud/crud-contract`), not a second resource.

## Product decisions

- who owns a row, always stated: nobody (`public`), a workspace, a user, a
  user inside a workspace, a workspace with rows shared with every
  workspace, or no one any request may reach (`system`)
- the fields, which are required, searchable or hidden, and their defaults
- whether people edit records from forms read earlier (a version number)
- the default order of lists

## Invariants

- One table, one table resource, one owner feature.
- `ownership` matches the owner columns: `workspace` filters on the hidden
  `workspaceId` field, `user` on `userId`, `workspace_user` on both, and
  `workspace_or_shared` reads a workspace's rows plus the rows whose
  `workspaceId` is null. The handle adds that predicate to every statement and
  stamps new rows from the caller's context. A `system` table has no owner
  columns, and its handle refuses every call whose context is not a system
  context, before any statement: it is for rows that only the owner's
  background work keeps (queues, leases, run state), never served to a request.
- A field's default value is `defaultTo`; `default` is refused, since
  json-rest-api never read it.
- A field with `defaultTo` is not `required`: a create is checked for
  required fields before defaults apply, so `defineTableResource` refuses the
  two together.
- `lockVersionField` names an integer field over a non-null integer column
  with a starting value; `patch(id, changes, { ...options, lockVersion })` then refuses
  stale edits with a 409.
- The definition is shared with the client, so it holds no server-only keys:
  the row policy, hooks, server-only search entries and computed query fields
  go in the owner's `owns` entry.
- The source-controlled migration and the resource describe the same table.

## Framework APIs

`defineTableResource()` from `@jskit-ai/resource-core/shared/tableResource`
freezes the description and refuses the CRUD contract's keys (`namespace`,
`apiAccess`, `operations`, `messages`), `autofilter` and the server-only keys,
each with an error naming where it belongs.

A field that looks up a record of another resource names that resource's
namespace with `lookup`:

```js
customerId: { type: "id", required: true, search: true, lookup: "customers" }
```

`defineTableResource()` expands it, where `lookup` stood, to:

```js
relation: { kind: "lookup", namespace: "customers", valueKey: "id" },
belongsTo: "customers",  // the table resource named by the namespace, camel-cased
as: "customer",          // the field key without its Id suffix
ui: { formControl: "autocomplete" }
```

Keys you write beside `lookup` win: `belongsTo` and `as` replace the
filled-in values, and `relation` and `ui` are merged over them. A field whose
key has no `Id` suffix must write `as`.

The owner, on the server:

```js
const OrdersFeature = defineFeature({
  id: "orders",
  owns: [{ resource: orderResource, rowPolicy: ordersTheActorMayHandle }],
  provides: { orders: "orders" },
  setup: ({ resources }) => ({ orders: createOrdersRepository({ orders: resources.orders }) })
});
```

## Example files

- `example/orderResource.js` is a workspace-owned orders table with a lookup,
  defaults, a version number, a text search and a default sort.

## Variation points

Rename the table and fields, pick the ownership kind the product's owner
columns support, add search entries and sorts. A computed output field is
`storage: { virtual: true }` here and a `queryFields` entry in `owns`.

## Verification

- Import the resource and check its ownership, fields and lookups.
- Rebuild the table from source-controlled migrations in a disposable database.
- Give each repository path a scope test (`expectScoped`) and a flat-query
  test (`expectFlatQueries`) from `@jskit-ai/resource-runtime/test`.

## Avoid

- a second table resource for the same table
- `where workspace_id = ?` written by hand: ownership adds it
- a row policy, hooks or SQL in the shared definition
- `default:` instead of `defaultTo:`
- `required: true` beside `defaultTo`
