@outsidedata/dolex 9.0.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/src/cli/commands/sources.js +2 -1
  2. package/dist/src/cli/data-source.d.ts +0 -2
  3. package/dist/src/cli/data-source.js +0 -1
  4. package/dist/src/connectors/manager.js +71 -52
  5. package/dist/src/connectors/mongo/index.d.ts +8 -0
  6. package/dist/src/connectors/mongo/index.js +42 -6
  7. package/dist/src/connectors/pg/index.js +90 -22
  8. package/dist/src/connectors/sql-safety.d.ts +59 -17
  9. package/dist/src/connectors/sql-safety.js +275 -54
  10. package/dist/src/connectors/types.d.ts +8 -0
  11. package/dist/src/connectors/types.js +22 -0
  12. package/dist/src/mcp/index.js +23 -4
  13. package/dist/src/mcp/tools/analyze.js +1 -1
  14. package/dist/src/mcp/tools/clean-schemas.js +1 -1
  15. package/dist/src/mcp/tools/query-source.js +2 -2
  16. package/dist/src/mcp/tools/sources.d.ts +1 -1
  17. package/dist/src/mcp/tools/sources.js +7 -5
  18. package/dist/src/mcp/tools/transform-schemas.js +4 -4
  19. package/dist/src/mcp/tools/visualize-cli.js +1 -1
  20. package/dist/src/mcp/tools/visualize.js +2 -2
  21. package/dist/src/patterns/index.d.ts +1 -1
  22. package/dist/src/patterns/index.js +1 -1
  23. package/dist/src/patterns/registry.d.ts +1 -12
  24. package/dist/src/patterns/registry.js +0 -13
  25. package/dist/src/patterns/utils.d.ts +0 -24
  26. package/dist/src/patterns/utils.js +0 -71
  27. package/dist/src/renderers/d3/shared.d.ts +0 -18
  28. package/dist/src/renderers/d3/shared.js +0 -62
  29. package/dist/src/types.d.ts +1 -1
  30. package/dist/src/utils/capabilities.js +1 -1
  31. package/package.json +4 -4
  32. package/dist/src/analysis/clean-exec.d.ts +0 -23
  33. package/dist/src/analysis/clean-exec.js +0 -87
  34. package/dist/src/cleaning/author.d.ts +0 -30
  35. package/dist/src/cleaning/author.js +0 -7
  36. package/dist/src/cleaning/handlers.d.ts +0 -16
  37. package/dist/src/cleaning/handlers.js +0 -82
  38. package/dist/src/cleaning/manifest.d.ts +0 -35
  39. package/dist/src/cleaning/manifest.js +0 -95
@@ -7,6 +7,7 @@ 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
9
  import { resolveSourceConfig } from '../../connectors/source-factory.js';
10
+ import { redactUri } from '../../connectors/types.js';
10
11
  export async function sourcesCommand(argv) {
11
12
  const args = parseArgs(argv, {
12
13
  booleans: ['json', 'help', 'verify'],
@@ -166,7 +167,7 @@ export async function sourcesCommand(argv) {
166
167
  }
167
168
  /** One-line summary of where a source lives, for the `list` table. */
168
169
  /** 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
+ const hostPortDb = (connStr, host, port, database) => connStr ? redactUri(connStr) : [host, port].filter(Boolean).join(':') + (database ? `/${database}` : '');
170
171
  function describeLocation(config) {
171
172
  switch (config.type) {
172
173
  case 'csv':
@@ -13,8 +13,6 @@
13
13
  */
14
14
  import type { DataColumn, DataSchema } from '../types.js';
15
15
  import type { SourceManager, SqlQueryResult } from '../connectors/manager.js';
16
- import { dolexHome } from './paths.js';
17
- export { dolexHome };
18
16
  export interface OpenedSource {
19
17
  manager: SourceManager;
20
18
  sourceId: string;
@@ -14,7 +14,6 @@
14
14
  import { existsSync, statSync, readFileSync } from 'fs';
15
15
  import { resolve, basename, join } from 'path';
16
16
  import { dolexHome } from './paths.js';
17
- export { dolexHome };
18
17
  /**
19
18
  * Import the SourceManager module, turning a better-sqlite3 native-binding
20
19
  * load failure (e.g. a binary built for a different Node ABI) into an
@@ -13,7 +13,7 @@ import * as crypto from 'crypto';
13
13
  import { csvConnector } from './csv.js';
14
14
  import { pgConnector } from './pg/index.js';
15
15
  import { mongoConnector } from './mongo/index.js';
16
- import { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate } from './sql-safety.js';
16
+ import { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate, dividingOutputPositions, detectIntegerDivisionResult, tableAliases, } from './sql-safety.js';
17
17
  const MAX_RESULT_ROWS = 10000;
18
18
  // ─── SQL Safety ───────────────────────────────────────────────────────────
19
19
  function isReadOnlySelect(sql) {
@@ -78,15 +78,10 @@ const CONNECTOR_MAP = {
78
78
  /** SQL-family sources go through the SQL safety/limit/error machinery; a document store
79
79
  * (mongodb) is routed down a pipeline path instead (no SELECT gate, no LIMIT-wrap). */
80
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
- }
81
+ // The Mongo read-only gate lives in the connector (assertReadOnlyPipeline), applied to the PARSED
82
+ // pipeline the driver will actually run. A regex over the query string was not a boundary: a JSON
83
+ // unicode escape ("$out") parses straight through it, and a banned stage nested in a
84
+ // $lookup/$unionWith sub-pipeline never appears at the top level.
90
85
  function getConnectorForType(type) {
91
86
  return CONNECTOR_MAP[type];
92
87
  }
@@ -340,13 +335,8 @@ export class SourceManager {
340
335
  const resolved = await this.resolveSource(idOrName);
341
336
  if (!resolved.ok)
342
337
  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)) {
338
+ // A document store takes an aggregation pipeline, not SQL — the connector gates and runs it.
339
+ if (isSqlSource(resolved.source.type) && !isReadOnlySelect(sql)) {
350
340
  // Enforce read-only queries to prevent SQL injection attacks
351
341
  return { ok: false, error: 'Only SELECT queries are allowed.' };
352
342
  }
@@ -389,7 +379,7 @@ export class SourceManager {
389
379
  // Only mark as truncated if we hit our limit AND the user didn't have an explicit LIMIT
390
380
  const userHasLimit = /\bLIMIT\s+\d+/i.test(sql);
391
381
  const hitOurLimit = result.rows.length >= Math.min(maxRows, MAX_RESULT_ROWS);
392
- const warnings = await this.analyzeSqlSafety(resolved.source, sql);
382
+ const warnings = await this.analyzeSqlSafety(resolved.source, sql, result.columns);
393
383
  return {
394
384
  ok: true,
395
385
  rows: result.rows,
@@ -411,9 +401,6 @@ export class SourceManager {
411
401
  * detection is the language-plane work, added later. Never throws (audit-on-load relies on it).
412
402
  */
413
403
  async queryPipeline(source, query, maxRows) {
414
- const guard = isReadOnlyPipeline(query);
415
- if (!guard.ok)
416
- return { ok: false, error: guard.error };
417
404
  try {
418
405
  const result = await source.executeQuery(query);
419
406
  const errorMsg = hasErrorRow(result);
@@ -434,23 +421,38 @@ export class SourceManager {
434
421
  * yields no warnings (never blocks or breaks the query). Gated on a cheap
435
422
  * syntactic pre-filter so the type probes only run when a risky term exists.
436
423
  */
437
- async analyzeSqlSafety(source, sql) {
424
+ async analyzeSqlSafety(source, sql, outputColumns) {
438
425
  try {
439
- const hasDivision = riskyDivisionTerms(sql).length > 0;
426
+ const terms = riskyDivisionTerms(sql);
440
427
  const denoms = divisionDenominators(sql);
428
+ const dividing = dividingOutputPositions(sql);
441
429
  const maybeBareAgg = /\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/i.test(sql) && !/\bGROUP\s+BY\b/i.test(sql);
442
- if (!hasDivision && denoms.length === 0 && !maybeBareAgg)
430
+ if (!terms.length && !denoms.length && !dividing?.length && !maybeBareAgg)
443
431
  return [];
444
432
  const schema = await source.getSchema();
445
- const colToTable = new Map();
433
+ const byName = new Map();
446
434
  for (const t of schema.tables)
447
- for (const c of t.columns)
448
- if (!colToTable.has(c.name))
449
- colToTable.set(c.name, t.name);
435
+ byName.set(t.name.toLowerCase(), { name: t.name, columns: new Set(t.columns.map((c) => c.name)) });
436
+ const aliases = tableAliases(sql);
437
+ const queryTables = [...new Set(aliases.values())]
438
+ .map((t) => byName.get(t.toLowerCase()))
439
+ .filter((t) => !!t);
440
+ // A reference resolves through THIS query's own aliases: `B.H` → the table `B` names; a bare
441
+ // column → the first table the query reads that has it. Resolving by name across the whole
442
+ // schema typed a divide on zzz.val against aaa.val (issue #35, experiment 061).
443
+ const tableOf = (ref) => {
444
+ if (ref.qualifier) {
445
+ const t = byName.get((aliases.get(ref.qualifier.toLowerCase()) ?? '').toLowerCase());
446
+ return t?.columns.has(ref.column) ? t.name : undefined;
447
+ }
448
+ return queryTables.find((t) => t.columns.has(ref.column))?.name;
449
+ };
450
+ const q = (id) => `"${id.replace(/"/g, '""')}"`;
450
451
  // Type probe is dialect-specific: SQLite has typeof(); Postgres has pg_typeof().
451
452
  // Normalize the result so the integer-division check ('integer') works on both —
452
453
  // Postgres int columns report integer/bigint/smallint, floats numeric/double precision.
453
454
  const isPg = source.type === 'postgres';
455
+ const typeProbe = (col) => (isPg ? `pg_typeof(${q(col)})::text` : `typeof(${q(col)})`);
454
456
  const normalizeType = (raw) => {
455
457
  const t = raw.toLowerCase();
456
458
  if (t === 'integer' || t === 'bigint' || t === 'smallint')
@@ -460,37 +462,54 @@ export class SourceManager {
460
462
  return t;
461
463
  };
462
464
  const typeCache = new Map();
463
- const columnType = async (col) => {
464
- if (typeCache.has(col))
465
- return typeCache.get(col);
466
- let type;
467
- const table = colToTable.get(col);
468
- if (table) {
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`);
471
- const v = r.rows?.[0]?.t;
472
- type = typeof v === 'string' ? normalizeType(v) : undefined;
473
- }
474
- typeCache.set(col, type);
465
+ const columnType = async (ref) => {
466
+ const table = tableOf(ref);
467
+ if (!table)
468
+ return undefined;
469
+ const key = `${table}\u0000${ref.column}`;
470
+ if (typeCache.has(key))
471
+ return typeCache.get(key);
472
+ const r = await source.executeQuery(`SELECT ${typeProbe(ref.column)} AS t FROM ${q(table)} WHERE ${q(ref.column)} IS NOT NULL LIMIT 1`);
473
+ const v = r.rows?.[0]?.t;
474
+ const type = typeof v === 'string' ? normalizeType(v) : undefined;
475
+ typeCache.set(key, type);
475
476
  return type;
476
477
  };
477
478
  const zeroCache = new Map();
478
- const columnHasZero = async (col) => {
479
- if (zeroCache.has(col))
480
- return zeroCache.get(col);
481
- let zero = false;
482
- const table = colToTable.get(col);
483
- if (table) {
484
- const r = await source.executeQuery(`SELECT 1 AS z FROM "${table}" WHERE "${col}" = 0 LIMIT 1`);
485
- zero = (r.rows?.length ?? 0) > 0;
486
- }
487
- zeroCache.set(col, zero);
479
+ const columnHasZero = async (ref) => {
480
+ const table = tableOf(ref);
481
+ if (!table)
482
+ return false;
483
+ const key = `${table}\u0000${ref.column}`;
484
+ if (zeroCache.has(key))
485
+ return zeroCache.get(key);
486
+ const r = await source.executeQuery(`SELECT 1 AS z FROM ${q(table)} WHERE ${q(ref.column)} = 0 LIMIT 1`);
487
+ const zero = (r.rows?.length ?? 0) > 0;
488
+ zeroCache.set(key, zero);
488
489
  return zero;
489
490
  };
491
+ // The type of an OUTPUT column over the executed query — the database's own answer to
492
+ // "did this division truncate?". One probe per dividing output column, guarded so a probe
493
+ // that can't run (duplicate unaliased names, …) only loses its own signal.
494
+ const inner = sql.trim().replace(/;\s*$/, '');
495
+ const resultType = async (col) => {
496
+ try {
497
+ const r = await source.executeQuery(`SELECT ${typeProbe(col)} AS t FROM (${inner}) AS _p WHERE ${q(col)} IS NOT NULL LIMIT 1`);
498
+ const v = r.rows?.[0]?.t;
499
+ return typeof v === 'string' ? normalizeType(v) : undefined;
500
+ }
501
+ catch {
502
+ return undefined;
503
+ }
504
+ };
505
+ const syntactic = await detectSqlFootguns(sql, columnType);
490
506
  const warnings = [
491
- ...(await detectSqlFootguns(sql, columnType)),
507
+ ...syntactic,
508
+ // Expression shapes no operand rule can type ((SUM(CASE…)+…)/COUNT(*), scalar-subquery
509
+ // numerators). Skipped when the syntactic pass already flagged — one warning is the signal.
510
+ ...(syntactic.length ? [] : await detectIntegerDivisionResult(sql, outputColumns, resultType)),
492
511
  ...(await detectDivByZero(sql, columnHasZero)),
493
- ...detectBareAggregate(sql, (col) => colToTable.has(col)),
512
+ ...detectBareAggregate(sql, (ref) => tableOf(ref) !== undefined),
494
513
  ];
495
514
  return warnings.map((w) => w.message);
496
515
  }
@@ -10,4 +10,12 @@ export declare function parseSeam(query: string, defaultCollection?: string): {
10
10
  collection: string;
11
11
  pipeline: any[];
12
12
  };
13
+ /**
14
+ * Read-only gate over the PARSED pipeline — the authoritative one.
15
+ *
16
+ * A regex over the query STRING is not a boundary: JSON unicode escapes ("$out") parse
17
+ * straight through it, and a banned stage nested inside a $lookup/$unionWith sub-pipeline never
18
+ * appears at the top level. Walk the object the driver will actually run instead.
19
+ */
20
+ export declare function assertReadOnlyPipeline(node: unknown): void;
13
21
  export declare const mongoConnector: DataConnector;
@@ -4,6 +4,10 @@ import { importOptional } from '../../utils/optional-deps.js';
4
4
  * becomes a friendly "npm install mongodb", surfaced only when a Mongo source is actually used. */
5
5
  const loadMongo = () => importOptional('mongodb', 'mongodb');
6
6
  const SAMPLE_DOCS = 200; // docs sampled to discover the key universe + candidate types
7
+ // Above this many docs, computing exact percentiles by $push-ing the whole column into one array
8
+ // would blow Mongo's 16MB per-document BSON limit (allowDiskUse can't lift it). Past the cap we keep
9
+ // the streaming stats (min/max/avg/stddev) and omit median/quartiles rather than fail profiling.
10
+ const PERCENTILE_MAX_DOCS = 500_000;
7
11
  function uriFor(cfg) {
8
12
  if (cfg.uri)
9
13
  return cfg.uri;
@@ -51,7 +55,9 @@ async function profileCollection(db, name) {
51
55
  const coll = db.collection(name);
52
56
  const total = await coll.countDocuments();
53
57
  // Phase 1 — sample docs to discover the key universe + a candidate type per key.
54
- const sampled = await coll.find({}, { limit: SAMPLE_DOCS }).toArray();
58
+ // $sample (random) not find().limit() (natural/oldest order): keys added or retyped over the
59
+ // collection's life would otherwise be invisible, classified from the oldest documents only.
60
+ const sampled = await coll.aggregate([{ $sample: { size: SAMPLE_DOCS } }]).toArray();
55
61
  const keys = [];
56
62
  const candByKey = new Map();
57
63
  const sampleValsByKey = new Map();
@@ -79,15 +85,20 @@ async function profileCollection(db, name) {
79
85
  if (cand === 'numeric') {
80
86
  // Mongo 5.0 has no $percentile; sort + $push then pick positional elements server-side
81
87
  // (the array stays inside the sub-pipeline — the facet only stores the scalar result).
88
+ // Only for collections under PERCENTILE_MAX_DOCS — past that the $push array would exceed
89
+ // the 16MB BSON limit, so we keep streaming stats and drop the quartiles.
90
+ const withPercentiles = total <= PERCENTILE_MAX_DOCS;
82
91
  facet[`${k}__st`] = [
83
92
  { $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 } } },
93
+ ...(withPercentiles ? [{ $sort: { [k]: 1 } }] : []),
94
+ { $group: { _id: null, ...(withPercentiles ? { vals: { $push: `$${k}` } } : {}), min: { $min: `$${k}` }, max: { $max: `$${k}` }, avg: { $avg: `$${k}` }, sd: { $stdDevPop: `$${k}` }, n: { $sum: 1 } } },
86
95
  { $project: {
87
96
  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] } }] },
97
+ ...(withPercentiles ? {
98
+ median: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.5] } }] },
99
+ p25: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.25] } }] },
100
+ p75: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.75] } }] },
101
+ } : {}),
91
102
  } },
92
103
  ];
93
104
  }
@@ -175,6 +186,30 @@ export function parseSeam(query, defaultCollection) {
175
186
  return { collection: defaultCollection, pipeline: parsed.pipeline };
176
187
  throw new Error('Mongo query must be a JSON aggregation pipeline: a bare array [<stages>], or {"collection":"<name>","pipeline":[<stages>]}');
177
188
  }
189
+ /** Aggregation stages/operators that write, or execute arbitrary server-side JS. */
190
+ const BANNED_OPS = new Set(['$out', '$merge', '$function', '$accumulator', '$where']);
191
+ /**
192
+ * Read-only gate over the PARSED pipeline — the authoritative one.
193
+ *
194
+ * A regex over the query STRING is not a boundary: JSON unicode escapes ("$out") parse
195
+ * straight through it, and a banned stage nested inside a $lookup/$unionWith sub-pipeline never
196
+ * appears at the top level. Walk the object the driver will actually run instead.
197
+ */
198
+ export function assertReadOnlyPipeline(node) {
199
+ if (Array.isArray(node)) {
200
+ for (const n of node)
201
+ assertReadOnlyPipeline(n);
202
+ return;
203
+ }
204
+ if (node == null || typeof node !== 'object')
205
+ return;
206
+ for (const [k, v] of Object.entries(node)) {
207
+ if (BANNED_OPS.has(k)) {
208
+ throw new Error(`Only read-only aggregation pipelines are allowed (found "${k}"; no ${[...BANNED_OPS].join('/')}).`);
209
+ }
210
+ assertReadOnlyPipeline(v);
211
+ }
212
+ }
178
213
  class MongoConnectedSource {
179
214
  id;
180
215
  name;
@@ -197,6 +232,7 @@ class MongoConnectedSource {
197
232
  async executeQuery(query) {
198
233
  try {
199
234
  const { collection, pipeline } = parseSeam(query, this.schema.tables[0]?.name);
235
+ assertReadOnlyPipeline(pipeline);
200
236
  // Prepend a $set for each session-derived field so every aggregation sees it transparently,
201
237
  // without ever writing the base collection.
202
238
  const derived = this.derived.get(collection) ?? [];
@@ -4,14 +4,18 @@ import { importOptional } from '../../utils/optional-deps.js';
4
4
  * friendly "npm install pg", surfaced only when a Postgres source is actually used. */
5
5
  const loadPg = () => importOptional('pg', 'postgres');
6
6
  const q = (id) => '"' + id.replace(/"/g, '""') + '"';
7
+ // application_name tags dolex's connections in pg_stat_activity so a DBA can see (and kill) them;
8
+ // statement_timeout is a backstop so a pathological profiling scan aborts instead of hammering a
9
+ // primary for hours. Both apply to every connection this pool hands out (incl. the pinned client).
10
+ const POOL_GUARDS = { application_name: 'dolex', statement_timeout: 30_000, max: 4 };
7
11
  function poolFor(PoolCtor, cfg) {
8
12
  if (cfg.connectionString)
9
- return new PoolCtor({ connectionString: cfg.connectionString, max: 4 });
13
+ return new PoolCtor({ connectionString: cfg.connectionString, ...POOL_GUARDS });
10
14
  // The secret is either the literal password or (preferred) read from an env var at connect time,
11
15
  // so it need never be persisted in the registry file.
12
16
  const password = cfg.password ?? (cfg.passwordEnv ? process.env[cfg.passwordEnv] : undefined);
13
17
  return new PoolCtor({
14
- host: cfg.host, port: cfg.port, database: cfg.database, user: cfg.user, password, max: 4,
18
+ host: cfg.host, port: cfg.port, database: cfg.database, user: cfg.user, password, ...POOL_GUARDS,
15
19
  });
16
20
  }
17
21
  // Postgres type OIDs that should surface as JS numbers: int2/int4/int8, float4/float8, numeric.
@@ -42,32 +46,58 @@ async function profileTable(pool, schema, table) {
42
46
  countSel.push(`COUNT(DISTINCT ${q(c.name)})::bigint AS ${q('d_' + c.name)}`);
43
47
  countSel.push(`COUNT(${q(c.name)})::bigint AS ${q('n_' + c.name)}`);
44
48
  }
45
- const counts = (await pool.query(`SELECT ${countSel.join(', ')} FROM ${q(schema)}.${q(table)}`)).rows[0];
49
+ let counts;
50
+ try {
51
+ counts = (await pool.query(`SELECT ${countSel.join(', ')} FROM ${q(schema)}.${q(table)}`)).rows[0];
52
+ }
53
+ catch {
54
+ // COUNT(DISTINCT …) has no operator for json / xml / geometry columns — a single such column
55
+ // errors the whole combined query and would brick the entire source. Fall back to per-column
56
+ // counts so one uncountable column degrades to unknown-cardinality, not a dead database.
57
+ const total = Number((await pool.query(`SELECT COUNT(*)::bigint AS n FROM ${q(schema)}.${q(table)}`)).rows[0].n);
58
+ counts = { __total: total };
59
+ for (const c of cols) {
60
+ try {
61
+ const r = (await pool.query(`SELECT COUNT(DISTINCT ${q(c.name)})::bigint AS d, COUNT(${q(c.name)})::bigint AS n FROM ${q(schema)}.${q(table)}`)).rows[0];
62
+ counts['d_' + c.name] = r.d;
63
+ counts['n_' + c.name] = r.n;
64
+ }
65
+ catch {
66
+ counts['d_' + c.name] = 0;
67
+ counts['n_' + c.name] = total; // uncountable → assume all-present, unknown distinct
68
+ }
69
+ }
70
+ }
46
71
  const total = Number(counts.__total);
47
72
  const columns = [];
48
73
  for (const c of cols) {
49
74
  const distinct = Number(counts['d_' + c.name]);
50
75
  const nonNull = Number(counts['n_' + c.name]);
51
76
  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);
77
+ let sampleValues = [];
55
78
  let stats;
56
79
  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 }));
80
+ // Per-column detail is isolated: an uncountable/unsortable type (json/xml/geometry) that can't
81
+ // be DISTINCT'd or GROUP BY'd degrades to a bare column instead of failing the whole connect.
82
+ try {
83
+ const sv = await pool.query(`SELECT DISTINCT ${q(c.name)}::text AS v FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL LIMIT 20`);
84
+ sampleValues = sv.rows.map((r) => String(r.v)).slice(0, 5);
85
+ if (type === 'numeric' && nonNull > 0) {
86
+ const s = (await pool.query(`SELECT MIN(${q(c.name)})::float8 AS min, MAX(${q(c.name)})::float8 AS max, AVG(${q(c.name)})::float8 AS mean,
87
+ COALESCE(STDDEV_POP(${q(c.name)}),0)::float8 AS stddev,
88
+ percentile_cont(0.5) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS median,
89
+ percentile_cont(0.25) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p25,
90
+ percentile_cont(0.75) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p75
91
+ FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL`)).rows[0];
92
+ stats = { min: s.min, max: s.max, mean: s.mean, median: s.median, stddev: s.stddev, p25: s.p25, p75: s.p75 };
93
+ }
94
+ else if (type === 'categorical' || type === 'date') {
95
+ const tv = await pool.query(`SELECT ${q(c.name)}::text AS value, COUNT(*)::int AS count FROM ${q(schema)}.${q(table)}
96
+ WHERE ${q(c.name)} IS NOT NULL GROUP BY ${q(c.name)} ORDER BY COUNT(*) DESC LIMIT 10`);
97
+ topValues = tv.rows.map((r) => ({ value: String(r.value), count: r.count }));
98
+ }
70
99
  }
100
+ catch { /* uncountable column → bare profile (name/type/counts only) */ }
71
101
  columns.push({
72
102
  name: c.name, type, sampleValues,
73
103
  uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
@@ -112,8 +142,18 @@ class PgConnectedSource {
112
142
  return this.pinned ?? this.pool;
113
143
  }
114
144
  async executeQuery(sql) {
145
+ // The DATABASE is the read-only boundary, not a regex over the SQL text. Every model-authored
146
+ // query runs inside a READ ONLY transaction, so a data-modifying CTE (WITH … AS (DELETE …)),
147
+ // SELECT INTO, a multi-statement string, or a volatile writing function (setval/pg_terminate_backend)
148
+ // ERRORS instead of running — verified against PG 17. The trusted applyDerivation path is
149
+ // deliberately NOT wrapped, so CREATE TEMP VIEW still works (read-only txns forbid it).
150
+ // Read-only txns still permit reads of the derived temp view, so derivations are unaffected.
151
+ const usePinned = this.pinned != null;
152
+ const client = usePinned ? this.pinned : await this.pool.connect();
115
153
  try {
116
- const r = await this.runner().query(sql);
154
+ await client.query('BEGIN TRANSACTION READ ONLY');
155
+ const r = await client.query(sql);
156
+ await client.query('COMMIT');
117
157
  // Coerce by the RESULT column's actual Postgres type (OID), not by source-column
118
158
  // name — so aliased aggregates (AVG/SUM AS x) and computed columns are typed
119
159
  // correctly. node-postgres returns numeric/bigint as strings; we surface them as JS
@@ -126,8 +166,11 @@ class PgConnectedSource {
126
166
  const out = {};
127
167
  for (const col of columns) {
128
168
  const v = row[col];
129
- if (numericField.has(col) && typeof v === 'string' && v !== '' && !isNaN(Number(v)))
130
- out[col] = Number(v);
169
+ // A bigint / wide numeric past 2^53 does not survive Number() — coercing it would hand
170
+ // back a silently wrong id or total. Keep those as the exact string the driver gave us.
171
+ const n = numericField.has(col) && typeof v === 'string' && v !== '' ? Number(v) : NaN;
172
+ if (Number.isFinite(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER)
173
+ out[col] = n;
131
174
  else
132
175
  out[col] = v;
133
176
  }
@@ -136,8 +179,16 @@ class PgConnectedSource {
136
179
  return { columns, rows };
137
180
  }
138
181
  catch (err) {
182
+ try {
183
+ await client.query('ROLLBACK');
184
+ }
185
+ catch { /* txn already aborted */ }
139
186
  return { columns: [], rows: [{ error: err.message }] };
140
187
  }
188
+ finally {
189
+ if (!usePinned)
190
+ client.release();
191
+ }
141
192
  }
142
193
  async getSampleRows(tableName, count = 5) {
143
194
  const total = this.schema.tables.find((t) => t.name === tableName)?.rowCount ?? 0;
@@ -175,6 +226,23 @@ class PgConnectedSource {
175
226
  if (!this.pinned)
176
227
  this.pinned = await this.pool.connect();
177
228
  const c = this.pinned;
229
+ // CREATE TEMP VIEW cannot run inside a READ ONLY txn, so this path escapes the read-only
230
+ // boundary every other query rides. The expr is caller/model-authored, and a write needs no
231
+ // ";" to hide in it (`setval('s',1)`, a volatile writing function, a dblink call). So EVALUATE
232
+ // the expr first inside a READ ONLY txn: anything data-modifying errors there and never
233
+ // reaches the view. LIMIT 1, not LIMIT 0 — LIMIT 0 skips target-list evaluation.
234
+ await c.query('BEGIN TRANSACTION READ ONLY');
235
+ try {
236
+ await c.query(`SELECT (${expr}) FROM ${q(this.schemaName)}.${q(table)} LIMIT 1`);
237
+ await c.query('COMMIT');
238
+ }
239
+ catch (err) {
240
+ try {
241
+ await c.query('ROLLBACK');
242
+ }
243
+ catch { /* txn already aborted */ }
244
+ throw new Error(`derivation expr rejected: ${err.message}`);
245
+ }
178
246
  const cols = this.derived.get(table) ?? [];
179
247
  const existing = cols.find((d) => d.column === column);
180
248
  if (existing)
@@ -12,39 +12,72 @@
12
12
  * cried wolf on legitimate real-typed division. The promoted approach is
13
13
  * term-aware + TYPE-aware detection with no mutation.
14
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.
15
+ * Integer division is caught two ways (experiment 061):
16
+ * • syntactically — a `/` term whose operand columns are all integer-typed. Column
17
+ * references resolve through the query's own FROM/JOIN aliases, so `B.H / B.AB`,
18
+ * `"wins"/"games"` and a column name shared by two tables all type correctly.
19
+ * • by asking the database — for each top-level output column whose expression
20
+ * divides, the caller probes the type of that column over the executed query. An
21
+ * integer-typed division result is truncation whatever produced it, which covers
22
+ * `(SUM(CASE …) + SUM(CASE …)) / COUNT(*)` and `(SELECT COUNT(*) …) / COUNT(*)`,
23
+ * shapes no operand-level rule can type.
18
24
  */
19
25
  export interface SqlSafetyWarning {
20
26
  code: 'integer-division' | 'division-by-zero' | 'bare-aggregate';
21
27
  message: string;
22
28
  }
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>;
29
+ /** A column reference as written: `alias.col` carries its qualifier, a bare `col` does not. */
30
+ export interface ColumnRef {
31
+ qualifier?: string;
32
+ column: string;
33
+ }
34
+ /** Resolve a referenced column's storage type ('integer' | 'real' | ...), or undefined
35
+ * when it is not a resolvable base column (a CTE output, an alias, an expression). */
36
+ export type ColumnTypeResolver = (ref: ColumnRef) => Promise<string | undefined>;
37
+ /** The query text with string literals blanked, comments removed and identifiers unquoted.
38
+ * A quoted name that is not a plain identifier ("World Wide Sales (in $)") becomes a
39
+ * placeholder token; `ids` maps it back to the real name. */
40
+ export interface Stripped {
41
+ text: string;
42
+ ids: Map<string, string>;
43
+ }
44
+ export declare function stripSql(sql: string): Stripped;
45
+ /** Column references in an expression: skips function names (an identifier followed by `(`),
46
+ * SQL keywords and numbers; keeps an `alias.` qualifier; maps placeholder tokens back. */
47
+ export declare function columnRefs(expr: string, ids: Map<string, string>): ColumnRef[];
26
48
  /** 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. */
49
+ * literal, no CAST-to-real), with the column references they read. Pure syntax —
50
+ * cheap enough to use as a pre-filter before any type probing. */
29
51
  export declare function riskyDivisionTerms(sql: string): {
30
52
  term: string;
31
- columns: string[];
53
+ refs: ColumnRef[];
32
54
  }[];
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. */
55
+ /** Division denominators (the operand right of each `/`) with the column references they
56
+ * read. A `NULLIF(...)`-wrapped denominator is already guarded and skipped. Applies to ALL
57
+ * division (float `x/0` also yields NULL in SQLite), so it is independent of the
58
+ * integer-truncation check above. */
37
59
  export declare function divisionDenominators(sql: string): {
38
60
  denom: string;
39
- columns: string[];
61
+ refs: ColumnRef[];
40
62
  }[];
63
+ /** Every table the query reads, keyed by each name it can be referenced by: its alias
64
+ * (lowercased) and its own name (lowercased). Covers `FROM a, b x`, `JOIN t AS y`, quoted
65
+ * and schema-qualified names. A derived-table subquery `FROM (SELECT …) s` names no table. */
66
+ export declare function tableAliases(sql: string): Map<string, string>;
67
+ /** The OUTERMOST select's top-level items (split on commas at paren depth 0), skipping any
68
+ * leading WITH clause. null when there is no top-level SELECT. */
69
+ export declare function selectItems(text: string): string[] | null;
70
+ /** Positions (0-based, in output-column order) of the top-level select items whose
71
+ * expression divides outside a float context. null when the positions can't be trusted
72
+ * to line up with the output columns (a `*` item expands to an unknown number). */
73
+ export declare function dividingOutputPositions(sql: string): number[] | null;
41
74
  /**
42
75
  * Detect division whose denominator column actually CONTAINS a zero — `x / 0`
43
76
  * silently yields NULL in SQLite (no error), which then vanishes from downstream
44
77
  * aggregates. Data-gated on purpose: it warns ONLY when a real zero is present, so
45
78
  * it never cries wolf on a zero-free denominator (no overbearing blanket warning).
46
79
  */
47
- export declare function detectDivByZero(sql: string, columnHasZero: (column: string) => Promise<boolean>): Promise<SqlSafetyWarning[]>;
80
+ export declare function detectDivByZero(sql: string, columnHasZero: (ref: ColumnRef) => Promise<boolean>): Promise<SqlSafetyWarning[]>;
48
81
  /**
49
82
  * Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
50
83
  * aggregate with NO GROUP BY — e.g. `SELECT name, SUM(score) FROM t`. SQLite does
@@ -56,9 +89,11 @@ export declare function detectDivByZero(sql: string, columnHasZero: (column: str
56
89
  * too false-positive-prone);
57
90
  * - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
58
91
  * columns then take values from the extremal row, so that is actually correct;
59
- * - only flags identifiers that are real base columns.
92
+ * - reads the OUTERMOST select list (a scalar subquery's FROM ends nothing) and removes
93
+ * aggregate calls with balanced parens, so a column nested inside an aggregate is never "bare";
94
+ * - only flags references that resolve to real base columns.
60
95
  */
61
- export declare function detectBareAggregate(sql: string, isBaseColumn: (col: string) => boolean): SqlSafetyWarning[];
96
+ export declare function detectBareAggregate(sql: string, isBaseColumn: (ref: ColumnRef) => boolean): SqlSafetyWarning[];
62
97
  /**
63
98
  * Detect silent-wrong-answer footguns in a SELECT. Type-aware: a division term is
64
99
  * flagged only when EVERY resolvable operand column is integer-typed (a single
@@ -66,3 +101,10 @@ export declare function detectBareAggregate(sql: string, isBaseColumn: (col: str
66
101
  * are treated conservatively as non-integer (no flag) to avoid crying wolf.
67
102
  */
68
103
  export declare function detectSqlFootguns(sql: string, columnType: ColumnTypeResolver): Promise<SqlSafetyWarning[]>;
104
+ /**
105
+ * Ask the database: for each output column whose top-level expression divides, is the
106
+ * computed value integer-typed? `resultType(column)` reports the type of that output column
107
+ * over the executed query. Catches truncation in any expression shape (CASE sums, scalar
108
+ * subqueries, parenthesised arithmetic) because it reads the result, not the syntax.
109
+ */
110
+ export declare function detectIntegerDivisionResult(sql: string, outputColumns: string[], resultType: (column: string) => Promise<string | undefined>): Promise<SqlSafetyWarning[]>;