@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function depsCommand(argv: string[]): Promise<number>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dolex deps` — report which optional capabilities are available in THIS environment, so a
|
|
3
|
+
* human (or an AI agent driving Dolex) can see what's ready and how to enable the rest BEFORE
|
|
4
|
+
* trying it. The sibling of `dolex check` (which audits DATA health); this audits ENVIRONMENT health.
|
|
5
|
+
*
|
|
6
|
+
* `--json` emits the shared capability report for an agent to reason on. Exit code is non-zero only
|
|
7
|
+
* when a CORE dependency is missing (the base install is broken), like `dolex check`.
|
|
8
|
+
*/
|
|
9
|
+
import { parseArgs, bool } from '../args.js';
|
|
10
|
+
import * as o from '../output.js';
|
|
11
|
+
import { probeCapabilities } from '../../utils/capabilities.js';
|
|
12
|
+
export async function depsCommand(argv) {
|
|
13
|
+
const args = parseArgs(argv, { booleans: ['json', 'help'], aliases: { h: 'help' } });
|
|
14
|
+
if (bool(args, 'help')) {
|
|
15
|
+
o.out('dolex deps — report which optional capabilities are available in this environment.');
|
|
16
|
+
o.out(' --json machine-readable report (for an AI agent to check readiness before acting)');
|
|
17
|
+
return 0;
|
|
18
|
+
}
|
|
19
|
+
const cap = probeCapabilities();
|
|
20
|
+
if (bool(args, 'json')) {
|
|
21
|
+
o.out(JSON.stringify(cap, null, 2));
|
|
22
|
+
return cap.coreOk ? 0 : 1;
|
|
23
|
+
}
|
|
24
|
+
o.heading('Data sources — what can I connect to here');
|
|
25
|
+
o.out(o.table(['source', 'status'], [
|
|
26
|
+
{ source: 'CSV / SQLite', status: cap.sources.csv },
|
|
27
|
+
{ source: 'PostgreSQL', status: cap.sources.postgres },
|
|
28
|
+
{ source: 'MongoDB', status: cap.sources.mongodb },
|
|
29
|
+
]));
|
|
30
|
+
o.out();
|
|
31
|
+
o.heading('Optional features');
|
|
32
|
+
o.out(o.table(['feature', 'installed', 'how to enable'], [
|
|
33
|
+
...cap.deps.map((d) => ({ feature: d.enables, installed: d.installed ? `✓ ${d.version ?? ''}`.trim() : '—', 'how to enable': d.install ?? '' })),
|
|
34
|
+
{ feature: cap.python.enables, installed: cap.python.available ? `✓ ${cap.python.version ?? ''}`.trim() : '—', 'how to enable': cap.python.install ?? '' },
|
|
35
|
+
]));
|
|
36
|
+
if (!cap.coreOk) {
|
|
37
|
+
o.out();
|
|
38
|
+
o.fail('core engine (better-sqlite3) is missing — reinstall dolex.');
|
|
39
|
+
}
|
|
40
|
+
return cap.coreOk ? 0 : 1;
|
|
41
|
+
}
|
|
@@ -22,7 +22,8 @@ ${o.c.bold('COMMANDS')}
|
|
|
22
22
|
${o.c.cyan('columns')} <csv|source> List columns by layer (source / derived / working)
|
|
23
23
|
${o.c.cyan('drop')} <csv|source> Remove derived/working columns
|
|
24
24
|
${o.c.cyan('patterns')} [id] List the 43 chart patterns, or show one
|
|
25
|
-
${o.c.cyan('sources')} <list|add|rm>
|
|
25
|
+
${o.c.cyan('sources')} <list|add|rm> Register & manage data sources (CSV / Postgres / MongoDB)
|
|
26
|
+
${o.c.cyan('deps')} Report which data sources & optional features are available here
|
|
26
27
|
${o.c.cyan('mcp')} Run the MCP stdio server (Claude Desktop / agents)
|
|
27
28
|
${o.c.cyan('help')} [command] Show help; \`--version\` for version
|
|
28
29
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `dolex sources` — manage the persistent
|
|
3
|
-
* `~/.dolex/sources.json` (shared with the MCP server's `
|
|
2
|
+
* `dolex sources` — manage the persistent data-source registry at
|
|
3
|
+
* `~/.dolex/sources.json` (CSV / Postgres / MongoDB; shared with the MCP server's `load_source`).
|
|
4
4
|
*/
|
|
5
5
|
export declare function sourcesCommand(argv: string[]): Promise<number>;
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `dolex sources` — manage the persistent
|
|
3
|
-
* `~/.dolex/sources.json` (shared with the MCP server's `
|
|
2
|
+
* `dolex sources` — manage the persistent data-source registry at
|
|
3
|
+
* `~/.dolex/sources.json` (CSV / Postgres / MongoDB; shared with the MCP server's `load_source`).
|
|
4
4
|
*/
|
|
5
5
|
import { resolve } from 'path';
|
|
6
|
-
import { parseArgs, bool } from '../args.js';
|
|
6
|
+
import { parseArgs, bool, str, num, list } from '../args.js';
|
|
7
7
|
import * as o from '../output.js';
|
|
8
8
|
import { persistentManager } from '../data-source.js';
|
|
9
|
+
import { resolveSourceConfig } from '../../connectors/source-factory.js';
|
|
9
10
|
export async function sourcesCommand(argv) {
|
|
10
|
-
const args = parseArgs(argv, {
|
|
11
|
+
const args = parseArgs(argv, {
|
|
12
|
+
booleans: ['json', 'help', 'verify'],
|
|
13
|
+
aliases: { h: 'help' },
|
|
14
|
+
});
|
|
11
15
|
if (bool(args, 'help')) {
|
|
12
16
|
printHelp();
|
|
13
17
|
return 0;
|
|
@@ -25,23 +29,118 @@ export async function sourcesCommand(argv) {
|
|
|
25
29
|
o.hint('No registered sources. Add one: dolex sources add <name> <path.csv>');
|
|
26
30
|
return 0;
|
|
27
31
|
}
|
|
28
|
-
o.out(o.table(['name', 'id', 'type', '
|
|
32
|
+
o.out(o.table(['name', 'id', 'type', 'location'], entries.map((e) => ({ name: e.name, id: e.id, type: e.type, location: describeLocation(e.config) }))));
|
|
29
33
|
return 0;
|
|
30
34
|
}
|
|
31
35
|
case 'add': {
|
|
32
36
|
const name = args._[1];
|
|
33
|
-
const
|
|
34
|
-
if (!name
|
|
37
|
+
const pathArg = args._[2];
|
|
38
|
+
if (!name) {
|
|
35
39
|
o.fail('Usage: dolex sources add <name> <path-to-csv-or-dir>');
|
|
40
|
+
o.hint('Or a database source: dolex sources add <name> --type postgres|mongodb --uri <conn-string>');
|
|
36
41
|
return 1;
|
|
37
42
|
}
|
|
38
|
-
const
|
|
43
|
+
const type = str(args, 'type');
|
|
44
|
+
// CSV path may come as a positional (backward-compatible) or --path.
|
|
45
|
+
const path = str(args, 'path') ?? pathArg;
|
|
46
|
+
let config;
|
|
47
|
+
try {
|
|
48
|
+
config = resolveSourceConfig({
|
|
49
|
+
type,
|
|
50
|
+
// Resolve CSV paths to absolute so the registry entry is cwd-independent.
|
|
51
|
+
path: path !== undefined ? resolve(path) : undefined,
|
|
52
|
+
uri: str(args, 'uri'),
|
|
53
|
+
host: str(args, 'host'),
|
|
54
|
+
port: num(args, 'port'),
|
|
55
|
+
database: str(args, 'database'),
|
|
56
|
+
user: str(args, 'user'),
|
|
57
|
+
password: str(args, 'password'),
|
|
58
|
+
passwordEnv: str(args, 'password-env'),
|
|
59
|
+
schema: str(args, 'schema'),
|
|
60
|
+
collections: list(args, 'collections'),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
o.fail(e instanceof Error ? e.message : String(e));
|
|
65
|
+
return 1;
|
|
66
|
+
}
|
|
67
|
+
if (str(args, 'password')) {
|
|
68
|
+
o.warn('--password is stored in plaintext in ~/.dolex/sources.json (locked to your user). Prefer --password-env <VAR> to keep the secret out of the file.');
|
|
69
|
+
}
|
|
70
|
+
// Config-first: register even if the DB is unreachable right now (unless --verify). liveness is
|
|
71
|
+
// reported, not required — so setup never depends on the DB being up this second.
|
|
72
|
+
const res = await manager.add(name, config, { verify: bool(args, 'verify') });
|
|
39
73
|
if (!res.ok) {
|
|
40
74
|
o.fail(res.error ?? 'Failed to add source.');
|
|
41
75
|
return 1;
|
|
42
76
|
}
|
|
43
|
-
o.success(`Added "${name}" (${res.entry.id})`);
|
|
44
|
-
|
|
77
|
+
o.success(`Added "${name}" (${res.entry.id}) [${config.type}]`);
|
|
78
|
+
if (config.type !== 'csv' && res.verified === false) {
|
|
79
|
+
o.warn(`Registered, but couldn't connect yet: ${res.warning}`);
|
|
80
|
+
o.hint(`Fix the DB/credentials, then verify: dolex sources test ${name} (or update: dolex sources update ${name} --host … )`);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
o.hint(`Use it: dolex visualize ${name} -i "…" · dolex analyze ${name}`);
|
|
84
|
+
}
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
case 'test': {
|
|
88
|
+
const idOrName = args._[1];
|
|
89
|
+
if (!idOrName) {
|
|
90
|
+
o.fail('Usage: dolex sources test <name|id>');
|
|
91
|
+
return 1;
|
|
92
|
+
}
|
|
93
|
+
const r = await manager.testSource(idOrName);
|
|
94
|
+
if (bool(args, 'json')) {
|
|
95
|
+
o.out(JSON.stringify({ source: idOrName, ...r }, null, 2));
|
|
96
|
+
return r.ok ? 0 : 1;
|
|
97
|
+
}
|
|
98
|
+
if (r.ok) {
|
|
99
|
+
o.success(`"${idOrName}" is reachable ✓`);
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
102
|
+
o.fail(`"${idOrName}" is not reachable [${r.kind}]: ${r.error}`);
|
|
103
|
+
const nextStep = {
|
|
104
|
+
'driver-missing': 'install the driver (see the message above), then retry',
|
|
105
|
+
'unreachable': 'start the database / check host+port, then: dolex sources test ' + idOrName,
|
|
106
|
+
'host-not-found': 'fix the host, then: dolex sources update ' + idOrName + ' --host <host>',
|
|
107
|
+
'timeout': 'check the network/firewall or the DB is slow to accept connections',
|
|
108
|
+
'auth-failed': 'fix credentials: dolex sources update ' + idOrName + ' --user <u> --password-env <VAR>',
|
|
109
|
+
'db-not-found': 'fix the database name: dolex sources update ' + idOrName + ' --database <db>',
|
|
110
|
+
};
|
|
111
|
+
if (r.kind && nextStep[r.kind])
|
|
112
|
+
o.hint(nextStep[r.kind]);
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
case 'update': {
|
|
116
|
+
const idOrName = args._[1];
|
|
117
|
+
if (!idOrName) {
|
|
118
|
+
o.fail('Usage: dolex sources update <name|id> [--host … --port … --database … --user … --password-env … --uri …]');
|
|
119
|
+
return 1;
|
|
120
|
+
}
|
|
121
|
+
const patch = {};
|
|
122
|
+
for (const k of ['uri', 'host', 'database', 'user', 'password', 'password-env', 'schema']) {
|
|
123
|
+
const v = str(args, k);
|
|
124
|
+
if (v !== undefined)
|
|
125
|
+
patch[k === 'uri' ? 'connectionString' : k === 'password-env' ? 'passwordEnv' : k] = v;
|
|
126
|
+
}
|
|
127
|
+
const p = num(args, 'port');
|
|
128
|
+
if (p !== undefined)
|
|
129
|
+
patch.port = p;
|
|
130
|
+
if (Object.keys(patch).length === 0) {
|
|
131
|
+
o.fail('Nothing to update. Pass at least one of --host/--port/--database/--user/--password-env/--uri/--schema.');
|
|
132
|
+
return 1;
|
|
133
|
+
}
|
|
134
|
+
if (patch.password)
|
|
135
|
+
o.warn('--password is stored in plaintext. Prefer --password-env <VAR>.');
|
|
136
|
+
const res = await manager.update(idOrName, patch, { verify: bool(args, 'verify') });
|
|
137
|
+
if (!res.ok) {
|
|
138
|
+
o.fail(res.error ?? 'Failed to update source.');
|
|
139
|
+
return 1;
|
|
140
|
+
}
|
|
141
|
+
o.success(`Updated "${idOrName}"`);
|
|
142
|
+
if (res.verified === false)
|
|
143
|
+
o.warn(`Saved, but still can't connect: ${res.warning}. Test again: dolex sources test ${idOrName}`);
|
|
45
144
|
return 0;
|
|
46
145
|
}
|
|
47
146
|
case 'remove':
|
|
@@ -65,13 +164,40 @@ export async function sourcesCommand(argv) {
|
|
|
65
164
|
return 1;
|
|
66
165
|
}
|
|
67
166
|
}
|
|
167
|
+
/** One-line summary of where a source lives, for the `list` table. */
|
|
168
|
+
/** host:port/database for a live DB source (the connection string wins if present). */
|
|
169
|
+
const hostPortDb = (connStr, host, port, database) => connStr ?? [host, port].filter(Boolean).join(':') + (database ? `/${database}` : '');
|
|
170
|
+
function describeLocation(config) {
|
|
171
|
+
switch (config.type) {
|
|
172
|
+
case 'csv':
|
|
173
|
+
return config.path ?? '';
|
|
174
|
+
case 'postgres':
|
|
175
|
+
return hostPortDb(config.connectionString, config.host, config.port, config.database);
|
|
176
|
+
case 'mongodb':
|
|
177
|
+
return hostPortDb(config.uri, config.host, config.port, config.database);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
68
180
|
function printHelp() {
|
|
69
|
-
o.out(`${o.c.bold('dolex sources')} — manage the persistent
|
|
181
|
+
o.out(`${o.c.bold('dolex sources')} — manage the persistent source registry
|
|
70
182
|
|
|
71
183
|
${o.c.bold('USAGE')}
|
|
72
184
|
dolex sources list
|
|
73
185
|
dolex sources add <name> <path-to-csv-or-dir>
|
|
186
|
+
dolex sources add <name> --type postgres --host <h> --database <db> [--user <u> --password-env PGPASSWORD]
|
|
187
|
+
dolex sources add <name> --type mongodb --host <h> --port <p> --database <db>
|
|
188
|
+
dolex sources test <name|id> # is the saved DB reachable? (classified reason)
|
|
189
|
+
dolex sources update <name|id> [--host … --port … --database … --user … --password-env … --uri …]
|
|
74
190
|
dolex sources remove <name|id>
|
|
75
191
|
|
|
76
|
-
${o.c.
|
|
192
|
+
${o.c.bold('OPTIONS (add / update)')}
|
|
193
|
+
--type csv | postgres | mongodb (default: csv)
|
|
194
|
+
--uri connection string (libpq DSN for postgres, URI for mongodb)
|
|
195
|
+
--host/--port/--database/--user/--schema discrete connection fields
|
|
196
|
+
--password-env name of an env var holding the password (preferred — keeps the secret OUT of the file)
|
|
197
|
+
--password literal password (stored in plaintext; --password-env is safer)
|
|
198
|
+
--verify require a successful connection to register (default: register config-first even if the DB is down)
|
|
199
|
+
--collections mongodb: comma-separated list to restrict introspection
|
|
200
|
+
|
|
201
|
+
${o.c.dim('Config-first: a source registers even if its DB is momentarily down — run `sources test` once it is up.')}
|
|
202
|
+
${o.c.dim('Stored in ~/.dolex/sources.json (locked to your user; passwords via --password-env are NOT written). Shared with the MCP server.')}`);
|
|
77
203
|
}
|
|
@@ -49,8 +49,12 @@ export async function transformCommand(argv) {
|
|
|
49
49
|
return 1;
|
|
50
50
|
}
|
|
51
51
|
const col = tBody.created?.[0] ?? { column: create, expr, type: 'unknown' };
|
|
52
|
+
// A live source (Postgres/Mongo) derives session-locally — there is no manifest to promote to;
|
|
53
|
+
// the derived column exists for the life of the connection, non-destructive to the base data.
|
|
54
|
+
const srcType = opened.manager.get(opened.sourceId)?.config?.type;
|
|
55
|
+
const persistable = srcType === 'csv';
|
|
52
56
|
let manifestPath;
|
|
53
|
-
if (!dryRun) {
|
|
57
|
+
if (!dryRun && persistable) {
|
|
54
58
|
const promote = handlePromoteColumns({ sourceManager: opened.manager });
|
|
55
59
|
const pRes = await promote({ sourceId: opened.sourceId, table, columns: [create] });
|
|
56
60
|
const pBody = JSON.parse(pRes.content[0].text);
|
|
@@ -63,11 +67,16 @@ export async function transformCommand(argv) {
|
|
|
63
67
|
manifestPath = resolveManifestPath(entry.config);
|
|
64
68
|
}
|
|
65
69
|
if (bool(args, 'json')) {
|
|
66
|
-
o.out(JSON.stringify({ ...tBody, persisted: !dryRun, manifest: manifestPath }, null, 2));
|
|
70
|
+
o.out(JSON.stringify({ ...tBody, persisted: !dryRun && persistable, sessionLocal: !persistable, manifest: manifestPath }, null, 2));
|
|
67
71
|
return 0;
|
|
68
72
|
}
|
|
69
73
|
o.success(`${dryRun ? 'Previewed' : 'Created'} ${o.c.bold(col.column)} ${o.c.dim('= ' + col.expr)}`);
|
|
70
|
-
|
|
74
|
+
// CSV returns a typed working column; a live source returns { layer, materialization }
|
|
75
|
+
// instead — show whichever the connector actually reported (never "type undefined").
|
|
76
|
+
if (col.type !== undefined)
|
|
77
|
+
o.kv('type', col.type);
|
|
78
|
+
else if (col.materialization)
|
|
79
|
+
o.kv('materialization', col.materialization);
|
|
71
80
|
if (col.stats && typeof col.stats === 'object') {
|
|
72
81
|
const fmt = (v) => typeof v === 'number' ? (Number.isInteger(v) ? String(v) : v.toFixed(3)) : String(v);
|
|
73
82
|
for (const [k, v] of Object.entries(col.stats))
|
|
@@ -79,11 +88,17 @@ export async function transformCommand(argv) {
|
|
|
79
88
|
if (dryRun) {
|
|
80
89
|
o.warn('Preview only — not persisted. Re-run without --dry-run to keep it.');
|
|
81
90
|
}
|
|
82
|
-
else {
|
|
91
|
+
else if (persistable) {
|
|
83
92
|
if (manifestPath)
|
|
84
93
|
o.kv('persisted', manifestPath);
|
|
85
94
|
o.hint(`Use it: dolex query ${target} "SELECT ${col.column} FROM ${table} LIMIT 5"`);
|
|
86
95
|
}
|
|
96
|
+
else {
|
|
97
|
+
// Live PG/Mongo source: the derived column lives only on this connection, which a
|
|
98
|
+
// stateless CLI closes on exit — so a separate `dolex query` cannot see it, and for
|
|
99
|
+
// Mongo a SELECT hint would be invalid anyway. Be honest instead of promising a query.
|
|
100
|
+
o.warn(`Session-local — derived on the live ${srcType} connection only. The CLI is stateless, so this column is not persisted and a separate command cannot see it. Create it inside an MCP session, or inline the expression in your query.`);
|
|
101
|
+
}
|
|
87
102
|
return 0;
|
|
88
103
|
}
|
|
89
104
|
finally {
|
package/dist/src/cli/index.js
CHANGED
|
@@ -86,6 +86,9 @@ async function main() {
|
|
|
86
86
|
case 'sources':
|
|
87
87
|
case 'source':
|
|
88
88
|
process.exit(await (await import('./commands/sources.js')).sourcesCommand(rest));
|
|
89
|
+
case 'deps':
|
|
90
|
+
case 'doctor':
|
|
91
|
+
process.exit(await (await import('./commands/deps.js')).depsCommand(rest));
|
|
89
92
|
case 'mcp':
|
|
90
93
|
case 'serve':
|
|
91
94
|
await startMcpServer();
|
|
@@ -8,10 +8,12 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import Database from 'better-sqlite3';
|
|
10
10
|
import * as fs from 'fs';
|
|
11
|
+
import * as os from 'os';
|
|
11
12
|
import * as path from 'path';
|
|
12
13
|
import Papa from 'papaparse';
|
|
13
14
|
import { resolveManifestPath, readManifest, replayManifest } from '../transforms/manifest.js';
|
|
14
15
|
import { TransformMetadata } from '../transforms/metadata.js';
|
|
16
|
+
import { applyManifest as applyCleanfix, readCleanfixManifest } from '../cleaning/replay.js';
|
|
15
17
|
const SAMPLE_LIMIT = 30;
|
|
16
18
|
const SAMPLE_DISPLAY_LIMIT = 20;
|
|
17
19
|
/**
|
|
@@ -558,6 +560,13 @@ class CsvConnectedSource {
|
|
|
558
560
|
getDatabase() {
|
|
559
561
|
return this.db;
|
|
560
562
|
}
|
|
563
|
+
/**
|
|
564
|
+
* CSV derives columns the way it always has: ALTER TABLE + rowid-keyed UPDATE on the
|
|
565
|
+
* in-memory SQLite db (getDatabase still drives the actual work). Byte-identical behavior.
|
|
566
|
+
*/
|
|
567
|
+
derivationCapabilities() {
|
|
568
|
+
return { canDerive: true, materialization: 'sqlite-alter', rowKey: 'rowid', serverSideQueryable: true };
|
|
569
|
+
}
|
|
561
570
|
async close() {
|
|
562
571
|
try {
|
|
563
572
|
this.db.close();
|
|
@@ -619,6 +628,26 @@ export const csvConnector = {
|
|
|
619
628
|
},
|
|
620
629
|
];
|
|
621
630
|
}
|
|
631
|
+
// If a `<base>.cleanfix.json` sits next to a CSV, load the manifest-cleaned columns
|
|
632
|
+
// instead of the raw ones — so recon/query never re-hit a footgun the offline autoclean
|
|
633
|
+
// already solved. Replaying over the CURRENT raw file gives newly-arrived rows the same
|
|
634
|
+
// treatment; the original CSV is never written. Best-effort: any error → raw load.
|
|
635
|
+
csvPaths = csvPaths.map((cp) => {
|
|
636
|
+
const manifest = readCleanfixManifest(cp.filePath);
|
|
637
|
+
if (!manifest)
|
|
638
|
+
return cp;
|
|
639
|
+
try {
|
|
640
|
+
const { rows } = applyCleanfix(cp.filePath, manifest, false); // cleaned columns, no _raw noise
|
|
641
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dolex-cleanfix-'));
|
|
642
|
+
const cleanedPath = path.join(dir, path.basename(cp.filePath));
|
|
643
|
+
fs.writeFileSync(cleanedPath, Papa.unparse(rows));
|
|
644
|
+
return { ...cp, filePath: cleanedPath }; // tableName stays derived from the original file
|
|
645
|
+
}
|
|
646
|
+
catch (err) {
|
|
647
|
+
console.warn(`[csv-connector] cleanfix replay failed for ${cp.filePath}, loading raw: ${err?.message}`);
|
|
648
|
+
return cp;
|
|
649
|
+
}
|
|
650
|
+
});
|
|
622
651
|
const { db, tables, foreignKeys, warnings } = loadCsvs(csvPaths);
|
|
623
652
|
if (warnings.length > 0) {
|
|
624
653
|
for (const w of warnings) {
|
|
@@ -5,4 +5,6 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export type { DataConnector, ConnectedSource, QueryExecutionResult, ConnectorResult, SourceRegistryEntry, } from './types.js';
|
|
7
7
|
export { csvConnector } from './csv.js';
|
|
8
|
+
export { pgConnector } from './pg/index.js';
|
|
9
|
+
export { mongoConnector } from './mongo/index.js';
|
|
8
10
|
export { SourceManager } from './manager.js';
|
|
@@ -5,5 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
// ─── Connectors ─────────────────────────────────────────────────────────────
|
|
7
7
|
export { csvConnector } from './csv.js';
|
|
8
|
+
export { pgConnector } from './pg/index.js';
|
|
9
|
+
export { mongoConnector } from './mongo/index.js';
|
|
8
10
|
// ─── Manager ────────────────────────────────────────────────────────────────
|
|
9
11
|
export { SourceManager } from './manager.js';
|
|
@@ -22,6 +22,9 @@ export interface SqlQueryResult {
|
|
|
22
22
|
* re-issue a corrected query. The engine never rewrites the SQL itself. */
|
|
23
23
|
warnings?: string[];
|
|
24
24
|
}
|
|
25
|
+
/** Classify a connection failure into an actionable kind, so callers can give a specific next step
|
|
26
|
+
* (install the driver / start the DB / fix credentials) instead of relaying a raw driver string. */
|
|
27
|
+
export declare function classifyConnError(msg?: string): 'driver-missing' | 'unreachable' | 'host-not-found' | 'timeout' | 'auth-failed' | 'db-not-found' | 'error';
|
|
25
28
|
export declare class SourceManager {
|
|
26
29
|
private registry;
|
|
27
30
|
private connections;
|
|
@@ -38,10 +41,38 @@ export declare class SourceManager {
|
|
|
38
41
|
* Add a data source to the registry.
|
|
39
42
|
* Does NOT connect immediately — connection is lazy on first query or explicit connect().
|
|
40
43
|
*/
|
|
41
|
-
add(name: string, config: DataSourceConfig
|
|
44
|
+
add(name: string, config: DataSourceConfig, opts?: {
|
|
45
|
+
verify?: boolean;
|
|
46
|
+
}): Promise<{
|
|
42
47
|
ok: boolean;
|
|
43
48
|
entry?: SourceRegistryEntry;
|
|
44
49
|
error?: string;
|
|
50
|
+
verified?: boolean;
|
|
51
|
+
warning?: string;
|
|
52
|
+
}>;
|
|
53
|
+
/**
|
|
54
|
+
* Update a registered source's config in place (DB moved, password rotated, driver now installed)
|
|
55
|
+
* WITHOUT losing its id — so every existing reference keeps working. `patch` is merged over the
|
|
56
|
+
* stored config; the type is immutable. Any live connection is closed so the next use reconnects.
|
|
57
|
+
*/
|
|
58
|
+
update(idOrName: string, patch: Partial<DataSourceConfig>, opts?: {
|
|
59
|
+
verify?: boolean;
|
|
60
|
+
}): Promise<{
|
|
61
|
+
ok: boolean;
|
|
62
|
+
entry?: SourceRegistryEntry;
|
|
63
|
+
error?: string;
|
|
64
|
+
verified?: boolean;
|
|
65
|
+
warning?: string;
|
|
66
|
+
}>;
|
|
67
|
+
/**
|
|
68
|
+
* Connectivity health-check for a REGISTERED source (the return-user's "is my saved DB still
|
|
69
|
+
* reachable?" and an agent's pre-flight). Returns a classified failure so the caller can give an
|
|
70
|
+
* actionable next step rather than a raw driver string.
|
|
71
|
+
*/
|
|
72
|
+
testSource(idOrName: string): Promise<{
|
|
73
|
+
ok: boolean;
|
|
74
|
+
error?: string;
|
|
75
|
+
kind?: string;
|
|
45
76
|
}>;
|
|
46
77
|
/**
|
|
47
78
|
* Remove a data source by ID or name. Closes the connection if active.
|
|
@@ -82,6 +113,13 @@ export declare class SourceManager {
|
|
|
82
113
|
* Error messages are enriched with available table/column names.
|
|
83
114
|
*/
|
|
84
115
|
querySql(idOrName: string, sql: string, maxRows?: number): Promise<SqlQueryResult>;
|
|
116
|
+
/**
|
|
117
|
+
* Run a read-only aggregation pipeline against a document store and return rows + columns,
|
|
118
|
+
* capped to maxRows. The pipeline string is the {collection, pipeline} seam the connector
|
|
119
|
+
* parses. No SQL safety pass (those footguns are SQL-only); Mongo-specific footgun
|
|
120
|
+
* detection is the language-plane work, added later. Never throws (audit-on-load relies on it).
|
|
121
|
+
*/
|
|
122
|
+
private queryPipeline;
|
|
85
123
|
/**
|
|
86
124
|
* Advisory SQL-safety pass over a successful query. Best-effort: any failure
|
|
87
125
|
* yields no warnings (never blocks or breaks the query). Gated on a cheap
|