@outsidedata/dolex 8.1.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -7
- package/dist/src/analysis/planner.d.ts +2 -1
- package/dist/src/analysis/planner.js +2 -2
- package/dist/src/analysis/quality.js +96 -5
- package/dist/src/analysis/rules.d.ts +22 -2
- package/dist/src/analysis/rules.js +64 -23
- package/dist/src/cleaning/index.d.ts +2 -6
- package/dist/src/cleaning/index.js +8 -3
- package/dist/src/cleaning/replay.d.ts +34 -0
- package/dist/src/cleaning/replay.js +58 -0
- package/dist/src/cli/commands/analyze.js +13 -1
- package/dist/src/cli/commands/clean.js +15 -3
- package/dist/src/cli/commands/deps.d.ts +1 -0
- package/dist/src/cli/commands/deps.js +41 -0
- package/dist/src/cli/commands/help.js +2 -1
- package/dist/src/cli/commands/sources.d.ts +2 -2
- package/dist/src/cli/commands/sources.js +138 -12
- package/dist/src/cli/commands/transform.js +19 -4
- package/dist/src/cli/index.js +3 -0
- package/dist/src/connectors/csv.js +29 -0
- package/dist/src/connectors/index.d.ts +2 -0
- package/dist/src/connectors/index.js +2 -0
- package/dist/src/connectors/manager.d.ts +39 -1
- package/dist/src/connectors/manager.js +142 -15
- package/dist/src/connectors/mongo/index.d.ts +13 -0
- package/dist/src/connectors/mongo/index.js +323 -0
- package/dist/src/connectors/pg/index.d.ts +2 -0
- package/dist/src/connectors/pg/index.js +248 -0
- package/dist/src/connectors/source-factory.d.ts +38 -0
- package/dist/src/connectors/source-factory.js +80 -0
- package/dist/src/connectors/sql-safety.js +3 -3
- package/dist/src/connectors/types.d.ts +51 -0
- package/dist/src/connectors/types.js +11 -1
- package/dist/src/mcp/index.d.ts +1 -1
- package/dist/src/mcp/index.js +20 -9
- package/dist/src/mcp/tools/analyze.js +11 -1
- package/dist/src/mcp/tools/capabilities.d.ts +1 -0
- package/dist/src/mcp/tools/capabilities.js +14 -0
- package/dist/src/mcp/tools/clean-column.js +2 -0
- package/dist/src/mcp/tools/drop-columns.js +2 -0
- package/dist/src/mcp/tools/list-transforms.js +22 -0
- package/dist/src/mcp/tools/promote-columns.js +2 -0
- package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
- package/dist/src/mcp/tools/refine.d.ts +4 -4
- package/dist/src/mcp/tools/shared.d.ts +5 -0
- package/dist/src/mcp/tools/shared.js +11 -4
- package/dist/src/mcp/tools/sources.d.ts +46 -3
- package/dist/src/mcp/tools/sources.js +44 -4
- package/dist/src/mcp/tools/transform-data.js +22 -0
- package/dist/src/types.d.ts +29 -2
- package/dist/src/utils/capabilities.d.ts +28 -0
- package/dist/src/utils/capabilities.js +58 -0
- package/dist/src/utils/optional-deps.d.ts +8 -0
- package/dist/src/utils/optional-deps.js +8 -0
- package/package.json +5 -2
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
import * as fs from 'fs';
|
|
12
12
|
import * as crypto from 'crypto';
|
|
13
13
|
import { csvConnector } from './csv.js';
|
|
14
|
+
import { pgConnector } from './pg/index.js';
|
|
15
|
+
import { mongoConnector } from './mongo/index.js';
|
|
14
16
|
import { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate } from './sql-safety.js';
|
|
15
17
|
const MAX_RESULT_ROWS = 10000;
|
|
16
18
|
// ─── SQL Safety ───────────────────────────────────────────────────────────
|
|
@@ -51,9 +53,40 @@ function generateSourceId(name) {
|
|
|
51
53
|
const hash = crypto.createHash('sha256').update(name).digest('hex').slice(0, 12);
|
|
52
54
|
return `src-${hash}`;
|
|
53
55
|
}
|
|
56
|
+
/** Classify a connection failure into an actionable kind, so callers can give a specific next step
|
|
57
|
+
* (install the driver / start the DB / fix credentials) instead of relaying a raw driver string. */
|
|
58
|
+
export function classifyConnError(msg = '') {
|
|
59
|
+
if (/needs an optional dependency|npm install/i.test(msg))
|
|
60
|
+
return 'driver-missing';
|
|
61
|
+
if (/ECONNREFUSED|connection refused/i.test(msg))
|
|
62
|
+
return 'unreachable';
|
|
63
|
+
if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/i.test(msg))
|
|
64
|
+
return 'host-not-found';
|
|
65
|
+
if (/ETIMEDOUT|timed? ?out/i.test(msg))
|
|
66
|
+
return 'timeout';
|
|
67
|
+
if (/password|authentication|auth(entication)? failed|SCRAM|role ".*" does not exist|not authorized/i.test(msg))
|
|
68
|
+
return 'auth-failed';
|
|
69
|
+
if (/database ".*" does not exist|Unknown database|no such database/i.test(msg))
|
|
70
|
+
return 'db-not-found';
|
|
71
|
+
return 'error';
|
|
72
|
+
}
|
|
54
73
|
const CONNECTOR_MAP = {
|
|
55
74
|
csv: csvConnector,
|
|
75
|
+
postgres: pgConnector,
|
|
76
|
+
mongodb: mongoConnector,
|
|
56
77
|
};
|
|
78
|
+
/** SQL-family sources go through the SQL safety/limit/error machinery; a document store
|
|
79
|
+
* (mongodb) is routed down a pipeline path instead (no SELECT gate, no LIMIT-wrap). */
|
|
80
|
+
const isSqlSource = (type) => type === 'csv' || type === 'postgres';
|
|
81
|
+
/** Read-only gate for an aggregation pipeline: reject write stages ($out/$merge) and any
|
|
82
|
+
* arbitrary-JS operators ($function/$accumulator/$where) — the Mongo analogue of the
|
|
83
|
+
* SELECT-only SQL gate. Best-effort: a malformed pipeline string is rejected too. */
|
|
84
|
+
function isReadOnlyPipeline(query) {
|
|
85
|
+
if (/"\$(?:out|merge|function|accumulator|where)"/i.test(query)) {
|
|
86
|
+
return { ok: false, error: 'Only read-only aggregation pipelines are allowed (no $out/$merge/$function/$accumulator/$where).' };
|
|
87
|
+
}
|
|
88
|
+
return { ok: true };
|
|
89
|
+
}
|
|
57
90
|
function getConnectorForType(type) {
|
|
58
91
|
return CONNECTOR_MAP[type];
|
|
59
92
|
}
|
|
@@ -119,6 +152,11 @@ export class SourceManager {
|
|
|
119
152
|
const tmpPath = `${this.persistPath}.${process.pid}.tmp`;
|
|
120
153
|
fs.writeFileSync(tmpPath, JSON.stringify(entries, null, 2), 'utf-8');
|
|
121
154
|
fs.renameSync(tmpPath, this.persistPath);
|
|
155
|
+
// The registry may hold connection strings / credentials — restrict it to the owner.
|
|
156
|
+
try {
|
|
157
|
+
fs.chmodSync(this.persistPath, 0o600);
|
|
158
|
+
}
|
|
159
|
+
catch { /* best-effort */ }
|
|
122
160
|
}
|
|
123
161
|
catch {
|
|
124
162
|
// Persistence failure is non-fatal
|
|
@@ -129,15 +167,11 @@ export class SourceManager {
|
|
|
129
167
|
* Add a data source to the registry.
|
|
130
168
|
* Does NOT connect immediately — connection is lazy on first query or explicit connect().
|
|
131
169
|
*/
|
|
132
|
-
async add(name, config) {
|
|
170
|
+
async add(name, config, opts = {}) {
|
|
133
171
|
const connector = getConnectorForType(config.type);
|
|
134
172
|
if (!connector) {
|
|
135
173
|
return { ok: false, error: `Unsupported data source type: ${config.type}` };
|
|
136
174
|
}
|
|
137
|
-
const testResult = await connector.test(config);
|
|
138
|
-
if (!testResult.ok) {
|
|
139
|
-
return { ok: false, error: testResult.error };
|
|
140
|
-
}
|
|
141
175
|
const id = generateSourceId(name);
|
|
142
176
|
if (this.registry.has(id)) {
|
|
143
177
|
return {
|
|
@@ -145,10 +179,54 @@ export class SourceManager {
|
|
|
145
179
|
error: `A source named "${name}" already exists (id: ${id}). Remove it first or use a different name.`,
|
|
146
180
|
};
|
|
147
181
|
}
|
|
182
|
+
// Config-first: liveness is NOT a precondition for registering (a DB can be momentarily down,
|
|
183
|
+
// asleep, or behind a not-yet-started tunnel). We verify, but only REFUSE when opts.verify is
|
|
184
|
+
// set; otherwise we persist the config and report the connectivity result so the caller can act.
|
|
185
|
+
const testResult = await connector.test(config);
|
|
186
|
+
if (!testResult.ok && opts.verify) {
|
|
187
|
+
return { ok: false, error: testResult.error, verified: false };
|
|
188
|
+
}
|
|
148
189
|
const entry = { id, name, type: config.type, config };
|
|
149
190
|
this.registry.set(id, entry);
|
|
150
191
|
this.saveRegistry();
|
|
151
|
-
return { ok: true, entry };
|
|
192
|
+
return { ok: true, entry, verified: testResult.ok, warning: testResult.ok ? undefined : testResult.error };
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Update a registered source's config in place (DB moved, password rotated, driver now installed)
|
|
196
|
+
* WITHOUT losing its id — so every existing reference keeps working. `patch` is merged over the
|
|
197
|
+
* stored config; the type is immutable. Any live connection is closed so the next use reconnects.
|
|
198
|
+
*/
|
|
199
|
+
async update(idOrName, patch, opts = {}) {
|
|
200
|
+
const entry = this.findEntry(idOrName);
|
|
201
|
+
if (!entry)
|
|
202
|
+
return { ok: false, error: `Source not found: ${idOrName}` };
|
|
203
|
+
const config = { ...entry.config, ...patch, type: entry.config.type };
|
|
204
|
+
const connector = getConnectorForType(config.type);
|
|
205
|
+
const testResult = await connector.test(config);
|
|
206
|
+
if (!testResult.ok && opts.verify)
|
|
207
|
+
return { ok: false, error: testResult.error, verified: false };
|
|
208
|
+
const conn = this.connections.get(entry.id);
|
|
209
|
+
if (conn) {
|
|
210
|
+
await conn.close();
|
|
211
|
+
this.connections.delete(entry.id);
|
|
212
|
+
}
|
|
213
|
+
entry.config = config;
|
|
214
|
+
this.registry.set(entry.id, entry);
|
|
215
|
+
this.saveRegistry();
|
|
216
|
+
return { ok: true, entry, verified: testResult.ok, warning: testResult.ok ? undefined : testResult.error };
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Connectivity health-check for a REGISTERED source (the return-user's "is my saved DB still
|
|
220
|
+
* reachable?" and an agent's pre-flight). Returns a classified failure so the caller can give an
|
|
221
|
+
* actionable next step rather than a raw driver string.
|
|
222
|
+
*/
|
|
223
|
+
async testSource(idOrName) {
|
|
224
|
+
const entry = this.findEntry(idOrName);
|
|
225
|
+
if (!entry)
|
|
226
|
+
return { ok: false, error: `Source not found: ${idOrName}`, kind: 'not-registered' };
|
|
227
|
+
const connector = getConnectorForType(entry.config.type);
|
|
228
|
+
const r = await connector.test(entry.config);
|
|
229
|
+
return r.ok ? { ok: true } : { ok: false, error: r.error, kind: classifyConnError(r.error) };
|
|
152
230
|
}
|
|
153
231
|
/**
|
|
154
232
|
* Remove a data source by ID or name. Closes the connection if active.
|
|
@@ -259,13 +337,19 @@ export class SourceManager {
|
|
|
259
337
|
}
|
|
260
338
|
}
|
|
261
339
|
async query(idOrName, sql) {
|
|
262
|
-
// Enforce read-only queries to prevent SQL injection attacks
|
|
263
|
-
if (!isReadOnlySelect(sql)) {
|
|
264
|
-
return { ok: false, error: 'Only SELECT queries are allowed.' };
|
|
265
|
-
}
|
|
266
340
|
const resolved = await this.resolveSource(idOrName);
|
|
267
341
|
if (!resolved.ok)
|
|
268
342
|
return resolved;
|
|
343
|
+
// A document store takes an aggregation pipeline, not SQL — gate + run accordingly.
|
|
344
|
+
if (!isSqlSource(resolved.source.type)) {
|
|
345
|
+
const guard = isReadOnlyPipeline(sql);
|
|
346
|
+
if (!guard.ok)
|
|
347
|
+
return { ok: false, error: guard.error };
|
|
348
|
+
}
|
|
349
|
+
else if (!isReadOnlySelect(sql)) {
|
|
350
|
+
// Enforce read-only queries to prevent SQL injection attacks
|
|
351
|
+
return { ok: false, error: 'Only SELECT queries are allowed.' };
|
|
352
|
+
}
|
|
269
353
|
try {
|
|
270
354
|
const result = await resolved.source.executeQuery(sql);
|
|
271
355
|
const errorMsg = hasErrorRow(result);
|
|
@@ -283,12 +367,17 @@ export class SourceManager {
|
|
|
283
367
|
* Error messages are enriched with available table/column names.
|
|
284
368
|
*/
|
|
285
369
|
async querySql(idOrName, sql, maxRows = MAX_RESULT_ROWS) {
|
|
286
|
-
if (!isReadOnlySelect(sql)) {
|
|
287
|
-
return { ok: false, error: 'Only SELECT queries are allowed.' };
|
|
288
|
-
}
|
|
289
370
|
const resolved = await this.resolveSource(idOrName);
|
|
290
371
|
if (!resolved.ok)
|
|
291
372
|
return resolved;
|
|
373
|
+
// Document store: run the read-only aggregation pipeline (no SELECT gate, no LIMIT-wrap);
|
|
374
|
+
// cap the result set client-side instead of via SQL.
|
|
375
|
+
if (!isSqlSource(resolved.source.type)) {
|
|
376
|
+
return this.queryPipeline(resolved.source, sql, Math.min(maxRows, MAX_RESULT_ROWS));
|
|
377
|
+
}
|
|
378
|
+
if (!isReadOnlySelect(sql)) {
|
|
379
|
+
return { ok: false, error: 'Only SELECT queries are allowed.' };
|
|
380
|
+
}
|
|
292
381
|
const cappedSql = wrapWithLimit(sql, Math.min(maxRows, MAX_RESULT_ROWS));
|
|
293
382
|
try {
|
|
294
383
|
const result = await resolved.source.executeQuery(cappedSql);
|
|
@@ -315,6 +404,31 @@ export class SourceManager {
|
|
|
315
404
|
return { ok: false, error: `SQL query failed: ${enriched}` };
|
|
316
405
|
}
|
|
317
406
|
}
|
|
407
|
+
/**
|
|
408
|
+
* Run a read-only aggregation pipeline against a document store and return rows + columns,
|
|
409
|
+
* capped to maxRows. The pipeline string is the {collection, pipeline} seam the connector
|
|
410
|
+
* parses. No SQL safety pass (those footguns are SQL-only); Mongo-specific footgun
|
|
411
|
+
* detection is the language-plane work, added later. Never throws (audit-on-load relies on it).
|
|
412
|
+
*/
|
|
413
|
+
async queryPipeline(source, query, maxRows) {
|
|
414
|
+
const guard = isReadOnlyPipeline(query);
|
|
415
|
+
if (!guard.ok)
|
|
416
|
+
return { ok: false, error: guard.error };
|
|
417
|
+
try {
|
|
418
|
+
const result = await source.executeQuery(query);
|
|
419
|
+
const errorMsg = hasErrorRow(result);
|
|
420
|
+
if (errorMsg)
|
|
421
|
+
return { ok: false, error: errorMsg };
|
|
422
|
+
const capped = result.rows.slice(0, maxRows);
|
|
423
|
+
return {
|
|
424
|
+
ok: true, rows: capped, columns: result.columns,
|
|
425
|
+
totalRows: result.rows.length, truncated: result.rows.length > capped.length,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
catch (err) {
|
|
429
|
+
return { ok: false, error: `Pipeline query failed: ${err.message}` };
|
|
430
|
+
}
|
|
431
|
+
}
|
|
318
432
|
/**
|
|
319
433
|
* Advisory SQL-safety pass over a successful query. Best-effort: any failure
|
|
320
434
|
* yields no warnings (never blocks or breaks the query). Gated on a cheap
|
|
@@ -333,6 +447,18 @@ export class SourceManager {
|
|
|
333
447
|
for (const c of t.columns)
|
|
334
448
|
if (!colToTable.has(c.name))
|
|
335
449
|
colToTable.set(c.name, t.name);
|
|
450
|
+
// Type probe is dialect-specific: SQLite has typeof(); Postgres has pg_typeof().
|
|
451
|
+
// Normalize the result so the integer-division check ('integer') works on both —
|
|
452
|
+
// Postgres int columns report integer/bigint/smallint, floats numeric/double precision.
|
|
453
|
+
const isPg = source.type === 'postgres';
|
|
454
|
+
const normalizeType = (raw) => {
|
|
455
|
+
const t = raw.toLowerCase();
|
|
456
|
+
if (t === 'integer' || t === 'bigint' || t === 'smallint')
|
|
457
|
+
return 'integer';
|
|
458
|
+
if (t === 'numeric' || t === 'double precision' || t === 'real')
|
|
459
|
+
return 'real';
|
|
460
|
+
return t;
|
|
461
|
+
};
|
|
336
462
|
const typeCache = new Map();
|
|
337
463
|
const columnType = async (col) => {
|
|
338
464
|
if (typeCache.has(col))
|
|
@@ -340,9 +466,10 @@ export class SourceManager {
|
|
|
340
466
|
let type;
|
|
341
467
|
const table = colToTable.get(col);
|
|
342
468
|
if (table) {
|
|
343
|
-
const
|
|
469
|
+
const probe = isPg ? `pg_typeof("${col}")::text` : `typeof("${col}")`;
|
|
470
|
+
const r = await source.executeQuery(`SELECT ${probe} AS t FROM "${table}" WHERE "${col}" IS NOT NULL LIMIT 1`);
|
|
344
471
|
const v = r.rows?.[0]?.t;
|
|
345
|
-
type = typeof v === 'string' ? v : undefined;
|
|
472
|
+
type = typeof v === 'string' ? normalizeType(v) : undefined;
|
|
346
473
|
}
|
|
347
474
|
typeCache.set(col, type);
|
|
348
475
|
return type;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DataConnector } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* TOLERANT seam parse. Callers reliably produce correct aggregation STAGES but fumble the
|
|
4
|
+
* hand-written JSON ENVELOPE, so accept, in order: the full {"collection","pipeline":[…]}; a BARE
|
|
5
|
+
* pipeline array [<stages>] (wrapped with the primary collection); or an envelope missing its
|
|
6
|
+
* trailing brace(s), repaired by balancing. Empty/garbage is rejected with an actionable message —
|
|
7
|
+
* never silently "repaired" into a fake pipeline.
|
|
8
|
+
*/
|
|
9
|
+
export declare function parseSeam(query: string, defaultCollection?: string): {
|
|
10
|
+
collection: string;
|
|
11
|
+
pipeline: any[];
|
|
12
|
+
};
|
|
13
|
+
export declare const mongoConnector: DataConnector;
|
|
@@ -0,0 +1,323 @@
|
|
|
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
|
+
function uriFor(cfg) {
|
|
8
|
+
if (cfg.uri)
|
|
9
|
+
return cfg.uri;
|
|
10
|
+
return `mongodb://${cfg.host || 'localhost'}:${cfg.port || 27017}`;
|
|
11
|
+
}
|
|
12
|
+
const NUMERIC = (v) => typeof v === 'number';
|
|
13
|
+
/** Duck-type a BSON ObjectId without importing the driver class (an ObjectId has toHexString()). */
|
|
14
|
+
const isObjectId = (v) => v != null && typeof v === 'object' && typeof v.toHexString === 'function';
|
|
15
|
+
/** Coerce a BSON value to a JS-friendly value for consumer parity (charts/markdown/JSON). */
|
|
16
|
+
function jsValue(v) {
|
|
17
|
+
if (v == null)
|
|
18
|
+
return v;
|
|
19
|
+
if (isObjectId(v))
|
|
20
|
+
return v.toString();
|
|
21
|
+
if (v instanceof Date)
|
|
22
|
+
return v.toISOString();
|
|
23
|
+
return v;
|
|
24
|
+
}
|
|
25
|
+
/** Candidate type from a sampled value (refined by distinct/total in classify). */
|
|
26
|
+
function candidateType(v) {
|
|
27
|
+
if (typeof v === 'number')
|
|
28
|
+
return 'numeric';
|
|
29
|
+
if (v instanceof Date)
|
|
30
|
+
return 'date';
|
|
31
|
+
if (isObjectId(v))
|
|
32
|
+
return 'id';
|
|
33
|
+
return 'text'; // string/bool/other → text, refined to categorical by cardinality
|
|
34
|
+
}
|
|
35
|
+
function classify(cand, name, distinct, total) {
|
|
36
|
+
if (name === '_id')
|
|
37
|
+
return 'id';
|
|
38
|
+
if (cand === 'numeric') {
|
|
39
|
+
if (/(^|_)id$/i.test(name) && total > 0 && distinct >= total * 0.9)
|
|
40
|
+
return 'id';
|
|
41
|
+
return 'numeric';
|
|
42
|
+
}
|
|
43
|
+
if (cand === 'date' || cand === 'id')
|
|
44
|
+
return cand;
|
|
45
|
+
// text-ish: low cardinality ⇒ categorical
|
|
46
|
+
if (total > 0 && distinct <= Math.min(200, Math.max(50, total * 0.5)))
|
|
47
|
+
return 'categorical';
|
|
48
|
+
return 'text';
|
|
49
|
+
}
|
|
50
|
+
async function profileCollection(db, name) {
|
|
51
|
+
const coll = db.collection(name);
|
|
52
|
+
const total = await coll.countDocuments();
|
|
53
|
+
// Phase 1 — sample docs to discover the key universe + a candidate type per key.
|
|
54
|
+
const sampled = await coll.find({}, { limit: SAMPLE_DOCS }).toArray();
|
|
55
|
+
const keys = [];
|
|
56
|
+
const candByKey = new Map();
|
|
57
|
+
const sampleValsByKey = new Map();
|
|
58
|
+
for (const doc of sampled) {
|
|
59
|
+
for (const k of Object.keys(doc)) {
|
|
60
|
+
if (!candByKey.has(k)) {
|
|
61
|
+
keys.push(k);
|
|
62
|
+
candByKey.set(k, candidateType(doc[k]));
|
|
63
|
+
sampleValsByKey.set(k, []);
|
|
64
|
+
}
|
|
65
|
+
const sv = sampleValsByKey.get(k);
|
|
66
|
+
const v = doc[k];
|
|
67
|
+
if (v != null && sv.length < 5)
|
|
68
|
+
sv.push(String(jsValue(v)));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (total === 0 || keys.length === 0)
|
|
72
|
+
return { name, columns: [], rowCount: total };
|
|
73
|
+
// Phase 2 — ONE $facet: per-key non-null + distinct counts, numeric stats, categorical top-values.
|
|
74
|
+
const facet = {};
|
|
75
|
+
for (const k of keys) {
|
|
76
|
+
const cand = candByKey.get(k);
|
|
77
|
+
facet[`${k}__nn`] = [{ $match: { [k]: { $ne: null, $exists: true } } }, { $count: 'n' }];
|
|
78
|
+
facet[`${k}__dc`] = [{ $group: { _id: `$${k}` } }, { $count: 'n' }];
|
|
79
|
+
if (cand === 'numeric') {
|
|
80
|
+
// Mongo 5.0 has no $percentile; sort + $push then pick positional elements server-side
|
|
81
|
+
// (the array stays inside the sub-pipeline — the facet only stores the scalar result).
|
|
82
|
+
facet[`${k}__st`] = [
|
|
83
|
+
{ $match: { [k]: { $type: 'number' } } },
|
|
84
|
+
{ $sort: { [k]: 1 } },
|
|
85
|
+
{ $group: { _id: null, vals: { $push: `$${k}` }, min: { $min: `$${k}` }, max: { $max: `$${k}` }, avg: { $avg: `$${k}` }, sd: { $stdDevPop: `$${k}` }, n: { $sum: 1 } } },
|
|
86
|
+
{ $project: {
|
|
87
|
+
min: 1, max: 1, avg: 1, sd: 1,
|
|
88
|
+
median: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.5] } }] },
|
|
89
|
+
p25: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.25] } }] },
|
|
90
|
+
p75: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.75] } }] },
|
|
91
|
+
} },
|
|
92
|
+
];
|
|
93
|
+
}
|
|
94
|
+
else if (k !== '_id') {
|
|
95
|
+
facet[`${k}__tv`] = [{ $match: { [k]: { $ne: null } } }, { $sortByCount: `$${k}` }, { $limit: 10 }];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const [f] = await coll.aggregate([{ $facet: facet }], { allowDiskUse: true }).toArray();
|
|
99
|
+
const one = (arr) => (arr && arr.length ? arr[0] : undefined);
|
|
100
|
+
const columns = keys.map((k) => {
|
|
101
|
+
const nonNull = Number(one(f[`${k}__nn`])?.n ?? 0);
|
|
102
|
+
const distinct = Number(one(f[`${k}__dc`])?.n ?? 0);
|
|
103
|
+
const type = classify(candByKey.get(k), k, distinct, total);
|
|
104
|
+
let stats;
|
|
105
|
+
let topValues;
|
|
106
|
+
if (type === 'numeric') {
|
|
107
|
+
const s = one(f[`${k}__st`]);
|
|
108
|
+
if (s)
|
|
109
|
+
stats = { min: s.min, max: s.max, mean: s.avg, median: s.median, stddev: s.sd ?? 0, p25: s.p25, p75: s.p75 };
|
|
110
|
+
}
|
|
111
|
+
else if (k !== '_id') {
|
|
112
|
+
const tv = f[`${k}__tv`];
|
|
113
|
+
if (tv?.length)
|
|
114
|
+
topValues = tv.map((r) => ({ value: String(jsValue(r._id)), count: r.count }));
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
name: k, type, sampleValues: sampleValsByKey.get(k) ?? [],
|
|
118
|
+
uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
|
|
119
|
+
layer: 'source', stats, topValues,
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
return { name, columns, rowCount: total };
|
|
123
|
+
}
|
|
124
|
+
const tryParseJson = (q) => { try {
|
|
125
|
+
return JSON.parse(q);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return undefined;
|
|
129
|
+
} };
|
|
130
|
+
/** Append the closers for any unclosed { or [ (string-aware) — repairs a common caller near-miss:
|
|
131
|
+
* a correct pipeline whose outer envelope is missing its trailing brace. */
|
|
132
|
+
function balanceBrackets(q) {
|
|
133
|
+
const stack = [];
|
|
134
|
+
let inStr = false, esc = false;
|
|
135
|
+
for (const ch of q) {
|
|
136
|
+
if (esc) {
|
|
137
|
+
esc = false;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (ch === '\\') {
|
|
141
|
+
esc = true;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch === '"') {
|
|
145
|
+
inStr = !inStr;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (inStr)
|
|
149
|
+
continue;
|
|
150
|
+
if (ch === '{' || ch === '[')
|
|
151
|
+
stack.push(ch);
|
|
152
|
+
else if (ch === '}' || ch === ']')
|
|
153
|
+
stack.pop();
|
|
154
|
+
}
|
|
155
|
+
let out = q;
|
|
156
|
+
for (let i = stack.length - 1; i >= 0; i--)
|
|
157
|
+
out += stack[i] === '{' ? '}' : ']';
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* TOLERANT seam parse. Callers reliably produce correct aggregation STAGES but fumble the
|
|
162
|
+
* hand-written JSON ENVELOPE, so accept, in order: the full {"collection","pipeline":[…]}; a BARE
|
|
163
|
+
* pipeline array [<stages>] (wrapped with the primary collection); or an envelope missing its
|
|
164
|
+
* trailing brace(s), repaired by balancing. Empty/garbage is rejected with an actionable message —
|
|
165
|
+
* never silently "repaired" into a fake pipeline.
|
|
166
|
+
*/
|
|
167
|
+
export function parseSeam(query, defaultCollection) {
|
|
168
|
+
const raw = (query ?? '').trim();
|
|
169
|
+
const parsed = tryParseJson(raw) ?? tryParseJson(balanceBrackets(raw));
|
|
170
|
+
if (Array.isArray(parsed) && defaultCollection)
|
|
171
|
+
return { collection: defaultCollection, pipeline: parsed };
|
|
172
|
+
if (parsed && typeof parsed.collection === 'string' && Array.isArray(parsed.pipeline))
|
|
173
|
+
return { collection: parsed.collection, pipeline: parsed.pipeline };
|
|
174
|
+
if (parsed && Array.isArray(parsed.pipeline) && defaultCollection)
|
|
175
|
+
return { collection: defaultCollection, pipeline: parsed.pipeline };
|
|
176
|
+
throw new Error('Mongo query must be a JSON aggregation pipeline: a bare array [<stages>], or {"collection":"<name>","pipeline":[<stages>]}');
|
|
177
|
+
}
|
|
178
|
+
class MongoConnectedSource {
|
|
179
|
+
id;
|
|
180
|
+
name;
|
|
181
|
+
client;
|
|
182
|
+
db;
|
|
183
|
+
schema;
|
|
184
|
+
type = 'mongodb';
|
|
185
|
+
/** collection → derived fields materialized this session (a $set expr each), in creation order. */
|
|
186
|
+
derived = new Map();
|
|
187
|
+
constructor(id, name, client, db, schema) {
|
|
188
|
+
this.id = id;
|
|
189
|
+
this.name = name;
|
|
190
|
+
this.client = client;
|
|
191
|
+
this.db = db;
|
|
192
|
+
this.schema = schema;
|
|
193
|
+
}
|
|
194
|
+
async getSchema() {
|
|
195
|
+
return this.schema;
|
|
196
|
+
}
|
|
197
|
+
async executeQuery(query) {
|
|
198
|
+
try {
|
|
199
|
+
const { collection, pipeline } = parseSeam(query, this.schema.tables[0]?.name);
|
|
200
|
+
// Prepend a $set for each session-derived field so every aggregation sees it transparently,
|
|
201
|
+
// without ever writing the base collection.
|
|
202
|
+
const derived = this.derived.get(collection) ?? [];
|
|
203
|
+
const setStage = derived.length ? [{ $set: Object.fromEntries(derived.map((d) => [d.field, d.expr])) }] : [];
|
|
204
|
+
const docs = await this.db.collection(collection).aggregate([...setStage, ...pipeline]).toArray();
|
|
205
|
+
// Columns: union of keys across result docs, in first-seen order (docs are ragged).
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
const columns = [];
|
|
208
|
+
for (const d of docs)
|
|
209
|
+
for (const k of Object.keys(d))
|
|
210
|
+
if (!seen.has(k)) {
|
|
211
|
+
seen.add(k);
|
|
212
|
+
columns.push(k);
|
|
213
|
+
}
|
|
214
|
+
const rows = docs.map((d) => {
|
|
215
|
+
const out = {};
|
|
216
|
+
for (const k of columns)
|
|
217
|
+
out[k] = jsValue(d[k]);
|
|
218
|
+
return out;
|
|
219
|
+
});
|
|
220
|
+
return { columns, rows };
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
return { columns: [], rows: [{ error: err.message }] };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async getSampleRows(collectionName, count = 5) {
|
|
227
|
+
const total = this.schema.tables.find((t) => t.name === collectionName)?.rowCount ?? 0;
|
|
228
|
+
if (total === 0)
|
|
229
|
+
return [];
|
|
230
|
+
const docs = total <= count
|
|
231
|
+
? await this.db.collection(collectionName).find({}, { limit: count }).toArray()
|
|
232
|
+
: await this.db.collection(collectionName).aggregate([{ $sample: { size: count } }]).toArray();
|
|
233
|
+
return docs.map((d) => {
|
|
234
|
+
const out = {};
|
|
235
|
+
for (const k of Object.keys(d))
|
|
236
|
+
out[k] = jsValue(d[k]);
|
|
237
|
+
return out;
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
// getDatabase intentionally omitted → the derivation seam no longer keys on a raw db handle.
|
|
241
|
+
/**
|
|
242
|
+
* Mongo derives a FIELD via a `$set` aggregation expression prepended to every incoming pipeline
|
|
243
|
+
* (see executeQuery). No sidecar, no write to the base collection — the derived field is computed
|
|
244
|
+
* server-side on read. `materialization:'computed-set'` reflects that.
|
|
245
|
+
*/
|
|
246
|
+
derivationCapabilities() {
|
|
247
|
+
return { canDerive: true, materialization: 'computed-set', rowKey: '_id', serverSideQueryable: true };
|
|
248
|
+
}
|
|
249
|
+
/** Register a derived field: `expr` is a JSON Mongo aggregation expression (e.g. a $cond). It is
|
|
250
|
+
* prepended as a $set to every subsequent aggregation; the base collection is never written. */
|
|
251
|
+
async applyDerivation(table, column, expr) {
|
|
252
|
+
let parsed;
|
|
253
|
+
try {
|
|
254
|
+
parsed = JSON.parse(expr);
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
throw new Error('Mongo derivation expr must be a JSON aggregation expression, e.g. {"$cond":[...]}');
|
|
258
|
+
}
|
|
259
|
+
const cols = this.derived.get(table) ?? [];
|
|
260
|
+
const existing = cols.find((d) => d.field === column);
|
|
261
|
+
if (existing)
|
|
262
|
+
existing.expr = parsed;
|
|
263
|
+
else
|
|
264
|
+
cols.push({ field: column, expr: parsed });
|
|
265
|
+
this.derived.set(table, cols);
|
|
266
|
+
registerDerivedColumn(this.schema, table, column);
|
|
267
|
+
}
|
|
268
|
+
async close() {
|
|
269
|
+
try {
|
|
270
|
+
await this.client.close();
|
|
271
|
+
}
|
|
272
|
+
catch { /* already closed */ }
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
export const mongoConnector = {
|
|
276
|
+
type: 'mongodb',
|
|
277
|
+
async test(config) {
|
|
278
|
+
const cfg = config;
|
|
279
|
+
if (cfg.type !== 'mongodb')
|
|
280
|
+
return { ok: false, error: 'Config type must be "mongodb"' };
|
|
281
|
+
if (!cfg.database)
|
|
282
|
+
return { ok: false, error: 'Mongo config requires a "database"' };
|
|
283
|
+
const { MongoClient } = await loadMongo();
|
|
284
|
+
const client = new MongoClient(uriFor(cfg));
|
|
285
|
+
try {
|
|
286
|
+
await client.connect();
|
|
287
|
+
await client.db(cfg.database).command({ ping: 1 });
|
|
288
|
+
return { ok: true };
|
|
289
|
+
}
|
|
290
|
+
catch (err) {
|
|
291
|
+
const reason = err?.message || err?.code || err?.errors?.map((e) => e?.message || e?.code).filter(Boolean).join('; ') || String(err);
|
|
292
|
+
return { ok: false, error: `Cannot connect to MongoDB: ${reason}` };
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
await client.close().catch(() => { });
|
|
296
|
+
}
|
|
297
|
+
},
|
|
298
|
+
async connect(config) {
|
|
299
|
+
const cfg = config;
|
|
300
|
+
if (cfg.type !== 'mongodb')
|
|
301
|
+
throw new Error('Config type must be "mongodb"');
|
|
302
|
+
if (!cfg.database)
|
|
303
|
+
throw new Error('Mongo config requires a "database"');
|
|
304
|
+
const { MongoClient } = await loadMongo();
|
|
305
|
+
const client = new MongoClient(uriFor(cfg));
|
|
306
|
+
await client.connect();
|
|
307
|
+
const db = client.db(cfg.database);
|
|
308
|
+
let names = cfg.collections;
|
|
309
|
+
if (!names || names.length === 0) {
|
|
310
|
+
names = (await db.listCollections({}, { nameOnly: true }).toArray())
|
|
311
|
+
.map((c) => c.name).filter((n) => !n.startsWith('system.'));
|
|
312
|
+
}
|
|
313
|
+
// Each collection profiles independently (own count + sample + one $facet), so connect()
|
|
314
|
+
// latency need not scale linearly with collection count.
|
|
315
|
+
const tables = await Promise.all(names.map((n) => profileCollection(db, n)));
|
|
316
|
+
const id = `mongo-${cfg.database}`;
|
|
317
|
+
const dataSchema = {
|
|
318
|
+
tables, foreignKeys: [],
|
|
319
|
+
source: { id, type: 'mongodb', name: cfg.database, config },
|
|
320
|
+
};
|
|
321
|
+
return new MongoConnectedSource(id, cfg.database, client, db, dataSchema);
|
|
322
|
+
},
|
|
323
|
+
};
|