Table stores relational and structured JSONB data with strict column types, primary keys, unique constraints, secondary/GIN/expression indexes, foreign keys, ACID transactions, and optional atomic Change Data Capture (CDC).
Use Table for both classic relational schemas (foreign keys, typed joins, multi-table ACID commits) and document-style nested JSONB payloads (k.json(schema).index(), dot-path queries, @> containment, and partial dot-path updates) in one unified table primitive.
Declaring a table
Plain TypeScript SDK (@chimp-labs/keel/sdk)
import { k } from "@chimp-labs/keel/sdk"
export const UsersTable = k.table("users", {
id: k.uuid().primaryKey(),
email: k.text().unique(),
tier: k.text(),
bio: k.text().nullable(),
createdAt: k.datetime().defaultNow(),
})
export const OrdersTable = k.table(
"orders",
{
id: k.uuid().primaryKey(),
userId: k.text().references(UsersTable, "id", { onDelete: "cascade" }).index(),
totalCents: k.integer(),
status: k.text(),
createdAt: k.datetime().defaultNow(),
},
{ trackChanges: true }
)
Column builders and modifiers
| Builder | SQL type | TypeScript type | Notes |
|---|---|---|---|
k.uuid() |
text |
string |
Generates a UUID v4 when combined with .primaryKey(). |
k.text() |
text |
string |
Variable-length string. |
k.integer() |
integer |
number |
Supports .autoIncrement() on primary keys. |
k.real() |
real |
number |
Floating-point number. |
k.boolean() |
boolean |
boolean |
Boolean column. |
k.datetime() |
timestamp |
Date | string |
Supports .defaultNow(). |
k.json(schema) |
json (JSONB on Postgres) |
InferSchema<S> |
Validated JSONB column for Zod, Valibot, ArkType, or Effect Schema. Chain .index() for a PostgreSQL GIN index, or index nested dot-paths in indexes/unique. |
Supported column modifiers are .primaryKey(), .unique(), .index(), .nullable(), .autoIncrement(), .defaultNow(), and .references(table, column, { onDelete?, onUpdate? }).
JSONB document queries, partial updates, and indexes
Any k.json(schema) column supports document-style indexing, nested dot-path filtering, @> containment, and partial dot-path updates across Memory, SQLite, PostgreSQL 17, and SurrealDB 4:
import { Schema } from "effect"
import { k } from "@chimp-labs/keel/sdk"
export const ProfilesTable = k.table(
"profiles",
{
id: k.uuid().primaryKey(),
tenantId: k.text(),
data: k
.json(
k.object({
sku: k.string(),
tier: Schema.Literals(["free", "pro", "enterprise"]),
tags: k.array(k.string()),
address: k.object({ city: k.string(), country: k.string() }),
stats: k.object({ score: k.int(), visits: k.int() }),
})
)
.index(), // PostgreSQL: CREATE INDEX ... USING GIN ("data")
},
{
tenantScoped: true,
// PostgreSQL: CREATE UNIQUE INDEX ... (("tenantId"), (("data" #>> '{sku}')))
// SQLite: CREATE UNIQUE INDEX ... ("tenantId", json_extract("data", '$.sku'))
unique: [["tenantId", "data.sku"]],
indexes: [["data.tier"], ["tenantId", "data.address.city"]],
}
)
// Nested dot-path filtering & ordering
const highScores = await keel.profiles.select(
{ "data.stats.score": { gte: 100 }, "data.address.city": { like: "San%" } },
{ orderBy: { "data.stats.score": "desc" } }
)
// JSONB @> containment (uses the PostgreSQL GIN index)
const vipUs = await keel.profiles.select({
data: { contains: { tags: ["vip"], address: { country: "US" } } },
})
// Atomic dot-path partial updates (re-validated against the full JSON schema)
await keel.profiles.updateById(id, {
"data.tier": "pro",
"data.stats.score": 150,
})
Table options
| Option | Type | Default | Description |
|---|---|---|---|
trackChanges |
boolean |
false |
Writes typed row-change events (insert, update, delete) into the transactional outbox in the same transaction. |
primaryKey |
keyof Cols |
Inferred | Sets the primary key column when no column uses .primaryKey(). |
Effect v4 (@chimp-labs/keel/table)
import { Schema } from "effect"
import { Table } from "@chimp-labs/keel/table"
export class UsersTable extends Table("users", {
select: Schema.Struct({
id: Schema.String,
email: Schema.String,
createdAt: Schema.String,
}),
insert: Schema.Struct({
email: Schema.String,
}),
primaryKey: "id",
columns: {
id: { type: "text", generated: "uuid" },
email: { type: "text" },
createdAt: { type: "timestamp", generated: "now" },
},
unique: [["email"]],
trackChanges: true,
}) {}
Attaching to a service
Declare tables in your service’s resources array so Keel creates schemas, orders foreign-key migrations with sortTablesByForeignKeys, and includes keel_outbox when trackChanges is true:
export const OrdersService = k.service("orders", {
resources: [UsersTable, OrdersTable],
operations: { /* ... */ },
})
Operations reference
CRUD, filtering, and streaming
// Create tables and indexes (idempotent)
await keel.orders.ensure()
// Insert (generated columns like UUID PK and defaultNow are optional)
const order = await keel.orders.insert({
userId: user.id,
totalCents: 4500,
status: "paid",
})
// Lookup by primary key
const maybeOrder = await keel.orders.findById(order.id) // Order | undefined
const exactOrder = await keel.orders.getById(order.id) // throws RowNotFoundError
// Query with typed filters, ordering, and limits
const recent = await keel.orders.select(
{ userId: user.id, totalCents: { gte: 1000 } },
{ orderBy: { createdAt: "desc" }, limit: 20 }
)
// Stream large result sets with AbortSignal support
for await (const row of keel.orders.selectStream({ status: "paid" }, { signal })) {
console.log(row.id)
}
// Update & delete
const updated = await keel.orders.updateById(order.id, { status: "shipped" })
await keel.orders.deleteById(order.id)
The where clause supports direct value equality and the operators eq, neq, gt, gte, lt, lte, in, and contains.
Type-safe joins
TypeScript checks join columns at compile time through MatchingRightKeys. Branded IDs prevent joining mismatched foreign keys, for example productId against users.id:
const rows = await keel.orders.join(UsersTable, {
on: ["userId", "id"],
where: { status: "paid" },
})
// Each item is typed as { left: OrderRow, right: UserRow }
ACID transactions and transactional outbox
Use keel.transaction(async (tx) => ...) or Effect withTransaction to run multiple table writes and outbox writes inside one ACID transaction. If any step throws, the database rolls back all table writes and outbox rows together:
await keel.transaction(async (tx) => {
const created = await tx.orders.insert({
userId: user.id,
totalCents: 4500,
status: "paid",
})
await tx.orderPlaced.enqueueOutbox({
orderId: created.id,
totalCents: created.totalCents,
})
})
Live watches and atomic CDC
Keel provides two transaction-safe change mechanisms on any Table. Rolled-back writes never emit events under either mechanism.
| Mechanism | Delivery | Event shape | Replayable | Best for |
|---|---|---|---|---|
watch() (ephemeral) |
At-most-once while connected | { _tag: "Insert" | "Update", table, key, row } or { _tag: "Delete", table, key } |
No | Best-effort cache invalidation and SSE or WebSocket UI updates |
trackChanges: true (durable CDC) |
At-least-once via keel_outbox |
{ _tag: "TableRowCreated", table, key, after }, { _tag: "TableRowUpdated", ..., before, after }, { _tag: "TableRowDeleted", ..., before } |
Yes (durable Topic replay) |
Audit trails, search indexing, cross-service sync, and reactive consumers |
1. Ephemeral live watch for cache invalidation and UI streams
Use keel.<table>.watch({ signal }) for push notifications without persisting an event stream. On SurrealDB 4, this uses native LIVE SELECT. On Memory and SQLite, it emits events after transaction commit:
const controller = new AbortController()
// Background task: evict cached entries & push live updates to connected clients
void (async () => {
for await (const ev of keel.orders.watch({ signal: controller.signal })) {
await keel.orderCache.invalidate(ev.key)
switch (ev._tag) {
case "Insert":
broadcastToDashboard({ type: "order.created", order: ev.row })
break
case "Update":
broadcastToDashboard({ type: "order.updated", order: ev.row })
break
case "Delete":
broadcastToDashboard({ type: "order.deleted", id: ev.key })
break
}
}
})()
// Clean shutdown
controller.abort()
2. Durable atomic CDC with before and after diffs via keel_outbox
When a table enables { trackChanges: true }, every insert, updateById, and deleteById writes a typed TableChangeEvent row into keel_outbox inside the same database transaction. Derive the typed topic with k.tableChangeTopic(OrdersTable) or keel.orders.changeTopic():
import { createKeel, k } from "@chimp-labs/keel/sdk"
export const OrdersTable = k.table(
"orders",
{
id: k.uuid().primaryKey(),
userId: k.text().index(),
status: k.text(),
totalCents: k.integer(),
},
{ trackChanges: true }
)
export const OrderChanges = k.tableChangeTopic(OrdersTable)
await using keel = await createKeel({
backend: "sqlite",
resources: { orders: OrdersTable, orderChanges: OrderChanges },
ensureAll: true,
})
// Start push-driven outbox relay (or call keel.outbox.relayOnce() in tests)
await using relay = await keel.outbox.startRelay({ mode: "push" })
// Consume durable change events with full before/after snapshots
for await (const env of keel.orderChanges.catchUpAndTail({ after: 0, signal })) {
const change = env.payload
if (change._tag === "TableRowCreated") {
console.log("Created:", change.key, change.after)
} else if (change._tag === "TableRowUpdated") {
console.log(
`Status changed for ${change.key}: ${change.before.status} -> ${change.after.status}`
)
} else if (change._tag === "TableRowDeleted") {
console.log("Deleted:", change.key, "previous row:", change.before)
}
}
3. Reactive CDC consumer with loop guard
Because TableRowUpdated includes both before and after, a consumer reading k.tableChangeTopic(ProductsTable) can guard on the exact field transition so writing back to the same table does not trigger an infinite loop:
const ProductsTable = k.table(
"products",
{
id: k.uuid().primaryKey(),
sku: k.text().unique(),
priceCents: k.integer(),
onSale: k.boolean(),
},
{ trackChanges: true }
)
const ProductChanges = k.tableChangeTopic(ProductsTable)
// Only fires when priceCents actually drops — writing `onSale: true` will NOT re-trigger
for await (const env of keel.productChanges.catchUpAndTail({ after: 0, signal })) {
const change = env.payload
if (
change._tag === "TableRowUpdated" &&
change.after.priceCents < change.before.priceCents
) {
await keel.products.updateById(change.key, { onSale: true })
}
}
4. Syncing a projection or cache from table CDC
Consume the table CDC topic in a background worker to keep a read-model Table or Cache synchronized without manual publish calls in your CRUD handlers:
for await (const env of keel.productChanges.catchUpAndTail({ after: 0, signal })) {
const change = env.payload
if (change._tag === "TableRowDeleted") {
await keel.catalogCache.invalidate(change.key)
} else {
await keel.catalogCache.set(change.key, {
sku: change.after.sku,
priceCents: change.after.priceCents,
onSale: change.after.onSale,
})
}
}
5. Rollback safety
If a transaction rolls back, neither watch() listeners nor TableChangeTopic consumers receive the uncommitted write:
await tryKeel(() =>
keel.transaction(async (tx) => {
await tx.orders.insert({
userId: "usr_1",
status: "pending",
totalCents: 9900,
})
throw new Error("payment authorization failed")
})
)
// Zero rows in `orders`, zero watch events emitted, zero CDC rows in `keel_outbox`
await keel.outbox.relayOnce()
SDK and Effect API mapping
SDK method (keel.<table>.*) |
Effect function (@chimp-labs/keel/table) |
Description |
|---|---|---|
ensure() |
ensureTable(table) / ensureTables(tables) |
Create the table, constraints, and indexes idempotently. |
insert(row) |
insertRow(table, row) |
Validate and insert a row, then return the full row. |
findById(id) |
findById(table, id) |
Return the row (T | undefined in SDK, Option<T> in Effect). |
getById(id) |
getById(table, id) |
Return the row or fail with RowNotFoundError. |
select(where?, opts?) |
selectRows(table, where?, opts?) |
Query rows with typed filters, orderBy, and limit. |
selectStream(where?, opts?) |
selectRows(table, where?, opts?) |
Stream matching rows lazily. |
join(right, { on, where? }) |
joinSelect(left, right, opts) |
Run a type-checked inner join. |
updateById(id, patch) |
updateById(table, id, patch) |
Apply a partial update by primary key. |
deleteById(id) |
deleteById(table, id) |
Delete a row by primary key. |
watch({ signal? }) |
watchTable(table) |
Open a live stream of row changes. |
changeTopic() |
TableChangeTopic(table) |
Return the durable CDC topic descriptor (keel.table.<name>.changed). |
keel.transaction(fn) |
withTransaction(effect) |
Run operations inside an ACID transaction. |
Errors and failure modes
| Error tag | Category | HTTP status | Retryable | When it occurs |
|---|---|---|---|---|
RowNotFoundError |
not_found |
404 |
No | getById, updateById, or deleteById finds no matching row. |
UniqueViolationError |
conflict |
409 |
No | An insert or update violates a primary key or .unique() constraint. |
ForeignKeyViolationError |
conflict |
409 |
No | A referenced parent row does not exist or a restricted delete is blocked. |
SqlQueryError |
internal |
500 |
Yes | The database query or transaction failed. |
SchemaError |
invalid |
400 |
No | An input or stored row failed schema validation. |
Backends and infrastructure
| Backend | Support and behavior |
|---|---|
| Memory | ACID rollback snapshots, unique and foreign-key checks, joins, watch, and outbox CDC in process. |
SQLite (node:sqlite) |
Embedded ACID SQLite with foreign keys enabled and zero external dependencies. |
| SurrealDB 4 | Native tables, transactions, and LIVE SELECT watches. |
| PostgreSQL | Native SQL tables plus claimPending (FOR UPDATE SKIP LOCKED) via PgCapabilities. |
inferKeelInfra extracts every declared table into plan.surreal.tables and plan.sql.tables, and adds keel_outbox whenever trackChanges is true.
Testing in memory
import { createKeel, tryKeel } from "@chimp-labs/keel/sdk"
await using keel = await createKeel({
backend: "memory",
resources: { users: UsersTable, orders: OrdersTable },
ensureAll: true,
})
const user = await keel.users.insert({ email: "[email protected]", tier: "pro" })
// Verify unique constraint enforcement
const duplicate = await tryKeel(() =>
keel.users.insert({ email: "[email protected]", tier: "free" })
)
// duplicate.ok === false, duplicate.error.tag === "UniqueViolationError" (409)