turbine-orm 0.44.0 → 0.46.0-next.9e9c2ae
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/dist/cjs/cli/index.js +245 -52
- package/dist/cjs/cli/migrate.js +221 -16
- package/dist/cjs/index-advisor.js +0 -0
- package/dist/cjs/index-stats.js +450 -0
- package/dist/cjs/powdb.js +23 -1
- package/dist/cjs/powql.js +13 -3
- package/dist/cli/index.d.ts +5 -1
- package/dist/cli/index.js +246 -53
- package/dist/cli/migrate.d.ts +41 -9
- package/dist/cli/migrate.js +220 -16
- package/dist/index-advisor.d.ts +30 -0
- package/dist/index-advisor.js +0 -0
- package/dist/index-stats.d.ts +208 -0
- package/dist/index-stats.js +408 -0
- package/dist/powdb.d.ts +19 -2
- package/dist/powdb.js +23 -1
- package/dist/powql.js +13 -3
- package/package.json +3 -3
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Index statistics - cost-aware triage for the missing-index advisor.
|
|
3
|
+
*
|
|
4
|
+
* `index-advisor.ts` decides WHICH relation probes lack an index from pure
|
|
5
|
+
* schema topology. This module decides whether adding each one is worth it,
|
|
6
|
+
* reading live Postgres statistics (table size, write volume, existing indexes,
|
|
7
|
+
* HOT-update ratio, column null fraction) and scoring every finding into a tier:
|
|
8
|
+
*
|
|
9
|
+
* - take-freely large table, low write rate, few existing indexes;
|
|
10
|
+
* - take-deliberately real write rate, many existing indexes, or HOT at risk;
|
|
11
|
+
* - scrutinize tiny table, append-only log shape, or stats too young.
|
|
12
|
+
*
|
|
13
|
+
* DESIGN: the file splits into two halves.
|
|
14
|
+
* - The COLLECTOR half (`collectStatsSnapshot`) reads pg catalogs. It uses a
|
|
15
|
+
* single one-connection pool, sets a statement_timeout, and treats every
|
|
16
|
+
* catalog read as INDIVIDUALLY OPTIONAL: a read that fails (privileges,
|
|
17
|
+
* CockroachDB/YugabyteDB catalog gaps, missing view) degrades that one
|
|
18
|
+
* signal and records a notice rather than aborting the whole snapshot.
|
|
19
|
+
* - The PURE half (`scoreMissingIndex`, `findInvalidIndexes`, and the exported
|
|
20
|
+
* threshold constants) takes a typed {@link StatsSnapshot} and imports NO pg.
|
|
21
|
+
* It is fully unit-testable with hand-built snapshots and is what carries the
|
|
22
|
+
* thresholds the CLI prints alongside every verdict.
|
|
23
|
+
*
|
|
24
|
+
* All statistics features are Postgres-only. On a non-Postgres engine the
|
|
25
|
+
* collector returns an unavailable snapshot and the caller falls back to the
|
|
26
|
+
* topology-only report.
|
|
27
|
+
*/
|
|
28
|
+
import { buildDropIndexSql } from './index-advisor.js';
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Thresholds (exported + printed so a user can see exactly why a tier was chosen)
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
/**
|
|
33
|
+
* Heuristic thresholds behind the tier decision. Exported and surfaced in the
|
|
34
|
+
* doctor output so the reasoning is never a black box: if a threshold is wrong
|
|
35
|
+
* for a workload, the user can see the exact number that drove the verdict.
|
|
36
|
+
*/
|
|
37
|
+
export const STATS_THRESHOLDS = {
|
|
38
|
+
/** reltuples below this = tiny table; a missing index there is noise → scrutinize. */
|
|
39
|
+
tinyTableRows: 1_000,
|
|
40
|
+
/**
|
|
41
|
+
* Writes/day (n_tup_ins+upd+del normalized by stats age) at or above this is a
|
|
42
|
+
* "real" write rate: the per-index write tax is worth a second look → take deliberately.
|
|
43
|
+
*/
|
|
44
|
+
highWritesPerDay: 50_000,
|
|
45
|
+
/**
|
|
46
|
+
* Existing index count at or above this: every extra index compounds the write
|
|
47
|
+
* and storage tax, so a new one is no longer free → take deliberately.
|
|
48
|
+
*/
|
|
49
|
+
manyIndexes: 4,
|
|
50
|
+
/**
|
|
51
|
+
* HOT ratio (n_tup_hot_upd / n_tup_upd) at or above this, WITH real update
|
|
52
|
+
* volume, means the table currently relies on heap-only-tuple updates. A new
|
|
53
|
+
* index can disqualify HOT and amplify write cost → warning + take deliberately.
|
|
54
|
+
*/
|
|
55
|
+
hotRatioAtRisk: 0.3,
|
|
56
|
+
/** Minimum n_tup_upd for the HOT signal to be statistically meaningful. */
|
|
57
|
+
hotMinUpdates: 1_000,
|
|
58
|
+
/**
|
|
59
|
+
* null_frac at or above this on a probed FK column: the column is mostly NULL,
|
|
60
|
+
* so a partial `WHERE col IS NOT NULL` index covers every relation probe at a
|
|
61
|
+
* fraction of the size.
|
|
62
|
+
*/
|
|
63
|
+
partialNullFrac: 0.9,
|
|
64
|
+
/**
|
|
65
|
+
* Stats younger than this (days since stats_reset) cannot normalize a write
|
|
66
|
+
* rate; the whole report degrades to topology-only output.
|
|
67
|
+
*/
|
|
68
|
+
minStatsAgeDays: 1,
|
|
69
|
+
/** Append-heavy log shape: n_tup_ins at or above this ... */
|
|
70
|
+
appendHeavyMinInserts: 100_000,
|
|
71
|
+
/** ... with inserts making up at or above this fraction of all writes ... */
|
|
72
|
+
appendHeavyInsertRatio: 0.95,
|
|
73
|
+
/** ... and seq_scan at or below this ("near-zero probe reads") → scrutinize. */
|
|
74
|
+
appendHeavyMaxSeqScan: 5,
|
|
75
|
+
};
|
|
76
|
+
/** Build an empty (fully unavailable) snapshot - the honest "no stats" baseline. */
|
|
77
|
+
export function emptyStatsSnapshot(notices = []) {
|
|
78
|
+
return {
|
|
79
|
+
available: false,
|
|
80
|
+
statsReset: null,
|
|
81
|
+
statsAgeDays: null,
|
|
82
|
+
tables: {},
|
|
83
|
+
indexes: [],
|
|
84
|
+
nullFrac: {},
|
|
85
|
+
notices,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Format a byte count as a short human string (KB/MB/GB). */
|
|
89
|
+
export function formatBytes(bytes) {
|
|
90
|
+
if (bytes == null || !Number.isFinite(bytes))
|
|
91
|
+
return 'size unknown';
|
|
92
|
+
if (bytes < 1024)
|
|
93
|
+
return `${bytes} B`;
|
|
94
|
+
const units = ['KB', 'MB', 'GB', 'TB'];
|
|
95
|
+
let value = bytes / 1024;
|
|
96
|
+
let unit = 0;
|
|
97
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
98
|
+
value /= 1024;
|
|
99
|
+
unit++;
|
|
100
|
+
}
|
|
101
|
+
return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
|
|
102
|
+
}
|
|
103
|
+
function formatInt(n) {
|
|
104
|
+
return Math.round(n).toLocaleString('en-US');
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Score a single missing-index finding against a snapshot. Pure and total:
|
|
108
|
+
* every unknown degrades to a caveat rather than a fabricated number.
|
|
109
|
+
*/
|
|
110
|
+
export function scoreMissingIndex(missing, snapshot) {
|
|
111
|
+
const t = STATS_THRESHOLDS;
|
|
112
|
+
const stats = snapshot.tables[missing.table];
|
|
113
|
+
const probingRelations = missing.probes.length;
|
|
114
|
+
// reltuples 0/-1 = never analyzed → unknown, NOT tiny.
|
|
115
|
+
const rows = stats && stats.reltuples > 0 ? stats.reltuples : null;
|
|
116
|
+
const sizeBytes = stats?.totalSizeBytes ?? null;
|
|
117
|
+
const existingIndexCount = stats?.existingIndexCount ?? null;
|
|
118
|
+
const statsAgeDays = snapshot.statsAgeDays;
|
|
119
|
+
// Highest null_frac across the probed columns (single-column probes are the
|
|
120
|
+
// partial-index candidates; a composite FK is never rewritten to partial).
|
|
121
|
+
let nullFrac = null;
|
|
122
|
+
for (const col of missing.columns) {
|
|
123
|
+
const nf = snapshot.nullFrac[`${missing.table}.${col}`];
|
|
124
|
+
if (nf !== undefined)
|
|
125
|
+
nullFrac = nullFrac === null ? nf : Math.max(nullFrac, nf);
|
|
126
|
+
}
|
|
127
|
+
const partialNotNull = missing.columns.length === 1 && nullFrac !== null && nullFrac >= t.partialNullFrac;
|
|
128
|
+
// Write volume, normalized by stats age.
|
|
129
|
+
let writesPerDay = null;
|
|
130
|
+
if (stats &&
|
|
131
|
+
stats.nTupIns !== undefined &&
|
|
132
|
+
stats.nTupUpd !== undefined &&
|
|
133
|
+
stats.nTupDel !== undefined &&
|
|
134
|
+
statsAgeDays !== null &&
|
|
135
|
+
statsAgeDays > 0) {
|
|
136
|
+
writesPerDay = (stats.nTupIns + stats.nTupUpd + stats.nTupDel) / statsAgeDays;
|
|
137
|
+
}
|
|
138
|
+
// HOT ratio.
|
|
139
|
+
const hotRatio = stats && stats.nTupUpd !== undefined && stats.nTupUpd > 0 && stats.nTupHotUpd !== undefined
|
|
140
|
+
? stats.nTupHotUpd / stats.nTupUpd
|
|
141
|
+
: null;
|
|
142
|
+
const hotAtRisk = hotRatio !== null &&
|
|
143
|
+
stats?.nTupUpd !== undefined &&
|
|
144
|
+
hotRatio >= t.hotRatioAtRisk &&
|
|
145
|
+
stats.nTupUpd >= t.hotMinUpdates;
|
|
146
|
+
const hotWarning = hotAtRisk
|
|
147
|
+
? `${Math.round((hotRatio ?? 0) * 100)}% of updates are HOT (${formatInt(stats?.nTupUpd ?? 0)} updates since stats reset): a new index on this table can disable heap-only-tuple updates and amplify write cost`
|
|
148
|
+
: null;
|
|
149
|
+
const metrics = {
|
|
150
|
+
rows,
|
|
151
|
+
sizeBytes,
|
|
152
|
+
writesPerDay,
|
|
153
|
+
existingIndexCount,
|
|
154
|
+
probingRelations,
|
|
155
|
+
hotRatio,
|
|
156
|
+
nullFrac,
|
|
157
|
+
statsAgeDays,
|
|
158
|
+
};
|
|
159
|
+
const reasons = [];
|
|
160
|
+
// --- Scrutinize conditions (they win over everything) --------------------
|
|
161
|
+
const noStats = !stats;
|
|
162
|
+
const rowsUnknown = rows === null;
|
|
163
|
+
const tiny = rows !== null && rows < t.tinyTableRows;
|
|
164
|
+
const appendHeavy = stats?.nTupIns !== undefined &&
|
|
165
|
+
stats.nTupIns >= t.appendHeavyMinInserts &&
|
|
166
|
+
writesPerDay !== null &&
|
|
167
|
+
stats.nTupIns / Math.max(1, (stats.nTupIns ?? 0) + (stats.nTupUpd ?? 0) + (stats.nTupDel ?? 0)) >=
|
|
168
|
+
t.appendHeavyInsertRatio &&
|
|
169
|
+
(stats.seqScan ?? Number.POSITIVE_INFINITY) <= t.appendHeavyMaxSeqScan;
|
|
170
|
+
const rateUntrustable = writesPerDay === null;
|
|
171
|
+
let tier;
|
|
172
|
+
if (noStats) {
|
|
173
|
+
tier = 'scrutinize';
|
|
174
|
+
reasons.push('no statistics available for this table: cannot assess cost');
|
|
175
|
+
}
|
|
176
|
+
else if (rowsUnknown) {
|
|
177
|
+
tier = 'scrutinize';
|
|
178
|
+
reasons.push('row count unknown (table never analyzed): run ANALYZE, then re-check');
|
|
179
|
+
}
|
|
180
|
+
else if (tiny) {
|
|
181
|
+
tier = 'scrutinize';
|
|
182
|
+
reasons.push(`only ${formatInt(rows ?? 0)} rows (< ${formatInt(t.tinyTableRows)}): a sequential scan here is already cheap`);
|
|
183
|
+
}
|
|
184
|
+
else if (appendHeavy) {
|
|
185
|
+
tier = 'scrutinize';
|
|
186
|
+
reasons.push(`append-heavy: ${formatInt(stats?.nTupIns ?? 0)} inserts, near-zero reads (seq_scan ${formatInt(stats?.seqScan ?? 0)}): log-shaped table rarely benefits from a read index`);
|
|
187
|
+
}
|
|
188
|
+
else if (rateUntrustable) {
|
|
189
|
+
// Large table but the write rate cannot be normalized (young/NULL stats).
|
|
190
|
+
// Cannot claim take-freely without confirming a low write rate.
|
|
191
|
+
tier = 'scrutinize';
|
|
192
|
+
reasons.push(statsAgeDays === null
|
|
193
|
+
? 'stats reset time unknown: cannot normalize the write rate to confirm this is safe'
|
|
194
|
+
: 'write counters unavailable: cannot confirm a low write rate');
|
|
195
|
+
if (rows !== null)
|
|
196
|
+
reasons.push(`${formatInt(rows)} rows, ${formatBytes(sizeBytes)}`);
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
// --- Deliberate vs free ------------------------------------------------
|
|
200
|
+
const realWriteRate = writesPerDay !== null && writesPerDay >= t.highWritesPerDay;
|
|
201
|
+
const manyIndexes = existingIndexCount !== null && existingIndexCount >= t.manyIndexes;
|
|
202
|
+
if (realWriteRate || manyIndexes || hotAtRisk) {
|
|
203
|
+
tier = 'take-deliberately';
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
tier = 'take-freely';
|
|
207
|
+
}
|
|
208
|
+
reasons.push(`${formatInt(rows ?? 0)} rows, ${formatBytes(sizeBytes)}`);
|
|
209
|
+
if (writesPerDay !== null) {
|
|
210
|
+
reasons.push(`~${formatInt(writesPerDay)} writes/day since stats reset${statsAgeDays !== null ? ` (${formatStatsAge(statsAgeDays)} ago)` : ''}${realWriteRate ? ` - at/above the ${formatInt(t.highWritesPerDay)}/day threshold` : ''}`);
|
|
211
|
+
}
|
|
212
|
+
if (existingIndexCount !== null) {
|
|
213
|
+
reasons.push(`${existingIndexCount} existing index(es)${manyIndexes ? ` - at/above the ${t.manyIndexes}-index threshold, each new index compounds write cost` : ''}`);
|
|
214
|
+
}
|
|
215
|
+
reasons.push(`probed by ${probingRelations} relation(s)`);
|
|
216
|
+
}
|
|
217
|
+
if (hotWarning)
|
|
218
|
+
reasons.push(hotWarning);
|
|
219
|
+
if (partialNotNull) {
|
|
220
|
+
reasons.push(`column is ${Math.round((nullFrac ?? 0) * 100)}% NULL: suggesting a partial "WHERE ${missing.columns[0]} IS NOT NULL" index (caveat: a user-written where: { ${missing.columns[0]}: null } filter will NOT use it)`);
|
|
221
|
+
}
|
|
222
|
+
// Benefit sort key: bigger, more-probed tables first. Unknown rows sort last.
|
|
223
|
+
const benefitScore = (rows ?? 0) * Math.max(1, probingRelations);
|
|
224
|
+
return {
|
|
225
|
+
table: missing.table,
|
|
226
|
+
columns: missing.columns,
|
|
227
|
+
tier,
|
|
228
|
+
reasons,
|
|
229
|
+
metrics,
|
|
230
|
+
hotWarning,
|
|
231
|
+
partialNotNull,
|
|
232
|
+
benefitScore,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
function formatStatsAge(days) {
|
|
236
|
+
if (days < 1) {
|
|
237
|
+
const hours = Math.round(days * 24);
|
|
238
|
+
return `${hours}h`;
|
|
239
|
+
}
|
|
240
|
+
return `${Math.round(days)}d`;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Indexes left INVALID (indisvalid = false) - the failure artifact of a
|
|
244
|
+
* `CREATE INDEX CONCURRENTLY` that errored. `IF NOT EXISTS` on a retry silently
|
|
245
|
+
* skips the corpse, so the fix is DROP INDEX CONCURRENTLY then rerun.
|
|
246
|
+
*/
|
|
247
|
+
export function findInvalidIndexes(snapshot) {
|
|
248
|
+
return snapshot.indexes
|
|
249
|
+
.filter((idx) => !idx.isValid)
|
|
250
|
+
.map((idx) => ({
|
|
251
|
+
table: idx.table,
|
|
252
|
+
indexName: idx.indexName,
|
|
253
|
+
columns: idx.columns,
|
|
254
|
+
dropSql: buildDropIndexSql(idx.indexName, { concurrently: true }),
|
|
255
|
+
}))
|
|
256
|
+
.sort((a, b) => a.indexName.localeCompare(b.indexName));
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Whether the snapshot is trustworthy enough to render tier verdicts. Empty,
|
|
260
|
+
* unavailable, or too-young stats degrade to the topology-only report.
|
|
261
|
+
*/
|
|
262
|
+
export function isSnapshotUsable(snapshot) {
|
|
263
|
+
if (!snapshot.available)
|
|
264
|
+
return false;
|
|
265
|
+
if (snapshot.statsAgeDays === null || snapshot.statsAgeDays < STATS_THRESHOLDS.minStatsAgeDays)
|
|
266
|
+
return false;
|
|
267
|
+
// At least one table must have a known row count for the size sort to mean anything.
|
|
268
|
+
return Object.values(snapshot.tables).some((s) => s.reltuples > 0);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Read a live statistics snapshot from Postgres. Each catalog read is wrapped
|
|
272
|
+
* individually: a failure records a notice and leaves that signal absent, so a
|
|
273
|
+
* privilege gap or a CockroachDB/YugabyteDB catalog difference degrades one
|
|
274
|
+
* signal rather than the whole snapshot.
|
|
275
|
+
*/
|
|
276
|
+
export async function collectStatsSnapshot(options) {
|
|
277
|
+
const timeout = options.statementTimeoutMs ?? 5000;
|
|
278
|
+
const notices = [];
|
|
279
|
+
const snapshot = emptyStatsSnapshot(notices);
|
|
280
|
+
const { Pool } = (await import('pg')).default;
|
|
281
|
+
const pool = new Pool({ connectionString: options.connectionString, max: 1 });
|
|
282
|
+
const run = async (label, text, values) => {
|
|
283
|
+
try {
|
|
284
|
+
const res = await pool.query(text, values);
|
|
285
|
+
return res.rows;
|
|
286
|
+
}
|
|
287
|
+
catch (err) {
|
|
288
|
+
notices.push(`${label} unavailable (${err instanceof Error ? err.message.split('\n')[0] : String(err)})`);
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
try {
|
|
293
|
+
// statement_timeout is best-effort; if it fails the reads still run.
|
|
294
|
+
await run('statement_timeout', `SET statement_timeout = ${Number(timeout)}`);
|
|
295
|
+
// --- stats_reset / age --------------------------------------------------
|
|
296
|
+
const resetRows = await run('pg_stat_database.stats_reset', `SELECT stats_reset FROM pg_stat_database WHERE datname = current_database()`);
|
|
297
|
+
if (resetRows && resetRows.length > 0) {
|
|
298
|
+
const reset = resetRows[0].stats_reset;
|
|
299
|
+
snapshot.statsReset = reset ? new Date(reset) : null;
|
|
300
|
+
if (snapshot.statsReset) {
|
|
301
|
+
const ageMs = Date.now() - snapshot.statsReset.getTime();
|
|
302
|
+
snapshot.statsAgeDays = ageMs > 0 ? ageMs / 86_400_000 : null;
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
notices.push('pg_stat_database.stats_reset is NULL (statistics never reset): write rates cannot be normalized');
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// --- table stats (pg_stat_user_tables) ---------------------------------
|
|
309
|
+
const statRows = await run('pg_stat_user_tables', `SELECT relname, n_tup_ins, n_tup_upd, n_tup_del, n_tup_hot_upd, seq_scan, seq_tup_read, n_live_tup
|
|
310
|
+
FROM pg_stat_user_tables
|
|
311
|
+
WHERE schemaname = $1 AND relname = ANY($2)`, [options.schema, options.tables]);
|
|
312
|
+
// --- class size + existing index count (pg_class) ----------------------
|
|
313
|
+
const classRows = await run('pg_class size', `SELECT c.relname,
|
|
314
|
+
c.reltuples::bigint::text AS reltuples,
|
|
315
|
+
pg_total_relation_size(c.oid)::text AS total_size,
|
|
316
|
+
pg_relation_size(c.oid)::text AS table_size,
|
|
317
|
+
(SELECT count(*) FROM pg_index i WHERE i.indrelid = c.oid)::text AS index_count
|
|
318
|
+
FROM pg_class c
|
|
319
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
320
|
+
WHERE n.nspname = $1 AND c.relname = ANY($2)`, [options.schema, options.tables]);
|
|
321
|
+
// Merge table-level signals. A table appears in the snapshot if EITHER read
|
|
322
|
+
// returned it, so a missing pg_stat row still yields size info and vice versa.
|
|
323
|
+
const tableMap = snapshot.tables;
|
|
324
|
+
const ensure = (name) => {
|
|
325
|
+
let s = tableMap[name];
|
|
326
|
+
if (!s) {
|
|
327
|
+
s = { table: name, reltuples: 0 };
|
|
328
|
+
tableMap[name] = s;
|
|
329
|
+
}
|
|
330
|
+
return s;
|
|
331
|
+
};
|
|
332
|
+
if (classRows) {
|
|
333
|
+
snapshot.available = true;
|
|
334
|
+
for (const row of classRows) {
|
|
335
|
+
const s = ensure(row.relname);
|
|
336
|
+
s.reltuples = Number(row.reltuples);
|
|
337
|
+
s.totalSizeBytes = Number(row.total_size);
|
|
338
|
+
s.tableSizeBytes = Number(row.table_size);
|
|
339
|
+
s.existingIndexCount = Number(row.index_count);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (statRows) {
|
|
343
|
+
snapshot.available = true;
|
|
344
|
+
for (const row of statRows) {
|
|
345
|
+
const s = ensure(row.relname);
|
|
346
|
+
s.nTupIns = Number(row.n_tup_ins);
|
|
347
|
+
s.nTupUpd = Number(row.n_tup_upd);
|
|
348
|
+
s.nTupDel = Number(row.n_tup_del);
|
|
349
|
+
s.nTupHotUpd = Number(row.n_tup_hot_upd);
|
|
350
|
+
s.seqScan = Number(row.seq_scan);
|
|
351
|
+
s.seqTupRead = Number(row.seq_tup_read);
|
|
352
|
+
s.nLiveTup = Number(row.n_live_tup);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
// --- invalid + all indexes (whole schema, for invalid detection) -------
|
|
356
|
+
const indexRows = await run('pg_index', `SELECT c.relname AS table_name,
|
|
357
|
+
ic.relname AS index_name,
|
|
358
|
+
i.indisvalid, i.indisunique, i.indisprimary, i.indisreplident,
|
|
359
|
+
s.idx_scan::text AS idx_scan,
|
|
360
|
+
(SELECT array_agg(a.attname ORDER BY k.ord)
|
|
361
|
+
FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
362
|
+
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum) AS columns
|
|
363
|
+
FROM pg_index i
|
|
364
|
+
JOIN pg_class c ON c.oid = i.indrelid
|
|
365
|
+
JOIN pg_class ic ON ic.oid = i.indexrelid
|
|
366
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
367
|
+
LEFT JOIN pg_stat_user_indexes s ON s.indexrelid = i.indexrelid
|
|
368
|
+
WHERE n.nspname = $1`, [options.schema]);
|
|
369
|
+
if (indexRows) {
|
|
370
|
+
for (const row of indexRows) {
|
|
371
|
+
snapshot.indexes.push({
|
|
372
|
+
table: row.table_name,
|
|
373
|
+
indexName: row.index_name,
|
|
374
|
+
columns: row.columns ?? [],
|
|
375
|
+
idxScan: row.idx_scan == null ? undefined : Number(row.idx_scan),
|
|
376
|
+
isValid: row.indisvalid,
|
|
377
|
+
isUnique: row.indisunique,
|
|
378
|
+
isPrimary: row.indisprimary,
|
|
379
|
+
isReplicaIdent: row.indisreplident,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
// --- null_frac for probed columns (pg_stats) ---------------------------
|
|
384
|
+
if (options.columns.length > 0) {
|
|
385
|
+
const tablesArg = options.columns.map((c) => c.table);
|
|
386
|
+
const colsArg = options.columns.map((c) => c.column);
|
|
387
|
+
const nullRows = await run('pg_stats.null_frac', `SELECT s.tablename, s.attname, s.null_frac
|
|
388
|
+
FROM pg_stats s
|
|
389
|
+
JOIN unnest($2::text[], $3::text[]) AS probe(t, c)
|
|
390
|
+
ON probe.t = s.tablename AND probe.c = s.attname
|
|
391
|
+
WHERE s.schemaname = $1`, [options.schema, tablesArg, colsArg]);
|
|
392
|
+
if (nullRows) {
|
|
393
|
+
for (const row of nullRows) {
|
|
394
|
+
snapshot.nullFrac[`${row.tablename}.${row.attname}`] = Number(row.null_frac);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
try {
|
|
401
|
+
await pool.end();
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
/* pool teardown is best-effort */
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return snapshot;
|
|
408
|
+
}
|
package/dist/powdb.d.ts
CHANGED
|
@@ -261,11 +261,19 @@ export interface PowdbCapabilities {
|
|
|
261
261
|
* batched loaders.
|
|
262
262
|
*/
|
|
263
263
|
nestedProjections: boolean;
|
|
264
|
+
/**
|
|
265
|
+
* ≥ 0.19: entity links (`link` DDL, scalar/block traversal). Capability is
|
|
266
|
+
* recognized (probe-only), but query generation deliberately does NOT consume
|
|
267
|
+
* links yet: turbine keeps composing its own nested projections (see the
|
|
268
|
+
* PowDB engine page for the rationale). Declaring a link permanently upgrades
|
|
269
|
+
* the on-disk catalog to v7, so this stays FALSE in ALL_POWDB_CAPABILITIES.
|
|
270
|
+
*/
|
|
271
|
+
entityLinks: boolean;
|
|
264
272
|
/** Networked only: server ≥ 0.13 AND the client exposes `queryNativeRaw`. */
|
|
265
273
|
nativeRaw: boolean;
|
|
266
274
|
}
|
|
267
275
|
/** The feature-gate capability keys (everything except the version/nativeRaw metadata). */
|
|
268
|
-
type PowdbFeatureKey = 'jsonDocs' | 'docFieldIndexes' | 'introspection' | 'serverJoins' | 'nestedProjections';
|
|
276
|
+
type PowdbFeatureKey = 'jsonDocs' | 'docFieldIndexes' | 'introspection' | 'serverJoins' | 'nestedProjections' | 'entityLinks';
|
|
269
277
|
/**
|
|
270
278
|
* Trusted-caller default: every FEATURE gate on, engine version unknown. Used
|
|
271
279
|
* for a directly-constructed {@link PowdbPool} / {@link PowdbEmbeddedPool} that
|
|
@@ -275,6 +283,9 @@ type PowdbFeatureKey = 'jsonDocs' | 'docFieldIndexes' | 'introspection' | 'serve
|
|
|
275
283
|
* never inferred from a bare construction. `nestedProjections` stays OFF for
|
|
276
284
|
* the same reason: it changes the generated PowQL for every `with` query, and
|
|
277
285
|
* an unprobed engine below 0.18 would reject the syntax outright.
|
|
286
|
+
* `entityLinks` stays OFF for a stronger reason still: declaring a link
|
|
287
|
+
* one-way-upgrades the on-disk catalog to v7 and locks out pre-0.19 binaries,
|
|
288
|
+
* so it must only ever light up behind a real version probe.
|
|
278
289
|
*/
|
|
279
290
|
export declare const ALL_POWDB_CAPABILITIES: PowdbCapabilities;
|
|
280
291
|
/**
|
|
@@ -610,8 +621,14 @@ export declare function encodePowqlLiteral(value: unknown): string;
|
|
|
610
621
|
* {@link PowdbEmbeddedPool.exec}): an embedded addon whose engine line exceeds
|
|
611
622
|
* the ceiling yet still routes through the string wire is refused rather than
|
|
612
623
|
* materialized.
|
|
624
|
+
*
|
|
625
|
+
* Verification for the 0.19 line: `crates/query/src/lexer.rs` is byte-identical
|
|
626
|
+
* between v0.18.0 and v0.19.0 (empty git diff), and `link` was already a lexer
|
|
627
|
+
* keyword at 0.18.0. The 0.19 entity-links surface adds new STATEMENTS built from
|
|
628
|
+
* pre-existing tokens, so the tokenization / escape surface this ceiling guards is
|
|
629
|
+
* unmoved.
|
|
613
630
|
*/
|
|
614
|
-
export declare const POWQL_LEXER_TESTED_CEILING = "0.
|
|
631
|
+
export declare const POWQL_LEXER_TESTED_CEILING = "0.19";
|
|
615
632
|
/**
|
|
616
633
|
* Substitute every `$N` placeholder in a generator-produced PowQL template with
|
|
617
634
|
* the encoded literal of `params[N-1]`. Safe because the template is produced by
|
package/dist/powdb.js
CHANGED
|
@@ -197,6 +197,7 @@ const POWDB_FEATURE_MIN_VERSION = {
|
|
|
197
197
|
docFieldIndexes: '0.13',
|
|
198
198
|
serverJoins: '0.13',
|
|
199
199
|
nestedProjections: '0.18',
|
|
200
|
+
entityLinks: '0.19',
|
|
200
201
|
};
|
|
201
202
|
/**
|
|
202
203
|
* Trusted-caller default: every FEATURE gate on, engine version unknown. Used
|
|
@@ -207,6 +208,9 @@ const POWDB_FEATURE_MIN_VERSION = {
|
|
|
207
208
|
* never inferred from a bare construction. `nestedProjections` stays OFF for
|
|
208
209
|
* the same reason: it changes the generated PowQL for every `with` query, and
|
|
209
210
|
* an unprobed engine below 0.18 would reject the syntax outright.
|
|
211
|
+
* `entityLinks` stays OFF for a stronger reason still: declaring a link
|
|
212
|
+
* one-way-upgrades the on-disk catalog to v7 and locks out pre-0.19 binaries,
|
|
213
|
+
* so it must only ever light up behind a real version probe.
|
|
210
214
|
*/
|
|
211
215
|
export const ALL_POWDB_CAPABILITIES = {
|
|
212
216
|
engineVersion: null,
|
|
@@ -215,6 +219,7 @@ export const ALL_POWDB_CAPABILITIES = {
|
|
|
215
219
|
introspection: true,
|
|
216
220
|
serverJoins: true,
|
|
217
221
|
nestedProjections: false,
|
|
222
|
+
entityLinks: false,
|
|
218
223
|
nativeRaw: false,
|
|
219
224
|
};
|
|
220
225
|
/** Parse a PowDB semver prefix (`0.13.0`, `0.13`, `1.2.3-rc`) into components, or `null`. */
|
|
@@ -244,6 +249,7 @@ export function capabilitiesFromVersion(version, opts = {}) {
|
|
|
244
249
|
introspection: false,
|
|
245
250
|
serverJoins: false,
|
|
246
251
|
nestedProjections: false,
|
|
252
|
+
entityLinks: false,
|
|
247
253
|
nativeRaw: false,
|
|
248
254
|
};
|
|
249
255
|
}
|
|
@@ -254,6 +260,7 @@ export function capabilitiesFromVersion(version, opts = {}) {
|
|
|
254
260
|
docFieldIndexes: atLeastVersion(sem, 0, 13),
|
|
255
261
|
serverJoins: atLeastVersion(sem, 0, 13),
|
|
256
262
|
nestedProjections: atLeastVersion(sem, 0, 18),
|
|
263
|
+
entityLinks: atLeastVersion(sem, 0, 19),
|
|
257
264
|
nativeRaw: Boolean(opts.hasNativeRaw) && atLeastVersion(sem, 0, 13),
|
|
258
265
|
};
|
|
259
266
|
}
|
|
@@ -753,6 +760,15 @@ export function wrapPowdbError(err) {
|
|
|
753
760
|
return new ConnectionError(`[turbine] PowDB could not open the directory read-only: ${msg}. Open it once with a writable handle to ` +
|
|
754
761
|
'flush the WAL (recover the directory), then reopen it read-only for snapshot serving.', { cause: err });
|
|
755
762
|
}
|
|
763
|
+
// Catalog-version mismatch → ConnectionError (E004). A pre-0.19 binary/addon
|
|
764
|
+
// cannot open a data directory whose catalog was upgraded to v7 by a `link`
|
|
765
|
+
// declaration (the upgrade is one-way). It is an open-time connection failure,
|
|
766
|
+
// not a query defect, so it runs among the connection families BEFORE the
|
|
767
|
+
// generic validation regexes below.
|
|
768
|
+
if (/unsupported catalog version/i.test(msg)) {
|
|
769
|
+
return new ConnectionError(`[turbine] PowDB could not open the data directory: ${msg}. This directory uses a newer PowDB catalog ` +
|
|
770
|
+
'format (a `link` declaration upgrades it to v7); upgrade the PowDB addon/server to a version that can read it.', { cause: err });
|
|
771
|
+
}
|
|
756
772
|
// Per-query deadline → TimeoutError (E002). Message-path so it fires on the
|
|
757
773
|
// embedded transport too (code is always 'GenericFailure' there); retryable.
|
|
758
774
|
// Pass the engine prose through the message override (same pattern as the
|
|
@@ -1439,8 +1455,14 @@ export function encodePowqlLiteral(value) {
|
|
|
1439
1455
|
* {@link PowdbEmbeddedPool.exec}): an embedded addon whose engine line exceeds
|
|
1440
1456
|
* the ceiling yet still routes through the string wire is refused rather than
|
|
1441
1457
|
* materialized.
|
|
1458
|
+
*
|
|
1459
|
+
* Verification for the 0.19 line: `crates/query/src/lexer.rs` is byte-identical
|
|
1460
|
+
* between v0.18.0 and v0.19.0 (empty git diff), and `link` was already a lexer
|
|
1461
|
+
* keyword at 0.18.0. The 0.19 entity-links surface adds new STATEMENTS built from
|
|
1462
|
+
* pre-existing tokens, so the tokenization / escape surface this ceiling guards is
|
|
1463
|
+
* unmoved.
|
|
1442
1464
|
*/
|
|
1443
|
-
export const POWQL_LEXER_TESTED_CEILING = '0.
|
|
1465
|
+
export const POWQL_LEXER_TESTED_CEILING = '0.19';
|
|
1444
1466
|
/** Escape a string into a PowQL `"…"` literal, matching the engine lexer's escape rules. */
|
|
1445
1467
|
function encodePowqlString(s) {
|
|
1446
1468
|
let out = '"';
|
package/dist/powql.js
CHANGED
|
@@ -324,7 +324,11 @@ export class PowqlInterface {
|
|
|
324
324
|
conds.push(opVal === null ? `${ref} is null` : `${lhs} = ${this.bind(opVal, params, insensitive)}`);
|
|
325
325
|
break;
|
|
326
326
|
case 'not':
|
|
327
|
-
|
|
327
|
+
// Spell as `lhs != $N` (not `not (lhs = $N)`) so a missing-value row is
|
|
328
|
+
// EXCLUDED, matching SQL null semantics on PowDB >= 0.18.2. Behavior-neutral
|
|
329
|
+
// on older engines (pre-0.18.2 `!=` MATCHED missing rows exactly like the
|
|
330
|
+
// old `not (...)` spelling), so no capability gate is needed.
|
|
331
|
+
conds.push(opVal === null ? `${ref} is not null` : `${lhs} != ${this.bind(opVal, params, insensitive)}`);
|
|
328
332
|
break;
|
|
329
333
|
case 'gt':
|
|
330
334
|
conds.push(`${lhs} > ${this.bind(opVal, params, insensitive)}`);
|
|
@@ -466,11 +470,17 @@ export class PowqlInterface {
|
|
|
466
470
|
/** `lhs [not] in ($1, $2, …)` — empty list collapses to a constant. */
|
|
467
471
|
buildInList(lhs, values, params, insensitive, negate) {
|
|
468
472
|
if (!Array.isArray(values) || values.length === 0) {
|
|
469
|
-
// `in []` matches nothing; `not in []` matches everything
|
|
473
|
+
// `in []` matches nothing; `not in []` matches everything (SQL parity requires a
|
|
474
|
+
// missing-value row to match `notIn []`, so NO presence guard is appended here).
|
|
470
475
|
return negate ? '(1 = 1)' : this.alwaysFalse();
|
|
471
476
|
}
|
|
472
477
|
const items = values.map((v) => this.bind(v, params, insensitive)).join(', ');
|
|
473
|
-
|
|
478
|
+
if (negate) {
|
|
479
|
+
// PowQL `not in` matches missing-value rows, so append `and lhs is not null`
|
|
480
|
+
// for SQL null-semantics parity (non-empty list only, per the empty-list note above).
|
|
481
|
+
return `(${lhs} not in (${items}) and ${lhs} is not null)`;
|
|
482
|
+
}
|
|
483
|
+
return `${lhs} in (${items})`;
|
|
474
484
|
}
|
|
475
485
|
/**
|
|
476
486
|
* Pre-resolve every relation filter (`some`/`none`/`every`) in a where clause
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "turbine-orm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.0-next.9e9c2ae",
|
|
4
4
|
"description": "Postgres-native TypeScript ORM — runs on Neon, Vercel Postgres, Cloudflare, Supabase. Streaming cursors, typed errors, single-query nested relations. One dependency, no WASM engine",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -108,8 +108,8 @@
|
|
|
108
108
|
"@size-limit/esbuild": "^12.1.0",
|
|
109
109
|
"@size-limit/file": "^12.1.0",
|
|
110
110
|
"@types/node": "^26.1.0",
|
|
111
|
-
"@zvndev/powdb-client": "^0.
|
|
112
|
-
"@zvndev/powdb-embedded": "^0.
|
|
111
|
+
"@zvndev/powdb-client": "^0.19.0",
|
|
112
|
+
"@zvndev/powdb-embedded": "^0.19.0",
|
|
113
113
|
"c8": "^11.0.0",
|
|
114
114
|
"husky": "^9.1.7",
|
|
115
115
|
"lint-staged": "^17.0.8",
|