@outsidedata/dolex 8.0.2 → 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 +33 -7
- package/dist/src/analysis/clean-exec.d.ts +23 -0
- package/dist/src/analysis/clean-exec.js +87 -0
- package/dist/src/analysis/data-context.d.ts +140 -0
- package/dist/src/analysis/data-context.js +96 -0
- package/dist/src/analysis/planner.d.ts +2 -1
- package/dist/src/analysis/planner.js +2 -2
- package/dist/src/analysis/quality.d.ts +23 -0
- package/dist/src/analysis/quality.js +386 -11
- package/dist/src/analysis/rules.d.ts +22 -2
- package/dist/src/analysis/rules.js +100 -18
- package/dist/src/cleaning/author.d.ts +30 -0
- package/dist/src/cleaning/author.js +7 -0
- package/dist/src/cleaning/exec.d.ts +29 -0
- package/dist/src/cleaning/exec.js +161 -0
- package/dist/src/cleaning/handlers.d.ts +16 -0
- package/dist/src/cleaning/handlers.js +82 -0
- package/dist/src/cleaning/index.d.ts +4 -0
- package/dist/src/cleaning/index.js +9 -0
- package/dist/src/cleaning/manifest.d.ts +35 -0
- package/dist/src/cleaning/manifest.js +95 -0
- 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/check.js +2 -89
- package/dist/src/cli/commands/clean.d.ts +1 -0
- package/dist/src/cli/commands/clean.js +127 -0
- 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 +3 -1
- package/dist/src/cli/commands/query.js +4 -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/commands/visualize.js +2 -0
- package/dist/src/cli/index.js +5 -0
- package/dist/src/connectors/csv.js +110 -8
- package/dist/src/connectors/index.d.ts +2 -0
- package/dist/src/connectors/index.js +2 -0
- package/dist/src/connectors/manager.d.ts +49 -1
- package/dist/src/connectors/manager.js +200 -14
- 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.d.ts +68 -0
- package/dist/src/connectors/sql-safety.js +167 -0
- 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 +29 -10
- 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.d.ts +5 -0
- package/dist/src/mcp/tools/clean-column.js +47 -0
- package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
- package/dist/src/mcp/tools/clean-schemas.js +9 -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/query-source.d.ts +2 -2
- package/dist/src/mcp/tools/query-source.js +2 -1
- 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 +6 -0
- package/dist/src/mcp/tools/shared.js +12 -5
- 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/mcp/tools/visualize-cli.d.ts +2 -2
- package/dist/src/mcp/tools/visualize.d.ts +3 -2
- package/dist/src/mcp/tools/visualize.js +1 -0
- package/dist/src/transforms/evaluator.js +58 -3
- package/dist/src/transforms/tokenizer.js +20 -2
- package/dist/src/transforms/types.d.ts +6 -6
- package/dist/src/types.d.ts +39 -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 +9 -3
|
@@ -0,0 +1,248 @@
|
|
|
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
|
+
function poolFor(PoolCtor, cfg) {
|
|
8
|
+
if (cfg.connectionString)
|
|
9
|
+
return new PoolCtor({ connectionString: cfg.connectionString, max: 4 });
|
|
10
|
+
// The secret is either the literal password or (preferred) read from an env var at connect time,
|
|
11
|
+
// so it need never be persisted in the registry file.
|
|
12
|
+
const password = cfg.password ?? (cfg.passwordEnv ? process.env[cfg.passwordEnv] : undefined);
|
|
13
|
+
return new PoolCtor({
|
|
14
|
+
host: cfg.host, port: cfg.port, database: cfg.database, user: cfg.user, password, max: 4,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
// Postgres type OIDs that should surface as JS numbers: int2/int4/int8, float4/float8, numeric.
|
|
18
|
+
const PG_NUMERIC_OIDS = new Set([20, 21, 23, 700, 701, 1700]);
|
|
19
|
+
const NUMERIC_TYPES = new Set(['numeric', 'integer', 'bigint', 'double precision', 'real', 'smallint', 'decimal']);
|
|
20
|
+
const DATE_TYPES = new Set(['date', 'timestamp without time zone', 'timestamp with time zone', 'time without time zone']);
|
|
21
|
+
function classify(dataType, name, distinct, total) {
|
|
22
|
+
if (NUMERIC_TYPES.has(dataType)) {
|
|
23
|
+
if (/(^|_)id$/i.test(name) && total > 0 && distinct >= total * 0.9)
|
|
24
|
+
return 'id';
|
|
25
|
+
return 'numeric';
|
|
26
|
+
}
|
|
27
|
+
if (DATE_TYPES.has(dataType))
|
|
28
|
+
return 'date';
|
|
29
|
+
// text-ish
|
|
30
|
+
if (total > 0 && distinct <= Math.min(1000, Math.max(50, total * 0.5)) && distinct <= 200)
|
|
31
|
+
return 'categorical';
|
|
32
|
+
return 'text';
|
|
33
|
+
}
|
|
34
|
+
async function profileTable(pool, schema, table) {
|
|
35
|
+
// column list + pg data types
|
|
36
|
+
const colRes = await pool.query(`SELECT column_name, data_type FROM information_schema.columns
|
|
37
|
+
WHERE table_schema=$1 AND table_name=$2 ORDER BY ordinal_position`, [schema, table]);
|
|
38
|
+
const cols = colRes.rows.map((r) => ({ name: r.column_name, dataType: r.data_type }));
|
|
39
|
+
// one scan: COUNT(*) + per-column distinct + non-null counts
|
|
40
|
+
const countSel = ['COUNT(*)::bigint AS __total'];
|
|
41
|
+
for (const c of cols) {
|
|
42
|
+
countSel.push(`COUNT(DISTINCT ${q(c.name)})::bigint AS ${q('d_' + c.name)}`);
|
|
43
|
+
countSel.push(`COUNT(${q(c.name)})::bigint AS ${q('n_' + c.name)}`);
|
|
44
|
+
}
|
|
45
|
+
const counts = (await pool.query(`SELECT ${countSel.join(', ')} FROM ${q(schema)}.${q(table)}`)).rows[0];
|
|
46
|
+
const total = Number(counts.__total);
|
|
47
|
+
const columns = [];
|
|
48
|
+
for (const c of cols) {
|
|
49
|
+
const distinct = Number(counts['d_' + c.name]);
|
|
50
|
+
const nonNull = Number(counts['n_' + c.name]);
|
|
51
|
+
const type = classify(c.dataType, c.name, distinct, total);
|
|
52
|
+
// sample values (distinct, for display)
|
|
53
|
+
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`);
|
|
54
|
+
const sampleValues = sv.rows.map((r) => String(r.v)).slice(0, 5);
|
|
55
|
+
let stats;
|
|
56
|
+
let topValues;
|
|
57
|
+
if (type === 'numeric' && nonNull > 0) {
|
|
58
|
+
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,
|
|
59
|
+
COALESCE(STDDEV_POP(${q(c.name)}),0)::float8 AS stddev,
|
|
60
|
+
percentile_cont(0.5) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS median,
|
|
61
|
+
percentile_cont(0.25) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p25,
|
|
62
|
+
percentile_cont(0.75) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p75
|
|
63
|
+
FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL`)).rows[0];
|
|
64
|
+
stats = { min: s.min, max: s.max, mean: s.mean, median: s.median, stddev: s.stddev, p25: s.p25, p75: s.p75 };
|
|
65
|
+
}
|
|
66
|
+
else if (type === 'categorical' || type === 'date') {
|
|
67
|
+
const tv = await pool.query(`SELECT ${q(c.name)}::text AS value, COUNT(*)::int AS count FROM ${q(schema)}.${q(table)}
|
|
68
|
+
WHERE ${q(c.name)} IS NOT NULL GROUP BY ${q(c.name)} ORDER BY COUNT(*) DESC LIMIT 10`);
|
|
69
|
+
topValues = tv.rows.map((r) => ({ value: String(r.value), count: r.count }));
|
|
70
|
+
}
|
|
71
|
+
columns.push({
|
|
72
|
+
name: c.name, type, sampleValues,
|
|
73
|
+
uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
|
|
74
|
+
layer: 'source', stats, topValues,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
return { name: table, columns, rowCount: total };
|
|
78
|
+
}
|
|
79
|
+
async function readForeignKeys(pool, schema) {
|
|
80
|
+
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
|
|
81
|
+
FROM information_schema.table_constraints tc
|
|
82
|
+
JOIN information_schema.key_column_usage kcu ON tc.constraint_name=kcu.constraint_name AND tc.table_schema=kcu.table_schema
|
|
83
|
+
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name=tc.constraint_name AND ccu.table_schema=tc.table_schema
|
|
84
|
+
WHERE tc.constraint_type='FOREIGN KEY' AND tc.table_schema=$1
|
|
85
|
+
ORDER BY ft, fc`, [schema]);
|
|
86
|
+
return res.rows.map((r) => ({ fromTable: r.ft, fromColumn: r.fc, toTable: r.tt, toColumn: r.tcol }));
|
|
87
|
+
}
|
|
88
|
+
class PgConnectedSource {
|
|
89
|
+
id;
|
|
90
|
+
name;
|
|
91
|
+
pool;
|
|
92
|
+
schemaName;
|
|
93
|
+
schema;
|
|
94
|
+
type = 'postgres';
|
|
95
|
+
/** Once a derivation exists, ALL queries ride this ONE pinned client so pg_temp (the shadow
|
|
96
|
+
* view + temp table) is visible — a pooled connection would not see them (exp 043). */
|
|
97
|
+
pinned = null;
|
|
98
|
+
/** table → derived columns materialized this session, in creation order. */
|
|
99
|
+
derived = new Map();
|
|
100
|
+
constructor(id, name, pool, schemaName, schema) {
|
|
101
|
+
this.id = id;
|
|
102
|
+
this.name = name;
|
|
103
|
+
this.pool = pool;
|
|
104
|
+
this.schemaName = schemaName;
|
|
105
|
+
this.schema = schema;
|
|
106
|
+
}
|
|
107
|
+
async getSchema() {
|
|
108
|
+
return this.schema;
|
|
109
|
+
}
|
|
110
|
+
/** The query runner: the pinned client once a derivation is active, else the pool. */
|
|
111
|
+
runner() {
|
|
112
|
+
return this.pinned ?? this.pool;
|
|
113
|
+
}
|
|
114
|
+
async executeQuery(sql) {
|
|
115
|
+
try {
|
|
116
|
+
const r = await this.runner().query(sql);
|
|
117
|
+
// Coerce by the RESULT column's actual Postgres type (OID), not by source-column
|
|
118
|
+
// name — so aliased aggregates (AVG/SUM AS x) and computed columns are typed
|
|
119
|
+
// correctly. node-postgres returns numeric/bigint as strings; we surface them as JS
|
|
120
|
+
// numbers for consumer parity with the CSV path (charts/aggregation downstream).
|
|
121
|
+
// Math already happened in SQL (policy B, exp 038); this final cast is display-side and
|
|
122
|
+
// carries the same float64 ceiling the CSV connector has.
|
|
123
|
+
const columns = r.fields.map((f) => f.name);
|
|
124
|
+
const numericField = new Set(r.fields.filter((f) => PG_NUMERIC_OIDS.has(f.dataTypeID)).map((f) => f.name));
|
|
125
|
+
const rows = r.rows.map((row) => {
|
|
126
|
+
const out = {};
|
|
127
|
+
for (const col of columns) {
|
|
128
|
+
const v = row[col];
|
|
129
|
+
if (numericField.has(col) && typeof v === 'string' && v !== '' && !isNaN(Number(v)))
|
|
130
|
+
out[col] = Number(v);
|
|
131
|
+
else
|
|
132
|
+
out[col] = v;
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
});
|
|
136
|
+
return { columns, rows };
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
return { columns: [], rows: [{ error: err.message }] };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async getSampleRows(tableName, count = 5) {
|
|
143
|
+
const total = this.schema.tables.find((t) => t.name === tableName)?.rowCount ?? 0;
|
|
144
|
+
if (total === 0)
|
|
145
|
+
return [];
|
|
146
|
+
if (total <= count) {
|
|
147
|
+
return (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)}`)).rows;
|
|
148
|
+
}
|
|
149
|
+
// block-level server-side sample; fall back to a bounded scan if it under-fills
|
|
150
|
+
const pct = Math.min(100, Math.max(1, Math.ceil((count / total) * 100 * 20)));
|
|
151
|
+
let rows = (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)} TABLESAMPLE SYSTEM(${pct}) LIMIT ${count}`)).rows;
|
|
152
|
+
if (rows.length < count) {
|
|
153
|
+
rows = (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)} LIMIT ${count}`)).rows;
|
|
154
|
+
}
|
|
155
|
+
return rows;
|
|
156
|
+
}
|
|
157
|
+
// getDatabase intentionally omitted → the derivation seam no longer keys on a raw db handle.
|
|
158
|
+
/**
|
|
159
|
+
* Postgres derives via a session-local TEMP TABLE keyed by `id`, exposed to arbitrary later
|
|
160
|
+
* queries through a same-named TEMP VIEW on ONE pinned client. Declared here; the materialization
|
|
161
|
+
* itself is wired in a subsequent stage.
|
|
162
|
+
*/
|
|
163
|
+
derivationCapabilities() {
|
|
164
|
+
return { canDerive: true, materialization: 'session-temp', rowKey: 'id', serverSideQueryable: true };
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Materialize a derived column as a session-local shadow TEMP VIEW on the pinned client.
|
|
168
|
+
* `expr` is a Postgres SQL expression over the table's columns. pg_temp precedes the schema in
|
|
169
|
+
* search_path, so a later unqualified `FROM <table>` transparently reads the view. The base
|
|
170
|
+
* table (schema-qualified inside the view) is never written. Multiple derivations accumulate.
|
|
171
|
+
*/
|
|
172
|
+
async applyDerivation(table, column, expr) {
|
|
173
|
+
if (/;|--|\/\*/.test(expr))
|
|
174
|
+
throw new Error('derivation expr must be a single SQL expression (no ";" or comments)');
|
|
175
|
+
if (!this.pinned)
|
|
176
|
+
this.pinned = await this.pool.connect();
|
|
177
|
+
const c = this.pinned;
|
|
178
|
+
const cols = this.derived.get(table) ?? [];
|
|
179
|
+
const existing = cols.find((d) => d.column === column);
|
|
180
|
+
if (existing)
|
|
181
|
+
existing.expr = expr;
|
|
182
|
+
else
|
|
183
|
+
cols.push({ column, expr });
|
|
184
|
+
this.derived.set(table, cols);
|
|
185
|
+
const projected = cols.map((d) => `(${d.expr}) AS ${q(d.column)}`).join(', ');
|
|
186
|
+
await c.query(`DROP VIEW IF EXISTS pg_temp.${q(table)}`);
|
|
187
|
+
await c.query(`CREATE TEMP VIEW ${q(table)} AS SELECT b.*, ${projected} FROM ${q(this.schemaName)}.${q(table)} b`);
|
|
188
|
+
registerDerivedColumn(this.schema, table, column);
|
|
189
|
+
}
|
|
190
|
+
async close() {
|
|
191
|
+
try {
|
|
192
|
+
if (this.pinned) {
|
|
193
|
+
this.pinned.release();
|
|
194
|
+
this.pinned = null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch { /* noop */ }
|
|
198
|
+
try {
|
|
199
|
+
await this.pool.end();
|
|
200
|
+
}
|
|
201
|
+
catch { /* already closed */ }
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
export const pgConnector = {
|
|
205
|
+
type: 'postgres',
|
|
206
|
+
async test(config) {
|
|
207
|
+
const cfg = config;
|
|
208
|
+
if (cfg.type !== 'postgres')
|
|
209
|
+
return { ok: false, error: 'Config type must be "postgres"' };
|
|
210
|
+
const { Pool } = await loadPg();
|
|
211
|
+
const pool = poolFor(Pool, cfg);
|
|
212
|
+
try {
|
|
213
|
+
await pool.query('SELECT 1');
|
|
214
|
+
return { ok: true };
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
// A connection refusal often arrives as an AggregateError with an empty top-level message;
|
|
218
|
+
// fall back to the code / nested reason so the caller (and the AI agent) gets something actionable.
|
|
219
|
+
const reason = err?.message || err?.code || err?.errors?.map((e) => e?.message || e?.code).filter(Boolean).join('; ') || String(err);
|
|
220
|
+
return { ok: false, error: `Cannot connect to Postgres: ${reason}` };
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
await pool.end();
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
async connect(config) {
|
|
227
|
+
const cfg = config;
|
|
228
|
+
if (cfg.type !== 'postgres')
|
|
229
|
+
throw new Error('Config type must be "postgres"');
|
|
230
|
+
const schema = cfg.schema || 'public';
|
|
231
|
+
const { Pool } = await loadPg();
|
|
232
|
+
const pool = poolFor(Pool, cfg);
|
|
233
|
+
const tableRes = await pool.query(`SELECT table_name FROM information_schema.tables
|
|
234
|
+
WHERE table_schema=$1 AND table_type='BASE TABLE' ORDER BY table_name`, [schema]);
|
|
235
|
+
const tables = [];
|
|
236
|
+
for (const row of tableRes.rows) {
|
|
237
|
+
tables.push(await profileTable(pool, schema, row.table_name));
|
|
238
|
+
}
|
|
239
|
+
const foreignKeys = await readForeignKeys(pool, schema);
|
|
240
|
+
const dataSchema = {
|
|
241
|
+
tables, foreignKeys,
|
|
242
|
+
source: { id: '', type: 'postgres', name: cfg.database || 'postgres', config },
|
|
243
|
+
};
|
|
244
|
+
const id = `pg-${cfg.database || 'db'}`;
|
|
245
|
+
dataSchema.source.id = id;
|
|
246
|
+
return new PgConnectedSource(id, cfg.database || 'postgres', pool, schema, dataSchema);
|
|
247
|
+
},
|
|
248
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source factory — turn generic frontend arguments (a `--type`, a connection
|
|
3
|
+
* string, or discrete host/port/database fields) into a typed
|
|
4
|
+
* `DataSourceConfig` the `SourceManager` can register and connect.
|
|
5
|
+
*
|
|
6
|
+
* Model-free and dependency-free: it only shapes/validates a config object; it
|
|
7
|
+
* never opens a connection (the connector's `test()`/`connect()` does that).
|
|
8
|
+
* Shared by the CLI `sources add` command; the MCP loader can adopt it later.
|
|
9
|
+
*
|
|
10
|
+
* Backward compatibility: an omitted `--type` with a bare path resolves to CSV,
|
|
11
|
+
* so `dolex sources add <name> <path>` keeps working unchanged.
|
|
12
|
+
*/
|
|
13
|
+
import type { DataSourceConfig } from '../types.js';
|
|
14
|
+
/** Generic, frontend-agnostic inputs a factory resolves into a typed config. */
|
|
15
|
+
export interface SourceFactoryArgs {
|
|
16
|
+
/** csv | postgres | mongodb. Omitted ⇒ defaults to 'csv'. */
|
|
17
|
+
type?: string;
|
|
18
|
+
/** CSV: path to a `.csv` file or a directory of CSVs. */
|
|
19
|
+
path?: string;
|
|
20
|
+
/** Connection string: libpq DSN (postgres) or Mongo URI (mongodb). */
|
|
21
|
+
uri?: string;
|
|
22
|
+
host?: string;
|
|
23
|
+
port?: number;
|
|
24
|
+
database?: string;
|
|
25
|
+
user?: string;
|
|
26
|
+
password?: string;
|
|
27
|
+
/** Name of an env var holding the Postgres password (kept out of the registry file). */
|
|
28
|
+
passwordEnv?: string;
|
|
29
|
+
/** Postgres schema to introspect (default: public). */
|
|
30
|
+
schema?: string;
|
|
31
|
+
/** Mongo: restrict introspection to these collections. */
|
|
32
|
+
collections?: string[];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Resolve generic args into a typed `DataSourceConfig`. Throws an `Error` with
|
|
36
|
+
* an actionable message when required fields are missing or the type is unknown.
|
|
37
|
+
*/
|
|
38
|
+
export declare function resolveSourceConfig(args: SourceFactoryArgs): DataSourceConfig;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source factory — turn generic frontend arguments (a `--type`, a connection
|
|
3
|
+
* string, or discrete host/port/database fields) into a typed
|
|
4
|
+
* `DataSourceConfig` the `SourceManager` can register and connect.
|
|
5
|
+
*
|
|
6
|
+
* Model-free and dependency-free: it only shapes/validates a config object; it
|
|
7
|
+
* never opens a connection (the connector's `test()`/`connect()` does that).
|
|
8
|
+
* Shared by the CLI `sources add` command; the MCP loader can adopt it later.
|
|
9
|
+
*
|
|
10
|
+
* Backward compatibility: an omitted `--type` with a bare path resolves to CSV,
|
|
11
|
+
* so `dolex sources add <name> <path>` keeps working unchanged.
|
|
12
|
+
*/
|
|
13
|
+
const SUPPORTED_TYPES = ['csv', 'postgres', 'mongodb'];
|
|
14
|
+
/**
|
|
15
|
+
* Resolve generic args into a typed `DataSourceConfig`. Throws an `Error` with
|
|
16
|
+
* an actionable message when required fields are missing or the type is unknown.
|
|
17
|
+
*/
|
|
18
|
+
export function resolveSourceConfig(args) {
|
|
19
|
+
const rawType = args.type?.trim().toLowerCase();
|
|
20
|
+
const type = (rawType || 'csv');
|
|
21
|
+
if (!SUPPORTED_TYPES.includes(type)) {
|
|
22
|
+
throw new Error(`Unsupported source type "${args.type}". Use one of: ${SUPPORTED_TYPES.join(', ')}.`);
|
|
23
|
+
}
|
|
24
|
+
switch (type) {
|
|
25
|
+
case 'csv':
|
|
26
|
+
return resolveCsv(args);
|
|
27
|
+
case 'postgres':
|
|
28
|
+
return resolvePostgres(args);
|
|
29
|
+
case 'mongodb':
|
|
30
|
+
return resolveMongo(args);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function resolveCsv(args) {
|
|
34
|
+
if (!args.path) {
|
|
35
|
+
throw new Error('CSV source requires a path to a .csv file or a directory of CSVs.');
|
|
36
|
+
}
|
|
37
|
+
return { type: 'csv', path: args.path };
|
|
38
|
+
}
|
|
39
|
+
function resolvePostgres(args) {
|
|
40
|
+
const hasDiscrete = Boolean(args.host || args.database || args.user);
|
|
41
|
+
if (!args.uri && !hasDiscrete) {
|
|
42
|
+
throw new Error('Postgres source requires --uri <connection-string>, or discrete --host/--database (plus optional --port/--user/--password/--schema).');
|
|
43
|
+
}
|
|
44
|
+
const config = { type: 'postgres' };
|
|
45
|
+
if (args.uri)
|
|
46
|
+
config.connectionString = args.uri;
|
|
47
|
+
if (args.host)
|
|
48
|
+
config.host = args.host;
|
|
49
|
+
if (args.port !== undefined)
|
|
50
|
+
config.port = args.port;
|
|
51
|
+
if (args.database)
|
|
52
|
+
config.database = args.database;
|
|
53
|
+
if (args.user)
|
|
54
|
+
config.user = args.user;
|
|
55
|
+
if (args.password)
|
|
56
|
+
config.password = args.password;
|
|
57
|
+
if (args.passwordEnv)
|
|
58
|
+
config.passwordEnv = args.passwordEnv;
|
|
59
|
+
if (args.schema)
|
|
60
|
+
config.schema = args.schema;
|
|
61
|
+
return config;
|
|
62
|
+
}
|
|
63
|
+
function resolveMongo(args) {
|
|
64
|
+
if (!args.database) {
|
|
65
|
+
throw new Error('Mongo source requires --database (a Mongo connection has no single default db).');
|
|
66
|
+
}
|
|
67
|
+
if (!args.uri && !args.host) {
|
|
68
|
+
throw new Error('Mongo source requires --uri <connection-string> or --host (plus optional --port).');
|
|
69
|
+
}
|
|
70
|
+
const config = { type: 'mongodb', database: args.database };
|
|
71
|
+
if (args.uri)
|
|
72
|
+
config.uri = args.uri;
|
|
73
|
+
if (args.host)
|
|
74
|
+
config.host = args.host;
|
|
75
|
+
if (args.port !== undefined)
|
|
76
|
+
config.port = args.port;
|
|
77
|
+
if (args.collections && args.collections.length > 0)
|
|
78
|
+
config.collections = args.collections;
|
|
79
|
+
return config;
|
|
80
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL safety pass — advisory footgun detection for model/human-authored SELECTs.
|
|
3
|
+
*
|
|
4
|
+
* The engine NEVER rewrites the caller's SQL (that would be "hidden SQL" — the
|
|
5
|
+
* analyst must stay in control). Instead it DETECTS silent-wrong-answer traps and
|
|
6
|
+
* SIGNALS them back as warnings, so the caller re-issues a corrected query. This
|
|
7
|
+
* mirrors the evaluator-gate principle at the query layer.
|
|
8
|
+
*
|
|
9
|
+
* Design validated head-to-head in
|
|
10
|
+
* `local-orchestration/experiments/017-sql-integer-division.ts`: an auto-rewrite
|
|
11
|
+
* variant corrupted `/` inside string literals and comments; a type-blind detector
|
|
12
|
+
* cried wolf on legitimate real-typed division. The promoted approach is
|
|
13
|
+
* term-aware + TYPE-aware detection with no mutation.
|
|
14
|
+
*
|
|
15
|
+
* Currently detects: integer-division truncation (`int / int` → SQLite floors to 0).
|
|
16
|
+
* Add further checks (div-by-zero, bare GROUP BY, COUNT DISTINCT nulls, anti-join
|
|
17
|
+
* NULL trap) here as new functions invoked by detectSqlFootguns.
|
|
18
|
+
*/
|
|
19
|
+
export interface SqlSafetyWarning {
|
|
20
|
+
code: 'integer-division' | 'division-by-zero' | 'bare-aggregate';
|
|
21
|
+
message: string;
|
|
22
|
+
}
|
|
23
|
+
/** Resolve a base column's SQLite storage type ('integer' | 'real' | ...), or
|
|
24
|
+
* undefined when the operand is not a resolvable base column (alias/expr). */
|
|
25
|
+
export type ColumnTypeResolver = (column: string) => Promise<string | undefined>;
|
|
26
|
+
/** Multiplicative terms containing a `/` that are NOT already float-safe (no float
|
|
27
|
+
* literal, no CAST-to-real), with their candidate column identifiers. Pure syntax
|
|
28
|
+
* — cheap enough to use as a pre-filter before any type probing. */
|
|
29
|
+
export declare function riskyDivisionTerms(sql: string): {
|
|
30
|
+
term: string;
|
|
31
|
+
columns: string[];
|
|
32
|
+
}[];
|
|
33
|
+
/** Division denominators (the operand right of each `/`) with their candidate
|
|
34
|
+
* column identifiers. A `NULLIF(...)`-wrapped denominator is already guarded and
|
|
35
|
+
* skipped. Applies to ALL division (float `x/0` also yields NULL in SQLite), so
|
|
36
|
+
* it is independent of the integer-truncation check above. */
|
|
37
|
+
export declare function divisionDenominators(sql: string): {
|
|
38
|
+
denom: string;
|
|
39
|
+
columns: string[];
|
|
40
|
+
}[];
|
|
41
|
+
/**
|
|
42
|
+
* Detect division whose denominator column actually CONTAINS a zero — `x / 0`
|
|
43
|
+
* silently yields NULL in SQLite (no error), which then vanishes from downstream
|
|
44
|
+
* aggregates. Data-gated on purpose: it warns ONLY when a real zero is present, so
|
|
45
|
+
* it never cries wolf on a zero-free denominator (no overbearing blanket warning).
|
|
46
|
+
*/
|
|
47
|
+
export declare function detectDivByZero(sql: string, columnHasZero: (column: string) => Promise<boolean>): Promise<SqlSafetyWarning[]>;
|
|
48
|
+
/**
|
|
49
|
+
* Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
|
|
50
|
+
* aggregate with NO GROUP BY — e.g. `SELECT name, SUM(score) FROM t`. SQLite does
|
|
51
|
+
* not error; it pairs an ARBITRARY row's `name` with a whole-table aggregate (a
|
|
52
|
+
* meaningless pairing the caller rarely intends).
|
|
53
|
+
*
|
|
54
|
+
* Deliberately CONSERVATIVE — built to avoid false positives:
|
|
55
|
+
* - skips anything with a GROUP BY (verifying GROUP BY membership syntactically is
|
|
56
|
+
* too false-positive-prone);
|
|
57
|
+
* - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
|
|
58
|
+
* columns then take values from the extremal row, so that is actually correct;
|
|
59
|
+
* - only flags identifiers that are real base columns.
|
|
60
|
+
*/
|
|
61
|
+
export declare function detectBareAggregate(sql: string, isBaseColumn: (col: string) => boolean): SqlSafetyWarning[];
|
|
62
|
+
/**
|
|
63
|
+
* Detect silent-wrong-answer footguns in a SELECT. Type-aware: a division term is
|
|
64
|
+
* flagged only when EVERY resolvable operand column is integer-typed (a single
|
|
65
|
+
* real operand means SQLite promotes to real → no truncation). Unknown operands
|
|
66
|
+
* are treated conservatively as non-integer (no flag) to avoid crying wolf.
|
|
67
|
+
*/
|
|
68
|
+
export declare function detectSqlFootguns(sql: string, columnType: ColumnTypeResolver): Promise<SqlSafetyWarning[]>;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL safety pass — advisory footgun detection for model/human-authored SELECTs.
|
|
3
|
+
*
|
|
4
|
+
* The engine NEVER rewrites the caller's SQL (that would be "hidden SQL" — the
|
|
5
|
+
* analyst must stay in control). Instead it DETECTS silent-wrong-answer traps and
|
|
6
|
+
* SIGNALS them back as warnings, so the caller re-issues a corrected query. This
|
|
7
|
+
* mirrors the evaluator-gate principle at the query layer.
|
|
8
|
+
*
|
|
9
|
+
* Design validated head-to-head in
|
|
10
|
+
* `local-orchestration/experiments/017-sql-integer-division.ts`: an auto-rewrite
|
|
11
|
+
* variant corrupted `/` inside string literals and comments; a type-blind detector
|
|
12
|
+
* cried wolf on legitimate real-typed division. The promoted approach is
|
|
13
|
+
* term-aware + TYPE-aware detection with no mutation.
|
|
14
|
+
*
|
|
15
|
+
* Currently detects: integer-division truncation (`int / int` → SQLite floors to 0).
|
|
16
|
+
* Add further checks (div-by-zero, bare GROUP BY, COUNT DISTINCT nulls, anti-join
|
|
17
|
+
* NULL trap) here as new functions invoked by detectSqlFootguns.
|
|
18
|
+
*/
|
|
19
|
+
// Strip string literals + comments before any text analysis, so a `/` inside
|
|
20
|
+
// quoted content or a comment is never mistaken for a division operator.
|
|
21
|
+
// (Mirrors the literal/comment stripping already used by isReadOnlySelect.)
|
|
22
|
+
function strip(sql) {
|
|
23
|
+
return sql
|
|
24
|
+
.replace(/'[^']*'/g, "''")
|
|
25
|
+
.replace(/"[^"]*"/g, '""')
|
|
26
|
+
.replace(/--.*$/gm, '')
|
|
27
|
+
.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
28
|
+
}
|
|
29
|
+
// A maximal multiplicative term: operand ([*/] operand)+. operand = number |
|
|
30
|
+
// func(one paren level) | identifier. One level covers SUM(wins), AVG(x)/COUNT(*).
|
|
31
|
+
const OPERAND = String.raw `(?:\w+\s*\([^()]*\)|\w+(?:\.\w+)?|\d+(?:\.\d+)?)`;
|
|
32
|
+
const TERM = new RegExp(`${OPERAND}(?:\\s*[*/]\\s*${OPERAND})+`, 'g');
|
|
33
|
+
const FLOAT_LIT = /\d+\.\d+/;
|
|
34
|
+
const CAST_REAL = /CAST\s*\([^()]*AS\s+(?:REAL|FLOAT|DOUBLE)/i;
|
|
35
|
+
const TERM_FUNCS = new Set(['sum', 'avg', 'count', 'min', 'max', 'cast', 'as', 'real', 'float', 'double', 'total', 'abs', 'round', 'distinct', 'all']);
|
|
36
|
+
/** Multiplicative terms containing a `/` that are NOT already float-safe (no float
|
|
37
|
+
* literal, no CAST-to-real), with their candidate column identifiers. Pure syntax
|
|
38
|
+
* — cheap enough to use as a pre-filter before any type probing. */
|
|
39
|
+
export function riskyDivisionTerms(sql) {
|
|
40
|
+
const s = strip(sql);
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const m of s.matchAll(TERM)) {
|
|
43
|
+
const term = m[0];
|
|
44
|
+
if (!term.includes('/'))
|
|
45
|
+
continue; // pure multiplication can't truncate
|
|
46
|
+
if (FLOAT_LIT.test(term) || CAST_REAL.test(term))
|
|
47
|
+
continue; // float context → safe
|
|
48
|
+
const columns = [...term.matchAll(/[a-z_]\w*/gi)].map((x) => x[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()));
|
|
49
|
+
out.push({ term, columns });
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
/** Division denominators (the operand right of each `/`) with their candidate
|
|
54
|
+
* column identifiers. A `NULLIF(...)`-wrapped denominator is already guarded and
|
|
55
|
+
* skipped. Applies to ALL division (float `x/0` also yields NULL in SQLite), so
|
|
56
|
+
* it is independent of the integer-truncation check above. */
|
|
57
|
+
export function divisionDenominators(sql) {
|
|
58
|
+
const s = strip(sql);
|
|
59
|
+
const re = new RegExp(`/\\s*(${OPERAND})`, 'g');
|
|
60
|
+
const out = [];
|
|
61
|
+
for (const m of s.matchAll(re)) {
|
|
62
|
+
const denom = m[1].trim();
|
|
63
|
+
if (/^NULLIF\s*\(/i.test(denom))
|
|
64
|
+
continue; // already guarded
|
|
65
|
+
const columns = [...denom.matchAll(/[a-z_]\w*/gi)].map((x) => x[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()) && id.toLowerCase() !== 'nullif');
|
|
66
|
+
if (columns.length)
|
|
67
|
+
out.push({ denom, columns });
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Detect division whose denominator column actually CONTAINS a zero — `x / 0`
|
|
73
|
+
* silently yields NULL in SQLite (no error), which then vanishes from downstream
|
|
74
|
+
* aggregates. Data-gated on purpose: it warns ONLY when a real zero is present, so
|
|
75
|
+
* it never cries wolf on a zero-free denominator (no overbearing blanket warning).
|
|
76
|
+
*/
|
|
77
|
+
export async function detectDivByZero(sql, columnHasZero) {
|
|
78
|
+
const warnings = [];
|
|
79
|
+
for (const { denom, columns } of divisionDenominators(sql)) {
|
|
80
|
+
let zero = false;
|
|
81
|
+
for (const col of columns) {
|
|
82
|
+
if (await columnHasZero(col)) {
|
|
83
|
+
zero = true;
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (zero) {
|
|
88
|
+
warnings.push({
|
|
89
|
+
code: 'division-by-zero',
|
|
90
|
+
message: `Denominator "${denom}" contains zero values — SQLite returns NULL for x/0 (no error), and those rows silently drop out of aggregates. ` +
|
|
91
|
+
`Guard it: <numerator> / NULLIF(${denom}, 0), or filter the zeros out.`,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return warnings;
|
|
96
|
+
}
|
|
97
|
+
const AGG = /\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/i;
|
|
98
|
+
/** The top-level SELECT projection list (between the first SELECT and its FROM). */
|
|
99
|
+
function selectList(stripped) {
|
|
100
|
+
const m = stripped.match(/\bSELECT\b([\s\S]*?)\bFROM\b/i);
|
|
101
|
+
return m ? m[1] : undefined;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
|
|
105
|
+
* aggregate with NO GROUP BY — e.g. `SELECT name, SUM(score) FROM t`. SQLite does
|
|
106
|
+
* not error; it pairs an ARBITRARY row's `name` with a whole-table aggregate (a
|
|
107
|
+
* meaningless pairing the caller rarely intends).
|
|
108
|
+
*
|
|
109
|
+
* Deliberately CONSERVATIVE — built to avoid false positives:
|
|
110
|
+
* - skips anything with a GROUP BY (verifying GROUP BY membership syntactically is
|
|
111
|
+
* too false-positive-prone);
|
|
112
|
+
* - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
|
|
113
|
+
* columns then take values from the extremal row, so that is actually correct;
|
|
114
|
+
* - only flags identifiers that are real base columns.
|
|
115
|
+
*/
|
|
116
|
+
export function detectBareAggregate(sql, isBaseColumn) {
|
|
117
|
+
const s = strip(sql);
|
|
118
|
+
if (/\bGROUP\s+BY\b/i.test(s))
|
|
119
|
+
return []; // grouped → out of scope (conservative)
|
|
120
|
+
const list = selectList(s);
|
|
121
|
+
if (!list || !AGG.test(list))
|
|
122
|
+
return [];
|
|
123
|
+
// Lone MIN()/MAX() → SQLite fills bare columns from the extremal row (correct).
|
|
124
|
+
const aggs = [...list.matchAll(/\b(SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/gi)].map((m) => m[1].toUpperCase());
|
|
125
|
+
if (aggs.length === 1 && (aggs[0] === 'MIN' || aggs[0] === 'MAX'))
|
|
126
|
+
return [];
|
|
127
|
+
// Drop aggregate call expressions, then look for surviving base-column identifiers.
|
|
128
|
+
const bare = list.replace(/\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\([^()]*\)/gi, ' ');
|
|
129
|
+
const cols = [...bare.matchAll(/[a-z_]\w*/gi)].map((m) => m[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()) && isBaseColumn(id));
|
|
130
|
+
if (cols.length === 0)
|
|
131
|
+
return [];
|
|
132
|
+
const uniq = [...new Set(cols)];
|
|
133
|
+
return [{
|
|
134
|
+
code: 'bare-aggregate',
|
|
135
|
+
message: `Column${uniq.length > 1 ? 's' : ''} "${uniq.join('", "')}" ${uniq.length > 1 ? 'are' : 'is'} selected next to an aggregate with no GROUP BY — ` +
|
|
136
|
+
`SQLite pairs an ARBITRARY row's value with a whole-table aggregate here. ` +
|
|
137
|
+
`For the label of the top row use ORDER BY … LIMIT 1 (or a subquery); for per-group rows add GROUP BY.`,
|
|
138
|
+
}];
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Detect silent-wrong-answer footguns in a SELECT. Type-aware: a division term is
|
|
142
|
+
* flagged only when EVERY resolvable operand column is integer-typed (a single
|
|
143
|
+
* real operand means SQLite promotes to real → no truncation). Unknown operands
|
|
144
|
+
* are treated conservatively as non-integer (no flag) to avoid crying wolf.
|
|
145
|
+
*/
|
|
146
|
+
export async function detectSqlFootguns(sql, columnType) {
|
|
147
|
+
const warnings = [];
|
|
148
|
+
for (const { term, columns } of riskyDivisionTerms(sql)) {
|
|
149
|
+
if (columns.length === 0)
|
|
150
|
+
continue;
|
|
151
|
+
let allInteger = true;
|
|
152
|
+
for (const col of columns) {
|
|
153
|
+
if ((await columnType(col)) !== 'integer') {
|
|
154
|
+
allInteger = false;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (allInteger) {
|
|
159
|
+
warnings.push({
|
|
160
|
+
code: 'integer-division',
|
|
161
|
+
message: `Integer division in "${term.trim()}" truncates toward zero (int/int floors — e.g. 16/32 → 0, not 0.5). ` +
|
|
162
|
+
`Cast a numeric operand first: CAST(<numerator> AS REAL) / <denominator>.`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return warnings;
|
|
167
|
+
}
|
|
@@ -2,6 +2,42 @@
|
|
|
2
2
|
* Connector-specific types for Dolex data source connectors.
|
|
3
3
|
*/
|
|
4
4
|
import type { DataSourceType, DataSourceConfig, DataSchema } from '../types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Reflect a session-derived column in a connector's cached schema, so downstream consumers
|
|
7
|
+
* (schemaText, describe_data) see it. Shared by the live connectors' applyDerivation
|
|
8
|
+
* (Postgres shadow view / Mongo $set) — idempotent; a no-op if the column already exists.
|
|
9
|
+
*/
|
|
10
|
+
export declare function registerDerivedColumn(schema: DataSchema, table: string, column: string): void;
|
|
11
|
+
/**
|
|
12
|
+
* How a source materializes a derived column, declared by the connector itself
|
|
13
|
+
* so the transform/clean surfaces stay source-agnostic (no getDatabase-truthiness gate).
|
|
14
|
+
*
|
|
15
|
+
* - `sqlite-alter` — CSV: ALTER TABLE + rowid-keyed UPDATE on the in-memory SQLite db.
|
|
16
|
+
* - `session-temp` — Postgres: a session-local TEMP TABLE keyed by `id`, exposed to
|
|
17
|
+
* arbitrary later queries via a same-named TEMP VIEW on ONE pinned client.
|
|
18
|
+
* - `computed-set` — Mongo: a `$set` aggregation expression prepended to every incoming pipeline,
|
|
19
|
+
* computing the derived field server-side on read. Base collection never written.
|
|
20
|
+
* - `sidecar` — Mongo alt: a throwaway sidecar collection keyed by `_id`, joined via $lookup
|
|
21
|
+
* (used when the derived value is precomputed rather than an expression).
|
|
22
|
+
* - `none` — the source cannot derive columns.
|
|
23
|
+
*/
|
|
24
|
+
export type DerivationMaterialization = 'sqlite-alter' | 'session-temp' | 'computed-set' | 'sidecar' | 'none';
|
|
25
|
+
/** The row key a derivation joins the derived value back on. */
|
|
26
|
+
export type DerivationRowKey = 'rowid' | 'id' | '_id' | null;
|
|
27
|
+
/**
|
|
28
|
+
* A connector's self-declared derivation contract. The transform/clean surfaces read this
|
|
29
|
+
* (via `ConnectedSource.derivationCapabilities()`) instead of probing for a raw db handle.
|
|
30
|
+
*/
|
|
31
|
+
export interface DerivationCapabilities {
|
|
32
|
+
/** Can this source materialize a derived column at all? */
|
|
33
|
+
canDerive: boolean;
|
|
34
|
+
/** How the derived column is materialized. */
|
|
35
|
+
materialization: DerivationMaterialization;
|
|
36
|
+
/** The key column the derived value is joined back on. */
|
|
37
|
+
rowKey: DerivationRowKey;
|
|
38
|
+
/** Is the derived column visible to arbitrary subsequent analyst queries (not just an explicit JOIN)? */
|
|
39
|
+
serverSideQueryable: boolean;
|
|
40
|
+
}
|
|
5
41
|
/**
|
|
6
42
|
* A data connector knows how to connect to a specific data source type,
|
|
7
43
|
* introspect its schema, and execute queries against it.
|
|
@@ -31,6 +67,21 @@ export interface ConnectedSource {
|
|
|
31
67
|
getSampleRows(tableName: string, count?: number): Promise<Record<string, any>[]>;
|
|
32
68
|
/** Get the underlying database handle (only available for SQL-backed connectors). */
|
|
33
69
|
getDatabase?(): any;
|
|
70
|
+
/**
|
|
71
|
+
* Declare how (or whether) this source can materialize a derived column. The source-agnostic
|
|
72
|
+
* transform/clean surfaces gate on this instead of probing `getDatabase`. A connector that does
|
|
73
|
+
* not implement it is treated as non-deriving.
|
|
74
|
+
*/
|
|
75
|
+
derivationCapabilities?(): DerivationCapabilities;
|
|
76
|
+
/**
|
|
77
|
+
* Materialize a derived column named `column` on `table` from `expr` — an expression in THIS
|
|
78
|
+
* source's own native language (a SQL expression for a SQL source, a Mongo `$set` aggregation
|
|
79
|
+
* expression for Mongo). The derived column must become visible to arbitrary subsequent
|
|
80
|
+
* `executeQuery` calls WITHOUT mutating the base table/collection (a session-local temp view on
|
|
81
|
+
* Postgres, a prepended `$set` on Mongo). Only implemented by connectors that declare
|
|
82
|
+
* `serverSideQueryable` derivation. Throws on an unsafe/invalid expression.
|
|
83
|
+
*/
|
|
84
|
+
applyDerivation?(table: string, column: string, expr: string): Promise<void>;
|
|
34
85
|
/** Invalidate cached schema so the next getSchema() rebuilds from the live database. */
|
|
35
86
|
invalidateSchema?(): void;
|
|
36
87
|
/** Close the connection and free resources. */
|