@ultimat3/db 31.7.0 → 31.8.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/src/pool-gate.ts CHANGED
@@ -2,19 +2,29 @@
2
2
  // next one waits. `Bun.SQL` queues past `max` with no bound and publishes no occupancy, so this counts
3
3
  // in front of it: a statement and a pin each hold one slot, and a full pool refuses on one deadline.
4
4
 
5
- import type { Scheduler } from '@ultimat3/core';
5
+ import { isUltimateError, type Scheduler, throwIfAborted, tryUseContext } from '@ultimat3/core';
6
6
  import { type DbError, poolAcquireTimeout } from './errors';
7
7
  import type { PoolDemand } from './pool-gauge';
8
8
  import { unrefSchedule } from './pool-timer';
9
+ import { statementVerb } from './statement-shape';
10
+
11
+ /**
12
+ * How a queued waiter leaves early: when `signal` aborts, `reason()` is what it is refused with, or
13
+ * `undefined` to keep its place. Asked only once the waiter actually queues.
14
+ */
15
+ export interface QueueExit {
16
+ readonly signal: AbortSignal;
17
+ reason(): unknown;
18
+ }
9
19
 
10
20
  export interface PoolGate {
11
21
  /**
12
22
  * Take a slot. `undefined` when one was free, so the path that never waits pays no promise and
13
23
  * sends in the caller's own turn. Otherwise resolves `true` when the slot arrives, `false` when
14
- * this pool retired first, and rejects past `acquireTimeoutMs` (`X_DB_POOL_EXHAUSTED`). `0` waits
15
- * forever.
24
+ * this pool retired first, and rejects past `acquireTimeoutMs` (`X_DB_POOL_EXHAUSTED`) or with
25
+ * `exit`'s reason when its signal aborts first. `0` waits forever.
16
26
  */
17
- enter(acquireTimeoutMs: number): Promise<boolean> | undefined;
27
+ enter(acquireTimeoutMs: number, exit?: () => QueueExit | undefined): Promise<boolean> | undefined;
18
28
  /** Give a slot back. The oldest waiter inherits it, so a newcomer never overtakes the queue. */
19
29
  leave(): void;
20
30
  /** This pool is gone but the database may not be: everyone queued asks the next pool. */
@@ -29,19 +39,48 @@ export interface GatedPool {
29
39
  readonly demand: PoolDemand;
30
40
  }
31
41
 
42
+ /**
43
+ * Whether the scope's abort takes a queued waiter out — the rule `statement-cancel.ts` applies to a
44
+ * statement in flight, applied before it is sent. A coded reason (a deadline, a job's cancel) is
45
+ * somebody answered: any waiter leaves with that very error. An uncoded hang-up takes out a pooled
46
+ * `select` only, as core's `X_ABORTED`: a write or a pin keeps its place, since a click followed by a navigation must
47
+ * keep landing (`abandonment()`). A scope already aborted when it asks is not watched at all.
48
+ */
49
+ function scopeExit(statement: string | undefined): QueueExit | undefined {
50
+ const ctx = tryUseContext();
51
+ if (ctx === undefined || ctx.signal.aborted) return undefined;
52
+ const { signal } = ctx;
53
+ return {
54
+ signal,
55
+ reason() {
56
+ if (isUltimateError(signal.reason)) return signal.reason;
57
+ if (statement === undefined || statementVerb(statement) !== 'select') return undefined;
58
+ try {
59
+ throwIfAborted(ctx);
60
+ } catch (aborted) {
61
+ return aborted;
62
+ }
63
+ return undefined;
64
+ },
65
+ };
66
+ }
67
+
32
68
  /**
33
69
  * A slot on the current pool, counted from the ask: a statement queued behind a full pool is exactly
34
70
  * what `db_pool_waiting` reports. Answers the pool itself when a slot was free, so a caller checking
35
71
  * `instanceof Promise` sends in its own turn. A retirement during the wait re-asks the pool that
36
72
  * replaced it, with a fresh deadline: the work was never sent, so it can only be late, never doubled.
73
+ * `statement` is a pooled statement's text, `undefined` for a pin: its verb and the scope are read
74
+ * only once it queues, so the path that never waits pays neither (`scopeExit`).
37
75
  */
38
76
  export function takeSlot<P extends GatedPool>(
39
77
  connect: () => P,
40
78
  acquireTimeoutMs: number,
79
+ statement: string | undefined,
41
80
  ): P | Promise<P> {
42
81
  const asked = connect();
43
82
  asked.demand.enter();
44
- const wait = asked.gate.enter(acquireTimeoutMs);
83
+ const wait = asked.gate.enter(acquireTimeoutMs, () => scopeExit(statement));
45
84
  if (wait === undefined) return asked;
46
85
  return (async () => {
47
86
  let admitted: boolean;
@@ -53,7 +92,7 @@ export function takeSlot<P extends GatedPool>(
53
92
  }
54
93
  if (admitted) return asked;
55
94
  asked.demand.leave();
56
- return takeSlot(connect, acquireTimeoutMs);
95
+ return takeSlot(connect, acquireTimeoutMs, statement);
57
96
  })();
58
97
  }
59
98
 
@@ -65,7 +104,8 @@ export function freeSlot(pool: GatedPool): void {
65
104
 
66
105
  interface Waiter {
67
106
  readonly settle: (admitted: boolean) => void;
68
- readonly refuse: (reason: DbError) => void;
107
+ readonly refuse: (reason: unknown) => void;
108
+ /** Drops the deadline and the abort listener: called on every way out of the queue. */
69
109
  disarm: () => void;
70
110
  }
71
111
 
@@ -75,7 +115,7 @@ export function poolGate(max: number, schedule: Scheduler = unrefSchedule): Pool
75
115
  const waiting = new Set<Waiter>();
76
116
 
77
117
  return {
78
- enter(acquireTimeoutMs) {
118
+ enter(acquireTimeoutMs, exit) {
79
119
  // `leave` hands a slot over rather than freeing it, so a free slot means nobody is queued.
80
120
  if (out < max) {
81
121
  out += 1;
@@ -84,11 +124,26 @@ export function poolGate(max: number, schedule: Scheduler = unrefSchedule): Pool
84
124
  return new Promise<boolean>((settle, refuse) => {
85
125
  const waiter: Waiter = { settle, refuse, disarm: () => undefined };
86
126
  waiting.add(waiter);
87
- if (acquireTimeoutMs <= 0) return;
88
- waiter.disarm = schedule(() => {
89
- waiting.delete(waiter);
90
- refuse(poolAcquireTimeout(acquireTimeoutMs, max));
91
- }, acquireTimeoutMs);
127
+ const disarmTimer =
128
+ acquireTimeoutMs <= 0
129
+ ? undefined
130
+ : schedule(() => {
131
+ waiting.delete(waiter);
132
+ waiter.disarm();
133
+ refuse(poolAcquireTimeout(acquireTimeoutMs, max));
134
+ }, acquireTimeoutMs);
135
+ const leaving = exit?.();
136
+ const onAbort = (): void => {
137
+ const reason = leaving?.reason();
138
+ if (reason === undefined || !waiting.delete(waiter)) return;
139
+ waiter.disarm();
140
+ refuse(reason);
141
+ };
142
+ leaving?.signal.addEventListener('abort', onAbort, { once: true });
143
+ waiter.disarm = () => {
144
+ disarmTimer?.();
145
+ leaving?.signal.removeEventListener('abort', onAbort);
146
+ };
92
147
  });
93
148
  },
94
149
  leave() {
package/src/pool-pins.ts CHANGED
@@ -1,19 +1,31 @@
1
- // Single responsibility: the unanswered-statement bound of ONE pinned connection. A pin's statements
2
- // are swept like any other, against the `statement_timeout` in force on that connection: the role's,
3
- // until a `set_config('statement_timeout', …)` or `SET [LOCAL] statement_timeout` it answered moves
4
- // it, and back to the role's at the transaction's end. A miss leaves the pin dead, never reused.
1
+ // Single responsibility: the unanswered-statement bound of ONE pinned connection — the
2
+ // `statement_timeout` in force on it, which its statements are swept against like any other's. A
3
+ // miss leaves the pin dead, never reused.
4
+ //
5
+ // The bound is the role's until a `set_config('statement_timeout', …)` or `SET [LOCAL]
6
+ // statement_timeout` it answered moves it; back to the role's at the transaction's end or a RESET,
7
+ // and back to what a SAVEPOINT saw on a ROLLBACK TO it.
5
8
 
9
+ import { pinStatement } from './pin-statement';
6
10
  import type { SqlFragment } from './sql';
7
11
 
12
+ /** An open savepoint and the bound in force when it was taken: a ROLLBACK TO it restores that. */
13
+ interface Savepoint {
14
+ readonly name: string;
15
+ readonly boundMs: number;
16
+ }
17
+
8
18
  /** What one pin is bound by now. `boundMs` 0 is no bound, as the server reads it. */
9
19
  export interface PinBound {
10
20
  boundMs: number;
11
21
  /** A statement on it went unanswered: nothing more is sent on this connection. */
12
22
  dead: boolean;
23
+ /** Open savepoints, oldest first — the server's stack, as this pin answered it. */
24
+ readonly savepoints: Savepoint[];
13
25
  }
14
26
 
15
27
  export function pinBound(roleBoundMs: number): PinBound {
16
- return { boundMs: roleBoundMs, dead: false };
28
+ return { boundMs: roleBoundMs, dead: false, savepoints: [] };
17
29
  }
18
30
 
19
31
  /** The sweep's deadline for the next statement on `pin`; `0` is none to judge. */
@@ -23,10 +35,8 @@ export function pinDeadlineMs(pin: PinBound, extraMs: number): number {
23
35
 
24
36
  /** `setLocal`'s text (`local-settings.ts`), the framework's one writer, held by `pool-pins.test.ts`. */
25
37
  const SET_CONFIG = 'select set_config($1, $2, true)';
26
- const SET_TEXT = /^\s*set\s+(?:local\s+|session\s+)?statement_timeout\s*(?:=|to)\s*(.+?)\s*;?\s*$/i;
27
- const SET_CONFIG_TEXT =
28
- /^\s*select\s+set_config\s*\(\s*'statement_timeout'\s*,\s*'([^']*)'\s*,\s*(?:true|false)\s*\)\s*;?\s*$/i;
29
- const ENDS_TRANSACTION = /^\s*(?:commit|rollback|end|abort)(?:\s+(?:work|transaction))?\s*;?\s*$/i;
38
+ /** Longer than any `statement_timeout` value; a bind value is library input too. */
39
+ const TIMEOUT_VALUE_CHARS_MAX = 64;
30
40
  const UNITS: ReadonlyMap<string, number> = new Map([
31
41
  ['us', 0.001],
32
42
  ['ms', 1],
@@ -39,7 +49,13 @@ const UNITS: ReadonlyMap<string, number> = new Map([
39
49
  /** A `statement_timeout` value in Postgres' own grammar, as ms: a bare number is ms. */
40
50
  export function timeoutValueMs(value: unknown): number | undefined {
41
51
  if (typeof value !== 'string' && typeof value !== 'number') return undefined;
42
- const match = /^\s*'?\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*'?\s*$/i.exec(String(value));
52
+ if (String(value).length > TIMEOUT_VALUE_CHARS_MAX) return undefined;
53
+ // Quotes and padding come off by hand, so the one pattern left has no two adjacent quantifiers
54
+ // that can both take a space.
55
+ let text = String(value).trim();
56
+ if (text.startsWith("'")) text = text.slice(1);
57
+ if (text.endsWith("'")) text = text.slice(0, -1);
58
+ const match = /^(\d+(?:\.\d+)?)\s*([a-z]*)$/i.exec(text.trim());
43
59
  if (match === null) return undefined;
44
60
  const scale = UNITS.get((match[2] ?? '').toLowerCase() || 'ms');
45
61
  if (scale === undefined) return undefined;
@@ -53,16 +69,57 @@ export function boundSetBy(fragment: SqlFragment): number | undefined {
53
69
  ? timeoutValueMs(fragment.values[1])
54
70
  : undefined;
55
71
  }
56
- const text = SET_TEXT.exec(fragment.text) ?? SET_CONFIG_TEXT.exec(fragment.text);
57
- return text === null ? undefined : timeoutValueMs(text[1]);
72
+ const statement = pinStatement(fragment.text);
73
+ return statement?.kind === 'set' ? timeoutValueMs(statement.value) : undefined;
74
+ }
75
+
76
+ /** The newest open savepoint called `name`, or -1: names may repeat, the newest one is meant. */
77
+ function savepointIndex(pin: PinBound, name: string): number {
78
+ return pin.savepoints.findLastIndex((savepoint) => savepoint.name === name);
58
79
  }
59
80
 
60
- /** After `fragment` ANSWERED on `pin`: a refused statement moved nothing. */
81
+ /**
82
+ * After `fragment` ANSWERED on `pin`: a refused statement moved nothing. ROLLBACK TO keeps its
83
+ * savepoint and drops every newer one; RELEASE drops it and every newer one, keeping what was set
84
+ * inside it. The statement is read once, by `pinStatement`.
85
+ */
61
86
  export function noteAnswered(pin: PinBound, fragment: SqlFragment, roleBoundMs: number): void {
62
- if (ENDS_TRANSACTION.test(fragment.text)) {
63
- pin.boundMs = roleBoundMs;
87
+ if (fragment.text === SET_CONFIG) {
88
+ const set = boundSetBy(fragment);
89
+ if (set !== undefined) pin.boundMs = set;
64
90
  return;
65
91
  }
66
- const set = boundSetBy(fragment);
67
- if (set !== undefined) pin.boundMs = set;
92
+ const statement = pinStatement(fragment.text);
93
+ switch (statement?.kind) {
94
+ case 'end':
95
+ pin.boundMs = roleBoundMs;
96
+ pin.savepoints.length = 0;
97
+ return;
98
+ case 'role-bound':
99
+ pin.boundMs = roleBoundMs;
100
+ return;
101
+ case 'set': {
102
+ const set = timeoutValueMs(statement.value);
103
+ if (set !== undefined) pin.boundMs = set;
104
+ return;
105
+ }
106
+ case 'savepoint':
107
+ pin.savepoints.push({ name: statement.name, boundMs: pin.boundMs });
108
+ return;
109
+ case 'rollback-to': {
110
+ const at = savepointIndex(pin, statement.name);
111
+ const savepoint = pin.savepoints[at];
112
+ if (savepoint === undefined) return;
113
+ pin.boundMs = savepoint.boundMs;
114
+ pin.savepoints.length = at + 1;
115
+ return;
116
+ }
117
+ case 'release': {
118
+ const at = savepointIndex(pin, statement.name);
119
+ if (at !== -1) pin.savepoints.length = at;
120
+ return;
121
+ }
122
+ default:
123
+ return;
124
+ }
68
125
  }
package/src/rolling.ts CHANGED
@@ -75,9 +75,10 @@ export interface RollingUnsafeStatement {
75
75
  /**
76
76
  * Words, quoted identifiers and punctuation, with comments, literals and dollar bodies gone. Why
77
77
  * not `stripSqlNoise`, which `destructive.ts` reads: it blanks a quoted identifier too, and this
78
- * rail has to say WHICH column.
78
+ * rail has to say WHICH column. Exported with the readers below for `migration-lock-lint.ts`: two
79
+ * lexical rails over one token stream, never two tokenizers.
79
80
  */
80
- function tokensOf(statement: string): readonly string[] {
81
+ export function tokensOf(statement: string): readonly string[] {
81
82
  let text = '';
82
83
  let index = 0;
83
84
  while (index < statement.length) {
@@ -94,30 +95,42 @@ function tokensOf(statement: string): readonly string[] {
94
95
  return text.match(/"(?:[^"]|"")*"|[A-Za-z_][\w$]*|\S/g) ?? [];
95
96
  }
96
97
 
97
- const isWord = (lexeme: string | undefined, word: string): boolean =>
98
+ export const isWord = (lexeme: string | undefined, word: string): boolean =>
98
99
  lexeme !== undefined && !lexeme.startsWith('"') && lexeme.toLowerCase() === word;
99
100
 
100
101
  /** What Postgres folds a token to: a quoted one keeps its case, a bare one lowers. */
101
- const nameOf = (token: string): string =>
102
+ export const nameOf = (token: string): string =>
102
103
  token.startsWith('"') ? token.slice(1, -1).replaceAll('""', '"') : token.toLowerCase();
103
104
 
104
- /** `alter table [if exists] [only] [schema.]t`, as the table and where its subcommands start. */
105
- function alteredTable(tokens: readonly string[]): { table: string; next: number } | undefined {
106
- if (!isWord(tokens[0], 'alter') || !isWord(tokens[1], 'table')) return undefined;
107
- let at = 2;
108
- if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'exists')) at += 2;
109
- if (isWord(tokens[at], 'only')) at += 1;
105
+ /** `[schema.]name` from `at`, as the last part folded and where the tokens after it start. */
106
+ export function qualifiedNameAt(
107
+ tokens: readonly string[],
108
+ start: number,
109
+ ): { name: string; next: number } | undefined {
110
+ let at = start;
110
111
  let name = tokens[at];
111
112
  at += 1;
112
113
  while (tokens[at] === '.') {
113
114
  name = tokens[at + 1];
114
115
  at += 2;
115
116
  }
116
- return name === undefined ? undefined : { table: nameOf(name), next: at };
117
+ return name === undefined ? undefined : { name: nameOf(name), next: at };
118
+ }
119
+
120
+ /** `alter table [if exists] [only] [schema.]t`, as the table and where its subcommands start. */
121
+ export function alteredTable(
122
+ tokens: readonly string[],
123
+ ): { table: string; next: number } | undefined {
124
+ if (!isWord(tokens[0], 'alter') || !isWord(tokens[1], 'table')) return undefined;
125
+ let at = 2;
126
+ if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'exists')) at += 2;
127
+ if (isWord(tokens[at], 'only')) at += 1;
128
+ const named = qualifiedNameAt(tokens, at);
129
+ return named === undefined ? undefined : { table: named.name, next: named.next };
117
130
  }
118
131
 
119
132
  /** Top-level commas only: `add constraint … (a, b)` is one subcommand. */
120
- function subcommands(tokens: readonly string[]): readonly (readonly string[])[] {
133
+ export function subcommands(tokens: readonly string[]): readonly (readonly string[])[] {
121
134
  const parts: string[][] = [[]];
122
135
  let depth = 0;
123
136
  for (const token of tokens) {
@@ -0,0 +1,103 @@
1
+ // Single responsibility: one grep-able `warn` line per slow statement, from the `db.statement` bus
2
+ // event — the normalised shape (never a bound value), duration, rows and, through the logger's
3
+ // context fields, the request/job ids. Sampled to one line per shape per window, memo bounded.
4
+ // The runtime decides whether it runs (500 ms in production, off in tests); this is the mechanism.
5
+
6
+ import {
7
+ type DbStatementEvent,
8
+ finiteOption,
9
+ isUltimateError,
10
+ logger,
11
+ SEMCONV,
12
+ SEMCONV_VALUES,
13
+ subscribe,
14
+ } from '@ultimat3/core';
15
+ import { statementVerb } from './statement-shape';
16
+
17
+ /** The production default the runtime passes as `thresholdMs`. */
18
+ export const SLOW_STATEMENT_THRESHOLD_MS = 500;
19
+ /** One line per shape per this long; the rest are counted onto the next line as `suppressed`. */
20
+ export const SLOW_STATEMENT_WINDOW_MS = 10_000;
21
+ /** Shapes remembered at once. A process with more distinct slow shapes forgets the oldest first. */
22
+ export const SLOW_STATEMENT_SHAPES_MAX = 512;
23
+ /** A bulk insert's text can run to megabytes; a log line carries its head. */
24
+ const SHAPE_CHARS_MAX = 2_000;
25
+ const WHITESPACE = /\s+/g;
26
+
27
+ export interface SlowStatementLogOptions {
28
+ /** Statements at or over this many ms log. `0` (or less) is off: nothing subscribes. */
29
+ readonly thresholdMs: number;
30
+ readonly windowMs?: number | undefined;
31
+ /** Monotonic ms, for the sampling window only. Defaults to `performance.now`. */
32
+ readonly now?: (() => number) | undefined;
33
+ }
34
+
35
+ interface Seen {
36
+ readonly at: number;
37
+ suppressed: number;
38
+ }
39
+
40
+ /** The text with whitespace collapsed, capped: already `$n`-parameterised by `sql()`. */
41
+ function shapeOf(text: string): string {
42
+ const shape = text.replace(WHITESPACE, ' ').trim();
43
+ return shape.length > SHAPE_CHARS_MAX ? `${shape.slice(0, SHAPE_CHARS_MAX - 3)}...` : shape;
44
+ }
45
+
46
+ function lineOf(
47
+ event: DbStatementEvent,
48
+ shape: string,
49
+ suppressed: number,
50
+ ): Record<string, unknown> {
51
+ const verb = statementVerb(event.text);
52
+ const attribution = event.attribution;
53
+ return {
54
+ [SEMCONV.dbSystemName]: SEMCONV_VALUES.dbSystemPostgres,
55
+ [SEMCONV.dbQueryText]: shape,
56
+ ...(verb === '' ? {} : { [SEMCONV.dbOperationName]: verb.toUpperCase() }),
57
+ [SEMCONV.dbResponseReturnedRows]: event.rows,
58
+ durationMs: Math.round(event.durationMs),
59
+ ...(attribution === undefined
60
+ ? {}
61
+ : { attribution: `${attribution.entity}.${attribution.op}` }),
62
+ ...(event.error === undefined
63
+ ? {}
64
+ : { [SEMCONV.errorType]: isUltimateError(event.error) ? event.error.code : '_OTHER' }),
65
+ ...(suppressed === 0 ? {} : { suppressed }),
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Subscribe the slow-statement line. Returns the unsubscribe — wire it into the drain. Bound values
71
+ * never reach the line: the event's `values` is not read at all.
72
+ */
73
+ export function slowStatementLog(options: SlowStatementLogOptions): () => void {
74
+ const { thresholdMs } = options;
75
+ if (!(thresholdMs > 0)) return () => undefined;
76
+ const windowMs = finiteOption(
77
+ 'slowStatementLog',
78
+ 'windowMs',
79
+ options.windowMs ?? SLOW_STATEMENT_WINDOW_MS,
80
+ );
81
+ const now = options.now ?? (() => performance.now());
82
+ // Insertion order is last-logged order: a re-log deletes and re-inserts, so the first key is
83
+ // always the shape that logged longest ago — the one eviction drops.
84
+ const seen = new Map<string, Seen>();
85
+
86
+ return subscribe('db.statement', ({ payload }) => {
87
+ if (payload.durationMs < thresholdMs) return;
88
+ const shape = shapeOf(payload.text);
89
+ const at = now();
90
+ const last = seen.get(shape);
91
+ if (last !== undefined && at - last.at < windowMs) {
92
+ last.suppressed += 1;
93
+ return;
94
+ }
95
+ seen.delete(shape);
96
+ if (seen.size >= SLOW_STATEMENT_SHAPES_MAX) {
97
+ const oldest = seen.keys().next();
98
+ if (oldest.done !== true) seen.delete(oldest.value);
99
+ }
100
+ seen.set(shape, { at, suppressed: 0 });
101
+ logger.warn('db.statement.slow', lineOf(payload, shape, last?.suppressed ?? 0));
102
+ });
103
+ }
@@ -33,6 +33,10 @@ const interval = (value: unknown): value is PartitionInterval => INTERVALS.inclu
33
33
  const order = (value: unknown): value is 'asc' | 'desc' | null =>
34
34
  value === null || value === 'asc' || value === 'desc';
35
35
 
36
+ /** One direction per key, each of the closed set. */
37
+ const directions = (value: unknown): value is readonly ('asc' | 'desc' | null)[] =>
38
+ Array.isArray(value) && value.every(order);
39
+
36
40
  function column(value: unknown): ColumnDescription | undefined {
37
41
  if (!isRow(value)) return undefined;
38
42
  const { name, dataType, nullable, default: fallback, position, generated, retired } = value;
@@ -68,6 +72,7 @@ function check(value: unknown): CheckDescription | undefined {
68
72
  function index(value: unknown): IndexDescription | undefined {
69
73
  if (!isRow(value)) return undefined;
70
74
  const { name, columns, unique, primary, where, order: direction, using } = value;
75
+ const { expression, orders, include, operatorClass } = value;
71
76
  if (!str(name) || !strings(columns) || !bool(unique) || !bool(primary)) return undefined;
72
77
  // Written by 1.2.0 onwards. A sidecar from before it carries neither, and the total, ascending
73
78
  // reading is what that generation actually emitted — so an older file stays readable rather
@@ -80,6 +85,12 @@ function index(value: unknown): IndexDescription | undefined {
80
85
  // method and the fix, not here, where it would discard the whole snapshot without saying which
81
86
  // field was wrong. Absent stays absent: `indexMethodOf` reads it as the btree it always was.
82
87
  if (!(using === undefined || str(using))) return undefined;
88
+ // The four key parts: each absent or well-formed, never dropped. Dropped here, `indexShape` read
89
+ // the recorded index as the plain one and every `x db gen` rebuilt it — `generated`'s old hole.
90
+ if (!(expression === undefined || str(expression))) return undefined;
91
+ if (!(orders === undefined || directions(orders))) return undefined;
92
+ if (!(include === undefined || strings(include))) return undefined;
93
+ if (!(operatorClass === undefined || str(operatorClass))) return undefined;
83
94
  return {
84
95
  name,
85
96
  columns,
@@ -88,6 +99,10 @@ function index(value: unknown): IndexDescription | undefined {
88
99
  where: where === undefined ? null : where,
89
100
  order: direction === undefined ? null : direction,
90
101
  ...(using === undefined ? {} : { using }),
102
+ ...(expression === undefined ? {} : { expression }),
103
+ ...(orders === undefined ? {} : { orders }),
104
+ ...(include === undefined ? {} : { include }),
105
+ ...(operatorClass === undefined ? {} : { operatorClass }),
91
106
  };
92
107
  }
93
108