@ultimat3/entity 31.35.0 → 31.36.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.35.0",
3
+ "version": "31.36.0",
4
4
  "description": "A table + its domain type + invariants the database also enforces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -44,9 +44,9 @@
44
44
  "test": "bun test"
45
45
  },
46
46
  "dependencies": {
47
- "@ultimat3/core": "31.35.0",
48
- "@ultimat3/db": "31.35.0",
49
- "@ultimat3/schema": "31.35.0",
50
- "@ultimat3/time": "31.35.0"
47
+ "@ultimat3/core": "31.36.0",
48
+ "@ultimat3/db": "31.36.0",
49
+ "@ultimat3/schema": "31.36.0",
50
+ "@ultimat3/time": "31.36.0"
51
51
  }
52
52
  }
@@ -48,6 +48,6 @@ export const refuseNul = (value: string): string =>
48
48
  ? refuseColumn(
49
49
  'format',
50
50
  `expected text without a NUL character (U+0000), ${got(value)} that contains one`,
51
- "strip it at the call site — value.replaceAll('\\u0000', '') — Postgres text cannot store U+0000; binary content is bytea()",
51
+ "value.replaceAll('\\u0000', '') // strip it at the call site — Postgres text cannot store U+0000; binary content is bytea()",
52
52
  )
53
53
  : value;
package/src/column.ts CHANGED
@@ -164,7 +164,7 @@ const literal = (value: unknown): ColumnDefault => {
164
164
  return refuseColumn(
165
165
  'default',
166
166
  `a default must be a literal; got ${typeof value}`,
167
- ".default('draft'), .default(0) or .default(false) — a literal the DDL can carry; for an instant use timestamp().defaultNow(), and a computed default belongs in the insert",
167
+ "text().default('draft') // or .default(0), .default(false): a literal the DDL can carry; for an instant use timestamp().defaultNow(), and a computed default belongs in the insert",
168
168
  );
169
169
  };
170
170
 
@@ -317,7 +317,7 @@ export const assertColumnName = (name: string): string => {
317
317
  refuseColumn(
318
318
  'column-name',
319
319
  `"${name}" is not a physical column name: lower-case letters, digits and underscores, at most 63 of them`,
320
- ".column('created_at') — lower-case letters, digits and underscores, at most 63 of them",
320
+ "text().column('created_at') // lower-case letters, digits and underscores, at most 63 of them",
321
321
  );
322
322
  }
323
323
  return name;
@@ -43,7 +43,7 @@ export const json = <T>(schema: StandardSchemaV1<unknown, T>): Column<T> =>
43
43
  return refuseColumn(
44
44
  'json',
45
45
  `does not match the column's schema — ${formatIssues(result.issues).join('; ')}`,
46
- 'correct the key the cause names, or widen the schema this column was declared with — json(t.object({ seats: t.number })) validates on the way in and on the way back',
46
+ 'json(t.object({ seats: t.number })) // widen the schema this column was declared with, or correct the key the cause names — it validates on the way in and on the way back',
47
47
  );
48
48
  },
49
49
  { schema },
@@ -77,7 +77,7 @@ const int8 = (digits: string): string => {
77
77
  : refuseColumn(
78
78
  'bigint',
79
79
  'the value is past the int8 range (-2^63 to 2^63 - 1), which Postgres answers 22003 for',
80
- 'declare the column decimal({ precision: 40, scale: 0 }) — a numeric holds whole numbers past int8 — and run x db gen "widen the bigint to numeric"',
80
+ 'decimal({ precision: 40, scale: 0 }) // declare the column so — a numeric holds whole numbers past int8 — then run x db gen "widen the bigint to numeric"',
81
81
  );
82
82
  };
83
83
 
@@ -116,7 +116,7 @@ export const bigint = (): Column<string> =>
116
116
  : refuseColumn(
117
117
  'bigint',
118
118
  `${String(value)} is past ±2^53, where a JS number is no longer exact`,
119
- "quote the digits — bigint() takes and returns a decimal string, so pass '9007199254740993' rather than a number literal",
119
+ "insert({ amount: '9007199254740993' }) // quote the digits — bigint() takes and returns a decimal string, never a number literal",
120
120
  );
121
121
  }
122
122
  return typeof value === 'string' && DIGITS.test(value)
@@ -178,7 +178,7 @@ export const decimal = (options: DecimalOptions = {}): Column<string> => {
178
178
  return refuseColumn(
179
179
  'numeric',
180
180
  `expected a decimal number, ${got(value)}`,
181
- "pass the digits as a string — decimal() holds an exact decimal, so write '1.25'; a float is taken only where String(value) is already exact",
181
+ "insert({ amount: '1.25' }) // the digits as a string — decimal() holds an exact decimal; a float is taken only where String(value) is already exact",
182
182
  );
183
183
  }
184
184
  const digits = text.replace('-', '').split('.');
@@ -197,7 +197,7 @@ export const decimal = (options: DecimalOptions = {}): Column<string> => {
197
197
  return refuseColumn(
198
198
  'numeric',
199
199
  `${text} does not fit numeric(${precision}, ${scale ?? 0})`,
200
- `widen the column — decimal({ precision: ${whole + (scale ?? 0)}, scale: ${scale ?? 0} }) — and run x db gen "widen the numeric": what overflows is the digits BEFORE the point`,
200
+ `decimal({ precision: ${whole + (scale ?? 0)}, scale: ${scale ?? 0} }) // widen the column, then run x db gen "widen the numeric": what overflows is the digits BEFORE the point`,
201
201
  );
202
202
  }
203
203
  return canonicalDecimal(text, scale);
@@ -232,7 +232,7 @@ export const date = (): Column<PlainDate> =>
232
232
  ? refuseColumn(
233
233
  'date',
234
234
  `expected a calendar date, ${got(value)}`,
235
- "pass a Date built from a real value — new Date('2026-08-22'); new Date(undefined) and a failed parse both produce the Invalid Date this refuses",
235
+ "new Date('2026-08-22') // a Date built from a real value; new Date(undefined) and a failed parse both produce the Invalid Date this refuses",
236
236
  )
237
237
  : plainDateUtc(value);
238
238
  }
@@ -241,7 +241,7 @@ export const date = (): Column<PlainDate> =>
241
241
  : refuseColumn(
242
242
  'date',
243
243
  `expected a YYYY-MM-DD calendar date, ${got(value)}`,
244
- "pass '2026-08-22' or a Date — date() stores a calendar date with no clock and no zone; an instant is timestamp()",
244
+ "insert({ day: '2026-08-22' }) // a YYYY-MM-DD string or a Date — date() stores a calendar date with no clock and no zone; an instant is timestamp()",
245
245
  );
246
246
  });
247
247
 
@@ -281,7 +281,7 @@ export const arrayOf = <T>(element: Column<T>): Column<readonly T[]> => {
281
281
  return refuseColumn(
282
282
  'array',
283
283
  `expected an array, ${got(value)}`,
284
- 'wrap it — [value] — or drop arrayOf() and declare the element column on its own when the table holds one scalar',
284
+ '[value] // wrap it — or drop arrayOf() and declare the element column on its own when the table holds one scalar',
285
285
  );
286
286
  }
287
287
  return value.map((member) => element.$parse(member));
@@ -47,7 +47,7 @@ export const text = (options: TextOptions = {}): TextColumn => {
47
47
  return refuseColumn(
48
48
  'length',
49
49
  `expected at most ${max} characters, got ${charCount(value)}`,
50
- `truncate at the call site, or widen the column — text({ max: ${charCount(value)} }) — and run x db gen "widen the text"`,
50
+ `text({ max: ${charCount(value)} }) // widen the column, then run x db gen "widen the text" — or truncate at the call site`,
51
51
  );
52
52
  }
53
53
  return refuseNul(value);
@@ -81,6 +81,6 @@ export const boolean = (): Column<boolean> =>
81
81
  : refuseColumn(
82
82
  'type',
83
83
  `expected a boolean, ${got(value)}`,
84
- "value === 'true' at the call site for a text flag, and boolean().nullable() when the column has a third state",
84
+ "boolean().nullable() // when the column has a third state — and value === 'true' at the call site for a text flag",
85
85
  ),
86
86
  );
package/src/columns.ts CHANGED
@@ -101,7 +101,7 @@ const parseInstant = (value: unknown): Date => {
101
101
  return refuseColumn(
102
102
  'format',
103
103
  `expected a UTC instant — a Date, epoch milliseconds, or an ISO-8601 string with Z or an offset — ${got(value)}`,
104
- "'2026-03-14T09:00:00Z' or a Date — timestamp() stores an instant, so a string must name its zone; a calendar date with no clock is date(), and an elapsed span is integer()",
104
+ "new Date('2026-03-14T09:00:00Z') // or that ISO string — timestamp() stores an instant, so a string must name its zone; a calendar date is date(), an elapsed span integer()",
105
105
  );
106
106
  };
107
107
 
@@ -143,7 +143,7 @@ export const url = (): Column<string> =>
143
143
  return refuseColumn(
144
144
  'format',
145
145
  `expected an absolute http(s) URL, ${got(value)}`,
146
- 'prefix the value with https:// — url() stores an absolute http(s) URL; a path, a template or a mailto: address is text()',
146
+ "new URL('https://' + value).href // prefix the value with https:// — url() stores an absolute http(s) URL; a path, a template or a mailto: address is text()",
147
147
  );
148
148
  },
149
149
  { check: (name) => `${name} ~ '^https?://'` },
@@ -189,7 +189,7 @@ export const tz = <const Z extends readonly string[]>(zones: Z): Column<Z[number
189
189
  : refuseColumn(
190
190
  'iana-tz',
191
191
  `expected one of ${zones.join(' | ')}, ${got(value)}`,
192
- 'store one of the zones tz() declares, or add it to that list and run x db gen "extend the time zone check" — the zones are a CHECK constraint',
192
+ `tz([${zones.map((zone) => JSON.stringify(zone)).join(', ')}, …]) // add the zone to this list, then: x db gen "extend the time zone check" — or store one of these; they are a CHECK constraint`,
193
193
  ),
194
194
  { values: zones, check: oneOf(zones) },
195
195
  );
@@ -223,7 +223,7 @@ export const locale = <const L extends readonly string[]>(locales: L): Column<L[
223
223
  : refuseColumn(
224
224
  'bcp-47',
225
225
  `expected one of ${locales.join(' | ')}, ${got(value)}`,
226
- 'store one of the tags locale() declares, or add it to that list and run x db gen "extend the locale check" — the tags are a CHECK constraint',
226
+ `locale([${locales.map((tag) => JSON.stringify(tag)).join(', ')}, …]) // add the tag to this list, then: x db gen "extend the locale check" — or store one of these; they are a CHECK constraint`,
227
227
  ),
228
228
  { values: locales, check: oneOf(locales) },
229
229
  );
@@ -250,7 +250,7 @@ const parseMinor = (value: unknown): number => {
250
250
  return refuseColumn(
251
251
  'money-minor-units',
252
252
  `expected integer minor units, ${got(value)}`,
253
- "pass integer minor units — { minor: 1234, currency: 'EUR' } is 12.34 EUR; a formatted amount is text() and an exact decimal is decimal()",
253
+ "{ minor: 1234, currency: 'EUR' } // integer minor units: 12.34 EUR; a formatted amount is text() and an exact decimal is decimal()",
254
254
  );
255
255
  }
256
256
  if (!Number.isInteger(minor)) {
@@ -265,7 +265,7 @@ const parseMinor = (value: unknown): number => {
265
265
  'money-minor-units',
266
266
  `${String(value)} is past ±2^53 and no JS number holds it exactly — money is minor units ` +
267
267
  'inside that range',
268
- "split the amount across rows, or hold the digits beside it in a bigint() column — money()'s minor is a number so JSON.stringify carries it, and no JS number holds this one exactly",
268
+ "bigint() // a column beside it holding the digits — or split the amount across rows: money()'s minor is a number so JSON.stringify carries it, and no JS number holds this one exactly",
269
269
  );
270
270
  }
271
271
  return minor;
@@ -283,7 +283,7 @@ const parseCurrency = (value: unknown): string =>
283
283
  : refuseColumn(
284
284
  'iso-4217',
285
285
  `expected a 3-letter ISO-4217 code, ${got(value)}`,
286
- "pass money() a 3-letter uppercase ISO-4217 code — { minor: 1234, currency: 'EUR' }; a symbol or a currency name is not one",
286
+ "{ minor: 1234, currency: 'EUR' } // money() takes a 3-letter uppercase ISO-4217 code; a symbol or a currency name is not one",
287
287
  );
288
288
 
289
289
  /**
@@ -299,7 +299,7 @@ const parseScale = (value: unknown): number => {
299
299
  : refuseColumn(
300
300
  'money-scale',
301
301
  `expected a whole number of decimal places between 0 and ${MAX_MONEY_SCALE}, ${got(value)}`,
302
- `omit scale for the currency's own minor unit, or pass money() a whole number of decimal places from 0 to ${MAX_MONEY_SCALE} — { minor: 1250000, currency: 'EUR', scale: 6 }`,
302
+ `{ minor: 1250000, currency: 'EUR', scale: 6 } // money() takes a whole number of decimal places from 0 to ${MAX_MONEY_SCALE} — or omit scale for the currency's own minor unit`,
303
303
  );
304
304
  };
305
305
 
@@ -29,7 +29,7 @@ export const enumerated = <const V extends readonly string[]>(values: V): Enumer
29
29
  : refuseColumn(
30
30
  'enum',
31
31
  `expected one of ${values.join(' | ')}, ${got(value)}`,
32
- 'store one of the values enumerated() declares, or add the new variant to that list and run x db gen "extend the enum check" — the values are a CHECK constraint, so the table moves with them',
32
+ `enumerated([${values.map((value) => JSON.stringify(value)).join(', ')}, …]) // add the new variant to this list, then: x db gen "extend the enum check" — or store one of these; they are a CHECK constraint, so the table moves with them`,
33
33
  );
34
34
  return enumeratedWith<V, false>(
35
35
  { ...BARE, kind: 'text', values, check: oneOf(values) },
@@ -63,7 +63,7 @@ const enumeratedWith = <V extends readonly string[], Optional extends boolean>(
63
63
  refuseColumn(
64
64
  'transitions',
65
65
  'a state machine column may not hold null — null is not one of the declared states',
66
- 'drop .nullable() from this column, or drop .transitions() — a row outside every state has no legal move',
66
+ "enumerated(['draft', 'published']).transitions({ draft: ['published'], published: [] }) // without .nullable(): a row outside every state has no legal move — or drop .transitions()",
67
67
  );
68
68
  }
69
69
  return enumeratedWith<V, Optional>(
@@ -80,7 +80,7 @@ const enumeratedWith = <V extends readonly string[], Optional extends boolean>(
80
80
  refuseColumn(
81
81
  'transitions',
82
82
  'a state machine column may not hold null — null is not one of the declared states',
83
- 'drop .nullable() from this column, or drop .transitions() — a row outside every state has no legal move',
83
+ "enumerated(['draft', 'published']).transitions({ draft: ['published'], published: [] }) // without .nullable(): a row outside every state has no legal move — or drop .transitions()",
84
84
  );
85
85
  }
86
86
  return base.nullable();
package/src/errors.ts CHANGED
@@ -70,8 +70,8 @@ export const tenancyUnscoped = (
70
70
  : `${entityName}.${operation}() was checked against a plan with no org predicate, though the acting actor's tenant is ${renderValue(actorOrg)} — a plan is verified here, never rewritten, so the tenant had to be on it already`,
71
71
  fix:
72
72
  actorOrg === undefined
73
- ? `run it inside runWithContext(ctxOf({ actor: userActor({ id, orgId }) }), fn) — the actor's org scopes the plan — or name the tenant: ${entityName}.${operation}({ orgId }), which orgScoped(plan, orgId) is the plan-level form of`
74
- : `build the plan with scopedPlan('${entityName}', tenantColumn, '${operation}', plan) — it applies the actor's tenant — or add the predicate first: orgScoped(plan, ${asLiteral(actorOrg, "'<org>'")})`,
73
+ ? `runWithContext(ctxOf({ actor: userActor({ id, orgId }) }), fn) // the actor's org scopes the plan — or name the tenant: ${entityName}.${operation}({ orgId }), which orgScoped(plan, orgId) is the plan-level form of`
74
+ : `scopedPlan('${entityName}', tenantColumn, '${operation}', plan) // applies the actor's tenant — or add the predicate first: orgScoped(plan, ${asLiteral(actorOrg, "'<org>'")})`,
75
75
  });
76
76
 
77
77
  /**
@@ -97,7 +97,7 @@ export const tenancyActorMismatch = (init: {
97
97
  return new EntityError({
98
98
  code: 'X_TENANCY_ACTOR_MISMATCH',
99
99
  cause: `${init.entityName}.${init.operation}() was scoped to tenant ${renderValue(init.named)} but the acting actor's tenant is ${renderValue(init.actorOrg)}`,
100
- fix: `drop the orgId argument from ${init.entityName}.${init.operation}() — the actor's tenant scopes it — or act as that tenant: withChildContext({ actor: userActor({ id, orgId: ${asLiteral(init.named, "'<org>'")} }) }, fn). A read that must span tenants is crossTenant('<why>', fn)`,
100
+ fix: `withChildContext({ actor: userActor({ id, orgId: ${asLiteral(init.named, "'<org>'")} }) }, fn) // act as that tenant — or drop the orgId argument from ${init.entityName}.${init.operation}(): the actor's tenant scopes it. A read that must span tenants is crossTenant('<why>', fn)`,
101
101
  });
102
102
  };
103
103
 
@@ -123,7 +123,7 @@ export const tenancyRowMismatch = (init: {
123
123
  // A row literal is the least constrained input in the framework — this guard runs BEFORE
124
124
  // `$assert`, on purpose, so the value has been through no parse at all when it is rendered.
125
125
  cause: `${init.entityName}.${init.operation}() would write ${init.column} ${renderValue(init.named)} but the acting actor's tenant is ${renderValue(init.actorOrg)}`,
126
- fix: `set ${init.column} to ${asLiteral(init.actorOrg, "'<org>'")} in the row passed to ${init.entityName}.${init.operation}(), or write into another tenant deliberately: crossTenant('<why>', fn)`,
126
+ fix: `{ ${init.column}: ${asLiteral(init.actorOrg, "'<org>'")} } // in the row passed to ${init.entityName}.${init.operation}() — or write into another tenant deliberately: crossTenant('<why>', fn)`,
127
127
  });
128
128
 
129
129
  /**
@@ -143,7 +143,7 @@ export const tenancyActorOrgRequired = (init: {
143
143
  new EntityError({
144
144
  code: 'X_TENANCY_ACTOR_ORG_REQUIRED',
145
145
  cause: `${init.entityName}.${init.operation}() reads a tenant-scoped entity, but the ${init.actorKind} actor ${renderValue(init.actorId)} carries no orgId — there is no tenant to scope it to`,
146
- fix: `mint the actor with its tenant at the request boundary — userActor({ id: ${asLiteral(init.actorId, "'<actor id>'")}, orgId: '<org>' }) — or, for a sweep that legitimately spans tenants, crossTenant('<why>', fn)`,
146
+ fix: `userActor({ id: ${asLiteral(init.actorId, "'<actor id>'")}, orgId: '<org>' }) // mint the actor with its tenant at the request boundary — or, for a sweep that legitimately spans tenants, crossTenant('<why>', fn)`,
147
147
  });
148
148
 
149
149
  /**
@@ -159,7 +159,7 @@ export const crossTenantDenied = (init: {
159
159
  new EntityError({
160
160
  code: 'X_TENANCY_CROSS_DENIED',
161
161
  cause: `crossTenant(${JSON.stringify(init.reason)}) was entered by ${init.actor}, which does not carry the ${JSON.stringify(init.scope)} scope`,
162
- fix: `grant the capability where the actor is minted — serviceActor({ id: 'reconciler', scopes: ['${init.scope}'] }) — and run the sweep inside runWithContext(ctxOf({ actor }), fn); an ordinary request scopes to its own tenant instead and needs no crossTenant()`,
162
+ fix: `serviceActor({ id: 'reconciler', scopes: ['${init.scope}'] }) // grant the capability where the actor is minted, then run the sweep inside runWithContext(ctxOf({ actor }), fn); an ordinary request scopes to its own tenant instead and needs no crossTenant()`,
163
163
  });
164
164
 
165
165
  /**
@@ -343,7 +343,7 @@ export const nPlusOneQuery = (subject: string, count: number, batch: QueryLoopBa
343
343
  ? preloadCalls(batch.candidates)
344
344
  : batch.form === 'in'
345
345
  ? `db.${batch.entity}.andWhere('id', 'in', ids).all() # read the set once, then look each row up in memory`
346
- : `send one statement for the set — "where <key> = any($1)" — or expectedQueryLoop('<why one per row is optimal>', fn) when the loop is deliberate`,
346
+ : `SELECT … WHERE <key> = any($1) -- one statement for the set — or expectedQueryLoop('<why one per row is optimal>', fn) when the loop is deliberate`,
347
347
  });
348
348
 
349
349
  /** The same loop, writing. One statement per row is one round trip and one transaction entry each. */
@@ -354,5 +354,5 @@ export const nPlusOneWrite = (subject: string, count: number, batch: WriteLoopBa
354
354
  fix:
355
355
  batch.form === 'bulk'
356
356
  ? `${bulkWriteCall(batch.entity, batch.op)} # one statement for the whole set`
357
- : `send one statement for the set — "insert … values" over every row, or "update … where id = any($1)" — or expectedQueryLoop('<why one per row is optimal>', fn) when the loop is deliberate`,
357
+ : `INSERT … VALUES (…), (…) -- one statement over every row, or UPDATE … WHERE id = any($1) — or expectedQueryLoop('<why one per row is optimal>', fn) when the loop is deliberate`,
358
358
  });
package/src/expr.ts CHANGED
@@ -135,7 +135,7 @@ const matchOperator = (pattern: RegExp): string => {
135
135
  'matches',
136
136
  `/${pattern.source}/${pattern.flags} carries the flag${flags.length === 1 ? '' : 's'} ` +
137
137
  `"${flags}", which Postgres has no operator for`,
138
- `drop the flag and fold the behaviour into the pattern, or pass a predicate instead: matches((value) => /${pattern.source}/${pattern.flags.replaceAll(/[gy]/g, '')}.test(value)) — app-only, and it reports sql: null. Never g or y in that predicate: .test() advances lastIndex, so one row's verdict depends on the row before it`,
138
+ `matches((value) => /${pattern.source}/${pattern.flags.replaceAll(/[gy]/g, '')}.test(value)) // app-only, and it reports sql: null — or drop the flag and fold the behaviour into the pattern. Never g or y in that predicate: .test() advances lastIndex, so one row's verdict depends on the row before it`,
139
139
  );
140
140
  }
141
141
  return pattern.ignoreCase ? '~*' : '~';
@@ -185,7 +185,9 @@ const finite = <T>(rule: 'atLeast' | 'eq', operand: T): T => {
185
185
  refuseInvariant(
186
186
  rule,
187
187
  `${String(operand)} is not a number a CHECK can compare a column against`,
188
- `pass a finite number — c.total.${rule}(0) — or a bigint for a bound past 2^53: c.total.${rule}(9007199254740993n)`,
188
+ rule === 'eq'
189
+ ? 'c.total.eq(0) // a finite number — or a bigint for a bound past 2^53: c.total.eq(9007199254740993n)'
190
+ : 'c.total.atLeast(0) // a finite number — or a bigint for a bound past 2^53: c.total.atLeast(9007199254740993n)',
189
191
  );
190
192
  }
191
193
  return operand;
@@ -329,7 +331,7 @@ const sameAs = (left: Term, other: ColumnExpr): Expr => {
329
331
  refuseInvariant(
330
332
  'eq',
331
333
  'not a column expression',
332
- "pass a column of the same c — c.total.eq(c.subtotal) — or compare against a value: c.total.eq(0). A column of another entity cannot appear in this table's CHECK",
334
+ "c.total.eq(c.subtotal) // a column of the same c — or compare against a value: c.total.eq(0). A column of another entity cannot appear in this table's CHECK",
333
335
  );
334
336
  return check(
335
337
  [left.path, right.path],
@@ -17,7 +17,7 @@ export const searchUndeclared = (entityName: string): EntityError =>
17
17
  code: 'X_SEARCH_UNDECLARED',
18
18
  cause: `${entityName} has no searchable column, so there is no tsvector to match against`,
19
19
  // Screened where it enters the command: the line is pasted, and `$(…)` runs inside "…".
20
- fix: `add .searchable() to a text() column of ${entityName}, then: x db gen "search ${renderFixShellArg(entityName, '<entity>')}"`,
20
+ fix: `text().searchable() // on a text() column of ${entityName}, then: x db gen "search ${renderFixShellArg(entityName, '<entity>')}"`,
21
21
  });
22
22
 
23
23
  /**
@@ -31,7 +31,7 @@ export const searchInMemory = (entityName: string): EntityError =>
31
31
  new EntityError({
32
32
  code: 'X_SEARCH_IN_MEMORY',
33
33
  cause: `memoryDriver() cannot stem, weight or rank a tsvector, so a search of ${entityName} has no answer it could give that Postgres would agree with`,
34
- fix: `move this read into a <name>.live.test.ts and run it with TEST_DATABASE_URL set — bun test packages/entity/src/pg-search.live.test.ts is the model`,
34
+ fix: `bun test ./<name>.live.test.ts # with TEST_DATABASE_URL set, after moving this read into it — packages/entity/src/pg-search.live.test.ts is the model`,
35
35
  });
36
36
 
37
37
  /**
@@ -50,7 +50,7 @@ export const stateUndeclared = (
50
50
  cause: `${entityName}.${column} declares no state machine, so there is no transition to check`,
51
51
  fix:
52
52
  machines.length === 0
53
- ? `add .transitions(…) to ${entityName}.${column} — it must be an enumerated() column, and every value that set declares needs an entry`
53
+ ? `enumerated(['draft', 'published']).transitions({ draft: ['published'], published: [] }) // on ${entityName}.${column}: every value the set declares needs an entry`
54
54
  : `${entityName} declares a machine on: ${machines.join(', ')}`,
55
55
  });
56
56
 
@@ -91,7 +91,7 @@ export const stateTransitionIllegal = (
91
91
  return new EntityError({
92
92
  code: 'X_STATE_TRANSITION_ILLEGAL',
93
93
  cause: `${subject} is terminal in "${from}": the machine declares no move out of it, so "${to}" is not one`,
94
- fix: `move the row before it reaches "${from}", or add "${to}" to the "${from}" entry of the transitions() table`,
94
+ fix: `transitions({ '${from}': ['${to}'], … }) // add the move to the table — or move the row before it reaches "${from}"`,
95
95
  });
96
96
  }
97
97
  return new EntityError({
@@ -119,7 +119,7 @@ export const stateConflict = (
119
119
  new EntityError({
120
120
  code: 'X_STATE_CONFLICT',
121
121
  cause: `${entityName}.${column} named "${expected}" for row ${id}, which is in "${actual}" — something moved it first`,
122
- fix: `re-read the row and decide again against "${actual}": ${entityName}.findById(id) — a transition names the state it expects, so a stale read is refused rather than overwritten`,
122
+ fix: `${entityName}.findById(id) # re-read the row and decide again against "${actual}" — a transition names the state it expects, so a stale read is refused rather than overwritten`,
123
123
  });
124
124
 
125
125
  /**
package/src/like.ts CHANGED
@@ -13,7 +13,7 @@ const danglingEscape = (entityName: string): EntityError =>
13
13
  new EntityError({
14
14
  code: 'X_INVARIANT_VIOLATED',
15
15
  cause: `${entityName}: a like pattern ends with a backslash, which is the escape character — Postgres answers that pattern with 22025 (LIKE pattern must not end with escape character)`,
16
- fix: "double it — 'a\\\\' is the pattern that matches one literal backslash, and 'a\\%b' matches a literal %",
16
+ fix: "andWhere('<column>', 'like', 'a\\\\\\\\') // double it: that pattern matches one literal backslash, and 'a\\\\%b' a literal %",
17
17
  });
18
18
 
19
19
  const ONE = Symbol('_');
package/src/partition.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // column is a timestamp or a date — so `x db gen` never writes a migration the server refuses.
4
4
  // The SQL (the `partition by` clause, creating ahead, retention) is `@ultimat3/db`'s.
5
5
 
6
- import { renderFixShellArg } from '@ultimat3/core';
6
+ import { renderFixLiteral } from '@ultimat3/core';
7
7
  import { PARTITION_INTERVALS, type PartitionInterval } from '@ultimat3/db';
8
8
  import { parseDuration } from '@ultimat3/time';
9
9
  import { columnName } from './column';
@@ -49,11 +49,12 @@ export interface PartitionContext {
49
49
  readonly view: boolean;
50
50
  }
51
51
 
52
+ /** `edit` is one member of the entity's declaration, as source: the fix pastes it, then migrates. */
52
53
  export const partitionInvalid = (entity: string, reason: string, edit: string): EntityError =>
53
54
  new EntityError({
54
55
  code: 'X_ENTITY_PARTITION_INVALID',
55
56
  cause: `entity "${entity}" declares partitionBy, and ${reason}`,
56
- fix: `x db gen "partition" # after ${edit} in entity('${renderFixShellArg(entity, '<entity>')}')`,
57
+ fix: `entity(${renderFixLiteral(entity, "'<entity>'")}, { ${edit}, … }) // then: x db gen "partition"`,
57
58
  });
58
59
 
59
60
  const retainOf = (entity: string, after: unknown): PartitionDescription['retain'] => {
@@ -67,7 +68,7 @@ const retainOf = (entity: string, after: unknown): PartitionDescription['retain'
67
68
  throw partitionInvalid(
68
69
  entity,
69
70
  'partitionBy.retain.after is no window longer than zero',
70
- "partitionBy.retain: { after: '400d' }",
71
+ "partitionBy: { …, retain: { after: '400d' } }",
71
72
  );
72
73
  }
73
74
  return { after: String(after), afterMs };
@@ -83,22 +84,23 @@ export function partitionOf(
83
84
  const refuse = (reason: string, edit: string): never => {
84
85
  throw partitionInvalid(entity, reason, edit);
85
86
  };
86
- if (context.view) refuse('is a view: a view has no partitions', 'removing partitionBy');
87
+ if (context.view)
88
+ refuse('is a view: a view has no partitions', '/* no partitionBy: a view has none */');
87
89
  if (context.retain) {
88
90
  refuse(
89
91
  'retain sits beside it: a partitioned table drops whole partitions, never rows',
90
- 'moving the window to partitionBy.retain: { after }',
92
+ "partitionBy: { …, retain: { after: '400d' } } /* in place of the top-level retain */",
91
93
  );
92
94
  }
93
95
  if (!INTERVALS.includes(init.interval)) {
94
96
  refuse(
95
97
  `interval "${String(init.interval)}" is none of ${INTERVALS.join(', ')}`,
96
- "interval: 'month'",
98
+ "partitionBy: { …, interval: 'month' }",
97
99
  );
98
100
  }
99
101
  const ahead = init.ahead ?? DEFAULT_PARTITIONS_AHEAD;
100
102
  if (!Number.isInteger(ahead) || ahead < 0 || ahead > 1000) {
101
- refuse('partitionBy.ahead is no whole number from 0 to 1000', 'ahead: 3');
103
+ refuse('partitionBy.ahead is no whole number from 0 to 1000', 'partitionBy: { …, ahead: 3 }');
102
104
  }
103
105
  if (new TextEncoder().encode(context.table).length > MAX_PARENT_BYTES) {
104
106
  refuse(
@@ -111,7 +113,7 @@ export function partitionOf(
111
113
  throw partitionInvalid(
112
114
  entity,
113
115
  `partitionBy.column "${String(init.column)}" is no timestamp() or date() column of it`,
114
- "column: 'at'",
116
+ "partitionBy: { …, column: 'at' }",
115
117
  );
116
118
  }
117
119
  if (!context.primaryKey.includes(init.column)) {
@@ -128,7 +130,7 @@ export function partitionOf(
128
130
  if (unique !== undefined) {
129
131
  refuse(
130
132
  `a unique index on (${unique.join(', ')}) does not hold "${physical}": Postgres requires it`,
131
- `adding ${init.column} to that unique index or invariant`,
133
+ `/* ${init.column} added to the unique index or invariant on (${unique.join(', ')}) */`,
132
134
  );
133
135
  }
134
136
  return {
package/src/retain.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // is required and the app's — no default anywhere; `on` is an indexed timestamp, or every sweep is a
3
3
  // table scan; and `appendOnly` beside it is refused, because that trigger refuses every delete.
4
4
 
5
+ import { renderFixLiteral } from '@ultimat3/core';
5
6
  import { retainInvalid } from '@ultimat3/db';
6
7
  import { parseDuration } from '@ultimat3/time';
7
8
  import { columnName } from './column';
@@ -64,7 +65,7 @@ export function retainOf(
64
65
  throw new EntityError({
65
66
  code: 'X_ENTITY_RETAIN_UNINDEXED',
66
67
  cause: `entity "${entity}" retains by ${init.on}, and no index starts with it: every sweep would read the whole table`,
67
- fix: `x db gen "retain index" # after adding { on: ['${init.on}'] } to indexes in entity('${entity}')`,
68
+ fix: `entity(${renderFixLiteral(entity, "'<entity>'")}, { indexes: [{ on: ['${init.on}'] }], … }) // then: x db gen "retain index"`,
68
69
  });
69
70
  }
70
71
  return { after: init.after, afterMs, on: init.on, column: physical };
@@ -41,12 +41,12 @@ export const sealedPredicate = (
41
41
  ? new EntityError({
42
42
  code: 'X_ENTITY_SEALED_PREDICATE',
43
43
  cause: `${entityName}.${column} is sealed and was named in ${use} — the database holds ciphertext sealed with a fresh IV, so no two values match and nothing there can find, order or group by it`,
44
- fix: `find the row by another column, or declare ${entityName}.${column} as text().sealed({ lookup: true }) to allow equality in where() and .unique() — equal plaintexts then store as visibly equal ciphertexts, so never for a low-entropy value, and rows already stored must be written again before they match`,
44
+ fix: `text().sealed({ lookup: true }) // declare ${entityName}.${column} so to allow equality in where() and .unique(), or find the row by another column — equal plaintexts then store as visibly equal ciphertexts, so never for a low-entropy value, and rows already stored must be written again before they match`,
45
45
  })
46
46
  : new EntityError({
47
47
  code: 'X_ENTITY_SEALED_PREDICATE',
48
48
  cause: `${entityName}.${column} is sealed for lookup and was named in ${use} that is not an equality — the database holds ciphertext, and a deterministic seal preserves equality and nothing else: no order, no range, no like`,
49
- fix: `match it by equality — where({ ${column}: value }) or andWhere('${column}', 'in', values) — and order or range by a column that is not sealed`,
49
+ fix: `where({ ${column}: value }) // match it by equality, or andWhere('${column}', 'in', values) — and order or range by a column that is not sealed`,
50
50
  });
51
51
 
52
52
  /**
@@ -62,7 +62,7 @@ export const sealedLookupValue = (
62
62
  new EntityError({
63
63
  code: 'X_ENTITY_SEALED_PREDICATE',
64
64
  cause: `${entityName}.${column} is sealed for lookup and was matched against a ${shape === 'list' ? 'list holding a value' : 'value'} that is not a string — the column holds sealed strings or NULL, so the filter could only ever match nothing`,
65
- fix: `pass the plaintext as a string — where({ ${column}: String(value) }) — or null to ask for the rows where ${entityName}.${column} is NULL`,
65
+ fix: `where({ ${column}: String(value) }) // the plaintext as a string — or null to ask for the rows where ${entityName}.${column} is NULL`,
66
66
  });
67
67
 
68
68
  /**
@@ -83,7 +83,7 @@ export const sealedInView = (entityName: string, column: string): EntityError =>
83
83
  new EntityError({
84
84
  code: 'X_ENTITY_SEALED_IN_VIEW',
85
85
  cause: `${entityName}.$view([...]) names ${column}, which is sealed — a view is an action's output, an OpenAPI schema and an MCP tool result, and a sealed column leaves the server through none of them`,
86
- fix: `remove '${column}' from the $view([...]) list — server code reads it off the row; a caller that must be shown it gets its own field on a t.object output, set by the handler`,
86
+ fix: `$view([…]) // without '${column}' — server code reads it off the row; a caller that must be shown it gets its own field on a t.object output, set by the handler`,
87
87
  });
88
88
 
89
89
  /**
package/src/tenancy.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // under the acting actor's tenant — derived from the ambient context, never taken from an argument
3
3
  // — and a plan or a row that names a different one is refused rather than carried out.
4
4
 
5
- import { tryUseContext } from '@ultimat3/core';
5
+ import { renderFixShellArg, tryUseContext } from '@ultimat3/core';
6
6
  import { assertCrossTenant, crossTenantReason } from './cross-tenant';
7
7
  import {
8
8
  EntityError,
@@ -45,6 +45,14 @@ export interface QueryPlan {
45
45
  readonly select?: readonly string[];
46
46
  }
47
47
 
48
+ /**
49
+ * The builder a tenant column of this kind is declared with, for a fix that re-declares it. Only
50
+ * the kinds an org id is held in are named, because the paste has to compile; `text` otherwise.
51
+ */
52
+ const TENANT_BUILDERS: ReadonlySet<string> = new Set(['uuid', 'text', 'integer', 'bigint']);
53
+ const builderOf = (kind: string | undefined): string =>
54
+ kind !== undefined && TENANT_BUILDERS.has(kind) ? kind : 'text';
55
+
48
56
  /** The property key a tenant column takes when it is not marked explicitly. */
49
57
  export const ORG_COLUMN = 'orgId';
50
58
 
@@ -80,7 +88,7 @@ export const resolveTenantColumn = (
80
88
  throw new EntityError({
81
89
  code: 'X_INVARIANT_VIOLATED',
82
90
  cause: `${entityName}.tenant: tenant: '${declared}' names no column — pick from: ${available}`,
83
- fix: `set tenant to one of ${available} in entity('${entityName}'), or remove the tenant key — inference then takes the .tenant() column, else one named ${ORG_COLUMN}`,
91
+ fix: `tenant: '<column>' // in entity('${entityName}'), one of: ${available} — or remove the tenant key — inference then takes the .tenant() column, else one named ${ORG_COLUMN}`,
84
92
  });
85
93
  }
86
94
  const property = declared ?? tenantColumnOf(columns);
@@ -97,7 +105,7 @@ export const resolveTenantColumn = (
97
105
  throw new EntityError({
98
106
  code: 'X_INVARIANT_VIOLATED',
99
107
  cause: `${entityName}.${property} is the tenant column and is nullable — a row written with no ${property} is matched by no tenant-scoped query, so it belongs to nobody and no sweep can ever find it`,
100
- fix: `drop .nullable() from ${property} in entity('${entityName}'), then x db gen "backfill ${entityName} ${property}" — a row with no tenant needs one before the column can refuse it`,
108
+ fix: `columns: { ${property}: ${builderOf(columns[property]?.$meta.kind)}() } // in entity('${entityName}'), without .nullable() — then: x db gen "backfill ${renderFixShellArg(entityName, '<entity>')} ${renderFixShellArg(property, '<column>')}"; a row with no tenant needs one before the column can refuse it`,
101
109
  });
102
110
  }
103
111
  return property;