@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.
- package/CLAUDE.md +32 -31
- package/README.md +4 -0
- package/package.json +2 -2
- package/src/client.ts +2 -2
- package/src/drift-findings.ts +4 -1
- package/src/drift-index-keys.ts +54 -0
- package/src/drift.ts +14 -2
- package/src/entity-shape.ts +27 -5
- package/src/errors.ts +2 -0
- package/src/generate-history.ts +8 -2
- package/src/generate-snapshot.ts +3 -0
- package/src/generate.ts +9 -1
- package/src/index-ddl.ts +17 -6
- package/src/index-extension.ts +34 -0
- package/src/index-key-ddl.ts +159 -0
- package/src/index-plan.ts +38 -6
- package/src/index.ts +29 -0
- package/src/introspect-index.ts +110 -0
- package/src/introspect.ts +11 -52
- package/src/migration-lock-lint.ts +184 -0
- package/src/pin-statement.ts +154 -0
- package/src/pool-gate.ts +68 -13
- package/src/pool-pins.ts +74 -17
- package/src/rolling.ts +25 -12
- package/src/slow-statement-log.ts +103 -0
- package/src/snapshot-parse.ts +15 -0
- package/src/table-storage.ts +222 -0
package/CLAUDE.md
CHANGED
|
@@ -77,25 +77,21 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
77
77
|
|
|
78
78
|
## Observation
|
|
79
79
|
|
|
80
|
-
- **No observer slot** (v31): every statement is a `db.statement` event on core's bus
|
|
81
|
-
|
|
82
|
-
`
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
`
|
|
86
|
-
Each funnel reads core's `callerStack()` at its ENTRY (before the pool/turn-queue `await`) and
|
|
87
|
-
hands it to `traceStatement` as `DbStatementEvent.callerStack` — `undefined`, nothing built,
|
|
88
|
-
unless `captureStatementStacks()` is held (the `statements` fixture; never production).
|
|
80
|
+
- **No observer slot** (v31): every statement is a `db.statement` event on core's bus, emitted by
|
|
81
|
+
`traceStatement` (`statement-span.ts`), the ONE shell both funnels (`statement-funnel.ts`,
|
|
82
|
+
`pglite.ts`) call; guarded by `subscribed('db.statement')`, on success and failure, a
|
|
83
|
+
subscriber's throw contained by the bus. A subscriber issues no SQL. A `set*Observer` is
|
|
84
|
+
`X_INSTRUMENT_SLOT_FORBIDDEN`. `callerStack` is read at funnel ENTRY, built only under
|
|
85
|
+
`captureStatementStacks()` (the `statements` fixture).
|
|
89
86
|
- **`attribution.ts`**: `withStatementAttribution(entity, op, fn)` — guard first (two strings, no
|
|
90
87
|
allocation; the guard is `subscribed('db.statement')`), a scope not a parameter, innermost pair wins; the funnels stamp it on both settle paths.
|
|
91
88
|
`@ultimat3/entity`'s `postgresRepo` is the one producer.
|
|
92
89
|
- **`statement-shape.ts`**: `statementFingerprint(event)` (`entity.op` when attributed, else collapsed
|
|
93
90
|
text) and `statementKind(text)` off `statementVerb(text)`. Read by `x dev`'s ledger and
|
|
94
91
|
`@ultimat3/testing`'s `statements` fixture. It counts nothing.
|
|
95
|
-
- **`statement-span.ts`**: `withStatementSpan` wraps the send alone — `db.<verb>`,
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
included, subscriber or not.
|
|
92
|
+
- **`statement-span.ts`**: `withStatementSpan` wraps the send alone — `db.<verb>`, kind `client`,
|
|
93
|
+
core's `SEMCONV` attributes only. **Opened for every statement**, subscriber or not.
|
|
94
|
+
- **`slow-statement-log.ts`** — `db.statement` subscriber; the runtime installs it.
|
|
99
95
|
- **`expected-loop.ts` is the ONLY suppression**: `expectedQueryLoop(reason, fn)`, innermost reason,
|
|
100
96
|
blank is `X_INVARIANT`; the funnel stamps `expected`; it suppresses a verdict, never a statement.
|
|
101
97
|
The framework's own loops declare themselves (`migrate()`, `rollback()`, admin's `search.ts`).
|
|
@@ -103,8 +99,8 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
103
99
|
- **`failure-store-pg.ts` writes `x_failures` through `outsideTransaction`** — the 5xx rolled the
|
|
104
100
|
request's transaction back. Table applied by the boot (`FRAMEWORK_SCHEMA`) whether capture is on
|
|
105
101
|
or not; bundles only (counts are `x_error_groups`'). `failurePurgeTarget` has no default window.
|
|
106
|
-
- `@ultimat3/jobs` never imports this package; its statements reach the bus
|
|
107
|
-
|
|
102
|
+
- `@ultimat3/jobs` never imports this package; its statements reach the bus via `dbExecutor`
|
|
103
|
+
(`db-executor.ts`, the ONE `PgExecutor` builder), unattributed.
|
|
108
104
|
|
|
109
105
|
## Migrations
|
|
110
106
|
|
|
@@ -121,18 +117,19 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
121
117
|
on it.** `lock: false` reserves nothing and takes no lock; no shipped path passes it
|
|
122
118
|
(`migrate-pin.test.ts`). `migrate.live.test.ts` pins concurrent and failed-midway runs.
|
|
123
119
|
- **One send is one statement**: `applyScript` sends `statementsOf(script)` one at a time. Full rule: `docs/history/db.md`.
|
|
124
|
-
- **`destructive.ts` decides WHAT is destructive**:
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
-
|
|
129
|
-
|
|
120
|
+
- **`destructive.ts` decides WHAT is destructive**: `up` only, four forms (`drop table`, `drop
|
|
121
|
+
column`, `truncate`, `alter column … type`) on blanked text; a marker is a top-level line comment
|
|
122
|
+
(`marker-line.ts`). `X_MIGRATION_DESTRUCTIVE` (ship) ≠ `X_MIGRATION_IRREVERSIBLE` (generate).
|
|
123
|
+
- **`migration-lock-lint.ts`** — `X_MIGRATION_LOCK_HEAVY`: `set not null` with no prior validate,
|
|
124
|
+
non-concurrent `create index` on an existing table; `-- lock-heavy: true` admits; ids > `LOCK_HEAVY_SINCE`.
|
|
125
|
+
- **The ledger audit asks one question**: `auditLedger`'s `foreign` is `!known.has(row.id)`.
|
|
130
126
|
- **`refuseDependentViews(tx, script)`** (`dependent-view.ts`) runs before each migration's first statement. Full rule: `docs/history/db.md`.
|
|
131
127
|
|
|
132
128
|
## Generation (`x db gen`)
|
|
133
129
|
|
|
134
130
|
- **`generate.ts` reads an index, never re-derives one** — `IndexDescriptionLike` carries columns,
|
|
135
|
-
unique, `where`, `order`, `using
|
|
131
|
+
unique, `where`, `order`, `using`, and (`index-key-ddl.ts`) `expression`, `orders`, `include`,
|
|
132
|
+
`operatorClass`; each absent hashes as before. No column is `X_INVARIANT`.
|
|
136
133
|
- **An index's ACCESS METHOD is carried end to end**. Full rule: `docs/history/db.md`.
|
|
137
134
|
- **`index-plan.ts` walks both directions**; a removal and a `concurrently: true` build on a live table go to the non-transactional step (`concurrent-plan.ts`). Full rule: `docs/history/db.md`.
|
|
138
135
|
- **An entity's INVARIANTS reach the DDL** (`invariant-ddl.ts`): `check` a named constraint, `unique` a unique index, `assert` nothing. Full rule: `docs/history/db.md`.
|
|
@@ -189,22 +186,26 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
189
186
|
expression) vs `TableDescription.checkNames` (catalog: `conname` for `contype = 'c'`, always written
|
|
190
187
|
by `introspectSchema()`, `[]` included). Only the declared side is judged; never a `changed-check`.
|
|
191
188
|
`drift-check.live.test.ts`.
|
|
192
|
-
- `compareTable` judges declared indexes (`missing-index`, `changed-index` over method,
|
|
193
|
-
|
|
189
|
+
- `compareTable` judges declared indexes (`missing-index`, `changed-index` over method, key parts
|
|
190
|
+
— `drift-index-keys.ts`: expression presence, per-key directions, INCLUDE, operator class —
|
|
191
|
+
column list, uniqueness, predicate presence, direction; `asc` is `null`); never expression or
|
|
192
|
+
predicate text. `introspect-index.ts` reads them, each part only when present.
|
|
194
193
|
- `compareForeignKeys` matches on where a key points (`foreignKeyTarget`, the one copy) and compares
|
|
195
194
|
`onDelete` through `onDeleteRule` (`changed-foreign-key`; its fix, `changed-column`'s and
|
|
196
195
|
`missing-check`'s are one `psql -c` too — `repair()`, schema-scoped off `public`).
|
|
197
|
-
- `introspectSchema()` reads index
|
|
198
|
-
|
|
199
|
-
- **`
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
196
|
+
- `introspectSchema()` reads index keys in `indkey` order and a key's two column lists together
|
|
197
|
+
(`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`.
|
|
200
|
+
- **`appTables()`** excludes all of `x_` for drift; `introspectSchema()` only `x_migrations`.
|
|
201
|
+
`nonAppRelations` (`app-relation.ts`): extension-owned, views, matviews, foreign tables,
|
|
202
|
+
partitions — always excluded.
|
|
203
203
|
- **A partitioned parent is a table, a partition is not**; a concurrent build on one is
|
|
204
204
|
`X_MIGRATION_CONCURRENT_PARTITIONED`. `docs/history/db.md` (2026-11-06).
|
|
205
205
|
- **`dbDrift()` lives in `drift-errors.ts`** (it needs `shellInertIdentifier`), the only one.
|
|
206
206
|
`errors.ts` registers `DB_ERROR_TITLES` unconditionally.
|
|
207
|
-
- **`not-valid-constraint`** (`compareValidated`): `notValidNames` is catalog-only (`convalidated
|
|
207
|
+
- **`not-valid-constraint`** (`compareValidated`): `notValidNames` is catalog-only (`convalidated`),
|
|
208
|
+
declared side judged, keys by target; fix = the validate statement.
|
|
208
209
|
- `drift-findings.ts` holds the `DriftDifference` constructors and `DriftKind`; `drift-missing.ts` the
|
|
209
210
|
missing/rebuilt ones (table, column, index, foreign key); `drift.ts` keeps the comparisons. **No
|
|
210
211
|
drift fix is `x db migrate`**: the ledger holds the migration, so it applies nothing — every fix is a
|
package/README.md
CHANGED
|
@@ -44,6 +44,10 @@ await withTransaction(async (tx) => {
|
|
|
44
44
|
| `poolerFromEnv()` / `POOLER_ENV` / `PoolerMode` / `POOLER_WAIT_MS` / `statementBound()` / `lostStatementBound()` / `StatementBound` / `poolerSessionRequired()` | `As of 2026-11-03`: a connection pooler in the path (`pooler.ts`), and the two bounds as the session reads them. [Pool sizing by role](#pool-sizing-by-role) |
|
|
45
45
|
| `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 |
|
|
46
46
|
| `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 |
|
|
47
|
+
| `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 |
|
|
48
|
+
| `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
|
+
| `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 |
|
|
50
|
+
| `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` |
|
|
47
51
|
| `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 |
|
|
48
52
|
| `checkDrift()` / `diffSchema()` / `assertNoSchemaDrift()` | drift, with a `--json` report. `checkDrift()` is the **post-migrate verification** — the live database against the ledger: columns, declared indexes (access method `As of 2026-08-24`, columns, uniqueness, direction, and whether a predicate is there at all — never its text), declared CHECK constraints by NAME (`missing-check`, `As of 2026-08-25` — never a predicate, which the catalog answers rewritten) and declared foreign keys, matched on where the key points and not on its constraint name, with the `on delete` rule compared through one normalisation `As of 2026-08-19` |
|
|
49
53
|
| `declaredSchema()` / `expectedSchema()` | `As of 2026-08`: the schema the migrations write down, or `undefined` when the newest one carries no snapshot — never an older snapshot standing in for it |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/db",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.8.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.
|
|
48
|
+
"@ultimat3/core": "31.8.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"@electric-sql/pglite": ">=0.5.0"
|
package/src/client.ts
CHANGED
|
@@ -153,7 +153,7 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
|
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
async function run(fragment: SqlFragment): Promise<unknown> {
|
|
156
|
-
const slot = takeSlot(connect, profile.acquireTimeoutMs);
|
|
156
|
+
const slot = takeSlot(connect, profile.acquireTimeoutMs, fragment.text);
|
|
157
157
|
const live = slot instanceof Promise ? await slot : slot;
|
|
158
158
|
// Pooled only: a pin's statement belongs to a transaction, and cancelling it is not ours to do.
|
|
159
159
|
const watch = watchAbort(fragment.text);
|
|
@@ -189,7 +189,7 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
|
|
|
189
189
|
// One gate slot for the life of the pin, so one number counts statements and pins alike.
|
|
190
190
|
const budget = profile.acquireTimeoutMs;
|
|
191
191
|
const started = performance.now();
|
|
192
|
-
const live = await takeSlot(connect, budget);
|
|
192
|
+
const live = await takeSlot(connect, budget, undefined);
|
|
193
193
|
let reserved: BunSqlReserved;
|
|
194
194
|
try {
|
|
195
195
|
// `reserveWithin` keeps its own timer for `Bun.SQL`'s queue, on what the gate left of ONE
|
package/src/drift-findings.ts
CHANGED
|
@@ -37,7 +37,10 @@ export type DriftKind =
|
|
|
37
37
|
| 'unexpected-row-security'
|
|
38
38
|
// Constructed in `object-drift.ts`: a trigger, function, view, type or sequence in the live
|
|
39
39
|
// database that replaying the migrations does not create.
|
|
40
|
-
| 'unexpected-object'
|
|
40
|
+
| 'unexpected-object'
|
|
41
|
+
// Constructed in `@ultimat3/cli`'s `db-object-drift.ts` from `tableStorageDrift`: a framework
|
|
42
|
+
// table whose persistence or fillfactor is not what its `tableStorage()` declares.
|
|
43
|
+
| 'changed-table-storage';
|
|
41
44
|
|
|
42
45
|
export interface DriftDifference {
|
|
43
46
|
readonly kind: DriftKind;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Single responsibility: drift's reading of an index's key parts past a plain column list — an
|
|
2
|
+
// expression key, per-key directions, INCLUDE, the operator class. Answers what the live index
|
|
3
|
+
// "is" when it differs from the declaration, in `changedIndex`'s words, or `null` when they agree.
|
|
4
|
+
// Split from `drift.ts` (ceiling); `compareIndexes` asks it after the method, before the columns.
|
|
5
|
+
|
|
6
|
+
import type { IndexDescription } from './introspect';
|
|
7
|
+
|
|
8
|
+
type Index = IndexDescription;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The effective direction of every key, `asc` folded into `null` — `drift.ts`'s normalisation for
|
|
12
|
+
* `order`, because `createIndex` writes `asc` and Postgres stores it as not-descending. `orders`
|
|
13
|
+
* when present, else `order` repeated: a declared `['desc', 'desc']` and a catalog `order: 'desc'`
|
|
14
|
+
* are the same index.
|
|
15
|
+
*/
|
|
16
|
+
const directions = (index: Index): readonly ('desc' | null)[] =>
|
|
17
|
+
(index.orders ?? index.columns.map(() => index.order)).map((d) => (d === 'desc' ? 'desc' : null));
|
|
18
|
+
|
|
19
|
+
/** Whether this comparison owns the direction question — the plain `order` check yields to it. */
|
|
20
|
+
export const ownsDirection = (live: Index, expected: Index): boolean =>
|
|
21
|
+
live.orders !== undefined || expected.orders !== undefined;
|
|
22
|
+
|
|
23
|
+
/** Whether this comparison owns the key-list question — an expression's text is the catalog's. */
|
|
24
|
+
export const ownsKeys = (expected: Index): boolean => expected.expression !== undefined;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* An expression key's TEXT is never compared — the catalog answers its rewriting
|
|
28
|
+
* (`lower((email)::text)`), the predicate's reason in `drift.ts`. Its PRESENCE is: one key, marked
|
|
29
|
+
* by the parentheses `introspect-index.ts` puts on every expression key.
|
|
30
|
+
*/
|
|
31
|
+
export function keyPartsChange(live: Index, expected: Index): string | null {
|
|
32
|
+
if (ownsKeys(expected)) {
|
|
33
|
+
const [only] = live.columns;
|
|
34
|
+
if (live.columns.length !== 1 || only === undefined || !only.startsWith('(')) {
|
|
35
|
+
return `covers (${live.columns.join(', ')}), not one expression`;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (ownsDirection(live, expected)) {
|
|
39
|
+
const have = directions(live);
|
|
40
|
+
if (have.join(',') !== directions(expected).join(',')) {
|
|
41
|
+
return `orders its keys (${have.map((d) => d ?? 'asc').join(', ')})`;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const include = (index: Index): string => (index.include ?? []).join(', ');
|
|
45
|
+
if (include(live) !== include(expected)) {
|
|
46
|
+
return include(live) === '' ? 'includes no columns' : `includes (${include(live)})`;
|
|
47
|
+
}
|
|
48
|
+
if ((live.operatorClass ?? null) !== (expected.operatorClass ?? null)) {
|
|
49
|
+
return live.operatorClass === undefined
|
|
50
|
+
? 'uses the default operator class'
|
|
51
|
+
: `uses ${live.operatorClass}`;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
package/src/drift.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
unexpectedTable,
|
|
17
17
|
unknownSchema,
|
|
18
18
|
} from './drift-findings';
|
|
19
|
+
import { keyPartsChange, ownsDirection, ownsKeys } from './drift-index-keys';
|
|
19
20
|
import {
|
|
20
21
|
changedIndex,
|
|
21
22
|
missingColumn,
|
|
@@ -101,7 +102,15 @@ function compareIndexes(live: TableDescription, expected: TableDescription): Dri
|
|
|
101
102
|
);
|
|
102
103
|
continue;
|
|
103
104
|
}
|
|
104
|
-
|
|
105
|
+
// The key parts past a plain column list (`drift-index-keys.ts`): an expression key, per-key
|
|
106
|
+
// directions, INCLUDE, the operator class. Asked before the column list, which an expression
|
|
107
|
+
// key's catalog spelling could never equal.
|
|
108
|
+
const keyChange = keyPartsChange(counterpart, index);
|
|
109
|
+
if (keyChange !== null) {
|
|
110
|
+
differences.push(changedIndex(live.schema, live.name, index, counterpart, keyChange));
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (!ownsKeys(index) && counterpart.columns.join(',') !== index.columns.join(',')) {
|
|
105
114
|
differences.push(
|
|
106
115
|
changedIndex(
|
|
107
116
|
live.schema,
|
|
@@ -125,7 +134,10 @@ function compareIndexes(live: TableDescription, expected: TableDescription): Dri
|
|
|
125
134
|
);
|
|
126
135
|
continue;
|
|
127
136
|
}
|
|
128
|
-
if (
|
|
137
|
+
if (
|
|
138
|
+
!ownsDirection(counterpart, index) &&
|
|
139
|
+
(counterpart.order ?? 'asc') !== (index.order ?? 'asc')
|
|
140
|
+
) {
|
|
129
141
|
differences.push(
|
|
130
142
|
changedIndex(
|
|
131
143
|
live.schema,
|
package/src/entity-shape.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// part of it — a column's `on delete` rule included — crosses the seam by shape or not at all.
|
|
4
4
|
|
|
5
5
|
import type { ColumnDefaultLike } from './column-default';
|
|
6
|
+
import type { IndexOperatorClass } from './index-key-ddl';
|
|
6
7
|
import type { IndexMethod } from './index-method';
|
|
7
8
|
|
|
8
9
|
/** Structurally assignment-compatible with `@ultimat3/entity`'s `ColumnDescription`. */
|
|
@@ -108,13 +109,29 @@ export interface IndexDescriptionLike {
|
|
|
108
109
|
*/
|
|
109
110
|
readonly using?: IndexMethod | undefined;
|
|
110
111
|
/**
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
112
|
+
* HOW the index is built, never WHAT it is — not part of the name, not recorded in a snapshot
|
|
113
|
+
* and never a reason to rebuild one. Absent or `true`: on a table that already exists, `create
|
|
114
|
+
* index concurrently` in a migration of its own OUTSIDE a transaction (`concurrent-index.ts`), so
|
|
115
|
+
* a hot table keeps taking writes. `false`: the plain, transactional build, which `index-plan.ts`
|
|
116
|
+
* marks `-- lock-heavy: true` for `X_MIGRATION_LOCK_HEAVY`. A table the same migration creates,
|
|
117
|
+
* and a partitioned parent (`0A000`), are always built plainly.
|
|
116
118
|
*/
|
|
117
119
|
readonly concurrently?: boolean | undefined;
|
|
120
|
+
/**
|
|
121
|
+
* The four parts past a plain column list (`index-key-ddl.ts` renders them). Each is optional
|
|
122
|
+
* and absent by default, for `using`'s reason: a description written before them emits, records
|
|
123
|
+
* and compares exactly as it did.
|
|
124
|
+
*
|
|
125
|
+
* `expression`: the ONE key is this SQL expression (`lower(email)`, `(payload->>'kind')`), and
|
|
126
|
+
* `columns` names the columns it reads — what a foreign key's covering rule looks at.
|
|
127
|
+
*/
|
|
128
|
+
readonly expression?: string | undefined;
|
|
129
|
+
/** A direction per key, in key order; `null` writes none. Replaces `order`, never beside it. */
|
|
130
|
+
readonly orders?: readonly ('asc' | 'desc' | null)[] | undefined;
|
|
131
|
+
/** INCLUDE payload columns — stored in the index, never keyed (btree only). */
|
|
132
|
+
readonly include?: readonly string[] | undefined;
|
|
133
|
+
/** An operator class on every key. One member: `gin_trgm_ops`, which `contains` needs (gin only). */
|
|
134
|
+
readonly operatorClass?: IndexOperatorClass | undefined;
|
|
118
135
|
}
|
|
119
136
|
|
|
120
137
|
/** Structurally assignment-compatible with `@ultimat3/entity`'s `EntityDescription`. */
|
|
@@ -193,6 +210,11 @@ export interface HistoryDescriptionLike {
|
|
|
193
210
|
readonly text?: readonly string[] | undefined;
|
|
194
211
|
/** `timestamptz` columns the image stores as a UTC ISO string, whatever the session zone. */
|
|
195
212
|
readonly instants?: readonly string[] | undefined;
|
|
213
|
+
/**
|
|
214
|
+
* Sealed columns, left out of both images: their stored string is ciphertext, and a lookup
|
|
215
|
+
* one is deterministic — two rows' equal values would be equal in history. Absent is none.
|
|
216
|
+
*/
|
|
217
|
+
readonly sealed?: readonly string[] | undefined;
|
|
196
218
|
}
|
|
197
219
|
|
|
198
220
|
/** One counter, physical names: `<this table>.<column>` counts `<table>` rows by `<references>`. */
|
package/src/errors.ts
CHANGED
|
@@ -59,6 +59,7 @@ export const DB_OWNED_ERROR_CODES = [
|
|
|
59
59
|
'X_ENTITY_RETAIN_INVALID',
|
|
60
60
|
'X_LIFECYCLE_TRIGGER_MISSING',
|
|
61
61
|
'X_MIGRATION_PARTITION_CHANGE',
|
|
62
|
+
'X_MIGRATION_LOCK_HEAVY',
|
|
62
63
|
] as const;
|
|
63
64
|
|
|
64
65
|
/**
|
|
@@ -133,6 +134,7 @@ export const DB_ERROR_TITLES: Readonly<Record<DbOwnedErrorCode, string>> = {
|
|
|
133
134
|
X_LIFECYCLE_TRIGGER_MISSING:
|
|
134
135
|
'a history or counter trigger the migrations created is missing from the database',
|
|
135
136
|
X_MIGRATION_PARTITION_CHANGE: 'an existing table gained or lost entity({ partitionBy })',
|
|
137
|
+
X_MIGRATION_LOCK_HEAVY: 'this migration holds a live table still for a full scan',
|
|
136
138
|
};
|
|
137
139
|
|
|
138
140
|
// Registered unconditionally, in one call, so a second package claiming one of db's codes fails
|
package/src/generate-history.ts
CHANGED
|
@@ -37,7 +37,10 @@ const exact = (image: string, how: { readonly type: string; readonly text: strin
|
|
|
37
37
|
* column, the columns whose change alone records nothing (the counters the database keeps), and the
|
|
38
38
|
* columns `to_jsonb` spells otherwise than the row: an `int8`/`numeric` stored as its digits (a JSON
|
|
39
39
|
* number is a float to every reader past 2^53 and drops a scale's zeros), a `timestamptz` as UTC ISO
|
|
40
|
-
* to the millisecond (`to_jsonb` writes the SESSION zone's offset) — what the memory driver keeps
|
|
40
|
+
* to the millisecond (`to_jsonb` writes the SESSION zone's offset) — what the memory driver keeps —
|
|
41
|
+
* and the sealed columns, removed from both images before anything else reads them: ciphertext, and
|
|
42
|
+
* a lookup column's is deterministic, so history would compare rows the app cannot. Their change
|
|
43
|
+
* alone records nothing, exactly as an ignored column's.
|
|
41
44
|
* An argument a trigger installed before it existed reads NULL, and NULL is the empty list.
|
|
42
45
|
*
|
|
43
46
|
* `jsonb_populate_record` builds the history row, so every value lands in its column's own type —
|
|
@@ -53,8 +56,10 @@ export const HISTORY_FUNCTION_SQL =
|
|
|
53
56
|
'ignored text[] := tg_argv[3]::text[]; ' +
|
|
54
57
|
"digits text[] := coalesce(tg_argv[4], '{}')::text[]; " +
|
|
55
58
|
"instants text[] := coalesce(tg_argv[5], '{}')::text[]; " +
|
|
59
|
+
"sealed text[] := coalesce(tg_argv[6], '{}')::text[]; " +
|
|
56
60
|
'k text; ' +
|
|
57
|
-
|
|
61
|
+
'begin source := source - sealed; prior := prior - sealed; ' +
|
|
62
|
+
"if tg_op = 'UPDATE' and (prior - ignored) = (source - ignored) then return null; end if; " +
|
|
58
63
|
'foreach k in array digits loop ' +
|
|
59
64
|
`${exact('source', DIGITS)} ${exact('prior', DIGITS)} end loop; ` +
|
|
60
65
|
'foreach k in array instants loop ' +
|
|
@@ -116,6 +121,7 @@ export function historyTriggers(
|
|
|
116
121
|
nameArray(history.ignore),
|
|
117
122
|
nameArray(history.text ?? []),
|
|
118
123
|
nameArray(history.instants ?? []),
|
|
124
|
+
nameArray(history.sealed ?? []),
|
|
119
125
|
].join(', ');
|
|
120
126
|
return [
|
|
121
127
|
[
|
package/src/generate-snapshot.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { defaultExpression } from './column-default';
|
|
|
7
7
|
import type { EntityDescriptionLike } from './entity-shape';
|
|
8
8
|
import { foreignKeysOf } from './foreign-key-plan';
|
|
9
9
|
import { splitViews, viewDescriptionOf } from './generate-view';
|
|
10
|
+
import { declaredKeyParts } from './index-key-ddl';
|
|
10
11
|
import type { ColumnDescription, SchemaDescription, TableDescription } from './introspect';
|
|
11
12
|
import { declaredIndexes } from './invariant-ddl';
|
|
12
13
|
import { withSameTenantIndexes } from './same-tenant';
|
|
@@ -65,6 +66,8 @@ export function snapshotOf(
|
|
|
65
66
|
// every sidecar in every app on the next `x db gen` — a diff on every file for a fact
|
|
66
67
|
// that was already true, which `indexMethodOf` reads out of the absence anyway.
|
|
67
68
|
...(index.using === undefined ? {} : { using: index.using }),
|
|
69
|
+
// The four key parts, the same rule: each only when declared (`declaredKeyParts`).
|
|
70
|
+
...declaredKeyParts(index.name, index),
|
|
68
71
|
})),
|
|
69
72
|
foreignKeys: foreignKeysOf(entity),
|
|
70
73
|
// Absent, never `[]`, on a table declaring none: a sidecar that predates this field must
|
package/src/generate.ts
CHANGED
|
@@ -21,6 +21,7 @@ import { splitViews, viewPlan } from './generate-view';
|
|
|
21
21
|
import type { Regeneration } from './generated-column';
|
|
22
22
|
import { generatedClause, isGenerated, regenerate } from './generated-column';
|
|
23
23
|
import { createIndex, impliedByColumnClause } from './index-ddl';
|
|
24
|
+
import { extensionStatements } from './index-extension';
|
|
24
25
|
import { indexPlan } from './index-plan';
|
|
25
26
|
import {
|
|
26
27
|
type ColumnDescription,
|
|
@@ -446,7 +447,14 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
|
|
|
446
447
|
return assembleSteps({
|
|
447
448
|
id,
|
|
448
449
|
name: options.name,
|
|
449
|
-
|
|
450
|
+
// An index's extension first (`index-extension.ts`): `gin_trgm_ops` does not exist before it.
|
|
451
|
+
up: [
|
|
452
|
+
...extensionStatements(options.entities, current),
|
|
453
|
+
...viewed.before.up,
|
|
454
|
+
...preAlters.up,
|
|
455
|
+
...plan.up,
|
|
456
|
+
...viewed.after.up,
|
|
457
|
+
],
|
|
450
458
|
// Reverse order: the last thing created is the first thing dropped. `preAlters` goes in at the
|
|
451
459
|
// FRONT here precisely so reversal puts it last — a key is added back only once both of its
|
|
452
460
|
// ends have been retyped back, which is every other statement in the script.
|
package/src/index-ddl.ts
CHANGED
|
@@ -8,6 +8,13 @@ import { assert } from '@ultimat3/core';
|
|
|
8
8
|
import { indexOrderInvalid, indexPredicateUnsafe } from './ddl-errors';
|
|
9
9
|
import type { EntityDescriptionLike, IndexDescriptionLike } from './entity-shape';
|
|
10
10
|
import type { Plan } from './foreign-key-plan';
|
|
11
|
+
import {
|
|
12
|
+
declaredKeyParts,
|
|
13
|
+
hasKeyParts,
|
|
14
|
+
indexIncludeSql,
|
|
15
|
+
indexKeyShape,
|
|
16
|
+
indexKeysSql,
|
|
17
|
+
} from './index-key-ddl';
|
|
11
18
|
import { declaredMethod, indexMethodOf, indexMethodSql } from './index-method';
|
|
12
19
|
import type { IndexDescription } from './introspect';
|
|
13
20
|
import { identifier } from './sql';
|
|
@@ -118,17 +125,17 @@ export function createIndex(
|
|
|
118
125
|
const kind =
|
|
119
126
|
(index.unique ? 'create unique index' : 'create index') +
|
|
120
127
|
(concurrently ? ' concurrently if not exists' : '');
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
128
|
+
// Keys, then INCLUDE, then the predicate — Postgres' clause order. Both helpers answer the plain
|
|
129
|
+
// column list and `''` for an index declaring none of the newer parts: the same bytes as before.
|
|
130
|
+
const columns = indexKeysSql(index, indexOrderSql(index));
|
|
131
|
+
const include = indexIncludeSql(index);
|
|
125
132
|
const predicate = indexPredicateSql(index);
|
|
126
133
|
// Re-derived from the closed set, never spliced: `indexMethodSql` answers `''` for a btree, so
|
|
127
134
|
// an index that declared no method emits the statement this generator always emitted, byte for
|
|
128
135
|
// byte, and one that declared a method Postgres does not have is refused instead of built.
|
|
129
136
|
return (
|
|
130
137
|
`${kind} ${identifier(index.name).text} on ${identifier(table).text}` +
|
|
131
|
-
`${indexMethodSql(method)} (${columns})${predicate};`
|
|
138
|
+
`${indexMethodSql(method)} (${columns})${include}${predicate};`
|
|
132
139
|
);
|
|
133
140
|
}
|
|
134
141
|
|
|
@@ -159,7 +166,8 @@ export function mayBeConstraintBacked(index: IndexDescription): boolean {
|
|
|
159
166
|
!index.primary &&
|
|
160
167
|
index.where === null &&
|
|
161
168
|
index.order === null &&
|
|
162
|
-
indexMethodOf(index) === 'btree'
|
|
169
|
+
indexMethodOf(index) === 'btree' &&
|
|
170
|
+
!hasKeyParts(index)
|
|
163
171
|
);
|
|
164
172
|
}
|
|
165
173
|
|
|
@@ -177,6 +185,7 @@ export function asDeclared(index: IndexDescription): IndexDescriptionLike {
|
|
|
177
185
|
where: index.where,
|
|
178
186
|
order: index.order,
|
|
179
187
|
...(index.using === undefined ? {} : { using: declaredMethod(index.using) }),
|
|
188
|
+
...declaredKeyParts(index.name, index),
|
|
180
189
|
};
|
|
181
190
|
}
|
|
182
191
|
|
|
@@ -188,6 +197,8 @@ export function indexShape(index: IndexDescriptionLike | IndexDescription): stri
|
|
|
188
197
|
index.where,
|
|
189
198
|
index.order ?? null,
|
|
190
199
|
indexMethodOf(index),
|
|
200
|
+
// Spread, so an index declaring none of the four parts hashes exactly as it always did.
|
|
201
|
+
...indexKeyShape(index),
|
|
191
202
|
]);
|
|
192
203
|
}
|
|
193
204
|
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Single responsibility: the `create extension` an index needs before it can be built — today one,
|
|
2
|
+
// `pg_trgm` for `gin_trgm_ops` — emitted by `x db gen` once, in the migration that first builds
|
|
3
|
+
// such an index. Never dropped in `down`: another index, or the app's own SQL, may use it.
|
|
4
|
+
|
|
5
|
+
import type { EntityDescriptionLike } from './entity-shape';
|
|
6
|
+
import { requiredExtension } from './index-key-ddl';
|
|
7
|
+
import { findTable, type SchemaDescription } from './introspect';
|
|
8
|
+
import { declaredIndexes } from './invariant-ddl';
|
|
9
|
+
import { identifier } from './sql';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `create extension if not exists …` for each extension a declared index needs whose recorded
|
|
13
|
+
* counterpart did not already need it — so the migration that adds the first trigram index carries
|
|
14
|
+
* it, and the next `x db gen` (the index recorded) carries nothing. Sorted, one per extension.
|
|
15
|
+
*/
|
|
16
|
+
export function extensionStatements(
|
|
17
|
+
entities: readonly EntityDescriptionLike[],
|
|
18
|
+
current: SchemaDescription,
|
|
19
|
+
): readonly string[] {
|
|
20
|
+
const needed = new Set<string>();
|
|
21
|
+
for (const entity of entities) {
|
|
22
|
+
const recorded = findTable(current, entity.table)?.indexes ?? [];
|
|
23
|
+
for (const index of declaredIndexes(entity)) {
|
|
24
|
+
const extension = requiredExtension(index);
|
|
25
|
+
if (extension === null) continue;
|
|
26
|
+
const before = recorded.find((each) => each.name === index.name);
|
|
27
|
+
if (before !== undefined && requiredExtension(before) === extension) continue;
|
|
28
|
+
needed.add(extension);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return [...needed]
|
|
32
|
+
.sort()
|
|
33
|
+
.map((extension) => `create extension if not exists ${identifier(extension).text};`);
|
|
34
|
+
}
|