@x12i/countex 1.8.3 → 1.9.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.
Files changed (77) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +866 -858
  3. package/dist/cli.js +6 -6
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/insights/advisors/resource-advisor.d.ts.map +1 -1
  9. package/dist/insights/advisors/resource-advisor.js +5 -1
  10. package/dist/insights/advisors/resource-advisor.js.map +1 -1
  11. package/dist/insights/types.d.ts +4 -0
  12. package/dist/insights/types.d.ts.map +1 -1
  13. package/dist/storage/postgres.d.ts +104 -0
  14. package/dist/storage/postgres.d.ts.map +1 -0
  15. package/dist/storage/postgres.js +1023 -0
  16. package/dist/storage/postgres.js.map +1 -0
  17. package/dist/types/index.d.ts +11 -5
  18. package/dist/types/index.d.ts.map +1 -1
  19. package/docs/DEPLOYMENT.md +399 -375
  20. package/docs/END_TO_END_EXAMPLE.md +316 -316
  21. package/docs/INSIGHTS.md +59 -59
  22. package/docs/INSIGHTS_ANOMALY_DETECTION.md +33 -33
  23. package/docs/INSIGHTS_LLM_COST_AND_TOKENS.md +26 -26
  24. package/docs/INSIGHTS_RESOURCE_ADVISOR.md +33 -31
  25. package/docs/countex_gap_analysis_complete_checklist.md +1340 -1340
  26. package/docs/guides/README.md +36 -34
  27. package/docs/guides/adapter-memory.md +60 -60
  28. package/docs/guides/adapter-mongo.md +64 -62
  29. package/docs/guides/adapter-postgres.md +90 -0
  30. package/docs/guides/adapter-redis.md +89 -89
  31. package/docs/guides/backup-export.md +135 -135
  32. package/docs/guides/cardinality.md +50 -50
  33. package/docs/guides/cli.md +53 -53
  34. package/docs/guides/client-events.md +65 -65
  35. package/docs/guides/counter-maps.md +160 -160
  36. package/docs/guides/idempotency.md +39 -39
  37. package/docs/guides/ingestion-and-flush.md +67 -67
  38. package/docs/guides/insights-advisors-and-optimization.md +39 -39
  39. package/docs/guides/insights-anomalies-and-rules.md +48 -48
  40. package/docs/guides/insights-comparison-and-trends.md +47 -47
  41. package/docs/guides/insights-forecasting-and-budget.md +61 -61
  42. package/docs/guides/insights-overview.md +82 -82
  43. package/docs/guides/insights-ranking.md +81 -81
  44. package/docs/guides/measures.md +71 -71
  45. package/docs/guides/migrating-mongo-to-postgres.md +127 -0
  46. package/docs/guides/preview.md +92 -92
  47. package/docs/guides/querying.md +178 -178
  48. package/docs/guides/simulation-profiles.md +33 -33
  49. package/docs/guides/simulation-resource-estimation.md +31 -30
  50. package/docs/guides/simulation.md +36 -36
  51. package/docs/guides/timeframes-and-bucketing.md +55 -55
  52. package/docs/internals/README.md +21 -21
  53. package/docs/internals/internal-architecture-overview.md +65 -65
  54. package/docs/internals/internal-backup-stream.md +23 -23
  55. package/docs/internals/internal-buffer-merge-and-flush.md +51 -51
  56. package/docs/internals/internal-cardinality.md +30 -30
  57. package/docs/internals/internal-dimension-hash.md +34 -34
  58. package/docs/internals/internal-idempotency.md +36 -36
  59. package/docs/internals/internal-ingest-pipeline.md +52 -52
  60. package/docs/internals/internal-insights-layer.md +36 -36
  61. package/docs/internals/internal-mapping-validation-and-extraction.md +59 -59
  62. package/docs/internals/internal-measures-and-scales.md +35 -35
  63. package/docs/internals/internal-query-path.md +46 -46
  64. package/docs/internals/internal-storage-memory.md +13 -13
  65. package/docs/internals/internal-storage-mongo.md +44 -44
  66. package/docs/internals/internal-storage-postgres.md +32 -0
  67. package/docs/internals/internal-storage-redis.md +63 -63
  68. package/docs/internals/internal-timeframe-bucketing.md +33 -33
  69. package/docs/use-cases/README.md +56 -56
  70. package/docs/use-cases/audit-security-log-counts.md +550 -550
  71. package/docs/use-cases/llm-cost-and-token-metering.md +255 -255
  72. package/docs/use-cases/multi-tenant-isolation.md +203 -203
  73. package/docs/use-cases/ops-dashboard-daily-rollups.md +255 -255
  74. package/docs/use-cases/processing-workflow-activity.md +165 -165
  75. package/docs/use-cases/product-feature-usage.md +240 -240
  76. package/docs/use-cases/webhook-idempotent-ingestion.md +188 -188
  77. package/package.json +184 -169
@@ -0,0 +1,1023 @@
1
+ "use strict";
2
+ /**
3
+ * PostgreSQL durable adapter.
4
+ *
5
+ * Same cell, dictionary, sequence, and evidence semantics as MongoDurable.
6
+ * Writes are batched `INSERT … ON CONFLICT DO UPDATE` increments so concurrent
7
+ * flushes add counts instead of replacing them. Measure math runs in SQL.
8
+ *
9
+ * The host owns the `pg` Pool (connect, TLS, shutdown), same as MongoClient.
10
+ * Requires PostgreSQL 15+ (unique constraints on partitioned tables).
11
+ *
12
+ * Layout (one schema, default `countex`):
13
+ * cells — list-partitioned by timeframe_type (minute, hour, default)
14
+ * dict — (scope, kind, qualifier, source_key) → internal_id
15
+ * seq — per-scope dictionary id block
16
+ * evidence — exemplar payloads trimmed to maxSamplesAtCapture
17
+ *
18
+ * Identity columns are not updated on increment, so counter updates can be
19
+ * HOT. fillfactor and a tighter autovacuum scale factor are set on the
20
+ * minute/hour/default partitions for that reason.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.PostgresDurable = exports.POSTGRES_CELL_SCHEMA_VERSION = void 0;
24
+ const index_js_1 = require("../types/index.js");
25
+ const snapshot_encoding_js_1 = require("../backup/snapshot-encoding.js");
26
+ const timeframe_js_1 = require("../core/timeframe.js");
27
+ const errors_js_1 = require("../utils/errors.js");
28
+ const hash_js_1 = require("../utils/hash.js");
29
+ /** Persisted on cell rows. Aligns with COUNTEX_CELL_SCHEMA_VERSION. */
30
+ exports.POSTGRES_CELL_SCHEMA_VERSION = 1;
31
+ /** Default rows per INSERT. Keeps a flush to a handful of round-trips. */
32
+ const DEFAULT_BATCH_SIZE = 1000;
33
+ const IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
34
+ class PostgresDurable {
35
+ opts;
36
+ ready = new Map();
37
+ constructor(opts) {
38
+ const batch = opts.batchSize ?? DEFAULT_BATCH_SIZE;
39
+ this.opts = {
40
+ pool: opts.pool,
41
+ schema: assertIdent(opts.schema ?? "countex", "schema"),
42
+ schemaResolver: opts.schemaResolver,
43
+ cellsTable: assertIdent(opts.cellsTable ?? "cells", "cellsTable"),
44
+ dictTable: assertIdent(opts.dictTable ?? "dict", "dictTable"),
45
+ seqTable: assertIdent(opts.seqTable ?? "seq", "seqTable"),
46
+ evidenceTable: assertIdent(opts.evidenceTable ?? "evidence", "evidenceTable"),
47
+ skipIndexInit: opts.skipIndexInit ?? false,
48
+ batchSize: Number.isFinite(batch) && batch >= 1 ? Math.floor(batch) : DEFAULT_BATCH_SIZE,
49
+ };
50
+ }
51
+ async init() {
52
+ if (this.opts.schemaResolver)
53
+ return;
54
+ await this.ensureSchema(this.opts.schema);
55
+ }
56
+ async close() {
57
+ // The host owns the pool.
58
+ }
59
+ async applyDeltas(deltas, opts) {
60
+ if (deltas.length === 0)
61
+ return;
62
+ throwIfAborted(opts?.signal, "applyDeltas aborted");
63
+ const collapsed = collapseDeltas(deltas).sort((a, b) => (0, hash_js_1.cellKey)(a.identity).localeCompare((0, hash_js_1.cellKey)(b.identity)));
64
+ const bySchema = new Map();
65
+ for (const delta of collapsed) {
66
+ const schema = this.schemaFor(delta.identity.scopeId);
67
+ const arr = bySchema.get(schema) ?? [];
68
+ arr.push(delta);
69
+ bySchema.set(schema, arr);
70
+ }
71
+ for (const schema of bySchema.keys()) {
72
+ await this.ensureSchema(schema);
73
+ }
74
+ const client = await this.opts.pool.connect();
75
+ try {
76
+ await client.query("BEGIN");
77
+ for (const [schema, group] of bySchema) {
78
+ for (const batch of chunk(group, this.opts.batchSize)) {
79
+ throwIfAborted(opts?.signal, "applyDeltas aborted");
80
+ await client.query(incrementSql(schema, this.opts.cellsTable), incrementParams(batch));
81
+ }
82
+ }
83
+ await client.query("COMMIT");
84
+ }
85
+ catch (err) {
86
+ await rollback(client);
87
+ throw asStorageError("Postgres applyDeltas failed", err);
88
+ }
89
+ finally {
90
+ client.release();
91
+ }
92
+ }
93
+ async readCells(spec, opts) {
94
+ throwIfAborted(opts?.signal, "readCells aborted");
95
+ const schema = this.schemaFor(spec.scope);
96
+ await this.ensureSchema(schema);
97
+ const filter = cellFilter(spec);
98
+ const limit = spec.limit && !spec.groupBy?.length ? spec.limit : undefined;
99
+ const params = filter.params;
100
+ let sql = `SELECT * FROM ${qual(schema, this.opts.cellsTable)} WHERE ${filter.where}`;
101
+ if (limit !== undefined) {
102
+ params.push(limit);
103
+ sql += ` LIMIT $${params.length}`;
104
+ }
105
+ try {
106
+ const res = await this.opts.pool.query(sql, params);
107
+ return res.rows.map(rowToCell);
108
+ }
109
+ catch (err) {
110
+ throw asStorageError("Postgres readCells failed", err);
111
+ }
112
+ }
113
+ async importSnapshotCells(cells, opts) {
114
+ if (cells.length === 0)
115
+ return;
116
+ throwIfAborted(opts?.signal, "importSnapshotCells aborted");
117
+ const collapsed = collapseSnapshots(cells).sort((a, b) => (0, hash_js_1.cellKey)(a).localeCompare((0, hash_js_1.cellKey)(b)));
118
+ const bySchema = new Map();
119
+ for (const cell of collapsed) {
120
+ const schema = this.schemaFor(cell.scopeId);
121
+ const arr = bySchema.get(schema) ?? [];
122
+ arr.push(cell);
123
+ bySchema.set(schema, arr);
124
+ }
125
+ for (const schema of bySchema.keys()) {
126
+ await this.ensureSchema(schema);
127
+ }
128
+ const client = await this.opts.pool.connect();
129
+ try {
130
+ await client.query("BEGIN");
131
+ for (const [schema, group] of bySchema) {
132
+ for (const batch of chunk(group, this.opts.batchSize)) {
133
+ throwIfAborted(opts?.signal, "importSnapshotCells aborted");
134
+ await client.query(replaceSql(schema, this.opts.cellsTable), replaceParams(batch));
135
+ }
136
+ }
137
+ await client.query("COMMIT");
138
+ }
139
+ catch (err) {
140
+ await rollback(client);
141
+ throw asStorageError("Postgres importSnapshotCells failed", err);
142
+ }
143
+ finally {
144
+ client.release();
145
+ }
146
+ }
147
+ async resolveIds(lookups, opts) {
148
+ const out = new Map();
149
+ if (lookups.length === 0)
150
+ return out;
151
+ throwIfAborted(opts?.signal, "resolveIds aborted");
152
+ const bySchema = groupLookups(lookups, (l) => this.schemaFor(l.scopeId));
153
+ for (const [schema, group] of bySchema) {
154
+ await this.ensureSchema(schema);
155
+ const have = await this.readDict(schema, group);
156
+ const missing = group.filter((l) => !have.has(dictKey(l)));
157
+ if (missing.length > 0) {
158
+ const byScope = groupLookups(missing, (l) => l.scopeId);
159
+ for (const [scope, scopeMissing] of byScope) {
160
+ throwIfAborted(opts?.signal, "resolveIds aborted");
161
+ const startId = await this.allocateIds(schema, scope, scopeMissing.length);
162
+ await this.insertDict(schema, scopeMissing.map((l, i) => ({ lookup: l, internalId: startId + i })));
163
+ }
164
+ const reread = await this.readDict(schema, missing);
165
+ for (const [key, id] of reread)
166
+ have.set(key, id);
167
+ for (const l of missing) {
168
+ if (!have.has(dictKey(l))) {
169
+ throw new errors_js_1.StorageError("Failed to allocate dict id", { lookup: l });
170
+ }
171
+ }
172
+ }
173
+ for (const l of group) {
174
+ const id = have.get(dictKey(l));
175
+ if (id !== undefined)
176
+ out.set(dictKey(l), id);
177
+ }
178
+ }
179
+ return out;
180
+ }
181
+ async lookupIds(lookups, opts) {
182
+ const out = new Map();
183
+ if (lookups.length === 0)
184
+ return out;
185
+ throwIfAborted(opts?.signal, "lookupIds aborted");
186
+ const bySchema = groupLookups(lookups, (l) => this.schemaFor(l.scopeId));
187
+ for (const [schema, group] of bySchema) {
188
+ await this.ensureSchema(schema);
189
+ const have = await this.readDict(schema, group);
190
+ for (const l of group)
191
+ out.set(dictKey(l), have.get(dictKey(l)));
192
+ }
193
+ return out;
194
+ }
195
+ async reverseLookupIds(requests, opts) {
196
+ const out = new Map();
197
+ if (requests.length === 0)
198
+ return out;
199
+ throwIfAborted(opts?.signal, "reverseLookupIds aborted");
200
+ const bySchema = new Map();
201
+ for (const r of requests) {
202
+ const schema = this.schemaFor(r.scopeId);
203
+ const arr = bySchema.get(schema) ?? [];
204
+ arr.push(r);
205
+ bySchema.set(schema, arr);
206
+ }
207
+ for (const [schema, group] of bySchema) {
208
+ await this.ensureSchema(schema);
209
+ const dict = qual(schema, this.opts.dictTable);
210
+ try {
211
+ const res = await this.opts.pool.query(`SELECT scope_id, kind, qualifier, source_key, internal_id
212
+ FROM ${dict}
213
+ WHERE (scope_id, kind, qualifier, internal_id) IN (
214
+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::bigint[])
215
+ )`, [
216
+ group.map((r) => r.scopeId),
217
+ group.map((r) => r.kind),
218
+ group.map((r) => r.qualifier ?? ""),
219
+ group.map((r) => r.internalId),
220
+ ]);
221
+ for (const row of res.rows) {
222
+ out.set((0, index_js_1.reverseDictResultKey)({
223
+ scopeId: row.scope_id,
224
+ kind: row.kind,
225
+ qualifier: row.qualifier,
226
+ internalId: asNumber(row.internal_id),
227
+ }), row.source_key);
228
+ }
229
+ }
230
+ catch (err) {
231
+ throw asStorageError("Postgres reverseLookupIds failed", err);
232
+ }
233
+ }
234
+ return out;
235
+ }
236
+ async *streamCells(filter, opts) {
237
+ throwIfAborted(opts?.signal, "streamCells aborted");
238
+ const schema = this.schemaFor(filter.scope);
239
+ await this.ensureSchema(schema);
240
+ const spec = {
241
+ scope: filter.scope,
242
+ counterId: filter.counterId,
243
+ timeframe: filter.timeframe,
244
+ };
245
+ const base = cellFilter(spec);
246
+ const table = qual(schema, this.opts.cellsTable);
247
+ const order = "timeframe_key, subject_type, subject_id, metric_id, dimensions_hash";
248
+ let cursor = null;
249
+ for (;;) {
250
+ throwIfAborted(opts?.signal, "streamCells aborted");
251
+ const params = [...base.params];
252
+ let where = base.where;
253
+ if (cursor) {
254
+ params.push(cursor.timeframeKey, cursor.subjectType, cursor.subjectId, cursor.metricId, cursor.dimensionsHash);
255
+ const n = base.params.length;
256
+ where += ` AND (${order}) > ($${n + 1}, $${n + 2}, $${n + 3}::float8, $${n + 4}::float8, $${n + 5})`;
257
+ }
258
+ params.push(500);
259
+ const sql = `SELECT * FROM ${table} WHERE ${where} ORDER BY ${order} LIMIT $${params.length}`;
260
+ let res;
261
+ try {
262
+ res = await this.opts.pool.query(sql, params);
263
+ }
264
+ catch (err) {
265
+ throw asStorageError("Postgres streamCells failed", err);
266
+ }
267
+ if (res.rows.length === 0)
268
+ return;
269
+ for (const row of res.rows)
270
+ yield rowToCell(row);
271
+ const last = res.rows[res.rows.length - 1];
272
+ cursor = {
273
+ timeframeKey: last.timeframe_key,
274
+ subjectType: last.subject_type,
275
+ subjectId: asNumber(last.subject_id),
276
+ metricId: asNumber(last.metric_id),
277
+ dimensionsHash: last.dimensions_hash,
278
+ };
279
+ if (res.rows.length < 500)
280
+ return;
281
+ }
282
+ }
283
+ async appendEvidence(records, opts) {
284
+ if (records.length === 0)
285
+ return;
286
+ throwIfAborted(opts?.signal, "appendEvidence aborted");
287
+ const bySchema = new Map();
288
+ for (const record of records) {
289
+ const schema = this.schemaFor(record.identity.scopeId);
290
+ const arr = bySchema.get(schema) ?? [];
291
+ arr.push(record);
292
+ bySchema.set(schema, arr);
293
+ }
294
+ for (const schema of bySchema.keys()) {
295
+ await this.ensureSchema(schema);
296
+ }
297
+ const client = await this.opts.pool.connect();
298
+ try {
299
+ await client.query("BEGIN");
300
+ for (const [schema, group] of bySchema) {
301
+ throwIfAborted(opts?.signal, "appendEvidence aborted");
302
+ const table = qual(schema, this.opts.evidenceTable);
303
+ await client.query(`INSERT INTO ${table} (
304
+ scope_id, counter_id, timeframe_type, timeframe_key,
305
+ subject_type, subject_id, metric_id, dimensions_hash,
306
+ dimensions, payload, source_event_id, captured_at, max_samples_at_capture
307
+ )
308
+ SELECT
309
+ d.scope_id, d.counter_id, d.timeframe_type, d.timeframe_key,
310
+ d.subject_type, d.subject_id, d.metric_id, d.dimensions_hash,
311
+ d.dimensions::jsonb, d.payload::jsonb, NULLIF(d.source_event_id, ''),
312
+ d.captured_at::timestamptz, d.max_samples
313
+ FROM unnest(
314
+ $1::text[], $2::text[], $3::text[], $4::text[],
315
+ $5::text[], $6::float8[], $7::float8[], $8::text[],
316
+ $9::text[], $10::text[], $11::text[], $12::text[], $13::int[]
317
+ ) AS d(
318
+ scope_id, counter_id, timeframe_type, timeframe_key,
319
+ subject_type, subject_id, metric_id, dimensions_hash,
320
+ dimensions, payload, source_event_id, captured_at, max_samples
321
+ )`, [
322
+ group.map((r) => r.identity.scopeId),
323
+ group.map((r) => r.identity.counterId),
324
+ group.map((r) => r.identity.timeframeType),
325
+ group.map((r) => r.identity.timeframeKey),
326
+ group.map((r) => r.identity.subjectType),
327
+ group.map((r) => r.identity.subjectId),
328
+ group.map((r) => r.identity.metricId),
329
+ group.map((r) => r.identity.dimensionsHash),
330
+ group.map((r) => JSON.stringify(r.identity.dimensions ?? {})),
331
+ group.map((r) => JSON.stringify(r.payload ?? {})),
332
+ group.map((r) => r.sourceEventId ?? ""),
333
+ group.map((r) => r.capturedAt.toISOString()),
334
+ group.map((r) => r.maxSamplesAtCapture),
335
+ ]);
336
+ const unique = new Map();
337
+ for (const record of group) {
338
+ const key = (0, hash_js_1.cellKey)(record.identity);
339
+ if (!unique.has(key)) {
340
+ unique.set(key, { identity: record.identity, maxSamples: record.maxSamplesAtCapture });
341
+ }
342
+ }
343
+ for (const { identity, maxSamples } of unique.values()) {
344
+ const count = await client.query(`SELECT COUNT(*)::int AS n FROM ${table}
345
+ WHERE scope_id = $1 AND counter_id = $2 AND timeframe_type = $3 AND timeframe_key = $4
346
+ AND subject_type = $5 AND subject_id = $6 AND metric_id = $7 AND dimensions_hash = $8`, identityParams(identity));
347
+ const total = count.rows[0]?.n ?? 0;
348
+ if (total > maxSamples) {
349
+ await client.query(`DELETE FROM ${table}
350
+ WHERE id IN (
351
+ SELECT id FROM ${table}
352
+ WHERE scope_id = $1 AND counter_id = $2 AND timeframe_type = $3 AND timeframe_key = $4
353
+ AND subject_type = $5 AND subject_id = $6 AND metric_id = $7 AND dimensions_hash = $8
354
+ ORDER BY captured_at ASC, id ASC
355
+ LIMIT $9
356
+ )`, [...identityParams(identity), total - maxSamples]);
357
+ }
358
+ }
359
+ }
360
+ await client.query("COMMIT");
361
+ }
362
+ catch (err) {
363
+ await rollback(client);
364
+ throw asStorageError("Postgres appendEvidence failed", err);
365
+ }
366
+ finally {
367
+ client.release();
368
+ }
369
+ }
370
+ schemaFor(scope) {
371
+ const name = this.opts.schemaResolver?.({ scope }) ?? this.opts.schema;
372
+ return assertIdent(name, "schema");
373
+ }
374
+ ensureSchema(schema) {
375
+ if (this.opts.skipIndexInit)
376
+ return Promise.resolve();
377
+ const existing = this.ready.get(schema);
378
+ if (existing)
379
+ return existing;
380
+ const job = this.createSchema(schema).catch((err) => {
381
+ this.ready.delete(schema);
382
+ throw err;
383
+ });
384
+ this.ready.set(schema, job);
385
+ return job;
386
+ }
387
+ async createSchema(schema) {
388
+ const cells = qual(schema, this.opts.cellsTable);
389
+ const dict = qual(schema, this.opts.dictTable);
390
+ const seq = qual(schema, this.opts.seqTable);
391
+ const evidence = qual(schema, this.opts.evidenceTable);
392
+ const s = quoteIdent(schema);
393
+ const partitionOpts = "fillfactor = 85, autovacuum_vacuum_scale_factor = 0.05, autovacuum_vacuum_threshold = 1000, autovacuum_analyze_scale_factor = 0.02";
394
+ const sql = `
395
+ CREATE SCHEMA IF NOT EXISTS ${s};
396
+ ${mergeMeasuresFunctionSql(schema)}
397
+ CREATE TABLE IF NOT EXISTS ${cells} (
398
+ scope_id text NOT NULL,
399
+ counter_id text NOT NULL,
400
+ timeframe_type text NOT NULL,
401
+ timeframe_key text NOT NULL,
402
+ subject_type text NOT NULL,
403
+ subject_id double precision NOT NULL,
404
+ metric_id double precision NOT NULL,
405
+ dimensions_hash text NOT NULL,
406
+ dimensions jsonb NOT NULL DEFAULT '{}'::jsonb,
407
+ count double precision NOT NULL,
408
+ measures jsonb,
409
+ schema_version integer NOT NULL DEFAULT ${exports.POSTGRES_CELL_SCHEMA_VERSION},
410
+ created_at timestamptz NOT NULL,
411
+ updated_at timestamptz NOT NULL,
412
+ CONSTRAINT ${quoteIdent(`uniq_${this.opts.cellsTable}_identity`)} UNIQUE (
413
+ counter_id, scope_id, timeframe_type, timeframe_key,
414
+ subject_type, subject_id, metric_id, dimensions_hash
415
+ )
416
+ ) PARTITION BY LIST (timeframe_type);
417
+ CREATE TABLE IF NOT EXISTS ${qual(schema, `${this.opts.cellsTable}_minute`)}
418
+ PARTITION OF ${cells} FOR VALUES IN ('minute')
419
+ WITH (${partitionOpts});
420
+ CREATE TABLE IF NOT EXISTS ${qual(schema, `${this.opts.cellsTable}_hour`)}
421
+ PARTITION OF ${cells} FOR VALUES IN ('hour')
422
+ WITH (${partitionOpts});
423
+ CREATE TABLE IF NOT EXISTS ${qual(schema, `${this.opts.cellsTable}_default`)}
424
+ PARTITION OF ${cells} DEFAULT
425
+ WITH (${partitionOpts});
426
+ CREATE INDEX IF NOT EXISTS ${quoteIdent(`${this.opts.cellsTable}_by_subject`)}
427
+ ON ${cells} (counter_id, scope_id, subject_id, timeframe_type, timeframe_key);
428
+ CREATE INDEX IF NOT EXISTS ${quoteIdent(`${this.opts.cellsTable}_by_metric`)}
429
+ ON ${cells} (counter_id, scope_id, metric_id, timeframe_type, timeframe_key);
430
+ CREATE TABLE IF NOT EXISTS ${dict} (
431
+ scope_id text NOT NULL,
432
+ kind text NOT NULL,
433
+ qualifier text NOT NULL DEFAULT '',
434
+ source_key text NOT NULL,
435
+ internal_id bigint NOT NULL,
436
+ CONSTRAINT ${quoteIdent(`uniq_${this.opts.dictTable}_key`)} UNIQUE (scope_id, kind, qualifier, source_key)
437
+ );
438
+ CREATE INDEX IF NOT EXISTS ${quoteIdent(`${this.opts.dictTable}_reverse_lookup`)}
439
+ ON ${dict} (scope_id, kind, qualifier, internal_id);
440
+ CREATE TABLE IF NOT EXISTS ${seq} (
441
+ scope_id text PRIMARY KEY,
442
+ seq bigint NOT NULL
443
+ );
444
+ CREATE TABLE IF NOT EXISTS ${evidence} (
445
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
446
+ scope_id text NOT NULL,
447
+ counter_id text NOT NULL,
448
+ timeframe_type text NOT NULL,
449
+ timeframe_key text NOT NULL,
450
+ subject_type text NOT NULL,
451
+ subject_id double precision NOT NULL,
452
+ metric_id double precision NOT NULL,
453
+ dimensions_hash text NOT NULL,
454
+ dimensions jsonb NOT NULL,
455
+ payload jsonb NOT NULL,
456
+ source_event_id text,
457
+ captured_at timestamptz NOT NULL,
458
+ max_samples_at_capture integer NOT NULL
459
+ );
460
+ CREATE INDEX IF NOT EXISTS ${quoteIdent(`${this.opts.evidenceTable}_cell_time`)}
461
+ ON ${evidence} (
462
+ scope_id, counter_id, timeframe_type, timeframe_key,
463
+ subject_type, subject_id, metric_id, dimensions_hash, captured_at
464
+ );
465
+ `;
466
+ for (let attempt = 0; attempt < 2; attempt++) {
467
+ try {
468
+ await this.opts.pool.query(sql);
469
+ return;
470
+ }
471
+ catch (err) {
472
+ const code = err.code;
473
+ if (attempt === 0 && code && ["42P06", "42P07", "23505", "42710"].includes(code)) {
474
+ continue;
475
+ }
476
+ throw asStorageError("Postgres schema init failed", err);
477
+ }
478
+ }
479
+ }
480
+ async readDict(schema, lookups) {
481
+ const have = new Map();
482
+ if (lookups.length === 0)
483
+ return have;
484
+ const dict = qual(schema, this.opts.dictTable);
485
+ try {
486
+ const res = await this.opts.pool.query(`SELECT scope_id, kind, qualifier, source_key, internal_id
487
+ FROM ${dict}
488
+ WHERE (scope_id, kind, qualifier, source_key) IN (
489
+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::text[])
490
+ )`, [
491
+ lookups.map((l) => l.scopeId),
492
+ lookups.map((l) => l.kind),
493
+ lookups.map((l) => l.qualifier ?? ""),
494
+ lookups.map((l) => l.sourceKey),
495
+ ]);
496
+ for (const row of res.rows) {
497
+ have.set((0, index_js_1.dictionaryLookupKey)({
498
+ scopeId: row.scope_id,
499
+ kind: row.kind,
500
+ qualifier: row.qualifier,
501
+ sourceKey: row.source_key,
502
+ }), asNumber(row.internal_id));
503
+ }
504
+ return have;
505
+ }
506
+ catch (err) {
507
+ throw asStorageError("Postgres dict read failed", err);
508
+ }
509
+ }
510
+ async allocateIds(schema, scope, count) {
511
+ const seq = qual(schema, this.opts.seqTable);
512
+ try {
513
+ const res = await this.opts.pool.query(`INSERT INTO ${seq} AS id_seq (scope_id, seq) VALUES ($1, $2)
514
+ ON CONFLICT (scope_id) DO UPDATE SET seq = id_seq.seq + EXCLUDED.seq
515
+ RETURNING seq`, [scope, count]);
516
+ const value = res.rows[0]?.seq;
517
+ if (value === undefined)
518
+ throw new errors_js_1.StorageError("Failed to allocate sequence", { scope });
519
+ const after = asNumber(value);
520
+ return after - count + 1;
521
+ }
522
+ catch (err) {
523
+ throw asStorageError("Postgres allocateIds failed", err);
524
+ }
525
+ }
526
+ async insertDict(schema, rows) {
527
+ if (rows.length === 0)
528
+ return;
529
+ const dict = qual(schema, this.opts.dictTable);
530
+ try {
531
+ await this.opts.pool.query(`INSERT INTO ${dict} (scope_id, kind, qualifier, source_key, internal_id)
532
+ SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::text[], $5::bigint[])
533
+ ON CONFLICT (scope_id, kind, qualifier, source_key) DO NOTHING`, [
534
+ rows.map((r) => r.lookup.scopeId),
535
+ rows.map((r) => r.lookup.kind),
536
+ rows.map((r) => r.lookup.qualifier ?? ""),
537
+ rows.map((r) => r.lookup.sourceKey),
538
+ rows.map((r) => r.internalId),
539
+ ]);
540
+ }
541
+ catch (err) {
542
+ throw asStorageError("Postgres dict insert failed", err);
543
+ }
544
+ }
545
+ }
546
+ exports.PostgresDurable = PostgresDurable;
547
+ function incrementSql(schema, cellsTable) {
548
+ const cells = qual(schema, cellsTable);
549
+ const fn = `${quoteIdent(schema)}.merge_measures`;
550
+ return `
551
+ INSERT INTO ${cells} AS c (
552
+ scope_id, counter_id, timeframe_type, timeframe_key,
553
+ subject_type, subject_id, metric_id, dimensions_hash,
554
+ dimensions, count, measures, schema_version, created_at, updated_at
555
+ )
556
+ SELECT
557
+ d.scope_id, d.counter_id, d.timeframe_type, d.timeframe_key,
558
+ d.subject_type, d.subject_id, d.metric_id, d.dimensions_hash,
559
+ d.dimensions::jsonb, d.delta,
560
+ ${fn}('{}'::jsonb, d.measures::jsonb, d.scales::jsonb, true),
561
+ ${exports.POSTGRES_CELL_SCHEMA_VERSION}, now(), now()
562
+ FROM unnest(
563
+ $1::text[], $2::text[], $3::text[], $4::text[],
564
+ $5::text[], $6::float8[], $7::float8[], $8::text[],
565
+ $9::text[], $10::float8[], $11::text[], $12::text[]
566
+ ) AS d(
567
+ scope_id, counter_id, timeframe_type, timeframe_key,
568
+ subject_type, subject_id, metric_id, dimensions_hash,
569
+ dimensions, delta, measures, scales
570
+ )
571
+ ON CONFLICT (counter_id, scope_id, timeframe_type, timeframe_key, subject_type, subject_id, metric_id, dimensions_hash)
572
+ DO UPDATE SET
573
+ count = c.count + EXCLUDED.count,
574
+ measures = ${fn}(c.measures, EXCLUDED.measures, '{}'::jsonb, false),
575
+ updated_at = now()
576
+ `;
577
+ }
578
+ function incrementParams(batch) {
579
+ return [
580
+ batch.map((d) => d.identity.scopeId),
581
+ batch.map((d) => d.identity.counterId),
582
+ batch.map((d) => d.identity.timeframeType),
583
+ batch.map((d) => d.identity.timeframeKey),
584
+ batch.map((d) => d.identity.subjectType),
585
+ batch.map((d) => d.identity.subjectId),
586
+ batch.map((d) => d.identity.metricId),
587
+ batch.map((d) => d.identity.dimensionsHash),
588
+ batch.map((d) => JSON.stringify(d.identity.dimensions ?? {})),
589
+ batch.map((d) => d.delta),
590
+ batch.map((d) => measureDeltaJson(d.measures)),
591
+ batch.map((d) => JSON.stringify(d.measureScales ?? {})),
592
+ ];
593
+ }
594
+ function replaceSql(schema, cellsTable) {
595
+ const cells = qual(schema, cellsTable);
596
+ return `
597
+ INSERT INTO ${cells} AS c (
598
+ scope_id, counter_id, timeframe_type, timeframe_key,
599
+ subject_type, subject_id, metric_id, dimensions_hash,
600
+ dimensions, count, measures, schema_version, created_at, updated_at
601
+ )
602
+ SELECT
603
+ d.scope_id, d.counter_id, d.timeframe_type, d.timeframe_key,
604
+ d.subject_type, d.subject_id, d.metric_id, d.dimensions_hash,
605
+ d.dimensions::jsonb, d.count, d.measures::jsonb,
606
+ ${exports.POSTGRES_CELL_SCHEMA_VERSION}, d.created_at::timestamptz, d.updated_at::timestamptz
607
+ FROM unnest(
608
+ $1::text[], $2::text[], $3::text[], $4::text[],
609
+ $5::text[], $6::float8[], $7::float8[], $8::text[],
610
+ $9::text[], $10::float8[], $11::text[], $12::text[], $13::text[]
611
+ ) AS d(
612
+ scope_id, counter_id, timeframe_type, timeframe_key,
613
+ subject_type, subject_id, metric_id, dimensions_hash,
614
+ dimensions, count, measures, created_at, updated_at
615
+ )
616
+ ON CONFLICT (counter_id, scope_id, timeframe_type, timeframe_key, subject_type, subject_id, metric_id, dimensions_hash)
617
+ DO UPDATE SET
618
+ dimensions = EXCLUDED.dimensions,
619
+ count = EXCLUDED.count,
620
+ measures = EXCLUDED.measures,
621
+ schema_version = EXCLUDED.schema_version,
622
+ created_at = EXCLUDED.created_at,
623
+ updated_at = EXCLUDED.updated_at
624
+ `;
625
+ }
626
+ function replaceParams(batch) {
627
+ const now = new Date().toISOString();
628
+ return [
629
+ batch.map((c) => c.scopeId),
630
+ batch.map((c) => c.counterId),
631
+ batch.map((c) => c.timeframeType),
632
+ batch.map((c) => c.timeframeKey),
633
+ batch.map((c) => c.subjectType),
634
+ batch.map((c) => c.subjectId),
635
+ batch.map((c) => c.metricId),
636
+ batch.map((c) => c.dimensionsHash),
637
+ batch.map((c) => JSON.stringify((0, snapshot_encoding_js_1.presentationToStorageCell)(c).dimensions ?? {})),
638
+ batch.map((c) => (0, snapshot_encoding_js_1.presentationToStorageCell)(c).count),
639
+ batch.map((c) => storageMeasuresJson(c)),
640
+ batch.map((c) => (c.createdAt ?? new Date()).toISOString()),
641
+ batch.map(() => now),
642
+ ];
643
+ }
644
+ function cellFilter(spec) {
645
+ const buckets = (0, timeframe_js_1.bucketRange)(spec.timeframe.type, spec.timeframe.from, spec.timeframe.to);
646
+ const params = [spec.counterId, spec.scope, spec.timeframe.type, buckets];
647
+ const where = [
648
+ "counter_id = $1",
649
+ "scope_id = $2",
650
+ "timeframe_type = $3",
651
+ "timeframe_key = ANY($4::text[])",
652
+ ];
653
+ if (spec.subject?.type) {
654
+ params.push(spec.subject.type);
655
+ where.push(`subject_type = $${params.length}`);
656
+ }
657
+ if (spec.subject?.ids !== undefined) {
658
+ params.push(spec.subject.ids.map((id) => Number(id)));
659
+ where.push(`subject_id = ANY($${params.length}::float8[])`);
660
+ }
661
+ if (spec.metrics !== undefined) {
662
+ if (spec.metrics.length === 0) {
663
+ where.push("FALSE");
664
+ }
665
+ else {
666
+ const ids = spec.metrics.map((id) => Number(id)).filter((n) => Number.isFinite(n));
667
+ if (ids.length > 0) {
668
+ params.push(ids);
669
+ where.push(`metric_id = ANY($${params.length}::float8[])`);
670
+ }
671
+ }
672
+ }
673
+ if (spec.dimensions) {
674
+ for (const [name, allowed] of Object.entries(spec.dimensions)) {
675
+ params.push(name);
676
+ const nameIdx = params.length;
677
+ params.push(JSON.stringify(allowed));
678
+ const valuesIdx = params.length;
679
+ where.push(`(
680
+ dimensions -> $${nameIdx} IN (SELECT jsonb_array_elements($${valuesIdx}::jsonb))
681
+ OR (
682
+ $${valuesIdx}::jsonb @> '[null]'::jsonb
683
+ AND NOT (dimensions ? $${nameIdx})
684
+ )
685
+ )`);
686
+ }
687
+ }
688
+ return { where: where.join(" AND "), params };
689
+ }
690
+ function identityParams(id) {
691
+ return [
692
+ id.scopeId,
693
+ id.counterId,
694
+ id.timeframeType,
695
+ id.timeframeKey,
696
+ id.subjectType,
697
+ id.subjectId,
698
+ id.metricId,
699
+ id.dimensionsHash,
700
+ ];
701
+ }
702
+ function mergeMeasuresFunctionSql(schema) {
703
+ return `
704
+ CREATE OR REPLACE FUNCTION ${quoteIdent(schema)}.merge_measures(
705
+ existing jsonb,
706
+ incoming jsonb,
707
+ scales jsonb,
708
+ apply_scale boolean
709
+ ) RETURNS jsonb
710
+ LANGUAGE plpgsql
711
+ IMMUTABLE
712
+ SET search_path = pg_temp
713
+ AS $fn$
714
+ DECLARE
715
+ result jsonb := '{}'::jsonb;
716
+ k text;
717
+ e jsonb;
718
+ i jsonb;
719
+ sum_v numeric;
720
+ count_v numeric;
721
+ min_v numeric;
722
+ max_v numeric;
723
+ scale_v numeric;
724
+ obj jsonb;
725
+ BEGIN
726
+ existing := COALESCE(existing, '{}'::jsonb);
727
+ incoming := COALESCE(incoming, '{}'::jsonb);
728
+ scales := COALESCE(scales, '{}'::jsonb);
729
+
730
+ FOR k IN
731
+ SELECT DISTINCT key FROM (
732
+ SELECT jsonb_object_keys(existing) AS key
733
+ UNION
734
+ SELECT jsonb_object_keys(incoming)
735
+ UNION
736
+ SELECT jsonb_object_keys(scales)
737
+ ) AS keys
738
+ LOOP
739
+ e := existing -> k;
740
+ i := incoming -> k;
741
+
742
+ IF i IS NULL AND (NOT apply_scale OR scales -> k IS NULL) THEN
743
+ IF e IS NOT NULL THEN
744
+ result := result || jsonb_build_object(k, e);
745
+ END IF;
746
+ CONTINUE;
747
+ END IF;
748
+
749
+ IF (i IS NULL OR NOT (i ? 'sum')) AND (e IS NULL OR NOT (e ? 'sum')) THEN
750
+ sum_v := NULL;
751
+ ELSIF i IS NULL OR NOT (i ? 'sum') THEN
752
+ sum_v := (e ->> 'sum')::numeric;
753
+ ELSIF e IS NULL OR NOT (e ? 'sum') THEN
754
+ sum_v := (i ->> 'sum')::numeric;
755
+ ELSE
756
+ sum_v := (e ->> 'sum')::numeric + (i ->> 'sum')::numeric;
757
+ END IF;
758
+
759
+ IF (i IS NULL OR NOT (i ? 'count')) AND (e IS NULL OR NOT (e ? 'count')) THEN
760
+ count_v := NULL;
761
+ ELSIF i IS NULL OR NOT (i ? 'count') THEN
762
+ count_v := (e ->> 'count')::numeric;
763
+ ELSIF e IS NULL OR NOT (e ? 'count') THEN
764
+ count_v := (i ->> 'count')::numeric;
765
+ ELSE
766
+ count_v := (e ->> 'count')::numeric + (i ->> 'count')::numeric;
767
+ END IF;
768
+
769
+ IF i IS NULL OR NOT (i ? 'min') THEN
770
+ IF e IS NULL OR NOT (e ? 'min') THEN min_v := NULL;
771
+ ELSE min_v := (e ->> 'min')::numeric;
772
+ END IF;
773
+ ELSIF e IS NULL OR NOT (e ? 'min') THEN
774
+ min_v := (i ->> 'min')::numeric;
775
+ ELSE
776
+ min_v := LEAST((e ->> 'min')::numeric, (i ->> 'min')::numeric);
777
+ END IF;
778
+
779
+ IF i IS NULL OR NOT (i ? 'max') THEN
780
+ IF e IS NULL OR NOT (e ? 'max') THEN max_v := NULL;
781
+ ELSE max_v := (e ->> 'max')::numeric;
782
+ END IF;
783
+ ELSIF e IS NULL OR NOT (e ? 'max') THEN
784
+ max_v := (i ->> 'max')::numeric;
785
+ ELSE
786
+ max_v := GREATEST((e ->> 'max')::numeric, (i ->> 'max')::numeric);
787
+ END IF;
788
+
789
+ IF apply_scale THEN
790
+ IF e IS NOT NULL AND (e ? 'scale') THEN
791
+ scale_v := (e ->> 'scale')::numeric;
792
+ ELSIF scales ? k THEN
793
+ scale_v := (scales ->> k)::numeric;
794
+ ELSIF i IS NOT NULL AND (i ? 'scale') THEN
795
+ scale_v := (i ->> 'scale')::numeric;
796
+ ELSE
797
+ scale_v := NULL;
798
+ END IF;
799
+ ELSE
800
+ IF e IS NOT NULL AND (e ? 'scale') THEN
801
+ scale_v := (e ->> 'scale')::numeric;
802
+ ELSE
803
+ scale_v := NULL;
804
+ END IF;
805
+ END IF;
806
+
807
+ obj := '{}'::jsonb;
808
+ IF sum_v IS NOT NULL THEN obj := obj || jsonb_build_object('sum', sum_v); END IF;
809
+ IF count_v IS NOT NULL THEN obj := obj || jsonb_build_object('count', count_v); END IF;
810
+ IF min_v IS NOT NULL THEN obj := obj || jsonb_build_object('min', min_v); END IF;
811
+ IF max_v IS NOT NULL THEN obj := obj || jsonb_build_object('max', max_v); END IF;
812
+ IF scale_v IS NOT NULL THEN obj := obj || jsonb_build_object('scale', scale_v); END IF;
813
+ IF obj <> '{}'::jsonb THEN
814
+ result := result || jsonb_build_object(k, obj);
815
+ END IF;
816
+ END LOOP;
817
+
818
+ RETURN result;
819
+ END;
820
+ $fn$;
821
+ `;
822
+ }
823
+ function collapseDeltas(deltas) {
824
+ const map = new Map();
825
+ for (const delta of deltas) {
826
+ const key = (0, hash_js_1.cellKey)(delta.identity);
827
+ const cur = map.get(key);
828
+ if (!cur) {
829
+ map.set(key, {
830
+ identity: delta.identity,
831
+ delta: delta.delta,
832
+ measures: delta.measures ? mergeMeasureMaps(undefined, delta.measures) : undefined,
833
+ measureScales: delta.measureScales ? { ...delta.measureScales } : undefined,
834
+ });
835
+ continue;
836
+ }
837
+ cur.delta += delta.delta;
838
+ if (delta.measures)
839
+ cur.measures = mergeMeasureMaps(cur.measures, delta.measures);
840
+ cur.measureScales = mergeScales(cur.measureScales, delta.measureScales);
841
+ }
842
+ return [...map.values()];
843
+ }
844
+ function mergeMeasureDelta(cur, inc) {
845
+ const out = { ...cur };
846
+ if (inc.sum !== undefined)
847
+ out.sum = (out.sum ?? 0) + inc.sum;
848
+ if (inc.count !== undefined)
849
+ out.count = (out.count ?? 0) + inc.count;
850
+ if (inc.min !== undefined)
851
+ out.min = out.min !== undefined ? Math.min(out.min, inc.min) : inc.min;
852
+ if (inc.max !== undefined)
853
+ out.max = out.max !== undefined ? Math.max(out.max, inc.max) : inc.max;
854
+ return out;
855
+ }
856
+ function mergeMeasureMaps(cur, inc) {
857
+ const out = cur ? { ...cur } : {};
858
+ for (const [name, delta] of Object.entries(inc)) {
859
+ out[name] = mergeMeasureDelta(out[name], delta);
860
+ }
861
+ return out;
862
+ }
863
+ function mergeScales(cur, inc) {
864
+ if (!inc || Object.keys(inc).length === 0)
865
+ return cur;
866
+ const out = { ...cur };
867
+ for (const [key, value] of Object.entries(inc)) {
868
+ if (out[key] === undefined)
869
+ out[key] = value;
870
+ }
871
+ return Object.keys(out).length > 0 ? out : undefined;
872
+ }
873
+ function collapseSnapshots(cells) {
874
+ const map = new Map();
875
+ for (const cell of cells)
876
+ map.set((0, hash_js_1.cellKey)(cell), cell);
877
+ return [...map.values()];
878
+ }
879
+ function measureDeltaJson(measures) {
880
+ if (!measures)
881
+ return "{}";
882
+ const out = {};
883
+ for (const [name, delta] of Object.entries(measures)) {
884
+ const row = {};
885
+ if (delta.sum !== undefined)
886
+ row.sum = delta.sum;
887
+ if (delta.count !== undefined)
888
+ row.count = delta.count;
889
+ if (delta.min !== undefined)
890
+ row.min = delta.min;
891
+ if (delta.max !== undefined)
892
+ row.max = delta.max;
893
+ if (Object.keys(row).length > 0)
894
+ out[name] = row;
895
+ }
896
+ return JSON.stringify(out);
897
+ }
898
+ function storageMeasuresJson(cell) {
899
+ const stored = (0, snapshot_encoding_js_1.presentationToStorageCell)(cell);
900
+ if (!stored.measures || Object.keys(stored.measures).length === 0)
901
+ return "null";
902
+ const out = {};
903
+ for (const [name, value] of Object.entries(stored.measures)) {
904
+ const row = {};
905
+ if (value.sum !== undefined)
906
+ row.sum = value.sum;
907
+ if (value.count !== undefined)
908
+ row.count = value.count;
909
+ if (value.min !== undefined)
910
+ row.min = value.min;
911
+ if (value.max !== undefined)
912
+ row.max = value.max;
913
+ if (value.scale !== undefined)
914
+ row.scale = value.scale;
915
+ out[name] = row;
916
+ }
917
+ return JSON.stringify(out);
918
+ }
919
+ function rowToCell(row) {
920
+ const dimensions = typeof row.dimensions === "string" ? JSON.parse(row.dimensions) : row.dimensions;
921
+ return {
922
+ scopeId: row.scope_id,
923
+ counterId: row.counter_id,
924
+ timeframeType: row.timeframe_type,
925
+ timeframeKey: row.timeframe_key,
926
+ subjectType: row.subject_type,
927
+ subjectId: asNumber(row.subject_id),
928
+ metricId: asNumber(row.metric_id),
929
+ dimensionsHash: row.dimensions_hash,
930
+ dimensions: dimensions ?? {},
931
+ count: asNumber(row.count),
932
+ measures: unscaleMeasures(row.measures),
933
+ createdAt: asDate(row.created_at),
934
+ updatedAt: asDate(row.updated_at),
935
+ };
936
+ }
937
+ function unscaleMeasures(raw) {
938
+ if (raw == null)
939
+ return undefined;
940
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
941
+ if (!parsed || Object.keys(parsed).length === 0)
942
+ return undefined;
943
+ const out = {};
944
+ for (const [name, value] of Object.entries(parsed)) {
945
+ const scale = asOptionalNumber(value.scale);
946
+ const div = scale !== undefined && scale > 0 ? scale : 1;
947
+ const sum = asOptionalNumber(value.sum);
948
+ const min = asOptionalNumber(value.min);
949
+ const max = asOptionalNumber(value.max);
950
+ out[name] = {
951
+ sum: sum !== undefined ? sum / div : undefined,
952
+ count: asOptionalNumber(value.count),
953
+ min: min !== undefined ? min / div : undefined,
954
+ max: max !== undefined ? max / div : undefined,
955
+ scale,
956
+ };
957
+ }
958
+ return out;
959
+ }
960
+ function dictKey(lookup) {
961
+ return (0, index_js_1.dictionaryLookupKey)({ ...lookup, qualifier: lookup.qualifier ?? "" });
962
+ }
963
+ function groupLookups(lookups, keyOf) {
964
+ const out = new Map();
965
+ for (const lookup of lookups) {
966
+ const key = keyOf(lookup);
967
+ const arr = out.get(key) ?? [];
968
+ arr.push(lookup);
969
+ out.set(key, arr);
970
+ }
971
+ return out;
972
+ }
973
+ function chunk(items, size) {
974
+ const out = [];
975
+ for (let i = 0; i < items.length; i += size)
976
+ out.push(items.slice(i, i + size));
977
+ return out;
978
+ }
979
+ function assertIdent(name, label) {
980
+ if (!IDENT.test(name)) {
981
+ throw new errors_js_1.StorageError(`Invalid Postgres ${label}`, { name });
982
+ }
983
+ return name;
984
+ }
985
+ function quoteIdent(name) {
986
+ return `"${name}"`;
987
+ }
988
+ function qual(schema, table) {
989
+ return `${quoteIdent(schema)}.${quoteIdent(table)}`;
990
+ }
991
+ function asNumber(value) {
992
+ const n = typeof value === "number" ? value : Number(value);
993
+ return n;
994
+ }
995
+ function asOptionalNumber(value) {
996
+ if (value === undefined || value === null)
997
+ return undefined;
998
+ const n = typeof value === "number" ? value : Number(value);
999
+ return Number.isFinite(n) ? n : undefined;
1000
+ }
1001
+ function asDate(value) {
1002
+ if (value == null)
1003
+ return undefined;
1004
+ return value instanceof Date ? value : new Date(value);
1005
+ }
1006
+ function throwIfAborted(signal, message) {
1007
+ if (signal?.aborted)
1008
+ throw new errors_js_1.StorageError(message, {});
1009
+ }
1010
+ function asStorageError(message, err) {
1011
+ if (err instanceof errors_js_1.StorageError)
1012
+ return err;
1013
+ return new errors_js_1.StorageError(message, { cause: err instanceof Error ? err.message : String(err) });
1014
+ }
1015
+ async function rollback(client) {
1016
+ try {
1017
+ await client.query("ROLLBACK");
1018
+ }
1019
+ catch {
1020
+ // The connection is released by the caller either way.
1021
+ }
1022
+ }
1023
+ //# sourceMappingURL=postgres.js.map