@ultimat3/db 31.23.0 → 31.25.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/CLAUDE.md CHANGED
@@ -14,9 +14,10 @@ Tier 1 — it imports `@ultimat3/core` and nothing else. That placement is load-
14
14
  | SQLSTATE | one reader, `sqlState()` (`sqlstate.ts`). Never read `error.code` for a SQLSTATE |
15
15
  | Reading a caught value | `renderThrowable()` from core (`checkDb` backs `/readyz`) |
16
16
  | Errors | subclass `DbError`; never `throw new Error` in source. A test simulating a database failure throws `dbUnavailable()`; one simulating the caller's body failing throws a bare `Error` on purpose |
17
- | New code | `bun run new-error-code <CODE> --package db --title '…' --fix '…'` writes `DB_OWNED_ERROR_CODES`, `DB_ERROR_TITLES` and the wiki row together; then add it to `errors.test.ts`'s pinned list. The constructor lives where its imports allow (`migration-errors.ts`, `invariant-errors.ts`, `drift-errors.ts`, `dump-drift.ts`); `src/index.ts` re-exports all |
17
+ | New code | `bun run new-error-code <CODE> --package db --title '…' --fix '…'` writes `DB_OWNED_ERROR_CODES`, `DB_ERROR_TITLES` and the wiki row; then pin it in `errors.test.ts`. Constructors live where imports allow (`migration-errors.ts`, `invariant-errors.ts`, `drift-errors.ts`, `dump-drift.ts`); `src/index.ts` re-exports all |
18
18
  | A value ambient across an `await` | `asyncContext<T>(subject)` from core — never `new AsyncLocalStorage`. Three scopes: `transaction.ts`, `attribution.ts`, `expected-loop.ts` |
19
19
  | Exports | explicit in `src/index.ts`; no `export *` |
20
+ | Keyset | `keyset.ts`; SQL `keyset-seek.ts`; null tags `keyset-position.ts` (entity's) |
20
21
  | Files | < 200 LOC (the `packages/db/src/**/*.ts` path instruction), one responsibility, `kebab-case.ts`, test beside source |
21
22
 
22
23
  Pinned public seam — `@ultimat3/auth`, `@ultimat3/entity` and `@ultimat3/jobs` are written against
@@ -195,8 +196,8 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
195
196
  `missing-check`'s are one `psql -c` too — `repair()`, schema-scoped off `public`).
196
197
  - `introspectSchema()` reads index keys in `indkey` order and a key's two column lists together
197
198
  (`unnest(a, b) with ordinality`); `introspect-embedded.test.ts`.
198
- - **`table-storage.ts`**: a framework table's `fillfactor`/`unlogged`, one value — `tableDdl`
199
- renders the create plus idempotent alters (re-applied every framework apply), drift reads `pg_class`.
199
+ - **`table-storage.ts`**: a framework table's `fillfactor`/`unlogged`/`autovacuum`
200
+ (`table-autovacuum.ts`), one value; `tableDdl`: create + alters; `table-storage-drift.ts`: `pg_class`.
200
201
  - **`appTables()`** excludes all of `x_` for drift; `introspectSchema()` only `x_migrations`.
201
202
  `nonAppRelations` (`app-relation.ts`): extension-owned, views, matviews, foreign tables,
202
203
  partitions — always excluded.
@@ -262,4 +263,4 @@ Gotchas:
262
263
  the roles in `creators` (default: the connected user).
263
264
  - `Bun.SQL` is reached lazily inside `connect()` — importing `client.ts` must not open a socket.
264
265
 
265
- Why each rule above is shaped the way it is: [`docs/history/db.md`](../../docs/history/db.md).
266
+ Why: [`docs/history/db.md`](../../docs/history/db.md).
package/README.md CHANGED
@@ -46,7 +46,7 @@ await withTransaction(async (tx) => {
46
46
  | `replicatedClient()` / `ReplicaStats` / `REPLICA_URL_ENV` | `As of 2026-08-24`: one `DbClient` over a primary and a standby. `baseClient()` builds one when `DATABASE_REPLICA_URL` is set and the single-pool client when it is not |
47
47
  | `INDEX_METHODS` / `IndexMethod` / `indexMethodOf()` / `indexMethodSql()` / `declaredMethod()` | `As of 2026-08-24`: an index's access method — `btree` or `gin`, closed. Absent is `btree`, the live side is read open (whatever `pg_am` said), and the DDL literal is re-derived from the set rather than spliced from the input |
48
48
  | `IndexDescriptionLike.expression` / `.orders` / `.include` / `.operatorClass` · `INDEX_OPERATOR_CLASSES` / `requiredExtension()` | `As of 2026-11-12`: the index parts past a plain column list — one expression key (`unique (lower(email))`), a direction per key, INCLUDE payload columns (btree), `gin_trgm_ops` (gin; `requiredExtension()` answers `pg_trgm`). Each optional, absent hashes and renders as before; drift compares each, an expression by presence only |
49
- | `tableStorage(table, { fillfactor?, unlogged? })` / `tableDdl()` / `storageAlters()` / `tableStorageDrift()` / `readTableStorageDrift()` | `As of 2026-11-12`: a **framework-owned** table's storage parameters as one value. `tableDdl(storage, columns)` renders `create [unlogged] table if not exists … with (fillfactor = n)` plus the idempotent `alter`s that bring an existing table to it at framework-schema apply; drift reads `relpersistence`/`reloptions`, each difference with its `alter` as `fix`. A bad name or fillfactor is `X_SQL_UNSAFE` at import |
49
+ | `tableStorage(table, { fillfactor?, unlogged?, autovacuum? })` / `tableDdl()` / `storageAlters()` / `tableStorageDrift()` / `readTableStorageDrift()` | `As of 2026-11-14`: a **framework-owned** table's storage parameters as one value; `autovacuum` (`TableAutovacuum`: `vacuumThreshold`, `vacuumScaleFactor`, `analyzeThreshold`, `analyzeScaleFactor`) states when autovacuum visits it. `tableDdl(storage, columns)` renders `create [unlogged] table if not exists … with (fillfactor = n, autovacuum_… = v)` plus the idempotent `alter`s that bring an existing table to it at framework-schema apply; drift reads `relpersistence`/`reloptions`, each difference with its `alter` as `fix`. A bad name, fillfactor or autovacuum value is `X_SQL_UNSAFE` at import |
50
50
  | `slowStatementLog({ thresholdMs })` | one `warn` `db.statement.slow` line per slow statement shape per 10 s, with request/trace ids and no bind values; returns the unsubscribe |
51
51
  | `lockHeavyStatements()` / `migrationLockHeavy()` / `LOCK_HEAVY_MARKER` / `LOCK_HEAVY_SINCE` | `X_MIGRATION_LOCK_HEAVY`: `set not null` with no prior validate, non-concurrent `create index` on an existing table; `-- lock-heavy: true` to admit; judges ids > `LOCK_HEAVY_SINCE` |
52
52
  | `isPlainRead()` | `As of 2026-08-24`: whether a statement may leave the primary. An allow-list — everything it cannot vouch for is the primary's |
@@ -138,13 +138,15 @@ fragments to splice and `page(rows)`, which answers core's `Page`.
138
138
  | Precision | selected as `col::text` under `_keyset_<n>`, bound back as `$n::<kind>`: a microsecond survives, a `Date` would floor it and drop rows |
139
139
  | The seek | uniform direction: one row comparison, Index Only Scan on a matching index. Mixed: the or-chain |
140
140
  | `order by` | the bare columns. `date_trunc('milliseconds', …)` there is a Parallel Seq Scan and a sort (100 ms against 0.2 ms, 300,000 rows); the scaffolded `repo-raw-sql` guard reports it |
141
- | A null key | `X_KEYSET_NULL_KEY`, on any row of a page, whatever its size |
142
- | The cursor | core's signed codec; scoped to `scope` plus every key's column, kind and direction. Another read's is `X_CURSOR_INVALID` |
141
+ | A nullable key | `As of 2026-11-14`: `nullable: true`, NULL placed by `nulls: 'first' \| 'last'` (default `asc nulls last`, `desc nulls first`, as the entity driver). Written into `order by`, carried in the cursor as present/absent, seeked by the or-chain. Never the last key |
142
+ | A null key | on an undeclared key, `X_KEYSET_NULL_KEY` on any row of a page, whatever its size; a nullable last key is the same code at `keyset()` |
143
+ | The cursor | core's signed codec; scoped to `scope` plus every key's column, kind and direction (and a nullable key's NULL placement). Another read's is `X_CURSOR_INVALID` |
143
144
  | `limit` | a whole number ≥ 1 (`finiteCount`), read as `limit + 1` |
144
145
  | `direction`, `kind` | `As of 2026-11-09`: `'asc'`/`'desc'` and the five kinds, exactly — anything else is `X_INVARIANT` at `keyset()`. The `order by` splice is re-derived from the closed set, never the caller's text. Map a request's sort onto the two literals yourself |
145
146
 
146
147
  Proven on both engines: `keyset.live.test.ts` (Postgres) and `keyset-embedded.test.ts` (PGlite)
147
- walk four rows inside one millisecond across page boundaries, and assert the plan holds no sort.
148
+ walk four rows inside one millisecond across page boundaries, and assert the plan holds no sort;
149
+ the same suites walk a nullable key under all four direction × placement orders, every row once.
148
150
 
149
151
  ## Transactions that end badly
150
152
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/db",
3
- "version": "31.23.0",
3
+ "version": "31.25.0",
4
4
  "description": "Postgres access, transactions, migrations and drift detection",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,7 +45,7 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/core": "31.23.0"
48
+ "@ultimat3/core": "31.25.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@electric-sql/pglite": ">=0.5.0"
@@ -233,6 +233,18 @@ export interface CounterDescriptionLike {
233
233
  readonly references: string;
234
234
  /** The child's soft-delete column: a stamped row is not counted. `null` when it has none. */
235
235
  readonly softDelete: string | null;
236
+ /** `countedIn: { where }`: only a child row this predicate holds over is counted. Absent: all. */
237
+ readonly where?: CounterWhereLike | undefined;
238
+ }
239
+
240
+ /**
241
+ * A counter's predicate, compiled once by `@ultimat3/entity`. `sql` names the child's columns
242
+ * qualified by the alias `c` (`c."kind" = 'up'`), which the trigger and the recount both give the
243
+ * child row; `columns` are the physical columns it reads, so a change to one fires the trigger.
244
+ */
245
+ export interface CounterWhereLike {
246
+ readonly sql: string;
247
+ readonly columns: readonly string[];
236
248
  }
237
249
 
238
250
  /** `retain: { after, on }`, with `on` physical. */
@@ -5,7 +5,8 @@
5
5
  import type { CounterDescriptionLike } from './entity-shape';
6
6
  import { triggerInstall } from './generate-history';
7
7
  import type { TriggerRecord } from './introspect';
8
- import { identifier } from './sql';
8
+ import { CROSS_TENANT_SETTING } from './row-security';
9
+ import { identifier, raw, type SqlFragment, sql } from './sql';
9
10
 
10
11
  /**
11
12
  * `ultimate_count_<crc32 of parent.column>`: per counter, because each body names its own tables,
@@ -17,12 +18,19 @@ export function counterTriggerName(parent: string, counter: CounterDescriptionLi
17
18
  return `ultimate_count_${hash}`;
18
19
  }
19
20
 
20
- /** Whether a row image (`old`/`new`) is counted: it names a parent and is not soft-deleted. */
21
+ /**
22
+ * Whether a row image (`old`/`new`) is counted: it names a parent, is not soft-deleted, and — with a
23
+ * `where` — the predicate holds over it. The predicate names the child as `c`, so the image is
24
+ * given that alias in a one-row subquery: one compiled text serves the trigger and the recount.
25
+ */
21
26
  const counted = (image: 'old' | 'new', counter: CounterDescriptionLike): string =>
22
27
  `${image}.${identifier(counter.references).text} is not null` +
23
28
  (counter.softDelete === null
24
29
  ? ''
25
- : ` and ${image}.${identifier(counter.softDelete).text} is null`);
30
+ : ` and ${image}.${identifier(counter.softDelete).text} is null`) +
31
+ (counter.where === undefined
32
+ ? ''
33
+ : ` and exists (select from (select ${image}.*) c where ${counter.where.sql})`);
26
34
 
27
35
  const bump = (parent: string, counter: CounterDescriptionLike, image: string, sign: string) =>
28
36
  `update ${identifier(parent).text} set ${identifier(counter.column).text} = ` +
@@ -33,7 +41,8 @@ const bump = (parent: string, counter: CounterDescriptionLike, image: string, si
33
41
  * Old image out, new image in: an insert adds one, a delete takes one, a re-parent or a soft delete
34
42
  * moves it. Lock order is the PARENT row, so a hot parent serializes its writers — `countBy` plus a
35
43
  * cache is the alternative where that matters. `after … for each row`, so a refused write moves
36
- * nothing, and `update of` the two columns that can change the answer, so no other update pays.
44
+ * nothing, and `update of` the columns that can change the answer — key, stamp, the predicate's —
45
+ * so no other update pays.
37
46
  */
38
47
  export function counterTrigger(parent: string, counter: CounterDescriptionLike): TriggerRecord {
39
48
  const name = counterTriggerName(parent, counter);
@@ -43,16 +52,28 @@ export function counterTrigger(parent: string, counter: CounterDescriptionLike):
43
52
  `${bump(parent, counter, 'old', '-')} end if; if tg_op <> 'DELETE' and ` +
44
53
  `${counted('new', counter)} then ${bump(parent, counter, 'new', '+')} end if; ` +
45
54
  'return null; end; $counter$;';
46
- const watched = [counter.references, ...(counter.softDelete === null ? [] : [counter.softDelete])]
55
+ const watched = [
56
+ ...new Set([
57
+ counter.references,
58
+ ...(counter.softDelete === null ? [] : [counter.softDelete]),
59
+ ...(counter.where?.columns ?? []),
60
+ ]),
61
+ ]
47
62
  .map((column) => identifier(column).text)
48
63
  .join(', ');
49
- return triggerInstall(
64
+ const install = triggerInstall(
50
65
  name,
51
66
  { name, sql: fn },
52
67
  `after insert or delete or update of ${watched}`,
53
68
  counter.table,
54
69
  '',
55
70
  );
71
+ // Cross-tenant for the one statement: under forced row security an unset tenant matches no row.
72
+ const recount = [
73
+ `select set_config('${CROSS_TENANT_SETTING}', 'on', true);`,
74
+ recountSql(parent, counter),
75
+ ];
76
+ return { ...install, recount };
56
77
  }
57
78
 
58
79
  /** The true count of one parent row, as a correlated subquery over `parent` aliased `p`. */
@@ -60,11 +81,14 @@ const truth = (counter: CounterDescriptionLike): string =>
60
81
  `(select count(*)::integer from ${identifier(counter.table).text} c where ` +
61
82
  `c.${identifier(counter.references).text} = p.${identifier(counter.key).text}` +
62
83
  (counter.softDelete === null ? '' : ` and c.${identifier(counter.softDelete).text} is null`) +
84
+ (counter.where === undefined ? '' : ` and (${counter.where.sql})`) +
63
85
  ')';
64
86
 
65
87
  /**
66
88
  * Sets every drifted counter to the truth. A migration adding a counter runs it once, so a table
67
- * that already holds rows starts true; `x db recount --write` runs it again, by key range.
89
+ * that already holds rows starts true. Migration-only: it locks nothing first, so it is not safe
90
+ * beside live writers — `x db recount --write` repairs by key range instead (`recountLockSql`,
91
+ * then `recountBatchSql`), one transaction per window.
68
92
  */
69
93
  export function recountSql(parent: string, counter: CounterDescriptionLike): string {
70
94
  return (
@@ -83,3 +107,90 @@ export function recountDriftSql(parent: string, counter: CounterDescriptionLike)
83
107
  `order by p.${identifier(counter.key).text}`
84
108
  );
85
109
  }
110
+
111
+ /** `p.key > $after and p.key <= $last`, the half-open window one batch covers; no lower bound first. */
112
+ const windowOf = (
113
+ counter: CounterDescriptionLike,
114
+ after: string | null,
115
+ last: string,
116
+ ): SqlFragment => {
117
+ const key = raw(`p.${identifier(counter.key).text}`);
118
+ return after === null ? sql`${key} <= ${last}` : sql`${key} > ${after} and ${key} <= ${last}`;
119
+ };
120
+
121
+ /**
122
+ * The last key of the next window: up to `size` parent keys past `after`, in key order. `null` when
123
+ * none is left. Keys travel as text so any single-column key type bounds the next window.
124
+ */
125
+ export function recountWindowSql(
126
+ parent: string,
127
+ counter: CounterDescriptionLike,
128
+ after: string | null,
129
+ size: number,
130
+ ): SqlFragment {
131
+ const key = raw(`p.${identifier(counter.key).text}`);
132
+ const table = identifier(parent);
133
+ const from = raw(`select ${key.text}::text as "key" from ${table.text} p`);
134
+ const keys =
135
+ after === null
136
+ ? sql`${from} order by ${key} limit ${size}`
137
+ : sql`${from} where ${key} > ${after} order by ${key} limit ${size}`;
138
+ return sql`select max(w."key") as "last" from (${keys}) w`;
139
+ }
140
+
141
+ /**
142
+ * Locks one window's parent rows, in key order, as a counter's trigger locks a parent (`for no key
143
+ * update`, `pg-lock.ts`'s mode). Sent FIRST in the window's transaction: a writer whose trigger
144
+ * already holds a row commits before this returns, and the drift read and repair that follow, each
145
+ * its own statement under READ COMMITTED, take a snapshot that counts it; a writer arriving later
146
+ * waits in its trigger and moves the repaired count by one. An UPDATE alone re-checks a row it
147
+ * waited on but keeps its statement's snapshot for `count(*)` — and writes a stale count.
148
+ */
149
+ export function recountLockSql(
150
+ parent: string,
151
+ counter: CounterDescriptionLike,
152
+ after: string | null,
153
+ last: string,
154
+ ): SqlFragment {
155
+ const from = raw(`select 1 from ${identifier(parent).text} p where `);
156
+ const order = raw(` order by p.${identifier(counter.key).text} for no key update`);
157
+ return sql`${from}${windowOf(counter, after, last)}${order}`;
158
+ }
159
+
160
+ /** The drifted rows of one window, for the report: key, stored and true count. */
161
+ export function recountDriftBatchSql(
162
+ parent: string,
163
+ counter: CounterDescriptionLike,
164
+ after: string | null,
165
+ last: string,
166
+ ): SqlFragment {
167
+ const select = raw(
168
+ `select p.${identifier(counter.key).text}::text as "key", ` +
169
+ `p.${identifier(counter.column).text} as "stored", ${truth(counter)} as "actual" ` +
170
+ `from ${identifier(parent).text} p where `,
171
+ );
172
+ const drifted = raw(
173
+ ` and p.${identifier(counter.column).text} is distinct from ${truth(counter)} ` +
174
+ `order by p.${identifier(counter.key).text}`,
175
+ );
176
+ return sql`${select}${windowOf(counter, after, last)}${drifted}`;
177
+ }
178
+
179
+ /**
180
+ * Sets every drifted counter of one window to the truth: one statement, one batch — only after
181
+ * `recountLockSql` in the same transaction, or a concurrent writer's count is lost.
182
+ */
183
+ export function recountBatchSql(
184
+ parent: string,
185
+ counter: CounterDescriptionLike,
186
+ after: string | null,
187
+ last: string,
188
+ ): SqlFragment {
189
+ const update = raw(
190
+ `update ${identifier(parent).text} p set ${identifier(counter.column).text} = ${truth(counter)} where `,
191
+ );
192
+ const drifted = raw(
193
+ ` and p.${identifier(counter.column).text} is distinct from ${truth(counter)}`,
194
+ );
195
+ return sql`${update}${windowOf(counter, after, last)}${drifted}`;
196
+ }
@@ -4,11 +4,10 @@
4
4
 
5
5
  import type { EntityDescriptionLike } from './entity-shape';
6
6
  import type { Plan } from './foreign-key-plan';
7
- import { counterTrigger, recountSql } from './generate-counter';
7
+ import { counterTrigger } from './generate-counter';
8
8
  import { historyTriggers } from './generate-history';
9
9
  import type { SchemaDescription, TableDescription, TriggerRecord } from './introspect';
10
10
  import { findTable } from './introspect';
11
- import { CROSS_TENANT_SETTING } from './row-security';
12
11
  import { identifier } from './sql';
13
12
 
14
13
  /** Every declared lifecycle trigger, by the table it sits on, in declaration order. */
@@ -45,21 +44,28 @@ const same = (left: TriggerRecord, right: TriggerRecord): boolean =>
45
44
  * row, and the recount would update nothing in silence.
46
45
  */
47
46
  function recounts(
48
- entities: readonly EntityDescriptionLike[],
47
+ declared: ReadonlyMap<string, readonly TriggerRecord[]>,
49
48
  added: ReadonlySet<string>,
50
49
  ): string[] {
51
50
  const out: string[] = [];
52
- for (const entity of entities) {
53
- for (const counter of entity.counts ?? []) {
54
- const trigger = counterTrigger(entity.table, counter);
55
- if (!added.has(`${counter.table}.${trigger.name}`)) continue;
56
- out.push(`select set_config('${CROSS_TENANT_SETTING}', 'on', true);`);
57
- out.push(recountSql(entity.table, counter));
51
+ for (const [table, triggers] of declared) {
52
+ for (const trigger of triggers) {
53
+ if (added.has(`${table}.${trigger.name}`)) out.push(...(trigger.recount ?? []));
58
54
  }
59
55
  }
60
56
  return out;
61
57
  }
62
58
 
59
+ /**
60
+ * `down`'s reinstall of a recorded trigger, pushed for the final reversal: the recount it recorded
61
+ * (a counter's, under ITS predicate) runs after the reinstall, so a rolled-back `where` leaves the
62
+ * counts the old trigger keeps. A record without one reinstalls only, as before 31.23.
63
+ */
64
+ const reinstall = (recorded: TriggerRecord): readonly string[] => [
65
+ ...[...(recorded.recount ?? [])].reverse(),
66
+ ...[...recorded.install].reverse(),
67
+ ];
68
+
63
69
  /**
64
70
  * Both directions, after every table exists. Declared and not recorded (or recorded with other
65
71
  * statements): install, and `down` drops it — or reinstalls what was recorded. Recorded and no
@@ -82,7 +88,7 @@ export function triggerPlan(
82
88
  plan.up.push(...trigger.install);
83
89
  // `down` is reversed whole: pushed in apply order, reversed back into it.
84
90
  if (before === undefined) plan.down.push(dropSql(table, trigger.name));
85
- else plan.down.push(...[...before.install].reverse());
91
+ else plan.down.push(...reinstall(before));
86
92
  added.add(`${table}.${trigger.name}`);
87
93
  }
88
94
  }
@@ -92,10 +98,10 @@ export function triggerPlan(
92
98
  for (const recorded of table.triggers ?? []) {
93
99
  if (wanted.some((each) => each.name === recorded.name)) continue;
94
100
  plan.up.push(dropSql(table.name, recorded.name));
95
- plan.down.push(...[...recorded.install].reverse());
101
+ plan.down.push(...reinstall(recorded));
96
102
  }
97
103
  }
98
- plan.up.push(...recounts(entities, added));
104
+ plan.up.push(...recounts(declared, added));
99
105
  }
100
106
 
101
107
  /** The snapshot, each table carrying the triggers declared on it — absent where there are none. */
package/src/index.ts CHANGED
@@ -69,6 +69,7 @@ export { rowSecurityDifferences, rowSecurityDrift } from './drift-row-security';
69
69
  export type {
70
70
  ColumnDescriptionLike,
71
71
  CounterDescriptionLike,
72
+ CounterWhereLike,
72
73
  EntityDescriptionLike,
73
74
  HistoryDescriptionLike,
74
75
  IndexDescriptionLike,
@@ -108,7 +109,14 @@ export type { RecordedStatement, RecordingClient, StubResponse } from './fake';
108
109
  export { recordingClient } from './fake';
109
110
  export type { GeneratedMigration, GenerateOptions } from './generate';
110
111
  export { generateMigration, slugify, snapshotOf } from './generate';
111
- export { recountDriftSql, recountSql } from './generate-counter';
112
+ export {
113
+ recountBatchSql,
114
+ recountDriftBatchSql,
115
+ recountDriftSql,
116
+ recountLockSql,
117
+ recountSql,
118
+ recountWindowSql,
119
+ } from './generate-counter';
112
120
  export { ACTOR_SETTING, PURGE_SETTING, REQUEST_SETTING } from './generate-history';
113
121
  export type { PartitionMaintenanceOptions } from './generate-partition';
114
122
  export { partitionMaintenance } from './generate-partition';
@@ -273,19 +281,11 @@ export type { StatementBoundOptions } from './statement-bound';
273
281
  export { withStatementTimeout } from './statement-bound';
274
282
  export { statementFingerprint, statementKind, statementVerb } from './statement-shape';
275
283
  export { statementsOf } from './statement-split';
276
- export type {
277
- LiveTableStorage,
278
- TableStorage,
279
- TableStorageDifference,
280
- TableStorageOptions,
281
- } from './table-storage';
282
- export {
283
- readTableStorageDrift,
284
- storageAlters,
285
- tableDdl,
286
- tableStorage,
287
- tableStorageDrift,
288
- } from './table-storage';
284
+ export type { AutovacuumParameter, TableAutovacuum } from './table-autovacuum';
285
+ export type { TableStorage, TableStorageOptions } from './table-storage';
286
+ export { storageAlters, tableDdl, tableStorage } from './table-storage';
287
+ export type { LiveTableStorage, TableStorageDifference } from './table-storage-drift';
288
+ export { readTableStorageDrift, tableStorageDrift } from './table-storage-drift';
289
289
  export {
290
290
  completeTransaction,
291
291
  currentTx,
package/src/introspect.ts CHANGED
@@ -212,6 +212,12 @@ export interface TableDescription {
212
212
  export interface TriggerRecord {
213
213
  readonly name: string;
214
214
  readonly install: readonly string[];
215
+ /**
216
+ * A counter trigger's recount under ITS OWN predicate (`generate-counter.ts`): what `down` runs
217
+ * after reinstalling this record, so the counts follow the trigger that keeps them. Snapshot-only;
218
+ * absent on every other trigger and on a counter recorded before 31.23 (that `down` recounts nothing).
219
+ */
220
+ readonly recount?: readonly string[] | undefined;
215
221
  }
216
222
 
217
223
  /**
@@ -0,0 +1,24 @@
1
+ // Single responsibility: one keyset key's value as the cursor carries it — present, or NULL —
2
+ // and back. The tag scheme is entity's (`entity/src/cursor.ts`), replicated: db is tier 1.
3
+
4
+ import type { KeysetKey } from './keyset-seek';
5
+
6
+ const ABSENT_MARK = '~';
7
+ const PRESENT_MARK = '!';
8
+
9
+ /**
10
+ * A nullable key's place in the cursor is TAGGED, entity's scheme (`entity/src/cursor.ts`): `~`
11
+ * alone is NULL, `!` prefixes a present value — so a `text` key holding `~` is never read as
12
+ * absent. A not-null key is carried bare, as it was before nullable keys existed.
13
+ */
14
+ export const encodePart = (key: KeysetKey | undefined, value: string | null): string => {
15
+ if (key?.nullable !== true) return value ?? '';
16
+ return value === null ? ABSENT_MARK : `${PRESENT_MARK}${value}`;
17
+ };
18
+
19
+ export const decodePart = (key: KeysetKey, part: unknown): string | null | undefined => {
20
+ if (typeof part !== 'string') return undefined;
21
+ if (key.nullable !== true) return part;
22
+ if (part === ABSENT_MARK) return null;
23
+ return part.startsWith(PRESENT_MARK) ? part.slice(PRESENT_MARK.length) : undefined;
24
+ };
@@ -0,0 +1,94 @@
1
+ // Single responsibility: the SQL `keyset()` splices for an order — each key's `order by` term and
2
+ // the seek past a cursor's position, NULL's place in both written down for a nullable key.
3
+ // The shapes mirror `entity/src/pg-sql.ts` (`seekSql`); db is tier 1 and cannot import it.
4
+
5
+ import { join, raw, type SqlFragment, sql } from './sql';
6
+
7
+ /** The kinds a position can be bound back as, each with its own cast. A closed list. */
8
+ export type KeysetKind = 'timestamptz' | 'uuid' | 'text' | 'integer' | 'bigint';
9
+
10
+ export interface KeysetKey {
11
+ /** The ordered expression as written in the statement: `raw('p.created_at')`, or a `sql` one. */
12
+ readonly column: SqlFragment;
13
+ readonly kind: KeysetKind;
14
+ readonly direction: 'asc' | 'desc';
15
+ /** The key may be NULL on a row. Never the last key: the tiebreak must be not null. */
16
+ readonly nullable?: true | undefined;
17
+ /** NULL's place, nullable keys only. Default: `asc nulls last`, `desc nulls first`. */
18
+ readonly nulls?: 'first' | 'last' | undefined;
19
+ }
20
+
21
+ /** One key of a cursor's position: the column's text, or `null` where the boundary row had none. */
22
+ export type KeysetPosition = readonly (string | null)[];
23
+
24
+ export const CASTS: ReadonlyMap<KeysetKind, string> = new Map<KeysetKind, string>([
25
+ ['timestamptz', 'timestamptz'],
26
+ ['uuid', 'uuid'],
27
+ ['text', 'text'],
28
+ ['integer', 'integer'],
29
+ ['bigint', 'bigint'],
30
+ ]);
31
+
32
+ /** Where a nullable key's NULLs sort — the same defaults as the entity driver and the query layer. */
33
+ export const nullsOf = (key: KeysetKey): 'first' | 'last' =>
34
+ key.nulls ?? (key.direction === 'desc' ? 'first' : 'last');
35
+
36
+ const bind = (key: KeysetKey, text: string): SqlFragment =>
37
+ sql`${text}::${raw(CASTS.get(key.kind) ?? 'text')}`;
38
+
39
+ /**
40
+ * The splice re-derived from the closed set, as `entity/src/pg-sql.ts` does: never the caller's
41
+ * text. A not-null key stays bare so an index on `(created_at desc, id desc)` still answers it.
42
+ */
43
+ export const orderOf = (key: KeysetKey): SqlFragment => {
44
+ const direction = key.direction === 'desc' ? 'desc' : 'asc';
45
+ if (key.nullable !== true) return sql`${key.column} ${raw(direction)}`;
46
+ return sql`${key.column} ${raw(`${direction} nulls ${nullsOf(key) === 'first' ? 'first' : 'last'}`)}`;
47
+ };
48
+
49
+ const past = (key: KeysetKey, value: SqlFragment): SqlFragment =>
50
+ sql`${key.column} ${raw(key.direction === 'desc' ? '<' : '>')} ${value}`;
51
+
52
+ /**
53
+ * What sorts strictly after the position on this one key, as alternatives. A value is followed by
54
+ * the values past it, and by the NULLs too when they sort last. A NULL is followed by every value
55
+ * when NULLs sort first, and by nothing when they sort last — the later keys carry that page.
56
+ */
57
+ const after = (key: KeysetKey, value: string | null): SqlFragment[] => {
58
+ const last = nullsOf(key) === 'last';
59
+ if (value === null) return last ? [] : [sql`${key.column} is not null`];
60
+ const beyond = past(key, bind(key, value));
61
+ return key.nullable === true && last ? [beyond, sql`${key.column} is null`] : [beyond];
62
+ };
63
+
64
+ /** At the position on this key. `= $n` is never true of a NULL, so an absent one is `is null`. */
65
+ const equal = (key: KeysetKey, value: string | null): SqlFragment =>
66
+ value === null ? sql`${key.column} is null` : sql`${key.column} = ${bind(key, value)}`;
67
+
68
+ /**
69
+ * Uniform direction over not-null keys is ONE row comparison, the shape Postgres pushes into a
70
+ * multicolumn index as an Index Cond. A mixed order, or any nullable key, has none (a row
71
+ * comparison has no null order), so it is the or-chain — the same split as the entity driver's
72
+ * `seekSql`. The last key is not null, so the chain always holds at least one term.
73
+ */
74
+ export const seek = (keys: readonly KeysetKey[], position: KeysetPosition): SqlFragment => {
75
+ const valueAt = (index: number): string | null => position[index] ?? null;
76
+ const [first] = keys;
77
+ if (first === undefined) return sql`true`;
78
+ if (keys.length === 1) return past(first, bind(first, valueAt(0) ?? ''));
79
+ const rowComparable = keys.every(
80
+ (key) => key.direction === first.direction && key.nullable !== true,
81
+ );
82
+ if (rowComparable) {
83
+ const op = raw(first.direction === 'desc' ? '<' : '>');
84
+ const binds = keys.map((key, index) => bind(key, valueAt(index) ?? ''));
85
+ return sql`(${join(keys.map((key) => key.column))}) ${op} (${join(binds)})`;
86
+ }
87
+ const terms = keys.flatMap((key, index) => {
88
+ const prefix = keys.slice(0, index).map((prior, at) => equal(prior, valueAt(at)));
89
+ return after(key, valueAt(index)).map((term) =>
90
+ prefix.length === 0 ? term : sql`(${join([...prefix, term], ' and ')})`,
91
+ );
92
+ });
93
+ return terms.length === 1 && terms[0] !== undefined ? terms[0] : sql`(${join(terms, ' or ')})`;
94
+ };
package/src/keyset.ts CHANGED
@@ -13,22 +13,16 @@ import {
13
13
  renderCauseValue,
14
14
  } from '@ultimat3/core';
15
15
  import { DbError } from './errors';
16
+ import { decodePart, encodePart } from './keyset-position';
17
+ import { CASTS, type KeysetKey, type KeysetPosition, nullsOf, orderOf, seek } from './keyset-seek';
16
18
  import { join, raw, type SqlFragment, sql } from './sql';
17
19
 
18
- /** The kinds a position can be bound back as, each with its own cast. A closed list. */
19
- export type KeysetKind = 'timestamptz' | 'uuid' | 'text' | 'integer' | 'bigint';
20
-
21
- export interface KeysetKey {
22
- /** The ordered expression as written in the statement: `raw('p.created_at')`, or a `sql` one. */
23
- readonly column: SqlFragment;
24
- readonly kind: KeysetKind;
25
- readonly direction: 'asc' | 'desc';
26
- }
20
+ export type { KeysetKey, KeysetKind } from './keyset-seek';
27
21
 
28
22
  export interface KeysetOptions {
29
23
  /** This read and its arguments: a cursor from another scope is `X_CURSOR_INVALID`. */
30
24
  readonly scope: string;
31
- /** The order, last key the tiebreak. Every key must be not null on every row. */
25
+ /** The order, last key the tiebreak. A key not declared `nullable` must be not null on every row. */
32
26
  readonly keys: readonly KeysetKey[];
33
27
  /** The previous page's `nextCursor`; `null` for the first page. */
34
28
  readonly after: string | null;
@@ -49,18 +43,11 @@ export interface Keyset {
49
43
  page<Row extends object>(rows: readonly Row[]): Page<KeysetRow<Row>>;
50
44
  }
51
45
 
52
- const CASTS: ReadonlyMap<KeysetKind, string> = new Map<KeysetKind, string>([
53
- ['timestamptz', 'timestamptz'],
54
- ['uuid', 'uuid'],
55
- ['text', 'text'],
56
- ['integer', 'integer'],
57
- ['bigint', 'bigint'],
58
- ]);
59
-
60
46
  const NULL_KEY_FIX =
61
- "keyset({ keys: [{ column: sql`coalesce(p.published_at, p.created_at)`, kind: 'timestamptz', direction: 'desc' }, …] }) # or order by a not-null column";
47
+ "keyset({ keys: [{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true }, { column: raw('p.id'), kind: 'uuid', direction: 'desc' }], … }) # declare the key nullable; the last key stays not null";
62
48
 
63
49
  const DIRECTIONS: ReadonlySet<string> = new Set(['asc', 'desc']);
50
+ const PLACEMENTS: ReadonlySet<string> = new Set(['first', 'last']);
64
51
 
65
52
  /**
66
53
  * A direction and a kind are spliced as SQL text, and a sort read off a query string arrives typed
@@ -78,6 +65,26 @@ const assertKey = (key: KeysetKey, at: number): void => {
78
65
  `keyset() key ${String(at)} has kind ${renderCauseValue(key.kind)}, which has no cast to bind a position back with`,
79
66
  "keyset({ keys: [{ column: raw('p.created_at'), kind: 'timestamptz', … }] }) # one of: timestamptz, uuid, text, integer, bigint",
80
67
  );
68
+ assert(
69
+ key.nulls === undefined || (key.nullable === true && PLACEMENTS.has(key.nulls)),
70
+ `keyset() key ${String(at)} has nulls ${renderCauseValue(key.nulls)}${key.nullable === true ? '' : ' without nullable: true'}; NULL placement is spliced into SQL and only a nullable key has one`,
71
+ "keyset({ keys: [{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true, nulls: 'last' }, …] }) # nulls: 'first' | 'last'",
72
+ );
73
+ };
74
+
75
+ /**
76
+ * The last key breaks every tie, so it must be not null: two rows NULL on it are tied forever and
77
+ * one of them falls between pages. Refused at construction, before a row is read.
78
+ */
79
+ const assertTiebreak = (keys: readonly KeysetKey[]): void => {
80
+ const last = keys.at(-1);
81
+ if (last?.nullable !== true) return;
82
+ throw new DbError({
83
+ code: 'X_KEYSET_NULL_KEY',
84
+ cause: `keyset() key ${String(keys.length - 1)} (${last.column.text}) is the final tiebreak and is declared nullable: rows NULL on it tie with no order between them`,
85
+ fix: "keyset({ keys: [{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true }, { column: raw('p.id'), kind: 'uuid', direction: 'desc' }], … }) # end on a not-null unique key",
86
+ meta: { key: keys.length - 1 },
87
+ });
81
88
  };
82
89
 
83
90
  const aliasOf = (index: number): string => `_keyset_${String(index)}`;
@@ -85,67 +92,42 @@ const aliasOf = (index: number): string => `_keyset_${String(index)}`;
85
92
  /**
86
93
  * The scope the cursor is signed under: the caller's, plus the order itself — so a cursor minted
87
94
  * under `desc` cannot seek an `asc` read, nor a `uuid` key be bound back as `text`. Hashed: the
88
- * key expressions are the statement's, not the client's to read.
95
+ * key expressions are the statement's, not the client's to read. A nullable key adds its NULL
96
+ * placement; a not-null key's scope is unchanged, so a cursor minted before nullable keys pages on.
89
97
  */
90
98
  const scopeOf = (scope: string, keys: readonly KeysetKey[]): string => {
91
99
  const order = keys
92
100
  .map(
93
101
  (key) =>
94
- `${key.column.text}${JSON.stringify(key.column.values.map(String))} ${key.kind} ${key.direction}`,
102
+ `${key.column.text}${JSON.stringify(key.column.values.map(String))} ${key.kind} ${key.direction}${key.nullable === true ? ` nulls ${nullsOf(key)}` : ''}`,
95
103
  )
96
104
  .join(',');
97
105
  const digest = new Bun.CryptoHasher('sha256').update(`${scope}|${order}`).digest('hex');
98
106
  return `keyset:${digest.slice(0, 16)}`;
99
107
  };
100
108
 
101
- const bind = (key: KeysetKey, text: string): SqlFragment =>
102
- sql`${text}::${raw(CASTS.get(key.kind) ?? 'text')}`;
103
-
104
- /** The splice re-derived from the closed set, as `entity/src/pg-sql.ts` does: never the caller's text. */
105
- const orderOf = (key: KeysetKey): SqlFragment => raw(key.direction === 'desc' ? 'desc' : 'asc');
106
-
107
- const past = (key: KeysetKey, value: SqlFragment): SqlFragment =>
108
- sql`${key.column} ${raw(key.direction === 'desc' ? '<' : '>')} ${value}`;
109
-
110
- /**
111
- * Uniform direction is ONE row comparison, the shape Postgres pushes into a multicolumn index as
112
- * an Index Cond. A mixed order has none, so it is the or-chain — the same split as the entity
113
- * driver's `seekSql`. No null branch in either: `page` refuses a null key before it is a cursor.
114
- */
115
- const seek = (keys: readonly KeysetKey[], position: readonly string[]): SqlFragment => {
116
- const binds = (): SqlFragment[] => keys.map((key, index) => bind(key, position[index] ?? ''));
117
- const [first] = keys;
118
- if (first === undefined) return sql`true`;
119
- if (keys.length === 1) return past(first, bind(first, position[0] ?? ''));
120
- if (keys.every((key) => key.direction === first.direction)) {
121
- const op = raw(first.direction === 'desc' ? '<' : '>');
122
- return sql`(${join(keys.map((key) => key.column))}) ${op} (${join(binds())})`;
123
- }
124
- const terms = keys.map((key, index) => {
125
- const equal = keys
126
- .slice(0, index)
127
- .map((prior, at) => sql`${prior.column} = ${bind(prior, position[at] ?? '')}`);
128
- const term = past(key, bind(key, position[index] ?? ''));
129
- return equal.length === 0 ? term : sql`(${join([...equal, term], ' and ')})`;
130
- });
131
- return sql`(${join(terms, ' or ')})`;
132
- };
133
-
134
- const positionOf = (cursor: string, scope: string, keys: readonly KeysetKey[]): string[] => {
109
+ const positionOf = (cursor: string, scope: string, keys: readonly KeysetKey[]): KeysetPosition => {
135
110
  const { key } = decodeCursor(cursor, scope);
136
- if (key.length !== keys.length || !key.every((part) => typeof part === 'string')) {
111
+ if (key.length !== keys.length) {
137
112
  throw new CursorInvalidError(
138
113
  `it carries ${key.length} key values, this order needs ${keys.length}`,
139
114
  );
140
115
  }
141
- return key as string[];
116
+ return keys.map((spec, at) => {
117
+ const value = decodePart(spec, key[at]);
118
+ if (value === undefined) {
119
+ throw new CursorInvalidError(`key value ${String(at)} is not a position this order can seek`);
120
+ }
121
+ return value;
122
+ });
142
123
  };
143
124
 
144
- /** Every key of `row`, as the text the server answered — refused when one is null. */
145
- const keyText = (row: object, keys: readonly KeysetKey[], index: number): string[] =>
125
+ /** Every key of `row`, as the text the server answered — refused when an undeclared one is null. */
126
+ const keyText = (row: object, keys: readonly KeysetKey[], index: number): (string | null)[] =>
146
127
  keys.map((key, at) => {
147
128
  const value: unknown = Reflect.get(row, aliasOf(at));
148
129
  if (typeof value === 'string') return value;
130
+ if (value === null && key.nullable === true) return null;
149
131
  if (value === null) {
150
132
  throw new DbError({
151
133
  code: 'X_KEYSET_NULL_KEY',
@@ -183,6 +165,7 @@ export function keyset(options: KeysetOptions): Keyset {
183
165
  "keyset({ scope: 'posts.feed', … }) # one name per read, plus its filter arguments",
184
166
  );
185
167
  keys.forEach(assertKey);
168
+ assertTiebreak(keys);
186
169
  const limit = finiteCount('keyset', 'limit', options.limit, 1);
187
170
  const scope = scopeOf(options.scope, keys);
188
171
  const where =
@@ -190,7 +173,7 @@ export function keyset(options: KeysetOptions): Keyset {
190
173
  return {
191
174
  select: join(keys.map((key, at) => sql`${key.column}::text as ${raw(`"${aliasOf(at)}"`)}`)),
192
175
  where,
193
- orderBy: join(keys.map((key) => sql`${key.column} ${orderOf(key)}`)),
176
+ orderBy: join(keys.map(orderOf)),
194
177
  limit: sql`${limit + 1}`,
195
178
  page<Row extends object>(rows: readonly Row[]): Page<KeysetRow<Row>> {
196
179
  const positions = rows.map((row, index) => keyText(row, keys, index));
@@ -199,7 +182,11 @@ export function keyset(options: KeysetOptions): Keyset {
199
182
  const last = positions[limit - 1];
200
183
  const next =
201
184
  rows.length > limit && last !== undefined
202
- ? encodeCursor({ scope, key: last, id: '' })
185
+ ? encodeCursor({
186
+ scope,
187
+ key: last.map((value, at) => encodePart(keys[at], value)),
188
+ id: '',
189
+ })
203
190
  : null;
204
191
  return pageOf(kept, next);
205
192
  },
@@ -4,7 +4,8 @@
4
4
 
5
5
  import {
6
6
  backoffDelay,
7
- isUltimateError,
7
+ type FailureStreak,
8
+ failureStreak,
8
9
  logger,
9
10
  renderThrowable,
10
11
  type Scheduler,
@@ -43,23 +44,9 @@ interface Held {
43
44
  /**
44
45
  * Refused dials since this session last held, across retirements: a restart is ONE streak — one
45
46
  * line when it opens, one when a dial lands (`db.listen.redialed`, with the count), never a line
46
- * per attempt; a refusal with a different cause (`causeOf`) logs again, naming the one it ends.
47
- * Local until core ships a limiter for it.
47
+ * per attempt; a refusal with a different cause logs again, naming the one it ends.
48
48
  */
49
- failures: number;
50
- cause: FailureCause | undefined;
51
- }
52
-
53
- interface FailureCause {
54
- readonly key: string;
55
- readonly label: Readonly<Record<string, string>>;
56
- }
57
-
58
- /** What makes two refusals the same one: the code, or, uncoded, the rendered message. */
59
- function causeOf(error: unknown): FailureCause {
60
- if (isUltimateError(error)) return { key: `code:${error.code}`, label: { code: error.code } };
61
- const message = renderThrowable(error);
62
- return { key: `error:${message}`, label: { error: message } };
49
+ readonly refusals: FailureStreak;
63
50
  }
64
51
 
65
52
  export function poolListeners(
@@ -98,29 +85,11 @@ export function poolListeners(
98
85
  return;
99
86
  }
100
87
  entry.session = session;
101
- if (entry.failures > 0) {
102
- logger.info('db.listen.redialed', { channel: entry.channel, failures: entry.failures });
103
- }
104
- entry.failures = 0;
105
- entry.cause = undefined;
88
+ entry.refusals.passed();
106
89
  },
107
90
  (error: unknown) => {
108
91
  if (overtaken()) return;
109
- const cause = causeOf(error);
110
- if (entry.cause?.key === cause.key) entry.failures += 1;
111
- else {
112
- const ended = entry.cause;
113
- logger.warn('db.listen.redial_failed', {
114
- channel: entry.channel,
115
- attempt,
116
- error: renderThrowable(error),
117
- ...(ended === undefined
118
- ? {}
119
- : { previous: { ...ended.label, failures: entry.failures } }),
120
- });
121
- entry.failures = 1;
122
- entry.cause = cause;
123
- }
92
+ entry.refusals.failed(error, { attempt });
124
93
  // Equal jitter: a fleet that lost its database together must not re-dial it together.
125
94
  const wait = backoffDelay({
126
95
  attempt,
@@ -144,8 +113,12 @@ export function poolListeners(
144
113
  dial: 0,
145
114
  cancelRetry: () => undefined,
146
115
  ended: false,
147
- failures: 0,
148
- cause: undefined,
116
+ refusals: failureStreak({
117
+ event: 'db.listen.redial_failed',
118
+ recoveredEvent: 'db.listen.redialed',
119
+ level: 'warn',
120
+ fields: { channel },
121
+ }),
149
122
  };
150
123
  held.add(entry);
151
124
  try {
@@ -140,8 +140,11 @@ function all<T>(value: unknown, one: (item: unknown) => T | undefined): readonly
140
140
 
141
141
  function trigger(value: unknown): TriggerRecord | undefined {
142
142
  if (!isRow(value)) return undefined;
143
- const { name, install } = value;
144
- return str(name) && strings(install) ? { name, install } : undefined;
143
+ const { name, install, recount } = value;
144
+ if (!str(name) || !strings(install)) return undefined;
145
+ // `recount` arrived in 31.23 on counter triggers; a record written before carries none.
146
+ if (recount === undefined) return { name, install };
147
+ return strings(recount) ? { name, install, recount } : undefined;
145
148
  }
146
149
 
147
150
  function tableOf(value: unknown): TableDescription | undefined {
@@ -0,0 +1,71 @@
1
+ // Single responsibility: the autovacuum half of a `tableStorage()` declaration — the four trigger
2
+ // parameters a small, hot framework table states instead of Postgres' defaults (50 rows plus 20% of
3
+ // the table, more dead rows than such a table holds live ones), validated, rendered and read back.
4
+
5
+ /** When autovacuum visits a table, in Postgres' own terms. Each left out is not this value's. */
6
+ export interface TableAutovacuum {
7
+ /** `autovacuum_vacuum_threshold`: dead rows before a vacuum, before the scale factor. */
8
+ readonly vacuumThreshold?: number;
9
+ /** `autovacuum_vacuum_scale_factor`: the fraction of the table added to the threshold. */
10
+ readonly vacuumScaleFactor?: number;
11
+ /** `autovacuum_analyze_threshold`. */
12
+ readonly analyzeThreshold?: number;
13
+ /** `autovacuum_analyze_scale_factor`. */
14
+ readonly analyzeScaleFactor?: number;
15
+ }
16
+
17
+ /** Declaration key → storage parameter, in the order every rendering uses. */
18
+ const PARAMETERS = {
19
+ vacuumThreshold: 'autovacuum_vacuum_threshold',
20
+ vacuumScaleFactor: 'autovacuum_vacuum_scale_factor',
21
+ analyzeThreshold: 'autovacuum_analyze_threshold',
22
+ analyzeScaleFactor: 'autovacuum_analyze_scale_factor',
23
+ } as const;
24
+
25
+ export type AutovacuumParameter = (typeof PARAMETERS)[keyof typeof PARAMETERS];
26
+
27
+ const INT4_MAX = 2 ** 31 - 1;
28
+
29
+ /**
30
+ * Why a declaration may not be spliced into DDL, or `undefined`. Postgres' own ranges: a threshold
31
+ * is an integer from 0 to `INT_MAX`, a scale factor a finite number from 0 to 100.
32
+ */
33
+ export function autovacuumProblem(autovacuum: TableAutovacuum): string | undefined {
34
+ for (const [key, value] of Object.entries(autovacuum)) {
35
+ if (!Object.hasOwn(PARAMETERS, key))
36
+ return `autovacuum.${key} is not a parameter this declaration knows`;
37
+ if (typeof value !== 'number') return `autovacuum.${key} is not a number`;
38
+ const threshold = key.endsWith('Threshold');
39
+ const fits = threshold
40
+ ? Number.isInteger(value) && value >= 0 && value <= INT4_MAX
41
+ : Number.isFinite(value) && value >= 0 && value <= 100;
42
+ if (!fits) {
43
+ return `autovacuum.${key} ${String(value)} is not ${threshold ? 'an integer from 0 to 2147483647' : 'a number from 0 to 100'}`;
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ /** The declared parameters as `[name, value]`, in rendering order. */
50
+ export function autovacuumEntries(
51
+ autovacuum: TableAutovacuum | undefined,
52
+ ): readonly (readonly [AutovacuumParameter, number])[] {
53
+ if (autovacuum === undefined) return [];
54
+ return Object.entries(PARAMETERS).flatMap(([key, name]) => {
55
+ const value = autovacuum[key as keyof TableAutovacuum];
56
+ return value === undefined ? [] : [[name, value] as const];
57
+ });
58
+ }
59
+
60
+ /** `name = value` for a `with (...)` or `set (...)` list. */
61
+ export const autovacuumSettings = (autovacuum: TableAutovacuum | undefined): readonly string[] =>
62
+ autovacuumEntries(autovacuum).map(([name, value]) => `${name} = ${String(value)}`);
63
+
64
+ /** One option off `reloptions` joined by `, ` (`fillfactor=70, autovacuum_enabled=false`), or `null`. */
65
+ export function reloption(options: string | null, key: string): string | null {
66
+ for (const option of (options ?? '').split(',')) {
67
+ const [name, value] = option.trim().split('=');
68
+ if (name === key && value !== undefined) return value;
69
+ }
70
+ return null;
71
+ }
@@ -0,0 +1,124 @@
1
+ // Single responsibility: a `tableStorage()` declaration against the catalog — what `pg_class` holds
2
+ // for each declared parameter, every difference with the statement that converges it. Split from
3
+ // `table-storage.ts`, which declares and renders.
4
+
5
+ import type { DbClient } from './client';
6
+ import { psqlCommand } from './dependent-view';
7
+ import { sql } from './sql';
8
+ import type { AutovacuumParameter } from './table-autovacuum';
9
+ import { autovacuumEntries, reloption } from './table-autovacuum';
10
+ import type { TableStorage } from './table-storage';
11
+ import { storageAlters } from './table-storage';
12
+
13
+ /** What the catalog holds for one table — `CatalogTable` satisfies it. `options` is `reloptions` joined. */
14
+ export interface LiveTableStorage {
15
+ readonly unlogged: boolean;
16
+ readonly options: string | null;
17
+ }
18
+
19
+ export interface TableStorageDifference {
20
+ readonly table: string;
21
+ readonly parameter: 'table' | 'persistence' | 'fillfactor' | AutovacuumParameter;
22
+ readonly declared: string;
23
+ readonly live: string;
24
+ /** The statement that converges it, as SQL — `null` for a missing table, which `x db migrate` creates. */
25
+ readonly statement: string | null;
26
+ /** A command that runs as written: `psql … -c '<statement>'`, or `x db migrate`. */
27
+ readonly fix: string;
28
+ }
29
+
30
+ /**
31
+ * The statement and the line that runs it. `psqlCommand` quotes it as one shell word, and the name
32
+ * inside is the bare lower-case identifier `tableStorage` admitted, so nothing in it is shell-active.
33
+ */
34
+ const converge = (alter: string | undefined): { statement: string; fix: string } => {
35
+ const statement = `${alter ?? ''};`;
36
+ return { statement, fix: `${psqlCommand(statement)} # then x db migrate, which re-checks` };
37
+ };
38
+
39
+ /** Only what the declaration states is compared: a parameter left out is not this value's to judge. */
40
+ export function tableStorageDrift(
41
+ storage: TableStorage,
42
+ live: LiveTableStorage | undefined,
43
+ ): readonly TableStorageDifference[] {
44
+ const { table } = storage;
45
+ if (live === undefined) {
46
+ return [
47
+ {
48
+ table,
49
+ parameter: 'table',
50
+ declared: 'present',
51
+ live: 'absent',
52
+ statement: null,
53
+ fix: 'x db migrate',
54
+ },
55
+ ];
56
+ }
57
+ const alters = storageAlters(storage);
58
+ const differences: TableStorageDifference[] = [];
59
+ if (storage.unlogged !== undefined && storage.unlogged !== live.unlogged) {
60
+ const persistence = (unlogged: boolean): string => (unlogged ? 'unlogged' : 'logged');
61
+ differences.push({
62
+ table,
63
+ parameter: 'persistence',
64
+ declared: persistence(storage.unlogged),
65
+ live: persistence(live.unlogged),
66
+ ...converge(alters.find((alter) => /set (un)?logged$/.test(alter))),
67
+ });
68
+ }
69
+ const fillfactor = reloption(live.options, 'fillfactor');
70
+ // A number, as below: a hand-written `fillfactor = 080` is held as that text.
71
+ if (storage.fillfactor !== undefined && Number(fillfactor ?? Number.NaN) !== storage.fillfactor) {
72
+ differences.push({
73
+ table,
74
+ parameter: 'fillfactor',
75
+ declared: String(storage.fillfactor),
76
+ live: fillfactor ?? 'default (100)',
77
+ ...converge(alters.find((alter) => alter.includes('fillfactor'))),
78
+ });
79
+ }
80
+ // Compared as numbers: the catalog keeps the text the alter was written with.
81
+ for (const [parameter, value] of autovacuumEntries(storage.autovacuum)) {
82
+ const held = reloption(live.options, parameter);
83
+ if (held !== null && Number(held) === value) continue;
84
+ differences.push({
85
+ table,
86
+ parameter,
87
+ declared: String(value),
88
+ live: held ?? 'default',
89
+ ...converge(alters.find((alter) => alter.includes('autovacuum_'))),
90
+ });
91
+ }
92
+ return differences;
93
+ }
94
+
95
+ interface StorageRow {
96
+ readonly name: string;
97
+ readonly persistence: string;
98
+ readonly options: string | null;
99
+ }
100
+
101
+ /**
102
+ * Every declaration against the catalog, in ONE read — the reading `catalog-relations.ts` does
103
+ * (`relpersistence`, `reloptions` joined by `, `), narrowed to the named tables of `current_schema()`.
104
+ */
105
+ export async function readTableStorageDrift(
106
+ client: DbClient,
107
+ storages: readonly TableStorage[],
108
+ ): Promise<readonly TableStorageDifference[]> {
109
+ if (storages.length === 0) return [];
110
+ const rows = await client.query<StorageRow>(sql`
111
+ select c.relname as name, c.relpersistence as persistence,
112
+ array_to_string(c.reloptions, ', ') as options
113
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
114
+ where n.nspname = current_schema() and c.relkind in ('r', 'p')
115
+ and c.relname = any(${storages.map((storage) => storage.table)}::text[])`);
116
+ const live = new Map(rows.map((row) => [row.name, row]));
117
+ return storages.flatMap((storage) => {
118
+ const row = live.get(storage.table);
119
+ return tableStorageDrift(
120
+ storage,
121
+ row === undefined ? undefined : { unlogged: row.persistence === 'u', options: row.options },
122
+ );
123
+ });
124
+ }
@@ -1,7 +1,8 @@
1
- // Single responsibility: a framework-owned table's storage parameters (`fillfactor`, `unlogged`) as
2
- // ONE declared value — rendered into its `create table`, re-applied to an existing table by
3
- // idempotent `alter`s at framework-schema apply, and compared against `pg_class` by drift. Before
4
- // it, framework DDL was fixed strings and nothing could state either parameter.
1
+ // Single responsibility: a framework-owned table's storage parameters (`fillfactor`, `unlogged`,
2
+ // `table-autovacuum.ts`' triggers) as ONE declared value — rendered into its `create table`,
3
+ // re-applied by idempotent `alter`s at framework-schema apply, compared against `pg_class` by drift.
4
+ //
5
+ // Before it, framework DDL was fixed strings and nothing could state either parameter.
5
6
  //
6
7
  // The API, as a framework package uses it (`@ultimat3/http`'s `x_rate_limit`, `@ultimat3/jobs`):
7
8
  //
@@ -16,23 +17,28 @@
16
17
  //
17
18
  // tableStorageDrift(storage, catalogTable) — pure: declared vs one `CatalogTable`
18
19
  // readTableStorageDrift(client, [storage, …]) — one `pg_class` read, every difference
20
+ //
21
+ // Both drift readers live in `table-storage-drift.ts`.
19
22
 
20
- import type { DbClient } from './client';
21
- import { psqlCommand } from './dependent-view';
22
23
  import { DbError } from './errors';
23
- import { sql } from './sql';
24
+ import type { TableAutovacuum } from './table-autovacuum';
25
+ import { autovacuumProblem, autovacuumSettings } from './table-autovacuum';
24
26
 
25
27
  export interface TableStorageOptions {
26
28
  /** 10–100, Postgres' own range. Left out: the table's fillfactor is not this declaration's. */
27
29
  readonly fillfactor?: number;
28
30
  /** `true` unlogged, `false` logged (stated, e.g. a table that must survive a crash). Left out: neither. */
29
31
  readonly unlogged?: boolean;
32
+ /** When autovacuum visits the table. Left out: Postgres' defaults, never judged. */
33
+ readonly autovacuum?: TableAutovacuum;
30
34
  }
31
35
 
32
36
  export interface TableStorage {
33
37
  readonly table: string;
34
38
  readonly fillfactor: number | undefined;
35
39
  readonly unlogged: boolean | undefined;
40
+ /** Optional, so a `TableStorage` written before 31.25 still compiles. */
41
+ readonly autovacuum?: TableAutovacuum | undefined;
36
42
  }
37
43
 
38
44
  /**
@@ -49,7 +55,7 @@ const storageInvalid = (table: string, what: string): DbError =>
49
55
  new DbError({
50
56
  code: 'X_SQL_UNSAFE',
51
57
  cause: `tableStorage(${JSON.stringify(table)}): ${what}`,
52
- fix: "tableStorage('x_rate_limit', { fillfactor: 70, unlogged: true }) # a bare lower-case name, an integer fillfactor 10-100",
58
+ fix: "tableStorage('x_rate_limit', { fillfactor: 70, unlogged: true }) # a bare lower-case name, an integer fillfactor 10-100, autovacuum thresholds integers 0-2147483647 and scale factors 0-100",
53
59
  meta: { table },
54
60
  });
55
61
 
@@ -68,7 +74,15 @@ export function tableStorage(table: string, options: TableStorageOptions): Table
68
74
  `fillfactor ${String(fillfactor)} is not an integer from 10 to 100`,
69
75
  );
70
76
  }
71
- return Object.freeze({ table, fillfactor, unlogged: options.unlogged });
77
+ const autovacuum = options.autovacuum;
78
+ const problem = autovacuum === undefined ? undefined : autovacuumProblem(autovacuum);
79
+ if (problem !== undefined) throw storageInvalid(table, problem);
80
+ return Object.freeze({
81
+ table,
82
+ fillfactor,
83
+ unlogged: options.unlogged,
84
+ autovacuum: autovacuum === undefined ? undefined : Object.freeze({ ...autovacuum }),
85
+ });
72
86
  }
73
87
 
74
88
  /**
@@ -86,6 +100,10 @@ export function storageAlters(storage: TableStorage): readonly string[] {
86
100
  if (storage.unlogged !== undefined) {
87
101
  alters.push(`alter table ${storage.table} set ${storage.unlogged ? 'unlogged' : 'logged'}`);
88
102
  }
103
+ const autovacuum = autovacuumSettings(storage.autovacuum);
104
+ if (autovacuum.length > 0) {
105
+ alters.push(`alter table ${storage.table} set (${autovacuum.join(', ')})`);
106
+ }
89
107
  return alters;
90
108
  }
91
109
 
@@ -106,117 +124,11 @@ function columnBody(columns: string): string {
106
124
  */
107
125
  export function tableDdl(storage: TableStorage, columns: string): string {
108
126
  const head = storage.unlogged === true ? 'create unlogged table' : 'create table';
109
- const options =
110
- storage.fillfactor === undefined ? '' : ` with (fillfactor = ${String(storage.fillfactor)})`;
127
+ const settings = [
128
+ ...(storage.fillfactor === undefined ? [] : [`fillfactor = ${String(storage.fillfactor)}`]),
129
+ ...autovacuumSettings(storage.autovacuum),
130
+ ];
131
+ const options = settings.length === 0 ? '' : ` with (${settings.join(', ')})`;
111
132
  const create = `${head} if not exists ${storage.table} (\n${columnBody(columns)}\n)${options};`;
112
133
  return [create, ...storageAlters(storage).map((alter) => `${alter};`)].join('\n');
113
134
  }
114
-
115
- /** What the catalog holds for one table — `CatalogTable` satisfies it. `options` is `reloptions` joined. */
116
- export interface LiveTableStorage {
117
- readonly unlogged: boolean;
118
- readonly options: string | null;
119
- }
120
-
121
- export interface TableStorageDifference {
122
- readonly table: string;
123
- readonly parameter: 'table' | 'persistence' | 'fillfactor';
124
- readonly declared: string;
125
- readonly live: string;
126
- /** The statement that converges it, as SQL — `null` for a missing table, which `x db migrate` creates. */
127
- readonly statement: string | null;
128
- /** A command that runs as written: `psql … -c '<statement>'`, or `x db migrate`. */
129
- readonly fix: string;
130
- }
131
-
132
- /** `fillfactor=70, autovacuum_enabled=false` → `70`; absent → `null` (the server default, 100). */
133
- const liveFillfactor = (options: string | null): string | null => {
134
- for (const option of (options ?? '').split(',')) {
135
- const [key, value] = option.trim().split('=');
136
- if (key === 'fillfactor' && value !== undefined) return value;
137
- }
138
- return null;
139
- };
140
-
141
- /**
142
- * The statement and the line that runs it. `psqlCommand` quotes it as one shell word, and the name
143
- * inside is the bare lower-case identifier `tableStorage` admitted, so nothing in it is shell-active.
144
- */
145
- const converge = (alter: string | undefined): { statement: string; fix: string } => {
146
- const statement = `${alter ?? ''};`;
147
- return { statement, fix: `${psqlCommand(statement)} # then x db migrate, which re-checks` };
148
- };
149
-
150
- /** Only what the declaration states is compared: a parameter left out is not this value's to judge. */
151
- export function tableStorageDrift(
152
- storage: TableStorage,
153
- live: LiveTableStorage | undefined,
154
- ): readonly TableStorageDifference[] {
155
- const { table } = storage;
156
- if (live === undefined) {
157
- return [
158
- {
159
- table,
160
- parameter: 'table',
161
- declared: 'present',
162
- live: 'absent',
163
- statement: null,
164
- fix: 'x db migrate',
165
- },
166
- ];
167
- }
168
- const alters = storageAlters(storage);
169
- const differences: TableStorageDifference[] = [];
170
- if (storage.unlogged !== undefined && storage.unlogged !== live.unlogged) {
171
- const persistence = (unlogged: boolean): string => (unlogged ? 'unlogged' : 'logged');
172
- differences.push({
173
- table,
174
- parameter: 'persistence',
175
- declared: persistence(storage.unlogged),
176
- live: persistence(live.unlogged),
177
- ...converge(alters.find((alter) => /set (un)?logged$/.test(alter))),
178
- });
179
- }
180
- const fillfactor = liveFillfactor(live.options);
181
- if (storage.fillfactor !== undefined && String(storage.fillfactor) !== fillfactor) {
182
- differences.push({
183
- table,
184
- parameter: 'fillfactor',
185
- declared: String(storage.fillfactor),
186
- live: fillfactor ?? 'default (100)',
187
- ...converge(alters.find((alter) => alter.includes('fillfactor'))),
188
- });
189
- }
190
- return differences;
191
- }
192
-
193
- interface StorageRow {
194
- readonly name: string;
195
- readonly persistence: string;
196
- readonly options: string | null;
197
- }
198
-
199
- /**
200
- * Every declaration against the catalog, in ONE read — the reading `catalog-relations.ts` does
201
- * (`relpersistence`, `reloptions` joined by `, `), narrowed to the named tables of `current_schema()`.
202
- */
203
- export async function readTableStorageDrift(
204
- client: DbClient,
205
- storages: readonly TableStorage[],
206
- ): Promise<readonly TableStorageDifference[]> {
207
- if (storages.length === 0) return [];
208
- const rows = await client.query<StorageRow>(sql`
209
- select c.relname as name, c.relpersistence as persistence,
210
- array_to_string(c.reloptions, ', ') as options
211
- from pg_class c join pg_namespace n on n.oid = c.relnamespace
212
- where n.nspname = current_schema() and c.relkind in ('r', 'p')
213
- and c.relname = any(${storages.map((storage) => storage.table)}::text[])`);
214
- const live = new Map(rows.map((row) => [row.name, row]));
215
- return storages.flatMap((storage) => {
216
- const row = live.get(storage.table);
217
- return tableStorageDrift(
218
- storage,
219
- row === undefined ? undefined : { unlogged: row.persistence === 'u', options: row.options },
220
- );
221
- });
222
- }