npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ultimat3/entity

v31.58.0

Published

A table + its domain type + invariants the database also enforces

Readme

@ultimat3/entity 🗄️

An entity is columns + the invariants that hold for every row. The row type is derived from the columns: type Post = typeof posts.$row. Declare the shape once — repos, migrations, the admin screen, cache tags and the manifest are all projections of that one call.

bun add @ultimat3/entity · guide: Entities And Migrations

import { entity, enumerated, integer, invariant, text, timestamp, url, uuid } from '@ultimat3/entity';

const POST_STATUSES = ['draft', 'published'] as const;

const orgs = entity('orgs', { columns: { id: uuid().primaryKey() } });

export const posts = entity('posts', {
  tenant: 'orgId',
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid().references(() => orgs.id, { onDelete: 'cascade' }),
    slug: text({ max: 80 }),
    title: text({ max: 120 }),
    coverUrl: url().nullable(),
    status: enumerated(POST_STATUSES).default('draft'),
    likeCount: integer().default(0),
    createdAt: timestamp().defaultNow(),
    updatedAt: timestamp().defaultNow().onUpdateNow(),
  },
  invariants: (c) => [
    invariant('post_title_present', c.title.trimmed().minLength(1)),
    invariant('post_slug_unique_per_org', c.unique(['orgId', 'slug'])),
    invariant('post_like_count_non_negative', c.likeCount.atLeast(0)),
  ],
  indexes: [{ on: ['orgId', 'createdAt'], order: 'desc', where: (c) => c.status.eq('published') }],
});

export type Post = typeof posts.$row;

export const PostView = posts.$view(['id', 'title', 'coverUrl', 'status']);
export type PostView = typeof PostView.$row;

$view is what leaves the server

posts.$view([...]) returns a Standard Schema over a subset of the row, so an action names it directly — output: PostView — and the projected type flows on to the client and the component.

| Rule | Detail | |---|---| | Keys are checked twice | unknown key ⇒ tsc error, and X_INVARIANT_VIOLATED at declaration for a JS caller | | Values are the columns' | each key is parsed by the column that declared it; no second copy of the rule | | Nothing is invented | a view projects a row that exists — an absent required key is missing data, not a default | | It is an input too | input: posts.$view(['title']) publishes maxLength and refuses past it with one issue PER KEY — path: ['title'], a rule from the column's fact (string.max { max }, enum { values }, required, else type { type }) and the column's own sentence (expected at most 200 characters, got 300) — so a form binds it to the field. There is no $input.pick(): this is it | | $name | posts.view.id_title_coverUrl_status — stable, and legal as an OpenAPI components.schemas key | | It projects | a view carries the schema IR (node) the same way every t.* schema does, so output: PostView reaches OpenAPI, the MCP tool's outputSchema and the typed client — As of 2026-09-05; before that it validated fine and was refused at registration with X_SCHEMA_UNSUPPORTED, so every app re-declared its outputs as t.object. Column kinds publish the ROW value's shape: bigint()/decimal() are strings, date() is a YYYY-MM-DD string, money() is { minor, currency, scale? }, enumerated() is an enum, a nullable column is anyOf: [<type>, null] and still required |

There is no free view(posts, [...]) function: a projection is reached through the entity, and every framework member is $-prefixed so a column may still be called name, view or tenant.

A view the columns cannot express — a joined authorName, a computed excerpt — is a hand-written t.object({...}). t is re-exported here, the same object @ultimat3/schema exports, so that file still imports one package: import { entity, t } from '@ultimat3/entity'.

A whole row is a record

posts.$schema is the whole row as a t schema, and its node is branded (Symbol.for('ultimate.entity'), non-enumerable) with the entity's record projection. An action or query whose output names it — bare or wrapped — returns rows the client store adopts, with no records: option anywhere: the envelope is derived from the output schema.

import {
  entity,
  hasEntityRows,
  recordProjection,
  recordTypeForTable,
  rowsOf,
  t,
  text,
  uuid,
} from '@ultimat3/entity';

const posts = entity('posts', { columns: { id: uuid().primaryKey(), title: text() } });
const Feed = t.object({ items: t.array(posts.$schema), featured: posts.$schema.nullable() });
declare const answer: unknown; // what a handler returned

hasEntityRows(Feed);         // true — static, memoised per node
rowsOf(Feed, answer);        // { posts: { [recordKey]: row } } — null-prototype, same objects
recordProjection(posts);     // { type: 'posts', table: 'posts', key, schema, persist: false }
recordTypeForTable('posts'); // 'posts' — what a changefeed row belongs to

| Rule | Detail | |---|---| | Survives every wrapper | t.array, t.object, t.record, t.union keep the child node by reference; .nullable(), .optional(), .default(), .describe(), .refine() re-brand the copy they make | | A partial row is never a record | a $view, and any t.object(...).pick/omit/extend, carries no brand — it would overwrite a full record | | Wire shape | type → record key → row: the KEY travels, because a browser cannot compute one without importing the app's entity() declarations | | Union arms | a branded arm claims a value only when every column is an own key of it | | Record key | the primary key, in DECLARED order; a single key is the value itself (so it equals $tagFor(id)'s id), a composite one percent-encodes each part and joins on : | | Missing key | X_RECORD_KEY_MISSING — never keyed as undefined, because two keyless rows would be one record | | persist | entity(name, { persist: true }) — default false; a browser keeps the records on disk (IndexedDB, per principal) only when declared. Realtime's persister reads recordProjection(e).persist, never the declaration | | type / table | the entity name (the store's key) and the physical relation (what a changefeed names); two entities over one table are X_INVARIANT_VIOLATED from recordTypeForTable |

In browser code import these from @ultimat3/entity/record, never the barrel: the package declares no sideEffects, so the barrel retains ~1 MB of SQL rendering and @ultimat3/db a page never runs, while the subpath retains the projection, the key and the registry and nothing else — record-bundle.test.ts measures both.

Blessed columns

| Builder | Emits | Why it is the only way | |---|---|---| | uuid(), uuid<PostId>() | uuid; .primaryKey() defaults to v7 | time-ordered keys keep the pk index append-friendly; the optional brand is declared once and survives to every signature | | timestamp() | timestamptz | UTC storage is not a per-table decision; there is no naive variant | | money() | <name>_minor bigint + <name>_currency char(3) + <name>_scale integer null | never a float, never one implied currency. The row value is @ultimat3/schema's MoneyValue — the same declaration @ultimat3/money's Money is — so a decoded row goes straight to add()/formatMoney(). A writer may hand a bigint — Insertable says so on a table, RowWrite<Row> at a repository, and every whole-row write narrows it at its own entry, before an invariant or a statement sees it; a minor unit past ±2^53 is refused there and on read, never rounded. scale is the decimal exponent minor counts in when it is not the currency's own ({ minor: 2, currency: 'USD', scale: 6 } is $0.000002); NULL in the column means "the currency's own minor unit" and round-trips as an ABSENT key, never as 0 | | enumerated(v) | text + CHECK | a variant is a one-line migration, not ALTER TYPE | | tz(zones), locale(tags) | text + CHECK, Intl-validated at declaration | an offset is not a time zone | | text({ max }), integer(), boolean(), url() | text/integer/boolean + CHECK | format is enforced by the database too. url() judges the STORED text against its CHECK (^https?://), so leading whitespace, a tab inside the scheme and https:/a.b are refused here rather than by a raw 23514 |

Chain: .primaryKey() · .nullable() · .unique() · .default(v) · .defaultNow() · .onUpdateNow() · .references(() => other.id, { onDelete, crossTenant }) · .tenant() · .column(name) · .sealed() (text() only). Physical names are derived from the property key (orgId → org_id); a name is written once, or never — .column() is the exception, and it exists for tables this framework did not create.

A sealed column

A credential column is declared .sealed(). The row type stays string; the database never sees the plaintext.

import { database, entity, text, uuid } from '@ultimat3/entity';

export const connections = entity('connections', {
  columns: {
    id: uuid().primaryKey(),
    label: text({ max: 80 }),
    password: text({ max: 200 }).sealed(), // opaque: read and written, never compared
    token: text().nullable().sealed(),
    email: text().sealed({ lookup: true }).unique(), // deterministic: equality only
  },
});

const db = database({ connections });

export async function passwordFor(email: string): Promise<string | null> {
  const row = await db.connections.where({ email }).one();
  return row?.password ?? null; // the plaintext — on the server, and nowhere else
}

| Fact | | |---|---| | Builder | text() only — text().sealed(), in any order with .nullable(), .unique(), .column(). A sealed number or date does not compile | | Stored | x1.<keyId>.<iv>.<ciphertext+tag> from @ultimat3/core's seal(), in a plain text column. No new SQL type; a text({ max }) bound is checked against the plaintext before sealing and emits no CHECK | | Key | the master key x secrets manages. No key is X_SEAL_KEY_MISSING — the plaintext is never stored instead | | Purpose | derived: entity:<table>.<column>, physical names. Never stated, so two columns cannot share one; a value copied between sealed columns does not open. Renaming the table or the column is a re-seal — pin the name with .column() | | Both drivers | memoryDriver() seals too; memoryRepo(entity, seed) refuses a seed for a sealed entity (insertAll instead) | | The seam | sealedRepo(entity, repo) — both driver factories return through it, so database()'s handle and a hand-held postgresRepo(entity) agree. A driver written outside this package returns through it too | | Cost | the key ring is resolved ONCE per repository call, however many values it seals or opens — a 500-row page is one resolution, not a thousand | | Retry | X_ENTITY_SEALED_PREDICATE and X_ENTITY_SEALED_IN_VIEW are registered terminal (ENTITY_ERROR_RETRY): a job stops on its first attempt |

What leaves the server: nothing.

| Path | Sealed column | |---|---| | entity.$schema (an action's or query's output) | absent from the node and from the parsed value; the type is WireRow — the row without it | | entity.$view([...]) | X_ENTITY_SEALED_IN_VIEW | | a record (rowsOf, recordProjection, the persist: true browser store) | dropped from every collected row; projection.sealed lists them | | an entity.row event | dropped from before and after | | decodeRow on a write-ahead-log row | the stored string, never the plaintext (@ultimat3/realtime drops the property before a change leaves) | | a repository row serialised whole — a query's rows, a loose output, a log line, an error's meta, an island prop, a job payload, a cache tier | absent: the property is server-only (below) | | { token: row.token } — the secret named by hand | leaves. Naming it is the one read there is | | $parse, $row, the repository | the whole row, plaintext included — server code only |

A sealed property is server-only, As of 2026-10: own, readable and writable, not enumerable. row.password is the plaintext; nothing that walks the row sees it.

| | | |---|---| | Reads it | row.password, const { password } = row, update(id, row) and insert(row) with the row passed whole | | Does not | JSON.stringify(row), { ...row }, Object.keys / entries / assign, structuredClone(row) | | Prints it | console.log(row) / Bun.inspect(row) — log through logger | | A spread patch | update(id, { ...row, label }) leaves the stored secret alone | | A spread insert, required column | X_INVARIANT_VIOLATED naming the column and the rewrite: insert({ ...row, password: row.password }) | | A spread insert, nullable column | stores NULL — silent; an absent nullable column is a legal insert. Name it: { ...row, token: row.token } | | select({ password: true }), preload() | the row keeps it, still server-only |

Testing a sealed row. toEqual walks enumerable properties, so it cannot see the secret: expect(row).toEqual({ …, password }) fails with an empty diff, and expect(a).toEqual(b) passes over a wrong one. Write one of:

| Assertion | Compares | |---|---| | expect(row).toEqualRow({ id, label: 'primary', password: 'hunter2' }) | every own property (@ultimat3/testing) | | expect(row.password).toBe('hunter2') | the one property, by name | | expect(row).toMatchObject({ password: 'hunter2' }) | the named subset |

toEqualRow compares every own property and names what differs — a server-only one by name, never by value. No key is needed in a test: @ultimat3/testing/preload installs a throwaway one when the app supplied none.

What the database may compare: nothing, or equality.

| Use | .sealed() | .sealed({ lookup: true }) | |---|---|---| | where / andWhere eq, in | compile error; X_ENTITY_SEALED_PREDICATE at runtime | allowed — rewritten to the stored string | | andWhere(column, 'is-null') / 'is-not-null' | allowed — null is stored as NULL, never sealed, so presence is not a secret | allowed | | any other operator, orderBy, countBy, an aggregate, a cursor | refused | refused | | deleteWhere / updateWhere filter | refused | refused — find the row, then write by id | | .unique(), a unique index, an upsert conflict target | refused | allowed | | a plain index | refused | allowed, unordered | | an invariant other than unique | refused | refused — a CHECK would read ciphertext | | .default(), .primaryKey(), .tenant(), .references(), .searchable() | refused on the chain | refused on the chain |

lookup reveals equality: two rows holding one value store one string. Never for a low-entropy value — a boolean, a status, a PIN.

During a key rotation a lookup value has one stored form per declared key, so equality reads through in (…) over sealAll() and .unique() holds per key. x doctor reports X_SEAL_RESEAL_PENDING until every row is rewritten (update(id, { column: row.column }) seals under the current key) and the retired key is dropped (x secrets rotate --drop <keyId>).

A column that already holds plaintext is migrated, never tolerated. A stored value that is not a sealed value is X_SEAL_INVALID, always. Expand, backfill, contract:

| # | Step | Edit | |---|---|---| | 1 | expand | add passwordSealed: text().nullable().sealed() beside password; x db gen "add sealed password"; x db migrate | | 2 | backfill | a backfill() over db.connections.andWhere('passwordSealed', 'is-null') — only the rows still to seal — whose handle runs update(row.id, { passwordSealed: row.password }) per row. Idempotent, so a replayed page is harmless | | 3 | switch | readers and writers use passwordSealed | | 4 | contract | delete password; declare password: text().sealed().column('password_sealed') — the purpose follows the physical name, so nothing is re-sealed; x db gen "drop plaintext password" |

The full recipe with the backfill() declaration: Entities and migrations.

Wide columns

The vocabulary an EXISTING schema needs. The blessed set above is a decision the framework made for a table it was going to create; these are the shapes a table already has, As of 2026-08.

| Builder | Emits | Row type, and why | |---|---|---| | json(schema) | jsonb | the schema is required: a json() returning unknown is the any hole this framework forbids, and a column is the worst place for one — the value arrives from the database as often as from a caller. The object is bound as an object, never as JSON text | | decimal({ precision, scale }) | numeric(p, s) | a string, the exact digits. Money is the one decimal with an opinion (integer minor units + a currency); this is every other one, and a value with more decimal places than the column stores is refused rather than rounded. A whole part of 0 counts no digit, so numeric(2, 2) holds 0.50 | | date() | date | @ultimat3/time's PlainDate — a calendar date, no time, no zone. effective_on is the date a rate applies, and as a timestamptz it is a different date on either side of midnight for half the planet | | bigint() | bigint | a decimal string. A JS bigint is what JSON.stringify throws on and a number loses digits past 2^53 — which is exactly where a legacy int8 key lives. Both driver spellings (a string from Bun's sql, a bigint from PGlite) arrive as one. Bounded at int8 (−2^63 … 2^63−1): one past either end is refused where Postgres answers 22003 | | bytes() | bytea | a plain Uint8Array, normalised: Bun's sql returns a Buffer and PGlite a Uint8Array, and the two do not serialise alike | | arrayOf(column) | <element>[] | readonly T[], each member parsed by the element column it was given. Money and nested arrays are refused — an element is one scalar column. Read by the declaration, not by the driver: Bun.SQL hands uuid[] back as its text literal ('{…}') and PGlite as an Array, and both decode to the same row |

Adopting an existing table

Three overrides, and together they are what makes a schema Ultimate did not generate declarable at all. Nothing here changes what an entity without them emits.

import { date, entity, money, text, uuid } from '@ultimat3/entity';

export const accounts = entity('account', {
  table: 'legacy_accounts',
  columns: {
    id: uuid().primaryKey().column('account_id'),
    githubLogin: text({ max: 40 }).column('gh_login'),
    balance: money({ columns: { minor: 'amount_cents', currency: 'currency', scale: null } }),
    openedOn: date().column('opened_on'),
  },
});

| Override | What follows it | |---|---| | entity(name, { table }) | every statement, index name and foreign key. The entity NAME stays the framework's key — the registry, the cache tag (entity:account), x entities show and every relation are keyed by it, so renaming a table never moves a cache tag or a policy | | .column(name) | the DDL, the binding, the decoder, the predicate, the sort key, the cursor. Name it LAST in a chain — the link returns the general column, and only uuid() and timestamp() keep their own methods across it | | money({ columns }) | per part, merged over <name>_minor / <name>_currency / <name>_scale, so a table that renamed one does not restate the other two. scale: null says the table has no scale column: every amount is then at the currency's own minor unit, which is what an absent scale already means |

A physical name is checked where it is written — lower-case letters, digits and underscores, at most the 63 bytes Postgres truncates at — because it is spliced into every statement as an identifier.

What is not adoptable yet, As of 2026-08: a numeric money column with no currency column beside it (money() is two columns by construction — declare it decimal() and keep the currency in the app), a Postgres enum TYPE (enumerated() emits a CHECK, not a CREATE TYPE), a composite type, and a live query over a renamed column — @ultimat3/realtime rebuilds a row from the physical names alone and would deliver ghLogin where the repository says githubLogin.

Branded ids

import { database, entity, uuid } from '@ultimat3/entity';

type PostId = string & { readonly __brand: 'PostId' };
type UserId = string & { readonly __brand: 'UserId' };

const users = entity('users', { columns: { id: uuid().primaryKey() } });
declare const postId: PostId;

export const posts = entity('posts', {
  columns: { id: uuid<PostId>().primaryKey(), authorId: uuid<UserId>().references(() => users.id) },
});

const db = database({ posts });
const post = await db.posts.where({ id: postId }).one();   // PostId — a UserId here is a compile error

The brand is declared once, on the column, and carried by the whole chain: RowOf, Insertable, Repo.findById/update/delete and Table.update/delete, whose id parameters are IdOf<Row> — the type the entity's own id column declared. IdOf collapses to string for a row that declared no brand and for a composite key, so an unbranded entity reads exactly as it always did. Nothing is checked at runtime: a brand has no witness, $parse still validates the uuid, and type-pins.ts is where the claim is enforced.

Invariants run twice

One declaration, two enforcement points: the app checks it on every write, and the migration emits it. A bulk import or a psql session hits the same rule.

The DDL is @ultimat3/db's — one renderer, reading $describe(), so what x db gen writes is the only spelling there is. On a table this migration creates the check is an inline clause; on one that already exists it is the alter table beside it.

alter table "posts" add constraint "posts_post_like_count_non_negative_check" check (like_count >= 0);
create unique index "posts_post_slug_unique_per_org_key" on "posts" ("org_id", "slug");

A rule written as a JS predicate — c.slug.matches(isValidSlug), c.satisfies(fn, [...]) — still runs on write, reports kind: 'assert' and sql: null, and is what x verify warns about: a rule the database does not know is a rule a migration script can violate.

A RegExp is not a predicate and does reach the database: c.slug.matches(/^[a-z0-9]+(?:-[a-z0-9]+)*$/) is kind: 'check' and emits slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'. The same string runs in both places — nothing is translated — so a construct the two engines read differently is REFUSED where it is written, with the portable spelling in the fix where one exists (\w -> [A-Za-z0-9_], . -> [^\n\r]) and the app-only predicate where none does (\b is a word boundary to .test() and a BACKSPACE to Postgres). i becomes ~*; every other flag is refused. Also refused, because Postgres rejects the CHECK or answers it differently: an astral character (Bun writes /😀/ as a surrogate pair \uD83D\uDE00), a repetition bound past 255 ({256}), a - straight after a range or \d inside a class unless it is last ([a-z-9]), and a quantified lookahead ((?=a)*).

isNull() / isNotNull() are the only pair in the vocabulary TOTAL over NULL — IS NULL answers true or false for every input, and the app side reads an ABSENT key and a stored null as one value. iff(a, b) is the biconditional over two predicates, rendered (a) = (b), which is what Postgres spells one as:

import { entity, enumerated, iff, invariant, timestamp, uuid } from '@ultimat3/entity';

export const publishable = entity('publishable', {
  columns: {
    id: uuid().primaryKey(),
    status: enumerated(['draft', 'published']).default('draft'),
    publishedAt: timestamp().nullable(),
  },
  invariants: (c) => [
    invariant('post_publish_coherent', iff(c.status.eq('published'), c.publishedAt.isNotNull())),
    // check ((status = 'published') = (published_at is not null))
  ],
});

A satisfies(fn, [...]) that could be written this way should be: only one of the two reaches the database, and x verify reports the other as a rule the database does not know.

One typed handle

import { database, entity, timestamp, uuid } from '@ultimat3/entity';

const orgs = entity('orgs', { columns: { id: uuid().primaryKey() } });
const posts = entity('posts', {
  tenant: 'orgId',
  columns: { id: uuid().primaryKey(), orgId: uuid(), createdAt: timestamp().defaultNow() },
});
declare const orgId: string;

export const db = database({ orgs, posts });

db.posts.where({ orgId }).orderBy('createdAt').limit(50).page(); // { rows, nextCursor, hasMore }

db.posts exists because posts was declared. Pagination is cursor-only: OFFSET is wrong under concurrent writes, because an insert before the offset shifts every later page and the client silently skips and repeats rows.

The page is @ultimat3/core's Page — the one page shape, the same a query's .page() answers (this package's own Page, { rows, nextCursor } with no hasMore, left in 25.0.0). nextCursor is null exactly when hasMore is false, so while (page.hasMore) stops on the last page.

nextCursor is signed by @ultimat3/core and scoped to the plan that produced it — this entity, these filters, this sort order. A tampered cursor, or one taken from another listing, is X_CURSOR_INVALID rather than a silent page one. The page size is deliberately outside the scope: asking for a bigger next page is the same query.

The primary key is appended as the final sort key in the last declared key's direction, so orderBy('createdAt', 'desc') runs created_at desc, id desc — one direction throughout, which is what indexes: [{ on: ['createdAt', 'id'], order: 'desc' }] can cover and what lets the seek go out as the row comparison (created_at, id) < ($1, $2). Write the mixed order yourself (.orderBy('createdAt', 'desc').orderBy('id', 'asc')) and you get it, spelled out as an or-chain.

A nullable sort key orders rather than being refused: asc nulls last, desc nulls first — written into the statement rather than inherited from the server, and the same spelling @ultimat3/query uses. posts.orderBy('publishedAt', 'desc') on a nullable column pages correctly in both drivers; the cursor carries "this row had none" as a position of its own. The one ordering still refused is a nullable primary-key column, which no tiebreak can make total.

orderBy on a json, bytes or array column is refused where the plan is built, at any row count (X_INVARIANT_VIOLATED). It has no position a cursor can carry: it paged wrongly or threw past page

  1. Order by a scalar.

A timestamp() sort key is carried at the column's own microsecond precision, not at the millisecond a JS Date holds: the read projects the instant as text beside the column and the seek binds all six digits. Without it a desc page over rows sharing one millisecond — which defaultNow() produces routinely — served some of them on no page at all. Cursors do not survive that change: one minted by an older version is X_CURSOR_INVALID.

A page is bounded whether or not the caller bounded it. DEFAULT_PAGE_SIZE (50) covers the read nobody sized; MAX_PAGE_SIZE (10,000) covers the one they did — limit(input.pageSize) on a number that arrived over the wire is the same production incident with an argument in front of it. A page size that is not a whole number of rows in 1..MAX_PAGE_SIZE is X_INVARIANT_VIOLATED on the chain and again inside the plan both drivers build, so findMany({ limit }) straight at the repository cannot route around it. inBatches(size) is the call that means "every row" — one page per statement, never a table in memory.

A page is bounded in bytes too: MAX_PAGE_BYTES (64 MiB), weighed on the raw rows before decode (the projected page in memory and on a custom store) — past it X_ENTITY_PAGE_TOO_LARGE, naming a select(…) and a limit(n) that fits.

DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, MAX_PAGE_BYTES and MAX_ASSERTED_ROWS are exported, beside N_PLUS_ONE_THRESHOLD and for the same reason: an action validating its own pageSize input against a hardcoded 10_000 is a second declaration of one number, and the second one goes stale.

Iterating every row

As of 2026-08. A page is bounded on purpose, so reading a whole table is a loop — and the loop is the terminal, not something the caller writes around page():

// One statement per batch, one page of rows in memory at a time.
import { database, entity, text, uuid } from '@ultimat3/entity';
import { type Ctx } from '@ultimat3/core';

declare const checkpoint: string | null;
declare const deadline: Date;
declare const search: { index(rows: readonly object[]): Promise<void> };

const members = entity('members', {
  tenant: 'orgId',
  columns: { id: uuid().primaryKey(), orgId: uuid() },
});
const posts = entity('posts', {
  tenant: 'orgId',
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid(),
    authorId: uuid().references(() => members.id),
  },
});
const checkpoints = entity('checkpoints', {
  columns: { id: uuid().primaryKey(), cursor: text().nullable() },
});
const db = database({ checkpoints, members, posts });
declare const id: string;
declare const orgId: string;
declare const ctx: Ctx;

for await (const batch of db.posts.where({ orgId }).preload('author').inBatches(500)) {
  await search.index(batch);
}

// Stopping early is cheap: the position survives, so the next run resumes where this one stopped.
await using batches = db.posts.where({ orgId }).after(checkpoint).inBatches(500);
for await (const batch of batches) {
  await search.index(batch);
  if (ctx.clock.now() > deadline) break;
}
await db.checkpoints.update(id, { cursor: batches.cursor });

Every batch is the page page() would have returned at that position — same filters, same tenancy, same soft-delete visibility, same select(), same preload() — so there is no second read path to learn or to drift.

| | | |---|---| | Statements | one per batch, each asking for one row past it, exactly as page() does. An empty batch is never yielded | | Position | keyset, never OFFSET: a row written mid-iteration cannot make the loop skip or repeat one. after(cursor) starts it, .cursor is where it stopped, null once exhausted | | Closing | break, return and a throw all stop the next statement; await using is the same guarantee for a handle kept in a variable, and close() is idempotent. One handle is one iteration — a second for await continues it rather than restarting the table | | Refusals | on the chain, not one batch later: a size that is not a whole number of rows between 1 and MAX_PAGE_SIZE (10,000), a limit() on the same chain (one number, two meanings), and an ordering no cursor can carry — a nullable sort column, which a result that fits in one batch would otherwise hide until the table grew | | Tenancy | the plan's, as everywhere else: an unscoped chain is X_TENANCY_UNSCOPED on its first batch |

Aggregates

import { database, entity, integer, money, timestamp, uuid } from '@ultimat3/entity';

const payments = entity('payments', {
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid(),
    amount: money(),
    installments: integer().default(1),
    paidAt: timestamp(),
  },
});
// No tenant column, because an estimate is the whole TABLE's: a tenant-scoped entity is refused.
const events = entity('events', { columns: { id: uuid().primaryKey(), at: timestamp() } });
const db = database({ payments, events });
declare const orgId: string;
declare const since: Date;

await db.payments.where({ orgId }).andWhere('paidAt', 'gte', since).sum('amount');
// { minor: 128400, currency: 'EUR' }

await db.payments.where({ orgId }).avg('installments'); // '2.500000'
await db.payments.where({ orgId }).max('paidAt');       // Date | null
await db.events.approximateCount();                     // 12_400_000 | null

Over exactly the rows count() counts — the chain's filters, its tenancy and its soft-delete visibility, never its page.

| | | |---|---| | Never a float | sum/avg answer decimal text whatever the column was (the sum of a million integer rows is not an integer, and Number() past 2^53 loses digits); money answers MoneyValue in integer minor units; min/max answer the row's own type | | Empty set | null in every function, which is what SQL answers — a 0 would claim rows were seen. count() is 0, and that is the distinction | | avg | one fixed scale (6 digits), rounded half away from zero from the exact rational, so both drivers land on one number — at any magnitude: Postgres' own avg(bigint) keeps about sixteen significant digits, so the statement does the integer arithmetic itself (averageSql, As of 2026-11) | | Refused | min/max on text (ordering is the database's collation there and JS code-unit order here); avg over money (every answer would be a silent rounding of a fraction of a minor unit — sum() and count() instead, dividing where the rounding is a decision); an amount covering more than one currency or scale; a money total past ±2^53 minor units | | approximateCount() | reltuples out of pg_class, constant time, because count(*) walks every visible row and no index can make it cheaper. The whole table — a filtered chain, every tenant-scoped entity and every soft-deleting one (reltuples counts the deleted rows) are X_APPROXIMATE_COUNT_FILTERED, and null means the table has never been analysed |

The operator vocabulary

andWhere(column, op, value) takes one of OPERATORS — eq, neq, in, gt, gte, lt, lte, like, is-null, is-not-null, contains, contained-by, overlaps, has-key, matches — and the Operator type is derived from that one list. An op outside it ('>', 'GT') is X_ENTITY_OPERATOR_UNKNOWN on the andWhere line, and in both drivers for a hand-built plan — never an empty result. The fix names the operator meant: >→gt, >=→gte, <→lt, <=→lte, =→eq, !=/<>→neq. isOperator(value) is the same test, for an op read off the wire.

An operand is read by the column's kind, once for both drivers (predicate-operand.ts):

| Column | Operand | Both drivers | |---|---|---| | timestamp() | a Date or ISO text with Z/an offset | compared as that instant | | timestamp() | zoneless ISO text ('2026-01-01', '2026-01-01T10:00') | read as UTC in both drivers, never the server's TimeZone | | timestamp() | a number | X_INVARIANT_VIOLATED — epoch milliseconds are no instant Postgres parses | | timestamp() | a Date outside years 0001–9999, or text in year 0000 | X_INVARIANT_VIOLATED — Postgres reads an instant as ISO text with a four-digit year. A write is refused the same way, at its entry; a row the server already holds outside the range still reads (As of 2026-11) | | date() | a Date | its UTC calendar date (plainDateUtc), as $parse writes one | | integer() / bigint() | a fraction (1.5, '1.5', '1e1') | X_INVARIANT_VIOLATED — round it to the bound you mean | | every kind but text() / char() / bytes() | any like | X_INVARIANT_VIOLATED — a pattern matches text; a number is matched by range, a uuid, boolean, instant, date, jsonb or array by value (As of 2026-11) | | uuid() | any spelling Postgres parses — upper case, no hyphens, {braces} | the one value it names, in eq/neq/in, findById and a batched lookup | | uuid() | text that is no uuid, under eq/neq/in | a value no row equals: eq/in match nothing, neq every row; findById is null, update/delete are X_NOT_FOUND — never 22P02. It is not bound, so the statement reads 1 = 0 (As of 2026-11) | | any | an in list of 32,768 values or more | one array parameter (= any($1)) on Postgres, so a list past the 65,535-bind limit answers. bytes(), json() and arrayOf() have no array form: past 65,535 values they are X_INVARIANT_VIOLATED in both drivers (As of 2026-11) | | arrayOf() | a list, under eq/neq/in | element by element, in order (array_eq) |

A predicate tree: andWhereNode

andWhereNode(node) (As of 2026-11) adds one predicate TREE to a chain, AND-ed with the rest — the one way to say or, an and inside it, or a relation hop. One statement either way.

| Node (PredicateNode<Row>) | Compiles to | |---|---| | { column, op, value? } | a leaf, exactly andWhere(column, op, value) | | { or: [...] } | ( … or … ); [] is 1 = 0 | | { and: [...] } | ( … and … ); [] is true | | { via: { column, entity, target }, where: [...] } | "column" in (select "target" from <entity's table> where …) |

import { database, entity, text, timestamp, uuid } from '@ultimat3/entity';

const posts = entity('posts', {
  columns: {
    id: uuid().primaryKey(),
    authorId: uuid(),
    audience: text({ max: 10 }),
    publishedAt: timestamp().defaultNow(),
    deletedAt: timestamp().nullable(),
  },
});
entity('friendships', {
  columns: { id: uuid().primaryKey(), userId: uuid(), friendId: uuid() },
});
const db = database({ posts });
declare const me: string;

await db.posts
  .where({ deletedAt: null })
  .andWhereNode({
    or: [
      { column: 'authorId', op: 'eq', value: me },
      { column: 'audience', op: 'eq', value: 'public' },
      {
        via: { column: 'authorId', entity: 'friendships', target: 'friendId' },
        where: [{ column: 'userId', op: 'eq', value: me }],
      },
    ],
  })
  .orderBy('publishedAt', 'desc')
  .limit(20)
  .all();
  • A hop is planned through its TARGET's tenant guard (via-scope.ts, in readPlan): the acting actor's tenant and the target's soft delete apply inside the subselect; outside a request its where must name the tenant (X_TENANCY_UNSCOPED). An untenanted target behind a tenanted source must declare shared: or global:. A hop value no readPlan scoped is refused by both drivers.
  • entity is a registered entity NAME; column, target and every inner column must be declared and not sealed; at most MAX_PREDICATE_DEPTH (4) levels. Each refusal is X_ENTITY_PREDICATE_NODE_INVALID, on the chain line.
  • Leaf columns are typed by the row at the top and inside every group; a hop's inner level is the target's and takes any string. A ScopedNode — what @ultimat3/query hands a provider on RowWindow.nodes — is accepted as is.
  • Memory resolves a hop to an in list from its other tables (memory-via.ts); Postgres runs the subselect. entityDriverConformance's TREE_CHECKS hold both, tenancy included.
  • A defineDriver store takes a tree only under predicate:or / predicate:via, else X_DRIVER_UNSUPPORTED before the store is called; nothing in process can judge a hop row by row.

Filtering inside a json() or arrayOf() column

import { arrayOf, database, entity, json, text, uuid } from '@ultimat3/entity';
import { t } from '@ultimat3/schema';

const posts = entity('posts', {
  columns: {
    id: uuid().primaryKey(),
    tags: arrayOf(text({ max: 40 })),
    settings: json(t.object({ notify: t.object({ email: t.boolean }) })),
  },
});
const db = database({ posts });

await db.posts.andWhere('tags', 'contains', ['release']).all();
await db.posts.andWhere('tags', 'overlaps', ['release', 'beta']).all();
await db.posts.andWhere('settings', 'contains', { notify: { email: true } }).all();
await db.posts.andWhere('settings', 'has-key', 'notify').all();

contains is @>, contained-by is <@, overlaps is &&, has-key is the ? operator, written schema-qualified as operator(pg_catalog.?) — the function form jsonb_exists(col, $1) is the same test and the planner will not match a GIN index to it. Their meaning is Postgres', to the letter, in both drivers — including that the array-contains-a-primitive exception applies at the top level only and to primitives only, and that &&'s empty operand overlaps nothing where @>'s is contained by everything. Two more rules both drivers hold: a NULL array element equals nothing, itself included, on either side of @>, <@ and && (a jsonb null is a value and still equals itself); and has-key takes a string key — any other operand matches no row, never String(operand).

There is no jsonpath expression operator: contains already matches nested structure, and a path language inside the query language would be a second way to ask one question. && on a jsonb column is refused, because Postgres has no such operator.

Declare the index those operators need, or every one of them is a sequential scan:

import { arrayOf, entity, json, text, uuid } from '@ultimat3/entity';
import { t } from '@ultimat3/schema';

export const posts = entity('posts', {
  columns: {
    id: uuid().primaryKey(),
    tags: arrayOf(text({ max: 40 })),
    settings: json(t.object({ notify: t.object({ email: t.boolean }) })),
  },
  indexes: [{ on: ['tags'], using: 'gin' }, { on: ['settings'], using: 'gin' }],
});

| | | |---|---| | Methods | btree (the default, and what every index without using is) and gin. Omitting it emits the statement it always emitted, and regenerates nothing | | Served by a GIN index | array contains / contained-by / overlaps, and jsonb contains / has-key — measured on the planner, not assumed | | Not served | jsonb contained-by: <@ is not in Postgres' default jsonb_ops operator class, so it is a sequential scan whatever you declare | | Refused | a unique GIN and an ordered GIN, at entity() — Postgres has neither, and the refusal names the edit | | Naming | the method is part of what separates two indexes on the same columns, so a btree and a GIN on one column are two indexes with two names |

On a big, hot table, build an index with concurrently: true — { on: ['status'], concurrently: true }. x db gen emits create index concurrently if not exists in a migration of its own, marked -- transaction: false, so writes keep flowing while it builds; an interrupted build is rebuilt by the next x db migrate. It is how the index is built, not what it is: not part of the name, not recorded, and toggling it generates nothing. Every index REMOVED from indexes is dropped the same way, concurrently or not — @ultimat3/db's README, "Indexes built concurrently".

Code-point collation

text().collate('C') declares collate "C": the column orders and compares by code point, the order the memory driver and a live window's matcher already keep. 'C' is the only collation a column may declare (another is X_INVARIANT_VIOLATED where written). A live query ordered by a text column WITHOUT it is a query.live.order_collation warning in development and test (X_LIVE_ORDER_COLLATION): Postgres orders apple before Banana, the matcher does not.

import { entity, text, uuid } from '@ultimat3/entity';

export const tags = entity('tags', {
  columns: {
    id: uuid().primaryKey(),
    name: text({ max: 40 }).collate('C'),   // a live list may .orderBy('name')
  },
});

Declaring or dropping it on an existing column is x db gen: alter column … type text collate "C", in place, with its reverse in down.

Full-text search

.searchable() on a text() column puts it in the entity's one generated tsvector, with a GIN index on it. Nothing else to declare, and no second column on the row.

import { database, entity, text, timestamp, uuid } from '@ultimat3/entity';

declare const orgId: string;
declare const term: string;   // what the user typed, verbatim

const posts = entity('posts', {
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid().tenant(),
    title: text({ max: 120 }).searchable('A'),   // 'A' outranks 'D' under ts_rank
    body: text().nullable().searchable(),        // 'D' by default, Postgres' own
    createdAt: timestamp().defaultNow(),
  },
  // Only when the defaults do not fit: the column is `search_tsv`, the language is 'english'.
  search: { column: 'search_tsv', language: 'english' },
});

const db = database({ posts });

await db.posts.where({ orgId }).search(term).orderBy('createdAt', 'desc').limit(20).page();

| Fact | Why | |---|---| | the term is a bound parameter, parsed by websearch_to_tsquery | &, \|, !, :* and an unbalanced paren are characters to match, never operators and never a 42601. plainto_tsquery is safe too and silently discards "a phrase" and -negation; bare to_tsquery on user text is the injection | | the language is spliced from a closed set (SEARCH_LANGUAGES) | regconfig cannot be a bound parameter inside a generated column, and to_tsvector(text) with no configuration is not immutable, so Postgres refuses it there | | the column is generated always as (…) stored, not null | the database computes it on every write, including one made from psql | | tenancy, soft delete, the projection, the order and the cursor are unchanged | .search() is one more predicate on the chain you already had | | memoryDriver() refuses it — X_SEARCH_IN_MEMORY | stemming, stop words and a phrase parser are not a JS token comparison, and an answer memory could give is one Postgres would contradict. Assert a search in a .live.test.ts | | relevance is not an order the chain serves | ts_rank is a computed value and a cursor carries columns; the order is the one you declared, and it pages |

Search index (the searchIndex port)

.searchable() columns are searched through one port, SearchIndex (index / remove / query / list, every call tenant-scoped by { entity, tenant }; list leaving tenant out is every tenant's, the sweep's maintenance read).

| Index | What it is | |---|---| | postgresSearchIndex() | the default: the generated tsvector; index/remove send nothing (the server keeps the vector), query is the repository's own matches read — tenancy, actor check and soft delete included. Hits in primary-key order (no rank). list pages the table itself | | memorySearchIndex() | the reference to copy and the unit-test index: words, case-folded, every word required; no stemming | | Meilisearch / Typesense | the app's: implement SearchIndex, prove it with behavesLike(searchIndexConformance, …) from @ultimat3/testing/conformance, return it as searchIndex from runtime.ts |

import { database, entity, searchIndex, text, timestamp, uuid } from '@ultimat3/entity';

const posts = entity('posts', {
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid().tenant(),
    title: text().searchable('A'),
    updatedAt: timestamp().defaultNow().onUpdateNow(), // the document's version
  },
});
const db = database({ posts });

export const find = async (orgId: string, q: string) => {
  const hits = await searchIndex().query({ entity: 'posts', tenant: orgId, term: q, limit: 20 });
  const page = await db.posts.where({ orgId }).search(q).page(); // the same port, one path
  return { hits, page };
};

| Rule | Detail | |---|---| | .search(term) asks the installed index | built-in: the matches predicate in the statement (today's SQL). Any other: ids first — 10,000 (MAX_PAGE_SIZE) or more hits are refused with X_INVARIANT_VIOLATED, never truncated — then the chain reads those rows with its own tenancy, soft delete, order and cursor. The index is asked per tenant: the chain's eq on the tenant column, else the actor's org — and inside crossTenant() each tenant of an andWhere('<tenant>', 'in', [...]), never the actor's alone; a crossTenant search naming neither is refused (X_INVARIANT_VIOLATED) | | a document has a version | the row's onUpdateNow() instant, epoch ms. A searchable entity indexed by anything declares one — updatedAt: timestamp().defaultNow().onUpdateNow() — or searchDocumentOf and reindex() refuse (X_INVARIANT_VIOLATED) | | the version is STRICTLY increasing per row | a write of a searchable entity — a soft delete included — stores its version no earlier than the stored one + 1 ms: Postgres greatest($now, updated_at + interval '1 millisecond') in the update and the upsert's on conflict set; the memory driver in its merge (advanceVersion); a defineDriver store in ITS write, atomically per row — DriverRepo.update's advance argument, and advanceVersion(entity, stored, merged, (p) => plan.set.includes(p)) in its own upsert (entityDriverConformance refuses a store that skips either). So two writes inside one millisecond are two versions, and the index keeps the second. The column may run ahead of the clock by a millisecond per same-ms write. Other entities' onUpdateNow() columns are the clock's reading, unchanged | | keep only newer | an index applies a document only when its version is newer than what it holds for that id: a document, or the tombstone remove(scope, ids, version) leaves (a delete's: past the row's last version and no earlier than its instant). Equal = replay. EXCEPT a committed document — the write path's, index(docs, { committed: true }) — which replaces a tombstone whatever its version: a key deleted and written again is live at once, inside one millisecond too. reindex's reads are not committed, so a stale read never brings a deleted row back | | the write path | while an external index is installed (runtime.ts's searchIndex, installSearchIndex), every COMMITTED write of a searchable entity reaches it: insert/insertAll/upsertAll/update/transition/updateWhere index the rows written, delete/deleteWhere (soft or hard) remove them — whatever the key: id, another column, composite. Taken when the write runs, merged per key per transaction (a removal then a document of one key sends both, in that order; a document then a removal, the removal), sent at COMMIT on one chain per index, so the index hears this process's writes in commit order (search-mirror-batch.ts). No bus subscription: a rollback indexes nothing | | the rows of a delete or filtered write | the driver hands them over (returning * on Postgres) ONLY for a searchable entity under an external index — every other write stays a count | | a failed mirror never fails the write | logged as entity.search-index.write-failed (entity, op, code, cause, fix); reindex() (@ultimat3/jobs) is the repair, its sweep removing what the table lost | | not mirrored, logged the same way | a delete or filtered write past MAX_ASSERTED_ROWS rows: Postgres counts first and sends no returning * past it (memory and defineDriver stores the same) | | the built-in index costs nothing | under postgresSearchIndex() a write sends the statement it always did: no returning, no read |

searchDocumentOf(entity, row) is the one document builder (only .searchable() columns leave). searchVersionColumn and searchVersionOf are on the . barrel; installSearchIndex is on @ultimat3/entity/adapter.

A state machine over a column

.transitions() on an enumerated() column. The states are yours; the machine is the framework's.

import { database, entity, enumerated, timestamp, uuid } from '@ultimat3/entity';

declare const id: string;

const ORDER_STATES = ['pending', 'paid', 'shipped', 'delivered', 'cancelled'] as const;

const orders = entity('orders', {
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid().tenant(),
    status: enumerated(ORDER_STATES)
      .transitions({
        pending: ['paid', 'cancelled'],
        paid: ['shipped', 'cancelled'],
        shipped: ['delivered'],
        delivered: [],     // terminal — nothing leaves it, and an empty list is how you say so
        cancelled: [],
      })
      .default('pending'),
    updatedAt: timestamp().defaultNow().onUpdateNow(),
  },
});

const db = database({ orders });

// One statement. `from` is the state you believe the row is in, and it rides in the predicate.
const shipped = await db.orders.transition('status', id, { from: 'paid', to: 'shipped' });

// Decided about the row? Say what the decision read, and the move is conditional on it too.
const read = await db.orders.where({ id }).one();
await db.orders.transition('status', id, {
  from: 'shipped',
  to: 'delivered',
  observed: { row: read, read: ['orgId'] },
});

| Fact | Why | |---|---| | the table is a mapped type over your enumerated() set | a missing state, an unknown key and an unknown target are compile errors — the framework never names a state | | one statement, with from in its predicate | the state observed and the state written are one decision, under the row's lock. Two callers who both read pending cannot both move it: the second matches no row | | a move the table does not hold is X_STATE_TRANSITION_ILLEGAL, before any statement | the table is a property of the declaration, so an illegal move never reaches the database | | a row that moved first is X_STATE_CONFLICT, naming the state it is really in | read back after the refusal — a diagnosis, never the decision | | another org's row is X_NOT_FOUND, never a conflict | a conflict would confirm the row exists and name its state | | a terminal state is one with an empty list | derived. Which state is terminal is yours | | onUpdateNow() moves, because a transition is an update | the audit of when it moved, with no second mechanism beside it | | the CHECK comes from enumerated() | the machine emits no DDL of its own — one declaration of what a legal value is | | memoryDriver() answers it exactly as Postgres does | a compare-and-set over a map is the same question; unlike a tsvector match, there is nothing to fake | | an undefined or null id is X_NOT_FOUND, and moves no row | an absent id names no row — it is refused before the statement, where it used to drop out of the filter and move every row in the from state | | observed: { row, read } pins what a decision read, in the same statement | a move decided about the row (row.authorId === actor.id) is conditional on that row still holding it: each read property that is a plain column of THIS row (a row carrying another key is another record; a keyless projection is this one) joins id and from in the predicate. A reassignment committed first matches no row; one in flight holds the row's lock, and Postgres re-checks the predicate after it commits. Either way X_STATE_CONFLICT, naming the column and never its value. @ultimat3/action's transition() fills it from what its policy read (#702) | | a timestamptz, jsonb, array, bytea, money or sealed column is not pinned | none has an = meaning one thing in both drivers — a defaultNow() column holds microseconds in Postgres and a decoded Date milliseconds, so a pin on it would refuse every move there and none in memory (transition-observed.test.ts) |

What is deliberately not here: who may make a move, what happens on arrival, an approval chain, a reason code. Those differ per app — wrap transition() in your own function and put them there.

A series of time buckets, and views

As of 2026-11. series({ on, unit, timeZone, value }) is the grouped count per bucket of time — minute/hour/day/week/month, in the IANA zone named (required), truncated as Postgres' date_trunc(unit, col, zone) truncates, by the same rules in the memory driver (time-bucket.ts). value is 'count' or { sum: column }; ascending; past 1000 buckets X_ENTITY_SERIES_INVALID. Optional on Repo (X_ENTITY_SERIES_UNSUPPORTED for a hand-written one).

entity(name, { view: { sql, materialized? }, columns }) is a read-only relation: $viewQuery, $describe().view, every write X_ENTITY_VIEW_READ_ONLY (view-repo.ts, applied through appendOnlyRepo). Full reference: Entities and migrations.

Counting by a column

As of 2026-08. count() answers one number, so a screen or a backfill that needs one per row asks N times. countBy(column) is that whole loop as one statement, keyed by the value:

// One statement for every post in `ids`, not one `select count(*)` each.
import { database, entity, integer, uuid } from '@ultimat3/entity';

const posts = entity('posts', {
  tenant: 'orgId',
  columns: { id: uuid().primaryKey(), orgId: uuid(), likeCount: integer().default(0) },
});
const likes = entity('likes', {
  tenant: 'orgId',
  columns: { id: uuid().primaryKey(), orgId: uuid(), postId: uuid() },
});
const db = database({ likes, posts });
declare const orgId: string;
declare const ids: readonly string[];

const counts = await db.likes.where({ orgId }).andWhere('postId', 'in', ids).countBy('postId');
for (const id of ids) await db.posts.update(id, { likeCount: counts.get(id) ?? 0 });

ReadonlyMap<Row[K], number>, keyed by the column named — the chain knows the row, so counts.get(postId) is a number | undefined and the undefined is load-bearing.

| | | |---|---| | Counts | the whole predicate, exactly as count() does: the chain's filters, its tenancy and its soft-delete visibility. limit() and after() bound the page, never the count | | A value nothing matched | absent, never 0 — that is what group by returns, and it is what tells "none" apart from "never asked". The default is the caller's ?? 0 | | NULL | one group, keyed null, in both drivers. 0, '' and false stay the values they are | | Order | biggest group first, ties by the value (numbers and bigints numerically, everything else by its text), null last — applied after the rows are in, since a hash aggregate and a Map filled row by row have no order to inherit | | Groupable columns | uuid, text, char, boolean, integer, bigint. A timestamp, a jsonb or money is X_INVARIANT_VIOLATED naming one of this entity's columns that is: a Map compares a non-primitive key by identity, so such a map could only ever answer undefined | | More than 1000 groups | X_INVARIANT_VIOLATED, never a truncated map — the statement asks for one group past the bound, exactly as a page reads one row past its limit. The fix spells the andWhere('<column>', 'in', <values>) that bounds it | | Statement | select "post_id" as group_value, count(*) as group_count … group by "post_id". Both names are fixed aliases, so an entity may still declare a column called count, and the grouped value is re-parsed by the column that declared it |

Newest per group, several measures, many locks, a version

import { database, entity, integer, money, text, timestamp, uuid } from '@ultimat3/entity';

const messages = entity('messages', {
  columns: { id: uuid().primaryKey(), conversationId: uuid(), body: text(), createdAt: timestamp() },
});
const posts = entity('posts', {
  columns: { id: uuid().primaryKey(), orgId: uuid(), authorId: uuid(), status: text() },
});
const payments = entity('payments', {
  columns: { id: uuid().primaryKey(), orgId: uuid(), amount: money(), status: text() },
});
const accounts = entity('accounts', { columns: { id: uuid().primaryKey(), balance: integer() } });
const db = database({ messages, posts, payments, accounts });
declare const ids: string[];
declare const orgId: string;
declare const from: string;
declare const to: string;

// One DISTINCT ON statement: the newest message of each conversation (memory mirrors it)
await db.messages.andWhere('conversationId', 'in', ids).latestBy('conversationId', { order: 'createdAt' });

// count(*) filter (where …): a group the filter empties answers 0, never absent
await db.posts.where({ orgId }).countBy('authorId', { where: [['status', 'eq', 'published']] });
// Several measures, one statement
await db.payments.where({ orgId }).aggregate({
  total: { fn: 'count' },
  paid: { fn: 'sum', column: 'amount', where: [['status', 'eq', 'paid']] },
});

// Every key held for fn, in ONE transaction, taken in sorted order: no deadlock between callers
await db.accounts.lockKeys(['acct:' + from, 'acct:' + to], async (tx) => { /* … */ });

| | | |---|---| | latestBy(group, { order, direction? }) | one row per group, ties to the primary key, groups ordered null last; past MAX_LATEST_GROUPS refused, never truncated; orderBy()/limit()/after() on the same chain refused. Repo.latestBy? is optional: without it (a hand-written repository, a custom store) paged findMany reads are folded — correct, never one statement. preload(rel, { perParent: n }) reads n per parent in one LATERAL | | countBy(col, { where }) · aggregate({ name: { fn, column?, where? } }) | one statement on Postgres and memory; at most MAX_MEASURES; sum/avg decimal text, money a MoneyValue, never a float. A defineDriver store composes them from the capabilities it declares (aggregate:countBy, aggregate:<fn>): several store calls, the same answer | | andWhere(col, 'contains', term) on text()/char() | case-insensitive substring (ilike, the term bound and escaped). Served by a trigram index only — declare indexes: [{ on: ['<col>'], using: 'gin', operatorClass: 'gin_trgm_ops' }] (trigramDeclaration(col)); the plan sweep reports one without it | | indexes: key parts | four optional fields beside on, each absent by default so no existing index name or schema hash moves (declared-index-keys.ts, refused at entity() with X_INVARIANT_VIOLATED): expression: 'lower(email)' — the ONE key is that SQL over physical columns, on names the columns it reads (a concurrent refreshView refuses it as its unique key); orders: ['desc', null] — a direction per key, btree only, never beside order; include: ['title'] — INCLUDE payload, btree only; operatorClass: 'gin_trgm_ops' — needs using: 'gin'. A foreign-key index another index already leads with is still emitted — dropping it would make an existing app's next x db gen remove an index the database holds — and is listed on RegistryEntry.coveredIndexes (CoveredIndex: the index and the one that covers it; coveredImplicitIndexes, tenant-index.ts) | | lockKeys(keys, fn) | lockKey's tenancy and hashing per key, deduped, sorted, at most MAX_LOCK_KEYS (64), one transaction; X_LOCK_UNSUPPORTED for a repository without it | | holdKey(key) · holdKeys(keys) | lockKey's / lockKeys' lock taken in the caller's open transaction, held to its root's end (or a rollback to a savepoint it was taken in): no callback, no savepoint, one statement. Outside a transaction X_LOCK_HOLD_OUTSIDE_TX; X_LOCK_UNSUPPORTED for a repository without them | | entity({ version: 'lockVersion' }) | an optimistic lock on an integer().default(0) column: update(id, { …patch, lockVersion: row.lockVersion }) conditions on it and increments it — moved since the read is X_ENTITY_STALE (409), omitted is X_ENTITY_VERSION_INVALID. updateMany checks every row (one stale row refuses the batch). updateWhere/updateAll/transition/soft delete increment it and may not set it (compare-and-set goes in the filter: where({ id, lockVersion: 3 })). upsertAll with onMatch: 'update' is refused, 'nothing' allowed. A mutator carries the version as input | | .all() | one page; when a next page existed and the chain named no limit(), dev and test log ALL_TRUNCATED ('entity.all.truncated') with the fix (inBatches() or .limit(n)) | | a countedIn child write | reports each parent whose count moved as an entity.row update (read back in the write's transaction, only while subscribed; before = the count moved back; a filter-pinned bulk write reports before: null, an unpinned one entity.bulk for the parent) — counter-observed.ts | | a subject's history erase | a history table is append-only in both drivers; purgingHistory(name, work) lets a filtered delete of THAT table through — the in-process twin of x.purge, which the GDPR erase opens (memory parity) |

Writing by filter

deleteWhere/updateWhere are the bulk forms of delete/update — the same fix insertAll is for a per-row insert loop, applied to the two write shapes a composite-key entity cannot address one row at a time: a for … of deleting or patching one row per iteration is one statement here, not n.

import { database, entity, integer, text, timestamp, uuid } from '@ultimat3/entity';

const members = entity('members', {
  tenant: 'orgId',
  columns: { id: uuid().primaryKey(), orgId: uuid() },
});
const posts = entity('posts', {
  tenant: 'orgId',
  columns: {
    id: uuid().primaryKey(),
    orgId: uuid(),
    authorId: uuid().references(() => members.id),
    title: text(),
    status: text().default('draft'),
    rank: integer().default(0),
    publishedAt: timestamp().nullable(),
  },
});
const likes = entity('likes', {
  tenant: 'orgId',
  columns: { id: uuid().primaryKey(), orgId: uuid(), postId: uuid(), userId: uuid() },
});
const participants = entity('participants', {
  columns: {
    id: uuid().primaryKey(),
    conversationId: uuid(),
    userId: uuid(),
    lastReadAt: timestamp().nullable(),
  },
});
const db = database({ likes, participants, posts });
declare const id: string;
declare const ids: readonly string[];
declare const title: string;
declare const postId: string;
declare const userId: string;
declare const authorId: string;
declare const conversationId: string;
declare const lastReadA