@outsidedata/dolex 8.1.0 → 9.0.2

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 (79) hide show
  1. package/README.md +30 -7
  2. package/dist/src/analysis/planner.d.ts +2 -1
  3. package/dist/src/analysis/planner.js +2 -2
  4. package/dist/src/analysis/quality.js +96 -5
  5. package/dist/src/analysis/rules.d.ts +22 -2
  6. package/dist/src/analysis/rules.js +64 -23
  7. package/dist/src/cleaning/index.d.ts +2 -6
  8. package/dist/src/cleaning/index.js +8 -3
  9. package/dist/src/cleaning/replay.d.ts +34 -0
  10. package/dist/src/cleaning/replay.js +58 -0
  11. package/dist/src/cli/commands/analyze.js +13 -1
  12. package/dist/src/cli/commands/clean.js +15 -3
  13. package/dist/src/cli/commands/deps.d.ts +1 -0
  14. package/dist/src/cli/commands/deps.js +41 -0
  15. package/dist/src/cli/commands/help.js +2 -1
  16. package/dist/src/cli/commands/sources.d.ts +2 -2
  17. package/dist/src/cli/commands/sources.js +139 -12
  18. package/dist/src/cli/commands/transform.js +19 -4
  19. package/dist/src/cli/data-source.d.ts +0 -2
  20. package/dist/src/cli/data-source.js +0 -1
  21. package/dist/src/cli/index.js +3 -0
  22. package/dist/src/connectors/csv.js +29 -0
  23. package/dist/src/connectors/index.d.ts +2 -0
  24. package/dist/src/connectors/index.js +2 -0
  25. package/dist/src/connectors/manager.d.ts +39 -1
  26. package/dist/src/connectors/manager.js +191 -45
  27. package/dist/src/connectors/mongo/index.d.ts +21 -0
  28. package/dist/src/connectors/mongo/index.js +359 -0
  29. package/dist/src/connectors/pg/index.d.ts +2 -0
  30. package/dist/src/connectors/pg/index.js +316 -0
  31. package/dist/src/connectors/source-factory.d.ts +38 -0
  32. package/dist/src/connectors/source-factory.js +80 -0
  33. package/dist/src/connectors/sql-safety.d.ts +59 -17
  34. package/dist/src/connectors/sql-safety.js +275 -54
  35. package/dist/src/connectors/types.d.ts +59 -0
  36. package/dist/src/connectors/types.js +33 -1
  37. package/dist/src/mcp/index.d.ts +1 -1
  38. package/dist/src/mcp/index.js +43 -13
  39. package/dist/src/mcp/tools/analyze.js +12 -2
  40. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  41. package/dist/src/mcp/tools/capabilities.js +14 -0
  42. package/dist/src/mcp/tools/clean-column.js +2 -0
  43. package/dist/src/mcp/tools/clean-schemas.js +1 -1
  44. package/dist/src/mcp/tools/drop-columns.js +2 -0
  45. package/dist/src/mcp/tools/list-transforms.js +22 -0
  46. package/dist/src/mcp/tools/promote-columns.js +2 -0
  47. package/dist/src/mcp/tools/query-source.js +2 -2
  48. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  49. package/dist/src/mcp/tools/refine.d.ts +4 -4
  50. package/dist/src/mcp/tools/shared.d.ts +5 -0
  51. package/dist/src/mcp/tools/shared.js +11 -4
  52. package/dist/src/mcp/tools/sources.d.ts +47 -4
  53. package/dist/src/mcp/tools/sources.js +51 -9
  54. package/dist/src/mcp/tools/transform-data.js +22 -0
  55. package/dist/src/mcp/tools/transform-schemas.js +4 -4
  56. package/dist/src/mcp/tools/visualize-cli.js +1 -1
  57. package/dist/src/mcp/tools/visualize.js +2 -2
  58. package/dist/src/patterns/index.d.ts +1 -1
  59. package/dist/src/patterns/index.js +1 -1
  60. package/dist/src/patterns/registry.d.ts +1 -12
  61. package/dist/src/patterns/registry.js +0 -13
  62. package/dist/src/patterns/utils.d.ts +0 -24
  63. package/dist/src/patterns/utils.js +0 -71
  64. package/dist/src/renderers/d3/shared.d.ts +0 -18
  65. package/dist/src/renderers/d3/shared.js +0 -62
  66. package/dist/src/types.d.ts +30 -3
  67. package/dist/src/utils/capabilities.d.ts +28 -0
  68. package/dist/src/utils/capabilities.js +58 -0
  69. package/dist/src/utils/optional-deps.d.ts +8 -0
  70. package/dist/src/utils/optional-deps.js +8 -0
  71. package/package.json +5 -2
  72. package/dist/src/analysis/clean-exec.d.ts +0 -23
  73. package/dist/src/analysis/clean-exec.js +0 -87
  74. package/dist/src/cleaning/author.d.ts +0 -30
  75. package/dist/src/cleaning/author.js +0 -7
  76. package/dist/src/cleaning/handlers.d.ts +0 -16
  77. package/dist/src/cleaning/handlers.js +0 -82
  78. package/dist/src/cleaning/manifest.d.ts +0 -35
  79. package/dist/src/cleaning/manifest.js +0 -95
@@ -0,0 +1,359 @@
1
+ import { registerDerivedColumn } from '../types.js';
2
+ import { importOptional } from '../../utils/optional-deps.js';
3
+ /** Lazily load the mongodb driver so the base install never requires it — a missing package
4
+ * becomes a friendly "npm install mongodb", surfaced only when a Mongo source is actually used. */
5
+ const loadMongo = () => importOptional('mongodb', 'mongodb');
6
+ const SAMPLE_DOCS = 200; // docs sampled to discover the key universe + candidate types
7
+ // Above this many docs, computing exact percentiles by $push-ing the whole column into one array
8
+ // would blow Mongo's 16MB per-document BSON limit (allowDiskUse can't lift it). Past the cap we keep
9
+ // the streaming stats (min/max/avg/stddev) and omit median/quartiles rather than fail profiling.
10
+ const PERCENTILE_MAX_DOCS = 500_000;
11
+ function uriFor(cfg) {
12
+ if (cfg.uri)
13
+ return cfg.uri;
14
+ return `mongodb://${cfg.host || 'localhost'}:${cfg.port || 27017}`;
15
+ }
16
+ const NUMERIC = (v) => typeof v === 'number';
17
+ /** Duck-type a BSON ObjectId without importing the driver class (an ObjectId has toHexString()). */
18
+ const isObjectId = (v) => v != null && typeof v === 'object' && typeof v.toHexString === 'function';
19
+ /** Coerce a BSON value to a JS-friendly value for consumer parity (charts/markdown/JSON). */
20
+ function jsValue(v) {
21
+ if (v == null)
22
+ return v;
23
+ if (isObjectId(v))
24
+ return v.toString();
25
+ if (v instanceof Date)
26
+ return v.toISOString();
27
+ return v;
28
+ }
29
+ /** Candidate type from a sampled value (refined by distinct/total in classify). */
30
+ function candidateType(v) {
31
+ if (typeof v === 'number')
32
+ return 'numeric';
33
+ if (v instanceof Date)
34
+ return 'date';
35
+ if (isObjectId(v))
36
+ return 'id';
37
+ return 'text'; // string/bool/other → text, refined to categorical by cardinality
38
+ }
39
+ function classify(cand, name, distinct, total) {
40
+ if (name === '_id')
41
+ return 'id';
42
+ if (cand === 'numeric') {
43
+ if (/(^|_)id$/i.test(name) && total > 0 && distinct >= total * 0.9)
44
+ return 'id';
45
+ return 'numeric';
46
+ }
47
+ if (cand === 'date' || cand === 'id')
48
+ return cand;
49
+ // text-ish: low cardinality ⇒ categorical
50
+ if (total > 0 && distinct <= Math.min(200, Math.max(50, total * 0.5)))
51
+ return 'categorical';
52
+ return 'text';
53
+ }
54
+ async function profileCollection(db, name) {
55
+ const coll = db.collection(name);
56
+ const total = await coll.countDocuments();
57
+ // Phase 1 — sample docs to discover the key universe + a candidate type per key.
58
+ // $sample (random) not find().limit() (natural/oldest order): keys added or retyped over the
59
+ // collection's life would otherwise be invisible, classified from the oldest documents only.
60
+ const sampled = await coll.aggregate([{ $sample: { size: SAMPLE_DOCS } }]).toArray();
61
+ const keys = [];
62
+ const candByKey = new Map();
63
+ const sampleValsByKey = new Map();
64
+ for (const doc of sampled) {
65
+ for (const k of Object.keys(doc)) {
66
+ if (!candByKey.has(k)) {
67
+ keys.push(k);
68
+ candByKey.set(k, candidateType(doc[k]));
69
+ sampleValsByKey.set(k, []);
70
+ }
71
+ const sv = sampleValsByKey.get(k);
72
+ const v = doc[k];
73
+ if (v != null && sv.length < 5)
74
+ sv.push(String(jsValue(v)));
75
+ }
76
+ }
77
+ if (total === 0 || keys.length === 0)
78
+ return { name, columns: [], rowCount: total };
79
+ // Phase 2 — ONE $facet: per-key non-null + distinct counts, numeric stats, categorical top-values.
80
+ const facet = {};
81
+ for (const k of keys) {
82
+ const cand = candByKey.get(k);
83
+ facet[`${k}__nn`] = [{ $match: { [k]: { $ne: null, $exists: true } } }, { $count: 'n' }];
84
+ facet[`${k}__dc`] = [{ $group: { _id: `$${k}` } }, { $count: 'n' }];
85
+ if (cand === 'numeric') {
86
+ // Mongo 5.0 has no $percentile; sort + $push then pick positional elements server-side
87
+ // (the array stays inside the sub-pipeline — the facet only stores the scalar result).
88
+ // Only for collections under PERCENTILE_MAX_DOCS — past that the $push array would exceed
89
+ // the 16MB BSON limit, so we keep streaming stats and drop the quartiles.
90
+ const withPercentiles = total <= PERCENTILE_MAX_DOCS;
91
+ facet[`${k}__st`] = [
92
+ { $match: { [k]: { $type: 'number' } } },
93
+ ...(withPercentiles ? [{ $sort: { [k]: 1 } }] : []),
94
+ { $group: { _id: null, ...(withPercentiles ? { vals: { $push: `$${k}` } } : {}), min: { $min: `$${k}` }, max: { $max: `$${k}` }, avg: { $avg: `$${k}` }, sd: { $stdDevPop: `$${k}` }, n: { $sum: 1 } } },
95
+ { $project: {
96
+ min: 1, max: 1, avg: 1, sd: 1,
97
+ ...(withPercentiles ? {
98
+ median: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.5] } }] },
99
+ p25: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.25] } }] },
100
+ p75: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.75] } }] },
101
+ } : {}),
102
+ } },
103
+ ];
104
+ }
105
+ else if (k !== '_id') {
106
+ facet[`${k}__tv`] = [{ $match: { [k]: { $ne: null } } }, { $sortByCount: `$${k}` }, { $limit: 10 }];
107
+ }
108
+ }
109
+ const [f] = await coll.aggregate([{ $facet: facet }], { allowDiskUse: true }).toArray();
110
+ const one = (arr) => (arr && arr.length ? arr[0] : undefined);
111
+ const columns = keys.map((k) => {
112
+ const nonNull = Number(one(f[`${k}__nn`])?.n ?? 0);
113
+ const distinct = Number(one(f[`${k}__dc`])?.n ?? 0);
114
+ const type = classify(candByKey.get(k), k, distinct, total);
115
+ let stats;
116
+ let topValues;
117
+ if (type === 'numeric') {
118
+ const s = one(f[`${k}__st`]);
119
+ if (s)
120
+ stats = { min: s.min, max: s.max, mean: s.avg, median: s.median, stddev: s.sd ?? 0, p25: s.p25, p75: s.p75 };
121
+ }
122
+ else if (k !== '_id') {
123
+ const tv = f[`${k}__tv`];
124
+ if (tv?.length)
125
+ topValues = tv.map((r) => ({ value: String(jsValue(r._id)), count: r.count }));
126
+ }
127
+ return {
128
+ name: k, type, sampleValues: sampleValsByKey.get(k) ?? [],
129
+ uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
130
+ layer: 'source', stats, topValues,
131
+ };
132
+ });
133
+ return { name, columns, rowCount: total };
134
+ }
135
+ const tryParseJson = (q) => { try {
136
+ return JSON.parse(q);
137
+ }
138
+ catch {
139
+ return undefined;
140
+ } };
141
+ /** Append the closers for any unclosed { or [ (string-aware) — repairs a common caller near-miss:
142
+ * a correct pipeline whose outer envelope is missing its trailing brace. */
143
+ function balanceBrackets(q) {
144
+ const stack = [];
145
+ let inStr = false, esc = false;
146
+ for (const ch of q) {
147
+ if (esc) {
148
+ esc = false;
149
+ continue;
150
+ }
151
+ if (ch === '\\') {
152
+ esc = true;
153
+ continue;
154
+ }
155
+ if (ch === '"') {
156
+ inStr = !inStr;
157
+ continue;
158
+ }
159
+ if (inStr)
160
+ continue;
161
+ if (ch === '{' || ch === '[')
162
+ stack.push(ch);
163
+ else if (ch === '}' || ch === ']')
164
+ stack.pop();
165
+ }
166
+ let out = q;
167
+ for (let i = stack.length - 1; i >= 0; i--)
168
+ out += stack[i] === '{' ? '}' : ']';
169
+ return out;
170
+ }
171
+ /**
172
+ * TOLERANT seam parse. Callers reliably produce correct aggregation STAGES but fumble the
173
+ * hand-written JSON ENVELOPE, so accept, in order: the full {"collection","pipeline":[…]}; a BARE
174
+ * pipeline array [<stages>] (wrapped with the primary collection); or an envelope missing its
175
+ * trailing brace(s), repaired by balancing. Empty/garbage is rejected with an actionable message —
176
+ * never silently "repaired" into a fake pipeline.
177
+ */
178
+ export function parseSeam(query, defaultCollection) {
179
+ const raw = (query ?? '').trim();
180
+ const parsed = tryParseJson(raw) ?? tryParseJson(balanceBrackets(raw));
181
+ if (Array.isArray(parsed) && defaultCollection)
182
+ return { collection: defaultCollection, pipeline: parsed };
183
+ if (parsed && typeof parsed.collection === 'string' && Array.isArray(parsed.pipeline))
184
+ return { collection: parsed.collection, pipeline: parsed.pipeline };
185
+ if (parsed && Array.isArray(parsed.pipeline) && defaultCollection)
186
+ return { collection: defaultCollection, pipeline: parsed.pipeline };
187
+ throw new Error('Mongo query must be a JSON aggregation pipeline: a bare array [<stages>], or {"collection":"<name>","pipeline":[<stages>]}');
188
+ }
189
+ /** Aggregation stages/operators that write, or execute arbitrary server-side JS. */
190
+ const BANNED_OPS = new Set(['$out', '$merge', '$function', '$accumulator', '$where']);
191
+ /**
192
+ * Read-only gate over the PARSED pipeline — the authoritative one.
193
+ *
194
+ * A regex over the query STRING is not a boundary: JSON unicode escapes ("$out") parse
195
+ * straight through it, and a banned stage nested inside a $lookup/$unionWith sub-pipeline never
196
+ * appears at the top level. Walk the object the driver will actually run instead.
197
+ */
198
+ export function assertReadOnlyPipeline(node) {
199
+ if (Array.isArray(node)) {
200
+ for (const n of node)
201
+ assertReadOnlyPipeline(n);
202
+ return;
203
+ }
204
+ if (node == null || typeof node !== 'object')
205
+ return;
206
+ for (const [k, v] of Object.entries(node)) {
207
+ if (BANNED_OPS.has(k)) {
208
+ throw new Error(`Only read-only aggregation pipelines are allowed (found "${k}"; no ${[...BANNED_OPS].join('/')}).`);
209
+ }
210
+ assertReadOnlyPipeline(v);
211
+ }
212
+ }
213
+ class MongoConnectedSource {
214
+ id;
215
+ name;
216
+ client;
217
+ db;
218
+ schema;
219
+ type = 'mongodb';
220
+ /** collection → derived fields materialized this session (a $set expr each), in creation order. */
221
+ derived = new Map();
222
+ constructor(id, name, client, db, schema) {
223
+ this.id = id;
224
+ this.name = name;
225
+ this.client = client;
226
+ this.db = db;
227
+ this.schema = schema;
228
+ }
229
+ async getSchema() {
230
+ return this.schema;
231
+ }
232
+ async executeQuery(query) {
233
+ try {
234
+ const { collection, pipeline } = parseSeam(query, this.schema.tables[0]?.name);
235
+ assertReadOnlyPipeline(pipeline);
236
+ // Prepend a $set for each session-derived field so every aggregation sees it transparently,
237
+ // without ever writing the base collection.
238
+ const derived = this.derived.get(collection) ?? [];
239
+ const setStage = derived.length ? [{ $set: Object.fromEntries(derived.map((d) => [d.field, d.expr])) }] : [];
240
+ const docs = await this.db.collection(collection).aggregate([...setStage, ...pipeline]).toArray();
241
+ // Columns: union of keys across result docs, in first-seen order (docs are ragged).
242
+ const seen = new Set();
243
+ const columns = [];
244
+ for (const d of docs)
245
+ for (const k of Object.keys(d))
246
+ if (!seen.has(k)) {
247
+ seen.add(k);
248
+ columns.push(k);
249
+ }
250
+ const rows = docs.map((d) => {
251
+ const out = {};
252
+ for (const k of columns)
253
+ out[k] = jsValue(d[k]);
254
+ return out;
255
+ });
256
+ return { columns, rows };
257
+ }
258
+ catch (err) {
259
+ return { columns: [], rows: [{ error: err.message }] };
260
+ }
261
+ }
262
+ async getSampleRows(collectionName, count = 5) {
263
+ const total = this.schema.tables.find((t) => t.name === collectionName)?.rowCount ?? 0;
264
+ if (total === 0)
265
+ return [];
266
+ const docs = total <= count
267
+ ? await this.db.collection(collectionName).find({}, { limit: count }).toArray()
268
+ : await this.db.collection(collectionName).aggregate([{ $sample: { size: count } }]).toArray();
269
+ return docs.map((d) => {
270
+ const out = {};
271
+ for (const k of Object.keys(d))
272
+ out[k] = jsValue(d[k]);
273
+ return out;
274
+ });
275
+ }
276
+ // getDatabase intentionally omitted → the derivation seam no longer keys on a raw db handle.
277
+ /**
278
+ * Mongo derives a FIELD via a `$set` aggregation expression prepended to every incoming pipeline
279
+ * (see executeQuery). No sidecar, no write to the base collection — the derived field is computed
280
+ * server-side on read. `materialization:'computed-set'` reflects that.
281
+ */
282
+ derivationCapabilities() {
283
+ return { canDerive: true, materialization: 'computed-set', rowKey: '_id', serverSideQueryable: true };
284
+ }
285
+ /** Register a derived field: `expr` is a JSON Mongo aggregation expression (e.g. a $cond). It is
286
+ * prepended as a $set to every subsequent aggregation; the base collection is never written. */
287
+ async applyDerivation(table, column, expr) {
288
+ let parsed;
289
+ try {
290
+ parsed = JSON.parse(expr);
291
+ }
292
+ catch {
293
+ throw new Error('Mongo derivation expr must be a JSON aggregation expression, e.g. {"$cond":[...]}');
294
+ }
295
+ const cols = this.derived.get(table) ?? [];
296
+ const existing = cols.find((d) => d.field === column);
297
+ if (existing)
298
+ existing.expr = parsed;
299
+ else
300
+ cols.push({ field: column, expr: parsed });
301
+ this.derived.set(table, cols);
302
+ registerDerivedColumn(this.schema, table, column);
303
+ }
304
+ async close() {
305
+ try {
306
+ await this.client.close();
307
+ }
308
+ catch { /* already closed */ }
309
+ }
310
+ }
311
+ export const mongoConnector = {
312
+ type: 'mongodb',
313
+ async test(config) {
314
+ const cfg = config;
315
+ if (cfg.type !== 'mongodb')
316
+ return { ok: false, error: 'Config type must be "mongodb"' };
317
+ if (!cfg.database)
318
+ return { ok: false, error: 'Mongo config requires a "database"' };
319
+ const { MongoClient } = await loadMongo();
320
+ const client = new MongoClient(uriFor(cfg));
321
+ try {
322
+ await client.connect();
323
+ await client.db(cfg.database).command({ ping: 1 });
324
+ return { ok: true };
325
+ }
326
+ catch (err) {
327
+ const reason = err?.message || err?.code || err?.errors?.map((e) => e?.message || e?.code).filter(Boolean).join('; ') || String(err);
328
+ return { ok: false, error: `Cannot connect to MongoDB: ${reason}` };
329
+ }
330
+ finally {
331
+ await client.close().catch(() => { });
332
+ }
333
+ },
334
+ async connect(config) {
335
+ const cfg = config;
336
+ if (cfg.type !== 'mongodb')
337
+ throw new Error('Config type must be "mongodb"');
338
+ if (!cfg.database)
339
+ throw new Error('Mongo config requires a "database"');
340
+ const { MongoClient } = await loadMongo();
341
+ const client = new MongoClient(uriFor(cfg));
342
+ await client.connect();
343
+ const db = client.db(cfg.database);
344
+ let names = cfg.collections;
345
+ if (!names || names.length === 0) {
346
+ names = (await db.listCollections({}, { nameOnly: true }).toArray())
347
+ .map((c) => c.name).filter((n) => !n.startsWith('system.'));
348
+ }
349
+ // Each collection profiles independently (own count + sample + one $facet), so connect()
350
+ // latency need not scale linearly with collection count.
351
+ const tables = await Promise.all(names.map((n) => profileCollection(db, n)));
352
+ const id = `mongo-${cfg.database}`;
353
+ const dataSchema = {
354
+ tables, foreignKeys: [],
355
+ source: { id, type: 'mongodb', name: cfg.database, config },
356
+ };
357
+ return new MongoConnectedSource(id, cfg.database, client, db, dataSchema);
358
+ },
359
+ };
@@ -0,0 +1,2 @@
1
+ import type { DataConnector } from '../types.js';
2
+ export declare const pgConnector: DataConnector;
@@ -0,0 +1,316 @@
1
+ import { registerDerivedColumn } from '../types.js';
2
+ import { importOptional } from '../../utils/optional-deps.js';
3
+ /** Lazily load the pg driver so the base install never requires it — a missing package becomes a
4
+ * friendly "npm install pg", surfaced only when a Postgres source is actually used. */
5
+ const loadPg = () => importOptional('pg', 'postgres');
6
+ const q = (id) => '"' + id.replace(/"/g, '""') + '"';
7
+ // application_name tags dolex's connections in pg_stat_activity so a DBA can see (and kill) them;
8
+ // statement_timeout is a backstop so a pathological profiling scan aborts instead of hammering a
9
+ // primary for hours. Both apply to every connection this pool hands out (incl. the pinned client).
10
+ const POOL_GUARDS = { application_name: 'dolex', statement_timeout: 30_000, max: 4 };
11
+ function poolFor(PoolCtor, cfg) {
12
+ if (cfg.connectionString)
13
+ return new PoolCtor({ connectionString: cfg.connectionString, ...POOL_GUARDS });
14
+ // The secret is either the literal password or (preferred) read from an env var at connect time,
15
+ // so it need never be persisted in the registry file.
16
+ const password = cfg.password ?? (cfg.passwordEnv ? process.env[cfg.passwordEnv] : undefined);
17
+ return new PoolCtor({
18
+ host: cfg.host, port: cfg.port, database: cfg.database, user: cfg.user, password, ...POOL_GUARDS,
19
+ });
20
+ }
21
+ // Postgres type OIDs that should surface as JS numbers: int2/int4/int8, float4/float8, numeric.
22
+ const PG_NUMERIC_OIDS = new Set([20, 21, 23, 700, 701, 1700]);
23
+ const NUMERIC_TYPES = new Set(['numeric', 'integer', 'bigint', 'double precision', 'real', 'smallint', 'decimal']);
24
+ const DATE_TYPES = new Set(['date', 'timestamp without time zone', 'timestamp with time zone', 'time without time zone']);
25
+ function classify(dataType, name, distinct, total) {
26
+ if (NUMERIC_TYPES.has(dataType)) {
27
+ if (/(^|_)id$/i.test(name) && total > 0 && distinct >= total * 0.9)
28
+ return 'id';
29
+ return 'numeric';
30
+ }
31
+ if (DATE_TYPES.has(dataType))
32
+ return 'date';
33
+ // text-ish
34
+ if (total > 0 && distinct <= Math.min(1000, Math.max(50, total * 0.5)) && distinct <= 200)
35
+ return 'categorical';
36
+ return 'text';
37
+ }
38
+ async function profileTable(pool, schema, table) {
39
+ // column list + pg data types
40
+ const colRes = await pool.query(`SELECT column_name, data_type FROM information_schema.columns
41
+ WHERE table_schema=$1 AND table_name=$2 ORDER BY ordinal_position`, [schema, table]);
42
+ const cols = colRes.rows.map((r) => ({ name: r.column_name, dataType: r.data_type }));
43
+ // one scan: COUNT(*) + per-column distinct + non-null counts
44
+ const countSel = ['COUNT(*)::bigint AS __total'];
45
+ for (const c of cols) {
46
+ countSel.push(`COUNT(DISTINCT ${q(c.name)})::bigint AS ${q('d_' + c.name)}`);
47
+ countSel.push(`COUNT(${q(c.name)})::bigint AS ${q('n_' + c.name)}`);
48
+ }
49
+ let counts;
50
+ try {
51
+ counts = (await pool.query(`SELECT ${countSel.join(', ')} FROM ${q(schema)}.${q(table)}`)).rows[0];
52
+ }
53
+ catch {
54
+ // COUNT(DISTINCT …) has no operator for json / xml / geometry columns — a single such column
55
+ // errors the whole combined query and would brick the entire source. Fall back to per-column
56
+ // counts so one uncountable column degrades to unknown-cardinality, not a dead database.
57
+ const total = Number((await pool.query(`SELECT COUNT(*)::bigint AS n FROM ${q(schema)}.${q(table)}`)).rows[0].n);
58
+ counts = { __total: total };
59
+ for (const c of cols) {
60
+ try {
61
+ const r = (await pool.query(`SELECT COUNT(DISTINCT ${q(c.name)})::bigint AS d, COUNT(${q(c.name)})::bigint AS n FROM ${q(schema)}.${q(table)}`)).rows[0];
62
+ counts['d_' + c.name] = r.d;
63
+ counts['n_' + c.name] = r.n;
64
+ }
65
+ catch {
66
+ counts['d_' + c.name] = 0;
67
+ counts['n_' + c.name] = total; // uncountable → assume all-present, unknown distinct
68
+ }
69
+ }
70
+ }
71
+ const total = Number(counts.__total);
72
+ const columns = [];
73
+ for (const c of cols) {
74
+ const distinct = Number(counts['d_' + c.name]);
75
+ const nonNull = Number(counts['n_' + c.name]);
76
+ const type = classify(c.dataType, c.name, distinct, total);
77
+ let sampleValues = [];
78
+ let stats;
79
+ let topValues;
80
+ // Per-column detail is isolated: an uncountable/unsortable type (json/xml/geometry) that can't
81
+ // be DISTINCT'd or GROUP BY'd degrades to a bare column instead of failing the whole connect.
82
+ try {
83
+ const sv = await pool.query(`SELECT DISTINCT ${q(c.name)}::text AS v FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL LIMIT 20`);
84
+ sampleValues = sv.rows.map((r) => String(r.v)).slice(0, 5);
85
+ if (type === 'numeric' && nonNull > 0) {
86
+ const s = (await pool.query(`SELECT MIN(${q(c.name)})::float8 AS min, MAX(${q(c.name)})::float8 AS max, AVG(${q(c.name)})::float8 AS mean,
87
+ COALESCE(STDDEV_POP(${q(c.name)}),0)::float8 AS stddev,
88
+ percentile_cont(0.5) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS median,
89
+ percentile_cont(0.25) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p25,
90
+ percentile_cont(0.75) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p75
91
+ FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL`)).rows[0];
92
+ stats = { min: s.min, max: s.max, mean: s.mean, median: s.median, stddev: s.stddev, p25: s.p25, p75: s.p75 };
93
+ }
94
+ else if (type === 'categorical' || type === 'date') {
95
+ const tv = await pool.query(`SELECT ${q(c.name)}::text AS value, COUNT(*)::int AS count FROM ${q(schema)}.${q(table)}
96
+ WHERE ${q(c.name)} IS NOT NULL GROUP BY ${q(c.name)} ORDER BY COUNT(*) DESC LIMIT 10`);
97
+ topValues = tv.rows.map((r) => ({ value: String(r.value), count: r.count }));
98
+ }
99
+ }
100
+ catch { /* uncountable column → bare profile (name/type/counts only) */ }
101
+ columns.push({
102
+ name: c.name, type, sampleValues,
103
+ uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
104
+ layer: 'source', stats, topValues,
105
+ });
106
+ }
107
+ return { name: table, columns, rowCount: total };
108
+ }
109
+ async function readForeignKeys(pool, schema) {
110
+ const res = await pool.query(`SELECT tc.table_name AS ft, kcu.column_name AS fc, ccu.table_name AS tt, ccu.column_name AS tcol
111
+ FROM information_schema.table_constraints tc
112
+ JOIN information_schema.key_column_usage kcu ON tc.constraint_name=kcu.constraint_name AND tc.table_schema=kcu.table_schema
113
+ JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name=tc.constraint_name AND ccu.table_schema=tc.table_schema
114
+ WHERE tc.constraint_type='FOREIGN KEY' AND tc.table_schema=$1
115
+ ORDER BY ft, fc`, [schema]);
116
+ return res.rows.map((r) => ({ fromTable: r.ft, fromColumn: r.fc, toTable: r.tt, toColumn: r.tcol }));
117
+ }
118
+ class PgConnectedSource {
119
+ id;
120
+ name;
121
+ pool;
122
+ schemaName;
123
+ schema;
124
+ type = 'postgres';
125
+ /** Once a derivation exists, ALL queries ride this ONE pinned client so pg_temp (the shadow
126
+ * view + temp table) is visible — a pooled connection would not see them (exp 043). */
127
+ pinned = null;
128
+ /** table → derived columns materialized this session, in creation order. */
129
+ derived = new Map();
130
+ constructor(id, name, pool, schemaName, schema) {
131
+ this.id = id;
132
+ this.name = name;
133
+ this.pool = pool;
134
+ this.schemaName = schemaName;
135
+ this.schema = schema;
136
+ }
137
+ async getSchema() {
138
+ return this.schema;
139
+ }
140
+ /** The query runner: the pinned client once a derivation is active, else the pool. */
141
+ runner() {
142
+ return this.pinned ?? this.pool;
143
+ }
144
+ async executeQuery(sql) {
145
+ // The DATABASE is the read-only boundary, not a regex over the SQL text. Every model-authored
146
+ // query runs inside a READ ONLY transaction, so a data-modifying CTE (WITH … AS (DELETE …)),
147
+ // SELECT INTO, a multi-statement string, or a volatile writing function (setval/pg_terminate_backend)
148
+ // ERRORS instead of running — verified against PG 17. The trusted applyDerivation path is
149
+ // deliberately NOT wrapped, so CREATE TEMP VIEW still works (read-only txns forbid it).
150
+ // Read-only txns still permit reads of the derived temp view, so derivations are unaffected.
151
+ const usePinned = this.pinned != null;
152
+ const client = usePinned ? this.pinned : await this.pool.connect();
153
+ try {
154
+ await client.query('BEGIN TRANSACTION READ ONLY');
155
+ const r = await client.query(sql);
156
+ await client.query('COMMIT');
157
+ // Coerce by the RESULT column's actual Postgres type (OID), not by source-column
158
+ // name — so aliased aggregates (AVG/SUM AS x) and computed columns are typed
159
+ // correctly. node-postgres returns numeric/bigint as strings; we surface them as JS
160
+ // numbers for consumer parity with the CSV path (charts/aggregation downstream).
161
+ // Math already happened in SQL (policy B, exp 038); this final cast is display-side and
162
+ // carries the same float64 ceiling the CSV connector has.
163
+ const columns = r.fields.map((f) => f.name);
164
+ const numericField = new Set(r.fields.filter((f) => PG_NUMERIC_OIDS.has(f.dataTypeID)).map((f) => f.name));
165
+ const rows = r.rows.map((row) => {
166
+ const out = {};
167
+ for (const col of columns) {
168
+ const v = row[col];
169
+ // A bigint / wide numeric past 2^53 does not survive Number() — coercing it would hand
170
+ // back a silently wrong id or total. Keep those as the exact string the driver gave us.
171
+ const n = numericField.has(col) && typeof v === 'string' && v !== '' ? Number(v) : NaN;
172
+ if (Number.isFinite(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER)
173
+ out[col] = n;
174
+ else
175
+ out[col] = v;
176
+ }
177
+ return out;
178
+ });
179
+ return { columns, rows };
180
+ }
181
+ catch (err) {
182
+ try {
183
+ await client.query('ROLLBACK');
184
+ }
185
+ catch { /* txn already aborted */ }
186
+ return { columns: [], rows: [{ error: err.message }] };
187
+ }
188
+ finally {
189
+ if (!usePinned)
190
+ client.release();
191
+ }
192
+ }
193
+ async getSampleRows(tableName, count = 5) {
194
+ const total = this.schema.tables.find((t) => t.name === tableName)?.rowCount ?? 0;
195
+ if (total === 0)
196
+ return [];
197
+ if (total <= count) {
198
+ return (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)}`)).rows;
199
+ }
200
+ // block-level server-side sample; fall back to a bounded scan if it under-fills
201
+ const pct = Math.min(100, Math.max(1, Math.ceil((count / total) * 100 * 20)));
202
+ let rows = (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)} TABLESAMPLE SYSTEM(${pct}) LIMIT ${count}`)).rows;
203
+ if (rows.length < count) {
204
+ rows = (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)} LIMIT ${count}`)).rows;
205
+ }
206
+ return rows;
207
+ }
208
+ // getDatabase intentionally omitted → the derivation seam no longer keys on a raw db handle.
209
+ /**
210
+ * Postgres derives via a session-local TEMP TABLE keyed by `id`, exposed to arbitrary later
211
+ * queries through a same-named TEMP VIEW on ONE pinned client. Declared here; the materialization
212
+ * itself is wired in a subsequent stage.
213
+ */
214
+ derivationCapabilities() {
215
+ return { canDerive: true, materialization: 'session-temp', rowKey: 'id', serverSideQueryable: true };
216
+ }
217
+ /**
218
+ * Materialize a derived column as a session-local shadow TEMP VIEW on the pinned client.
219
+ * `expr` is a Postgres SQL expression over the table's columns. pg_temp precedes the schema in
220
+ * search_path, so a later unqualified `FROM <table>` transparently reads the view. The base
221
+ * table (schema-qualified inside the view) is never written. Multiple derivations accumulate.
222
+ */
223
+ async applyDerivation(table, column, expr) {
224
+ if (/;|--|\/\*/.test(expr))
225
+ throw new Error('derivation expr must be a single SQL expression (no ";" or comments)');
226
+ if (!this.pinned)
227
+ this.pinned = await this.pool.connect();
228
+ const c = this.pinned;
229
+ // CREATE TEMP VIEW cannot run inside a READ ONLY txn, so this path escapes the read-only
230
+ // boundary every other query rides. The expr is caller/model-authored, and a write needs no
231
+ // ";" to hide in it (`setval('s',1)`, a volatile writing function, a dblink call). So EVALUATE
232
+ // the expr first inside a READ ONLY txn: anything data-modifying errors there and never
233
+ // reaches the view. LIMIT 1, not LIMIT 0 — LIMIT 0 skips target-list evaluation.
234
+ await c.query('BEGIN TRANSACTION READ ONLY');
235
+ try {
236
+ await c.query(`SELECT (${expr}) FROM ${q(this.schemaName)}.${q(table)} LIMIT 1`);
237
+ await c.query('COMMIT');
238
+ }
239
+ catch (err) {
240
+ try {
241
+ await c.query('ROLLBACK');
242
+ }
243
+ catch { /* txn already aborted */ }
244
+ throw new Error(`derivation expr rejected: ${err.message}`);
245
+ }
246
+ const cols = this.derived.get(table) ?? [];
247
+ const existing = cols.find((d) => d.column === column);
248
+ if (existing)
249
+ existing.expr = expr;
250
+ else
251
+ cols.push({ column, expr });
252
+ this.derived.set(table, cols);
253
+ const projected = cols.map((d) => `(${d.expr}) AS ${q(d.column)}`).join(', ');
254
+ await c.query(`DROP VIEW IF EXISTS pg_temp.${q(table)}`);
255
+ await c.query(`CREATE TEMP VIEW ${q(table)} AS SELECT b.*, ${projected} FROM ${q(this.schemaName)}.${q(table)} b`);
256
+ registerDerivedColumn(this.schema, table, column);
257
+ }
258
+ async close() {
259
+ try {
260
+ if (this.pinned) {
261
+ this.pinned.release();
262
+ this.pinned = null;
263
+ }
264
+ }
265
+ catch { /* noop */ }
266
+ try {
267
+ await this.pool.end();
268
+ }
269
+ catch { /* already closed */ }
270
+ }
271
+ }
272
+ export const pgConnector = {
273
+ type: 'postgres',
274
+ async test(config) {
275
+ const cfg = config;
276
+ if (cfg.type !== 'postgres')
277
+ return { ok: false, error: 'Config type must be "postgres"' };
278
+ const { Pool } = await loadPg();
279
+ const pool = poolFor(Pool, cfg);
280
+ try {
281
+ await pool.query('SELECT 1');
282
+ return { ok: true };
283
+ }
284
+ catch (err) {
285
+ // A connection refusal often arrives as an AggregateError with an empty top-level message;
286
+ // fall back to the code / nested reason so the caller (and the AI agent) gets something actionable.
287
+ const reason = err?.message || err?.code || err?.errors?.map((e) => e?.message || e?.code).filter(Boolean).join('; ') || String(err);
288
+ return { ok: false, error: `Cannot connect to Postgres: ${reason}` };
289
+ }
290
+ finally {
291
+ await pool.end();
292
+ }
293
+ },
294
+ async connect(config) {
295
+ const cfg = config;
296
+ if (cfg.type !== 'postgres')
297
+ throw new Error('Config type must be "postgres"');
298
+ const schema = cfg.schema || 'public';
299
+ const { Pool } = await loadPg();
300
+ const pool = poolFor(Pool, cfg);
301
+ const tableRes = await pool.query(`SELECT table_name FROM information_schema.tables
302
+ WHERE table_schema=$1 AND table_type='BASE TABLE' ORDER BY table_name`, [schema]);
303
+ const tables = [];
304
+ for (const row of tableRes.rows) {
305
+ tables.push(await profileTable(pool, schema, row.table_name));
306
+ }
307
+ const foreignKeys = await readForeignKeys(pool, schema);
308
+ const dataSchema = {
309
+ tables, foreignKeys,
310
+ source: { id: '', type: 'postgres', name: cfg.database || 'postgres', config },
311
+ };
312
+ const id = `pg-${cfg.database || 'db'}`;
313
+ dataSchema.source.id = id;
314
+ return new PgConnectedSource(id, cfg.database || 'postgres', pool, schema, dataSchema);
315
+ },
316
+ };