@ultimat3/db 31.6.1 → 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.
@@ -0,0 +1,184 @@
1
+ // Single responsibility: decide whether a hand-written migration's `up` holds a live table still for
2
+ // a full scan — `set not null` with no validated check before it, or a non-concurrent index build —
3
+ // and raise `X_MIGRATION_LOCK_HEAVY` for it. `rolling.ts`'s shape and token stream: lexical, `up`
4
+ // only, a closed list, a marker to admit a deliberate one.
5
+
6
+ import { renderFixShellArg } from '@ultimat3/core';
7
+ import { NO_TRANSACTION_MARKER } from './concurrent-index';
8
+ import { DbError } from './errors';
9
+ import { hasMarkerLine } from './marker-line';
10
+ import { alteredTable, isWord, nameOf, qualifiedNameAt, subcommands, tokensOf } from './rolling';
11
+ import { statementExcerpt } from './statement-excerpt';
12
+ import { statementsOf } from './statement-split';
13
+
14
+ /** The line a migration carries when the lock is deliberate: a small table, a maintenance window. */
15
+ export const LOCK_HEAVY_MARKER = '-- lock-heavy: true';
16
+
17
+ const LOCK_HEAVY_COMMENT = /^--[ \t]*lock-heavy:[ \t]*true[ \t]*\r?\n?$/i;
18
+
19
+ /** The comments and blank space `statementsOf` carries in front of a statement's SQL. */
20
+ const LEADING_NOISE = /^(?:\s*(?:--[^\n]*|\/\*[\s\S]*?\*\/)\s*)+/;
21
+
22
+ /** Only spaces and tabs between `at` and the start of its line in `up` (or the file's start). */
23
+ function startsLine(up: string, at: number): boolean {
24
+ for (let index = at - 1; index >= 0; index -= 1) {
25
+ if (up[index] === '\n') return true;
26
+ if (up[index] !== ' ' && up[index] !== '\t') return false;
27
+ }
28
+ return true;
29
+ }
30
+
31
+ /**
32
+ * Whether the line directly above the statement's first SQL line is the marker, as a line of its
33
+ * own (`hasMarkerLine`). `at` is where the trimmed `statement` starts in `up`: a marker that is the
34
+ * statement's first line must start its line there too, or it trails the previous statement.
35
+ */
36
+ function markedAbove(up: string, statement: string, at: number): boolean {
37
+ const lines = (LEADING_NOISE.exec(statement)?.[0] ?? '').split('\n');
38
+ // The SQL must open its own line: `*/ create …` puts the line above inside the comment.
39
+ if (lines.length < 2 || (lines.at(-1) ?? '').trim() !== '') return false;
40
+ const above = lines.length - 2;
41
+ if (above === 0 && !startsLine(up, at)) return false;
42
+ return hasMarkerLine(`${lines[above] ?? ''}\n`, LOCK_HEAVY_COMMENT);
43
+ }
44
+
45
+ /**
46
+ * The migration id the rail judges after, exclusive: the release that shipped it. An applied
47
+ * migration cannot gain a marker (its checksum covers it), so judging history would turn an
48
+ * existing app red with no fix but rewriting it. The comparison `rollingSince` makes, with the
49
+ * bound fixed by the framework rather than opted into, since every app's next file can comply.
50
+ */
51
+ export const LOCK_HEAVY_SINCE = '20261113000000';
52
+
53
+ export const lockHeavyJudged = (id: string): boolean => id > LOCK_HEAVY_SINCE;
54
+
55
+ /** The closed list. Every other lock is either the generator's or too rare to earn a parser. */
56
+ export type LockHeavyKind = 'set-not-null' | 'create-index';
57
+
58
+ export interface LockHeavyStatement {
59
+ readonly kind: LockHeavyKind;
60
+ readonly table: string;
61
+ /** The column `set not null` names; `null` for an index build. */
62
+ readonly column: string | null;
63
+ /** The statement as written, on one line. */
64
+ readonly statement: string;
65
+ }
66
+
67
+ /**
68
+ * `create [temp|temporary|unlogged|materialized] table|view [if not exists] [schema.]t`: the
69
+ * relation no reader has yet, or none. A materialized view is here because `generate-view.ts`
70
+ * rebuilds one by drop + create and indexes it in the same file.
71
+ */
72
+ function createdTable(tokens: readonly string[]): string | undefined {
73
+ if (!isWord(tokens[0], 'create')) return undefined;
74
+ let at = 1;
75
+ if (['temp', 'temporary', 'unlogged'].some((word) => isWord(tokens[at], word))) at += 1;
76
+ if (isWord(tokens[at], 'materialized') && isWord(tokens[at + 1], 'view')) at += 1;
77
+ else if (!isWord(tokens[at], 'table')) return undefined;
78
+ at += 1;
79
+ if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'not') && isWord(tokens[at + 2], 'exists'))
80
+ at += 3;
81
+ return qualifiedNameAt(tokens, at)?.name;
82
+ }
83
+
84
+ /**
85
+ * `create [unique] index …` without `concurrently` and not `on only`: the table it locks. `on only`
86
+ * builds an invalid index on a partitioned parent's own (empty) relation, the first of the
87
+ * concurrent partitioned form, so it scans nothing.
88
+ */
89
+ function blockingIndexTable(tokens: readonly string[]): string | undefined {
90
+ if (!isWord(tokens[0], 'create')) return undefined;
91
+ const at = isWord(tokens[1], 'unique') ? 2 : 1;
92
+ if (!isWord(tokens[at], 'index') || isWord(tokens[at + 1], 'concurrently')) return undefined;
93
+ const on = tokens.findIndex((token, index) => index > at && isWord(token, 'on'));
94
+ if (on < 0 || isWord(tokens[on + 1], 'only')) return undefined;
95
+ return qualifiedNameAt(tokens, on + 1)?.name;
96
+ }
97
+
98
+ /** `alter [column] c set not null`: the column, or none. */
99
+ function setNotNullColumn(part: readonly string[]): string | undefined {
100
+ if (!isWord(part[0], 'alter')) return undefined;
101
+ const at = isWord(part[1], 'column') ? 2 : 1;
102
+ const [name, set, not, nul] = part.slice(at, at + 4);
103
+ if (name === undefined || !isWord(set, 'set') || !isWord(not, 'not') || !isWord(nul, 'null'))
104
+ return undefined;
105
+ return nameOf(name);
106
+ }
107
+
108
+ /**
109
+ * Every statement in `up` that scans a table it did not create under a lock that stops writes, in
110
+ * apply order. A table created earlier in the same `up` has no rows yet. A `validate constraint` on
111
+ * the table earlier in the same `up` is the two-step form's second half: Postgres 12+ proves NOT
112
+ * NULL from a validated `check (c is not null)` and skips the scan. A statement with the marker on
113
+ * the line directly above it is admitted — that statement only, never the file.
114
+ */
115
+ export function lockHeavyStatements(up: string): readonly LockHeavyStatement[] {
116
+ const found: LockHeavyStatement[] = [];
117
+ const created = new Set<string>();
118
+ const validated = new Set<string>();
119
+ let cursor = 0;
120
+ for (const statement of statementsOf(up)) {
121
+ const at = up.indexOf(statement, cursor);
122
+ cursor = at < 0 ? cursor : at + statement.length;
123
+ const admitted = at >= 0 && markedAbove(up, statement, at);
124
+ const tokens = tokensOf(statement);
125
+ const table = createdTable(tokens);
126
+ if (table !== undefined) created.add(table);
127
+ const indexed = blockingIndexTable(tokens);
128
+ if (indexed !== undefined && !created.has(indexed) && !admitted) {
129
+ found.push({
130
+ kind: 'create-index',
131
+ table: indexed,
132
+ column: null,
133
+ statement: statementExcerpt(statement),
134
+ });
135
+ }
136
+ const altered = alteredTable(tokens);
137
+ if (altered === undefined) continue;
138
+ for (const part of subcommands(tokens.slice(altered.next))) {
139
+ if (isWord(part[0], 'validate')) validated.add(altered.table);
140
+ const column = setNotNullColumn(part);
141
+ if (
142
+ column === undefined ||
143
+ admitted ||
144
+ created.has(altered.table) ||
145
+ validated.has(altered.table)
146
+ )
147
+ continue;
148
+ found.push({
149
+ kind: 'set-not-null',
150
+ table: altered.table,
151
+ column,
152
+ statement: statementExcerpt(statement),
153
+ });
154
+ }
155
+ }
156
+ return found;
157
+ }
158
+
159
+ const STATED: Readonly<Record<LockHeavyKind, string>> = {
160
+ 'set-not-null': 'sets a column not null with no validated check before it',
161
+ 'create-index': 'builds an index without concurrently',
162
+ };
163
+
164
+ /** The two-step form for the kind, then the marker for a lock that is deliberate. */
165
+ function twoSteps(first: LockHeavyStatement): string {
166
+ const table = renderFixShellArg(first.table, '<table>');
167
+ if (first.kind === 'create-index')
168
+ return `create index concurrently … on "${table}" (…); # in a migration of its own whose first line is "${NO_TRANSACTION_MARKER}" — x db gen writes it so for an index whose entity does not say concurrently: false`;
169
+ const column = renderFixShellArg(first.column ?? '<column>', '<column>');
170
+ const check = `${table}_${column}_not_null`;
171
+ return (
172
+ `alter table "${table}" add constraint "${check}" check ("${column}" is not null) not valid; # ` +
173
+ `deploy, then a new migration: alter table "${table}" validate constraint "${check}"; alter table "${table}" alter column "${column}" set not null; alter table "${table}" drop constraint "${check}";`
174
+ );
175
+ }
176
+
177
+ /** The gate's finding over a committed file. One per migration, as `migrationRollingUnsafe` is. */
178
+ export const migrationLockHeavy = (file: string, first: LockHeavyStatement, more = 0): DbError =>
179
+ new DbError({
180
+ code: 'X_MIGRATION_LOCK_HEAVY',
181
+ cause: `${file} ${STATED[first.kind]}, so "${first.table}" stops taking writes for a full scan${more === 0 ? '' : ` (and ${more} more)`}: ${first.statement}`,
182
+ fix: `${twoSteps(first)} — a deliberate one: add the line "${LOCK_HEAVY_MARKER}" directly above that statement in ${file} before it is applied — it admits that statement only`,
183
+ meta: { file, kind: first.kind, table: first.table, column: first.column },
184
+ });
@@ -0,0 +1,154 @@
1
+ // Single responsibility: which of the few statements that move a pin's `statement_timeout` a text
2
+ // is — a transaction end, a savepoint verb, a RESET, a SET or a `set_config` — read from its
3
+ // leading words in ONE linear pass. Statement text is library input: no backtracking regex reads
4
+ // it, and a long statement stops being read after `PIN_WORDS_MAX` words.
5
+
6
+ /** More words than any statement recognised here has, so a bulk INSERT is dropped after a dozen. */
7
+ export const PIN_WORDS_MAX = 12;
8
+
9
+ export type PinStatement =
10
+ | { readonly kind: 'end' }
11
+ | { readonly kind: 'savepoint' | 'rollback-to' | 'release'; readonly name: string }
12
+ | { readonly kind: 'role-bound' }
13
+ | { readonly kind: 'set'; readonly value: string };
14
+
15
+ const PUNCTUATION = '=(),;';
16
+
17
+ function isSpace(code: number): boolean {
18
+ return code === 32 || (code >= 9 && code <= 13);
19
+ }
20
+
21
+ /** The index just past the quote closing the one at `start` (`''`/`""` escape it), or -1. */
22
+ function quotedEnd(text: string, start: number, quote: string): number {
23
+ let at = start + 1;
24
+ while (at < text.length) {
25
+ if (text[at] !== quote) at += 1;
26
+ else if (text[at + 1] === quote) at += 2;
27
+ else return at + 1;
28
+ }
29
+ return -1;
30
+ }
31
+
32
+ /**
33
+ * The words of `text`: a quoted identifier or literal whole, each of `= ( ) , ;` alone, any other
34
+ * run of non-space characters as one. One trailing `;` dropped. `undefined` past `PIN_WORDS_MAX`
35
+ * words or at an unterminated quote: neither is a statement this file recognises.
36
+ */
37
+ export function pinWords(text: string): readonly string[] | undefined {
38
+ const words: string[] = [];
39
+ let at = 0;
40
+ for (;;) {
41
+ while (at < text.length && isSpace(text.charCodeAt(at))) at += 1;
42
+ if (at >= text.length) break;
43
+ if (words.length === PIN_WORDS_MAX) return undefined;
44
+ const char = text[at] ?? '';
45
+ let end = at + 1;
46
+ if (char === '"' || char === "'") {
47
+ end = quotedEnd(text, at, char);
48
+ if (end === -1) return undefined;
49
+ } else if (!PUNCTUATION.includes(char)) {
50
+ while (end < text.length && !isSpace(text.charCodeAt(end))) {
51
+ const next = text[end] ?? '';
52
+ if (PUNCTUATION.includes(next) || next === '"' || next === "'") break;
53
+ end += 1;
54
+ }
55
+ }
56
+ words.push(text.slice(at, end));
57
+ at = end;
58
+ }
59
+ if (words.at(-1) === ';') words.pop();
60
+ return words;
61
+ }
62
+
63
+ const UNQUOTED_NAME = /^[a-z_][\w$]*$/i;
64
+
65
+ /** A savepoint name as the server compares it: unquoted folds to lower case, quoted is exact. */
66
+ function nameOf(word: string | undefined): string | undefined {
67
+ if (word === undefined) return undefined;
68
+ if (word.startsWith('"'))
69
+ return word.length > 2 ? word.slice(1, -1).replaceAll('""', '"') : undefined;
70
+ return UNQUOTED_NAME.test(word) ? word.toLowerCase() : undefined;
71
+ }
72
+
73
+ /** `[savepoint] name` as the last one or two words from `from`. */
74
+ function savepointAt(
75
+ words: readonly string[],
76
+ from: number,
77
+ optional: boolean,
78
+ ): string | undefined {
79
+ const at = optional && words[from]?.toLowerCase() === 'savepoint' ? from + 1 : from;
80
+ return at === words.length - 1 ? nameOf(words[at]) : undefined;
81
+ }
82
+
83
+ /** `rollback [work|transaction] to [savepoint] name`, or a bare transaction end. */
84
+ function rollbackOf(words: readonly string[]): PinStatement | undefined {
85
+ const at = ['work', 'transaction'].includes(words[1]?.toLowerCase() ?? '') ? 2 : 1;
86
+ if (at === words.length) return { kind: 'end' };
87
+ if (words[at]?.toLowerCase() !== 'to') return undefined;
88
+ const name = savepointAt(words, at + 1, true);
89
+ return name === undefined ? undefined : { kind: 'rollback-to', name };
90
+ }
91
+
92
+ /** `set [local|session] statement_timeout {=|to} value` — `default` is the role's. */
93
+ function setOf(words: readonly string[]): PinStatement | undefined {
94
+ const at = ['local', 'session'].includes(words[1]?.toLowerCase() ?? '') ? 2 : 1;
95
+ if (words[at]?.toLowerCase() !== 'statement_timeout' || words.length !== at + 3) return undefined;
96
+ if (!['=', 'to'].includes(words[at + 1]?.toLowerCase() ?? '')) return undefined;
97
+ const value = words[at + 2] ?? '';
98
+ return value.toLowerCase() === 'default' ? { kind: 'role-bound' } : { kind: 'set', value };
99
+ }
100
+
101
+ /** `select set_config('statement_timeout', 'value', true|false)`. */
102
+ function setConfigOf(words: readonly string[]): PinStatement | undefined {
103
+ const [, fn, open, key, , value, , local, close] = words;
104
+ const shape =
105
+ words.length === 9 &&
106
+ fn?.toLowerCase() === 'set_config' &&
107
+ open === '(' &&
108
+ key?.toLowerCase() === "'statement_timeout'" &&
109
+ words[4] === ',' &&
110
+ words[6] === ',' &&
111
+ ['true', 'false'].includes(local?.toLowerCase() ?? '') &&
112
+ close === ')' &&
113
+ value?.startsWith("'") === true;
114
+ return shape
115
+ ? { kind: 'set', value: (value ?? '').slice(1, -1).replaceAll("''", "'") }
116
+ : undefined;
117
+ }
118
+
119
+ export function pinStatement(text: string): PinStatement | undefined {
120
+ const words = pinWords(text);
121
+ if (words === undefined) return undefined;
122
+ const verb = words[0]?.toLowerCase();
123
+ switch (verb) {
124
+ case 'commit':
125
+ case 'end':
126
+ case 'abort': {
127
+ const tail = words[1]?.toLowerCase();
128
+ const bare =
129
+ words.length === 1 || (words.length === 2 && ['work', 'transaction'].includes(tail ?? ''));
130
+ return bare ? { kind: 'end' } : undefined;
131
+ }
132
+ case 'rollback':
133
+ return rollbackOf(words);
134
+ case 'savepoint': {
135
+ const name = savepointAt(words, 1, false);
136
+ return name === undefined ? undefined : { kind: 'savepoint', name };
137
+ }
138
+ case 'release': {
139
+ const name = savepointAt(words, 1, true);
140
+ return name === undefined ? undefined : { kind: 'release', name };
141
+ }
142
+ case 'reset': {
143
+ const what = words[1]?.toLowerCase();
144
+ const known = words.length === 2 && (what === 'statement_timeout' || what === 'all');
145
+ return known ? { kind: 'role-bound' } : undefined;
146
+ }
147
+ case 'set':
148
+ return setOf(words);
149
+ case 'select':
150
+ return setConfigOf(words);
151
+ default:
152
+ return undefined;
153
+ }
154
+ }
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
  }