@outsidedata/dolex 8.1.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +30 -7
  2. package/dist/src/analysis/planner.d.ts +2 -1
  3. package/dist/src/analysis/planner.js +2 -2
  4. package/dist/src/analysis/quality.js +96 -5
  5. package/dist/src/analysis/rules.d.ts +22 -2
  6. package/dist/src/analysis/rules.js +64 -23
  7. package/dist/src/cleaning/index.d.ts +2 -6
  8. package/dist/src/cleaning/index.js +8 -3
  9. package/dist/src/cleaning/replay.d.ts +34 -0
  10. package/dist/src/cleaning/replay.js +58 -0
  11. package/dist/src/cli/commands/analyze.js +13 -1
  12. package/dist/src/cli/commands/clean.js +15 -3
  13. package/dist/src/cli/commands/deps.d.ts +1 -0
  14. package/dist/src/cli/commands/deps.js +41 -0
  15. package/dist/src/cli/commands/help.js +2 -1
  16. package/dist/src/cli/commands/sources.d.ts +2 -2
  17. package/dist/src/cli/commands/sources.js +139 -12
  18. package/dist/src/cli/commands/transform.js +19 -4
  19. package/dist/src/cli/data-source.d.ts +0 -2
  20. package/dist/src/cli/data-source.js +0 -1
  21. package/dist/src/cli/index.js +3 -0
  22. package/dist/src/connectors/csv.js +29 -0
  23. package/dist/src/connectors/index.d.ts +2 -0
  24. package/dist/src/connectors/index.js +2 -0
  25. package/dist/src/connectors/manager.d.ts +39 -1
  26. package/dist/src/connectors/manager.js +191 -45
  27. package/dist/src/connectors/mongo/index.d.ts +21 -0
  28. package/dist/src/connectors/mongo/index.js +359 -0
  29. package/dist/src/connectors/pg/index.d.ts +2 -0
  30. package/dist/src/connectors/pg/index.js +316 -0
  31. package/dist/src/connectors/source-factory.d.ts +38 -0
  32. package/dist/src/connectors/source-factory.js +80 -0
  33. package/dist/src/connectors/sql-safety.d.ts +59 -17
  34. package/dist/src/connectors/sql-safety.js +275 -54
  35. package/dist/src/connectors/types.d.ts +59 -0
  36. package/dist/src/connectors/types.js +33 -1
  37. package/dist/src/mcp/index.d.ts +1 -1
  38. package/dist/src/mcp/index.js +43 -13
  39. package/dist/src/mcp/tools/analyze.js +12 -2
  40. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  41. package/dist/src/mcp/tools/capabilities.js +14 -0
  42. package/dist/src/mcp/tools/clean-column.js +2 -0
  43. package/dist/src/mcp/tools/clean-schemas.js +1 -1
  44. package/dist/src/mcp/tools/drop-columns.js +2 -0
  45. package/dist/src/mcp/tools/list-transforms.js +22 -0
  46. package/dist/src/mcp/tools/promote-columns.js +2 -0
  47. package/dist/src/mcp/tools/query-source.js +2 -2
  48. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  49. package/dist/src/mcp/tools/refine.d.ts +4 -4
  50. package/dist/src/mcp/tools/shared.d.ts +5 -0
  51. package/dist/src/mcp/tools/shared.js +11 -4
  52. package/dist/src/mcp/tools/sources.d.ts +47 -4
  53. package/dist/src/mcp/tools/sources.js +51 -9
  54. package/dist/src/mcp/tools/transform-data.js +22 -0
  55. package/dist/src/mcp/tools/transform-schemas.js +4 -4
  56. package/dist/src/mcp/tools/visualize-cli.js +1 -1
  57. package/dist/src/mcp/tools/visualize.js +2 -2
  58. package/dist/src/patterns/index.d.ts +1 -1
  59. package/dist/src/patterns/index.js +1 -1
  60. package/dist/src/patterns/registry.d.ts +1 -12
  61. package/dist/src/patterns/registry.js +0 -13
  62. package/dist/src/patterns/utils.d.ts +0 -24
  63. package/dist/src/patterns/utils.js +0 -71
  64. package/dist/src/renderers/d3/shared.d.ts +0 -18
  65. package/dist/src/renderers/d3/shared.js +0 -62
  66. package/dist/src/types.d.ts +30 -3
  67. package/dist/src/utils/capabilities.d.ts +28 -0
  68. package/dist/src/utils/capabilities.js +58 -0
  69. package/dist/src/utils/optional-deps.d.ts +8 -0
  70. package/dist/src/utils/optional-deps.js +8 -0
  71. package/package.json +5 -2
  72. package/dist/src/analysis/clean-exec.d.ts +0 -23
  73. package/dist/src/analysis/clean-exec.js +0 -87
  74. package/dist/src/cleaning/author.d.ts +0 -30
  75. package/dist/src/cleaning/author.js +0 -7
  76. package/dist/src/cleaning/handlers.d.ts +0 -16
  77. package/dist/src/cleaning/handlers.js +0 -82
  78. package/dist/src/cleaning/manifest.d.ts +0 -35
  79. package/dist/src/cleaning/manifest.js +0 -95
@@ -0,0 +1,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
+ }
@@ -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[]>;
@@ -12,19 +12,35 @@
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
- // 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, '""')
25
+ // String literals (with '' escapes) are blanked before anything else, so a `/` or a quote
26
+ // inside quoted content is never read as SQL. Quoted identifiers are UNQUOTED rather than
27
+ // blanked — blanking them made every `"col"` invisible to the detectors (issue #35).
28
+ export function stripSql(sql) {
29
+ const ids = new Map();
30
+ let n = 0;
31
+ const text = sql
32
+ .replace(/'(?:[^']|'')*'/g, "''")
33
+ .replace(/"((?:[^"]|"")+)"|`([^`]+)`/g, (_m, dq, bq) => {
34
+ const name = (dq ?? bq ?? '').replace(/""/g, '"');
35
+ if (/^[A-Za-z_]\w*$/.test(name))
36
+ return name;
37
+ const token = `__qid${n++}__`;
38
+ ids.set(token, name);
39
+ return token;
40
+ })
26
41
  .replace(/--.*$/gm, '')
27
42
  .replace(/\/\*[\s\S]*?\*\//g, '');
43
+ return { text, ids };
28
44
  }
29
45
  // A maximal multiplicative term: operand ([*/] operand)+. operand = number |
30
46
  // func(one paren level) | identifier. One level covers SUM(wins), AVG(x)/COUNT(*).
@@ -32,42 +48,195 @@ const OPERAND = String.raw `(?:\w+\s*\([^()]*\)|\w+(?:\.\w+)?|\d+(?:\.\d+)?)`;
32
48
  const TERM = new RegExp(`${OPERAND}(?:\\s*[*/]\\s*${OPERAND})+`, 'g');
33
49
  const FLOAT_LIT = /\d+\.\d+/;
34
50
  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']);
51
+ const KEYWORDS = new Set([
52
+ 'sum', 'avg', 'count', 'min', 'max', 'cast', 'as', 'real', 'float', 'double', 'total', 'abs', 'round', 'distinct', 'all',
53
+ 'case', 'when', 'then', 'else', 'end', 'and', 'or', 'not', 'null', 'is', 'in', 'like', 'between',
54
+ 'integer', 'int', 'numeric', 'text', 'select', 'from', 'where',
55
+ ]);
56
+ /** Column references in an expression: skips function names (an identifier followed by `(`),
57
+ * SQL keywords and numbers; keeps an `alias.` qualifier; maps placeholder tokens back. */
58
+ export function columnRefs(expr, ids) {
59
+ const out = [];
60
+ for (const m of expr.matchAll(/([A-Za-z_]\w*)(?:\.([A-Za-z_]\w*))?(\s*\()?/g)) {
61
+ if (m[3])
62
+ continue;
63
+ const qualifier = m[2] ? m[1] : undefined;
64
+ const column = m[2] ?? m[1];
65
+ if (!qualifier && KEYWORDS.has(column.toLowerCase()))
66
+ continue;
67
+ out.push({ qualifier, column: ids.get(column) ?? column });
68
+ }
69
+ return out;
70
+ }
36
71
  /** 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. */
72
+ * literal, no CAST-to-real), with the column references they read. Pure syntax —
73
+ * cheap enough to use as a pre-filter before any type probing. */
39
74
  export function riskyDivisionTerms(sql) {
40
- const s = strip(sql);
75
+ const { text, ids } = stripSql(sql);
41
76
  const out = [];
42
- for (const m of s.matchAll(TERM)) {
77
+ for (const m of text.matchAll(TERM)) {
43
78
  const term = m[0];
44
79
  if (!term.includes('/'))
45
80
  continue; // pure multiplication can't truncate
46
81
  if (FLOAT_LIT.test(term) || CAST_REAL.test(term))
47
82
  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 });
83
+ out.push({ term, refs: columnRefs(term, ids) });
50
84
  }
51
85
  return out;
52
86
  }
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. */
87
+ /** Division denominators (the operand right of each `/`) with the column references they
88
+ * read. A `NULLIF(...)`-wrapped denominator is already guarded and skipped. Applies to ALL
89
+ * division (float `x/0` also yields NULL in SQLite), so it is independent of the
90
+ * integer-truncation check above. */
57
91
  export function divisionDenominators(sql) {
58
- const s = strip(sql);
92
+ const { text, ids } = stripSql(sql);
59
93
  const re = new RegExp(`/\\s*(${OPERAND})`, 'g');
60
94
  const out = [];
61
- for (const m of s.matchAll(re)) {
95
+ for (const m of text.matchAll(re)) {
62
96
  const denom = m[1].trim();
63
97
  if (/^NULLIF\s*\(/i.test(denom))
64
98
  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 });
99
+ const refs = columnRefs(denom, ids);
100
+ if (refs.length)
101
+ out.push({ denom, refs });
68
102
  }
69
103
  return out;
70
104
  }
105
+ /** Words that end a table reference — never an alias (`JOIN t ON …` has no alias). */
106
+ const CLAUSE_WORDS = new Set(['on', 'using', 'where', 'group', 'order', 'having', 'limit', 'join', 'left', 'right', 'inner', 'outer', 'cross', 'full', 'natural', 'union', 'except', 'intersect', 'window']);
107
+ /** Every table the query reads, keyed by each name it can be referenced by: its alias
108
+ * (lowercased) and its own name (lowercased). Covers `FROM a, b x`, `JOIN t AS y`, quoted
109
+ * and schema-qualified names. A derived-table subquery `FROM (SELECT …) s` names no table. */
110
+ export function tableAliases(sql) {
111
+ const { text, ids } = stripSql(sql);
112
+ const map = new Map();
113
+ const add = (ref) => {
114
+ const parts = ref.trim().split(/\s+/).filter((p) => p && !/^as$/i.test(p));
115
+ if (!parts[0] || parts[0].startsWith('('))
116
+ return; // a derived-table subquery names no table
117
+ const raw = ids.get(parts[0]) ?? parts[0];
118
+ const table = raw.includes('.') && !ids.has(parts[0]) ? raw.split('.').pop() : raw;
119
+ map.set(table.toLowerCase(), table);
120
+ const alias = parts[1];
121
+ if (alias && /^[A-Za-z_]\w*$/.test(alias) && !KEYWORDS.has(alias.toLowerCase()) && !CLAUSE_WORDS.has(alias.toLowerCase())) {
122
+ map.set(alias.toLowerCase(), table);
123
+ }
124
+ };
125
+ const lower = text.toLowerCase();
126
+ const isWord = (i) => /\w/.test(lower[i] ?? ' ');
127
+ const wordAt = (i, w) => lower.startsWith(w, i) && !isWord(i - 1) && !isWord(i + w.length);
128
+ // Each FROM clause runs to the next clause keyword at its own paren depth (or the `)` that
129
+ // closes its scope). Inside it, table references are separated by top-level commas and by
130
+ // JOIN keywords; an ON/USING condition belongs to the reference before it and is dropped.
131
+ const END = ['where', 'group', 'order', 'having', 'limit', 'union', 'except', 'intersect', 'window'];
132
+ const JOIN_WORDS = ['join', 'left', 'right', 'inner', 'outer', 'cross', 'full', 'natural'];
133
+ for (let f = 0; f < text.length; f++) {
134
+ if (!wordAt(f, 'from'))
135
+ continue;
136
+ let depth = 0;
137
+ let piece = '';
138
+ let inCondition = false;
139
+ const flush = () => { if (!inCondition)
140
+ add(piece); piece = ''; inCondition = false; };
141
+ for (let i = f + 4; i < text.length; i++) {
142
+ const ch = text[i];
143
+ if (ch === '(')
144
+ depth++;
145
+ if (ch === ')') {
146
+ if (depth === 0)
147
+ break;
148
+ depth--;
149
+ }
150
+ if (depth === 0) {
151
+ if (ch === ';' || END.some((w) => wordAt(i, w)))
152
+ break;
153
+ if (ch === ',') {
154
+ flush();
155
+ continue;
156
+ }
157
+ const jw = JOIN_WORDS.find((w) => wordAt(i, w));
158
+ if (jw) {
159
+ if (piece.trim())
160
+ flush();
161
+ inCondition = false;
162
+ i += jw.length - 1;
163
+ continue;
164
+ }
165
+ if (wordAt(i, 'on') || wordAt(i, 'using')) {
166
+ add(piece);
167
+ piece = '';
168
+ inCondition = true;
169
+ continue;
170
+ }
171
+ }
172
+ if (!inCondition)
173
+ piece += ch;
174
+ }
175
+ flush();
176
+ }
177
+ return map;
178
+ }
179
+ /** The OUTERMOST select's top-level items (split on commas at paren depth 0), skipping any
180
+ * leading WITH clause. null when there is no top-level SELECT. */
181
+ export function selectItems(text) {
182
+ const lower = text.toLowerCase();
183
+ const isWord = (i) => /\w/.test(lower[i] ?? ' ');
184
+ let depth = 0;
185
+ let start = -1;
186
+ for (let i = 0; i < text.length; i++) {
187
+ const ch = text[i];
188
+ if (ch === '(')
189
+ depth++;
190
+ else if (ch === ')')
191
+ depth--;
192
+ else if (depth === 0 && lower.startsWith('select', i) && !isWord(i - 1) && !isWord(i + 6)) {
193
+ start = i + 6;
194
+ break;
195
+ }
196
+ }
197
+ if (start < 0)
198
+ return null;
199
+ const items = [];
200
+ let cur = '';
201
+ depth = 0;
202
+ for (let i = start; i < text.length; i++) {
203
+ const ch = text[i];
204
+ if (ch === '(')
205
+ depth++;
206
+ else if (ch === ')')
207
+ depth--;
208
+ if (depth === 0 && lower.startsWith('from', i) && !isWord(i - 1) && !isWord(i + 4))
209
+ break;
210
+ if (depth === 0 && ch === ',') {
211
+ items.push(cur.trim());
212
+ cur = '';
213
+ continue;
214
+ }
215
+ cur += ch;
216
+ }
217
+ if (cur.trim())
218
+ items.push(cur.trim());
219
+ return items;
220
+ }
221
+ /** Positions (0-based, in output-column order) of the top-level select items whose
222
+ * expression divides outside a float context. null when the positions can't be trusted
223
+ * to line up with the output columns (a `*` item expands to an unknown number). */
224
+ export function dividingOutputPositions(sql) {
225
+ const items = selectItems(stripSql(sql).text);
226
+ if (!items)
227
+ return null;
228
+ if (items.some((it) => /(^|\.)\*$/.test(it.trim())))
229
+ return null;
230
+ const out = [];
231
+ items.forEach((it, k) => {
232
+ if (!it.includes('/'))
233
+ return;
234
+ if (FLOAT_LIT.test(it) || CAST_REAL.test(it))
235
+ return;
236
+ out.push(k);
237
+ });
238
+ return out;
239
+ }
71
240
  /**
72
241
  * Detect division whose denominator column actually CONTAINS a zero — `x / 0`
73
242
  * silently yields NULL in SQLite (no error), which then vanishes from downstream
@@ -76,10 +245,10 @@ export function divisionDenominators(sql) {
76
245
  */
77
246
  export async function detectDivByZero(sql, columnHasZero) {
78
247
  const warnings = [];
79
- for (const { denom, columns } of divisionDenominators(sql)) {
248
+ for (const { denom, refs } of divisionDenominators(sql)) {
80
249
  let zero = false;
81
- for (const col of columns) {
82
- if (await columnHasZero(col)) {
250
+ for (const ref of refs) {
251
+ if (await columnHasZero(ref)) {
83
252
  zero = true;
84
253
  break;
85
254
  }
@@ -94,11 +263,40 @@ export async function detectDivByZero(sql, columnHasZero) {
94
263
  }
95
264
  return warnings;
96
265
  }
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;
266
+ const AGG_NAMES = 'SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV';
267
+ /** Cut every aggregate call and every parenthesised scalar subquery out of a select list, with
268
+ * balanced parens, returning what's left and the aggregates found at this level. A one-level
269
+ * regex left `AVG((grid - (SELECT AVG(grid) …)))`'s inner columns behind as "bare" (exp. 065). */
270
+ function removeAggregates(list) {
271
+ const aggs = [];
272
+ const call = new RegExp(`^(${AGG_NAMES})\\s*\\(`, 'i');
273
+ let out = '';
274
+ for (let i = 0; i < list.length;) {
275
+ const m = /\w/.test(list[i - 1] ?? ' ') ? null : call.exec(list.slice(i));
276
+ const sub = /^\(\s*select\b/i.exec(list.slice(i));
277
+ if (m || sub) {
278
+ if (m)
279
+ aggs.push(m[1].toUpperCase());
280
+ let depth = 0;
281
+ let j = m ? i + m[0].length - 1 : i;
282
+ for (; j < list.length; j++) {
283
+ if (list[j] === '(')
284
+ depth++;
285
+ else if (list[j] === ')') {
286
+ depth--;
287
+ if (depth === 0) {
288
+ j++;
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ out += ' ';
294
+ i = j;
295
+ continue;
296
+ }
297
+ out += list[i++];
298
+ }
299
+ return { rest: out, aggs };
102
300
  }
103
301
  /**
104
302
  * Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
@@ -111,22 +309,24 @@ function selectList(stripped) {
111
309
  * too false-positive-prone);
112
310
  * - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
113
311
  * columns then take values from the extremal row, so that is actually correct;
114
- * - only flags identifiers that are real base columns.
312
+ * - reads the OUTERMOST select list (a scalar subquery's FROM ends nothing) and removes
313
+ * aggregate calls with balanced parens, so a column nested inside an aggregate is never "bare";
314
+ * - only flags references that resolve to real base columns.
115
315
  */
116
316
  export function detectBareAggregate(sql, isBaseColumn) {
117
- const s = strip(sql);
118
- if (/\bGROUP\s+BY\b/i.test(s))
317
+ const { text, ids } = stripSql(sql);
318
+ if (/\bGROUP\s+BY\b/i.test(text))
119
319
  return []; // grouped → out of scope (conservative)
120
- const list = selectList(s);
121
- if (!list || !AGG.test(list))
320
+ const items = selectItems(text);
321
+ if (!items)
322
+ return [];
323
+ const { rest, aggs } = removeAggregates(items.join(', '));
324
+ if (!aggs.length)
122
325
  return [];
123
326
  // 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
327
  if (aggs.length === 1 && (aggs[0] === 'MIN' || aggs[0] === 'MAX'))
126
328
  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));
329
+ const cols = columnRefs(rest, ids).filter(isBaseColumn).map((r) => r.column);
130
330
  if (cols.length === 0)
131
331
  return [];
132
332
  const uniq = [...new Set(cols)];
@@ -145,23 +345,44 @@ export function detectBareAggregate(sql, isBaseColumn) {
145
345
  */
146
346
  export async function detectSqlFootguns(sql, columnType) {
147
347
  const warnings = [];
148
- for (const { term, columns } of riskyDivisionTerms(sql)) {
149
- if (columns.length === 0)
348
+ for (const { term, refs } of riskyDivisionTerms(sql)) {
349
+ if (refs.length === 0)
150
350
  continue;
151
351
  let allInteger = true;
152
- for (const col of columns) {
153
- if ((await columnType(col)) !== 'integer') {
352
+ for (const ref of refs) {
353
+ if ((await columnType(ref)) !== 'integer') {
154
354
  allInteger = false;
155
355
  break;
156
356
  }
157
357
  }
158
- if (allInteger) {
159
- warnings.push({
160
- code: 'integer-division',
161
- message: `Integer division in "${term.trim()}" will truncate toward zero (SQLite floors int/int — e.g. 16/32 → 0, not 0.5). ` +
162
- `Wrap the numerator: CAST(<numerator> AS REAL) / <denominator>.`,
163
- });
164
- }
358
+ if (allInteger)
359
+ warnings.push(integerDivisionWarning(`"${term.trim()}"`));
360
+ }
361
+ return warnings;
362
+ }
363
+ const integerDivisionWarning = (what) => ({
364
+ code: 'integer-division',
365
+ message: `Integer division in ${what} truncates toward zero (int/int floors — e.g. 16/32 → 0, not 0.5). ` +
366
+ `Cast a numeric operand first: CAST(<numerator> AS REAL) / <denominator>.`,
367
+ });
368
+ /**
369
+ * Ask the database: for each output column whose top-level expression divides, is the
370
+ * computed value integer-typed? `resultType(column)` reports the type of that output column
371
+ * over the executed query. Catches truncation in any expression shape (CASE sums, scalar
372
+ * subqueries, parenthesised arithmetic) because it reads the result, not the syntax.
373
+ */
374
+ export async function detectIntegerDivisionResult(sql, outputColumns, resultType) {
375
+ const positions = dividingOutputPositions(sql);
376
+ if (!positions || !positions.length)
377
+ return [];
378
+ const items = selectItems(stripSql(sql).text) ?? [];
379
+ if (items.length !== outputColumns.length)
380
+ return []; // can't line items up with columns
381
+ const warnings = [];
382
+ for (const k of positions) {
383
+ const col = outputColumns[k];
384
+ if ((await resultType(col)) === 'integer')
385
+ warnings.push(integerDivisionWarning(`output column "${col}"`));
165
386
  }
166
387
  return warnings;
167
388
  }