@ultimat3/cli 31.8.0 → 31.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +29 -29
- package/src/framework-schema.ts +3 -2
- package/wiki/Auth.md +3 -1
- package/wiki/Entities-And-Migrations.md +328 -17
- package/wiki/Jobs-And-Workflows.md +3 -1
- package/wiki/Policies-And-Authz.md +43 -1
- package/wiki/Upgrading.md +13 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/cli",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.10.0",
|
|
4
4
|
"description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -53,34 +53,34 @@
|
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@babel/core": "^8.0.9",
|
|
56
|
-
"@ultimat3/action": "31.
|
|
57
|
-
"@ultimat3/admin": "31.
|
|
58
|
-
"@ultimat3/ai": "31.
|
|
59
|
-
"@ultimat3/auth": "31.
|
|
60
|
-
"@ultimat3/cache": "31.
|
|
61
|
-
"@ultimat3/core": "31.
|
|
62
|
-
"@ultimat3/db": "31.
|
|
63
|
-
"@ultimat3/entity": "31.
|
|
64
|
-
"@ultimat3/flags": "31.
|
|
65
|
-
"@ultimat3/http": "31.
|
|
66
|
-
"@ultimat3/i18n": "31.
|
|
67
|
-
"@ultimat3/jobs": "31.
|
|
68
|
-
"@ultimat3/mail": "31.
|
|
69
|
-
"@ultimat3/manifest": "31.
|
|
70
|
-
"@ultimat3/mcp": "31.
|
|
71
|
-
"@ultimat3/money": "31.
|
|
72
|
-
"@ultimat3/notify": "31.
|
|
73
|
-
"@ultimat3/policy": "31.
|
|
74
|
-
"@ultimat3/pwa": "31.
|
|
75
|
-
"@ultimat3/query": "31.
|
|
76
|
-
"@ultimat3/realtime": "31.
|
|
77
|
-
"@ultimat3/render": "31.
|
|
78
|
-
"@ultimat3/schema": "31.
|
|
79
|
-
"@ultimat3/scraping": "31.
|
|
80
|
-
"@ultimat3/seo": "31.
|
|
81
|
-
"@ultimat3/storage": "31.
|
|
82
|
-
"@ultimat3/testing": "31.
|
|
83
|
-
"@ultimat3/time": "31.
|
|
56
|
+
"@ultimat3/action": "31.10.0",
|
|
57
|
+
"@ultimat3/admin": "31.10.0",
|
|
58
|
+
"@ultimat3/ai": "31.10.0",
|
|
59
|
+
"@ultimat3/auth": "31.10.0",
|
|
60
|
+
"@ultimat3/cache": "31.10.0",
|
|
61
|
+
"@ultimat3/core": "31.10.0",
|
|
62
|
+
"@ultimat3/db": "31.10.0",
|
|
63
|
+
"@ultimat3/entity": "31.10.0",
|
|
64
|
+
"@ultimat3/flags": "31.10.0",
|
|
65
|
+
"@ultimat3/http": "31.10.0",
|
|
66
|
+
"@ultimat3/i18n": "31.10.0",
|
|
67
|
+
"@ultimat3/jobs": "31.10.0",
|
|
68
|
+
"@ultimat3/mail": "31.10.0",
|
|
69
|
+
"@ultimat3/manifest": "31.10.0",
|
|
70
|
+
"@ultimat3/mcp": "31.10.0",
|
|
71
|
+
"@ultimat3/money": "31.10.0",
|
|
72
|
+
"@ultimat3/notify": "31.10.0",
|
|
73
|
+
"@ultimat3/policy": "31.10.0",
|
|
74
|
+
"@ultimat3/pwa": "31.10.0",
|
|
75
|
+
"@ultimat3/query": "31.10.0",
|
|
76
|
+
"@ultimat3/realtime": "31.10.0",
|
|
77
|
+
"@ultimat3/render": "31.10.0",
|
|
78
|
+
"@ultimat3/schema": "31.10.0",
|
|
79
|
+
"@ultimat3/scraping": "31.10.0",
|
|
80
|
+
"@ultimat3/seo": "31.10.0",
|
|
81
|
+
"@ultimat3/storage": "31.10.0",
|
|
82
|
+
"@ultimat3/testing": "31.10.0",
|
|
83
|
+
"@ultimat3/time": "31.10.0",
|
|
84
84
|
"babel-preset-solid": "^1.9.16"
|
|
85
85
|
}
|
|
86
86
|
}
|
package/src/framework-schema.ts
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
SQL_ERROR_GROUPS_TABLE,
|
|
15
15
|
} from '@ultimat3/admin/schema';
|
|
16
16
|
import {
|
|
17
|
+
AUTH_LOCKOUTS_STORAGE,
|
|
17
18
|
AUTH_SERVER_TABLES,
|
|
18
19
|
AUTH_TABLE_NAMES,
|
|
19
20
|
AUTH_TABLES,
|
|
@@ -21,7 +22,7 @@ import {
|
|
|
21
22
|
SQL_AUTH_SERVER_TABLES,
|
|
22
23
|
SQL_TOTP_REPLAY_TABLE,
|
|
23
24
|
} from '@ultimat3/auth/schema';
|
|
24
|
-
import { FAILURES_TABLE, SQL_FAILURES_TABLE, type TableStorage
|
|
25
|
+
import { FAILURES_TABLE, SQL_FAILURES_TABLE, type TableStorage } from '@ultimat3/db';
|
|
25
26
|
import { RATE_LIMIT_STORAGE, SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
|
|
26
27
|
import { SQL_JOBS_TABLE } from '@ultimat3/jobs';
|
|
27
28
|
import { MCP_CONFIRMATIONS_TABLE, SQL_MCP_CONFIRMATIONS_TABLE } from '@ultimat3/mcp/schema';
|
|
@@ -114,7 +115,7 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
|
|
|
114
115
|
ddl: Object.freeze([SQL_AUTH_LIMIT_TABLES]),
|
|
115
116
|
// Stays LOGGED, stated so drift catches a hand `set unlogged`: a crash must never forget a
|
|
116
117
|
// lockout (`x_rate_limit` may, a refilled bucket is a brief free burst, never a bypass).
|
|
117
|
-
storage: Object.freeze([
|
|
118
|
+
storage: Object.freeze([AUTH_LOCKOUTS_STORAGE]),
|
|
118
119
|
}),
|
|
119
120
|
// Spent TOTP steps, so a code is single-use across the fleet rather than per replica.
|
|
120
121
|
Object.freeze({
|
package/wiki/Auth.md
CHANGED
|
@@ -43,6 +43,7 @@ login on an app that declared no `handles` is `X_CONFIG_INVALID`. The deployed d
|
|
|
43
43
|
| two expiries, independent | absolute and idle; activity never moves the absolute ceiling (`X_SESSION_EXPIRED` names which) |
|
|
44
44
|
| not a write per request | `lastSeenAt` moves at most once per `idleSlideMs` (default `idleTtlMs / 20`); a changed IP or user agent is written at once |
|
|
45
45
|
| revocation is immediate | the user row is re-read on every request, so a revoked role takes effect on the next one |
|
|
46
|
+
| one statement per request | `authenticate` reads the session and its user in one join on `postgresAuthAdapter` (was two; `As of 2026-11`, `authenticate-statements.test.ts`), through the adapter's optional `getSessionWithUser(id)` → `{ session, user \| null } \| null`. An adapter without it gets `getSession` then `findUserById`, the same answer; `authAdapterConformance` holds one that has it to exactly that answer. A slid idle window adds its one write |
|
|
46
47
|
| the cookie | `__Host-x_session`, `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/`, `Max-Age` |
|
|
47
48
|
| brute force | per-IP, per-account and per-org buckets (`X_ACCOUNT_LOCKED`); every login failure is one indistinguishable `X_UNAUTHENTICATED`. `rateLimit: { scope: 'shared' }` makes the count one for the fleet. The org bucket (`orgMaxAttempts`, default 100 per window) can be exhausted by someone who knows about 20 of an org's addresses, locking its password sign-in — kept by decision ([`SECURITY.md`](https://github.com/developerz-ai/ultimate/blob/main/SECURITY.md#known-gaps)) |
|
|
48
49
|
|
|
@@ -247,7 +248,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
|
|
|
247
248
|
| `routes` | `GET /.well-known/oauth-authorization-server` (RFC 8414), `POST /oauth/token`, `/oauth/revoke` (RFC 7009), `/oauth/introspect` (RFC 7662), plus `/oauth/register` (RFC 7591, `registration: 'dynamic'`) and `/oauth/device` (RFC 8628). Plain `Route`s for `runtime.routes`, public, no cookie authenticates them. Every answer is `no-store` RFC 6749 JSON |
|
|
248
249
|
| consent | the page calls `readRequest(url)` → `{ client, scopes, resource, redirectUri }` or a refusal; an unknown client or unregistered redirect has `redirectTo: null` — render it, never redirect. Its action calls `approve({ subject, request, scopes? })` / `deny({ request })` for the redirect URL (`code`, `state`, `iss`). A forged request is `X_AUTH_CONSENT_INVALID` (422) |
|
|
249
250
|
| device | the verification page calls `readDevice({ userCode, key })`, `approveDevice` / `denyDevice`; `key` is the caller's bucket — 10 misses lock it (`X_ACCOUNT_LOCKED`) |
|
|
250
|
-
| `registerClient(...)` | a client the app creates itself — a partner's `client_credentials` client; the secret is shown once and stored hashed |
|
|
251
|
+
| `registerClient(...)` | a client the app creates itself — a partner's `client_credentials` client; the secret is shown once and stored hashed. A redirect URI, grant, scope or resource that is empty or holds whitespace is `X_AUTH_CLIENT_INVALID` (422, `meta.field`): the store keeps each list space-joined, so it would read back as a different list |
|
|
251
252
|
| `resolve(token)` | `{ subject, scopes, clientId, resource } \| null`. `oauthBearerResolver(server, { actor, resource? })` is the `resolveToken` a bearer mount and `defineAppMcp` take; `actor` runs per call, so a removed member loses access at once |
|
|
252
253
|
| `revoke({ subject, clientId? })` · `purge({ before })` | immediate; `purge` is the app's `task` to schedule, nothing here runs on a timer |
|
|
253
254
|
|
|
@@ -260,6 +261,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
|
|
|
260
261
|
| refresh tokens only for a client whose `grantTypes` list `refresh_token`; otherwise none is issued and refreshing is `unauthorized_client` (device grant too) | `authorization-server.test.ts`, `authorization-server-postgres.test.ts` |
|
|
261
262
|
| a confidential client authenticates only with its registered `token_endpoint_auth_method`; the other is `invalid_client` | `authorization-server-clients.test.ts` |
|
|
262
263
|
| a redirect URI containing whitespace is refused at registration | `authorization-server-clients.test.ts` |
|
|
264
|
+
| `registerClient` refuses an empty or whitespace-holding list value, before a secret is minted (`X_AUTH_CLIENT_INVALID`) | `authorization-server-register-client.test.ts` |
|
|
263
265
|
| `resource` (RFC 8707) binds the grant; one not in `resources` is `invalid_target` | `authorization-server-request.test.ts`, `oauth-bearer-resolver.test.ts` |
|
|
264
266
|
| tokens are opaque and stored hashed, never a JWT, so `revoke` holds on the next lookup | `token-endpoints.test.ts` |
|
|
265
267
|
| an `https://` `client_id` is a metadata document, fetched through `outbound({ dial: 'public' })`, 5 KiB, cached 5 minutes, public clients only | `authorization-server-clients.test.ts` |
|
|
@@ -67,12 +67,67 @@ The entity name is the first argument. Everything else is the init object:
|
|
|
67
67
|
| `shared` | `'<why its rows belong to no tenant>'` — for an entity with no tenant column whose references reach one that has a tenant (a price list every org's subscriptions point at). Without it the `exercise` step reports `X_ENTITY_TENANT_UNDECLARED`; blank is refused at `entity()` with the same code, and beside a tenant column it is `X_INVARIANT_VIOLATED`. See [Policies and authz](Policies-And-Authz#the-static-tenant-check) |
|
|
68
68
|
| `scan` | `'<why it stays small>'` — a bounded table (`'a closed catalog of 8 rows'`) the `exercise` step's plan sweep may see read whole. Without it a sequential scan of it is `X_QUERY_UNINDEXED`; blank is `X_INVARIANT_VIOLATED`. See [Testing](Testing#the-plan-and-scale-sweeps) |
|
|
69
69
|
| `invariants` | `(c) => [invariant(name, expr), …]` — named predicates enforced on write, projected to a CHECK or UNIQUE constraint where expressible. `c` is typed from `columns`, so a typo is a compile error |
|
|
70
|
-
| `indexes` | composite and partial indexes; a single unique or indexed column declares it on the column instead. On a table that already exists `x db gen` builds it with `create index concurrently` by default (`As of 2026-11`), in a migration of its own, outside a transaction; `concurrently: false` is the plain build, marked `-- lock-heavy: true` ([Indexes built concurrently](Migrations-And-Backfills#indexes-built-concurrently--expand--contract)) |
|
|
70
|
+
| `indexes` | composite and partial indexes; a single unique or indexed column declares it on the column instead. On a table that already exists `x db gen` builds it with `create index concurrently` by default (`As of 2026-11`), in a migration of its own, outside a transaction; `concurrently: false` is the plain build, marked `-- lock-heavy: true` ([Indexes built concurrently](Migrations-And-Backfills#indexes-built-concurrently--expand--contract)). Key parts — `expression`, `orders`, `include`, `operatorClass` — under [Index key parts](#index-key-parts) |
|
|
71
|
+
| `version` | the optimistic-lock column, `As of 2026-11`: `update(id)` must carry it and fails `X_ENTITY_STALE` (409) when it moved. See [An optimistic lock](#an-optimistic-lock--version) |
|
|
71
72
|
| `primaryKey` | composite keys only — a single key is `.primaryKey()` on the column |
|
|
72
73
|
| `tags` | extra cache tags this entity participates in, beyond its own `entity:<name>` |
|
|
73
74
|
|
|
74
75
|
Presence of a `deletedAt` column is what makes an entity soft-deletable — not a flag.
|
|
75
76
|
|
|
77
|
+
### Index key parts
|
|
78
|
+
|
|
79
|
+
Four optional fields beside `on`, `As of 2026-11`. Each absent by default, so no existing index
|
|
80
|
+
name, schema hash or migration moves. A bad combination is `X_INVARIANT_VIOLATED` at `entity()`
|
|
81
|
+
(`declared-index-keys.ts`), never a server syntax error inside `ROLE=migrate`.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { entity, text, timestamp, uuid } from '@ultimat3/entity';
|
|
85
|
+
|
|
86
|
+
export const users = entity('users', {
|
|
87
|
+
columns: {
|
|
88
|
+
id: uuid().primaryKey(),
|
|
89
|
+
orgId: uuid().tenant(),
|
|
90
|
+
email: text(),
|
|
91
|
+
status: text(),
|
|
92
|
+
title: text(),
|
|
93
|
+
createdAt: timestamp().defaultNow(),
|
|
94
|
+
},
|
|
95
|
+
indexes: [
|
|
96
|
+
{ on: ['email'], unique: true, expression: 'lower(email)' }, // unique(lower(email))
|
|
97
|
+
{ on: ['orgId', 'createdAt'], orders: ['asc', 'desc'] },
|
|
98
|
+
{ on: ['orgId', 'status'], include: ['title'] }, // an index-only scan reads title
|
|
99
|
+
{ on: ['title'], using: 'gin', operatorClass: 'gin_trgm_ops' }, // what text `contains` needs
|
|
100
|
+
],
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
| Field | Rule |
|
|
105
|
+
|---|---|
|
|
106
|
+
| `expression` | the ONE key is this SQL, over **physical** column names; `on` names the columns it reads (the name and the covering rule read those). A unique expression index is no `upsertAll` conflict target (Postgres `42P10`), and no key for a concurrent `refreshView` (`X_JOB_REFRESH_VIEW_INVALID`) |
|
|
107
|
+
| `orders` | one direction per key, `null` writes none. btree only; never beside `order` |
|
|
108
|
+
| `include` | `INCLUDE` payload columns, the entity's own properties. btree only, never empty |
|
|
109
|
+
| `operatorClass` | `'gin_trgm_ops'` on every key; needs `using: 'gin'`. `x db gen` writes `create extension if not exists pg_trgm` in the migration that first builds one |
|
|
110
|
+
|
|
111
|
+
A column's own index (`.references()`, `.index()`, `.tenant()`) that the primary key, another
|
|
112
|
+
total btree index or a unique invariant already leads with is **still emitted**: dropping it would
|
|
113
|
+
make `x db gen` remove a live index in every existing app. It is listed on
|
|
114
|
+
`RegistryEntry.coveredIndexes` (`CoveredIndex`: `name`, `columns`, `coveredBy`), outside
|
|
115
|
+
`$describe()` so no schema hash moves. Nothing reads the list yet — a report and an opt-in drop are
|
|
116
|
+
planned.
|
|
117
|
+
|
|
118
|
+
### Substring search is `contains` on a text column
|
|
119
|
+
|
|
120
|
+
`andWhere('title', 'contains', term)` on a `text()` or `char()` column is a case-insensitive
|
|
121
|
+
substring match, `As of 2026-11`: `"title" ilike $1`, the term bound with `%`, `_` and `\` escaped
|
|
122
|
+
— a `%` typed into a search box is a percent sign. On `jsonb` and `arrayOf()` it stays `@>`
|
|
123
|
+
containment (`text-contains.ts`). Memory answers the same (both sides lower-cased; Unicode
|
|
124
|
+
`toLowerCase`, so only locale-specific folds such as Turkish dotted I can differ).
|
|
125
|
+
|
|
126
|
+
Served only by a trigram index: `indexes: [{ on: ['title'], using: 'gin', operatorClass:
|
|
127
|
+
'gin_trgm_ops' }]`. Nothing checks it at runtime; the `exercise` step's plan sweep reports a
|
|
128
|
+
sequential scan as `X_QUERY_UNINDEXED`, its fix that exact declaration (`trigramDeclaration(col)`,
|
|
129
|
+
exported). Ranked full-text search stays [`.search()`](#full-text-search--the-searchindex-port).
|
|
130
|
+
|
|
76
131
|
### Which invariants reach the database
|
|
77
132
|
|
|
78
133
|
"Where expressible" is a rule, not a hedge. An invariant reports a `sql:` string or `sql: null`, and
|
|
@@ -251,15 +306,23 @@ export async function like(postId: string): Promise<void> {
|
|
|
251
306
|
export async function nextInvoice(year: number): Promise<number> {
|
|
252
307
|
return db.invoices.lockKey(`number:${String(year)}`, async (tx) => nextNumber(year, tx));
|
|
253
308
|
}
|
|
309
|
+
|
|
310
|
+
// Both invoice series held for one renumbering, whichever order a caller names them in.
|
|
311
|
+
export async function renumber(a: number, b: number): Promise<void> {
|
|
312
|
+
await db.invoices.lockKeys([`number:${String(a)}`, `number:${String(b)}`], async (tx) => {
|
|
313
|
+
await nextNumber(a, tx);
|
|
314
|
+
await nextNumber(b, tx);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
254
317
|
```
|
|
255
318
|
|
|
256
|
-
| | `lock(id, (row, tx) => R, options?)` | `lockKey(key, (tx) => R, options?)` |
|
|
257
|
-
|
|
258
|
-
| Postgres | `select … for update`, the read path's own statement | `pg_advisory_xact_lock(hashtextextended('<table>:<tenant or ->:<key>', 0))` |
|
|
259
|
-
| Scope | that row | one key, one table, one tenant: org A's key never blocks org B |
|
|
260
|
-
| Absent, another tenant's, soft-deleted | `X_NOT_FOUND` | n/a |
|
|
261
|
-
| No actor on a scoped entity | `X_TENANCY_UNSCOPED`, as a read | `X_TENANCY_UNSCOPED`, as a read |
|
|
262
|
-
| Blank key | n/a | `X_INVARIANT` |
|
|
319
|
+
| | `lock(id, (row, tx) => R, options?)` | `lockKey(key, (tx) => R, options?)` | `lockKeys(keys, (tx) => R, options?)` |
|
|
320
|
+
|---|---|---|---|
|
|
321
|
+
| Postgres | `select … for update`, the read path's own statement | `pg_advisory_xact_lock(hashtextextended('<table>:<tenant or ->:<key>', 0))` | the same per key, every key in ONE statement, taken in sorted order — two callers naming overlapping keys in any order never deadlock |
|
|
322
|
+
| Scope | that row | one key, one table, one tenant: org A's key never blocks org B | each key as `lockKey`'s, deduplicated |
|
|
323
|
+
| Absent, another tenant's, soft-deleted | `X_NOT_FOUND` | n/a | n/a |
|
|
324
|
+
| No actor on a scoped entity | `X_TENANCY_UNSCOPED`, as a read | `X_TENANCY_UNSCOPED`, as a read | `X_TENANCY_UNSCOPED`, as a read |
|
|
325
|
+
| Blank key | n/a | `X_INVARIANT` | `X_INVARIANT`; so are an empty list and more than `MAX_LOCK_KEYS` (64) distinct keys — the fix is one coarser key |
|
|
263
326
|
|
|
264
327
|
| Rule | Detail |
|
|
265
328
|
|---|---|
|
|
@@ -267,9 +330,43 @@ export async function nextInvoice(year: number): Promise<number> {
|
|
|
267
330
|
| Writes inside `fn` | with `{ tx }`, the rule on every write. Memory undoes only what names it |
|
|
268
331
|
| Bound | no wait option. The role's `statement_timeout`. A deadlock is `X_DB_SERIALIZATION_FAILURE` |
|
|
269
332
|
| Memory driver | a queue per key, reentrant within one async chain; a nested lock joins the outer one's transaction; `update(id)` and `delete(id)` wait for a row's holder, the filtered writes and `upsertAll` do not; a waiter past 5 s is `X_DB_STATEMENT_TIMEOUT`, Postgres' code, usually two locks taken in opposite order |
|
|
270
|
-
| A hand-written `Repo` |
|
|
333
|
+
| A hand-written `Repo` | all three are optional on the contract; the handle answers `X_LOCK_UNSUPPORTED`. Memory and `defineDriver` build `lockKeys` from their one-key lock, held in the same sorted order inside one transaction (`holdInOrder`, `lock-key.ts`) |
|
|
271
334
|
| `crossTenant()` with no `orgId` | holds its own `<table>:-:<key>`, no org's. Name `orgId` to take that org's key |
|
|
272
335
|
|
|
336
|
+
### An optimistic lock — `version`
|
|
337
|
+
|
|
338
|
+
A form open for minutes cannot hold a row lock. `entity({ version })` makes a write that read a
|
|
339
|
+
stale row fail instead of overwriting it, `As of 2026-11`:
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
import { database, entity, integer, text, uuid } from '@ultimat3/entity';
|
|
343
|
+
|
|
344
|
+
const notes = entity('notes', {
|
|
345
|
+
columns: { id: uuid().primaryKey(), body: text(), lockVersion: integer().default(0) },
|
|
346
|
+
version: 'lockVersion',
|
|
347
|
+
});
|
|
348
|
+
const db = database({ notes });
|
|
349
|
+
|
|
350
|
+
// `lockVersion` is the one the editor read; it travels in the mutator's input.
|
|
351
|
+
export async function saveNote(id: string, body: string, lockVersion: number): Promise<void> {
|
|
352
|
+
await db.notes.update(id, { body, lockVersion });
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
| Write | Rule |
|
|
357
|
+
|---|---|
|
|
358
|
+
| `update(id, patch)` | the patch must name the version (else `X_ENTITY_VERSION_INVALID`, 500). The statement is conditioned on it and increments it: `where "lock_version" = $n`, `set "lock_version" = "lock_version" + 1`. Moved since the read: `X_ENTITY_STALE` (409); absent: `X_NOT_FOUND` |
|
|
359
|
+
| `updateMany(rows)` | every row names its version; one stale row refuses the whole batch, nothing written |
|
|
360
|
+
| `updateWhere` · chain `updateAll` · `transition` · soft delete | increment it on every matched row and may not set it (`X_ENTITY_VERSION_INVALID`). Compare-and-set over a filter goes in the filter: `where({ id, lockVersion: 3 }).updateAll(patch)` |
|
|
361
|
+
| `upsertAll` | `onMatch: 'update'` — the default — is refused: it would overwrite rows it never read. `onMatch: 'nothing'` is allowed |
|
|
362
|
+
| `insert`, `insertAll`, `copyAll`, hard delete | untouched; an insert takes the column default |
|
|
363
|
+
| Declaration | the column is an `integer()`, not nullable, with a `.default(n)`, neither key nor tenant column — else `X_ENTITY_VERSION_INVALID` at `entity()` |
|
|
364
|
+
|
|
365
|
+
Memory, Postgres and `defineDriver` answer alike (`entity-conformance-version-lock.ts`); a
|
|
366
|
+
`defineDriver` store gets one compare-and-set write per row. No mutator option: the version is a
|
|
367
|
+
column of the row, so the input carries it and a stale submit answers 409 through any surface
|
|
368
|
+
(`packages/action/src/mutator-version.test.ts`).
|
|
369
|
+
|
|
273
370
|
## The repo
|
|
274
371
|
|
|
275
372
|
A feature's `repo.ts` is the only module that touches the database, and every statement in it goes
|
|
@@ -310,7 +407,7 @@ export const db = database(entities, { driver });
|
|
|
310
407
|
| paging — `.limit(n)`, then `.after(cursor).page()`; a raw join pages with `keyset()` from `@ultimat3/db` ([below](#paging-a-raw-join)) | an offset, or a paging module |
|
|
311
408
|
| the transaction — inside `withTransaction` the handle is the transaction, and a statement on it after the scope ended is `X_DB_TRANSACTION_CLOSED`: `await` it, or `outsideTransaction(fn)` for work that must outlive the scope | a client argument |
|
|
312
409
|
| locks — `db.posts.lock(id, fn)` for a row, `db.posts.lockKey(key, fn)` for a key, both under the tenant | `for update` by hand, or an advisory lock |
|
|
313
|
-
| abandonment — once `ctx.signal` is aborted with a coded reason (`X_TIMEOUT`, a job's cancellation) a write rethrows that reason: a transaction rolls back and neither driver writes. A client hang-up is not a refusal. `runToCompletion(fn)` for work that must land | a check of the signal before each write |
|
|
410
|
+
| abandonment — once `ctx.signal` is aborted with a coded reason (`X_TIMEOUT`, a job's cancellation) a write rethrows that reason: a transaction rolls back and neither driver writes. A client hang-up is not a refusal. `runToCompletion(fn)` for work that must land. A pooled Postgres read in flight when `ctx.signal` aborts is cancelled on the server and throws `X_ABORTED` (`packages/db/src/statement-cancel.ts`, pinned by `pg-read-cancel.live.test.ts`); a read sent after the abort, or inside a transaction, runs — cleanup in a `finally` still reads. `As of 2026-11` | a check of the signal before each write |
|
|
314
411
|
|
|
315
412
|
| Raw `sql` | Where |
|
|
316
413
|
|---|---|
|
|
@@ -444,6 +541,7 @@ a page later.
|
|
|
444
541
|
| Shape | a `belongsTo` attaches the row or `null`; a `hasMany` attaches an array, empty when there are none. Always present, so "no author" and "nobody preloaded the author" cannot read the same |
|
|
445
542
|
| Statements | one extra statement per named relation, resolved **concurrently** — two `preload()` calls are two statements in flight, never one after the other. Naming one relation twice is one statement |
|
|
446
543
|
| Ceiling | `preload('<relation>', { max })` — the most related rows one relation may attach to one page; default 10,000 (`MAX_PRELOADED_ROWS`, the largest page a read may ask for). Past it the read is refused with `X_INVARIANT_VIOLATED`, never truncated |
|
|
544
|
+
| First n per parent | `preload('<relation>', { perParent: n, order?, direction? })`, a `hasMany` only (`As of 2026-11`): at most `n` related rows per parent — "the last 3 messages of each conversation" — in ONE `cross join lateral` statement per 500 parents, each reading `n` rows off an index, not one `limit(n)` read per parent. `order` is a column of the related entity, `direction` defaults to `desc`; unnamed, the related key descending. `perParent` on a `belongsTo`, an `order` without `perParent`, or `n` outside 1–10,000 is `X_INVARIANT_VIOLATED`. A repository without `latestBy` (hand-written, `defineDriver`) answers through paged `findMany` reads: the same rows, more statements |
|
|
447
545
|
| Terminals | `page()`, `all()`, `one()` resolve every named relation. `count()`, `countBy()` and `plan()` do not — a count reads no row to attach one to |
|
|
448
546
|
| Projection | attached after `select()`. `select()` is widened internally with the relation's own key, so a projection can drop neither the key the preload reads nor the relation it attaches — `plan().select` reports the widened list, the one that actually ran |
|
|
449
547
|
| Tenancy | the page's own tenant predicate carries onto the related read only when **both** entities are scoped by a column of that same name — a value that scopes one entity is a guess on another, and a source scoped by `workspaceId` may carry an ordinary `orgId` predicate that is a filter and not its tenancy. Carrying nothing is not silence: the related read builds its own plan, so it is refused as `X_TENANCY_UNSCOPED` rather than answered with a guess |
|
|
@@ -457,11 +555,52 @@ stated rather than inferred from a loop. The other two members of the family ask
|
|
|
457
555
|
`findById` batches a same-microtask fan-out for itself, and a `for … of` loop over a page is
|
|
458
556
|
already two statements, above.
|
|
459
557
|
|
|
558
|
+
## The newest row per group is `latestBy`
|
|
559
|
+
|
|
560
|
+
"The last message of each conversation" is one statement, not one `.orderBy().one()` per
|
|
561
|
+
conversation, `As of 2026-11`:
|
|
562
|
+
|
|
563
|
+
```ts
|
|
564
|
+
import { database, entity, timestamp, uuid } from '@ultimat3/entity';
|
|
565
|
+
|
|
566
|
+
const messages = entity('messages', {
|
|
567
|
+
columns: {
|
|
568
|
+
id: uuid().primaryKey(),
|
|
569
|
+
orgId: uuid().tenant(),
|
|
570
|
+
conversationId: uuid(),
|
|
571
|
+
createdAt: timestamp().defaultNow(),
|
|
572
|
+
},
|
|
573
|
+
});
|
|
574
|
+
const db = database({ messages });
|
|
575
|
+
|
|
576
|
+
// select distinct on ("conversation_id") … order by "conversation_id", "created_at" desc, "id" desc
|
|
577
|
+
export const lastMessages = (orgId: string, ids: readonly string[]) =>
|
|
578
|
+
db.messages
|
|
579
|
+
.where({ orgId })
|
|
580
|
+
.andWhere('conversationId', 'in', ids)
|
|
581
|
+
.latestBy('conversationId', { order: 'createdAt' });
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
| Property | Behavior |
|
|
585
|
+
|---|---|
|
|
586
|
+
| Rows | one per group the chain matches; a group with no row is absent. Ordered by the group, `null` last |
|
|
587
|
+
| Newest | `order` (required) in `direction` (default `desc`); ties go to the primary key in the same direction |
|
|
588
|
+
| Scope | the chain's filters, tenancy and soft-delete visibility, as `page()`. Sealed columns cannot be the group or the order |
|
|
589
|
+
| Bound | more than `MAX_LATEST_GROUPS` (1,000) groups is `X_INVARIANT_VIOLATED`, never truncated — the read asks for one group past the bound |
|
|
590
|
+
| Refused on the chain | `orderBy()`, `limit()`, `after()`: one row per group is the whole shape, and it has no cursor (`X_INVARIANT_VIOLATED`) |
|
|
591
|
+
| Cost | `DISTINCT ON` reads every row of the matched groups, then keeps one each. Bound the groups with `andWhere(group, 'in', …)`; for a few rows per parent over long histories, `preload(rel, { perParent })` reads `n` per key off an index |
|
|
592
|
+
| Drivers | Postgres and memory in one pass each (`pg-latest-by.ts`, `memory-latest-by.ts`). `Repo.latestBy` is optional: a hand-written repository or a `defineDriver` store is answered by paged `findMany` reads folded in process (`latestRows`, `latest-by.ts`) — correct, never one statement |
|
|
593
|
+
|
|
460
594
|
## Reading a whole table is a loop of pages
|
|
461
595
|
|
|
462
596
|
A page is bounded on purpose, so reading everything is iteration — and the iteration is a terminal
|
|
463
597
|
on the same chain, not something written around `page()`, `As of 2026-08`:
|
|
464
598
|
|
|
599
|
+
`.all()` is that one page too — 50 rows unless the chain says `.limit(n)`. When a next page existed
|
|
600
|
+
and the chain named no limit, a development or test process logs one warning, `entity.all.truncated`
|
|
601
|
+
(`ALL_TRUNCATED`), naming the entity and both ways out: `.inBatches(n)` for every row, `.limit(n)`
|
|
602
|
+
for one page meant. Staging and production say nothing; refusing is a break, and waits for a major.
|
|
603
|
+
|
|
465
604
|
```ts
|
|
466
605
|
// One statement per batch, one page of rows in memory at a time.
|
|
467
606
|
for await (const batch of db.posts.where({ orgId }).preload('author').inBatches(500)) {
|
|
@@ -494,6 +633,21 @@ await db.checkpoints.update(id, { cursor: batches.cursor }); // resume with .a
|
|
|
494
633
|
| Unsortable kinds | `orderBy` on a `json`, `bytes` or array column is refused at plan time, at any row count (`X_INVARIANT_VIOLATED`). It paged wrongly or threw past page 1. Order by a scalar |
|
|
495
634
|
| Patches | `update`, `updateWhere` validate named columns, with `insert`'s issues, before the statement, on both drivers. Absent stays absent, `null` clears a nullable column |
|
|
496
635
|
| Tenancy | the plan's, as everywhere else: an unscoped chain is `X_TENANCY_UNSCOPED` on its first batch |
|
|
636
|
+
| Heavy rows | a batch past the [page byte bound](#a-page-is-bounded-in-bytes) is re-read from the same cursor at half the rows, down to one, and the smaller size is kept for the batches after it (`batch-bytes.ts`): a sweep over heavy rows finishes. At most `⌈log2(size)⌉` refused statements per batch; one row over the bound on its own is still `X_ENTITY_PAGE_TOO_LARGE`. `As of 2026-11` |
|
|
637
|
+
|
|
638
|
+
### A page is bounded in bytes
|
|
639
|
+
|
|
640
|
+
`MAX_PAGE_SIZE` bounds rows; `MAX_PAGE_BYTES` (64 MiB, exported) bounds what they weigh, measured on
|
|
641
|
+
the raw rows before one is decoded. Past it the read is `X_ENTITY_PAGE_TOO_LARGE` (500), never a
|
|
642
|
+
truncated page. `As of 2026-11`:
|
|
643
|
+
|
|
644
|
+
| Property | Behavior |
|
|
645
|
+
|---|---|
|
|
646
|
+
| Where | every `findMany`: `page()`, `all()`, `one()`, a batch. Postgres weighs the page it answered (`pg-driver.ts`), memory and a `defineDriver` store the projected page — so a test against memory refuses the page production would |
|
|
647
|
+
| Weight | a string by its length, binary by `byteLength`, 8 per scalar or `Date`, a parsed `jsonb` walked; counting stops at the bound |
|
|
648
|
+
| The `fix:` | names the heaviest column and pastes onto the read: `.select({ id: true, title: true }).limit(n)` — every column but that one, and the row count that fits |
|
|
649
|
+
| A constant | no per-call or per-driver option. As of 2026-11 the heaviest page in both tracked apps' suites is 16,560 B (120 `users` rows), about 4,000× under the bound |
|
|
650
|
+
| Cost | as of 2026-11, Bun 1.4.4: 3–4 µs per 51-row page of flat columns, 11–12 µs with a small `jsonb` per row |
|
|
497
651
|
|
|
498
652
|
## A count per row is one grouped count
|
|
499
653
|
|
|
@@ -524,6 +678,45 @@ a `number | undefined` — and the `undefined` is load-bearing.
|
|
|
524
678
|
There is no `groupBy()` builder and no error code of its own: `countBy` is a terminal on the chain
|
|
525
679
|
that already exists, over exactly the rows `count()` counts.
|
|
526
680
|
|
|
681
|
+
### A filtered count and several measures, one statement
|
|
682
|
+
|
|
683
|
+
`countBy(column, { where })` counts only the rows that satisfy `where` in each group, and
|
|
684
|
+
`aggregate({ name: measure })` answers several measures at once, each with its own filter —
|
|
685
|
+
`count(*) filter (where …)`, `As of 2026-11`:
|
|
686
|
+
|
|
687
|
+
```ts
|
|
688
|
+
import { database, entity, money, text, uuid } from '@ultimat3/entity';
|
|
689
|
+
|
|
690
|
+
const posts = entity('posts', {
|
|
691
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), authorId: uuid(), status: text() },
|
|
692
|
+
});
|
|
693
|
+
const orders = entity('orders', {
|
|
694
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), status: text(), total: money() },
|
|
695
|
+
});
|
|
696
|
+
const db = database({ posts, orders });
|
|
697
|
+
|
|
698
|
+
// Every author the chain matched, with 0 for one who has published nothing.
|
|
699
|
+
export const publishedPerAuthor = (orgId: string) =>
|
|
700
|
+
db.posts.where({ orgId }).countBy('authorId', { where: [['status', 'eq', 'published']] });
|
|
701
|
+
|
|
702
|
+
// { all: number, paid: number, revenue: MoneyValue | null } in one statement.
|
|
703
|
+
export const orderTile = (orgId: string) =>
|
|
704
|
+
db.orders.where({ orgId }).aggregate({
|
|
705
|
+
all: { fn: 'count' },
|
|
706
|
+
paid: { fn: 'count', where: [['status', 'eq', 'paid']] },
|
|
707
|
+
revenue: { fn: 'sum', column: 'total', where: [['status', 'eq', 'paid']] },
|
|
708
|
+
});
|
|
709
|
+
```
|
|
710
|
+
|
|
711
|
+
| Property | Behavior |
|
|
712
|
+
|---|---|
|
|
713
|
+
| `where` | `andWhere`'s three arguments as a tuple, per filter; narrows that measure only, inside the rows the chain matched (filters, tenancy, soft delete) |
|
|
714
|
+
| `countBy` with `where` | a group the chain matched but no row satisfies is present with `0` — what tells it from `andWhere(…).countBy(col)`, where it is absent |
|
|
715
|
+
| Measures | `fn` is `'count'` (no `column`: `count(*)`; with one, its non-null values), `'sum'`, `'avg'`, `'min'`, `'max'`. At most `MAX_MEASURES` (32) |
|
|
716
|
+
| Answers | a `count` a number, `0` over no rows; the rest exactly what `sum()`/`avg()`/`min()`/`max()` answer — decimal text, money a `MoneyValue`, `null` over no rows. Never a float |
|
|
717
|
+
| Refused | before any row is read, `X_AGGREGATE_UNSUPPORTED`: an unknown function, an undeclared column or filter column, a kind with no aggregate, `avg` over money, no measures or more than 32. Two currencies under one money `sum`: `X_AGGREGATE_MIXED_CURRENCY` |
|
|
718
|
+
| Drivers | one statement on Postgres and memory. A `defineDriver` store composes both from the capabilities it already declares (`aggregate:countBy`, `aggregate:<fn>`): several store calls, the same answer. A hand-written `Repo` without `aggregates` answers `aggregate()` with `X_AGGREGATE_UNSUPPORTED` |
|
|
719
|
+
|
|
527
720
|
## A count per day is a series
|
|
528
721
|
|
|
529
722
|
A chart is a count per bucket of time, in a person's zone. One statement, under every guard the
|
|
@@ -594,8 +787,122 @@ already stored is skipped and absent, which is how a caller counts what it actua
|
|
|
594
787
|
| Nulls | a null in the conflict target collides with nothing, in both drivers — a Postgres unique index is `NULLS DISTINCT` |
|
|
595
788
|
| Size | past 65535 bind parameters the batch is several statements inside one transaction (a savepoint inside an open `withTransaction`), never one the server refuses. A failure in any chunk leaves no row of the batch, in both drivers; one chunk stays one autocommit statement, no `BEGIN`. Partial progress is yours to ask for: split the batch and call once per part |
|
|
596
789
|
|
|
597
|
-
|
|
598
|
-
|
|
790
|
+
### A count instead of the rows
|
|
791
|
+
|
|
792
|
+
`{ returning: false }` on `insertAll` or `upsertAll` resolves with how many rows were written: no
|
|
793
|
+
`returning *`, nothing decoded. The same chunks, judging and atomicity as the returning form.
|
|
794
|
+
`As of 2026-11`:
|
|
795
|
+
|
|
796
|
+
```ts
|
|
797
|
+
import { database, entity, integer, text, uuid } from '@ultimat3/entity';
|
|
798
|
+
|
|
799
|
+
const events = entity('events', {
|
|
800
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), name: text({ max: 80 }) },
|
|
801
|
+
});
|
|
802
|
+
const counters = entity('counters', {
|
|
803
|
+
columns: {
|
|
804
|
+
id: uuid().primaryKey(),
|
|
805
|
+
orgId: uuid().tenant(),
|
|
806
|
+
day: text({ max: 10 }),
|
|
807
|
+
total: integer(),
|
|
808
|
+
},
|
|
809
|
+
indexes: [{ on: ['orgId', 'day'], unique: true }],
|
|
810
|
+
});
|
|
811
|
+
const db = database({ events, counters });
|
|
812
|
+
|
|
813
|
+
export const record = async (orgId: string, names: readonly string[]): Promise<number> =>
|
|
814
|
+
db.events.insertAll(
|
|
815
|
+
names.map((name) => ({ orgId, name })),
|
|
816
|
+
{ returning: false },
|
|
817
|
+
);
|
|
818
|
+
|
|
819
|
+
export const tally = async (orgId: string, days: readonly string[]): Promise<number> =>
|
|
820
|
+
db.counters.upsertAll(
|
|
821
|
+
days.map((day) => ({ orgId, day, total: 1 })),
|
|
822
|
+
{ onConflict: ['orgId', 'day'], returning: false },
|
|
823
|
+
);
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
While an external search index or an `entity.row` subscriber needs the rows, the count form runs as
|
|
827
|
+
its returning counterpart and still resolves with the count.
|
|
828
|
+
|
|
829
|
+
### A bulk load is `copyAll`
|
|
830
|
+
|
|
831
|
+
`db.<table>.copyAll(rows)` sends one `COPY … FROM STDIN`: all or nothing, resolves with the count.
|
|
832
|
+
Rows are parsed, sealed, tenant-checked and judged exactly as `insertAll` judges them. `As of 2026-11`:
|
|
833
|
+
|
|
834
|
+
| Property | Behavior |
|
|
835
|
+
|---|---|
|
|
836
|
+
| Columns | every row names the same columns, else `X_INVARIANT_VIOLATED`: COPY has one column list and no per-row `default` cell. Refused on every driver |
|
|
837
|
+
| Collisions | none handled: a duplicate refuses the whole load. `upsertAll` is the call that tolerates one |
|
|
838
|
+
| Where it is COPY | `postgresDriver()`, on a client with `copyIn` (`canCopyIn`, `@ultimat3/db`). Inside `withTransaction` it is that transaction's; under the replica router, the primary's |
|
|
839
|
+
| Where it is `insertAll` | memory, a `defineDriver` store, row-security settings installed (a copy would skip the tenant `BEGIN`), a client with no `copyIn` — insert statements, no `returning`. While a search index or an `entity.row` subscriber listens: `insert … returning *` |
|
|
840
|
+
| Measured | as of 2026-11, 100k rows × 4 columns through the typed handle, Postgres 17 on loopback, Bun 1.4.4, median of 5 at load 13–15: `copyAll` 1,073 ms, `insertAll({ returning: false })` 2,778 ms, `insertAll` 2,880 ms |
|
|
841
|
+
|
|
842
|
+
### A filtered write is a chain terminal
|
|
843
|
+
|
|
844
|
+
`.updateAll(patch)` and `.deleteAll()` end any read chain: one statement over exactly the rows the
|
|
845
|
+
same chain's `.all()` would read, every operator included. `As of 2026-11`:
|
|
846
|
+
|
|
847
|
+
```ts
|
|
848
|
+
import { database, entity, enumerated, timestamp, uuid } from '@ultimat3/entity';
|
|
849
|
+
|
|
850
|
+
const likes = entity('likes', {
|
|
851
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), postId: uuid(), userId: uuid() },
|
|
852
|
+
});
|
|
853
|
+
const posts = entity('posts', {
|
|
854
|
+
columns: {
|
|
855
|
+
id: uuid().primaryKey(),
|
|
856
|
+
orgId: uuid().tenant(),
|
|
857
|
+
authorId: uuid(),
|
|
858
|
+
status: enumerated(['draft', 'live']),
|
|
859
|
+
publishedAt: timestamp().nullable(),
|
|
860
|
+
},
|
|
861
|
+
});
|
|
862
|
+
const db = database({ likes, posts });
|
|
863
|
+
|
|
864
|
+
// One statement each; resolves with how many rows it reached.
|
|
865
|
+
export const unlike = (postId: string, userIds: readonly string[]): Promise<number> =>
|
|
866
|
+
db.likes.where({ postId }).andWhere('userId', 'in', userIds).deleteAll();
|
|
867
|
+
|
|
868
|
+
export const parkUnpublished = (authorId: string): Promise<number> =>
|
|
869
|
+
db.posts.where({ authorId }).andWhere('publishedAt', 'is-null').updateAll({ status: 'draft' });
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
| Property | Behavior |
|
|
873
|
+
|---|---|
|
|
874
|
+
| One plan | `updateWhere(filter, patch)` / `deleteWhere(filter)` and the chain build the same plan (`write-where.ts`): tenancy, soft-delete reach, invariant judging, `onUpdateNow()`, sealing, the search mirror and the `entity.bulk` report cannot differ. The filter is the chain's equalities |
|
|
875
|
+
| Unbounded | no predicate is `X_WRITE_UNFILTERED`. So is a chain predicate whose value is `undefined` — dropped, it would widen the write to everything the rest of the chain matches; `.andWhere('<col>', 'is-null')` is SQL NULL. In `updateWhere`'s filter an `undefined` is dropped, as it always was |
|
|
876
|
+
| No page | `limit()`, `after()` and `search()` on a write chain are `X_INVARIANT_VIOLATED`: a write reaches every match, and a search index answers a bounded sample of ids. `orderBy`, `select` and `preload` are ignored |
|
|
877
|
+
| Sealed columns | a lookup column matched as a read matches it; a null test passes; any other predicate on a sealed column is refused |
|
|
878
|
+
|
|
879
|
+
### A different value per row is `updateMany`
|
|
880
|
+
|
|
881
|
+
`db.<table>.updateMany([{ id, patch }])` writes each row its own patch: one tenant-scoped
|
|
882
|
+
`update … from (select …)` per bind-count chunk, resolving with how many rows were written.
|
|
883
|
+
A chunk is ⌊(65,535 − the scope's binds) / (columns + 1)⌋ rows, so 1,000 one-column patches are one statement (`pg-update-many-sql.test.ts`). `As of 2026-11`:
|
|
884
|
+
|
|
885
|
+
```ts
|
|
886
|
+
import { database, entity, integer, uuid } from '@ultimat3/entity';
|
|
887
|
+
|
|
888
|
+
const posts = entity('posts', {
|
|
889
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), rank: integer() },
|
|
890
|
+
});
|
|
891
|
+
const db = database({ posts });
|
|
892
|
+
|
|
893
|
+
// Each row its own rank, one statement: resolves with how many rows were written.
|
|
894
|
+
export const rerank = (ranked: readonly { id: string; rank: number }[]): Promise<number> =>
|
|
895
|
+
db.posts.updateMany(ranked.map(({ id, rank }) => ({ id, patch: { rank } })));
|
|
896
|
+
```
|
|
897
|
+
|
|
898
|
+
| Property | Behavior |
|
|
899
|
+
|---|---|
|
|
900
|
+
| Shape | every patch names the same columns, each id appears once, a single-column primary key: else `X_INVARIANT_VIOLATED`. An empty patch is `X_PATCH_EMPTY` |
|
|
901
|
+
| Missing rows | an absent, soft-deleted or other tenant's id is neither written nor counted, never `X_NOT_FOUND` — `updateWhere`'s semantics |
|
|
902
|
+
| Atomicity | on Postgres one chunk is one autocommit statement; several chunks, or a JS-only invariant, run in one transaction. Memory and a `defineDriver` store judge the batch whole (tenant, invariants, uniques) before a row lands; a `defineDriver` store gets one `update` per row, and a store refusal part way writes the moved rows back |
|
|
903
|
+
| Typing | the source rows are typed from the table (`select … where false union all select $…`): `values (…)` binds as text and Postgres refuses `uuid = text` |
|
|
904
|
+
| Reports | `entity.bulk`, as `updateWhere` |
|
|
905
|
+
| A hand-written `Repo` | `updateMany`, `copyAll`, `insertAllCount` and `upsertAllCount` are optional on it. Absent, the typed handle sends one `updateWhere` per row, and `insertAll(…)` / `upsertAll(…)` counted |
|
|
599
906
|
|
|
600
907
|
The composite unique index the tenancy rule requires is emitted correctly since 2.0.0 — declare it
|
|
601
908
|
on the entity and generate. Through 1.2.0 `indexes: [{ on: ['orgId','createdAt'] }]` emitted one
|
|
@@ -889,7 +1196,7 @@ Rule: `.search(term)` on a chain asks the INSTALLED `SearchIndex` — one search
|
|
|
889
1196
|
|---|---|
|
|
890
1197
|
| the version | every `SearchDocument` carries `version`, the row's `onUpdateNow()` instant in epoch ms — STRICTLY increasing per row: a write (a soft delete included) stores it no earlier than the stored one + 1 ms (Postgres `greatest($now, updated_at + interval '1 millisecond')`; the memory driver and a `defineDriver` store through `advanceVersion` / `DriverRepo.update`'s `advance`), so two writes inside one millisecond are two versions and the column may run a millisecond ahead of the clock per same-ms write. A searchable entity declares `updatedAt: timestamp().defaultNow().onUpdateNow()`; without one `searchDocumentOf` and `reindex()` refuse (`X_INVARIANT_VIOLATED`) |
|
|
891
1198
|
| keep only newer | an adapter applies a document only when its version is newer than the document or tombstone it holds for that id; `remove(scope, ids, version)` leaves a tombstone (a delete's: past the row's last version and no earlier than its instant); an equal version is a replay. EXCEPT a `committed` document — the write path's, `index(docs, { committed: true })` — which replaces a tombstone whatever its version, so a key deleted and written again is live at once; `reindex()`'s reads are not `committed`, so a stale read never brings a deleted row back. `searchIndexConformance` (`@ultimat3/testing/conformance`) checks each case |
|
|
892
|
-
| the write path | with an external index installed, every committed write of a searchable entity reaches it: insert, upsert, update, transition and `
|
|
1199
|
+
| the write path | with an external index installed, every committed write of a searchable entity reaches it: insert, upsert, `copyAll`, update, transition, `updateWhere`/`updateAll` and `updateMany` index the rows written; `delete` and `deleteWhere`/`deleteAll` (soft or hard) remove them — whatever the primary key (`id`, another column, composite; an instant in a key is spelled ISO 8601 UTC). Taken when the write runs, merged per key per transaction, sent at commit on one chain per index (`search-mirror-batch.ts`), so a rolled-back write indexes nothing. The driver hands a delete's or filtered write's rows over (`returning *` on Postgres) only for a searchable entity under an external index; under the built-in index every write is the statement it always was |
|
|
893
1200
|
| a failed index write | never fails the business write: one `entity.search-index.write-failed` log line; repair with `reindex()` ([Jobs](Jobs-And-Workflows#rebuilding-a-search-index--reindex)), whose sweep also removes what the table lost |
|
|
894
1201
|
| not mirrored | 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) — logged the same way; `reindex()` repairs it |
|
|
895
1202
|
|
|
@@ -939,10 +1246,11 @@ export const likes = entity('likes', {
|
|
|
939
1246
|
```
|
|
940
1247
|
|
|
941
1248
|
- **Retention is a promise `x verify` checks.** A `retain` no `purge()` covers is `X_ENTITY_RETAIN_UNSWEPT` in the `manifest` step. `purge({ entities: 'declared' })` covers every one, history tables included, and needs no line per entity.
|
|
942
|
-
- **History is recorded by trigger**, so `updateWhere`, a cascade and raw SQL are recorded too. An update that changes nothing records nothing; a change to a counted column, or to columns `history: { ignore }` names, alone records nothing — on both drivers (`history-ignore.test.ts`). `ignore` takes the entity's own columns, typed; another name is `X_INVARIANT_VIOLATED`. Declaring it changes the trigger's arguments, so `x db gen` writes the migration that reinstalls it. `.sealed()` columns stay ciphertext in the images. `actor_id`/`request_id` are what the WRITE'S transaction set (`x.actor`, `x.request`): the repository sets them before its first write to a history entity inside a transaction; an autocommit write records `null`, never a guess. Update of a history row is refused always; delete only under `x.purge` naming that table, which the retention sweep
|
|
1249
|
+
- **History is recorded by trigger**, so `updateWhere`, a cascade and raw SQL are recorded too. An update that changes nothing records nothing; a change to a counted column, or to columns `history: { ignore }` names, alone records nothing — on both drivers (`history-ignore.test.ts`). `ignore` takes the entity's own columns, typed; another name is `X_INVARIANT_VIOLATED`. Declaring it changes the trigger's arguments, so `x db gen` writes the migration that reinstalls it. `.sealed()` columns stay ciphertext in the images. `actor_id`/`request_id` are what the WRITE'S transaction set (`x.actor`, `x.request`): the repository sets them before its first write to a history entity inside a transaction; an autocommit write records `null`, never a guess. Update of a history row is refused always; delete only under `x.purge` naming that table, which the retention sweep and a subject erase set (`X_ENTITY_APPEND_ONLY`, SQLSTATE `23001`). Reading it is an ordinary, tenant-scoped, cursor-paged read: `database({ posts, postsHistory: posts.$history })`.
|
|
943
1250
|
- **One row's history is `history(db.postsHistory, id)`**: every version, oldest first, each numbered `version` from 1 — ordered by chaining each `before` onto the previous `after` across every version, `at` only breaking ties: `at` is the transaction's START, so a transaction that began first and committed last carries the earlier `at` and the later image. `history(table, id, { limit: n })` reads the `n` versions with the latest `at` (ties at the edge kept), numbered as the whole history numbers them — chosen by transaction start, so a transaction that began before that window and committed inside it can fall outside. The read is the history table's, so another tenant's row reads back `[]`; the policy is the query or action that calls it. `version` counts what is retained: after a `retain` sweep, 1 is the oldest kept. As of 31.3.
|
|
944
1251
|
- **A counter locks its parent row.** A hot parent serializes its writers; where that matters, `countBy` plus a cache is the alternative. A soft-deleted child is not counted. A new counter's migration recounts once, so an existing table starts true; `x db recount posts.likeCount` reports drift and `--write` repairs it.
|
|
945
|
-
- **A counter's write is
|
|
1252
|
+
- **A counter's write is reported as the parent's change.** The WAL replicator sees the trigger's write; the in-process `entity.row` event (what `x dev` on PGlite and the memory driver feed live queries from) reports it too: after a child write, while `entity.row` has a subscriber, the parents whose count moved are read back in the write's transaction and each is an `update` at COMMIT, `before` the row with the count moved back. A filtered write (`deleteWhere`, `updateWhere`, a chain's `deleteAll`/`updateAll`) pinned to one parent by its key reports that row with `before: null`; one spanning parents is `entity.bulk` for the parent table. With no subscriber, nothing is read. So a live count needs no recount in the mutator (`counter-observed.test.ts`). As of 2026-11.
|
|
1253
|
+
- **An erase reaches history.** A parent `subjectErase()` deletes or anonymizes writes the person into a before image, so its `<table>_history` needs a line in `defineSubject({ tables })`: `'delete'` removes every image of those rows in the parent's own transaction — under `x.purge` on Postgres, under `purgingHistory(table, work)` in memory, the one delete each lets through — `{ retain: '<why>' }` keeps them, `anonymize` is refused. An undeclared one is `X_SUBJECT_TABLE_UNDECLARED`, an `anonymize` `X_SUBJECT_TREATMENT_INVALID`; images written before an upgrade are reached only by the next erase of that subject ([Jobs and workflows](Jobs-And-Workflows#one-persons-data--subjectexport-and-subjecterase)). As of 2026-11.
|
|
946
1254
|
- **Memory answers as Postgres does**: the memory driver records history and moves counters in its repository (`counter.test.ts`, `history.test.ts` are the parity tables).
|
|
947
1255
|
- Drift names a missing or disabled lifecycle trigger: `X_LIFECYCLE_TRIGGER_MISSING`, its fix the statements that re-create it.
|
|
948
1256
|
|
|
@@ -998,7 +1306,7 @@ of 2026-11:
|
|
|
998
1306
|
|
|
999
1307
|
| Rule | |
|
|
1000
1308
|
|---|---|
|
|
1001
|
-
| Writes | `insert`, `insertAll`, `upsertAll`, `update`, `delete`, `updateWhere`, `deleteWhere`, `lock`: `X_ENTITY_READ_ONLY`, in both drivers, before a statement exists, the reason in the cause |
|
|
1309
|
+
| Writes | `insert`, `insertAll`, `upsertAll`, `copyAll`, `update`, `delete`, `updateWhere`, `deleteWhere`, `updateMany`, a chain's `updateAll`/`deleteAll`, `lock`: `X_ENTITY_READ_ONLY`, in both drivers, before a statement exists, the reason in the cause |
|
|
1002
1310
|
| Refused at declaration | a blank reason, `view` (already read-only), `appendOnly` (it admits the inserts this refuses): `X_INVARIANT_VIOLATED` |
|
|
1003
1311
|
| Seeds | `x db seed --generate` and `x exercise` seed no row of it. A nullable reference into it is seeded null; a NOT NULL one is `X_SEED_GRAPH_UNSATISFIED` naming the table, its reason, and the fix: `readOnly` on the referencing table too, or `.nullable()` then `x db gen` |
|
|
1004
1312
|
| Subjects | `defineSubject`'s `'delete'` or `anonymize` on it is `X_SUBJECT_TREATMENT_INVALID`; `retain` is the one treatment that holds |
|
|
@@ -1033,7 +1341,10 @@ A store that is not Postgres — Mongo, Cassandra, a key-value store — is a `D
|
|
|
1033
1341
|
An undeclared capability (`upsert`, `matches`, `aggregate:<kind>`, `transactions`) is
|
|
1034
1342
|
`X_DRIVER_UNSUPPORTED` with `meta.capability`; a declared one with no method behind it is
|
|
1035
1343
|
`X_DRIVER_CAPABILITY_MISSING` when the table opens. `lock` and `series` undeclared answer the
|
|
1036
|
-
shipped `X_LOCK_UNSUPPORTED` / `X_ENTITY_SERIES_UNSUPPORTED`.
|
|
1344
|
+
shipped `X_LOCK_UNSUPPORTED` / `X_ENTITY_SERIES_UNSUPPORTED`. A child entity whose column declares
|
|
1345
|
+
`countedIn` is refused when `database()` builds its repository (`X_DRIVER_UNSUPPORTED`,
|
|
1346
|
+
`meta.capability: 'countedIn'`, `driver-counters.ts`): a custom store has no trigger and no
|
|
1347
|
+
repository hook, so the parent's count would never move. `As of 2026-11`.
|
|
1037
1348
|
|
|
1038
1349
|
A searchable entity's version is strictly increasing per row, and a custom store advances it in
|
|
1039
1350
|
its OWN write, atomically: `update(filter, patch, advance?)` writes `advance.property` per matched
|
|
@@ -514,6 +514,8 @@ export const exportMember = subjectExport({
|
|
|
514
514
|
| children first, the subject last; one step per page of parent keys | a killed run resumes at the page it stopped on; every write is an equality on one key, so a replay changes nothing twice |
|
|
515
515
|
| a loop of deleted tables needs one nullable key | it is cleared first; none is `X_SUBJECT_CYCLE` |
|
|
516
516
|
| a table with no foreign key to the person is invisible | list it: `columns: { audit_copies: 'memberId' }`, then it needs a treatment too |
|
|
517
|
+
| a deleted or anonymized table's `<table>_history` is reached too (`As of 2026-11`) | the write records the person in one more before image, and `row_id` is no foreign key. `'delete'` removes every history row whose `before` or `after` image names the subject (`@>` on the parent's key column, tenant-scoped — so a row deleted, soft-deleted or inserted before the erase is reached too) in the parent's own step and transaction, after the write — the one delete the append-only guard lets through (`x.purge` on Postgres, `purgingHistory` in memory); `{ retain: '<why>' }` keeps and counts the same rows; `anonymize` is `X_SUBJECT_TREATMENT_INVALID`, undeclared `X_SUBJECT_TABLE_UNDECLARED`. |
|
|
518
|
+
| a deleted table's own delete purges the images Postgres writes into a child's history (`As of 2026-11`) | `on delete set null` or `cascade` rewrites a child row, and the child's trigger records the person's key in its before image. A child history declared `'delete'` loses those images in the parent's step and transaction (`orphansOf`, `packages/jobs/src/subject-plan.ts:341`; `packages/jobs/src/subject-erase-history.ts`). Limits: the memory driver applies no `onDelete` action, so a kept child keeps the erased key there; a child history declared `{ retain }` is counted only for writes to its own table — the images a set-null or cascade write records into it are neither purged nor counted |
|
|
517
519
|
| framework data is a `targets:` entry | `authSubjectTarget` (`@ultimat3/auth`), `auditSubjectTarget` (`@ultimat3/action`, rewrites who acted, keeps the row), `storageSubjectTarget(disk, keysOf)` (`@ultimat3/storage`); `{ target, retain }` keeps one |
|
|
518
520
|
| the export is one object per page per table plus `index.json` | each table's count, treatment and `retain` reason; sealed columns never leave |
|
|
519
521
|
| one job per tenant | crossing tenants is the app's loop; queued job inputs and logs are out of reach (`x_jobs` ages out by `jobs-retention.ts`) |
|
|
@@ -599,7 +601,7 @@ export const refreshPostTotals = refreshView({
|
|
|
599
601
|
| `refreshView()` | |
|
|
600
602
|
|---|---|
|
|
601
603
|
| Each run | `refresh materialized view [concurrently]` in one step; `tenant: 'none'` — the read path scopes the rows |
|
|
602
|
-
| `concurrently` | readers keep the old rows meanwhile; needs a unique index on the view (`.unique()`) |
|
|
604
|
+
| `concurrently` | readers keep the old rows meanwhile; needs a unique index on the view (`.unique()`) over plain columns, with no `where` — a unique `expression` index is no key for it (`As of 2026-11`) |
|
|
603
605
|
| Refused at declaration | a table, a plain view, `concurrently` with no unique index — `X_JOB_REFRESH_VIEW_INVALID` |
|
|
604
606
|
|
|
605
607
|
## Rebuilding a search index — `reindex()`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Policies and authz
|
|
2
2
|
|
|
3
|
-
One authz system. Authentication is
|
|
3
|
+
One authz system. Authentication is `@ultimat3/auth` ([Auth](Auth)); **authorization is this page**, because it must be identical in HTTP, WebSocket, jobs, and MCP.
|
|
4
4
|
|
|
5
5
|
```ts
|
|
6
6
|
policy: can('post:publish', ({ input, actor }) => ownsPost(actor, input.postId))
|
|
@@ -116,6 +116,48 @@ The matrix runs **outside a request**: no input, no row. A rule that reads eithe
|
|
|
116
116
|
|
|
117
117
|
`x policy list` also names the permissions **no** action or query enforces. A grant nothing checks is a grant that does nothing, and it is invisible from any single declaration.
|
|
118
118
|
|
|
119
|
+
## Scope — a policy's database filter
|
|
120
|
+
|
|
121
|
+
`scoped(policy, scope)` attaches `scope(actor) → where` to a policy, `As of 2026-11`: the
|
|
122
|
+
conjunction a read hands the database, so the visible rows arrive as one index-served page rather
|
|
123
|
+
than a JS filter over an over-fetch that leaves a viewer a short page. The policy decides exactly as
|
|
124
|
+
before; the JS rule stays the authority.
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import type { Actor, Policy } from '@ultimat3/policy';
|
|
128
|
+
import { policyScope, scoped } from '@ultimat3/policy';
|
|
129
|
+
|
|
130
|
+
interface Post {
|
|
131
|
+
readonly orgId: string;
|
|
132
|
+
readonly audience: 'public' | 'members';
|
|
133
|
+
}
|
|
134
|
+
declare const postRule: Policy<unknown, Post>;
|
|
135
|
+
declare const actor: Actor | null;
|
|
136
|
+
|
|
137
|
+
export const seePost = scoped(postRule, (who) =>
|
|
138
|
+
who === null
|
|
139
|
+
? [{ column: 'audience', op: 'eq', value: 'public' }]
|
|
140
|
+
: [{ column: 'orgId', op: 'eq', value: who.orgId }],
|
|
141
|
+
);
|
|
142
|
+
policyScope(seePost, actor); // the frozen conditions, or undefined for an unscoped policy
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
| `policyScope(policy, actor)` answers | Means |
|
|
146
|
+
|---|---|
|
|
147
|
+
| `undefined` | no scope declared: nothing is handed down |
|
|
148
|
+
| `[]` | every row (an admin): the empty conjunction |
|
|
149
|
+
| `[{ column, op, value? }, …]` | every condition must hold — AND only, there is no `or`. `column` is typed by the policy's row; `op` is one of `eq` `neq` `in` `gt` `gte` `lt` `lte` `is-null` `is-not-null`; `value` is always bound |
|
|
150
|
+
|
|
151
|
+
- **The scope belongs to the clause it is declared on.** `and`/`or`/`not` over a scoped policy
|
|
152
|
+
carry none: the conjunction of children's scopes is not the scope of `or`. Scope the outermost
|
|
153
|
+
policy.
|
|
154
|
+
- **Tenant scoping is not scope.** Tenancy stays the entity layer's (the tenant predicate every
|
|
155
|
+
repository applies, [below](#tenancy)); a scope narrows what one actor sees inside a tenant and
|
|
156
|
+
never replaces it.
|
|
157
|
+
- **Planned, not shipped:** composing a scope into `@ultimat3/query` reads, and a finding for a
|
|
158
|
+
scope that admits other rows than its rule on the exercise seed. Until then `policyScope` is the
|
|
159
|
+
read an app composes itself, e.g. `db.posts.where({ orgId })` plus each condition as `andWhere`.
|
|
160
|
+
|
|
119
161
|
## Tenancy
|
|
120
162
|
|
|
121
163
|
Authz and tenancy are separate checks, both mandatory.
|
package/wiki/Upgrading.md
CHANGED
|
@@ -224,10 +224,21 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
|
|
|
224
224
|
| `.search()` through a non-Postgres search index answers `X_INVARIANT_VIOLATED` when a term matches 10,000 or more rows (**31.7.0**); before, it silently counted and paged only the first 10,000 | narrow the term, or `installSearchIndex(postgresSearchIndex())` |
|
|
225
225
|
| a multipart part URL on a local or memory disk signs its exact length (**31.8.0**: `x-len`, `v3-part`): one minted before the upgrade is refused, and a part shorter than signed is `X_STORAGE_URL_INVALID`, as on s3 | nothing: `uploadFile` re-requests the part URL (each expires in 15 min anyway). A client of its own calls `signPart` again with the part's exact `size` |
|
|
226
226
|
| `x db gen` builds an index on an existing table `concurrently` by default (**31.8.0**), in a `-- transaction: false` follow-up file; `x verify` refuses an unmarked lock-heavy migration newer than `20261113000000` (`X_MIGRATION_LOCK_HEAVY`) | generated migrations: nothing. A hand-written `create index` on an existing table: `create index concurrently` in a file whose first line is `-- transaction: false`, or `-- lock-heavy: true` for a deliberate plain build. A hand-written `set not null`: a `check (… is not null) not valid` constraint, validated in the next migration, first |
|
|
227
|
-
| drift can newly report `changed-index` (**31.8.0**) for a live index of a declared name that a hand edit gave `INCLUDE` columns or a non-default operator class: drift now compares both | rebuild it as declared — `drop index concurrently` then `create index concurrently` in a `-- transaction: false` migration — or give the hand-built index a name of its own: a live index no snapshot names is never drift.
|
|
227
|
+
| drift can newly report `changed-index` (**31.8.0**) for a live index of a declared name that a hand edit gave `INCLUDE` columns or a non-default operator class: drift now compares both | rebuild it as declared — `drop index concurrently` then `create index concurrently` in a `-- transaction: false` migration — or give the hand-built index a name of its own: a live index no snapshot names is never drift. Through 31.9.x an entity's `indexes:` cannot declare `include` or an operator class; from **31.10.0** it can (`include`, `operatorClass`, [Index key parts](Entities-And-Migrations#index-key-parts)) |
|
|
228
228
|
| an anonymous, compressible, public answer carries `W/"…"` whenever the request offers a coding (**31.8.0**), even when too small to be coded; the 304 carries the same form | nothing. A client comparing that ETag strongly switches to weak comparison |
|
|
229
|
-
| the boot runs `alter table x_rate_limit set unlogged` (**31.8.0**): a rewrite under ACCESS EXCLUSIVE of a tiny table, bounded by the migrate `lock_timeout`. After a Postgres crash, or on a promoted standby, every bucket comes back full — one free burst per key, never a lockout; a clean restart keeps the buckets. `x_auth_lockouts` stays logged |
|
|
229
|
+
| the boot runs `alter table x_rate_limit set unlogged` (**31.8.0**): a rewrite under ACCESS EXCLUSIVE of a tiny table, bounded by the migrate `lock_timeout`. After a Postgres crash, or on a promoted standby, every bucket comes back full — one free burst per key, never a lockout; a clean restart keeps the buckets. `x_auth_lockouts` stays logged. An app that commits the framework schema dump (`packages/db/schema/framework/`) sees `X_SCHEMA_DUMP_DRIFT` on `x_rate_limit` until it regenerates it | `x db gen` once, commit the regenerated `04_tables/x_rate_limit.sql` (now `create unlogged table … with (fillfactor=70)`); no migration |
|
|
230
230
|
| a routine 401/403/429 refusal logs `debug` after the first `info` line per route per minute (**31.8.0**) | an alert keyed on those `info` lines moves to the `http_refusals_total{code}` counter |
|
|
231
|
+
| a read whose page weighs more than `MAX_PAGE_BYTES` (64 MiB) before decoding is `X_ENTITY_PAGE_TOO_LARGE`, a 500 (**31.9.0**), on Postgres, memory and `defineDriver` alike — a test storing big rows in memory meets it too. Before, the page was decoded whole. `inBatches()` halves its batch instead of refusing, down to one row | paste the `fix:` onto that read: `.select({ … })` without the heaviest column it names, and the `.limit(n)` that fits — or `.inBatches(n)` to visit every row. A single row over 64 MiB on its own stays refused: move that value to storage |
|
|
232
|
+
| `updateMany`, `copyAll` and the `{ returning: false }` forms (**31.9.0**) reach a hand-written `Repo` — a `Driver.repo()` not built with `defineDriver` — through fallbacks, as optional members: `updateMany` is one `updateWhere` per row (n statements, no duplicate-id or same-columns refusal, atomic only inside `withTransaction`), `copyAll` and a count form are `insertAll(…)` / `upsertAll(…)` counted. A `defineDriver` store needs nothing | nothing. For one statement, implement `updateMany`, `insertAllCount`, `upsertAllCount` and `copyAll` on the repository (`Repo` in `@ultimat3/entity`) |
|
|
233
|
+
| `deletePlan` / `updatePlan` from `@ultimat3/entity/adapter` are the shipped names of `writeWherePlan` / `updateWherePlan` (**31.9.0**): the same arguments and refusals, plus an optional `options.where` for a chain's predicates | nothing |
|
|
234
|
+
| `X_SUBJECT_TABLE_UNDECLARED` for `<table>_history` (**31.10.0**, security): a `defineSubject()` that deletes or anonymizes an entity declared with `history: true` now reaches its history table, because that write records the person in one more before image. The run refuses before touching a row, and `x verify`'s `exercise` step reports it. Before, an erased person's data survived in `before`/`after` images | add the history table to `tables`: `posts_history: 'delete'` (every row whose `before` or `after` image names the subject, a row deleted before the erase included, removed in the parent's own transaction) or `posts_history: { retain: '<why>' }`. Images of people erased before the upgrade stay until removed by hand, per table: `begin; select set_config('x.purge', '<t>_history', true); delete from "<t>_history" where row_id = any(array['<id>', …]); commit;` — the ids from the images themselves, e.g. `select distinct row_id from "<t>_history" where before->>'<author_column>' = '<subject id>'` |
|
|
235
|
+
| `andWhere(col, 'contains', term)` on a `text()`/`char()` column is a case-insensitive substring match (**31.10.0**). Before, Postgres refused the statement (`text @> text[]`) and the memory driver compared for equality, so a test passed that production failed | where equality was meant, `andWhere(col, 'eq', term)`. Where search was meant, keep it and declare `indexes: [{ on: ['<col>'], using: 'gin', operatorClass: 'gin_trgm_ops' }]`, then `x db gen "trigram <col>"` — without it the plan sweep reports `X_QUERY_UNINDEXED` |
|
|
236
|
+
| `database()` over a `defineDriver` store throws `X_DRIVER_UNSUPPORTED` (`meta.capability: 'countedIn'`) for an entity whose column declares `countedIn` (**31.10.0**). Before, the parent's count silently never moved | serve that entity with `postgresDriver()` or `memoryDriver()`, or drop `countedIn` from the column and read `db.<child>.countBy('<key>')` instead |
|
|
237
|
+
| `registerClient()` throws `X_AUTH_CLIENT_INVALID` (422, `meta.field`) for a redirect URI, grant type, scope or resource that is empty or contains whitespace (**31.10.0**). Before, it was stored and read back as a different list | split the value into one element per item: `registerClient({ name, scopes: ['read', 'write'] })`, never `['read write']`. Rows already stored: `select client_id, redirect_uris, scopes from x_oauth_clients` and re-register any whose list is wrong |
|
|
238
|
+
| a `development` or `test` process logs `entity.all.truncated` (`ALL_TRUNCATED`) when `.all()` dropped a next page and its chain named no `.limit(n)` (**31.10.0**). The rows answered are unchanged: one page | `.inBatches(n)` where every row was meant; `.limit(n)` where one page was |
|
|
239
|
+
| a `countedIn` child write publishes an `entity.row` `update` for the parent row on memory and Postgres, PGlite in `x dev` included (**31.10.0**), so a live view of the count moves by itself | nothing. A mutator that recounted only to move a live view (`countBy` then `update`) can drop the recount |
|
|
240
|
+
| `AuthAdapter` gains the optional `getSessionWithUser(id)` (**31.10.0**); `postgresAuthAdapter` and `memoryAuthAdapter` implement it, taking `authenticate` from two statements to one | nothing. A hand-written adapter may add it — `{ session, user \| null }` or `null`, what `getSession` then `findUserById` answer — and run `authAdapterConformance` on it |
|
|
241
|
+
| an entity that adds `version: '<column>'` (**31.10.0**, opt-in) refuses `update(id)` without the version, setting it in `updateWhere`, and `upsertAll` with the default `onMatch: 'update'` — a seed's `upsertAll` included (`X_ENTITY_VERSION_INVALID`) | carry the version read: `update(id, { …patch, lockVersion: row.lockVersion })`; a seed uses `upsertAll(rows, { onConflict, onMatch: 'nothing' })` |
|
|
231
242
|
|
|
232
243
|
## 29.x → 30.0.0, entry by entry
|
|
233
244
|
|